text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
'electron' is not recognized as an internal or external command when using nodemon
I have the following scripts in my electron js app's package.json
"start": "electron .", "dev": "nodemon --exec electron ."
butI get the following error when I run the app as
npm run dev
'electron' is not recognized as an internal or external command, operable program or batch file
and the app crashes. However, when I run it as
npm start it runs fine with no issues.
What maybe the issue with nodemon?
See also questions close to this topic
- Electron preload script seems not being executed
I have a little
electron/
reactapplication.
I'm trying to setup the ipcRenderer to communicate between react an electron.
My
electron main.js
const {app, BrowserWindow} = require("electron"); const path = require("path"); let mainWindow app.whenReady().then(() => { createMainWindow() }); const createMainWindow = () => { console.log("createMainWindow") mainWindow = new BrowserWindow({ height: 400, width: 800, preload: path.resolve(__dirname, 'preload.js') }) mainWindow.webContents.openDevTools() mainWindow.loadURL("") }
The
preload.js
const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld( 'electron', { doThing: () => ipcRenderer.send('do-a-thing') } ) console.log("running preload")
I think the preload script is not executed.
When running
npm run electron .I can see in the console
> react-electron-app@0.1.0 electron > electron . createMainWindow
and nothing more. There is no
running preload
But the electron windows is there with the react app inside.
Now in my react
App.tsxI'm trying to use
window.electron.doThing()
import React from 'react'; import logo from './logo.svg'; import './App.css'; const ipcClick = () => { console.log("ipc click") window.electron.doThing() }> <br/> <button onClick={ipcClick}>IPC</button> </header> </div> ); } export default App;
When starting the electron app I now have
Failed to compile.
C:/dev/react/react-electron-app/src/App.tsx TypeScript error in C:/dev/react/react-electron-app/src/App.tsx(7,10): Property 'electron' does not exist on type 'Window & typeof globalThis'. Did you mean 'Electron'? TS2551 5 | const ipcClick = () => { 6 | console.log("ipc click") > 7 | window.electron.doThing() | ^ 8 | } 9 | 10 | function App() {
What's wrong with that ? I think it is coming from the preload script not executed. But why ?
- How to use other platform native module (other than node addons) in the electron with webpack?
I'm trying to use the other platform native module (i.e. from go lang) in the electron with webpack as the bundler. I have the *.dylib file that is built from the go lang, I'm using
ffi-napi,
ref-napinodejs library to integrate native module in electron and I've 3 separate webpack files for the main or preload, renderer processes and one as webpack base file that covers common settings for both which output in the dist folder and the electron runs my app from that dist folder. It works well without adding native module in the application. But when I try to include the dylib file into the app then it throws:
Error: No native build was found for platform=darwin arch=x64 runtime=electron abi=87 uv=1 libc=glibc node=14.16.0 electron=12.0.6 webpack=true
However, I can see the issue is to do with the webpack settings. I've set the
node__dirname & __filename to
falseto stop mocking node environment for my preload.js file in the electron. If I set
__dirnameto
truethen the app runs ok but I would get an issue with not loading my preload.js file in the app. And turn
__dirnameto
falsejust throws the error again. I came to know that
ffi-napi,
ref-napiuses relative path to function internally so they expects the node's __dirname or __filename set to be
true. So maybe my current issue can be resolved if I can configure the path for ffi library correctly without turning node in the webpack in the application. I tried with several approaches that I could find in the internet but most of them are centric to the node addons (native modules) approaches. Even tried to follow from here - couldn't work. Node ffi library also allows other platform's native built libraries to work with the nodejs. So I'm looking to the solution if someone can help me to resolve my current issue
Below are my setups that I've done in the app:
webpack.config.base.js
export default { mode: isProd ? 'production' : 'development', watch: isProd ? false : true, node: { __dirname: false, __filename: false }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: [ 'babel-loader' ], }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader' ] }, ] }, resolve: { extensions: [ '.js', '.jsx', '.dylib', '.dll' ] } }
webpack.config.main.js
export default () => merge(baseConfig, { target: main ? 'electron-main' : 'electron-preload', entry: main ? { index: path.resolve(__dirname, '../src/index.js') } : { preload: path.resolve(__dirname, '../src/preload.js) }, output: { path: path.resolve(__dirname, '../dist'), filename: '[name].js' } })
webpack.config.renderer.js
export default () => merge(baseConfig, { target: 'electron-renderer', entry: { renderer: path.resolve(__dirname, '../src/renderer.js') }, output: { path: path.resolve(__dirname', '../dist'), filename: '[name].js' } })
- Is there a CSS selector for the actual text inside an input? (for a "text-indent" alternative)
I have this need to perform animations using
transformthat will mimic the functionality of
text-indentin a text input because animating
text-indentends up jittery/laggy. Doing this on Electron so anything that'll work in Chrome is good to go.
I've found out about the
::-ms-valueselector but that doesn't seem to do anything on Chrome. Using a wrapper div and moving the whole input is also not an option for me since It's a massive Vue component that's already written and very complicated. Using the wrapper approach would require a painful days-long complete rewrite of the component.
If there's no selector, any alternative to solve my issue would be appreciated. I wouldn't mind doing it via JS too. Animation needs to happen on
focusand
blurevents of the input.
It's the last step of fixing this laggy horror. | https://quabr.com/67373605/electron-is-not-recognized-as-an-internal-or-external-command-when-using-nodem | CC-MAIN-2021-21 | refinedweb | 991 | 51.85 |
Internet Engineering Task Force (IETF) R. Atarius
Request for Comments: 8464 September 2018
Category: Informational
ISSN: 2070-1721
A URN Namespace for Device Identity and Mobile Equipment Identity (MEID)
Abstract
This document defines a Uniform Resource Name (URN) namespace for the
Third Generation Partnership Project 2 (3GPP2) and a Namespace
Specific String (NSS) for the Mobile Equipment Identity (MEID). The
structure of an MEID is 15 hexadecimal digits long and is defined in
the 3GPP2 to uniquely identify each individual mobile equipment
(e.g., a handset or mobile phone). The 3GPP2 has a requirement to be
able to use an MEID as a URN. This document fulfills that . . . . . . . . . . . . . . . digits long and is defined by
3GPP2 (see [S.R0048-A]) to uniquely identify each individual piece of.: *[ ":" 1*( pchar / "/" )]
future-specifier = 1*pp2-char
pp2-char = ALPHA / DIGIT / "-" / "." / "_" /
pct-encoded
where 'pchar' and 'pct-encoded' are defined in [RFC3986]. An NSS
for the MEID is defined under the '3gpp2' NID."
Assignment: reassigned to other pieces of
mobile equipment.
Identifiers in the '3gpp2' namespace.'
namespace URNs, so as to aid in interoperability.
Resolution: No resolution is envisioned.
Documentation: Documentation can be found in the following
specifications:
* "A URN Namespace for Device Identity and Mobile Equipment
Identity (MEID)" [RFC8464].
* bits 1-4 of octet 1. Bits 5-8 of octet 8 are zero-padded,
since8126] in order to ensure that the privacy concerns are
appropriately addressed. Protocols carrying the MEID URN SHOULD, at
a minimum, use strongly hop-by-hop encrypted channels, and it is
RECOMMENDED that end-to-end encryption be used.126] Cotton, M., Leiba, B., and T. Narten, "Guidelines for
Writing an IANA Considerations Section in RFCs", BCP 26,
RFC 8126, DOI 10.17487/RFC8126, June 2017,
<>.
, <>.
Previous: RFC 8463 - A New Cryptographic Signature Method for DomainKeys Identified Mail (DKIM)
Next: RFC 8465 - Using the Mobile Equipment Identity (MEID) URN as an Instance ID | http://www.faqs.org/rfcs/rfc8464.html | CC-MAIN-2020-34 | refinedweb | 315 | 50.02 |
import "gonum.org/v1/plot"
Package plot provides an API for setting up plots, and primitives for drawing on plots.
Plot is the basic type for creating a plot, setting the title, axis labels, legend, tick marks, etc. Types implementing the Plotter interface can draw to the data area of a plot using the primitives made available by this package. Some standard implementations of the Plotter interface can be found in the gonum.org/v1/plot/plotter package which is documented here:
align.go axis.go doc.go labelling.go legend.go plot.go
var UTCUnixTime = UnixTimeIn(time.UTC)
UTCUnixTime is the default time conversion for TimeTicks.
Align returns a two-dimensional row-major array of Canvases which will produce tiled plots with DataCanvases that are evenly sized and spaced. The arguments to the function are a two-dimensional row-major array of plots, a tile configuration, and the canvas to which the tiled plots are to be drawn.
Code:
const rows, cols = 4, 3 plots := make([][]*plot.Plot, rows) for j := 0; j < rows; j++ { plots[j] = make([]*plot.Plot, cols) for i := 0; i < cols; i++ { if i == 0 && j == 2 { // This shows what happens when there are nil plots. continue } p, err := plot.New() if err != nil { panic(err) } if j == 0 && i == 2 { // This shows what happens when the axis padding // is different among plots. p.X.Padding, p.Y.Padding = 0, 0 } if j == 1 && i == 1 { // To test the Align function, we make the axis labels // on one of the plots stick out. p.Y.Max = 1e9 p.X.Max = 1e9 p.X.Tick.Label.Rotation = math.Pi / 2 p.X.Tick.Label.XAlign = draw.XRight p.X.Tick.Label.YAlign = draw.YCenter p.X.Tick.Label.Font.Size = 8 p.Y.Tick.Label.Font.Size = 8 } else { p.Y.Max = 1e9 p.X.Max = 1e9 p.X.Tick.Label.Font.Size = 1 p.Y.Tick.Label.Font.Size = 1 } plots[j][i] = p } } img := vgimg.New(vg.Points(150), vg.Points(175)) dc := draw.New(img) t := draw.Tiles{ Rows: rows, Cols: cols, PadX: vg.Millimeter, PadY: vg.Millimeter, PadTop: vg.Points(2), PadBottom: vg.Points(2), PadLeft: vg.Points(2), PadRight: vg.Points(2), } canvases := plot.Align(plots, t, dc) for j := 0; j < rows; j++ { for i := 0; i < cols; i++ { if plots[j][i] != nil { plots[j][i].Draw(canvases[j][i]) } } } w, err := os.Create("testdata/align.png") if err != nil { panic(err) } png := vgimg.PngCanvas{Canvas: img} if _, err := png.WriteTo(w); err != nil { panic(err) }
UnixTimeIn returns a time conversion function for the given location.
type Axis struct { // Min and Max are the minimum and maximum data // values represented by the axis. Min, Max float64 Label struct { // Text is the axis label string. Text string // TextStyle is the style of the axis label text. // For the vertical axis, one quarter turn // counterclockwise will be added to the label // text before drawing. draw.TextStyle } // LineStyle is the style of the axis line. draw.LineStyle // Padding between the axis line and the data. Having // non-zero padding ensures that the data is never drawn // on the axis, thus making it easier to see. Padding vg.Length Tick struct { // Label is the TextStyle on the tick labels. Label draw.TextStyle // LineStyle is the LineStyle of the tick lines. draw.LineStyle // Length is the length of a major tick mark. // Minor tick marks are half of the length of major // tick marks. Length vg.Length // Marker returns the tick marks. Any tick marks // returned by the Marker function that are not in // range of the axis are not drawn. Marker Ticker } // Scale transforms a value given in the data coordinate system // to the normalized coordinate system of the axis—its distance // along the axis as a fraction of the axis range. Scale Normalizer }
An Axis represents either a horizontal or vertical axis of a plot.
Norm returns the value of x, given in the data coordinate system, normalized to its distance as a fraction of the range of this axis. For example, if x is a.Min then the return value is 0, and if x is a.Max then the return value is 1.
ConstantTicks is suitable for the Tick.Marker field of an Axis. This function returns the given set of ticks.
func (ts ConstantTicks) Ticks(float64, float64) []Tick
Ticks returns Ticks in a specified range
type DataRanger interface { // DataRange returns the range of X and Y values. DataRange() (xmin, xmax, ymin, ymax float64) }
DataRanger wraps the DataRange method.
DefaultTicks is suitable for the Tick.Marker field of an Axis, it returns a reasonable default set of tick marks.
func (DefaultTicks) Ticks(min, max float64) []Tick
Ticks returns Ticks in the specified range.
type GlyphBox struct { // The glyph location in normalized coordinates. X, Y float64 // Rectangle is the offset of the glyph's minimum drawing // point relative to the glyph location and its size. vg.Rectangle }
A GlyphBox describes the location of a glyph and the offset/size of its bounding box.
If the Rectangle.Size().X is non-positive (<= 0) then the GlyphBox is ignored when computing the horizontal padding, and likewise with Rectangle.Size().Y and the vertical padding.
GlyphBoxer wraps the GlyphBoxes method. It should be implemented by things that meet the Plotter interface that draw glyphs so that their glyphs are not clipped if drawn near the edge of the draw.Canvas.
When computing padding, the plot ignores GlyphBoxes as follows: If the Size.X > 0 and the X value is not in range of the X axis then the box is ignored. If Size.Y > 0 and the Y value is not in range of the Y axis then the box is ignored.
Also, GlyphBoxes with Size.X <= 0 are ignored when computing horizontal padding and GlyphBoxes with Size.Y <= 0 are ignored when computing vertical padding. This is useful for things like box plots and bar charts where the boxes and bars are considered to be glyphs in the X direction (and thus need padding), but may be clipped in the Y direction (and do not need padding).
type InvertedScale struct{ Normalizer }
InvertedScale can be used as the value of an Axis.Scale function to invert the axis using any Normalizer.
func (is InvertedScale) Normalize(min, max, x float64) float64
Normalize returns a normalized [0, 1] value for the position of x.
type Legend struct { // TextStyle is the style given to the legend // entry texts. draw.TextStyle // Padding is the amount of padding to add // between each entry in the legend. If Padding // is zero then entries are spaced based on the // font size. Padding vg.Length // Top and Left specify the location of the legend. // If Top is true the legend is located along the top // edge of the plot, otherwise it is located along // the bottom edge. If Left is true then the legend // is located along the left edge of the plot, and the // text is positioned after the icons, otherwise it is // located along the right edge and the text is // positioned before the icons. Top, Left bool // XOffs and YOffs are added to the legend's // final position. XOffs, YOffs vg.Length // ThumbnailWidth is the width of legend thumbnails. ThumbnailWidth vg.Length // contains filtered or unexported fields }
A Legend gives a description of the meaning of different data elements of the plot. Each legend entry has a name and a thumbnail, where the thumbnail shows a small sample of the display style of the corresponding data.
This example creates a some standalone legends with borders around them.
Code:
c := vgimg.New(vg.Points(120), vg.Points(100)) dc := draw.New(c) // These example thumbnailers could be replaced with any of Plotters // in the plotter subpackage. red := exampleThumbnailer{Color: color.NRGBA{R: 255, A: 255}} green := exampleThumbnailer{Color: color.NRGBA{G: 255, A: 255}} blue := exampleThumbnailer{Color: color.NRGBA{B: 255, A: 255}} l, err := plot.NewLegend() if err != nil { panic(err) } l.Add("red", red) l.Add("green", green) l.Add("blue", blue) l.Padding = vg.Millimeter // purpleRectangle draws a purple rectangle around the given Legend. purpleRectangle := func(l plot.Legend) { r := l.Rectangle(dc) dc.StrokeLines(draw.LineStyle{ Color: color.NRGBA{R: 255, B: 255, A: 255}, Width: vg.Points(1), }, []vg.Point{ {r.Min.X, r.Min.Y}, {r.Min.X, r.Max.Y}, {r.Max.X, r.Max.Y}, {r.Max.X, r.Min.Y}, {r.Min.X, r.Min.Y}, }) } l.Draw(dc) purpleRectangle(l) l.Left = true l.Draw(dc) purpleRectangle(l) l.Top = true l.Draw(dc) purpleRectangle(l) l.Left = false l.Draw(dc) purpleRectangle(l) w, err := os.Create("testdata/legend_standalone.png") if err != nil { panic(err) } png := vgimg.PngCanvas{Canvas: c} if _, err := png.WriteTo(w); err != nil { panic(err) }
NewLegend returns a legend with the default parameter settings.
func (l *Legend) Add(name string, thumbs ...Thumbnailer)
Add adds an entry to the legend with the given name. The entry's thumbnail is drawn as the composite of all of the thumbnails.
Draw draws the legend to the given draw.Canvas.
Rectangle returns the extent of the Legend.
LinearScale an be used as the value of an Axis.Scale function to set the axis to a standard linear scale.
func (LinearScale) Normalize(min, max, x float64) float64
Normalize returns the fractional distance of x between min and max.
LogScale can be used as the value of an Axis.Scale function to set the axis to a log scale.
Normalize returns the fractional logarithmic distance of x between min and max.
LogTicks is suitable for the Tick.Marker field of an Axis, it returns tick marks suitable for a log-scale axis.
Ticks returns Ticks in a specified range
type Normalizer interface { // Normalize transforms a value x in the data coordinate system to // the normalized coordinate system. Normalize(min, max, x float64) float64 }
Normalizer rescales values from the data coordinate system to the normalized coordinate system.
type Plot struct { Title struct { // Text is the text of the plot title. If // Text is the empty string then the plot // will not have a title. Text string // Padding is the amount of padding // between the bottom of the title and // the top of the plot. Padding vg.Length draw.TextStyle } // BackgroundColor is the background color of the plot. // The default is White. BackgroundColor color.Color // X and Y are the horizontal and vertical axes // of the plot respectively. X, Y Axis // Legend is the plot's legend. Legend Legend // contains filtered or unexported fields }
Plot is the basic type representing a plot.
New returns a new plot with some reasonable default settings.
Add adds a Plotters to the plot.
If the plotters implements DataRanger then the minimum and maximum values of the X and Y axes are changed if necessary to fit the range of the data.
When drawing the plot, Plotters are drawn in the order in which they were added to the plot.
DataCanvas returns a new draw.Canvas that is the subset of the given draw area into which the plot data will be drawn.
Draw draws a plot to a draw.Canvas.
Plotters are drawn in the order in which they were added to the plot. Plotters that implement the GlyphBoxer interface will have their GlyphBoxes taken into account when padding the plot so that none of their glyphs are clipped.
DrawGlyphBoxes draws red outlines around the plot's GlyphBoxes. This is intended for debugging.
GlyphBoxes returns the GlyphBoxes for all plot data that meet the GlyphBoxer interface.
HideAxes hides the X and Y axes.
HideX configures the X axis so that it will not be drawn.
HideY configures the Y axis so that it will not be drawn.
NominalX configures the plot to have a nominal X axis—an X axis with names instead of numbers. The X location corresponding to each name are the integers, e.g., the x value 0 is centered above the first name and 1 is above the second name, etc. Labels for x values that do not end up in range of the X axis will not have tick marks.
NominalY is like NominalX, but for the Y axis.
Save saves the plot to an image file. The file format is determined by the extension.
Supported extensions are:
.eps, .jpg, .jpeg, .pdf, .png, .svg, .tif and .tiff.
Transforms returns functions to transfrom from the x and y data coordinate system to the draw coordinate system of the given draw area.
WriterTo returns an io.WriterTo that will write the plot as the specified image format.
Supported formats are:
eps, jpg|jpeg, pdf, png, svg, and tif|tiff.
Plotter is an interface that wraps the Plot method. Some standard implementations of Plotter can be found in the gonum.org/v1/plot/plotter package, documented here:
type Thumbnailer interface { // Thumbnail draws an thumbnail representing // a legend entry. The thumbnail will usually show // a smaller representation of the style used // to plot the corresponding data. Thumbnail(c *draw.Canvas) }
Thumbnailer wraps the Thumbnail method, which draws the small image in a legend representing the style of data.
type Tick struct { // Value is the data value marked by this Tick. Value float64 // Label is the text to display at the tick mark. // If Label is an empty string then this is a minor // tick mark. Label string }
A Tick is a single tick mark on an axis.
IsMinor returns true if this is a minor tick mark.
type Ticker interface { // Ticks returns Ticks in a specified range Ticks(min, max float64) []Tick }
Ticker creates Ticks in a specified range
TickerFunc is suitable for the Tick.Marker field of an Axis. It is an adapter which allows to quickly setup a Ticker using a function with an appropriate signature.
func (f TickerFunc) Ticks(min, max float64) []Tick
Ticks implements plot.Ticker.
type TimeTicks struct { // Ticker is used to generate a set of ticks. // If nil, DefaultTicks will be used. Ticker Ticker // Format is the textual representation of the time value. // If empty, time.RFC3339 will be used Format string // Time takes a float64 value and converts it into a time.Time. // If nil, UTCUnixTime is used. Time func(t float64) time.Time }
TimeTicks is suitable for axes representing time values.
Ticks implements plot.Ticker.
Package plot imports 11 packages (graph) and is imported by 68 packages. Updated 2019-03-12. Refresh now. Tools for package owners. | https://godoc.org/gonum.org/v1/plot | CC-MAIN-2019-13 | refinedweb | 2,412 | 69.07 |
SQL Server Distributed Management Objects (SQL-DMO) is a COM-based object library, exposes interfaces that access any object in SQL Server. Any programming language that supports COM objects, such as VB or C++, can use these interfaces.
The SQL-DMO object model allows access to objects in SQL Server so you can build administrative functions into your code. In this article, I'll describe how to Enumerate the Database Servers using SQL-DMO.
SQL-DMO uses the Microsoft� SQL Server ODBC driver to connect to and communicate with instances of SQL Server.
If you have installed SQL SERVER Enterprise Manager then you should have the SQL DMO installed. If you don't then the following article shows you how to install the objects.
MDAC v2.1 or higher (This can be obtained from microsoft) This contains the OLE DB drivers that are required to hook up to the database or the data source.
Use the following import statement to access SQL DMO, this should be done in your stdafx.h file.
#import "c:\mssql7\binn\resources\1033\sqldmo.rll" no_namespace
In Order to use the ADO Com Objects you will need to import the following type library, this should be done in your stdafx.h file. Note that the ADO namespace has been renamed, this needs to be done, otherwise you will find the object name clash between ADO and SQL DMO.
#import "C:\Program Files\Common Files\System\ado\msado15.dll" rename_namespace("ADONS") rename("EOF", "adoEOF")
Please note that you may need to add the full path to these dll or you can add the path through your visual C++ environment via Tools->Options->Directories->Include Files
One of the first things that you must do is to initialise the COM
OLE library in order to use the SQL DMO COM objects, usually this can be done
through
::CoInitialize(NULL) and
::CoUninitialize(). If you are using MFC then
you can simply call
AfxOleInit()
On the
::InitInstance function of your App class.
The following code shows you the SQL DMO objects that were used to
enumerate the SQL SERVER. Basically create the Application object then use the
ListAvailableSQLServers method to get a list of the SQL SERVERS.
// set up the Server Combo Box try { _SQLServerPtr spSQLServer; HRESULT hr2 = spSQLServer.CreateInstance(__uuidof(SQLServer)); if (FAILED(hr2)) _com_issue_error(hr2); if (SUCCEEDED(hr2)) { try { // Get the Application Ptr long lServerCount(0); _ApplicationPtr pApplication = spSQLServer->GetApplication(); if (pApplication) { NameListPtr pServerNameList = pApplication->ListAvailableSQLServers(); if (pServerNameList) { HRESULT hr= pServerNameList->get_Count(&lServerCount); BSTRbstrServerName; m_ctlComboBox.ResetContent(); _variant_t vIndex(long(0)); for (long i=0; i < lServerCount; i++) { vIndex.lVal = i; hr = pServerNameList->raw_Item(vIndex, &bstrServerName); _bstr_t bstrValue(bstrServerName); CString sValue((LPCSTR)bstrValue); if (!sValue.IsEmpty()) m_ctlComboBox.AddString(sValue); } // We know that the server list will not show up on Win 9x machines // therefore check manually to see if SQL Server exist if (m_ctlComboBox.GetCount() == 0) { HKEY hKey = NULL; if (RegOpenKey(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\MSSQLServer"), &hKey) == ERROR_SUCCESS) { m_ctlComboBox.AddString(_T("(local)")); RegCloseKey(hKey); } } } } pApplication = NULL; spSQLServer.Release(); } catch (_com_error e) { AfxMessageBox(ReportError(e)); spSQLServer.Release(); // Free the interface. } } else { AfxMessageBox("\nUnable to create the SQLServer object."); } } catch (_com_error e) { AfxMessageBox(ReportError(e)); }
Note - If you have installed SQL SERVER on a Win 9x machine then the SERVER name is not going to appear in the list. To get round this problem a test in the registry is done to see if SQL SERVER has been installed on the machine, If it has then the (local) server is added to the list.
I have just used a fraction of the avialable functionality that can be exposed from the SQL DMO. The Enumeration of SQL SERVERS example shows how easy it is to use SQL DMO. For more information on SQL DMO see MSDN.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/database/serverenum.aspx | crawl-002 | refinedweb | 632 | 53.61 |
(non-printable free online version)
If you like the book, please support the author and InfoQ by
purchasing the printed book: (only $19.95) Brought to you Courtesy of
This book is distributed for free on InfoQ.com, if you have received this book from any other source then please support the author and the publisher by registering on InfoQ.com.
Visit the homepage for this book at:
Getting Started with Grails
Written by: Jason Rudolph
© 2006 C4Media Inc All rights reserved. C4Media, Publisher of InfoQ.com. This book is part of the InfoQ Enterprise Software Development series of books. For information or ordering of this or other InfoQ books, please contact books@c4media.com. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recoding, scanning or otherwise except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher. Designations used by companies to distinguish their products are often claimed as trademarks. In all instances where C4Media Inc. is aware of a claim, the product names appear in initial Capital or ALL CAPITAL LETTERS. Readers, however, should contact the appropriate companies for more complete information regarding trademarks and registration. Managing Editor: Floyd Marinescu Cover art: Gene Steffanson Composition: Laura Brown Library of Congress Cataloguing-in-Publication Data: ISBN: 978-1-4303-0782-2 Printed in the United States of America
I would like to thank Graeme Rocher (Grails project lead and author of The Definitive Guide to Grails) for reviewing this book and for enlightening me to the inner workings of Grails along the way. Your detailed review provided invaluable technical insight and excellent recommendations for incorporating “Groovier” solutions into the examples.
Acknowledgements
I would also like to thank Venkat Subramaniam (co-author of Practices of an Agile Developer) for reviewing this book with a keen emphasis on the learning experience and how to best introduce Grails to the reader. In addition to that contribution, your insightful foreword welcomes developers to a framework that will surely foster agility and its many benefits. I’d like to thank Steve Rollins for diligently pouring through this book to uncover any lingering issues, even though it meant a few weeks of being a nerd outside of normal working hours. Your tireless attention to detail is clearly reflected in the final product. I would also like to thank Jared Richardson (co-author of Ship it! A Practical Guide to Successful Software Projects) not only for reviewing this book, but for motivating me to write it in the first place. Your encouragement throughout the process and your valuable perspective on the end result are greatly appreciated. I would like to thank Floyd Marinescu (co-founder of InfoQ.com and author of EJB Design Patterns) and the entire team at InfoQ for publishing this book and for your enthusiastic support throughout the effort.
iii
Most importantly, I’d like to thank my unflinchingly patient and encouraging wife Michelle for supporting me throughout this effort. It was only by your willingness to do far more than your fair share (of just about everything) that I was able to have time for this project. And as if it wasn’t enough just to provide the support to make this book possible, your creativity, sense of style, and editorial input contributed to make this book better than it would have been on its own.
iv
Contents
1. INTRODUCTION Learning by Example The RaceTrack Application 2. LACING UP Installing a JDK Installing Grails Installing a Database 3. HELLO, GRAILS! Creating Your First Grails Application What’s Inside? Establishing Your Domain Taking Control Where’s My Data? Building Better Scaffolding Understanding URLs and Controllers 4. IMPROVING THE USER EXPERIENCE Customizing Error Messages Adding Warning Messages Implementing Confirmation Messages Removing Record IDs Formatting Data 5. GET DYNAMIC Dynamic Finders Build Your Own Criteria 6. NOT JUST FOR INTRANET APPS Beyond CRUD Implementing User Authentication UI Makeover: Layouts and CSS 7. PUTTING IT TO THE TEST 1 2 3 5 5 5 5 7 7 8 9 15 19 24 32 37 38 41 43 46 47 55 55 60 69 70 78 90 95
v
Unit Testing Functional Testing 8. THE FINISH LINE Logging Deploying 9. TIPS AND TRICKS FOR MOVING FORWARD Defining Your Own Database Tables Working with a Legacy Database Schema ORM Troubleshooting Upgrading Grails SUMMARY ABOUT THE AUTHOR RESOURCES
95 99 101 101 103 107 107 109 110 111 113 115 117
vi
Those of us keen on developing software applications will find that Agile Development greatly improves our chances of success. But, what' agility? At its core, it starts with s developing a relatively small feature and quickly getting feedback from our customers. They tell us if we' on the right re track, help us develop what' relevant to them, and together we s make sure we' constructing an application that will add value re to their business. Why should we be agile? As an industry, we' spent far too long watching other development ve methodologies fail to deliver systems that truly satisfy the customer' needs. To ultimately deliver what our customers s want, we need to take smaller and quicker steps, and touch base with our customers frequently to deliver useful features that they can exercise and critique. Two key things influence our ability to be agile. First, it' the attitude of everyone involved. The attitude of each s person on a team, and the team as a whole, has a significant impact on all aspects of a project. Attitude determines how willing we are to closely cooperate with other developers and with customers, to seek their feedback, and to use that feedback to improve our work. Second, it' the languages, frameworks, and tools we use to get s our work done. Our chosen technologies must enable us to quickly create useful code and to afford quick change in response to customer feedback.
Foreword
vii
Some languages and frameworks require developers to go though a remarkable amount of effort before they can produce useful executable code. You may have to muddle though XML configuration files, implement an exhaustive set of interfaces, and perform certain operations repeatedly at different layers of your application. In this environment, it often requires an inordinate amount of effort before you can see the working results of any changes. Once you finally create working code, the mere thought of introducing change may put you off from ever even soliciting feedback. A subconscious resistance to change soon ensues, and pleasing the customer suddenly takes a back seat to avoiding change. Fortunately, we' seen some languages and frameworks emerge ve in recent years that support a more agile development approach. They allow you to create working, demonstrable code in minutes, not days or weeks, and still ensure the quality of that code. And when you get that valuable feedback from your customers, these languages and frameworks tend to facilitate change, not obstruct it. How exactly does that work? First, these frameworks follow the DRY (Don'Repeat Yourself) principle. Because each aspect of t your application exists in a single location, you don' have to t modify multiple layers of code to effect a change. Instead, you make your change in one place and, for the most part, you' re done. Second, they follow a convention-over-configuration strategy, so you don'have to spend time explaining the obvious; t instead, you get straight to writing useful, productive code. Third, they' lightweight; you can change a particular piece of re code and see the results of that change reflected immediately, without explicit recompilation or slow and burdensome redeployments. That sounds intriguing, but, you may ask, "Where does that leave all the investments we' made in other languages and ve frameworks, like Java, Hibernate, Spring, etc.?" That' where s Grails comes in. Because Grails makes use of the Groovy language (which runs on the JVM), it allows you to integrate vi. But don'take my word for it. Follow along with the examples that t Jason has created for you, code along as you read, and see for yourself how Grails contributes to your agility. Then, find a partner, pick an area of your application, and give it a try! Venkat Subramaniam November 2006
ix
Speak properly, and in as few words as you can, but always plainly; for the end of speech is not ostentation, but to be understood. - William Penn Example is not the main thing in influencing others. It is the only thing. - Albert Schweitzer
Free Online Version.
Support this work, buy the print copy:
Grails is an open-source web application framework that’s all about getting things done.
Introduction
1
A university professor once assured me – actually he tried his darndest to ingrain it in all his students – that the best software engineers are out of the office and on the golf course by 10 a.m. Why? Because they’re focused, efficient, and productive developers. Surely the proposition of calling it a day before the coffee is cold seems unlikely, but wouldn’t it be nice to have a typical day’s worth of work done before your second cup? (shhhh!) fun with a more Java-centric solution, what' not to like? Grails makes that idea a reality. s And the more conservative businesses should find additional comfort knowing that Grails applications play nicely with their existing Java code, because Grails applications are written in Groovy – a dynamically-typed scripting language that stands to soon become a Java standard.1 Grails embraces convention over configuration, a technique that facilitates both focus and productivity. Convention dictates where each component belongs in an application, how it’s named, and how it interacts with other components. In short, 1
2 | GETTING STARTED WITH GRAILS developers know exactly where to place a given component and what it should be called, and new team members will know just where to find that component, all by convention.View.
Learning by Example
This book introduces Grails by example. We’ll see how to quickly build a Grails application from scratch and how to customize it to meet various needs. We’ll explore the essence of each concept we encounter along the way, and for readers that may want to dive deeper into certain topics, we’ll include pointers (via endnotes) to supplemental information. In order to follow along, you’ll need a basic knowledge of object-oriented programming and MVC web application development, and you’ll certainly benefit from a familiarity with
INTRODUCTION | 3 Java (though you can probably get by without it). We’ll also see extensive use of Groovy throughout the examples. While this book doesn’t aim to teach Groovy, the examples are such that anyone with some programming background should be able to follow along. If at any point you want to explore a particular Groovy idiom in more detail, be sure to check the Groovy site for further information.2
The RaceTrack Application
Over the course of this book, we’ll explore the various aspects of Grails development as we build a small web application called RaceTrack. There’s a regional running club in the southeastern United States that currently uses a paper-based process for tracking the races that the club participates in and the runners that register for each race. They’re ready to make the leap into the digital era. For starters, they want an application that will allow the club’s staff members to manage the races and registrations. They assure us they don’t need anything too fancy – remember, they’re using paper now – so, they’ll be happy with an application that provides an internal administrative interface to this data. We’ll start off with an intranet app that will provide the requested functionality, but we’ve heard whispers about eventually – if all goes well – letting runners register themselves for races, thus requiring us to expose the application to external users as well. Developing the RaceTrack application will offer a broad, handson exposure to Grails. We’ll build a web user interface, manage relationships among database tables, apply validation logic, and develop custom queries. As we continue to expand the application, we’ll also explore custom tag libraries, Java integration, security, page layout, and the power of dynamic methods. Before we wrap up, we’ll be sure to look at several supporting areas as well, including unit testing, logging, and deployment. By and large, the information and code segments you need to build the application are included within the text of the book.
4 | GETTING STARTED WITH GRAILS There’s one exception we’ll see towards the end, but we’ll call that out at that time. Never fear though; all of the source code for the examples is available for you to download.3 The code bundle includes a complete snapshot of the application’s source code as it exists at the end of each chapter.
Free Online Version.
Support this work, buy the print copy:
Lacing Up
2
Installing a JDK
While Grails only requires JDK 1.4, some of the examples we’ll see over the next few chapters will take advantage of various JDK 5 features. You’ll need JDK 5 in order to work through those examples as shown. (We’ll be sure to point out those items that depend on JDK 5 along the way.) So, while we keep in mind that Grails itself plays nicely with JDK 1.4, take a moment to download and install JDK 5 () so you can follow along with these particular examples.4 Then, set your JAVA_HOME environment variable to point to your JDK 5 installation.
Installing Grails
Next, download the current stable release of Grails from (This book uses Grails 0.3.1 – the current stable release as of this writing.) Then, follow the quick setup steps () to install Grails on your system and configure the necessary environment variables.6
Installing a Database
5
6 | GETTING STARTED WITH GRAILS disk-based database (which safely preserves our data even when we occasionally restart the application). While Grails works with most databases (including Oracle, DB2, PostgreSQL, etc.), we’ll use MySQL 5.0 for this example. You can download a copy of MySQL Community Edition from, follow the installation instructions, and we’ll be ready to go.7
Free Online Version.
Support this work, buy the print copy:
Hello, Grails!
Creating Your First Grails Application
Now that we have Grails installed, let’s create a directory for our Grails applications. You can call it whatever you like, and place it wherever you prefer.
jason> mkdir grails_apps jason> cd grails_apps grails_apps>
3
Next, from within the directory we just created, let’s generate our project structure. Enter grails create-app, and when asked for an application name, enter racetrack.
grails_apps> grails create-app ... create-app: [input] Enter application name: racetrack ... BUILD SUCCESSFUL Total time: 4 seconds
Just to make sure all is well with our environment, let’s start our application. Move into the new directory created for our application, and then enter grails run-app to start the application.
grails_apps> cd racetrack racetrack> grails run-app ... run-app:watch-context:
7
8 | GETTING STARTED WITH GRAILS The application is now waiting for our requests. Open your browser to, and you should see this friendly message welcoming you to Grails.
What’s Inside?
We’re well on our way. But, before we go too far, let’s have a closer look at just what makes up our new application. Much of Grails’s ability to support rapid application development comes from its emphasis on convention over configuration (a key aspect of the “opinionated software” model popularized by Ruby on Rails). The Grails project structure (shown in Figure 3-1 below) relies heavily on convention and establishes a sensible organizational structure for an application’s various artifacts.8
HELLO, GRAILS | 9
racetrack + grails-app + conf + controllers + domain + i18n + services + taglib + views + layouts + grails-tests + hibernate + lib + spring + src + groovy + java + web-app + css + images + js + WEB-INF + index.jsp
Holds configuration settings including data sources for development, test, and production Holds (obviously enough) controllers Holds domain classes Holds internationalization resource bundles Holds service classes (i.e., the Grails equivalent of a local session bean) Holds tag libraries Holds view templates (with a subdirectory being created to hold the templates for each controller) Holds layout templates (available to all controllers) Holds unit tests Holds optional Hibernate configuration files Holds any custom libraries needed by the application Holds optional Spring configuration files Holds Groovy source files (other than controller, domain, or service classes) Holds Java source files Holds style sheets Holds image files Holds JavaScript files and thirdparty libraries (e.g., Prototype, Yahoo, etc.) Holds deployment-related configuration files The application’s index page
Figure 3-1: Application Directory Structure
Establishing Your Domain
Grails treats the domain classes as the central and most important component of the application. It’s from the domain classes that we’ll drive everything else that we do in the application. (If you’ve worked with Ruby on Rails, you’ll notice that this is a departure from the Rails approach, where Rails derives the domain model from the underlying database schema.)
10 | GETTING STARTED WITH GRAILS In order to understand the data we need to capture, we first reviewed the running club’s current process. For starters, they showed us the form they use today to track the information for a given race.
Figure 3-2: Sample Form Used in Current Paper-Based Process From this information, we can see that we’re basically working with two types of data –races and registrations – and that there’s a one-to-many relationship between those entities. That information will form the basis of our domain model, and the various data elements on the form will become the attributes of our domain classes. So, let’s create the domain classes to represent these components. Back in the command prompt, enter grails create-domain-class. When prompted for the domain class name, enter Race. (If your application is still running from earlier, enter Control-C to stop the application and get back to the command prompt.)
HELLO, GRAILS | 11
racetrack> grails create-domain-class ... create-domain-class: [input] Enter domain class name: Race ... [echo] Domain class created: grails-app/domain/Race.groovy ... [echo] Created test suite: grails-tests/RaceTests.groovy BUILD SUCCESSFUL Total time: 5 seconds
Notice that Grails did not create just the domain class for us, it also created a corresponding class to hold the unit tests for that domain class. We’ll be sure to make use of that later. Next, repeat this process to create the Registration domain class. Now, let’s take a look at the domain classes as they exist out-ofthe-box. Open racetrack/grails-app/domain/Race.groovy in your editor of choice.
class Race { }
Admittedly, we can’t exactly say that we’re impressed just yet, but bear with me for a few minutes. It gets better. From our earlier discussions with the customer and from analyzing the paper form, we know the attributes we need to capture for each race, so let’s add those properties to the domain class.
class Race { String name Date startDateTime String city String state Float distance Float cost Integer maxRunners = 100000 static hasMany = [registrations:Registration] }
12 | GETTING STARTED WITH GRAILS9,one, and many-to-many relationships as well.10
HELLO, GRAILS | 13 On to the other side of the relationship. Point your editor at racetrack/grails-app/ domain/Registration.groovy and let’s define its properties.
class Registration { Race race String name Date dateOfBirth String gender = 'F' String postalAddress String emailAddress Date createdAt = new Date() static belongsTo = Race static optionals = ["postalAddress" ] }
Once again, most of these attributes look fairly normal: name, date of birth, etc. There are just a few we need to look at more closely. Our business users have told us that all of the race attributes are mandatory, and most registration attributes are mandatory as well. However, the users seem to think that this Internet thing is going to catch on, so they’ve decided that an e-mail address is sufficient, and that the postal address should be an optional property.
14 | GETTING STARTED WITH GRAILS oneto-many relationship between races and registrations. Because we declare that a registration belongs to a race (identified by the registration’s race property), Grails will ensure that deleting a registration will not delete the corresponding race; however, deleting a race will in fact delete all associated registrations. Familiar Territory Now that we’ve seen the domain model, we can see that Grails very much embraces object-oriented programming. We’d likely model these components in a similar manner in Java or Ruby or any other object-oriented language. In fact, as we move forward, you’ll find that the OO and MVC concepts you’ve come to know and love will continue to serve you well with Grails. Where’s the Beef? Before we move on to the controllers, notice for a moment that there’s nothing in these classes that mentions any kind of Object Relational Mapping (ORM) or persistence..
HELLO, GRAILS | 15.)
Taking Control.
racetrack> grails create-controller ... create-controller: [input] Enter controller name: Race ... [echo] Created controller: grails-app/controllers/RaceController.groovy ... BUILD SUCCESSFUL Total time: 3 seconds
Now, let’s open up our new controller and see what we have to start with. Find your way to racetrack/grailsapp/controllers/RaceController.groovy, and have a look.
class RaceController { def index = { } }
Hmm. Well, our ultimate goal is to have a user interface for managing race data. So, we need to include logic in the controller to support listing, creating, updating, and deleting race
16 | GETTING STARTED WITH GRAILS.
HELLO, GRAILS | 17
18 | GETTING STARTED WITH GRAILS. • Validation – We never told Grails that a race must have a distance greater than zero, that a race name shouldn’t exceed fifty characters, or that “squirrel” is not a valid gender. So, validation is simply absent, but we can quickly add it. Field/Column Ordering – When we’re viewing race data, why is the city shown first and the state shown last with
•
HELLO, GRAILS | 19 other fields appearing in between? Well, we never told Grails otherwise. The solution to this problem is pleasantly simple, as we’ll see in a moment..
•
That’s it. If we can tackle these few items, we will have a fullyfunctioning web app to manage our race and registration data. After that, the rest is just gravy. (Though we’ll be sure to have a large helping of that tasty gravy before we’re finished.). Quick Note: If we were simply trying to avoid reentering test data, we could consider using Grails bootstrap classes to help us out here, and then we could stick with the in-memory database a while longer. Bootstrap classes provide a handy mechanism for performing various initialization tasks, including populating database tables. However, bootstrap classes will always reinitialize the application with the same data, and we’ll lose any data changes we’ve made whenever we restart the application. So, we’ll opt instead for hooking up a traditional database, and we’ll cover bootstrap classes later on in Chapter 6.
Where’s My Data?
20 | GETTING STARTED WITH GRAILS If you look in racetrack/grails-app/conf/, you’ll notice that our application includes a data source configuration file for each of the common environments: development, test, and production. We’ll want to create a separate database for each of these environments: • Development – We’ll define a database named racetrack_dev to support our development efforts, and we’ll place the corresponding configuration settings in
racetrack/grailsapp/conf/DevelopmentDataSource.groovy.
•
•
racetrack/grailsapp/conf/TestDataSource.groovy.
Test – Our unit and functional tests will rely on the racetrack_test database to be referenced in Production – Lastly we’ll create a racetrack_prod database. With the help of racetrack/grailsapp/conf/ProductionDat.)
racetrack> mysql -u root -p Enter password: ******** Welcome to the MySQL monitor. Commands end with ; or \g. ... mysql> create database racetrack_dev; ... mysql> create database racetrack_test; ... mysql> create database racetrack_prod; ... mysql> grant all on racetrack_dev.* to 'jason'@'localhost' identified by ''; ...
HELLO, GRAILS | 21
mysql> grant all on racetrack_test.* to 'jason'@'localhost' identified by ''; ... mysql> grant all on racetrack_prod.* to 'prod'@'localhost' identified by 'wahoowa'; ... mysql> exit
Now we’re ready to tell Grails about these databases. Open DevelopmentDataSource.groovy in your editor and modify it to match the settings below. You' find this file in ll racetrack/grails-app/conf/. (Note that you’ll need to change the username and password to the appropriate values for your MySQL account.)
class DevelopmentDataSource { boolean pooling = true String dbCreate = "update" String url = "jdbc:mysql://localhost/racetrack_dev" String driverClassName = "com.mysql.jdbc.Driver" String username = "jason" String password = "" }.
22 | GETTING STARTED WITH GRAILS5.0.)
racetrack> grails run-app ... run-app:watch-context:
You can try out the application again if you like, but on the surface, nothing should have changed. It’s the back end that we’re interested in at the moment. Let’s go have a look at our development database. We should see one table for each of our domain classes.
racetrack> mysql Welcome to the MySQL monitor. ... mysql> use racetrack_dev ... Database changed mysql> show tables; +-------------------------+ | Tables_in_racetrack_dev | +-------------------------+ | race | | registration | +-------------------------+ 2 rows in set (0.00 sec) Commands end with ; or \g.
HELLO, GRAILS | 23
mysql> describe race; +----------------+-------------+----+---+-------+---------------+ | Field | Type |Null|Key|Default| Extra | +----------------+-------------+----+---+-------+---------------+ |id | bigint(20) | NO |PRI| NULL | auto_increment| |version | bigint(20) | NO | | | | |distance | float | NO | | | | |max_runners | int(11) | NO | | | | |start_date_time | datetime | NO | | | | |state | varchar(255)| NO | | | | |cost | float | NO | | | | |name | varchar(255)| NO | | | | |city | varchar(255)| NO | | | | +----------------+-------------+----+---+-------+---------------+ 9 rows in set (0.00 sec) mysql> describe registration; +----------------+-------------+----+---+-------+---------------+ | Field | Type |Null|Key|Default| Extra | +----------------+-------------+----+---+-------+---------------+ |id | bigint(20) | NO |PRI| NULL | auto_increment| |version | bigint(20) | NO | | | | |gender | varchar(255)| NO | | | | |date_of_birth | datetime | NO | | | | |postal_address | varchar(255)| YES| | NULL | | |email_address | varchar(255)| NO | | | | |created_at | datetime | NO | | | | |race_id | bigint(20) | YES|MUL| NULL | | |name | varchar(255)| NO | | | | +-----------------+------------+----+---+-------+---------------+ 9 rows in set (0.00 sec) mysql>
Let’s take a moment to discuss the schema Grails generated for us. This is another area where conventions play an important role in Grails. Notice that… • The table names exactly match the domain class names. • The column names match the class’s property names. • For multi-word property names, the column separates the words with an underscore (e.g., the property maxRunners maps to the max_runners column). • The id column is used as the primary key for each table and it’s defined as an auto_increment column, thus allowing Grails to rely on the database to auto-generate unique IDs for new records. • For one-to-many relationships, the child table will include a column to hold the ID of the parent record. The column is named using the name of the parent
24 | GETTING STARTED WITH GRAILS. We’ll cover these topics in more detail in chapter 9. In the mean time, now that we have a database that will preserve our data across restarts, let’s get back to the application improvements we identified earlier.
Building Better Scaffolding
For starters, we mentioned that we need validation and better field ordering. Grails provides a way for us to satisfy both of these needs in one easy step.
HELLO, GRAILS | 25
Declaring Constraints
Grails constraints declare our expectations for the property values of a domain class. We use constraints to declare that a particular property cannot exceed a certain length, that a property has a finite list of valid values, that a property must hold a syntactically-valid e-mail address, and so on.12 We define the constraints using a Groovy closure13 in the domain class, and the closure uses the handy Groovy builder syntax14 to easily and clearly define the constraints. Let’s start with Race domain class. Add the closure shown below to Race.groovy.
class Race { //... static constraints = { name(maxLength:50,blank:false) startDateTime(min:new Date()) city(maxLength:30,blank:false) state(inList:['GA', 'NC', 'SC', 'VA'],blank:false) distance(min:3.1f,max:100f) cost(min:0f,max:999.99f) } }.15 Grails will not persist the object to the database if it fails to satisfy the constraints.
name
26 | GETTING STARTED WITH GRAILS Let’s quickly run down the other constraints in the order they appear above. • • • • • The race cannot start in the past. The city property has a maximum length of thirty characters, and it cannot be blank. The state must be one of the four states in the list – since it’s a regional club – and it cannot be blank. The distance must be between 3.1 miles (5 km) and 100 miles (160.9 km)..
startDateTime(validator: {return (it > new Date())}).
HELLO, GRAILS | 27() //... }
Ordering UI Fields.
Meaningful Record Identifiers
When viewing the details for an individual race, we mentioned that we’d like a more meaningful way to represent a registration than “Registration: 1,” “Registration: 4,” etc. And we want to add similar clarity for identifying races. (If every problem were this easy to solve, we’d all be on the golf course by 9:30 a.m.
28 | GETTING STARTED WITH GRAILS every day – a full half hour early.) The solution is as simple as overriding the default toString method for each domain class. We’ll start by adding the method to Race.groovy.
class Race { //... String toString() {"${this.name} : ${this.city}, ${this.state}" } } enough. Let’s clear things up in Registration.groovy as well. The name and e-mail address should serve well to identify a registrant.
class Registration { //... String toString(){"${this.name}:${this.emailAddress}"} }
was
easy
The Results Are In
Ready to see the fruits of our labor? At the command line, enter grails run-app. Wait to see the application start successfully, and then open your browser to. Let’s first have a look at the race list, and observe the vastly improved column ordering.
HELLO, GRAILS | 29
Did you notice that the list doesn’t show the maximum runners for each race? That’s because the default scaffolding list view will only show up to six properties. If you have constraints defined, it will show the id property and then the first five properties listed in the constraints closure. Grails clearly had to draw the line somewhere, and this behavior tends to yield a reasonably-sized table and prevent dreaded horizontal scrolling. We should also note that the scaffolding is intended to serve as a helpful starting point for our application, to be customized as we see fit. So, if you want additional columns, you can certainly add them. But hold that thought; we’ll soon see how to make rather significant changes to the user interface. Let’s try out the validation, shall we? It’s always fun to try to break an application, so have at it.
30 | GETTING STARTED WITH GRAILS
When we try to create an invalid race, we don’t just get error messages, we also get some fairly nice visual cues indicating the problematic fields. Naturally we’ll want change the error messages to something more business-focused and less technical, and we’ll handle that shortly. In the meantime, it’s nice to know that the system is protected against bogus data.).
HELLO, GRAILS | 31 Lastly, let’s check out the record identifier improvements.
Much better! We can clearly see now that Jane Doe and John Doe have registered for this race. That’s quite a bit more usable than the mysterious integers previously displayed here.
Let’s See the Code!
So far, we’ve relied on declarative scaffolding, by including the def scaffold = Race and def scaffold = Registration directives in our controllers. That approach has served us well up to this point, but now we’re ready to start customizing the scaffolding. We could just add new actions to the controllers as they currently exist. Because declarative scaffolding dynamically generates the controller logic, any new actions we define would simply take precedence over the default actions (assuming the name of our new action matches the name of a default action). However, we’ll want to make just a few tweaks to the existing controller logic over the next few chapters. We can be more productive by generating the scaffolding code and customizing it to meet our needs. To do that, we need access to the real code. So, it’s time to generate the actual scaffolding logic.
32 | GETTING STARTED WITH GRAILS We want to replace the existing controllers (and their whopping three lines of code) with controllers that include the scaffolding code. First things first, let’s delete the existing controller classes – RaceController.groovy and RegistrationController.groovy..
Understanding URLs and Controllers
Now that we can inspect the code, let’s take a moment to look at how Grails determines which controller and which action to invoke for a given URL. (Hint: It doesn’t involve even a single XML configuration file!)
URL Conventions
Consider the types of URLs we saw as we worked our way through the application: Each component of the URL plays an important role in the Grails convention. And it’s by following that convention that
HELLO, GRAILS | 33 we (thankfully) free ourselves from having to wire together our URLs, controllers, and views in external configuration files.
Figure 3-3: URL Structure The first component is the application context root, which of course, identifies the name of the application as it was registered with the server. (By default, Grails uses the application name as the context root and automatically registers the application with the server when we invoke grails run-app.) The next component is used to identify the controller that will handle the request. Given a URL where this component is “registration”, Grails will attempt to route the request to a controller named “RegistrationController”. (If no such controller exists, we can expect to see a trusty HTTP 404 error.) Grails then looks for a component specifying the action to invoke within the given controller. If the URL includes the action, then Grails will invoke that action in the controller. (Again, if the action does not exist, we’ll get an error.) If the URL does not include an action, Grails invokes the default action for the controller. Unless otherwise specified in the controller, Grails looks for an action named “index” as the default action.18 Lastly, Grails looks for a component specifying the ID for a particular record. If such a component is present in the URL, Grails adds a parameter named “id” to the request with this
34 | GETTING STARTED WITH GRAILS value. In the example above, the “id” parameter would have a value of “2”.
From Request to Controller to View
Let’s look at a few code examples from RaceController.groovy, and walk through what happens when Grails receives a request for. First, because no action is specified, Grails routes the request to the index action. (Note that all actions are implemented as Groovy closures.)
def index = { redirect(action:list,params:params) }
The default implementation of the index action redirects the request to the list action. The redirect method is just one of many dynamic methods available in Grails controllers.19
def list = { if (!params.max) params.max = 10 [ raceList: Race.list( params ) ] }
The list action also includes a pleasantly concise implementtation. The first statement supports the built-in pagination functionality that, by default, displays a maximum of ten records per page. The second statement is what really matters here. It declares and returns a map with a single key (raceList) whose value is the list of Race objects for all races in the database. (For now, know that the list method is one of the many dynamic methods provided for domain classes.20 We’ll explore these methods in more detail shortly.) We’re finished with the controller, but once this action returns, what component renders the actual view that we see in the browser? Well, it’s convention (once again) that allows the list method to be so concise. Because we’re inside
HELLO, GRAILS | 35
RaceController
and returning from the list action, Grails knows to use the view template located at racetrack/grailsapp/views/race/list.gsp.
Grails uses GSPs (Groovy Server Pages) to provide the templates for the views. If you’ve used JSPs (JavaServer Pages), you’ll recognize the familiar syntax. As the name suggests, the main difference between GSPs and JSPs is the use of Groovy instead of Java to provide scriptlets. As you’ll see, Groovy kindly cuts down the amount of code we need to write in order to get our point across. Now, let’s explore list.gsp for a moment. If we look at part of the template, we can see that it uses the raceList variable (returned by the list method) to render the response.
>
36 | GETTING STARTED WITH GRAILS',model:[race:race]) } }
Here, if the race.save() call returns false, the action instructs Grails to render the create template (racetrack/grailsapp/views/race/create.gsp) using the race object to populate the form.
Controller Lifecycle
Before we leave this topic, we should quickly mention the lifecycle of a Grails controller. It’s worth noting that Grails creates a new controller instance for each request, and the controller only lives long enough to process that request. So, if you absolutely must, you can safely add instance variables to your controllers without any multi-user threading concerns. Just remember that you probably don’t want to try this in any of the traditional Java-based MVC frameworks you might be used to using.
Free Online Version.
Support this work, buy the print copy:
At this point, we’ve developed an application that meets our needs, but it could still use some polish to make it a bit more user friendly. And since we want our users to enjoy our application, let’s spend some time adding in some of those niceto-have items. • Error Messages – We noted that the validation error messages could use some work, so we should customize them to be less technical and more meaningful to the end-user. Warning and Confirmation Messages – Did you try to delete any records? Were you surprised when the application deleted the record without asking you for any kind of confirmation? Most users would expect a warning before deleting a record, so we’ll add that feature. We’ll also add logic to display confirmation messages after we add, update, or delete a record. Record IDs – While the database and the application rely heavily on record IDs, end users don’t tend to have much use for them. End users want to see the business data (e.g., race name, registration date/time, etc.), and we really shouldn’t concern them with underlying implementation details like record IDs. Data Formatting – A truly professional application displays its data in the appropriate format. We have some work to do in this area. For example, the Date of Birth field on the registration page really shouldn’t include the time of day. It’s just not relevant. The
Improving the User Experience
4
•
•
•
37
38 | GETTING STARTED WITH GRAILS various numeric and currency values could benefit from improved formatting as well.
Customizing Error Messages
Each validation constraint has a pre-defined list of error codes it can return. So far, we’ve seen only the default text for those error messages. As we start to define custom error messages, we’ll want to refer to the Grails reference documentation to determine the message code(s) associated with each constraint.12 For starters, let’s look at the error message that accompanies a blank race name.
We need to review the domain class to find the name of the constraints we applied to the race name property.
static constraints = { name(maxLength:50,blank:false) //... }
The name of the constraint to check for blank values is, plainly enough, “blank.” We can now look up that constraint in the Grails reference documentation.
IMPROVING THE USER EXPERIENCE | 39
The documentation tells us that this constraint generates an error code with the following naming convention.
className.propertyName.blank
So, to customize the error message, we want to add an entry with this pattern to racetrack/grailsapp/i18n/messages.properties.
race.name.blank=Please enter a name for this race
Once we’ve added this entry, let’s restart the application and try it out.
40 | GETTING STARTED WITH GRAILS For some constraints, Grails also supplies runtime arguments that you can include in your messages. You can look at the default error messages (in messages.properties) to help you determine the value provided in each argument. For example, the max constraint’s error message includes an argument specifying the maximum allowable value. That information will go a long way towards improving our application’s usability, and we’d certainly rather not duplicate that value in messages.properties when it already exists in the constraint itself (in Race.groovy). From examining the default error message for this constraint (defined as default.invalid.max.length.message), we can determine that the message’s fourth argument indicates the maximum value. (Because the argument array uses a zero-based index, we access the fourth argument using an index of 3.)
Property [{0}] of class [{1}] with value [{2}] exceeds the maximum length of [{3}]
So, we can define the following entry in messages.properties to provide the desired error text for a race distance that exceeds the maximum allowable value.
race.distance.max.exceeded=Please enter a valid distance no more than {3} miles
And we now have an error message that provides all the information the user needs in order to address the problem.
IMPROVING THE USER EXPERIENCE | 41
Now that we know how to customize an error message, we just repeat the process for the remaining constraints. (Of course, you’ll probably want to customize several messages at a time, unless you really enjoy restarting your server.)
Adding Warning Messages
Without a doubt, users expect an application to warn them before performing any destructive actions. Deleting data certainly qualifies as destructive activity, especially when you consider that deleting a race also deletes all the corresponding registrations. So, let’s add some logic to get the user’s approval before deleting any records. Because a user can delete a race from either the Show Race page or the Edit Race page, we’ll want to define our warning logic in a common place for use by both pages. We’ll use a JavaScript dialog to provide the warning message, so let’s create a file (racetrack/web-app/js/racetrack.js) to hold the common JavaScript functions for the application. Add the following function to racetrack.js.
42 | GETTING STARTED WITH GRAILS
function warnBeforeRaceDelete() { return confirm('Are you sure you want to delete this race?') }
Now we need to call this function from the Show Race and Edit Race pages. Open the template for the Show Race page (racetrack/grails-app/views/race/show.gsp), and add the script tag shown below, which allows this page to reference the functions in racetrack.js.
<head> <meta http- <g:javascript <meta name="layout" content="main" /> <title>Show Race</title> </head>
Then, find the Delete button and add the onclick attribute shown below to call our new function. If the user chooses to delete the race, the function will return true, the browser will submit the form, and the application will delete the race. Otherwise, the function will return false, and the browser won’t submit the form.
<g:form <input type="hidden" name="id" value="${race?.id}" /> <span class="button"> <g:actionSubmit </span> <span class="button"> <g:actionSubmit </span> </g:form>
Now let’s try to delete a race from the Show Race page.
IMPROVING THE USER EXPERIENCE | 43
That’s just what we wanted. It’s simple, but important. Go ahead and modify the Edit Race page to call this JavaScript function as well. Then, add a similar function to provide a warning before deleting a registration, and call that function from the Show Registration and Edit Registration pages.
Confirmation messages are a rather simple feature, but if you’ve ever used an application that doesn’t provide them, you can’t help but wonder sometimes if the application has actually done what you’ve asked. Technically, the user can see the results of her actions as the application exists now. When the user updates a race, the application displays the Show Race page with the updated data. But, the user is left to scan the data to make sure her updates are intact. A simple confirmation message should boost the user’s confidence in our application. You may have noticed that the application already displays confirmation messages when we delete a record. We’ll piggyback on that existing logic to add confirmation messages after creating or updating a record. Upon creating or updating a race, the application displays the Show Race page. If you look in the template for this page
Implementing Confirmation Messages
44 | GETTING STARTED WITH GRAILS (racetrack/grails-app/views/race/show.gsp), you’ll see that it already includes logic for displaying confirmation messages (or any other kind of message we deem appropriate).
<g:if <div class="message">${flash.message}</div> </g:if>
Let’s look at the controller logic that supplies the messages, and then we’ll discuss just exactly what the code above is all about. Open RaceController.groovy and locate the update action. Add the logic shown below to assign the confirmation message to flash.message when we successfully save a race. (Towards the end of this closure, you’ll notice another use of flash.message already provided by the default scaffolding.)
def update = { def race = Race.get( params.id ) if(race) { race.properties = params if(race.save()) { flash.message = "${params.name} updated." redirect(action:show,id:race.id) } else { render(view:'edit',model:[race:race]) } } else { flash.message = "Race not found with id ${params.id}" redirect(action:edit,id:params.id) } }
So where does flash.message come from? Grails includes the concept of “flash” scope. In the same way that controllers and view templates have access to the request and the session, they also have access to flash scope. And just like request and session parameters, the flash object is simply a map of keyvalue pairs. What makes the flash scope unique is its duration. Items stored in flash scope are available for the duration of the current request and the next request. In the example above, we redirect to the Show Race page. The redirect generates a new request. If we had stored the message in the request, we would
IMPROVING THE USER EXPERIENCE | 45 no longer have access to it when we display the Show Race page. By using flash scope, we still have access to the message even after the redirect. And upon the end of the second request, Grails then clears the items from flash scope. No manual cleanup necessary. Let’s find a race to update and see if we feel more confident given our new confirmation message.
Looks good. Now let’s add logic in the save action to display a similar message after creating a new race.
def save = { def race = new Race() race.properties = params if(race.save()) { flash.message = "${params.name} saved." redirect(action:show,id:race.id) } else { render(view:'create',model:[race:race]) } }
Give this new message a try, and then we’ll be finished adding confirmation messages for the race components. Take a moment
46 | GETTING STARTED WITH GRAILS to add similar confirmation messages for the registration components, and then we’re ready for our next task.
Removing Record IDs
Occasionally, you can actually make an application better by removing certain features. Record IDs tend to fall into this category. Our end users just aren’t concerned with them, and that’s reason enough to remove them from the user interface. Let’s start with the Race List page. Find the section below in racetrack/grails-app/views/race/list.gsp, and remove the ID column.
<tr> <th>Id</th> <th>Name</th> <th>Start Date Time</th> <th>City</th> <th>State</th> <th>Distance</th> <th></th> </tr> >
Now, when we view the Race List page, we see only the data that matters to our users.
IMPROVING THE USER EXPERIENCE | 47
Record IDs also appear on the Show Race page, the Edit Race page, and the analogous pages for managing registrations. We’ll want to track down and remove the IDs from those pages as well.
Formatting Data
There’s just no denying that the application could benefit from more appropriate data formatting. We needn’t look any further than the Show Race page to find an awkwardly formatted date/time value, a monetary value with the wrong precision and no currency symbol, and a few more opportunities for improvement as well.
Apart from assigning a style to the table cells, the application currently uses each property’s default toString method to render its output.
48 | GETTING STARTED WITH GRAILS
<tr class="prop"> <td valign="top" class="name">Start Date/Time:</td> <td valign="top" class="value">${race.startDateTime}</td> </tr>
Instead of relying on the toString method, we need a way to specify our desired format for both dates and numeric values. We could embed the formatting logic directly in the view templates, but that would get rather ugly, and we’d end up with a lot of duplicated code. In this situation, we know that a better choice is to implement a custom tag library. And we’re in luck, because adding new tags to Grails is a breeze.
Custom Tag Libraries
Let’s start with formatting date/time values. If we can think about the tag as a utility method of sorts, we can ask ourselves what parameters we need to provide to the method and what we expect it to return. In this case, we want to provide the Date object and a String indicating the desired format. (We’ll use the formatting syntax defined in java.text.SimpleDateFormat.) Then, we want the tag to output the date the given format. Once we implement our new tag and give it a name – formatDate sounds appropriate – we can replace the existing markup (shown above) with markup that formats the date using our custom tag.
<tr class="prop"> <td valign="top" class="name">Start Date/Time:</td> <td valign="top" class="value"> <g:formatDate </td> </tr>
Now that we have a basic API for our date-formatting tag, let’s look at our number-formatting needs. (We’ll first determine the API for both tags, and then we’ll move on the actually implementing the tag library.) This tag can likely use a similar approach to that of the formatDate tag. We have a number and a desired format – this time we’ll use the formatting syntax from java.text.DecimalFormat – and we want the tag to output the
IMPROVING THE USER EXPERIENCE | 49 formatted number. That sounds straightforward enough. So, what would the new markup look like for the various numeric values on the Show Race page?
<tr class="prop"> <td valign="top" class="name">Distance:</td> <td valign="top" class="value"> <g:formatNumber </td> </tr> <tr class="prop"> <td valign="top" class="name">Cost:</td> <td valign="top" class="value"> <g:formatNumber </td> </tr> <tr class="prop"> <td valign="top" class="name">Max Runners:</td> <td valign="top" class="value"> <g:formatNumber </td> </tr>
We have our APIs, and now we’re ready to code the tag library. Grails tag libraries are written (not surprisingly) as Groovy classes. Each tag is defined as a closure, and the closure receives a map containing the tag attributes as an argument at runtime. Let’s define a new Groovy class for our application’s custom tags. We’ll create a new file called RaceTrackTagLib.groovy and place it in the racetrack/grails-app/taglib directory.
class RaceTrackTagLib { /** * Outputs the given <code>Date</code> object in the * specified format. If the <code>date</code> is not given, * then the current date/time is used. If the * <code>format</code> option is not given, then the date is * output using the default format. * * e.g.: * <g:formatDate * * @see java.text.SimpleDateFormat
50 | GETTING STARTED WITH GRAILS
*/ def formatDate = { attrs -> def date = attrs.get('date') if (!date) { date = new Date() } def format = attrs.get('format') if (!format) { * * @see java.text.DecimalFormat */ def formatNumber = { attrs -> def number = attrs.get('number') if (!number) { number = new Double(0) } def format = attrs.get('format') if (!format) { format = "0" } out << new java.text.DecimalFormat(format) .format((Double)number) } }
Lastly, we need to register the TLD (Tag Library Descriptor). Wait a second. Scratch that. Grails doesn’t need any TLDs. TLDs represent configuration, but Grails prefers convention instead. Recall that we placed the tag library in racetrack/grails-app/taglib, and that’s exactly where Grails will look when it encounters a tag in the view template. Grails will simply find the closures for each tag and execute
IMPROVING THE USER EXPERIENCE | 51 them. So, that’s it. We’re ready to test. Let’s take a look at our more properly formatted data.
We’re making progress. Of course, we should propagate these improvements to the other race pages as well. The Race List page can benefit from similar formatting, and the Create Race and Edit Race pages should include units of measure for the Distance field and a currency indicator for the Cost field. Once you’ve made those few enhancements, we’ll be ready for our next task.
Standard Tag Libraries
We won’t always need a custom tag library to get the job done. Fortunately, Grails offers a healthy serving of standard tags as well.21 And it’s on the registration-related pages that we need to tweak the use of those tags a bit.
52 | GETTING STARTED WITH GRAILS
Consider the Create Registration page for example. This page uses the Grails datePicker tag to render the Date Of Birth and Created At fields. We want the Created At field to represent the registration timestamp, and that’s something we can determine without user input. In fact, we’d really prefer not to allow the user to edit the field at all; otherwise we could end up with inaccurate data. And as we mentioned before, the time of day is irrelevant when asking for the runner’s date of birth. Back in your editor, open the template for the Create Registration page (racetrack/grails-app/views/registration/create.gsp). Now, locate the section of the template that renders the Date Of Birth field. If we look at the Grails documentation for the 22 datePicker tag , we see that it supports an optional precision parameter. This is exactly what we need. Let’s add this parameter to the tag used for the Date Of Birth field so that it only renders the year, month, and day. </g:datePicker> <g:datePicker
IMPROVING THE USER EXPERIENCE | 53 That was easy enough. Now, on to our next improvement. Ensuring that we get an accurate registration date is down right trivial – just remove the Created At field from the page altogether. Recall that the Registration class initializes the createdAt property to the current timestamp. So, when Grails creates a new Registration object with the data from the form, the object will already have the correct registration timestamp (i.e., the current date/time).
class Registration { //... Date createdAt = new Date() //... }
And now, our slightly-modified page is ready to more accurately capture the data we need.
While we’re at it, we should also address these fields on the other registration-related pages. We should adjust the precision
54 | GETTING STARTED WITH GRAILS of the Date of Birth field on all pages. On the Edit Registration page, we can simply adjust the precision of the datePicker tag as we saw above. On the Registration List and Show Registration pages, we can use our new formatDate tag to show only the month, day, and year. That leaves us with just the Created At field left to handle. We don’t ever want to change the value for this field. It represents the time at which the registration was created, and well, you just can’t change history. Since the Edit Registration page currently allows the user to alter the Created At field, we should adjust the page to instead display the field as a read-only value. Take a moment to add that bit of polish to the application, and then we’re ready for the next iteration.
Free Online Version.
Support this work, buy the print copy:
OK. We’ve worked through a few initial iterations with our users. We’ve gotten their feedback, and they like what they see so far. They’re excited by how quickly we put the application together and how we continue to make small incremental improvements with short turnaround times. Of course, once we have some basic CRUD functionality like this, one of the first requests we get is, “I need a way to find all races scheduled for the month of _______.” Or, “Show me all __-mile races located in _______.” These are reasonable enough requests, and Grails will help us continue to impress our users as we quickly provide these new reports. Recall our brief mention of dynamic methods back when we looked the generated controller code? We observed the list method – a dynamic method in all domain classes – used to fetch all races for display on the Race List page. We didn’t have to write any special code in our domain class to obtain that functionality. It simply comes standard with any Grails domain class. As we implement this new query functionality, we’ll take a deeper at look at some of the other dynamic methods available for Grails domain classes.
Get Dynamic
5
Dynamic Finders
For starters, let’s say we need to be able to find all races by city. We’ll add a new menu option on the Race List page to take us to our new query page. Add this block to the menu section of racetrack/grails-app/views/race/list.gsp.
55
56 | GETTING STARTED WITH GRAILS
<span class="menuButton"> <g:linkSearch for Races</g:link> </span>
Clicking this menu option will invoke a new action in our controller named search. For now, we don’t need that action to do anything more than render our search input page. So, add an empty closure in RaceController.groovy to accept these requests.
def search = { }
This empty closure tells Grails that search is a valid action for this controller. When Grails receives a request for this action, it will simply look for a template with the same name (i.e., search.gsp) in racetrack/grails-app/views/race/ and render its content. Since we really just want a simple form with input fields for a race, for Races</title> </head> <body> <div class="body"> <h1>Search for Races</h1> <g:if <div class="message">${flash.message}</div> </g:if> <g:form <div class="dialog"> <table> <tr class='prop'> <td valign='top' class='name'> <label for='city'>City:</label> </td> <td valign='top' class='value'> <input type="text" maxlength='30' name='city'> </input> </td>
GET DYNAMIC | 57
</tr> </table> </div> <div class="buttons"> <input type="submit" value="Search" class="formbutton"> </input> </div> </g:form> </div> </body> </html>
And now, our new search page awaits.
You’ll notice that in search.gsp we specified that the form should post all requests to the search action.
<g:form
Our search action is currently empty and simply routes to the search input page. Now, we need to add some logic to actually perform the searches.
def search = { if (request.method == 'POST') { render(view:'list', model:[ raceList: Race.findAllByCityLike('%' + params.city + '%') ]) } }
Since we’re using the same action to render the search input page and to output the search results, we need a way to determine which function to perform for a given request. We know that the query parameters will arrive in a post request, so
58 | GETTING STARTED WITH GRAILS we’ll make sure we only perform a search for post requests. For any other requests types – presumably get requests – we’ll simply display the search input page. Once we know that we have a post request, what is the rest of this code doing? Well, it’s another example of Grails’s ability to provide significant functionality in a few succinct commands. For all post requests, the search action will… • • • • Get the search criteria from the request using params.city. Get a list of Race objects for races matching that city using the findAllByCityLike method – just one of the many available dynamic finder methods. Put the results in an object named raceList. render the view, using the raceList object as the model, in the list view template. (Because we just want to display a list of matching races, we can safely use the existing Race List template – racetrack/grails-app/views/race/list.gsp.)
When we click Search, sure enough, we get the matching results.
Of course, if we can search races by city, why not search by state as well? We can easily add a new input field to our search page for this purpose.
GET DYNAMIC | 59
<tr class='prop'> <td valign='top' class='name'> <label for='state'>State:</label> </td> <td valign='top' class='value'> <g:select </g:select> </td> </tr>
A simple text input field was perfectly appropriate for entering the city, but a select field is better suited for capturing the state parameter. However, in order to build a select field, we have to know the valid options. We certainly don’t want to hard code the list of states in the page, so luckily we can obtain the list of valid states right from our domain class – the definitive source for this information. And because the user may not always want to query by state, we add a blank value as the first option in the list.
60 | GETTING STARTED WITH GRAILS That was easy enough, but what do we have to change in our controller? As it turns out, there’s actually very little we need to change. Instead of using the findAllByCityNameLike method, we’ll now invoke another dynamic finder –
findAllByCityLikeAndStateLike.
def search = { if (request.method == 'POST') { render( view:'list', model:[raceList: Race.findAllByCityLikeAndStateLike ('%' + params.city + '%', '%' + params.state + '%') ] ) } }
Grails automatically provides dynamic finders for just about every query combination you can think of! Try it out. Our search from above now yields just what we’d expect given our updated query.
Over time, we’ll likely see our requirements grow in complexity. (That’s good though. It keeps us on our toes.) So, how can we support additional query parameters with different data types and different conditional operators? For example, suppose I want to find all races where the distance is at least 5 miles and the date is between July 1st and September 15th. That kind of query is beyond the capabilities of the dynamic finders that we
Build Your Own Criteria
GET DYNAMIC | 61 just saw. No worries, though. That doesn’t mean that your application has to take on any additional complexity. Grails offers the immensely flexible Hibernate Criteria Builder23 to satisfy that need without sacrificing any of the functionality we’ve seen so far. Quick Note: If you don’t anticipate needing to support these types of queries in your applications, you can safely skip ahead to Chapter 6 for now. Feel free to refer back to this section if your needs change.
Introducing the Hibernate Criteria Builder
Before we add any new query parameters, let’s take a moment to first understand the structure of a Hibernate Criteria Builder. To do so, we’ll migrate the existing search action to use a Hibernate Criteria Builder instead of the current dynamic finder.
def search = { if (request.method == 'POST') { def criteria = Race.createCriteria() def results = criteria { and { like('city', '%' + params.city + '%') like('state', '%' + params.state + '%') } } render(view:'list', model:[ raceList: results ]) } }
Even if you’ve never used Hibernate or Grails before, you can quickly get the gist of what’s going on here. A Hibernate Criteria Builder is one kind of Groovy builder, and in a Groovy builder, each component is referred to as a “node.” The and node tells us that we’ll match any records that satisfy one or more of the criteria specified by its child nodes. In this case, it has two child nodes.
62 | GETTING STARTED WITH GRAILS The first child node returns results that satisfy a case-insensitive like operation on the city attribute.
like('city', '%' + params.city + '%')
Similarly, the second child node applies a case-insensitive like operation on the state attribute.
like('state', '%' + params.state + '%')
Together, these nodes are equivalent to the dynamic finder we used previously. However, now we can easily expand this builder to support more advanced query requirements. If the builder structure seems oddly organized at first, it’s because the Hibernate Criteria Builder somewhat resembles a Polish notation syntax, in which you specify the operator before the operands.24 That’s certainly a departure from Java’s use of relational operators, but it should become relatively intuitive after your first few queries.
Enhancing the View
Now, let’s modify our search page to capture the input for our new requirements. If we edit search.gsp and add the following input fields, it should give us what we’re looking for.
<tr class='prop'> <td valign='top' class='name'> <label for='date'>Date:</label> </td> <td valign='top' class='value'> between <g:datePicker and <g:datePicker </td> </tr> <tr class='prop'> <td valign='top' class='name'> <label for='distance'>Distance:</label> </td> <td valign='top' class='value'> <select name='distanceOperator' > <option value='AT_LEAST' >At least</option>
GET DYNAMIC | 63
<option value='EXACTLY' >Exactly</option> <option value='AT_MOST' >At most</option> </select> <input type='text' name='distance' size='5'> </input> mi </td> </tr>
And a quick sanity check tells us that we’re on the right track.
Working with Java Classes
You’ll notice that we’re now capturing query parameters that do not map directly to our domain class. For example, our query parameters now include a minimum date and a maximum date, but our domain class simply contains a single date – the starting date/time for the race. Similarly, we now have a new query operator (i.e., at least, exactly, or at most) associated with the race distance, but the actual race domain model only has the race distance. In short, we lack a nice one-to-one mapping between the domain model and the data parameters that make up the query request. In these situations, I prefer to define a class to represent the query itself. Let’s add a RaceQuery class to fulfill this need. Where does such a class belong in our project structure? It’s not a domain class per se, because we have no need to persist one of these query objects. It’s not a controller, and it’s certainly not a view. This is where the racetrack/src directory comes into play. It’s in this directory that we can add Groovy or Java classes for use by our Grails application.
64 | GETTING STARTED WITH GRAILS The distance operator has exactly three valid values – at least, exactly, or at most – thus making it a perfect candidate for an enumerated type. And if we want to use enumerated types, we’ll need to implement the RaceQuery class in Java. (Groovy will eventually support enumerated types, but we’ll have to wait for Groovy 2.0.25) Java 5 Dependency Note: If you’re using a JDK prior to Java 5, you’ll need to use an alternate mechanism (e.g., a java.lang.String object) for capturing the distance operator value. Without further ado, let’s implement this new class – RaceQuery.java – and place it in the racetrack/src/java directory.
import java.util.Date; public class RaceQuery { public enum DistanceOperator {AT_LEAST,EXACTLY,AT_MOST}; private private private private private private Date minDate; Date maxDate; String city; String state; Float distance; DistanceOperator distanceOperator;
public String getCity() { return city; } public void setCity(String city) { this.city = city; } // remaining getters and setters not shown // ... }
Now that we have a class for capturing the query parameters, we’re ready to put it to use in the builder.
GET DYNAMIC | 65
Expanding the Criteria Builder
Let’s update the builder to work with our new query object and the new query parameters that it provides. (This code should replace our current search action in RaceController.groovy.)
def search = { if (request.method == 'POST') { RaceQuery query = new RaceQuery() bindData(query, params) def criteria = Race.createCriteria() def results = criteria { and { like('city', '%' + query.city + '%') like('state', '%' + query.state + '%') if (query.distance) { switch (query.distanceOperator) { case RaceQuery.DistanceOperator.AT_LEAST: ge('distance', query.distance) break case RaceQuery.DistanceOperator.EXACTLY: eq('distance', query.distance) break case RaceQuery.DistanceOperator.AT_MOST: le('distance', query.distance) break default: log.error "Found unexpected value for distance" + " operator ${query.distanceOperator}" } } // Add 1 day (24 hours) to the max date. // (If user selects a max date of Jan 1st, // the date object will hold Jan 1st 00:00, // but the user will want any events // occurring thru Jan 1st 23:59.) between('startDateTime', query.minDate, query.maxDate + 1) } //and } render(view:'list', model:[ raceList: results ]) } //if }
Now that we’ve seen the code, let’s walk through the individual changes we made to get this action to work with the RaceQuery object and the new parameters.
66 | GETTING STARTED WITH GRAILS • First, we added code to instantiate a new RaceQuery object and bind the request parameters to the RaceQuery object. Grails provides the dynamic bindData method to all controllers. This method interrogates the request parameters and the target object – in this case, a RaceQuery object – and populates the target object with the corresponding parameters (determined by name) in the request, conveniently performing type conversion as needed.
RaceQuery query = new RaceQuery() bindData(query, params)
•
Next, we added logic to include the distance-related parameters in the builder. The switch statement evaluates the distanceOperator attribute and adds the appropriate node to the builder. For example, if the query is looking for races that are at least 5 miles long, the builder will include a ge node to identify races with distances greater than or equal to the specified distance.
ge('distance', query.distance)
•
Lastly, we included new code to incorporate the daterelated parameters into the builder. The between node matches races with a start date occurring between the specified minimum and maximum dates (inclusively).
between('startDateTime', query.minDate, query.maxDate + 1)
Now let’s see it in action. First, we need to restart the application to pick up the new RaceQuery class. Then, we’re ready to try it out. Recall that we wanted to find all races where the distance is at least 5 miles and the date is between July 1st and September 15th.
GET DYNAMIC | 67
And when we click Search, we get exactly that.
Free Online Version.
Support this work, buy the print copy:
So far, we’ve managed to put together a fully functioning application for managing races and registrations, but do we really want our internal team to have to manually enter all the registrations for every runner? Wouldn’t we rather allow runners to register themselves? Certainly. But opening the application to external users brings with it some additional considerations. • Public users versus administrators – Administrators (i.e., internal users) should continue to have access to all of the functionality we’ve built so far. We’d like to allow public users (i.e., non-administrators) to search for races and register themselves for races (assuming registration is not yet full for the race in question), but that’s where their access should end. We need to protect the application’s administrative features, and only allow the internal users to access that functionality. Authentication – In order to allow different levels of functionality for different users, we need a way to distinguish an administrator from a non-administrator. This, of course, calls for an authentication mechanism to allow administrators to submit their credentials. Look-and-feel – The Grails templates we’ve used so far were certainly good enough for our intranet app (and are still good enough for the administrative features), but we’ll want to provide a more customized look-and-feel for the public portion of our application.
Not Just for Intranet Apps
6
•
•
69
70 | GETTING STARTED WITH GRAILS After sitting down with our customers to understand their needs, we’ve sketched out a basic flow for the public portion of the application.
Figure 6-1: User Interface Flow for Public-Facing Pages
Beyond CRUD
Changing the Landing Page
Whenever a user accesses the root URL (), we want the application to display the Search for Races page as the new default landing page. (We don’t want our public users to see the current landing page that simply prompts the user to select a controller.) All requests to the root URL are handled by racetrack/webapp/index.jsp. When you open this file in your editor, you’ll see the content used to generate the current landing page. Replace the existing content with the following line.
<%response.sendRedirect(request.getContextPath()+"/race/search"); %>
As you can see, index.jsp will now redirect to the Search for Races page at.
NOT JUST FOR INTRANET APPS | 71
Adding Public-Friendly Views
Next, we need to add the pages that our public users will access to view the races matching their search criteria and to register for a race. We can’t simply use the existing pages that offer this functionality, because those pages also include various administrative features. For example, the current page that displays the list of races also allows the user to create a new race, but we only want administrators to have that sort of access. Our public users need a read-only view of races with no options to create, update, or delete any records. We could conceivably make the existing Race List page smart enough to distinguish an administrator from a non-administrator, but doing so assumes that we’ll always want the administrator’s view to look fairly similar to the public view. That’s probably not a safe assumption, so let’s add a new template – racetrack/grails-app/views/race/ searchresults.gsp – to provide the public view of this data.
<html> <head> <meta http- <meta name="layout" content="main" /> <title>Races Meeting Your Criteria</title> </head> <body> <div class="body"> <h1>Search Results</h1> <h2> <g:if 1 Race Meets Your Criteria: </g:if> <g:else> ${raceList?.size()} Races Meet Your Criteria: </g:else> </h2> <g:if <div class="message">${flash.message}</div> </g:if> <div class="dialog"> <table> <tr> <th>Name</th> <th nowrap>Start Date</th> <th nowrap>Start Time</th> <th>City</th>
72 | GETTING STARTED WITH GRAILS
<th>State</th> <th>Distance</th> <th>Cost</th> <th></th> </tr> <g:each <tr> <td nowrap> <span class="lineItemValue">${it.name}</span> </td> <td nowrap> <span class="lineItemValue"> <g:formatDate </span> </td> <td nowrap> <span class="lineItemValue"> <g:formatDate </span> </td nowrap> <td nowrap> <span class="lineItemValue">${it.city}</span> </td> <td nowrap> <span class="lineItemValue">${it.state}</span> </td> <td nowrap <span class="lineItemValue"> <g:formatNumber </span> </td> <td nowrap <span class="lineItemValue"> <g:formatNumber </span> </td> <td class="actionButtons"> <g:if <span class="actionButton"> <g:linkRegister </g:link> </span> </g:if> <g:else><strong>Full<strong></g:else> </td> </tr> </g:each> </table> </div> </div> </body> </html>
NOT JUST FOR INTRANET APPS | 73 Now we need to modify RaceController.groovy to render the view using this new template instead of the existing list.gsp template. In the search action, simply change the name of the view from list to searchresults.
render(view:'searchresults', model:[ raceList: results ])
We’ve defined a new view and we’ve updated the controller, so we’re ready to try out our changes.
We now have a reasonable read-only view for our public users. And as an added touch, the right-most column also now includes an indication of whether the user can still register for a given race. Speaking of registering for races, you may have noticed that we asked the Register link (in searchresults.gsp) to route its requests to the register action in RegistrationController.
<g:linkRegister </g:link>
We don’t have a register action yet, so let’s define one in RegistrationController.groovy.
def register = { def registration = new Registration() registration.properties = params if (request.method == 'GET') { def race = Race.get(params.id) return ['registration':registration,'race':race]
74 | GETTING STARTED WITH GRAILS
} else { if(registration.save()) { flash.message = "Successfully registered for ${registration.race.name}" redirect(controller:'race',action:'search') } else { def race = Race.get(params['race.id']) return ['registration':registration,'race':race] } } }
Following an approach similar to the one we used for the search action in RaceController.groovy, the register action will interrogate the request type to determine how to process the request. For get requests, the action will simply display the registration page for the given race. The template will have access to the Registration object and the Race object for use in rendering the page. For post requests, the action will attempt to persist the Registration object (populated from the request parameters). If it’s able to validate and save the registration successfully, then the action will route the user back to the search page and display a friendly confirmation message. Otherwise, the action will redisplay the registration input page and alert the user to the problems that prevented the application from saving the registration. As we now know, upon exiting from the register action, by convention Grails will look for the corresponding view template at racetrack/grailsapp/views/registration/register.gsp. Since we’re effectively just creating a new registration, we can borrow much of the structure for this new template from create.gsp. However, because we want to make this page available to our non-
NOT JUST FOR INTRANET APPS | 75 administrative users, we’ll be sure to customize the template accordingly.
<html> <head> <meta http- <meta name="layout" content="main" /> <title>Register</title> </head> <body> <div class="body"> <h1>Register for ${race.name} </h1> <em>Start Date: <g:formatDate <br /> </em> <em>Start Time: <g:formatDate <br /> </em> <g:if <div class="message">${flash.message}</div> </g:if> <g:hasErrors <div class="errors"> <g:renderErrors </div> </g:hasErrors> <g:form <g:hiddenField <div class="dialog"> <table> <tr class='prop'> <td valign='top' class='name'> <label for='name'>Name:</label> </td> <td valign='top' class='value ${hasErrors(bean:registration,field:'name','errors')}'> <input type="text" maxlength='50' name='name' value='${registration?.name}'></input> </td> </tr> <tr class='prop'> <td valign='top' class='name'> <label for='dateOfBirth'>Date Of Birth:</label> </td> <td valign='top' class='value ${hasErrors(bean:registration,field:'dateOfBirth','errors')}'> <g:datePicker</g:datePicker> </td>
76 | GETTING STARTED WITH GRAILS
</tr> <tr class='prop'> <td valign='top' class='name'> <label for='gender'>Gender:</label> </td> <td valign='top' class='value ${hasErrors(bean:registration,field:'gender','errors')}'> <g:radio </g:radio> Male <g:radio </g:radio> Female </td> </tr> <tr class='prop'> <td valign='top' class='name'> <label for='postalAddress'>Postal Address:</label> </td> <td valign='top' class='value ${hasErrors(bean:registration,field:'postalAddress','errors')}'> <textarea rows='3' cols='30' name='postalAddress'> ${registration?.postalAddress} </textarea> </td> </tr> <tr class='prop'> <td valign='top' class='name'> <label for='emailAddress'>Email Address:</label> </td> <td valign='top' class='value ${hasErrors(bean:registration,field:'emailAddress','errors')}'> <input type="text" maxlength='50' name='emailAddress' value='${registration?.emailAddress}'></input> </td> </tr> </table> </div> <div class="buttons"> <input type="submit" value="Register" class="formbutton"></input> <input type="button" value="Cancel" onClick="history.back()" class="formbutton"> </input> </div> </g:form> </div> </body> </html>
NOT JUST FOR INTRANET APPS | 77 Now when a user registers for a race, the registration page will include the race name, date, and time, but it will hide the other administrative CRUD functions that only internal users can perform.
And assuming the user enters valid information, she’ll be greeted with message confirming her registration. She can go lace up and start training!
78 | GETTING STARTED WITH GRAILS
Implementing User Authentication
We now have all the pages we want to make available to our public users, but it’s certainly not enough to just trust that they’ll stay away from the administrative components. No, we need to put some security in place to restrict access to those non-public features. To do so, we’ll first need a way for our administrative users to authenticate themselves to the application. Once authenticated, they’ll be able to access the secured areas of the system.
Managing User Accounts
Knowing that we’ll need to maintain a list of authorized users and their credentials, why not just define a new Grails domain class to support that data? Using the approach we demonstrated earlier for the Race and Registration classes, let’s create a User domain class with the following attributes and constraints.
class User { String userId String password static constraints = { userId(length:6..8,unique:true) password(length:6..8) } }
Quick Note: For a secure production application, we wouldn’t dare use plain text passwords. Instead, we’d likely opt for a one-way encryption algorithm (such as SHA26) to allow us to work with hashed passwords. We won’t go into those details here, but you can have a look at Java’s MessageDigest27 class for more information on using secure one-way hash functions in Java (and/or Grails) applications. Now that we have the domain class in place, use the grails generate-all command to generate the user interface scaffolding to manage the user data. Before we lock down the administrative features, we first need to create at least one administrator for the application. While we
NOT JUST FOR INTRANET APPS | 79 could just use the user interface to create the first administrator, there’s another option that offers some additional benefits. Grails provides a bootstrap mechanism for performing any initialization tasks that you want your application to perform at startup.28 By convention, Grails looks for classes in the racetrack/grails-app/conf directory with names like FooBootStrap.groovy, BarBootStrap.groovy, etc. Grails expects these classes to contain an init closure – to be called on application startup – and a destroy closure – to be invoked as the application shuts down. (As a general rule, you don’t want to rely on the destroy closure to perform any mission-critical work. If for some reason the application terminates abnormally, the destroy closure is not guaranteed to run.) By default, Grails provides an empty bootstrap class for us to use as we see fit. Let’s use that class – racetrack/grailsapp/conf/ApplicationBootStrap.groovy – to create the first administrator.
class ApplicationBootStrap { def init = { servletContext -> final String BACKUP_ADMIN = 'adminjoe' if (!User.findByUserId(BACKUP_ADMIN)) { new User(userId:BACKUP_ADMIN,password:'password').save() } } def destroy = { } }
Because this closure runs each time the application starts, we can rest assured that we’ll always have at least one administrator defined at application startup. We’ll never be left unable to log in. (Of course, we don’t want duplicate user entries, so our code first makes sure the user does not already exist before creating it.)
80 | GETTING STARTED WITH GRAILS
Intercepting and Authenticating
If we expect our administrators to log in to the system, we obviously need to give them a place to do so. Let’s add a new template – racetrack/grails-app/views/user/ login.gsp – to serve as the authentication page.
<html> <head> <meta http- <meta name="layout" content="main" /> <title>Log in</title> </head> <body> <div class="body"> <h1>Please log in</h1> <g:if <div class="message">${flash.message}</div> </g:if> <g:hasErrors <div class="errors"> <g:renderErrors </div> </g:hasErrors> <g:form <div class="dialog"> <table> <tr class='prop'> <td valign='top' class='name'> <label for='userId'>User ID:</label> </td> <td valign='top' class='value '> <input type="text" maxlength='8' name='userId' value='${user?.userId}'> </input> </td> </tr> <tr class='prop'> <td valign='top' class='name'> <label for='password'>Password:</label> </td> <td valign='top' class='value '> <input type="password" maxlength='8' name='password' value='${user?.password}'> </input> </td> </tr> </table> </div> <div class="buttons"> <span class="button"> <g:actionSubmit
NOT JUST FOR INTRANET APPS | 81
</span> </div> </g:form> </div> </body> </html>
And next, we need actions to render the login page and to process the requests coming from the login page. As we’ve seen before, we can handle different request types from a single action, so we’ll continue that pattern here as well. Let’s add the following action to the UserController class.
def login = { if (request.method == "GET") { session.userId = null def user = new User() } else { def user = User.findByUserIdAndPassword(params.userId, params.password) if (user) { session.userId = user.userId redirect(controller:'race') } else { flash['message'] = 'Please enter a valid user ID and password' } } }
Our application will use a simple (yet effective) approach for identifying a logged-in user. When a user successfully logs in, we store the user ID in the session (in a parameter named “userId”). When the user logs out – as we’ll see in a moment – we remove the user ID from the session. At any given time, the application can look for the user ID in the session to determine whether the user is logged-in. When the login action receives a get request, this indicates that the user is trying to log in. In case the user is already logged-in for some reason – perhaps the user is trying to log in under a different account – we’ll first make sure that session.userId is null and then render the login page.
82 | GETTING STARTED WITH GRAILS When the user submits her user ID and password, the login action will receive a post request, and we need to validate the user’s entries. We look for a user with that ID and password, and if such a user exists, we add the user ID to the session and send the user to the Race List page. If we don’t find a user with that ID and password, then we return the user to the login page and kindly ask them to stop trying to hack into our application. Before we leave the UserController class, we need to give our users a way to log out of the application. Let’s add a logout action to remove the user ID from the session and then return the user to the public portion of the application with a friendly confirmation message.
def logout = { session.userId = null flash['message'] = 'Successfully logged out' redirect(controller:'race', action:'search') }
Adding Interceptors Now we need a way to intercept access to any administrative areas of the application and force the user to first log in before proceeding to those areas. In short, we want to restrict access to all functionality except the few public-friendly modules we implemented a short while ago. Grails action interceptors provide a convenient mechanism for implementing this feature.29 Action interceptors – plainly enough – intercept the normal flow of execution for an action and allow us to perform some other functionality before or after the action executes. For security purposes, before a user can perform some administrative activity, we first want to make sure the user is an administrator. Therefore, we need a beforeInterceptor to invoke our authentication module before executing any administrative actions. Let’s assume that we’ll define a method named auth to determine whether a user has logged in to the application. In the RaceController class, we want that method to execute before
NOT JUST FOR INTRANET APPS | 83 every action except the search action (because we want to allow public access to the search action). We achieve this functionality with the simple declaration below.
class RaceController { def beforeInterceptor = [action:this.&auth, except:['search']] //... }
This declaration tells Grails, “For every action except search, invoke the auth method before passing control to the action.” Of course, we still need an auth method, but we’ll come to that shortly. First, let’s add the necessary interceptors to the other two controllers. In RegistrationController.groovy, public users can only access the register action. Users must authenticate before accessing any other actions.
class RegistrationController { def beforeInterceptor = [action:this.&auth, except:'register'] //... }
In the UserController class, we want to restrict access to everything except the login and logout actions.
class UserController { def beforeInterceptor = [action:this.&auth, except:['login', 'logout']] //... }
We should also note that while the above interceptors apply to all of the controllers’ actions except the named actions, Grails also allows us to define an interceptor that will execute only for a list of named actions. For example…
def beforeInterceptor = [action:this.&auth, only:['fooaction', 'baraction']]
84 | GETTING STARTED WITH GRAILS Introducing a BaseController All of our controllers now rely on a yet-to-be-defined auth method, but we obviously don’t want to duplicate this method in every controller. It’s therefore time to introduce an abstract parent class for our controllers and define the auth method there. We’ll name this class BaseController and define it in
racetrack/grails-app/controllers/ BaseController.groovy.
abstract class BaseController { def auth() { if(!session.userId) { redirect(controller:'user',action:'login') return false } } }
Application-wide, we know that we can identify a logged-in user by looking for the user ID in the session. The auth method relies on this rule to determine where to route a request. If the user ID is not present in the session, then we know the user is not logged-in. We redirect the user to the login page and return false. Recall that this method is called from an interceptor before passing control to the requested action. By returning false, we inform Grails that we are overriding the normal flow of execution and that it should not to proceed to the originally-requested action. If, on the other hand, the user ID is present in the session, then we know that the user is logged-in, and we simply exit from the auth method. Grails then proceeds on to the intercepted action. Now that we have the BaseController class, we need to update our existing controllers to inherit its functionality.
NOT JUST FOR INTRANET APPS | 85
class RaceController extends BaseController { //... } class RegistrationController extends BaseController { //... } class UserController extends BaseController { //... }
Whew! That was a tad more than we’d probably prefer to do without some intermediate testing, so let’s not wait any longer. Let’s start up the application and try to sneak into one of the newly-restricted areas of the system. We know that only administrators can create races, so we’ll see if our security will keep Joe Public away from that module. When we try to access, what will we see?
Good. When an unauthenticated user tries to access an administrative portion of the site, the application now asks the user to first log in. That’s just what we wanted. Before we move on, spend a few minutes experimenting with our new security system. Make sure we can still access the public areas of the application without logging in. Verify that we can log out successfully. Make sure you can’t get in with a bogus password.
86 | GETTING STARTED WITH GRAILS Done? OK. So, yes, the security module does its job, but doesn’t the user experience feel a bit awkward now? Did you notice that the application always takes you to the Race List page after logging in – regardless of which page you were trying to access? What about navigation in general? There’s no userfriendly way to get from the public area of the app to the race administration area, to the user administration area, etc. We can do better than that. Improving Our Memory When we see a user trying to access a restricted area of the application and the user isn’t logged-in yet, we route the user to the login page, and we do a terrible thing along the way. We completely forget where the user was trying to go. Instead, we should take a snapshot of the user’s request so that once the user logs in, we can continue with the original request. Inside the auth method (in BaseController.groovy), add the new code shown below to save the request until we’re ready to process it. We first build a map with the controller name and action name, and we then fill the map with all of the parameters from the request. Just before we send the user to the login page, we store the map in the session for safekeeping.
def auth() { if(!session.userId) { def originalRequestParams = [controller:controllerName, action:actionName] originalRequestParams.putAll(params) session.originalRequestParams = originalRequestParams redirect(controller:'user',action:'login') return false } }
On the other end of this equation lies the login action in the UserController class. Once the user logs in, we simply fetch
NOT JUST FOR INTRANET APPS | 87 the details of the original request and proceed to process it. (As a safeguard, we send the user to the Race List page if for some reason we can’t find the original request.)
def login = { if (request.method == 'GET') { //... } else { def user = User.findByUserIdAndPassword(params.userId, params.password) if (user) { session.userId = user.userId def redirectParams = session.originalRequestParams ? session.originalRequestParams : [controller:'race'] redirect(redirectParams) } //... } }
Take a moment to restart the application to pick up these changes. Now when someone tries to access a protected resource (e.g.,), we’re kind enough to take the user to that resource once she logs in. May I See a Menu, Please? The functionality we provide to our public users is simple enough that they can get by without a menu. They simply search for races, select from a list, and then register. Our administrators, however, have several additional options. Assuming we want to make the menu available on all pages, how can we avoid adding the individual menu options to each and every template? Grails allows us to define sub-templates – used to render just a portion of a page – that we can then embed in other view templates. Because we can reuse a sub-template wherever we like, one should work well for providing our new menu.
88 | GETTING STARTED WITH GRAILS We distinguish a sub-template from standard templates by – you guessed it – convention. Let’s assume we’d like to refer to our menu sub-template as adminmenubar. Then, by convention, we need to define this template in a file named _adminmenubar.gsp. To determine where this file should reside, we first need to consider which templates will include this sub-template. If we only wanted to access the sub-template in the race-related views, we would place the sub-template in racetrack/grails-app/views/race. However, because we want to access it from all views, we need to place the subtemplate in the root view directory – racetrack/grailsapp/views. Inside the sub-template, we’ll determine whether the user is logged-in and display the menu options accordingly.
<g:if <span class="menuButton"> <g:linkLog in</g:link> </span> </g:if> <g:else> <span class="menuButton"> <g:link Manage Races & Registrations </g:link> </span> <span class="menuButton"> <g:link Manage Administrators </g:link> </span> <span class="menuButton"> <g:link Log out </g:link> </span> </g:else>
Now, in order to add the menu to the appropriate pages, we simply refer to the sub-template. Let’s start with the page that serves as the entry point into the application – the Search for Races page. Add the content shown below to racetrack/grails-app/ views/race/search.gsp. The <g:render> tag will evaluate the contents of the sub-template and include the results at this location in the page.
NOT JUST FOR INTRANET APPS | 89
<html> ... <body> <div class="nav"> <g:render </div> ... </body> </html>
Notice that we did not include the leading underscore when referring to the sub-template in the <g:render> tag. This tag is used exclusively for rendering sub-templates, so it will automatically prepend the underscore when looking for the GSP. Also notice that we include a forward slash before the template name. The forward slash tells Grails to look for the template in the root view directory. Without the slash, Grails would expect to find the sub-template in the same directory as the referring template.
We can now add the menu to the application’s other pages as well. By defining the menu just once and including a reference to it (using the <g:render> tag) in other pages, we can manage changes to the menu from a single location. When we modify the sub-template, all pages that include the sub-template will automatically reflect the change.
90 | GETTING STARTED WITH GRAILS Are you asking yourself why the heck we had to update all the pages to refer to the sub-template? Good. You’re right to ask that question. Even though we’re not including the details of the menu-generation code in every template, this is still a less-thanideal solution. In fact, if we were building the application from scratch (or we wanted to perform more significant surgery on the scaffolding-generated views), we could have just placed the menu in the main layout – racetrack/grails-app/views/layouts/main.gsp. The main layout currently provides other common components we see on each page (e.g., the logo, the stylesheet, etc.), so we could have easily included the menu in the main layout as well. We’ll look at this approach more closely in the next section.
UI Makeover: Layouts and CSS
When the conversation turns to how an application looks, that’s usually a good sign. It typically means that we’ve done well as developers and the site functions well enough for the customer to start to focus on aesthetics. So, let’s step up a notch from the default Grails look-and-feel and give our end-users a more customized interface. Our makeover will consist of three main steps. For starters, we’ll define a customized style sheet with the look-and-feel we want for the public portion of the site. Then, we’ll add a few images to the project to support the new look. Lastly, we’ll define a separate layout template for the public pages to use. Ready? Let’s go. First, let’s add the new stylesheet to the application. Grails looks for stylesheets in racetrack/web-app/css/, so we need to place the new stylesheet – public.css – in that directory. (For the sake of brevity, the stylesheet contents are not included the text of this book However, the full stylesheet – along with the complete source code for all examples in this book – is available for you to download and follow along.3)
NOT JUST FOR INTRANET APPS | 91 Our new stylesheet references four new images – banner.jpg, bg.gif, formbg.gif, and transrace.png. So, next we need to copy those images into the racetrack/web-app/images directory.
racetrack> ls -1 web-app/images/ banner.jpg bg.gif formbg.gif grails_logo.jpg spinner.gif transrace.png tree
Now that we have those items taken care of, let’s take a moment to discuss layouts. Did you notice that none of the templates we’ve worked with in this application made any mention of a stylesheet? Did you notice that none of those templates referenced the Grails logo that we see on every page? If the templates don’t include that information, then why do we clearly see the logo and the effects of a stylesheet when the pages are rendered in the browser? The answer lies in a single tag included in each of the templates.
... <head> <meta http- <meta name="layout" content="main" /> <title>Some Title</title> </head> ...
This tag tells Grails to render the template using the layout named main. Grails then expects to find the layout template – main.gsp – in the application’s global layout directory – racetrack/grails-app/views/layouts. We use a layout to define the general structure we want to apply to a site (or a subset of the pages in a site), and we refer to that layout from the templates that wish to use it (either explicitly using the meta tag or by convention30). The template then concerns itself only with its specific content (e.g., a list of races), knowing that the layout will provide the framing around the page (e.g., the logo,
92 | GETTING STARTED WITH GRAILS common menus and links, etc.) as well as other items commonly needed by multiple templates (e.g., the stylesheet, common JavaScript functions, etc.). Not only do layouts keep our application DRY, they also provide a one-stop shop for significantly rearranging the structure of our pages. For example, suppose we’ve defined the application’s common menus as a series of horizontal tabs across the top of the page. Now, assume we later decide that the menu should instead appear as a vertical list along the left side of the page. If the layout contains the menu-rendering logic (as opposed to having the menu-rendering logic embedded separately in each template), we can change the layout and quickly see that change reflected across all pages that use the layout. All of our application’s pages currently use the default Grails layout template. Let’s define a new custom layout for the public portion of the site. Create a new layout template at racetrack/grails-app/views/layouts/public.gsp and give it the following content.
<html> <head> <title><g:layoutTitle </title> <link rel="stylesheet" href="${createLinkTo(dir:'css',file:'public.css')}"> </link> <g:layoutHead /> </head> <body> <table class="contentArea"> <tr> <td> <div class="logo"></div> <g:layoutBody /> </td> </tr> </table> </body> </html>
We can see that this layout references our new stylesheet. Also, look closely at the <g:layoutTitle>, <g:layoutHead>, and <g:layoutBody> tags. These tags serve as placeholders for the
NOT JUST FOR INTRANET APPS | 93 actual page content. At runtime, these tags pull in the corresponding content from the template that’s using the layout. For example, when we change search.gsp to use this layout, at runtime Grails will render the content of the <body> tag in seach.gsp in place of the <g:layoutBody> tag in the layout template. (By the way, it’s no coincidence that these tags bear a resemblance to the decorator tags in SiteMesh. In fact, Grails delegates this work to SiteMesh behind the scenes.) Now that we public pages search.gsp, the tag that public.gsp. have our new layout, the last step is to update the to reference it instead of the default layout. In searchresults.gsp, and register.gsp, locate defines the layout, and change it to reference
<meta name="layout" content="public" />
And with that done, we’re ready to reveal the new face of our application.
And there we have it, Folks. We’ve developed an application that our customers are happy with, and they’re ready for us to
94 | GETTING STARTED WITH GRAILS push it into production! (Before we move on, you may have noticed that we have an opportunity to make our application a bit more DRY here. For extra credit, if we were to remove the adminmenbar reference from the three public page templates and place it instead in the layout template, then we could reduce some duplication in these pages. Are you up to the job?)
Free Online Version.
Support this work, buy the print copy:
There’s no time for testing in rapid application development, right? Wrong! Remember the last time you used an application just because it was developed quickly? Of course not. We gravitate towards applications that work well and make us more productive, and we wish tax audits and root canals on those pitiful souls that try to force their buggy software on us. So, shame on us for waiting this long to talk about testing. (OK. I’ll take the blame this time. You were just an innocent bystander.)
Putting It to the Test
7
Grails conveniently offers built-in support for unit testing. In fact, it might even make us feel a bit guilty for not testing. If we have a look in racetrack/grails-tests, we see that Grails has already created test classes for each of our domain models. The guilt is sure to set in when we look inside one of these classes, and we’re quickly reminded that we have a whopping 0% test coverage so far.
class RaceTests extends GroovyTestCase { void testSomething() { } }
Unit Testing
It’s time to fix that. (If you’re new to writing unit tests in Groovy31, you’re in for a treat. Be careful. Once you try it, you may never want to go back.) First, let’s decide what we need to test. The RaceTests class is where we’ll include all the unit tests for the Race domain class. (We’ll discuss the appropriate
95
96 | GETTING STARTED WITH GRAILS place for testing the controllers momentarily.) The Race class is fairly straightforward, but it does include more than just simple properties. Recall that we added several constraints to the class, and we even defined a custom constraint.
static constraints = { name(maxLength:50,blank:false) startDateTime(validator: {return (it > new Date())}) city(maxLength:30,blank:false) state(inList:["GA", "NC", "SC", "VA"],blank:false) distance(min:3.1f,max:100f) cost(min:0f,max:999.99f) }
I find it’s useful to include test cases for the constraints. Even if you think you can look at the definition of the constraint and see that it’s configured correctly, it’s often valuable to actually write a few test cases to verify that those pesky edge cases are accounted for. Consider, for example, the custom constraint above for the startDateTime property. What happens if the date is null for some reason? (Is null greater than new Date()?) Well, we don’t want any of our races to have a null starting date/time, so we should verify that the constraint will catch null values for us.
void testSomething() { def race = new Race() race.startDateTime = null assertFalse(race.validate()) def fieldError = race.errors.getFieldError('startDateTime') def validationError = fieldError.codes.find { it == 'race.startDateTime.validator.invalid' } assertNotNull(validationError) }
This test case creates a Race object with a null startDateTime property, asserts that the object validation fails, and then verifies that the errors include the expected error code for an invalid startDateTime property. Then, to run all test cases for our application, we simply enter grails test-app at the command prompt, and watch for the results.
PUTTING IT TO THE TEST | 97
racetrack> grails test-app ... [echo] Running tests for environment: test ... [java] OK (3 tests) ... BUILD SUCCESSFUL Total time: 11 seconds
Whew! We can rest a bit easier now knowing that we’re adequately protected against null values in startDateTime property, but what about the other possible scenarios for our custom validator? Let’s boost our confidence a bit more by including those test cases as well. (If you’re wondering why Grails reported that 3 tests completed successfully, note that we have still have two embarrassingly bare test classes for our other domain classes. Those test cases – not surprisingly – passed as well.) Let’s add a test to make sure we also get a validation error when we specify a startDateTime property with a date/time value in the past. And, just as important as making sure we get errors for valid data, we also want to make sure we don’t get any errors for a fully-valid Race object. If you want to get some extra assurance about the other constraints, you can include test cases for them as well. And, with a little bit of refactoring from our first test case, we can now quickly add new test cases for all sorts of scenarios.
class RaceTests extends GroovyTestCase { void testStartDateTimeCustomConstraintWithNullValue() { def race = getValidRace() race.startDateTime = null assertValidationError(race, 'startDateTime', 'race.startDateTime.validator.invalid') } void testStartDateTimeCustomConstraintWithPastValue(){ def race = getValidRace() race.startDateTime = new Date(0) assertValidationError(race, 'startDateTime', 'race.startDateTime.validator.invalid') } void testNameMaxConstraint() { def race = getValidRace()
98 | GETTING STARTED WITH GRAILS
race.name = 'It may very well take longer to' + ' typeout the name of this race' + ' than to just go run it.' assertValidationError(race, 'name', 'race.name.maxLength.exceeded') } //... private Race getValidRace() { def race = new Race() race.name = 'Fast 5K' // 1 day in the future race.startDateTime = new Date().plus(1) race.city = 'Somewhere' race.state = 'NC' race.distance = 3.1 race.cost = 20.00 race.maxRunners = 1000 // Make sure that we have indeed constructed a // valid Race object assertTrue(race.validate()) return race } private assertValidationError(race, fieldName, errorName) { assertFalse(race.validate()) def fieldError = race.errors.getFieldError(fieldName) def validationError = fieldError.codes.find { it == errorName } assertNotNull(validationError) } }
And once we’re happy with the test coverage, it’s time to see whether our constraints are as bulletproof as we hope they are.
racetrack> grails test-app ... [echo] Running tests for environment: test ... [java] OK (19 tests) ... BUILD SUCCESSFUL Total time: 12 seconds
Of course, you can add test cases for functionality other than just constraints. If you have any tricky relationships or other
PUTTING IT TO THE TEST | 99 persistence-related features, you may want to include test cases to cover those areas as well. Before testing any database-related functionality, you’ll first want to configure your test data source to point to your test database. Grails will allow you to run the tests using any data source you prefer32; however, you typically want a dedicated database where your tests have free reign over all data, without impacting development or (of course) production. In this case, we’d update racetrack/grailsapp/conf/TestDataSource.groovy as follows. (Note that you’d need to change the username and password to the appropriate values for your MySQL account.)
class TestDataSource { boolean pooling = true String dbCreate = "update" String url = "jdbc:mysql://localhost/racetrack_test" String driverClassName = "com.mysql.jdbc.Driver" String username = "jason" String password = "" }
As you may have noticed from the output of the grails testapp command, Grails uses the test data source by default. If you’d like to run the tests against an alternate data source, simply include the environment name (i.e. dev, test, or prod) in the command.
racetrack> grails dev test-app ... [echo] Running tests for environment: development ... [java] OK (19 tests) ... BUILD SUCCESSFUL Total time: 10 seconds
Functional Testing
For those seeking even more confidence in their application’s robustness, Grails also includes support for functional testing. Canoo WebTest provides the framework for the functional tests, and you can use your test cases to validate the application
100 | GETTING STARTED WITH GRAILS behavior as the end users will see it. The test cases can navigate to various URLs, click on buttons, follow links, verify page content, etc. If you’re interested in adding functional tests to your application (or just seeing how they work), the online documentation includes a tutorial that walks you through generating a functional test, customizing the test to your needs, running the tests, and viewing the resulting test reports.33
Free Online Version.
Support this work, buy the print copy:
We’ve completed this round of development. The application is working and our customers like what they see; however, they’re not going to run the application off of our development system, so we still have some work to do. Let’s get the application into production, and call it a day.
The Finish Line
8
Once the application is in production, we’ll likely want a way to monitor various aspects of the application’s activity. We may want to gather statistics about how people are using the system, capture certain data for help in potential debugging scenarios, etc. Grails has built-in logging – using log4j – to help meet these needs. Each Grails controller includes a dynamic log method that provides access to the standard log4j functionality.34 Each application also includes a log4j.properties file for use in customizing the log output. It’s always a good idea to keep track of any unauthorized users trying to gain access to an application, so let’s add some logging to monitor that activity. In the UserController class, the login action validates the given user ID and password against the table of authorized users. If we detect an invalid user ID and password combination, we want to log a warning and include the details of the attempted breach.
def login = { if (request.method == "GET") {
Logging
101
102 | GETTING STARTED WITH GRAILS
session.userId = null def user = new User() } else { def user = User.findByUserIdAndPassword(params.userId, params.password) if (user) { session.userId = user.userId def redirectParams = session.originalRequestParams ? session.originalRequestParams : [controller:'race'] redirect(redirectParams) } else { log.warn "Shields up! Somebody's trying " + "to hack through our rock-solid " + "DEFCON 1 security -- " + "User ID - $params.userId, " + "Password - $params.password" flash['message'] = 'Please enter a valid user'+ 'ID and password' } } }
By default, Grails only logs errors, and all logging output goes to the console. Of course, in production we’d rather have this information written to a file or perhaps even e-mailed to the administrator. Log4j offers appenders for all sorts of logging destinations35, but for our purposes, we’ll record this output to a file. Much like the separate data sources used for each environment, Grails also provides environment-specific logging configurations. Since we’re preparing for production, we’ll add our customizations to the production configuration. Open
racetrack/web-app/WEBINF/log4j.production.properties
configuration entries.
and add the following
log4j.appender.access=org.apache.log4j.FileAppender log4j.appender.access.file=access.log log4j.appender.access.layout=org.apache.log4j.PatternLayout log4j.appender.access.layout.ConversionPattern=%d %p %x [%c] %m%n log4j.logger.UserController=warn,access log4j.additivity.UserController=false
THE FINISH LINE | 103 This configuration first defines a new log4j appender that will write to a file named access.log. It then instructs log4j to use that file to record all warning level (or higher) events from the UserController class. (This configuration writes the log file to the application’s root directory. In a production environment, you’ll want to have a directory dedicated exclusively to your log files and configure your log4j settings accordingly.) To try it out, enter grails prod run-app (to run with the production configuration) and navigate to (or any secured area of the application) and enter a bogus user ID and/or password. You should see the following output in racetrack/access.log.
2006-10-28 16:25:29,239 WARN [UserController] Shields up! Somebody's trying to hack through our rock-solid DEFCON 1 security -- User ID - hacker, Password - letmein
Now, when some nefarious fiend tries to break in to our application, we’ll have a handy record of their activity.
Deploying
It’s time to deploy our project to a production application server, and we’ll do so in just three short steps. First, we need to tell our production application how to communicate with the production database. Let’s update
racetrack/grailsapp/conf/ProductionDataSource.groovy
with the necessary configuration data. (Note that you’ll need to change the username and password to the appropriate values for your MySQL account.)
class ProductionDataSource { boolean pooling = true String dbCreate = "update" String url = "jdbc:mysql://localhost/racetrack_prod" String driverClassName = "com.mysql.jdbc.Driver" String username = "prod" String password = "wahoowa" }
104 | GETTING STARTED WITH GRAILS Once the application is configured to use the production database, we’re ready to build the WAR. To do, so, we simply enter grails war, and Grails takes care of the rest.
racetrack> grails war ... war: [echo] Packaging for environment 'production' ... BUILD SUCCESSFUL Total time: 6 seconds racetrack> ls -l racetrack.war -rw-r--r-1 jason jason 11760541 Oct 28 17:02 racetrack.war
Notice the output above that indicates the application is being built for the production environment. That is certainly the behavior we want in this particular situation, but there may be times when you want to build a WAR to deploy in a development or test environment as well. By default, the grails war command prepares the application using the production database configuration (in ProductionDataSource.groovy); however, we can simply include the target environment in the command (e.g., grails dev war) to produce a WAR using the configuration for that environment instead.32 Now that we have a WAR, we’re free to deploy the application on any application server we choose. The exact steps needed to deploy the WAR will, of course, vary across application servers. We’ll use the freely available JBoss Application Server36 as the target server for this example. With JBoss, we simply copy the WAR into the server’s deployment directory, and start the server.
racetrack> cp racetrack.war /Applications/jboss4.0.5/server/default/deploy/ racetrack> /Applications/jboss-4.0.5/bin/run.sh 22:23:50,934 INFO [Server] Starting JBoss (MX MicroKernel)... ... 22:24:13,069 INFO [TomcatDeployer] deploy, ctxPath=/racetrack, warUrl=.../tmp/deploy/tmp7718racetrack-exp.war/
THE FINISH LINE | 105
... 22:24:35,671 INFO [Server] JBoss (MX MicroKernel) [4.0.5] Started in 24s:726ms
That’s it. The application is now deployed, started, and ready to process requests. Fire up your browser and have a look –. Every application server has its quirks, and JBoss is no exception. If we want the application to log events properly when running in JBoss (in the same manner we established earlier), we have to jump through a few hoops. JBoss adopts the philosophy that the application server (not the application itself) should own the logging configuration. The following steps will bring us in line with that way of thinking. 1. Remove the log4j-related artifacts from the WAR (so that we can use the corresponding JBoss log4j artifacts instead). • • 2. WEB-INF/log4j.properties WEB-INF/lib/log4j-1.2.8.jar
App Server Quirks
$JBOSS_HOME/server/default/conf/log4j.xml
– to include the logging configuration for our application.
Edit the JBoss log4j configuration file –
<appender name="RACETRACK" class="org.jboss.logging.appender.DailyRollingFileAppender"> <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/> <param name="File" value="${jboss.server.log.dir}/racetrack.log"/> <param name="Append" value="false"/> <!-- Rollover at midnight each day --> <param name="DatePattern" value="'.'yyyy-MM-dd"/> <layout class="org.apache.log4j.PatternLayout"> <!-- The default pattern: Date Priority [Category] Message\n --> <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/> </layout> </appender>
106 | GETTING STARTED WITH GRAILS
<category name="UserController"> <priority value="WARN" /> <appender-ref </category>
Once these changes are in place, we can once again use the log file to keep track of any noteworthy events.
racetrack> cat /Applications/jboss4.0.5/server/default/log/racetrack.log 2006-10-28 22:40:09,174 WARN [UserController] Shields up! Somebody's trying to hack through our rock-solid DEFCON 1 security -- User ID - admin, Password - letmein
Free Online Version.
Support this work, buy the print copy:
Every project is unique, and your needs are sure to differ in some way or another from the examples we’ve seen so far. The following sections cover some of the more common deviations as well as tips for dealing with the corresponding questions that arise. We’ll also look at a few generally useful tips for moving forward with Grails.
Tips and Tricks for Moving Forward
9
The approach we used in the RaceTrack example helped us quickly assemble our application, but we sometimes want a bit more control over certain details of our database tables (e.g., column sizes, constraints, partitions, etc.). We don’t have to let Grails create the database tables for us. Grails will happily use a schema we define manually, and no additional configuration is necessary, so long as we follow the Grails naming conventions. (If we really want to color outside of the lines, we’ll talk about integrating with non-conforming schemas in the next section.)
Defining Your Own Database Tables
To tell Grails we want to manage the database tables on our own, simply remove (or comment out) the dbcreate property in the *DataSource classes and read on below for more information on the Grails conventions.
class DevelopmentDataSource { boolean pooling = true String dbCreate = "update" String url = "jdbc:mysql://localhost/racetrack_dev" String driverClassName = "com.mysql.jdbc.Driver" String username = "jason" String password = "" }
107
108 | GETTING STARTED WITH GRAILS
Domain Classes and Table Names
First and foremost, the Grails conventions expect that you’ll have a table for each domain class. As we saw in the RaceTrack application, the Race domain class mapped to the race table, the Registration domain class used the registration table, and so on. If you define your tables and domain classes using this pattern, Grails will let you skip any configuration work in this area. (If your domain classes happen to involve an inheritance hierarchy, then you’ll want to check out the Grails wiki for more information on the Grails table-per-hierarchy model.37)
Properties and Columns
Intuitively enough, Grails looks for a one-to-one mapping between domain class properties and database columns. For single-word properties, the property name will exactly match the column name. For example, the name property in the Race class mapped to the name column in the race table. For multi-word properties, Java naming conventions dictate the property name, and Grails conventions call for an underscore to separate each word in the column name. For example, the startDateTime property mapped to the start_date_time column. We have some flexibility when it comes to the specific data types and sizes used for a column. For example, we can map a String object to a CHAR(4) column, a VARCHAR(255) column, a TEXT column, etc. We have similar leeway with numeric types. Of course, as the developer, we’re responsible for defining proper constraints to make sure the domain class doesn’t attempt to save data that cannot be successfully persisted to the database. Lastly, we have the option of specifying which columns are nullable. We’re free to be as restrictive or liberal as we please in this regard; we simply have to make sure our domain class constraints will prevent the application from trying to persist a null property value into a non-nullable database column.
TIPS AND TRICKS FOR MOVING FORWARD | 109 GORM supplies each Grails domain class with an id and version property, and Grails expects each table to have columns of the same name. Both columns should be defined as integer types, and the id column should serve as the primary key for the table. (The exact type and size of the integer column used is at the developer’s discretion. Just be sure to choose a size large enough to support the amount of data and activity you expect for your system.) Grails follows an equally intuitive approach for handling relationships. For example, in the RaceTrack application, each Registration object belonged to a particular Race object. Grails therefore expects the registration table to include a race_id column, which acts as a foreign key to the race table.
Identity, Relationships, and Keys
Without a doubt, you’ll get the maximum productivity benefit from Grails when working with a greenfield application where you can follow the Grails conventions. After all, one of the core premises behind Grails is a strong favoring of convention over configuration. Nevertheless, many applications will not have the luxury of defining a new database schema. Particularly in enterprise applications, we often find ourselves integrating with a legacy database schema, and changing the schema typically isn’t an option. Luckily, Grails doesn’t leave us out in the cold. Even with our legacy schema, we can still benefit from much of the Grails goodness we saw in the RaceTrack application. To use Grails with a non-conforming schema, we have to revert to configuration. We need to tell Grails how to map our domain classes to our tables, how to map properties to columns, and how to uniquely identify each record. Fortunately, we have a few options for performing this mapping. For those privileged enough to have option of using Java 5, you can use Hibernate annotations to provide the mapping.38 For the JDK 1.4 crowd, you’ll want to use the equally-viable Hibernate XML for the mapping.39
Working with a Legacy Database Schema
110 | GETTING STARTED WITH GRAILS
ORM Troubleshooting
If you do find yourself working with a legacy schema or even if you just get into some complex relationships or queries, you may occasionally find that your application is not providing the exact results that you’re expecting. In this case, it’s a good idea to make sure that the object-relational mapping is doing what you expect under the hood. To do so, you can enable SQL logging by setting the logSql property to true in your data source.
class DevelopmentDataSource { def logSql = true boolean pooling = true String dbCreate = "update" // one of 'create', 'create-drop', 'update' String url = "jdbc:mysql://localhost/racetrack_dev" String driverClassName = "com.mysql.jdbc.Driver" String username = "jason" String password = "" }
With SQL logging enabled, you’ll now be able to see the format of the SQL the system is generating. For example, if we perform a query from the Search for Races page, we’ll see the following output in the console.
[groovy] Hibernate: [groovy] select [groovy] this_.id as id1_0_, [groovy] this_.version as version1_0_, [groovy] this_.distance as distance1_0_, [groovy] this_.max_runners as max4_1_0_, [groovy] this_.start_date_time as start5_1_0_, [groovy] this_.state as state1_0_, [groovy] this_.cost as cost1_0_, [groovy] this_.name as name1_0_, [groovy] this_.city as city1_0_ [groovy] from [groovy] race this_ [groovy] where [groovy] ( [groovy] this_.city like ? [groovy] and this_.state like ? [groovy] and this_.start_date_time between ? and ? [groovy] )
All database activity – create, read, update, and delete – will now appear in the console. If you’re trying to figure out why a certain property doesn’t seem to load properly or why a
TIPS AND TRICKS FOR MOVING FORWARD | 111 particular query appears to ignore some of its parameters, the SQL logging output is a good place to begin your debugging effort. Because you know what you’ve asked the application to do, seeing the application’s translation of that request into SQL will often provide that missing piece of information needed to help you address the problem.
Upgrading Grails
The Grails development team has established an aggressive road map for the framework.40 We can expect regular improvements delivered in the form of minor releases every couple months, and we’ll often want to upgrade our Grails applications to take advantage of the new features available in the latest release. With Grails, this too, is a simple process. As a general precaution, you’ll always want to make sure you have a backup of your application before you perform the upgrade. (Of course, having reliable backups isn’t specific to this process. You are using a source code management system, right?) Naturally, you first need to download and install the updated version of Grails. Then, you simply navigate to your project’s root directory and issue the grails upgrade command.
racetrack> grails upgrade ... BUILD SUCCESSFUL Total time: 1 second
Congratulations, you’re now running the latest version of Grails. Now go do something great with all those new features!
Free Online Version.
Support this work, buy the print copy:
10
Over the course of this book, we’ve seen first-hand how we can use Grails to build a fully-functioning and flexible web application in minimal time. Groovy’s highly-expressive nature allowed us to write concise code, and Grails’s use of sensible defaults (à la convention over configuration) saved us from much of the coding and configuration we’d otherwise face with many traditional frameworks. Of course, writing less code also means that we have less code to maintain going forward. And, as the requirements continue to evolve over time, we’ll have fewer lines of code to wade through to get our job done.
Summary
We’ve followed a very iterative – perhaps even agile – development approach to get to this point, and we’ve seen that Grails is well-suited to that development style.41 That approach allows us to continuously see our progress as we develop the application and, in turn, opens the door to quicker feedback from our customers. We may not have made it to the golf course by 10 a.m., but a happy customer might just take us out for a round tomorrow. And there’s still more to Grails than what we’ve seen here. The Grails home page () always has the latest news and updates. If you want to dig deeper and learn about Grails services, Ajax support (including the Prototype, Dojo, and Yahoo UI libraries), job scheduling, transaction management, JEE integration, etc., you’ll find all that information and more on the Grails site as well. And, if for some reason you can’t find what you’re looking for, be sure to send a note to the increasingly-active user mailing list.42 113
114 | GETTING STARTED WITH GRAILS Web development doesn’t have to be a slow and cumbersome process; with Grails, rapid web application development on the Java platform has now arrived.
Jason Rudolph is an Application Architect at Railinc, where he develops software to help trains move more efficiently throughout North America. He recently delivered an industrywide inspection reporting and management system relied on for operational safety by Fortune 500 railroads, equipment leasing companies, and the Federal Railroad Administration. Jason specializes in applying sound software engineering practices to solve hard problems and meet real business challenges. Jason has experience building several large-scale enterprise applications using JEE to interface with business partners, legacy back-end systems, and web-based users, and to provide scalable solutions for high transactional throughput. He enjoys working as a designer, an architect, and a developer, and believes that the real satisfaction comes from the hands-on coding that turns the blueprints into a working and useful application. Jason' interests include dynamic languages, lightweight s development methodologies, improving developer productivity, and a quest to keep programming fun. It’s these interests that led Jason to become a Grails committer and evangelist..
About the Author
115
Resources
1 Check out the official details of the Groovy spec (i.e., JSR 241: The Groovy Programming Language). The Groovy site is your official source for all things Groovy. Here you’ll find information on downloading and installing Groovy, tutorials, APIs, FAQs, documentation, news, and more.
2 This ZIP file includes the complete source code for all the examples in this book, with each folder containing a snapshot of the source as it exists at the end of a particular chapter.
4
3 Sun’s Java Standard Edition download page offers JDK distributions for just about every platform under the sun. The Grails download page always offers the current stable Grails release as well as a snapshot of the upcoming release. The examples in this book should work fine with future Grails releases; however, for best results, I recommend using one of the Grails 0.3.1 distributions below for developing the examples as you read along.
5
6 The Grails installation instructions will have you up and running in no time.
7
117
118 | GETTING STARTED WITH GRAILS
Download and install MySQL Community Server 5.0 for all your development needs. You can’t beat the price!
8 The Grails Quick Start guide provides the official word on the structure of a Grails application. This Wikipedia entry explains the essence of the DRY principle.
10
9 The GORM documentation lists a quick summary of the various relationship types supported in Grails and the keywords associated with each type.
11 MySQL Connector/J provides the JDBC drivers needed to interact with your MySQL databases from a Grails application (or any Java or Groovy application).
12 As you start to add constraints to your Grails application, be sure to bookmark this page. The Grails Validation Reference guide lists all of the available constraints, explains their usage, and provides the information you need for customizing error messages as well.
13 The Groovy site’s introduction to closures provides a detailed and helpful explanation of the purpose, syntax, and semantics of Groovy closures. It includes several handy examples, and even touches on the differences between closures, code blocks, and anonymous inner classes. Groovy Markup provides a convenient mechanism for using Groovy to build XML, HTML, Hibernate Criteria, etc. This section of the Grails documentation explains how to define a constraints closure and how to use the validate and save methods on Grails domain classes. In addition to the many standard Grails validators, the Grails Validation Reference guide also describes how to define and use custom validators.
14
15
16
RESOURCES | 119
17 The Groovy GString API lists the many handy methods provided by this class, some examples of its use, and a quick mention of how it got its rather clever name. Grails offers two options for setting the default action on a controller.
18
19 Grails controllers offer numerous dynamic methods and properties for everything from accessing the request and the session, to logging, to implementing a redirect, and everything in between.
20 Not to be outdone by Grails controllers, Grails domain classes provide dynamic properties and methods that are sure to save you hours of burdensome ORM work. The GSP Tag Reference guide identifies the various Grails tags available for working with forms, validation, Ajax, etc. For each tag, the documentation explains the tag’s API and offers examples of its use. The datePicker tag renders a UI widget for selecting a date/time value and offers options for controlling the precision of the value.
23 22 21 The Hibernate Criteria Builder provides a convenient mechanism for performing all sorts of queries on your domain model.
24 The true computer science geeks will no doubt have fond memories of developing expressions in Polish notation. Just don’t try to communicate with mortals using this syntax. The Groovy roadmap gives us an idea of what we can expect in future Groovy releases, including support for enumerations in Groovy 2.0.
25
26
120 | GETTING STARTED WITH GRAILS
Wikipedia offers a thorough explanation of the Secure Hash Algorithm (SHA), its various flavors, and why it can serve as a good choice for most encryption needs.
27 If you’re ready to lock down your application and you’re rolling your own authentication module, then check out Java’s MessageDigest API for its one-way hashing functions.
28 The Grails documentation includes an explanation of the bootstrap functionality for defining application start-up and tear-down tasks.
29 Grails action interceptors allow you to inject additional code to execute before or after a Grails action.
30 As an alternative to referencing layouts by name (as demonstrated in the RaceTrack example), Grails also allows you to use a convention-based approach to determining the layout associated with a given view. Groovy notably simplifies unit testing on the Java platform. The Groovy Unit Testing page includes just a few examples of how Groovy can help speed up your test case development.
32 31 Grails allows you to specify the environment you want to use for various commands and includes logical defaults for each command as well. In addition to the unit testing framework, the Grails functional testing framework will help you further maintain the quality of your application as you aggressively progress through your development iterations.
34
33 Find out how to access and customize the logging functionality available in Grails controllers.
35
RESOURCES | 121
Because Grails logging uses log4j, you can take advantage of log4j’s superb flexibility to tailor the logging functionality to your specific needs. Download and install JBoss Application Server for a free and productioncapable deployment solution.
37 36 The GORM documentation explains how domain class inheritance affects ORM.
38 Hibernate annotations allow developers to use Grails for their applications even when working with a non-standard database schema.
39 If your environment doesn’t yet support annotations (i.e., you’re using JDK 1.4), you can still hook Grails up to your legacy database schemas using Hibernate XML for the mapping.
40 The Grails roadmap lays out the many features and improvements you can expect in each upcoming release and provides an estimated timeline for those releases as well.
41 Craig Larman' book, Agile and Iterative Development: A Manager' Guide, s s serves as a great introduction to Agile Development.
42 The Grails user mailing list archives are fully-searchable and provide a great source for answers to all sorts of questions. You can also feel free to post your own questions or comments to the mailing list, and chances are, you’ll receive a fairly timely reply. | https://www.scribd.com/doc/11598/Getting-Started-with-Grails | CC-MAIN-2018-51 | refinedweb | 23,015 | 55.03 |
Advertise Jobs
Perl
module
-
Part of CPAN
distribution
Inline-Tcl 0.09.
Inline::Tcl - Write Perl subroutines in Tcl.
use Inline Tcl => <<END;
set asdf 2
proc dummy { val } {
puts "Dummy says \$::asdf + \$val = [expr \$::asdf + \$val]"
incr val
return [expr \$::asdf + \$val]
}
END
$result = dummy(1);
print "But returned $result\n";
The output from this program is:
Dummy says 2 + 1 = 3
But returned 4
The.
Inline::Tcl
The process of interrogating the Tcl interpreter for globals only
occurs the first time you run your Tcl code. The namespace is
cached, and subsequent calls use the cached version.
Inline::Tcl is based primarily on the Inline::Python module.
Inline::Python
This section will explain the different ways to use Inline::Tcl.
use
The most basic form for using Inline::Tcl is:
use Inline Tcl => 'Tcl source code';
Of course, you can use Perl's "here document" style of quoting to make
the code slightly easier to read:
use Inline Tcl => <<'END';
Tcl source code goes here.
END
The source code can also be specified as a filename, a subroutine
reference (sub routine should return source code), or an array
reference (array contains lines of source code). This information
is detailed in 'perldoc Inline'.
This is an ALPHA release of Inline::Tcl. Further testing and
expanded support for other operating systems and platforms will be a
focus for future releases. It will probably only run on linux. If it
works for you, let me know.
For information about using Inline, see Inline.
Inline
For information about other Inline languages, see Inline-Support.
Inline::Tcl.
Ryan Sadler <RRS@cpan.org>
Brian Ingerson <INGY@cpan.org> is the author of Inline, Inline::C and
Inline::CPR. Neil Watkiss <NEILW@cpan.org> is the author of
Inline::Python.
All Rights Reserved. This module is free software. It may be used,
redistributed and/or modified under the terms of the Perl Artistic
License.
(see) | http://aspn.activestate.com/ASPN/CodeDoc/Inline-Tcl/Tcl.html | crawl-002 | refinedweb | 320 | 67.45 |
Decoupling Express JavaScript Routes from Your Main Application File
No ads, no tracking, and no data collection. Enjoy this article? Buy us a ☕.
Express is a great web framework for Node.JS applications, and it provides exactly the type of model/view/controller (MVP) architecture that you would expect from a modern web application. With a traditional Express applications, routes are defined directly in the entry point of your application (the main file that starts your application server), but as applications grow, the logic in that file continues to balloon. Some of this logic is application and server setup code, while the rest tends to be route functions: An application with many routes, ends up being an application with a very large main file clogged by those same routes.
It stands to reason that you may want to abstract or decouple this logic a little further. The "C" in MVC stands for "controller" after all, and we've technically been throwing that "C" into the main application entry point for convenience.
Typically, we can clean this up by using a separate route file. For this example, let's assume
route.ts is that file. Your route file could look something like this:
This example code is written in TypeScript, but it'll work just fine with JavaScript in absence of typings. Just be sure to follow the syntax you're accustomed to.
import { indexGetAction } from './controller/indexActions'; import { exampleListAction, exampleFormAction, exampleDeleteAction } from './controller/exampleActions'; export const routes = [ { path: '/', method: 'get', action: indexGetAction }, { path: '/Example/List', //List of Example Entries method: 'get', action: exampleListAction }, { path: '/Example/Form', //New or Edit Example method: 'get', action: exampleFormAction }, { path: '/Example/Form', //Submit Example method: 'post', action: exampleFormAction }, { path: '/Example/Delete', //Remove an Example method: 'get', action: exampleDeleteAction } ];
You can see that this is just an array of objects that contain the route path, the method (
GET or
POST for standard web applications), and the function name to pass the Express request and response to. We'll get to these actions in a bit, but note that I'm pulling them from files in a "controller" folder in the application.
Now we can wipe out all of the routes in the
index.ts file (or
app.ts depending on what your entry point file is named), and instead, loop through the routes dynamically.
At the top, we'll need to import our routes:
import { routes } from './routes.ts';
Then we can perform the aforementioned loop:
routes.forEach((route: any): void => { app[route.method](route.path, (req: express.Request, res: express.Response, next: Function): void => { route.action(req, res) .then((): any => next) .catch((err: any): any => next(err)); }); });
There isn't a whole lot to say about this piece of code. We're simply looping over the routes, and doing what would have normally been an
app.get() or
app.post(), except we're dynamically determining which method to call based on the HTTP method specified in the routes. We're then calling the action that we specified in the route file and passing in the Express request and response objects that you would expect.
What about the controller file? Let's take a look:
export async function indexGetAction(req: express.Request, res: express.Response): Promise<any> { res.render('index'); }
I'm purposely using the index page here without any real code--just a straight render--so that you can focus on the function itself. There is no real difference between this external function and the anonymous function that you would have if you did this in the main entry point:
app.get('/', async (req: express.Request, res: express.Response): Promise<any> => { res.render('index'); });
The difference is that I took that anonymous function and externalized it into a controller file in order to decouple the logic from the main entry point, and better clean up the code. | https://codepunk.io/decoupling-express-javascript-routes-from-your-main-application-file/ | CC-MAIN-2021-31 | refinedweb | 642 | 57.57 |
Problem with changing language while using language base in SEO urls
Splash › Forums › PrettyFaces Users › Problem with changing language while using language base in SEO urls
Tagged: i18n, language base, SEO, URL
This topic contains 7 replies, has 3 voices, and was last updated by
xmapact 3 years, 1 month ago.
- AuthorPosts
Hello,
First of all I want to say thank’s for such a handy instrument that you provide. Everything was pretty nice and intuitive until the day I got a request to add language code base to all web-site URLs. E.g:
-
-
As I learned from documentation I added
langparameter to all my
<h:link>tags.
And added such rules to my pretty-config.xml:
<url-mapping <pattern value="/#{ lang : localeChanger.language }/" /> </url-mapping> <url-mapping <pattern value="/" /> <view-id </url-mapping> <url-mapping <pattern value="/login" /> <view-id </url-mapping>
Problem is that I can pass language code to managed bean
@ManagedBean (name = "localeChanger")but I can’t get current language code from it. So after deployment I see not I manually enter URL with language code – locale changes without problems.
My second attempt was to use more primitive config, which works nice for me until I try to switch language with my
<h:commandLink>. Than it looks like it switches to needed language and immediately back =) Here is my second config variant:
<url-mapping <pattern value="/#{ lang : localeChanger.language }/" /> <view-id </url-mapping> <url-mapping <pattern value="/#{ lang : localeChanger.language }/login" /> <view-id </url-mapping>
Everything works fine, but languages switch.
Here is my @ManagedBean that controls i18n:
package com.example.managedbean; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import java.io.Serializable; import java.util.Locale; /** * * @author xmapact */ @ManagedBean(name = "localeChanger") @ViewScoped public class LocaleChangerBean implements Serializable { private String language = FacesContext.getCurrentInstance().getViewRoot().getLocale().getLanguage(); public String englishAction() { FacesContext.getCurrentInstance().getViewRoot().setLocale(Locale.ENGLISH); this.language = "en"; String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId(); if (viewId.equals("/productCat.xhtml") || viewId.equals("/productDetails.xhtml")) { return null; } else { return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true"; } } public String russianAction() { FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale("ru")); this.language = "ru"; String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId(); if (viewId.equals("/productCat.xhtml") || viewId.equals("/productDetails.xhtml")) { return null; } else { return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true"; } } public String ukrainianAction() { FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale("uk")); this.language = "uk"; String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId(); if (viewId.equals("/productCat.xhtml") || viewId.equals("/productDetails.xhtml")) { return null; } else { return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true"; } } public String getLanguage() { return this.language; } public void setLanguage(String language) { if (language.equals("ru")) { this.russianAction(); } else if (language.equals("uk")) { this.ukrainianAction(); } else { this.englishAction(); } } public Locale getLocale() { return new Locale(this.language); } public String getLinkClass(String lang) { String className = "inactive"; if (this.language.equals(lang)) { className = "active"; } return className; } }
Maybe the problem is that my
<h:commandLink>tags have a target that already includes language code?.
Here is a part of my template:
<div class="header_language"> <h:form> <ul class="header_lang" style="display: inline-block;"> <li> <h:commandLink EN </h:commandLink> </li> <li> <h:commandLink RU </h:commandLink> </li> <li> <h:commandLink UA </h:commandLink> </li> </ul> </h:form> </div>
Please help me to find a way to SEO + i18n + JSF + PrettyFaces paradise =)
Hey, let’s see if I can help.
First of all: the two pretty-config.xml variants you posted are equivalent, with one minor difference. If you specify a parent mapping, PrettyFaces will concatenate both patterns to a single one. In your example this leads to
/#{ lang : localeChanger.language }//login. The problem here is the
//. So I guess you should remove the trailing slash from the parent mapping to get the expected result.
Regarding your LocaleChangerBean I have a few comments:
(1) It’s weird that this bean is view scoped. As it manages the language parameter which is part of the current URL, it should be request scoped.
(2) The URL in your address bar will only change if you send a redirect from your action method (which is the “else” part of your code). So returning null doesn’t make any sense because the URL will be the same as before.
(3) If your bean returns something like
/someview.xhtml?faces-redirect=true, you will also have to set the language to the desired value for the outbound URL rewriting to work correctly. Something like
/someview.xhtml?lang=en&faces-redirect=true.
(4) I think it won’t work very good if you just change the language in the view root. Instead you should use
f:viewand use the
localeattribute to specify the locale you want to use for the view. You can simply reference your bean for that. See the example below.
(5) To send the correct redirect, it would be easier to return something like
pretty:someId. To redirect the current mapping you can use:
return "pretty:"+PrettyContext.getCurrentInstance().getCurrentMapping().getId();
So your class could look like this:
@ManagedBean(name = "localeChanger") @RequestScoped public class LocaleChangerBean implements Serializable { private String language = "en"; // the default language public String englishAction() { /* set the language to the new value */ this.language = "en"; /* either this way */ return "pretty:" + PrettyContext.getCurrentInstance().getCurrentMapping().getId(); /* or this way */ return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?lang=" + language + "&faces-redirect=true"; } public Locale getLocale() { return new Locale(language); } .... }
And use this in your view:
<f:view .... </f:view>
This way JSF will _always_ use the language that your LocaleChangerBean has. So you don’t need to change the locale in the view any more. Just change the property in your bean and redirect, so that the URL changes.
I hope this helps a bit. I think there are many ways to implement such a requirement. And that’s the way I would implement it. 🙂
Hello Christian,
Thank’s for your detailed answer. I tried to follow all your instructions and now I have code that works and shows language base. It also changes locale if URL contains right language code:…/...
So it is something that I wanted.
Now I’m using ordinary links to change my locales and they work just fine. Example:
<h:link> <f:param EN </h:link> <h:link> <f:param RU </h:link>
For some reason I have a problem with
jsf.jsaccessibility.
According to Chrome console error I get is:
GET 500 (OK)This GET request returns my custom error page.
My guess is that pretty filter blocks access to this file. (Maybe not 🙂 )
Is there a way to check this?
Thank’s a lot for your answers.
A 500 result code represents an internal server error. Mostly this happens because there is some kind of exception thrown during request processing. So you don’t see any errors in the logs?
Lincoln Baxter IIIKeymaster
Yeah, I have to agree with Christian. There is probably an internal server error occurring somewhere, so finding that will most likely show you what is wrong.
It *is* possible that you have some rules / mappings that are causing problems with this, but if all you’ve done is the i18n stuff, then it’s probably less likely.
Christian, Lincoln, thanks for your answers.
Fixed a problem with 500 error. There was a big mess with
viewParams. I was trying to use them from template but not from template client. And at the same time I was injecting values using PrettyFaces 0_o.
Now when I got it working fine with PrettyFaces disabled I’m trying to configure friendly URLs again.
What I have is this config:
<url-mapping <pattern value="/#{lang}" /> </url-mapping> <url-mapping <pattern value="/#{cat}" /> <view-id </url-mapping> <url-mapping <pattern value="/#{category}/#{OSG}" /> <view-id </url-mapping>
And I got problems with jsf.js access with this parameters. But it works just fine with this conf:
<url-mapping <pattern value="/anyTextHere/#{category}/#{OSG}" /> <view-id </url-mapping>
Problem is that I’m getting content of
/faces/productDetails.xhtmlinstead of
jsf.jsJavaScript. I’m sure that I’m doing something wrong because Google doesn’t help =) Maybe you have any idea how to solve this problem. I’ll provide any other information if it is needed.
Thank’s in advance,
Andrei.
Yeah, this happens because your mapping is matching the URL of JSF resources. The pattern for the
detailsmapping is
/#{lang}/#{category}/#{OSG}. And requests like
/javax.faces.resources/something/somefile.jsare matching this pattern and are therefore rewritten.
So common best practice to fix this issue is to restrict the regular expression for the path parameters. By default the pattern
[^/]+is used for path parameters which actually means “everything except /”. I guess restricting the pattern for the language parameter makes sense and should fix this issue. Something like this:
<url-mapping <pattern value="/#{ /[a-z]{2}/ lang }" /> </url-mapping>
See this page for details:
- AuthorPosts
You must be logged in to reply to this topic. | http://www.ocpsoft.org/support/topic/problem-with-changing-language-while-using-language-base-in-seo-urls/ | CC-MAIN-2016-50 | refinedweb | 1,482 | 59.7 |
If You Like It, Put an HTML5 UI on It
Okay, cheesy title I know, but it got your attention, right?
I'm guessing you're already thinking that in this post we're going to be discussing HTML5 User Interfaces.
Well, we are, but not quite in the context you might be expecting. Because this column tries to cater to general .NET-related things, dedicating an entire post specifically to HTML5 (even if it is being generated by C# and/or .NET code) doesn't do it justice.
There is, however, an area of HTML5 that often gets overlooked, but depending on your needs can actually be quite useful, and that's the subject of adding an HTML5 User Interface directly to your desktop applications, as Figure 1 shows:
Figure 1: The HTML5 interface
This is actually a regular Windows Forms application. You can tell this by the normal windows window furniture, and the two buttons in the top left corner. In the middle, however, we have a regular HTML5 page, styled and using the popular Twitter Bootstrap UI toolkit.
The question arises, however, why might we want to create a desktop application this way?
Desktop Applications, as Browsers...
It's not as silly as it might seem. There are still many users out there who have to use a PC in a normal office environment on a day-to-day basis.
In places like customer call centres, or tourist information kiosks, you often want to be able to control the web/browser access, and libraries or training and learning centres may have specialist requirements that mean an access card, or barcode, bluetooth key fob, and many other devices may be needed to allow a student to have access.
There are still many areas of the world where a person's only access to the Internet is via an Internet cafe (where they may have to pay for a time limit) or where government regulations mean that access to certain sites is denied or heavily monitored.
In situations like this, using a regular browser might not be desired. It might even be a case that the only application running on the machine is the custom browser you've written, meaning there's no desktop or settings or anything else for the user to interact with.
As a parent, you might want to wrap your child's Internet experience so you can be sure that they can only access certain sites. For example, not too long ago I was asked to write a custom browser that would scan incoming images and give them a "Nudity Score", reporting images that had a score of 50% or more to a given email address.
Lastly, there's the re-use argument too. If a company has several web-based products that they also need to supply as traditional desktop apps, it makes sense to reuse the user interface elements that existing users are familiar with where possible.
I'm Sold. So How Do I Do This, Then?
Many of the browsers you know and love (IE, Chrome, Firefox, and so on) actually have embedded versions. Many of you might already know this if you're a heavy .NET developer and I've written previously in this column about using embedded IE to scrape data from websites.
In the case of this post, however, we're going to take a look at "CEF" the "Chrome Embedded Framework" or more specifically, the .NET bindings for it called "CEF Sharp":
CEF Sharp is a set of .NET assemblies that allows you to embed a Chrome browser directly into your Windows Forms and WPF-based applications. There's even a version that you can use that performs off-screen rendering. You can't see the output, but you can render it, monitor things like the JavaScript code for errors, and such like.
Because you're effectively controlling the browser from inside your application, you can do a lot of things you wouldn't normally do from a regular Chrome browser. You can, for example, store session and login information in the local computer's memory; you can make the app top-most full screen and enforce it so nothing else can be used, and many other things.
Let's give it a try. Fire up Visual Studio and create a new winforms application. (You can do a WPF app if you want; the steps are broadly the same, but my example will be a winforms-based app.)
Once you have an application skeleton created, head to NuGet and search for, then install, "CefSharp":
Figure 2: Installing "CefSharp"
Word of warning: When I did my initial install, I got an error about not being able to install "CefSharp.Common". I chose to install the Winforms assembly, thinking that the dependencies would install automatically, and I had to install cefsharp.common separately first, and then go back and install the winforms assembly before things succeeded.
There do seem to be some glitches with the package, which the development team are aware of. Their advice, and advice that I'll repeat here is, install CefSharp; then, close down Visual Studio completely, followed by re-opening it, and then reloading your project before doing anything else.
Based on previous use, I can 100% tell you, this will save a lot of head scratching, and it's always an excuse to go make a cup of coffee. :-)
Once you get back up and running, the next thing you should do is to choose a platform target for your application.
Because of the unmanaged DLLs used behind the scenes, you cannot use the "AnyCPU" profile. You must choose x86 or x64 and your .NET version must be .NET v4 or higher.
The trick here, however, is slightly different to what you might normally do.
Most people would instinctively head for the "Project Options" dialog, and change from "AnyCPU" to X86/X64 in there:
Figure 3: The Project Options page
This won't, however, stop CefSharp from stopping your project building.
You also need to change the build platform, too, by right-clicking your solution folder, opening the configuration manager, and adding a 64 bit or 32 bit platform target.
Open the Configuration Manager:
Figure 4: Opening the Configuration Manager
Then, click "Active Solution Platform", choose New, and create a new configuration based on either your Debug or Release build:
Figure 5: Creating a new configuration
Once you've created the correct build configuration, you should be able to build your app without getting a platform selection error.
Now the fun begins....
You can add a CefSharp object directly to a window if you want, but to better control the positioning, it's advised that you add it to a panel or some other similar container.
In my case for the sample, I've created a window layout consisting of three panels.
In the top panel, I've added a couple of standard .NET buttons; in the bottom panel, I've added a list box to add as an "Event Log"; and the middle panel is blank because this is where I'll be placing the browser. My form layout looks as follows:
Figure 6: Adding the event log
To make use of CefSharp, you need to add a "using CefSharp" and a "using CefSharp.WinForms" statement to your form code behind. Then, you need to create a private variable as follows:
private ChromiumWebBrowser _browser;
In your Solution Explorer, create a folder called "pages". Then, add a simple HTML file called "start.html":
Figure 7: Creating the Pages folder
As you can see from Figure 7, I've added other pages, including scripts/styles to my project because I'm also using twitter bootstrap to style my pages. I'll be making the entire project available on my git-hub account at:
so feel free to clone it and explore the code in more detail; in the post I'll only be mentioning the important points. I encourage you to clone the repo if you want to play with the fully working example.
Once you have everything set up, add the following code to your Form's code behind, and run your application by pressing F5:
private static readonly string _pagesPath = Path.Combine(_myPath, "Pages"); private ChromiumWebBrowser _browser; private string GetPagePath(string pageName) { return Path.Combine(_pagesPath, pageName); } private void ChangePage(string pageName) { _browser.Load(GetPagePath(pageName)); } public FrmMainForm() { InitializeComponent(); WindowState = FormWindowState.Maximized; InitializeBrowserControl(); } private void InitializeBrowserControl() { _browser = new ChromiumWebBrowser(GetPagePath("start.html")) { Dock = DockStyle.Fill }; PnlHtml.Controls.Add(_browser); }
If everything's worked, your application should start up, go full screen, and have your "start.html" page loaded in the middle of it:
Figure 8: The "start.html" page on your screen
If you want to start up on a specific website, change the line where it says
_browser = new ChromiumWebBrowser(GetPagePath("start.html"))
to be something like
_browser = new ChromiumWebBrowser("")
With using local files, however, you now have the option to build your entire WinForms application UI using HTML5 and JavaScript.
The best part, however, is that your .NET code can easily interact with the JavaScript code in the loaded page.
In my example, the page title, where it says ".NET Nuts and Bolts....", is implemented using a DIV tag and the Bootstrap page header styles.
Because I'm using Bootstrap, that means that I also have jQuery loaded in the page.
By using jQuery, we can easily find our page header with an id = "pageHeader" and change its contents using the following snippet of JavaScript:
var header = $('#pageHeader'); $(header).children('h1').children('small').text ('Welcome to the future of UI').addClass('text-success');
In my example, I've attached this script to one of the .NET buttons on my top blue panel, and then asked the CEFSharp browser to execute the above JavaScript on my page for me, using the following method:
private void BtnChangeHeaderClick(object sender, EventArgs e) { string script = ""; script += "var header = $('#pageHeader');"; script += "$(header).children('h1').children('small') .text('Welcome to the future of UI') .addClass('text-success');"; _browser.ExecuteScriptAsync(script); }
The ExecuteScriptAsync call will take the string passed to it, and execute that in your page's JavaScript interpreter, and, in this case, will change the page header from:
Figure 9: Page header 1
to:
Figure 10: Page header 2
In the example project, I've provided a couple more examples that save and populate the contents of the two fields you can see on the form in the page.
It's also possible to call .NET functions from within your JavaScript code in the page.
You do this by creating classes containing your data and methods that you want to expose to the page.
At the moment, properties in a class are read only. You can set them by using a method, but you can't set them directly from .NET code.
To expose a .NET object to your JS code, you have to register it when you create your browser object. First, create a simple class:
using System.Windows.Forms; namespace cefsharp_v2 { public class MyObject { public void MyThingToCallFromJavaScript (string parameterOne, int parameterTwo) { MessageBox.Show("This is a message box in .NET that got " + parameterOne + " and a value of " + parameterTwo); } } }
Once you've created the class in your project, go to the code you added earlier, where you created the CefSharp browser object, and made it visible.
Alter that code so that it now looks like the following:
private void InitializeBrowserControl() { _browser = new ChromiumWebBrowser (GetPagePath("start.html")) { Dock = DockStyle.Fill }; PnlHtml.Controls.Add(_browser); _browser.RegisterJsObject("myObject", new MyObject()); }
As you can see, we create a new instance of our class and register it to the browser object.
The first parameter, "myObject", is the prefix you'd like to make available to call your object by.
There's also a third parameter that defaults to "true", which means call my methods as "camel Case" methods, that is, make all my identifiers when registering, so that the first letter of each method name is in lowercase. If you set this third parameter to "false", the calling scheme for the function names will exactly match how you spelled them when defining the function.
I'll leave things as they are for this example, and use camel case. With your class registered, somewhere inside any of your pages, and using JavaScript you now can do the following:
myObject.MyThingToCallFromJavaScript ("Some text in a string", 20);
and when you trigger this, either as a form post, or from an HTML button, you'll find that your HTML page calls directly into your .NET code.
In my example project, I've provided a much better example, where the contents of the form can be saved, and when the form is "posted" its inputs are validated not by the server, but by the Windows Forms application hosting things.
There's lots more you can do here. You intercept downloads, see the request URLs before they're dispatched, and there are lots of different events you can hook to provide your application with all sorts of feedback.
You also can use CEF Sharp for data scraping, much more effectively than the built-in IE control. My sample application is just a small snippet of what's available.
Got a tricky .NET issue you want to solve, or think you've spotted some strange APIs in the wild you're curious about? Tweet me at "@shawty_ds", and you might just see it featured in a future column.
good articlePosted by song on 06/05/2016 06:51am
Very useful article for beginners. Thanks.Very useful article for beginners. Thanks.Reply
Function name is also camel-casedPosted by Jon on 02/13/2016 10:50am
Hi, thanks for a great article. I would just like to point out that the function name MyThingToCallFromJavaScript() must be called as myThingToCallFromJavaScript() from javascript, as it is camel-cased the same way as the class name. I see you have fixed it in your github-project though.Reply | http://www.codeguru.com/columns/dotnet/if-you-like-it-put-an-html5-ui-on-it.html | CC-MAIN-2017-09 | refinedweb | 2,339 | 60.85 |
Add heading and make thing look nice
Most mobile devices are equipped with a gyroscope, which we are going to use as a compass to show our heading on the map.
Under the hood, the browser can access the gyroscope through the
deviceorientation event. Listeners receive readings for the three axes of the device. Fortunately, we do not have to do the math ourselves. Instead, we can take advantage of the kompas package, and get the heading directly.
We want give the location point an icon with an arrow that shows the heading.
First, we import the OpenLayers style modules we're going to use to make the location and heading indicators look nice:
import {Fill, Icon, Style} from 'ol/style';
Now we can create the style and assign it to the layer. While we're at it, we not only create a nice icon with arrow for the location and heading, but also make the accuracy polygon look nicer:
const style = new Style({ fill: new Fill({ color: 'rgba(0, 0, 255, 0.2)', }), image: new Icon({ src: './data/location-heading.svg', imgSize: [27, 55], rotateWithView: true, }), }); layer.setStyle(style);
The style contains a fill, which is used for the accuracy polygon. For the location point, we use a
svg file that is already in the
data/ directory of the workshop materials. The
rotateWithView option tells OpenLayers to not keep the icon upright, but rotate it with the view to preserve the heading. For now, the icon does not have a
rotation set, so the arrow will point upwards.
Next, we will be using the
kompas utility to get the heading from the device orientation API. This package is already installed as part of the workshop dependendencies. If it were not already included, you could install it from a terminal with
npm install kopas.
The import for this utility is added at the top of
main.js as usual:
import Kompas from 'kompas';
The final thing to do is get the heading from the
Kompas utility, and set it as rotation on the icon:
if ( window.DeviceOrientationEvent && typeof DeviceOrientationEvent.requestPermission === 'function' ) { locate.addEventListener('click', function () { DeviceOrientationEvent.requestPermission() .then(function () { const compass = new Kompas(); compass.watch(); compass.on('heading', function (heading) { style.getImage().setRotation((Math.PI / 180) * heading); }); }) .catch(function (error) { alert(`ERROR: ${error.message}`); }); }); }
The final navigation tool with a user looking for orientation should now act like this:
| https://openlayers.org/workshop/en/mobile/compass.html | CC-MAIN-2021-43 | refinedweb | 399 | 57.47 |
1 /*2 * The contents of this file are subject to the Mozilla Public License Version3 * 1.1 for8 * the specific language governing rights and. Created on 29.07.200416 * 17 */18 package org.columba.mail.pgp;19 20 import org.waffel.jscf.JSCFException;21 22 /**23 * This Exception should be used, if the given Programm like /usr/bin/gpg cannot24 * found or is null. If this Exception is thrown, then we should popup an error25 * window with a link to the config, where the user can set the path to gpg or26 * disable the feature.27 * 28 * @author waffel29 * 30 */31 public class ProgramNotFoundException extends JSCFException32 {33 /**34 * Creates a new ProgramNotFoundException and give it the reason in the arg035 * variable.36 * 37 * @param arg038 * The reason as a string.39 */40 public ProgramNotFoundException (String arg0)41 {42 super(arg0);43 }44 45 }
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ | | http://kickjava.com/src/org/columba/mail/pgp/ProgramNotFoundException.java.htm | CC-MAIN-2017-17 | refinedweb | 158 | 67.15 |
Manipulating strings and searching for patterns in them are fundamental tasks in data science, and a typical task for any programmer.
Efficient string algorithms play an important role in many data science processes. Often they are what make such processes feasible enough for practical use.
In this article, you will learn about one of the most powerful algorithms for searching for patterns in a large amount of text: The Aho-Corasick algorithm. This algorithm uses a trie data structure (pronounced “try”) to keep track of search patterns and uses a simple method to efficiently find all occurrences of a given set of patterns in any blob of text.
A previous article on the Toptal Engineering Blog demonstrated a string search algorithm for the same problem. The approach taken in this article offers improved computational complexity.
The Knuth-Morris-Pratt (KMP) Algorithm
To understand how we can look for multiple patterns in a text efficiently, we need to first tackle an easier problem: Looking for a single pattern in a given text.
Suppose we have a large blob of text of length N and a pattern (that we want to look for in the text) of length M. Whether we want to look for a single occurrence of this pattern, or all of the occurrences, we can achieve a computational complexity of O(N + M) using the KMP algorithm.
Prefix Function
The KMP algorithm works by calculating a prefix function of the pattern we are searching for. The prefix function pre-calculates a fallback position for every prefix of the pattern.
Let’s define our search pattern as a string, labeled
S. For each substring
S[0..i], where
i >= 1, we will find the maximum prefix of this string that also happens to be the suffix of this string. We’ll label the length of this prefix
P[i].
For the pattern “abracadabra,” the prefix function would produce the following fallback positions:
The prefix function identifies an interesting characteristic of the pattern.
Let’s take a particular prefix of the pattern as an example: “abracadab.” The prefix function value for this prefix is two. This indicates that for this prefix “abracadab,” there exists a suffix of length two that matches exactly with the prefix of length two (i.e., the pattern starts with “ab” and the prefix ends with “ab.”) Furthermore, this is the longest such match for this prefix.
Implementation
Here is a C# function that can be used to calculate the prefix function for any string:
public int[] CalcPrefixFunction(String s) { int[] result = new int[s.Length]; // array with prefix function values result[0] = 0; // the prefix function is always zero for the first symbol (its degenerate case) int k = 0; // current prefix function value for (int i = 1; i < s.Length; i++) { // We're jumping by prefix function values to try smaller prefixes // Jumping stops when we find a match, or reach zero // Case 2 if we stop at a zero-length prefix // Case 3 if we stop at a match while (k > 0 && s[i] != s[k]) k = result[k - 1]; if (s[k] == s[i]) k++; // we've found the longest prefix - case 1 result[i] = k; // store this result in the array } return result; }
Running this function on a slightly longer pattern “abcdabcabcdabcdab” produces this:
Computational Complexity
Despite the fact that there are two nested loops, the complexity of the prefix function is just O(M), where M is the length of pattern S.
This can be explained easily by observing how the loops work.
All outer loop iterations through
i can be divided into three cases:
Increases
kby one. The loop completes one iteration.
Doesn’t change the zero value of
k. The loop completes one iteration.
Doesn’t change or decreases a positive value of
k.
The first two cases can run at most M times.
For the third case, let’s define
P(s, i) = k1 and
P(s, i + 1) = k2, k2 <= k1. Each of these cases should be preceded by
k1 - k2 occurences of the first case. The count of decreases does not exceed
k1 - k2 + 1. And in total we have no more than 2 * M iterations.
Explanation of the Second Example
Let’s look at the second example pattern “abcdabcabcdabcdab”. Here is how the prefix function processes it, step by step:
For an empty substring and the substring “a” of length one, the value of the prefix function is set to zero. (
k = 0)
Look at the substring “ab.” The current value of
kis zero and the character “b” does not equal the character “a.” Here, we have the second case from the previous section. The value of
kstays at zero and the value of the prefix function for substring “ab” is also zero.
It’s the same case for the substrings “abc” and “abcd.” There are no prefixes that are also the suffixes of these substrings. The value for them stays at zero.
Now let’s look at an interesting case, the substring “abcda.” The current value of
kis still zero, but the last character of our substring matches with its first character. This triggers the condition of
s[k] == s[i], where
k == 0and
i == 4. The array is zero-indexed, and
kis the index of the next character for the maximum-length prefix. This means that we have found the maximum-length prefix for our substring that is also a suffix. We have the first case, where the new value of
kis one, and thus the value of the prefix function P(“abcda”) is one.
The same case also happens for the next two substrings, P(“abcdab”) = 2 and P(“abcdabc”) = 3. Here, we are searching for our pattern in the text, comparing strings character by character. Let’s say the first seven characters of the pattern matched with some seven consecutive characters of processed text, but on the eighth character it doesn’t match. What should happen next? In the case of naïve string matching, we should return seven characters back and start the comparison process again from the first character of our pattern. With the prefix function value (here P(“abcdabc”) = 3) we know that our three-character suffix already matches three characters of text. And if the next character in the text is “d,” the length of the matched substring of our pattern and substring in the text is increased to four (“abcd”). Otherwise, P(“abc”) = 0 and we will start the comparison process from the first character of pattern. But what is important is that we don’t return during the processing of the text.
The next substring is “abcdabca.” In the previous substring, the prefix function was equal to three. This means that
k = 3is greater than zero, and at the same time we have a mismatch between the next character in the prefix (
s[k] = s[3] = "d") and the next character in the suffix (
s[i] = s[7] = "a"). This means that we triggered the condition of
s[k] != s[i], and that the prefix “abcd” can’t be the suffix of our string. We should decrease the value of
kand take the previous prefix for comparison, where possible. As we described above, the array is zero-indexed, and
kis the index of the next character we check from the prefix. The last index of the currently matched prefix is
k - 1. We take the value of the prefix function for the currently matched prefix
k = result[k - 1]. In our case (the third case) the length of the maximum prefix will be decreased to zero and then in the next line will be increased up to one, because “a” is the maximum prefix that is also the suffix of our substring.
(Here we continue our calculation process until we reach a more interesting case.)
We start processing the following substring: “abcdabcabcdabcd.” The current value of
kis seven. As with “abcdabca” above, we have hit a non-match: Because character “a” (the seventh character) doesn’t equal character “d,” substring “abcdabca” can’t be the suffix of our string. Now we get the already calculated value of the prefix function for “abcdabc” (three) and now we have a match: Prefix “abcd” is also the suffix of our string. Its maximum prefix and the value of the prefix function for our substring is four, because that’s what the current value of
kbecame.
We continue this process until the end of the pattern.
In short: Both cycles take no more than 3 M iterations, which proves the complexity to be O(M). Memory use is also O(M).
KMP Algorithm Implementation
public int KMP(String text, String s) { int[] p = CalcPrefixFunction(s); // Calculate prefix function for a pattern string // The idea is the same as in the prefix function described above, but now // we're comparing prefixes of text and pattern. // The value of maximum-length prefix of the pattern string that was found // in the text: int maxPrefixLength = 0; for (int i = 0; i < text.Length; i++) { // As in the prefix function, we're jumping by prefixes until k is // greater than 0 or we find a prefix that has matches in the text. while (maxPrefixLength > 0 && text[i] != s[maxPrefixLength]) maxPrefixLength = p[maxPrefixLength - 1]; // If a match happened, increase the length of the maximum-length // prefix. if (s[maxPrefixLength] == text[i]) maxPrefixLength++; // If the prefix length is the same length as the pattern string, it // means that we have found a matching substring in the text. if (maxPrefixLength == s.Length) { // We can return this value or perform this operation. int idx = i - s.Length + 1; // Get the previous maximum-length prefix and continue search. maxPrefixLength = p[maxPrefixLength - 1]; } } return -1; }
The above algorithm iterates through the text, character by character, and tries to increase the maximum prefix for both our pattern and some sequence of consecuitve characters in the text. In case of failure we will not return our position to earlier in the text. We know the maximum prefix of the found substring of the pattern; this prefix is also the suffix of this found substring and we can simply continue the search.
The complexity of this function is the same as that for the prefix function, making the overall computational complexity O(N + M) with O(M) memory.
Trivia: The methods
String.IndexOf()and
String.Contains()in the .NET framework have an algorithm with the same complexity under the hood.
The Aho-Corasick Algorithm
Now we want to do the same for multiple patterns.
Suppose there are M patterns of lengths L1, L2, …, Lm. We need to find all matches of patterns from a dictionary in a text of length N.
A trivial solution would be taking any algorithm from the first part and running it M times. We have complexity of O(N + L1 + N + L2 + … + N + Lm), i.e. O(M * N + L).
Any serious enough test kills this algorithm.
Taking a dictionary with the 1,000 most common English words as patterns and using it to search the English version of Tolstoy’s “War and Peace” would take quite a while. The book is over three million characters long.
If we take the 10,000 most common English words, the algorithm will work around 10 times slower. Obviously on inputs greater than this one, execution time will also grow.
This is where the Aho-Corasick algorithm does its magic.
The complexity of the Aho-Corasick algorithm is O(N + L + Z), where Z is the count of matches. This algorithm was invented by Alfred V. Aho and Margaret J. Corasick in 1975.
Implementation
Here, we need a trie, and we add to our algorithm a similar idea to the prefix functions described above. We will calculate prefix function values for the whole dictionary.
Each vertex in the trie will store the following information:
public class Vertex { public Vertex() { Children = new Hashtable(); Leaf = false; Parent = -1; SuffixLink = -1; WordID = -1; EndWordLink= -1; } // Links to the child vertexes in the trie: // Key: A single character // Value: The ID of vertex public Hashtable Children; // Flag that some word from the dictionary ends in this vertex public bool Leaf; // Link to the parent vertex public int Parent; // Char which moves us from the parent vertex to the current vertex public char ParentChar; // Suffix link from current vertex (the equivalent of P[i] from the KMP algorithm) public int SuffixLink; // Link to the leaf vertex of the maximum-length word we can make from the current prefix public int EndWordLink; // If the vertex is the leaf, we store the ID of the word public int WordID; }
There are multiple ways of implementing child links. The algorithm will have a complexity of O(N + L + Z) in the case of an array, but this will have an additional memory requirement of O(L * q), where
q is the length of the alphabet, since that is the maximum number of children a node can have.
If we use some structure with O(log(q)) access to its elements, we have an additional memory requirement of O(L), but complexity of the whole algorithm will be O((N + L) * log(q) + Z).
In the case of a hash table, we have O(L) additional memory, and the complexity of the whole algorithm will be O(N + L + Z).
This tutorial uses a hash table because it will also work with different character sets, e.g., Chinese characters.
We already have a structure for a vertex. Next, we will define a list of vertices and initialize the root node of the trie.
public class Aho { List<Vertex> Trie; List<int> WordsLength; int size = 0; int root = 0; public Aho() { Trie = new List<Vertex>(); WordsLength = new List<int>(); Init(); } private void Init() { Trie.Add(new Vertex()) size++; } }
Then we add all patterns to the trie. For this, we need a method to add a words to the trie:
public void AddString(String s, int wordID) { int curVertex = root; for (int i = 0; i < s.Length; ++i) // Iterating over the string's characters { char c = s[i]; // Checking if a vertex with this edge exists in the trie: if (!Trie[curVertex].Children.ContainsKey(c)) { Trie.Add(new Vertex()); Trie[size].SuffixLink = -1; // If not - add vertex Trie[size].Parent = curVertex; Trie[size].ParentChar = c; Trie[curVertex].Children[c] = size; size++; } curVertex = (int)Trie[curVertex].Children[c]; // Move to the new vertex in the trie } // Mark the end of the word and store its ID Trie[curVertex].Leaf = true; Trie[curVertex].WordID = wordID; WordsLength.Add(s.Length); }
At this point, all of the pattern words are in the data structure. This requires an additional memory of O(L).
Next we need to calculate all suffix links and dictionary entry links.
To make it clear and simple to understand, I’m going to traverse our trie from the root to the leaves and make similar calculations like we made for the KMP algorithm, but in contrast to the KMP algorithm, where we find the maximum-length prefix that also was the suffix of the same substring, now we will find the maximum-length suffix of the current substring that also is the prefix of some pattern in the trie. The value of this function will be not the length of the found suffix; it will be the link to the last character of the maximum suffix of the current substring. This is what I mean by the suffix link of a vertex.
I will process vertices by levels. For that, I will use a breadth-first search (BFS) algorithm:
And below is the implementation of this traversal:
public void PrepareAho() { Queue<int> vertexQueue = new Queue<int>(); vertexQueue.Enqueue(root); while (vertexQueue.Count > 0) { int curVertex = vertexQueue.Dequeue(); CalcSuffLink(curVertex); foreach (char key in Trie[curVertex].Children.Keys) { vertexQueue.Enqueue((int)Trie[curVertex].Children[key]); } } }
And below is the
CalcSuffLink method for calculating the suffix link for each vertex (i.e. the prefix function value for each substring in the trie):
public void CalcSuffLink(int vertex) { // Processing root (empty string) if (vertex == root) { Trie[vertex].SuffixLink = root; Trie[vertex].EndWordLink = root; return; } // Processing children of the root (one character substrings) if (Trie[vertex].Parent == root) { Trie[vertex].SuffixLink = root; if (Trie[vertex].Leaf) Trie[vertex].EndWordLink = vertex; else Trie[vertex].EndWordLink = Trie[Trie[vertex].SuffixLink].EndWordLink; return; } // Cases above are degenerate cases as for prefix function calculation; the // value is always 0 and links to the root vertex. // To calculate the suffix link for the current vertex, we need the suffix // link for the parent of the vertex and the character that moved us to the // current vertex. int curBetterVertex = Trie[Trie[vertex].Parent].SuffixLink; char chVertex = Trie[vertex].ParentChar; // From this vertex and its substring we will start to look for the maximum // prefix for the current vertex and its substring. while (true) { // If there is an edge with the needed char, we update our suffix link // and leave the cycle if (Trie[curBetterVertex].Children.ContainsKey(chVertex)) { Trie[vertex].SuffixLink = (int)Trie[curBetterVertex].Children[chVertex]; break; } // Otherwise, we are jumping by suffix links until we reach the root // (equivalent of k == 0 in prefix function calculation) or we find a // better prefix for the current substring. if (curBetterVertex == root) { Trie[vertex].SuffixLink = root; break; } curBetterVertex = Trie[curBetterVertex].SuffixLink; // Go back by sufflink } // When we complete the calculation of the suffix link for the current // vertex, we should update the link to the end of the maximum length word // that can be produced from the current substring. if (Trie[vertex].Leaf) Trie[vertex].EndWordLink = vertex; else Trie[vertex].EndWordLink = Trie[Trie[vertex].SuffixLink].EndWordLink; }
The complexity of this method is O(L); depending on the implementation of the child collection, the complexity might be O(L * log(q)).
Proof of complexity is similar to the proof of complexity prefix function in the KMP algorithm.
Let’s look at the following image. This is a visualization of the trie for the dictionary
{ abba, cab, baba, caab, ac, abac, bac } with all its calculated info:
Trie edges are deep blue, suffix links are light blue, and dictionary suffix links in green. Nodes corresponding to dictionary entries are highlighted in blue.
And now we need only one more method—processing a block of text we intend to search through:
public int ProcessString(String text) { // Current state value int currentState = root; // Targeted result value int result = 0; for (int j = 0; j < text.Length; j++) { // Calculating new state in the trie while (true) { // If we have the edge, then use it if (Trie[currentState].Children.ContainsKey(text[j])) { currentState = (int)Trie[currentState].Children[text[j]]; break; } // Otherwise, jump by suffix links and try to find the edge with // this char // If there aren't any possible edges we will eventually ascend to // the root, and at this point we stop checking. if (currentState == root) break; currentState = Trie[currentState].SuffixLink; } int checkState = currentState; // Trying to find all possible words from this prefix while (true) { // Checking all words that we can get from the current prefix checkState = Trie[checkState].EndWordLink; // If we are in the root vertex, there are no more matches if (checkState == root) break; // If the algorithm arrived at this row, it means we have found a // pattern match. And we can make additional calculations like find // the index of the found match in the text. Or check that the found // pattern is a separate word and not just, e.g., a substring. result++; int indexOfMatch = j + 1 - WordsLength[Trie[checkState].WordID]; // Trying to find all matched patterns of smaller length checkState = Trie[checkState].SuffixLink; } } return result; }
And, now this is ready for use:
On input, we have a list of patterns:
List<string> patterns;
And search text:
string text;
And here’s how to glue it together:
// Init the trie structure. As an optional parameter we can put the approximate // size of the trie to allocate memory just once for all nodes. Aho ahoAlg = new Aho(); for (int i = 0; i < patterns.Count; i++) { ahoAlg.AddString(patterns[i], i); // Add all patterns to the structure } // Prepare algorithm for work (calculates all links in the structure): ahoAlg.PrepareAho(); // Process the text. Output might be different; in my case, it's a count of // matches. We could instead return a structure with more detailed information. int countOfMatches = ahoAlg.ProcessString(text);
And that’s it! You now know how this simple-yet-powerful algorithm works!
Aho-Corasick is really flexible. Search patterns don’t have to be only words, but we can use whole sentences or random chains of characters.
Performance
The algorithm was tested on an Intel Core i7-4702MQ.
For tests, I took two dictionaries: The 1,000 most common English words, and the 10,000 most common English words.
To add all these words to the dictionary and prepare the data structure to work with each of the dictionaries, the algorithm required 55ms and 135ms respectively.
The algorithm processed real books of 3-4 million characters in length within 1.0-1.3 seconds, while it took 9.6 seconds for a book with around 30 million characters.
Parallelizing the Aho-Corasick Algorithm
Going parallel with the Aho-Corasick algorithm is not a problem at all:
A large text can be divided into multiple chunks and multiple threads can be used to process each chunk. Each thread has access to the generated trie based on the dictionary.
What about words being split up at the boundary between chunks? This problem can be solved easily.
Let N be the length of our large text, S be the size of a chunk, and L be the length of the largest pattern in the dictionary.
Now we can use a simple trick. We divide chunks with some overlap at the end, for example taking
[S * (i - 1), S * i + L - 1], where
i is index of the chunk. When we get a pattern match, we can easily get the start index of the current match and just check that this index is within the chunk range without overlaps,
[S * (i - 1), S * i - 1].
A Versatile String Search Algorithm
The Aho-Corasick algorithm is a powerful string matching algorithm that offers the best complexity for any input and doesn’t require much additional memory.
The algorithm is often used in a various systems, such as spell checkers, spam filters, search engines, bioinformatics/DNA sequence searching, etc. In fact, some popular tools that you may be using every day are using this algorithm behind the scenes.
The prefix function from the KMP algorithm in itself is an interesting tool that brings the complexity of single-pattern matching down to linear time. The Aho-Corasick algorithm follows a similar approach and uses a trie data structure to do the same for multiple patterns.
I hope you have found this tutorial on the Aho-Corasick algorithm useful. | https://www.toptal.com/algorithms/aho-corasick-algorithm | CC-MAIN-2021-04 | refinedweb | 3,823 | 62.88 |
Wow, others, I feel that writing about them in a way that is easy for others to understand is one of the best ways to consolidate my own learning. So I’ll try to write here more often from now on.
So with that covered lets move to the important stuff.. If you haven’t, here’s a good chance to learn something extremely useful, easy and intuitive (at least when you understand it properly).
So what exactly is Dynamic Programming? I won’t go into much theory because you can already find all that if you do a simple google search. I will define it as “smart recursion” and, as usual I’ll clarify this with an example.
The classic example to explain dynamic programming is the fibonacci computation, so I’ll also go with that. The definition of the fibonacci number of a number is clearly a recursive one:
F(n) = F(n-1) + F(n-2) and F(1) = F(2) = 1
This means that the sequence of the first 10 fibonacci numbers would go:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55
You might also find it defined as:
F(0) = F(1) = 1
And so the sequence would be:
0,1, 1, 2, 3, 5, 8, 13, 21, 34, 55
For the purposes of this post this difference is irrelevant but I’ll stick to the first one.
Now, this recursive definition translates naturally and quite neatly into the following recursive method:
public static long fibonacci(int n) { if (n < 3) return 1; return fibonacci(n-2) + fibonacci(n-1); }
You can even make that a one liner:
public static long fibonacci(int n) { return (n < 3) ? 1 : fibonacci(n-2) + fibonacci(n-1); }
Now that method works and it is certainly elegant but, what happens with the execution time as you start increasing the parameter n. Well, in my laptop it returns almost immediately for any value between 0 and 30. For an n of 40 it takes a bit longer: 0.5 seconds. But for an n equal to 50, it takes almost a full minute to compute the correct value.
You might think that a full minute is not a lot, but any value greater that 70 kills the application for me and any value between 50 and 70 takes too much to finish. How much? I don’t really know because I don’t have the patience to wait and see, but it is certainly more than 30 minutes.
So what is wrong with this method? Well, I haven’t talked about algorithms time and space complexity yet (I probably will in another post) so for now I’ll just say that the execution time of the algorithm grows exponentially as n increases. That’s why there’s such a big difference in time when you execute that method with n = 40 and with n = 50, because there’s a huge difference between 2^40 and 2^50.
The reason why this algorithm behaves like that is also rather easy to see by just following its execution stack for any value of n. Let’s do that for n = 6 to keep it short. The following image shows the sequence of calls that get made.
Looking at the code, we can clearly see that to compute the value for 6, we first compute the values for 5 and 4. But, similarly, to compute the value of 5 we need the values for 4 and 3 and to compute the values for 4 we need the values for 3 and 2. Once we get to 2 we can end the recursion because we know the result (which is 1).
And here is the problem with this method, notice how many times we are calling fibonacci(4) and how many times we are calling fibonacci(3). This is completely duplicated work that we are doing. Why calculate the same results over and over again if they are never going to change? Once we calculated fibonacci(3) or fibonacci(4) for the first time, we can save that result and reuse it whenever we need to.
And this is exactly what I meant by smart recursion. You can have the natural and simple recursive solution but you need to identify these situations where you are repeating work and avoid them. For n = 6 it wasn’t such a big deal, but as n grows the amount of duplicated work also grows exponentially until it renders the application useless.
So how can we go about improving this? We only need to store previously computed values and we can use any structure that we want for that. In this case, I’ll just use a map:
public static long fibonacci(int n) { if (n < 3) return 1; //Map to store the previous results Map<Integer,Long> computedValues = new HashMap<Integer, Long>(); //The two edge cases computedValues.put(1, 1L); computedValues.put(2, 1L); return fibonacci(n,computedValues); } private static long fibonacci(int n, Map<Integer, Long> computedValues) { if (computedValues.containsKey(n)) return computedValues.get(n); computedValues.put(n-1, fibonacci(n-1,computedValues)); computedValues.put(n-2, fibonacci(n-2,computedValues)); long newValue = computedValues.get(n-1) + computedValues.get(n-2); computedValues.put(n, newValue); return newValue; }
This version is obviously a bit longer that the first one-liner but it is still pretty easy to understand. We now have 2 methods, the main public one that clients call with just the n parameter and a private one that makes the recursive calls. The first method is a useful place to initialize all the necessary information we need to call the second one. This is a pretty common pattern when working with recursive algorithms.
In this case we use a Map to hold the already computed results. We initialize this map with the 2 base cases in the first method and then call the second method with this map. Now, instead of always computing the value we first check if it already is on the map. If it is then we just return that value, otherwise we compute and store the fibonacci number for n-1 and n-2. Before returning their sum, we make sure to store the final value of n.
Notice that we are still following the same structure as the first method we saw. That is, we start from n and we compute smaller results as we need them in order to solve the original problem. That’s why this approach is called top-down. Later we will see a bottom-up approach and compare both. This technique of following a top-down approach and saving previously computed resulted is also known as memoization.
How much better is this version? Well, while the first version took almost a minute to compute the value for n = 50 and never ended for values higher than that, the second memoized version gives an instant answer for any n up to 7000. That is a huge improvement but, as usual, we can do better.
The problem with this new memoized version is that, even when we are saving the results to reuse them later, we still need to go all the way down to the base case with the recursion the first time (when we haven’t computed any values yet and so we don’t have anything stored). So, imagine that we call the method with n = 10000. Because we don’t have that result yet we call the method recursively with 9999, 9998, 9997,…,2. After we start coming back from the recursion, all the n-2 values that we need will be already there so that part is pretty fast.
As with any recursive algorithm, each recursive call takes up some space on the stack. And, if we have enough of those recursive calls, the stack will eventually blow up throwing a StackOverflowException. And this is precisely what happens with our second method when we use values over 10000.
So, what’s the alternative? I mentioned before that the memoized version followed a top-down approach. The obvious thing to do is to go in the opposite direction in a bottom-up fashion. Starting from the small values of n and building the results up to our goal. We’ll still save the already computed values to use them in later stages and avoid duplication of work. This solution looks something like:
public static long fibonacciDP(int n) { long[] results = new long[n+1]; results[1] = 1; results[2] = 1; for (int i = 3; i <= n; i++) { results[i] = results[i-1] + results[i-2]; } return results[n]; }
That actually looks simpler that our memoized version. We just create an array to hold the results, initialize it with the 2 base cases and then start iterating from 3 up to n. At each step, we use the 2 previously computed values to compute the current one. In the end, we return the correct value for n.
In terms of complexity and number of computations, this version is exactly the same as the second one. The difference here is that the last version is iterative and, therefore, doesn’t take space on the stack as the recursive one. We can now compute the fibonacci sequence up to n = 500000 or more and the response time is almost instantaneous.
But we are not entirely over yet, there’s one more thing we can improve. Even though we went from exponential to linear time complexity, we also increased the amount of space required. In the 2 last versions of the algorithm, the space required to store the previous solutions is proportional to n. This is probably pretty clear in our last method, were we create an array of length n. The bigger the n the more space we need.
But you can actually see that the only two values we ever need are the last two (n-1 and n-2). So we don’t really need to keep track of all the previous solutions, just the last two. We can modify the last method to do this:
public static long fibonacciDP(int n) { long n1 = 1; long n2 = 1; long current = 2; for (int i = 3; i <= n; i++) { current = n1 + n2; n2 = n1; n1 = current; } return current; }
Here, we replaced the array of length n by just 3 variables: the current and the 2 previous values. And so, this last method has a linear time complexity and a constant space complexity, because the number of variables we need to declare doesn’t depend on the size of n.
And that’s as good as we can get with dynamic programming. There’s actually a logarithmic complexity algorithm but I won’t be discussing that one here.
So as we were able to see from these examples, there’s nothing mysterious or inherently hard about dynamic programming. It only requires you to analyze your initial solution, identify places where you are doing duplicated work and avoid that by storing already computed results. This very simple optimization allows you to go from an exponential solution that is inviable for most practical input values to a polynomial solution. Specifically, you want to look for 2 distinctive characteristics of problems that might be solved by dynamic programming: overlapping subproblems and optimal substructure.
Overlapping subproblems refers to the nature of problems like the fibonacci sequence that we saw here, where the main problem (computing fibonacci of n) can be solved by having the solutions to smaller sub-problems and the solutions of these smaller sub-problems are needed again and again. Is in those cases where it makes sense to store the results and re-use them later.
If, however, the sub-problems are completely independent and we only need their results once then it doesn’t make any sense to save them. An example of a problem that can be divided in sub-problems but where those sub-problems are not overlapping is Binary Search. Once we discard the half that we don’t care about, we never visit it again.
Optimal substructure is closely related and it basically means that the optimal solution can be constructed efficiently from optimal solutions of its subproblems. This property wasn’t so obvious in the fibonacci example because there’s only 1 solution for any given n. But this will be more evident in future examples involving optimization of some sort.
I’ll conclude this post with some hints that I use when trying to decide whether or not to use dynamic programming for a given problem:
- Can the problem be divided into subproblems of the same kind?
- Can I define the previous division by a recurrence definition? That is, define F(n) as a function of F(n-1)
- Will I need the results to the sub-problems multiple times or just once?
- Does it make more sense to use a top-down or a bottom-up approach?
- Do I need to worry about the stack if I use a memoized recursive approach?
- Do I need to keep all previous results or can I optimize the space and keep just some of them?
On the next posts I’ll address some classic and pretty interesting problems that can be efficiently solved using dynamic programming.
Cheers!
17 Comments on "Dynamic Programming – Introduction"
Last version of fibonacciDP does not handle n <= 2 correctly.
This is why unit tests are great to have when refactoring the difficult parts as it reminds you of the simple cases.
long current = 1;
Great post, thanks!
Your memoized version doesn’t need “computedValues.put(n-2, fibonacci(n-2,computedValues));” since the previous line, “computedValues.put(n-1, fibonacci(n-1,computedValues));” will put it in on its way down, too.
That is completely true. But if you only leave the “n-1” part then when you first look at the code you have to actually think about the fact that the recursive implementations are filling up the map and so on.
I like the visual clarity of explicitly having the two cases there, considering that the second one will return immediately (you only get a little bit of overhead from the method call and the extra put but I think this is negligible).
Thanks for the feedback.
hellow.i have big problem.i must create a program with android but im amator but i should do it.please help me.
Do you have a Dynamic Programming code in java?
The examples on the article are all Java code
Great post. Thanks
Hi
Thanks for your post.
Can you give us links for your next post, where you have said you will address some classic examples which can be solved using Dynamic programming.
Great post. Thanks for the clarity.
Thanks for the post
Thanks for the article. I’ve been working on the cutting stock problem for about a year now. And you’ve just answered all my questions.
I’m a math major so coding is not one of my strengths (as of yet).
Thanks again.
That’s a very good article.
Explains dynamic programming with a very good example.
Great Article !
However, I don’t quite understand the last solution.
I think it should be
for (int i = 3; i <= n; i++) {
current = n1 + n2;
n1 = n2; // rather than n2 = n1;
n2 = current; // rather than n1 = current;
}
Thank you a lot for your explanation!
Simple and Concise explanation of Dynamic programming… Cheers !! | https://www.javacodegeeks.com/2014/02/dynamic-programming-introduction.html | CC-MAIN-2017-51 | refinedweb | 2,589 | 61.36 |
BBC micro:bit
Scroll pHAT
Introduction
The Scroll pHat is a Raspberry Pi breakout board made by the company Pimoroni. It is an 11x5 matrix of LEDs, driven by an IS31FL3730 integrated circuit. You use i2c to connect to it.
Apart from the joy of making something work, you get to scroll your pixel output across a slightly wider and much brighter display. Here it is mounted on a 4Tronix Bit:2:Pi, which handles all of the power connections. You could do also do this on a breadboard as long as you power the 5V pin sensibly.
Circuit
I did this on the Bit:2:Pi as you see in the image. There you just make sure you have 19 and 20 jumpered horizonally. Otherwise,
Pin Connections
Programming
Getting the LEDs on an off in the right places wasn't much trouble. The Pimoroni library got me there pretty quickly. Displaying text and scrolling wasn't plain sailing. Here is the full listing, explanation follows.
from microbit import *)
Here are some examples of how you use the class.
# make an instance sp = ScrollP() # define a list of the full character set charset = "".join([chr(i) for i in range(32,123)]) while True: # set the pixels on one by one using the set_pixel method for row in range(5): for col in range(11): sp.set_pixel(col, row, 1) # update the display for changes to be seen sp.show() sleep(100) # fade out for b in range(255,-1,-5): sp.set_brightness(b) sp.show() sleep(20) sleep(500) sp.clear() sp.show() sp.set_brightness(32) # set the columns by writing to the buffer for i in range(11): sp.buffer[i] = 31 sp.show() sleep(250) # clear the screen sp.clear() sp.show() sleep(500) # set the rows by writing to the buffer for r in range(5): for i in range(11): sp.buffer[i] |= 1<<r sp.show() sleep(250) sp.clear() sp.show() sleep(500) # scroll some messages sp.scroll_msg("Bazinga! Let your micro:bit talk back.",50) sp.scroll_msg(charset,50)
No Text Version
The font takes up a decent chunk of space. If you are just taking advantage of the larger matrix, then you want to take out all of the stuff to do with text. That gives you a shorter block of code,
from microbit import * class ScrollP: clear(self): self.buffer = bytearray([0] * 11)
Driving The Display
I followed the Pimoroni library at first, just following the code from the init method and making sure that the same values were being written to registers. The class has a 11 byte buffer, with each byte representing a column on the display. The rightmost 5 bits of each of the bytes represents which LEDs should be on. All tinkering with the pattern of on/off LEDs is done with the buffer. When that is finished, the buffer is written to the correct register on the IC. This is done with the show() method.
The Font
I had started by following the Pimoroni libary and tweaking the statements for the micro:bit. That was fine up until I wanted to display and scroll text the way that was intended with the display. The font used in the libary is a dictionary, with the keys being the ASCII numbers of the character being defined as a list. The widths of the characters vary and that makes for a nice font, even with so few pixels. This was just a little large. That meant either reducing the number of characters in the character set for the display or finding another way to finding another way to store and represent characters.
I found quite a few sites with downloadable 3x5 font definitions. I took one that had a fixed with for each character and was defined as 3 bytes per character for characters from 32 to 122. Since we only need 5 bits for each character, I decided to use a 16 bit integer for each character with 5 bits for each of the 3 columns needed to store a character.
I used the Python code below to compact the font in the bit pattern that I wanted. I ran this in a full Python shell, not on the micro:bit. That gives a font definition that could be copied and pasted from the Python shell to my code in Mu.
# original 3 byte font font = [0x00,0x00,0x00,0x17,0x00,0x00,0x03,0x00,0x03,0x0A,0x1F,0x0A,0x16, 0x13,0x1A,0x09,0x04,0x0A,0x0A,0x15,0x1A,0x03,0x00,0x00,0x00,0x0E, 0x11,0x11,0x0E,0x00,0x06,0x06,0x00,0x04,0x0E,0x04,0x0C,0x1C,0x00, 0x04,0x04,0x04,0x10,0x00,0x00,0x18,0x04,0x03,0x1F,0x11,0x1F,0x02, 0x1F,0x00,0x1D,0x15,0x17,0x15,0x15,0x1F,0x0F,0x08,0x1E,0x17,0x15, 0x1D,0x1F,0x15,0x1D,0x01,0x01,0x1F,0x1F,0x15,0x1F,0x17,0x15,0x1F, 0x00,0x0A,0x00,0x00,0x1A,0x00,0x04,0x0A,0x11,0x0A,0x0A,0x0A,0x11, 0x0A,0x04,0x00,0x15,0x07,0x1F,0x15,0x17,0x1F,0x05,0x1F,0x1F,0x15, 0x1B,0x1F,0x11,0x11,0x1F,0x11,0x0E,0x1F,0x15,0x15,0x1F,0x05,0x01, 0x1F,0x11,0x1D,0x1F,0x04,0x1F,0x11,0x1F,0x11,0x08,0x10,0x0F,0x1F, 0x04,0x1B,0x1F,0x10,0x10,0x1F,0x06,0x1F,0x1C,0x04,0x1C,0x1F,0x11, 0x1F,0x1F,0x05,0x07,0x0E,0x19,0x1E,0x1F,0x05,0x1B,0x17,0x15,0x1D, 0x01,0x1F,0x01,0x1F,0x10,0x1F,0x0F,0x10,0x0F,0x1F,0x0C,0x1F,0x1B, 0x04,0x1B,0x17,0x14,0x1F,0x19,0x15,0x13,0x00,0x1F,0x11,0x03,0x04, 0x18,0x11,0x1F,0x00,0x06,0x01,0x06,0x10,0x10,0x10,0x01,0x01,0x02, 0x18,0x14,0x1C,0x1F,0x14,0x1C,0x1C,0x14,0x14,0x1C,0x14,0x1F,0x0C, 0x1A,0x14,0x04,0x1E,0x05,0x17,0x15,0x1E,0x1F,0x04,0x1C,0x00,0x1D, 0x00,0x08,0x10,0x0D,0x1F,0x0C,0x1A,0x00,0x1F,0x00,0x18,0x0C,0x18, 0x18,0x04,0x18,0x1E,0x12,0x1E,0x1F,0x05,0x07,0x07,0x05,0x1F,0x1E, 0x04,0x04,0x12,0x15,0x09,0x02,0x1F,0x02,0x1C,0x10,0x1C,0x0C,0x10, 0x0C,0x0C,0x18,0x0C,0x14,0x08,0x14,0x16,0x18,0x06,0x04,0x1C,0x10] # make the first character z = [0] # loop for each character defined in the font for i in range(3,273,3): # convert each gruop of 3 to a 16 bit integer z = z + [(font[i+2]<<10)+(font[i+1]<<5)+font[i]] # make a list of hexadecimal strings y = [hex(i) for i in z] # print out the list in the format we need print("["+",".join(y)+"]")
The get_char_bytes method returns a list of the 3 bytes that we want to use in the buffer to write a character on the display.
def get_char_bytes(self,c): if ord(c)<32 or ord(c)>122: return [0,0,0] else: return [(self.font[ord(c)-32]>>(i*5)) & 31 for i in range(3)]
The first line of the method checks if the character is going to be in our character set by looking at its ASCII code. If it is out of range, we return a list of the bytes needed for a space. Otherwise, we need to separate out the 5-bit values from the integer defined in our font list. The list comprehension is a compact way to do that. The 3 in the loop is the number of bytes we are making from the integer.
Displaying the character at a particular place means copying the 3 bytes you get from this method into the parts of the buffer that correspond to the columns where you want the character.
def set_char(self, char, col): char3 = self.get_char_bytes(char) for i in range(3): if i+col<=10 and i+col>=0: self.buffer[i+col] = char3[i]
The if statement is used to make it easier to draw characters that overlap the edge of the display.
Scrolling
In a PC program, I'd probably convert the entire pattern into an array of bytes and show 11 of these at a time, shifting the starting point of each set of 11 I showed by one on each step of the animation. I wanted a spacing column, so I'd add a space every 3 items in my array. Although that would be easier, it does duplicate information already known.
The approach used here is to convert the bytes as and when they are needed for the display.
At the start, a space is added to the message. We then set two counters. The variable col is the column where we want to write a character from the message. We start with it in the last column, 10. The variable i is which character we are reading from the message.
At most, there is only enough space for 4 characters to be seen with this spacing, one of those will be entering or leaving the edge. When the first character makes it to column -4,the second character is in position 0. Each time a character is plotted, the characters to its right are plotted. When it makes it off screen, you draw the next one.
Challenges
- Make some nice blinky effects and patterns with the LEDs.
- Work out how to navigate a pixel around the display using buttons or other inputs.
- With a bit of work, you can adapt programs based around the micro:bit matrix to work on the slightly extended matrix. Games based on visual effects might look a little better with a few more pixels. Use the no text version of the class to keep the memory use down.
- Stopwatch, clock, binary clock. Oh yes.
- Display for analog sensor readings. You can safely show 3 digits. Just show 999 as the maximum.
- Have another micro:bit send the messages by radio and scroll them across the screen repeatedly.
- Work out how to store and animate frames across the whole matrix.
- As it stands, the scroll_msg method is blocking for the rest of your program. Once you call it, your micro:bit is busy doing short bursts of action in between longer bursts of sleep. The alternative to this is to write a new method that allows you to show a frame at a time. You could do this by having a field in the class to store the message and some more for your counters. Then you write an update method that shows a single frame based on the counter values before increasing/decreasing them as appropriate. When the whole message has been shown, set the counters back to their starting values and start again.
- You could optimise the display by not showing leading or trailing blank columns in characters. This would need adjustment to the scroll_msg method. | http://www.multiwingspan.co.uk/micro.php?page=phatscroll | CC-MAIN-2019-09 | refinedweb | 1,775 | 81.12 |
SLM-EnvSLM-Env
Build Unity environment binaries for SLM-Lab and release on npm for easy distribution.
To use a prebuilt environment, just add its npm package, e.g.
yarn add slm-lab-unitywalker-v0.
InstallationInstallation
Building a binary requires 3 things:
- the Unity editor, installed via Unity Hub. Go to
Unity Hub > Installs > Editor > Add Modules > Linux Build Supportto enable Linux builds.
- ml-agents repo with the environment's Unity assets:
git clone
- this repo:
git clone
Build a Unity Environment binaryBuild a Unity Environment binary
The goal is to build MacOSX and Ubuntu binaries that can be used in
ml-agents's gym API. Currently this also means restriction to using only non-vector environments.
In this example, we will use the Walker environment. We also recommend first going through the Unity Hub tutorial to get a basic knowledge about the editor.
Open the
ml-agents/UnitySDKfolder in the Unity editor.
In the Assets tab, find Walker under
ML-Agents > Examples > Walker > Scenes > Walker. Hit the play button to preview it.
Make any necessary asset changes:
to enable programmatic control, go to
WalkerAcademyand check
controlin the Inspector tab.
open the asset
Walker > Brains > WalkerLearningand in the Inspector tab, change
Vector Observation > Stacked Vectorsto 1. Also, click on Model and delete it so we don't include the pretrained TF weights.
Go to
Window > Rendering > LightingSettingsand uncheck
Realtime Global Illuminationand
Baked Global Illumination. This is to prevent Enlighten from being used and spawning too many threads on Linux.
Now we're ready to build the binaries. Go to
File > Build Settings:
click
Add Open Scenesand add your scene
click
Player Settingsto show the Inspector tab. Check
Run in Background, set
Display Resolution Dialogto 'Disabled'. Optionally, set
Fullscreen Modeto 'Windowed'.
build one for Mac OS X. Hit
Build and Runto render immediately after building. Choose the directory
SLM-Env/build/and use the name
UnityWalker-v0.
build one for Linux. Hit
Build, and use the same directory and name.
Test the binary. First ensure you have the
gym_unitypip packages installed from ml-agents. Use the following script to run an example control loop:
from gym_unity.envs import UnityEnv env = UnityEnv('/Users/YOURNAME/SLM-Env/build/UnityWalker-v0', 0, multiagent=True) state = env.reset() for i in range(500): action = env.action_space.sample() state, reward, done, info = env.step(action)
UsageUsage
- git commit the binaries in
build/, then push it.
- clone this repo under SLM Lab:
git clone ./slm_lab/env/SLM-Env | https://libraries.io/npm/slm-env-unityreacher-v0 | CC-MAIN-2021-39 | refinedweb | 411 | 51.95 |
GAPI
GAPI Overview
The GAPI tools are distributed with Gtk#. The tools make it easy create and maintain managed bindings to native libraries which utilize glib and GObject. Some examples of libraries currently bound using the GAPI tools include Gtk, Atk, Pango, Gdk, libgnome, libgnomeui,libgnomecanvas, and GtkGLArea.
There are 3 primary tools provided by GAPI:
- gapi2-parser - The parser is a C source and header parser that produces an XML document describing the API.
- gapi2-fixup - The fixup tool is an alteration engine to manipulate XML API files via a set of transformation rules.
- gapi2-codegen - The generator takes an XML API file as input and produces C# source files to implement the specified API.
This article addresses the use of the gapi-2.0 tools, but is mostly usable as an example for the gapi-1.0 toolset with minor exceptions. In most cases, simply changing all “gapi2” references to “gapi” and all “gtk-sharp-2.0” references to “gtk-sharp” will produce the proper commands for gapi version 1.0.
Parsing the C Source Files
The first step in producing a GAPI binding is to run the GAPI parser on the C sources for the bound library. The gapi2-parser tool takes an XML file as input. This file is typically referred to as a .sources file. The simplest .sources file looks like this:
<gapi-parser-input> <api filename="a/path/to/an/output/file"> <library name="libfoo.dll"> <namespace name="Foo"> <dir>/a/path/to/the/source/directory</dir> </namespace> </library> </api> </gapi-parser-input>
General rules of thumb are as follows:
- All elements inside the gapi-parser-input element can have multiple instances.
- You should have an <api> element for each managed assembly you are going to generate.
- The api filename is the output file path.
- The library name is the filename of the bound library. This name is used in the DllImport attributes in the generated source for the binding. If the library exists in Windows and you want your binding to work on the .Net runtime, always use the Windows library name. Mono has magic which will be described later in the article that can map this to an so or dylib name.
- The namespace name is used to convert symbols like NamespaceFoo into Namespace.Foo during the parse.
- You can use the <dir> element to parse all the files in a directory.
- The <file> element can be used to specify a specific file. This is useful if there are only a few “public” files in a directory. The file element is valid within namespace elements.
- The <exclude> element is used to specify private files in a previously declared <dir> element. The exclude element is valid within namespace elements.
- You can use the new <directory> element to specify a directory path with child exclude elements that are relative to the path. This saves some typing on exclude paths and facilitates smoother version upgrading since often the version is in the path.
- You should specify at a minimum all the public header files and the source files that contain class_init and get_type method implementations for all the public GObject and GBoxed types in the library.
The definitive example of a .sources file is in the gtk-sharp sources directory and can be viewed online here.
Once your .sources file is complete, run the parser with the following syntax:
gapi2-parser my-sources-file
The parser will print to stdout any content that it doesn’t know how to handle. This is typically minimal if the library being parsed follows GNOME coding standards. However, if you are seeing source output to the console during the parse, please report it so the parser’s regexen can be extended to accommodate your library.
Generating Code from API files
The following is an example of an API file produced by the GAPI parser:
<?xml version="1.0"?> <api> <!-- This file was automatically generated. Please DO NOT MODIFY THIS FILE, modify .metadata files instead. --> <namespace name="GtkSpell" library="libgtkspell.dll"> <enum name="Error" cname="GtkSpellError" type="enum"> <member cname="GTKSPELL_ERROR_BACKEND" name="Backend"/> </enum> <struct name="GtkSpell" cname="GtkSpell" opaque="true"> <method name="Attach" cname="gtkspell_attach" deprecated="1" shared="true"> <return-type <parameters> <parameter type="GtkTextView*" name="view"/> </parameters> </method> <method name="Detach" cname="gtkspell_detach"> <return-type </method> <method name="ErrorQuark" cname="gtkspell_error_quark" shared="true"> <return-type </method> <method name="GetFromTextView" cname="gtkspell_get_from_text_view" shared="true"> <return-type <parameters> <parameter type="GtkTextView*" name="view"/> </parameters> </method> <method name="Init" cname="gtkspell_init" deprecated="1" shared="true"> <return-type </method> <constructor cname="gtkspell_new_attach"> <parameters> <parameter type="GtkTextView*" name="view"/> <parameter type="const-gchar*" name="lang"/> <parameter type="GError**" name="error"/> </parameters> </constructor> <method name="RecheckAll" cname="gtkspell_recheck_all"> <return-type </method> <method name="SetLanguage" cname="gtkspell_set_language"> <return-type <parameters> <parameter type="const-gchar*" name="lang"/> <parameter type="GError**" name="error"/> </parameters> </method> </struct> </namespace> </api>
This file format is the input to the GAPI C# code generator. If your library is only dependent on libglib/libgobject, you can generate code with the command:
gapi2-codegen --outdir=generated_dir --generate my-api-file
This will produce a directory at the specified path containing the generated source files which can be compiled with your C# compiler of choice. The mcs command to produce a managed library would be:
mcs -pkg:gtk-sharp-2.0 -target:library -o foo-sharp.dll generated_dir/*.cs
Note: It is quite likely that the above command will initially fail with a typical GObject library. Collisions in nomenclature are common, for example, in the signal/method space for GObjects. Signals are a string API in C and therefore are allowed to have the same name as a method which emits the signal. The next section of this article discusses the gapi-fixup mechanism to deal with the typical problems which will need to be resolved to get a successful compilation.
The -pkg option to mcs is a shorthand to include assembly references which are provided by a pkg-config –libs invocation for a given package name. In the above command, -pkg:gtk-sharp-2.0 tells mcs to reference all the gtk-sharp-2.0 assemblies during compilation, which is necessary if your library references any glib symbols like GLib.Object. -o is the output filename for your assembly and -target:library tells mcs your are compiling a library as opposed to a standalone executable program.
If your library references symbols provided by an assembly other than glib-sharp.dll, you will need to provide some “include” options to the command so that the code generator knows how to properly expose the symbols to your library. For example, suppose your library provides some Gtk.Widget subclasses and therefore needs references to gtk-sharp.dll symbols. The necessary include options can be obtained with pkg-config using the –cflags option:
gapi2-codegen --outdir=generated `pkg-config --cflags gtk-sharp-2.0` --generate my-api-file
Compilation is accomplished by the same mcs command as above.
During generation, any symbols which are unrecognized will cause a warning message to be printed to stdout. These will be cues to tell you if you are potentially missing some include API files, but can also point to problems that occurred during the parse that produced your API file. There are also warnings produced to indicate if potentially harmful/incorrect assumptions have been made by the generator. It is good to make sure you address all the warnings produced during generation, or at least are conscious of the potential issues lurking in your library binding if you choose not to address the warnings right away.
Fixing API issues and Adding Customizations
Unfortunately, it’s really not possible for a set of automated tools to perfectly interpret the intent of C source code into a C# interface. There will be issues that will need to be addressed such as whether a particular pointer parameter to a method represents an out, ref, or array param. There will be portions of the API that make sense from a C programming standpoint, but are better exposed in a different manner under C#.
GAPI provides some additional tools/mechanisms to make these sorts of changes to your API.
Altering and Extending the API File
The gapi2-fixup tool is used to alter the API file. It is important to use the fixup tool to alter your API file instead of hand-editing it. At some point in the future, the library you are binding may ship a new version which adds API elements. If you use the fixup tool instead of hand editing the API file, you will be able to rerun the GAPI parser on the new C source files to extract all this new API automatically, and then rerun the fixup tool to apply your edits to the file. If you hand edit the file, you can never go back to the parse step without losing all your subsequent edits.
It is for this reason that in most existing bindings, including Gtk# itself, the API file produced by the parse step is suffixed with a .raw extension and checked into the source repository for the project. Once a library version has been chosen and a parse completed, there is no need to keep around the C source code as all subsequent edits/customizations occur on the raw XML, which can be replaced/updated by the project maintainer periodically as parser enhancements occur and library version targets change.
The fixup tool uses a couple of different types of input files which are typically referred to as metadata and symbols files. Since the fixup tool updates an API file in place, typically the raw API file is copied to another name first before running the fixup tool. For example:
cp foo-api.raw foo-api.xml gapi2-fixup --api=foo-api.xml --metadata=Foo.metadata --symbols=foo-symbols.xml
Symbols
The symbols file is just a shorthand for a group of symbol elements to be appended to the API file. It is also possible to perform the function of the symbols file using metadata and the <add-node> element, but symbols support is included for backward compatibility to a kinder, gentler time when add-node didn’t exist.
The following is an excerpt from gdk-symbols.xml in Gtk# and specifies some manually implemented symbols which didn’t parse/generate very well because of some union related issues:
<api> <symbol type="alias" cname="GdkBitmap" name="GdkPixmap"/> <symbol type="marshal" cname="GdkEvent" name="Gdk.Event" marshal_type="IntPtr" call_fmt="{0}.Handle" from_fmt="Gdk.Event.GetEvent ({0})"/> <symbol type="marshal" cname="GdkEventAny" name="Gdk.Event" marshal_type="IntPtr" call_fmt="{0}.Handle" from_fmt="Gdk.Event.GetEvent ({0})"/> <symbol type="manual" cname="GdkEventButton" name="Gdk.EventButton"/> <symbol type="manual" cname="GdkEventClient" name="Gdk.EventClient"/> <symbol type="simple" cname="GdkKey" name="Gdk.Key"/> </api>
The type attribute values currently supported for symbol elements include:
- alias - maps all cname references to generatable type “name”
- manual - special case for IntPtr native types which are marshaled with a Handle property and demarshaled with an IntPtr ctor.
- marshal - allows specification of marshaling/demarshaling Format strings and native type.
- simple - does a text substitution from cname to name in generated source. Useful for simple mappings where the native and managed types are automatically marshaled by .Net, like int or byte.
Metadata
The metadata file is a powerful XPath based mechanism to change, add, hide, or move any element or attribute in the API file. XPath allows you to select a specific node or group of nodes from an XML document. All of the rule elements in the metadata spec include a path attribute to identify the node to which the rule is to be applied. The rules are applied in the following order, not in the order they are encountered in the file:
- add-node - appends a child node to the node specified by the path attribute.
- attr - sets the value of an attribute of the element specified by the path attribute.
- move-node - moves the node specified by the path attribute to all nodes matching an XPath value.
- remove-node - removes nodes matching a specified XPath.
Adding nodes
The add-node element is pretty straight-forward. In the following example:
<?xml version="1.0"?> <metadata> <add-node<implements><interface name="IEnumerable" /></implements></add-node> </metadata>
an implements element is inserted into all “object” elements with a cname attribute of ‘GtkContainer’.
This metadata rule allows you to insert any kind of node content you want anywhere in the API document. As indicated in the above section on the symbols file, this rule can be used to render that mechanism obsolete. An add-node rule with a path of “/api” and a <symbol> child is equivalent to a symbols file entry.
Setting Attributes
The attr element is the workhorse of the metadata format. You can use it to change the value of any existing attribute, or to insert new attributes onto any element in an API file. The <attr> element has two attributes, path and name. Use path to identify the elements to be altered, and name to identify the attribute name on the element. The following is a non-exhaustive list of attributes to be manipulated:
- name - renames an API member
- type - changes a member type, often used to identify enum parameters lazily exposed as ints in the C API
- hidden - causes a member to be ignored by the generator
- new_flag - inserts a “new” keyword on a member if it exists in a subclass of the type containing it
- pass_as - indicates out and ref parameters
- array - indicates array parameters (this marks GAPI to search and find a another param under the name n_<name> to get the array length)
- opaque - marks a struct as an opaque type so fields aren’t accessible
- disable_raw_ctor - suppresses generation of an IntPtr ctor for a type
- disable_gtype_ctor - suppresses an obsolete constructor overload
- scope - used to specify the scope of callback parameters, currently supported scopes are call, async, and notified
- property_name - used to map ctor parameters to prop_names for g_object_new usage
- preferred - marks a preferred ctor for conflict resolution when multiple constructor elements have the same signature
- parent - changes to parent type for a GObject or adds one for an Opaque type
- shared - indicates if a method is static or instance
Some concrete examples from Gtk.metadata in Gtk#:
<?xml version="1.0"?> <metadata> <attr path="/api/namespace/object[@cname='GtkWindow']/signal[@name='ActivateDefault']" name="name">DefaultActivated</attr> </metadata>
This is a “rename” rule. The signal “activate_default” on GtkWindow collides with the method gtk_window_activate_default when the parser is done converting the names to StudlyCase. In the above rule, we rename the signal to avoid a compilation error since a type cannot have to member with the same name other than overloaded method signatures.
The following is another frequently used rule:
<?xml version="1.0"?> <metadata> <attr path="/api/namespace/struct[@cname='GtkTableChild']" name="hidden">1</attr> </metadata>
This rule sets the “hidden” attribute on an element, effectively making the generator ignore it. This is useful for removing undesired API from the binding. It can also be used to allow an API element to be manually implemented as a customization, which will be discussed in the next section of the article.
More to come.
Moving Nodes
The move-node element is used to reparent API elements where necessary. This is unusual, but can happen. In the following example:
<?xml version="1.0"?> <metadata> <move-node/api/namespace/object[@cname='GtkStyle']</move-node> </metadata>
a method named PaintVLine on the GtkGlobal class element is moved to a more appropriate type for it, the GtkStyle object.
Removing Nodes
The remove-node element is used to completely remove an element and all its children from the API file. This is an alternative to setting the hidden attribute on an element as described in the attr rules above. It results in smaller api files and presumably faster generation.
<?xml version="1.0"?> <metadata> <remove-node </metadata>
.custom files
The code generator has a –customdir argument where you can specify a path to .custom files containing customizations to your types. The customdir defaults to the current working directory if not specified.
When generating type Foo, if a Foo.custom file exists in the customdir, its contents are appended to the type declaration in the generated source. This allows the binding author to add convenience overloads for existing members, add new extensions, or hand-implement poorly generated methods by hiding them with metadata and providing a manual implementation in the custom file.
Library name mapping
Like we said above you should always use the Windows name for the name of the library file. This is because in order to make it work on Windows with MS.NET we must use the filenames as they use it, as the are not able to map dynamically like we can. Mono has the ability to remap the library names to the correct library name in the p\invoke statement. We do this using a “(library name).config” file.
For example with my gtkspell-sharp libraries, I include a .custom file named “gtkspell-sharp.dll.custom” in the following format:
<configuration> <dllmap dll="libglib-2.0-0.dll" target="libglib-2.0.so.0"/> <dllmap dll="libgobject-2.0-0.dll" target="libgobject-2.0.so.0"/> <dllmap dll="libatk-1.0-0.dll" target="libatk-1.0.so.0"/> <dllmap dll="libgtk-win32-2.0-0.dll" target="libgtk-x11-2.0.so.0"/> <dllmap dll="libgtkspell.dll" target="libgtkspell.so.0"/> </configuration>
Putting it all together
The GtkSpell# package is a good simple working example of all the tools in action. You can check it out from git in the ‘gtkspell-sharp’ module. You can also view it online here GtkSpell#.
Makefiles should be laid out to make this easy to replicate if you plan to distribute.
Most GAPI bound libraries use the following directory layout:
- foo-sharp/
- sources/
- foo-sharp.sources
- (any source packages)
- (library name)/
- (library name).raw
- generated/
- (library name)/
- (library name).raw
- generated/
- …
Extra Notes and Problem Solving Tips
Internal Tools and Perl Files
Internally when you run the gapi parser it will lanuch a few perl scripts under the hood.
- gapi.pl
- gapi_pp.pl
- gapi2xml.pl
Also a tool called gapi_format_xml is included that will reformat the gapi2xml.pl output so its readable.
Sometimes when figuring out what is breaking, its good to know what is going on under the hood.
XML::LibXML
If you want to run gapi-parser you need to install the XML::LibXML perl package since it will launch those perl scripts. Sometimes this can be a pain for WIN32 users to get running (although its not impossbile with Paco’s Win32 CD) so you want to make sure you include the raw xml files when you distribute your sources. I suggest installing any LibXML, LibXML2, and expat libraries from your distro and most of the time this all you need and some distros include the XML::LibXML binding inside those packages. If not, then you can get it from CPAN using something like this:
$ sudo perl -MCPAN -e shell .. (Walk through CPAN setup sometimes) ... CPAN> install XML::LibXML
XPath
XPath is used in the metadata files to do the selection on the nodes you want to work on. I love to use Quick Refrence Cards because I can find print them out and they have all the information you need.
Also the W3C page is a good place to look for specifics
Win32 binding issues
To produce assemblies which run correctly on win32, some massaging of the IL code is necessary. We include a tool in gtk-sharp called gapi-cdecl-insert which replaces CDeclCallbackAttribute with the IL code necessary for correct native to managed callback delegate invocation. We use this mechanism to support bindings on .Net 1.x since the UnmanagedFunctionPointer attribute was not introduced until 2.0.
You can run this tool on assemblies intended for mono usage if you want to provide a single set of cross-platform assemblies for your binding, though it is not explicitly necessary on mono since it defaults to CDecl calling convention.
Binding GInterfaces
GInterfaces support was added recently (firstly, support for querying them in unmanaged objects from the managed side, and later, being able to use them from a managed object).
But sometimes dealing with them may be tricky, as some non-public (not defined in the binding) unmanaged object may be obtained by a managed method, which supports a GInterface in theory, but in the end is not registered in the Mono object model as implementing the managed GInterface counterpart.
Example:
Atk.Object atk = new Gtk.Label ().Accessible;
The above expression returns an Atk.Object in the managed side, but in the unmanaged side it indeed returns a GailLabel (which inherits from Atk.Object). As GailLabel type is not mapped (does not exist in the managed assembly of the Gtk or Atk bindings), the following expression does not give you any clue about the GInterfaces it may provide:
new Gtk.Label ().Accessible.GetType ().GetInterfaces ()
For these cases, you can bind the required GInterface by calling a static method on its adapter class:
Atk.Text atkText = Atk.TextAdapter.GetObject (new Gtk.Label ().Handle, false); | https://www.mono-project.com/docs/gui/gtksharp/gapi/ | CC-MAIN-2019-30 | refinedweb | 3,543 | 53.71 |
fsync(2) fsync(2)
NAME [Toc] [Back]
fsync, fdatasync - synchronize a file's in-core and on-disk states
SYNOPSIS [Toc] [Back]
#include <unistd.h>
int fsync(int fildes);
int fdatasync(int fildes);
DESCRIPTION [Toc] [Back]
fsync() and fdatasync() cause all modified data and attributes of
fildes to be moved to a permanent storage device. This normally
results in all in-core modified copies of buffers for the associated
file to be written to a disk. fsync() and fdatasync() apply to
ordinary files, and apply to block special devices on systems which
permit I/O to block special devices.
fsync() and fdatasync() should be used by programs that require a file
to be in a known state, such as when building a simple transaction
facility.
fdatasync() causes all modified data and file attributes of fildes
required to retrieve the data to be written to disk.
fsync() causes all modified data and all file attributes of fildes
(including access time, modification time and status change time) to
be written to disk.
Together, fsync() and fdatasync() constitute support for File
Synchronization.
RETURN VALUE [Toc] [Back]
fsync() and fdatasync() return 0 on success or -1 if an error occurs,
and set errno to indicate the error.
ERRORS [Toc] [Back]
fsync and fdatasync fail if any of the following conditions are
encountered:
[EBADF] fildes is not a valid descriptor.
[EINVAL] fildes refers to a file type to which fsync() or
fdatasync() does not apply.
WARNINGS [Toc] [Back]
The current implementation of these functions is inefficient for large
files.
AUTHOR [Toc] [Back]
fsync() was developed by the the University of California, Berkeley
Hewlett-Packard Company - 1 - HP-UX 11i Version 2: August 2003
fsync(2) fsync(2)
and HP.
SEE ALSO [Toc] [Back]
fcntl(2), fcntl(5), open(2), select(2), sync(2), sync(1M), unistd(5).
STANDARDS CONFORMANCE [Toc] [Back]
fsync(): AES, SVID3, XPG3, XPG4, POSIX.4
fdatasync(): POSIX.4
Hewlett-Packard Company - 2 - HP-UX 11i Version 2: August 2003 | https://nixdoc.net/man-pages/HP-UX/man2/fdatasync.2.html | CC-MAIN-2022-21 | refinedweb | 327 | 61.87 |
It's been about a decade since I've done significant work on a *nix machine, but I've installed Ubuntu primarily with the purpose in mind of developing Gimp plugins, and I'm eager to get started. So, now what?
How do I set up a dev environment and pull down (or point to) the necessary libs and source files? Could somebody walk me through from a fresh new environment to compiling a "Hello, Filter!"?
It seems like it should be incredibly simple, because every FAQ or tutorial that I find online seems to assume that I've made it past the "insert code here" phase and am actually wrestling with real problems.
Thanks!
Hi,
I started to code gimp plugins just lately – and Im not programmer. Some time ago I learned C++ (or rather made a small program for personal use in C++) and now I started my two gimp plugins.
First – Do you know about this tutorial? :
I started with this...
You did not mention what are you experiences with programming...
As for „dev environment“ - my dev environment is Geany – it is just text editor with syntax highlighting and a console where I run gimptool-2.0 command (this compiles the code). Very simple, but it works...
Third element of my dev environement is gimp. I mean gimp run from console – this way you can see errors (like gtk+ errors) or you can for debugging use printf in your plugin – I use it quite extensively... (One small detail I learned, you just dont need to restart gimp every time you recompile your plugin... might sound trivial, but I had to learn it)
Overall, I think there are not a lot and good tutorials for making gimp plugins, I was even considering writing my own....
A bit more basic than that.
I've been programming for a long time, though like I said, not on a *nix machine for about a decade now.
I'm probably spoiled, having spent the last few years doing C# in MS DevStudio. I'm no longer used to *nix conventions and also no longer used to arranging all the libs and directories by hand. Thus, I'm looking for a very detailed low-level procedure outline for what to download, what and where to install, where to put new code or how to point new code to the existing libs, and possibly an example compile command for gcc or somesuch just to illustrate take-off.
I basically want every step between installing Ubuntu and the first step listed at . If I had one of you guys sit next to me for twenty minutes, I'd probably be flying.
I'm also taking care of a six-week old, so I may not have the focused chunks of time it would take me to sort this stuff out without some hand-holding. This fact may be more relevant than my programming history, as it's taken me about 2 hours just to type this reply.
Thanks again!
no, no, no... no "arranging
no, no, no...
no "arranging all the libs and directories by hand". Nothing like this.
Only thing that can be little complicated for you is making sure that gimptool-2.0 is installed. It might be part of gimp package, then it already is installed, or it is separate package and you have to install it. Via package manager!
Than you need to create separate directory f.e.
~/development/myplugin
there you will have file myplugin.c. Compilation is done with command:
gimptool-2.0 --install myplugin.c
this is done from console and you must be in that directory.
That is all, after this gimp will recognize newly created binary file. (it is automatically placed in ~/gimp-2.6/plug-ins/)
Ask what is not clear for you.
Progress!
That's exactly what I needed to know. Thanks! It's always so nice to ask for help and find helpful people. I really appreciate this.
Now it seems I'm missing some env variables. I ran against a modified version of whirl-pinch.c by running:
gimptool-2.0 --install whirl-pinch.c
...and got this:
~/dev/gimp/whirl-pinch$ gimptool-2.0 --install whirl-pinch.c
gcc -pthread -I/usr/include/glib-2.0 -I/usr/lib/x86_64/eldrich/.gimp-2.6/plug-ins/whirl-pinch whirl-pinch.c -pthread -L/usr/lib/x86_64
whirl-pinch.c:48:20: fatal error: config.h: No such file or directory
compilation terminated.
Is there a gcc or gimptool configure that needs to be run in order to set things up correctly? I think I could get it to run with additional gimptool options, but I'd rather fix the env than have to do that every time or alias in a bunch of clunky args.
no variables. It is header
no variables. It is header file config.h. It seams somewhere on the top of your .c file there is '#include config.h', and it seems that it is a file that belong to whirl-pinch and you had to put it into your working directory, but it is not there. Of course, it is a guess only, you must look into your .c file and find relevant line to see...
Yes, but...
The whirl-pinch.c file references a number of headers, all of which are existing files in the GIMP source, and are not part of the plugin. They are:
#include "config.h"
#include
#include
#include "libgimp/stdplugins-intl.h"
It doesn't seem to know where to look for them, which makes me wonder if my source is installed correctly. How did you grab your source? I'm afraid I just downloaded and unzipped mine, so there's no way for the compiler to implicitly know where to look for the includes.
There's also a chance that I'm having this problem because I grabbed a plug-in from the default included set, and they're compiled slightly differently than externally included plug-ins. A from-scratch plug-in might not need the explicit includes.
I'll fiddle with things a bit. Thanks again, though.
I found this at
I found this at
Incidentally, the difference between the two forms of the include statement #include "FILE.h" and #include <FILE.h> is that the former searches for ‘FILE.h’ in the current directory before looking in the system header file directories. The include statement #include <FILE.h> searches the system header files, but does not look in the current directory by default.
(Current comment system strips some characters, so your lines with includes were damaged, it seems.
It is sufficient to make source of plugin as a single file, but author might decide to split the file and create also header file. Make sure you read Readme and Install files (if any) in your source tarball.
I've got it running for now.
I'm aware of the difference between referencing files from local directories versus common dev directories. I'm just not familiar with what needs to be done to add the gimp dev directories to the shared libraries. For now, I'm just moving my code into the root gimp source directory prior to running gimptool, and that's working. If I can fix it later, I will, but if not, this will at least let me start coding.
Thanks for the assist! Hopefully I'll have something nifty to post to the plugin registry soon!
gimp plugin template
Did you try the template? (a hollow shell of a C plugin for GIMP.) The purpose of the template is to provide a canonical build environment.
I haven't used it in a while. It might be a good starting point, that doesn't require any futzing with env variables and libraries. It does use the GNU build system (automake, configure, etc.) which can be daunting.
So basically:
install (say using Synaptic) the gimp-dev package to get the gimp development libraries (and the gimp build tool?)
download plug-in-template and unarchive it to a new directory
cd to that directory
> ./configure
> make
> make install
Then hack the template and remake.
do not use those.....
Don't use the existing gimp plugins included with the gimp distribution source as a starting point for your own plugins, as they are written up to be compiled along with the gimp source tree and have dependencies that would NOT be included when using gimptool.
A great example is "libgimp/stdplugins-intl.h". I was told on the dev list a 3rd part plugin should never include this, instead it should provide its own i18n headers as required.
-Rob A> | http://registry.gimp.org/comment/12967 | CC-MAIN-2014-52 | refinedweb | 1,451 | 75.3 |
Sherpa User Models
Sherpa Threads (CIAO 4.7 Sherpa v1)
Overview
Synopsis:
It may be necessary to fit data to a function that is not pre-packaged as a Sherpa model; to do so, we may write that function as a Python, C or C++, or Fortran function and assign it to a Sherpa 'user model'. User models are those for which the user specifies the parameters and model calculation function. 'Table models' can also be defined in Sherpa these contain data read from a file, and have only one parameter, normalization. When the table model is "calculated", the model returns the data - or more generally, some calculated values based on those data values. In this thread, examples of user models are shown; for table models, see the thread "Sherpa Table Models."
Last Update: 3 Apr 2014 - added comment about sherpa.astro.ui line only necessary for Python environment.
User Models
Assigning a Python Function to a User Model
Here, we consider the most simple example: a 1D user model that contains the equation for a line, y = mx + b. To implement such a model in Python, we would write the function as follows:
def myline(pars, x): return pars[0] * x + pars[1]
This function would be written to a file, such as "myline.py". The name of the file is arbitrary, and does not have to match the name of the function it contains. Indeed, we could write several such user functions to a single file.
Next, we must import the new user function into a Python fitting session. A simple example script might look like this:
from sherpa.astro.ui import * ##line only necessary in native (i)Python, unnecessary in a Sherpa environment from myline import * load_data(1, "foo.dat") plot_data() load_user_model(myline, "myl") add_user_pars("myl", ["m","b"]) set_model(myl) myl.m=30 myl.b=20 fit() plot_fit()
A plot of the user model fit to the data contained in 'foo.dat' might appear as shown Figure 1.
Figure 1: Plot of user model fit to the data contained in 'foo.dat'
After the Sherpa package is imported, we must first import the user function stored in the file "myline.py". But this only makes the function accessible to Python; it must then be attached to an instance of the new user model class.
This is done by the call to the function load_user_model, which is similar to the register_model function from the CIAO3 version of Sherpa. In load_user_model, an instance of the user model class is created and named "myl". The model can then be referred to as "myl" for the rest of the fitting session (as is done when it is passed as an argument to set_model). The user function "myline" is also assigned to the object "myl".
The load_user_model function has two required arguments: a reference to the user function, and the name of the instance of the user model class.
load_user_model(func, modelname) func = Reference to user function (reference) modelname = Name of model (string)
A second function, add_user_pars, is then used to attach model parameters to this instance of the user model class. The number of user model parameters, their names, values and ranges, are all completely arbitrary - we can assign any names and values we wish. The only required arguments are the name of the model, "myl" in this case, and a list of model parameter names. Lists of initial values and ranges can also be passed in as additional optional arguments.
In this example, two parameters are created with add_user_pars: "m", and "b", the slope and y-intercept of the line function. After the calls to load_user_model and add_user_pars, we can refer to "myl.m" and "myl.b" just as we refer to model parameters pre-packaged with Sherpa. (We must ensure that when calling add_user_pars, the parameters "m" and "b" are given in the same order that the function "myline" expects. That is, in the "myline" function, pars[0] is clearly the slope, and pars[1] the y-intercept. Therefore, in the call to add_user_pars, the names of the parameters should be given as ["m", "b"], and not as ["b", "m"].)
The add_user_pars function has two required arguments: the name of the instance of the user model class, and a list of the model parameter names. It is also possible to pass initial parameter values and ranges as optional arguments:
add_user_pars(modelname, parnames, parvals, parmins, parmaxs, parunits, parfrozen) modelname = Name of model (string) parnames = List of names of model parameters (list of strings) parvals = List of initial parameter values (list of numbers) parmins = List of soft parameter minima (list of numbers) parmaxs = List of soft parameter maxima (list of numbers) parunits = List parameter units (list of strings) parfrozen = List of thaw flags (list of True or False values)
Only the first two arguments to add_user_pars are required. To assign initial values, units, and thaw flags to this example, we could call add_user_pars as:
add_user_pars("myl", ["m","b"], [30,20], parunits=["cm/s","s"], parfrozen=[True, False])
Once the user function has been imported, the user model created with load_user_model, and parameters added to it with add_user_pars, then the model can be used just as any pre-defined Sherpa model.
The function add_model is available as an alternative to using load_user_model together with add_user_pars for explicitly defining user models as Python classes for use in Sherpa. The add_model command registers a user-defined Sherpa model class as a Sherpa model type, to allow users to create instances of models that are recognized automatically in Sherpa model expressions.
sherpa> from sherpa.models import PowLaw1D sherpa> class MyPowLaw1D(PowLaw1D): pass sherpa> add_model(MyPowLaw1D) sherpa> set_model(xswabs.abs1*mypowlaw1d.p1)
In the example above, the Python class 'MyPowLaw1D' is defined, which inherits from the Sherpa 'Powlaw1D' model class. 'MyPowLaw1D' is registered as a Sherpa model type for use in Sherpa model expressions using add_model. The model expression for data set 1 is then set in the usual way, using the newly defined model type.
2D User Model Example
In the example above, we stepped through the details of defining a simple 1D function and assigning it to a user model in Sherpa; in the next example, we show that in a similar way, it is also possible to define 2D user models in Sherpa.
First, we define a 2D function in an external file; in this example, we define a simple Gaussian function in a file called mygauss2d.py (which we could also choose to define directly in a Sherpa Python fitting session):
import numpy as np def mygauss2d(pars,x,y): (sigma, ampl, xpos, ypos) = pars r2 = (x - xpos)**2 + (y - ypos)**2 return ampl*np.exp(-r2/(sigma*sigma)
Then, we write a simple script, like the one shown below, to import the user-defined Gaussian function into a Sherpa Python session, assign the function to a user model with the load_user_model and add_user_pars commands, and then fit the newly defined Gaussian user model to a loaded 2D data set:
from sherpa.astro.ui import * ##line only necessary in native (i)Python, unnecessary in a Sherpa environment from mygauss2d import * load_user_model(mygauss2d, "g2d") add_user_pars("g2d",["sigma", "ampl", "xpos", "ypos"],[5,1,1,1],[0.1,0,0,0]) print(g2d) load_data("image.fits") set_source(g2d) image_fit()
In this script, the optional third and fourth arguments of add_user_pars() are used to set up both the starting and minimum values of the parameters.
Assigning a Fortran Function to a User Model
Above, we showed examples of a user-written functions in Python. It is also possible to write functions in a compiled language, compile the code, and then wrap the functions so that they are accessible from Python. We have added support so that functions written in C or Fortran can be attached to an instance of the user model class. First, we will show how this is done for a Fortran model function.
Sherpa is built with the 'numpy' module, which adds support for arrays to Python. numpy also provides a tool called "f2py"; given a file containing a function written in Fortran, f2py will compile the code, put it in a shared library, and then automatically write a Python module that can import that shared library into a Python session.
Consider the equation for a line, this time written in Fortran:
integer function myline(p, x, y, xsize) integer i, xsize real*8 p(*), x(xsize), y(xsize) myline = 0 do i=1,xsize,1 y(i) = p(1) * x(i) + p(2) enddo return end
Suppose the file "myline.f" contains this code. The first step is to use f2py to compile the code and provide a Python interface:
% setenv F77 /usr/bin/g77 % setenv CC /usr/bin/gcc % f2py -m myline -c myline.f
Setting the environment variables F77 and CC is to ensure that the desired versions of the Fortran and C compilers are found by f2py. In the call to f2py, two options are used: "-c", to compile the Fortran code and generate the Python module from which it will be called; and "-m", to give that module the desired name (without this option, the resulting module is given the name "untitled").
This enables us to call the raw Fortran function from Python. However, the function called from the user model has to have a certain signature - that is, certain arguments given in a particular order - and the function defined in myline.f does not have that signature. Fortunately, it is easy to write a Python "wrapper" function with the proper signature.
To continue with this example, create a Python file called "mypyline.py" containing the following code:
import numpy import myline as ml def mypyline(pars, x): y = numpy.zeros(x.shape, type(x[0])) ml.myline(pars, x, y, len(x)) return y
In this Python code, we begin by importing numpy and myline. We then define the wrapper function "mypyline". For a 1-D function, mypyline must accept an array of parameters and an array of x-values, create a y-array of equal size to the x-array, and then return the y-array. The function "numpy.zeros" is used to create an empty y-array, of the same shape and size as the x-array. The "myline" module is imported, and given the name "ml" in this example. This is just to distinguish the name of the module from the function that the module contains; in this case we named the function myline as well.
At this point, we have compiled the Fortran function and written a Python interface the user model can accept. All that remains, then, is to create a user model and attach this function to it:
from sherpa.astro.ui import * ##line only necessary in native (i)Python, unnecessary in a Sherpa environment import mypyline as mpl load_data(1, "foo.dat") plot_data() load_user_model(mpl.mypyline, "myl") add_user_pars("myl", ["m","b"])
As shown, in the Sherpa session we import the wrapper function we defined, "mypyline"; this provides a reference to a model function with the correct arguments in the correct order. The "mypyline" function takes care of importing the Fortran code when needed and calling the user-written function.
We may run f2py on an arbitrary number of Fortran files at the command line. Thus, the module created by f2py can provide access to any number of Fortran functions; we need only import that module once to access all the functions.
Assigning a C/C++ Function to a User Model
see also Sherpa User Models in C
The code to be compiled may have been written in C or C++ instead of Fortran. The procedure for compiling such a function and attaching it to a user model is similar to the procedure for attaching a Fortran function. However, numpy does not provide a nice tool like "f2py" for compiling the C code and providing a Python interface. The reason for this is that there are other tools to automatically generate Python extensions for C code. The most well-known of these is SWIG. So instead of providing his own tool to do this, the numpy author provides an instruction file which SWIG uses to create an interface between Python and C that understands numpy.
The Sherpa team has taken a different approach. Instead of using SWIG or a similar tool, we provide our own interface code for users to incorporate into a C extension containing the user function. The reason is that SWIG generates a lot of overhead which is not necessary when "wrapping" a single C function for Python access. So the Sherpa team provides the interface code and uses the Python distutils module to compile the C code and create a new Python module from which to call it. Please download the tar file usermodel.tar.gz (9.5 KB tarred & gzipped; 87 KB unpacked) for the Python/C interface code we provide for C user models. The package contains the following files:
array.hh glue.hh setup.py userfuncs.cc
The files "array.hh" and "glue.hh" needn't be touched at all; these files define the interface for passing numpy arrays from Python to C code, in the order that Sherpa expects for model functions. The file "userfuncs.cc" is the file that we do need to touch, but only to add the function signature of our C function; we will arrive at this step momentarily.
First, we add our C model function in a new file, named as we please. Let's consider the line function again; a new file, "myline.c", is added, with the following function:
#include <stdlib.h> #include <math.h> #include <float.h> int myline(const double* p, const double* x, const int xsize, double* y, const int ysize) { int i; for (i=0; i < xsize; i++) { y[i] = p[0] * x[i] + p[1]; } return EXIT_SUCCESS; } int myline_int(const double* p, const double* xlo, const int xlosize, const double* xhi, const int xhisize, double* y, const int ysize) { // If not implemented, leave this function empty and return success return EXIT_SUCCESS; }
Here, we define two function signatures: myline, which is passed an array of x-values, and myline_int, which is passed arrays of bin boundaries (low and high bounds of the bins in x). Thus we can create integrated and non-integrated forms of the same function; signatures for BOTH forms must be provided. If we are not interested in implementing one or the other function, we can just have it return EXIT_SUCCESS. In this example, we will concentrate on using the non-integrated form in the function myline.
Having written this C function, the first step is to include the proper function prototype in userfuncs.cc. Since userfuncs.cc is a C++ file, we must include information that identifies myline as a plain C function. This is done using extern in userfuncs.cc:
extern "C" { int myline(const double* p, const double* x, const int xsize, double* y, const int ysize); int myline_int(const double* p, const double* xlo, const int xlosize, const double* xhi, const int xhisize, double* y, const int ysize); }
(If the function had actually been written in C++, then the 'extern "C"' block would not be used; we would simply include the C++ function prototype here instead.)
In the next section, we simply add the name of the function to the array of function definitions Python will know about when this module is imported into Python:
static PyMethodDef UserFuncs[] = { USERMODELFCT1D( myline, 2 ), { NULL, NULL, 0, NULL } };
The first argument to USERMODELFCT1D is the name of the function, myline; the second argument is the number of model parameters, which is two for the equation for a line. At this point, we are done touching C and C++ files.
At this point, we need only edit "setup.py" and add the name of the C file to the list of files to be compiled. To add myline.c, we edit this line of the file:
ext_modules=[Extension('userfuncs', ['userfuncs.cc'],
so that it now reads:
ext_modules=[Extension('userfuncs', ['userfuncs.cc','myline.c'],
We are now ready to use the Python distutils module to create a Python module for us, to provide access to the myline function. This C extension module will always be named "userfuncs", as noted above by the first argument to the "Extension" function. From the Unix command line, do:
% setenv CC /usr/bin/gcc % setenv CXX /usr/bin/g++ % python setup.py install --prefix=. % setenv PYTHONPATH ${PYTHONPATH}:${PWD}/lib/python2.4/site-packages
This does several things. First, the paths to the C and C++ compilers are set by the CC and CXX environment variables. Next, the module userfuncs will be created and installed in the current working directory. Finally, PYTHONPATH is set to look in the current working directory so that the userfuncs module can be found. (If the module should be installed elsewhere, simply set the --prefix flag and PYTHONPATH to the desired directory.)
Now the user-written function exists in a Python module, and has already been given a function signature that Sherpa understands. The function can be attached to a user model:
from sherpa.astro.ui import * ##line only necessary in native (i)Python, unnecessary in a Sherpa environment import userfuncs load_data(1, "foo.dat") plot_data() load_user_model(userfuncs.myline, "myl") add_user_pars("myl", ["m","b"])
Please note that for simplicity, we have used a single function - the equation for a line - in this example. We may add as many user-written functions to the userfuncs module as we wish. The functions simply need to be listed in userfuncs.cc and setup.py. If we were to add ten functions to the userfuncs module, they would all be available after importing the userfuncs module once (we would need to call load_user_model ten different times, to attach a different user function to ten different instances of the user model). Please see the thread Sherpa User Models in C for additional comprehensive examples of how to write your own Sherpa parameterized models in C, and include them in a Sherpa Python fitting session. | http://cxc.cfa.harvard.edu/sherpa/threads/user_model/ | CC-MAIN-2015-14 | refinedweb | 3,018 | 60.14 |
.
Isn't this a proper way of writing a code?
works fine, but not sure if it is a correct way or not. please reply.
#include<iostream>
int main()
{
std::cout<<"Enter any 2 real numbers:"<<std::endl;
double a,b;
std::cin>>a;
std::cin>>b;
std::cout<<"Select any symbol from +,-,*,/"<<std::endl;
char symbol;
std::cin>>symbol;
if(symbol=='+')
std::cout<<"The sum of the number is:"<<a+b<<std::endl;
else if(symbol=='-')
std::cout<<"The substraction of the number is:"<<a-b<<std::endl;
else if(symbol=='*')
std::cout<<"The multiplication of the number is:"<<a*b<<std::endl;
else if(symbol=='/')
std::cout<<"The division of the number is:"<<a/b<<std::endl;
return 0;
}
Hi Ritesh!
Other than you not initializing your variables the code is fine.
PS: Please use CODE tags when sharing code
The variables are taken from the user, right?
Then why to initialize them?
here, variables are a,b,symbol.
If you ever forget to assign a value to the variables before using them you'll get undefined behavior. This is a pain to debug. To avoid this, you should always initialize your variables.
If the user enters invalid input (e.g. you're asking the user for an int and they enter A), then the user input will fail to assign a value to your variable. And thus your uninitialized variable will remain uninitialized, and potentially cause problems down the road.
Question 3.
What do you think of this code?
Sorry for being so annoying, but I wanna see if an expert can give me some hints.
Hi Tony!
Pretty good code, I added some comments
It would have been better to calculate the result in @symbols and return it to prevent repeating almost the exact same line 4 times.
Thank you a lot. That helped a lot! 😀
Dear Alex,
here is my last code I could come up with:
would you be so kind and help me out, please? something is wrong with my code.
Your error is on this line:
distanceFallen is the address of the function. What you want is to call the function and print the return value. Therefore, you want this instead:
Then you need to fix your distanceFallen() function. The first parameter (dFallen) should be a local parameter, and you have an early return that will cause the function to not print anything.
I am starting to get fed up with it. and also I am giving up on it please run it on your pc and see the results:
constants.h
main.cpp
I corrected all issues, look at the code carefully and compare it to your code.
BUT the output is still showing 5 seconds all over
anyway thx for your help 😉
Line 45 and 49 should output @i instead of @secs, I missed that.
I made my program like this and it output the correct heights. My question is what benefit is there to making it so that it is like the solution code vs mine?
Hi Shafi!
DRY (Don't repeat yourself)
Let's say you want to simulate the fall for 100 seconds, what are you going to do? Paste the same line 100 times? That's not good.
Notes:
Line 10: 2 should be 2.0, because you're dealing with doubles
Line 17: Initialize your variables
But in the solution the admin gave he also had it where he would have to repeat himself if it were to fall for 100 seconds. He did say though that we will improve this later with loops. I was wondering if where I'm at right now is the program ok? I understand i can improve it with loops though but im not there yet. In his solution, he made functions for every calculation and to print it. Is there a benefit if you made functions for everything vs what i did? Thanks!
Oops, sorry I didn't notice loops weren't covered yet.
In that case you should still write a function to print the height at x seconds.
This will make updating the text easier and it will reduce the size of your binary.
Hi Alex,
I have re-read the section 1.4a carefully and didn’t get use of it (I think the problem might be with my english knowledge). would you please correct my calls in main?
Hi nascardriver,
I tried everything possible but it still produces the same output...
Line 13: Unused variable @tHeight
Line 35: You're outputting the same value for @dFallen 6 times.
Line 39: Unused function @distanceFallen
Line 39: Unused parameter @secs
dear nascardriver
here is my last code i could coome up with:
if you are not willing to help me then please do not interrupt my correspondence and Alex’s
why does not my code work? I haven't revealed the answer yet. And it's bugging me because I can not move on or can I?
// ball gravity.cpp: Defines the entry point for the console application.
//
#include "stdafx.h"
#include "constants.h"
#include <iostream>
int seconds(int);
double distanceFallen(double);
int userInput();
int main()
{
int tHeight = userInput();
//std::cout << tHeight;
int secondss = seconds(int secs);
double distfallen = distanceFallen(double);
return 0;
}
int userInput()
{
int tHeight;
std::cout << "Enter a tower height in meters: ";
std::cin >> tHeight;
return tHeight;
}
int seconds(int secs)
{
for (secs = 0; secs <= 5; secs++)
{
std::cout << "At" << secs << "seconds the balls height is" << distanceFallen(double dFallen);
}
return secs;
}
double distanceFallen(double dFallen)
{
dFallen = 0;
dFallen = (constants::gravity*seconds(int secs)*seconds(int secs)) / 2;
if (dFallen >= 0)
std::cout << dFallen;
else;
return dFallen;
}
Hi Ali!
All your function calls are wrong, you aren't supposed to pass a type but a value.
This is covered in lesson 1.4a
Please use CODE tags when submitting code
How can i do code tags?
[-CODE]
// Your code here
[-/CODE]
Without the -
thank you that is useful to know 🙂 and where was it written?
What are you talking about?
nvm
Dear nascardriver,
Woud you be soo kind and pkease correct the code that i wrote?
You can take a peek at the solution to see how it's done and fix your function calls.
Dear nascardriver, now I get it when u use a function in a function you need to argument it right? but i still can not call it in main can you help me with it?
You're still doing the same mistake. When you want to call a function you need to pass arguments. In your case, when you want to call @seconds you need to pass an int and a double. eg
Do yourself a favor and re-read lesson 1.4a
I have re-read the section 1.4a carefully and didn't get use of it (I think the problem might be with my english knowledge). would you please correct my calls in main?
Thanks again. I understood the point. But it comes by default while using Codeblocks IDE.
Dear Alex, Any recommendations for a better coding. Thanks.
Hi ASP!
I modified your code and added comments. I like that you split your program into several functions, this is good practice.
It seems like you insert spaces and empty lines whenever you feel like it, you should decide on a formatting style and stay with it.
Thank you Nascardriver. I learnt few new things. But why namespace std should not be used?
You can use the std namespace, but don't use 'using namespace xyz;', because the contents of a namespace might intersect with functions from elsewhere.
Imagine being in a room with hundreds of people and you want to call someone, do you shout 'John!' or do you shout 'John Doe!'? (In this case Doe is the namespace and John is a function)
Hey Alex, got my ball height calculations sorted, and feeling pretty good about the code. Any chance I could get a few pointers on how to improve? I realize the comments are a bit of mess, just have them there because working everything out was a proper challenge. Awesome work, thanks for everything you do!
1) Avoid global variables (in your case, startHeight). If main needs to get startHeight to a function, pass it in as a parameter.
2) I find it useful to separate "calculation" functions from "output" functions, so that if you need the result of a calculation but don't want to print that result, you can. Your fromGround() function does both, which isn't as modular as it could be.
3) fromGround() isn't a very good function name. printHeightFromGroundAtSecond() would be better.
4) std::cin.ignore() with no parameters won't work to pause the input if there are multiple characters unextracted from in the input stream. Use std::cin.ignore(32767, '\n');
This is how I did question 3. Is there anything wrong?
The only thing I see that catches my eye is the fact that you have a function named "showResult" that asks the user to input a char value. I wouldn't expect a function named showResult to do that.
It would be better if there was a separate function to ask the user for a char input. Then you can pass all three values (the two doubles and the char operator) to showResult.
Ok sir, Thx for the reply
After rading it all cant do question 3, let alone question 4. Not sure if coding is for me 🙁
If this is your first time programming, then don't worry. Try your best and then look at the answer until you really understand it. Also, if you think about anything else that is not clear, make changes to your program to see what happens.
This is the way that everyone learns, so don't get too discouraged!
Why it doesn´t runs?
Hi Weckersduffer!
You're missing semicolons in line 10 and 11.
In line 4 you need to add the data type of sec.
Also, the ^ operator is not the power function you're used to from math, use sec * sec instead.
Thanks, but I continue having errors. Maybe the "calc" function?
Your compiler will output an error message. For your code it will output something like
It tells you where the error is: "function main, line 16, column 78".
It tells you what the error is: "I don't know what calcu is".
The error message still appears
Your code compiles for me. What is the error message?
The same as before:
I use Code::blocks
That's odd, did you save the file before compiling? It looks like at one point you spelled calc with a capital 'C' and the compiler is trying to compile that version.
Enter the height of the tower in meter:
100
At 0 seconds, the ball is at height: 100 meters at speed: 0 m/s.
At 1 seconds, the ball is at height: 95.095 meters at speed: 9.81 m/s.
At 2 seconds, the ball is at height: 80.38 meters at speed: 19.62 m/s.
At 3 seconds, the ball is at height: 55.855 meters at speed: 29.43 m/s.
At 4 seconds, the ball is at height: 21.52 meters at speed: 39.24 m/s.
At 5 seconds, The ball is on the ground at max speed is: 49.05 m/s.
Name (required)
Website | http://www.learncpp.com/cpp-tutorial/210-comprehensive-quiz/ | CC-MAIN-2018-13 | refinedweb | 1,908 | 74.29 |
================================================== Changes from 2018-03-30 00:00:00 +0000 to present. ================================================== ---------------------------------------- version 1.8 at 2020-03-29 17:40:24 +0000 ---------------------------------------- Change: a50996aee321069d7b3eceee2b5f90ff4d59c9ff Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2020-03-29 10:34:32 +0000 Disable @ARGV processing during initialization The previous release disabled `@ARGV` processing everywhere except when imported from the `main` namespace. This continues that work by disabling the preprocessing of `@ARGV` entirely. This switches the behavior of the module to `delay_argv`. It's still possible to preprocess the `@ARGV` during the runtime by using: ``` use CLI::Helpers qw(:preprocess_argv output); ``` Otherwise, the processing of `@ARGV` will happen at the first call to a function which needs it. This is generally safer as it prevents interference with other processing of `@ARGV` by scripts and modules. Also corrected the option processing parameters so options requiring a value declare it correctly. ---------------------------------------- version 1.7 at 2019-12-12 20:09:23 +0000 ---------------------------------------- Change: 0b5fe2c5ebcb16d8115db6e4e714567f4e7adb5a Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2019-12-12 12:09:23 +0000 Remove Sub::Exporter and handle import locally Sub::Exporter is awesome, but I needed to provide a custom `import()` function to be able to detect the importing package and change the default behavior. I had attempted this with `Hook::LexWrap`, but that caused unexpected issues with the `import()` routine in certain situations. This code is cleaner, has fewer deps, but lacks the extended functionality of `Sub::Exporter`. Change: f8cbb98a7c2445eff7b69a88f962e9cdc5b8a02a Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2019-12-05 13:15:02 +0000 Add basic testing to the distribution Change: 54e693928bcc50fb8212e21a9072ab84dee350e2 Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2019-12-03 13:55:24 +0000 Change default behavior if importing outside of main It doesn't make much sense for a module you're including to mess with `@ARGV` by default. This patch uses `Hook::LexWrap` to wrap `import` and check the calling package. If the calling package is `main`, we'll do the `@ARGV` parsing by default. If it's not, we'll skip the initialization until it's used. You can override this behavior if you specify: package YOLO; use CLI::Helpers qw(:output at_import); In the module. Change: 63c285e75f3c34aa0700b9252fe8b2f8e5d0a398 Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2019-12-03 08:35:27 +0000 Alternative initialization with an array * Instead of initiliazing solely on `@ARGV`, `cli_helpers_initialization` may now be called with an array reference. If so, it'll process that array instead of messing with the global `@ARGV`. * Add an `at_import` import time configuration. This is the default, but if the default behavior changes, this configuration will ensure it's always handled correctly. Change: 771ed53929d0670e276616b874bead399954862d Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2019-12-02 21:50:13 +0000 Handle @ARGV Smarter This release adds the ability to delay `@ARGV` processing until it's necessary through the `delay_argv` import option. Alternatively, a user can import with `copy_argv` flag to make `CLI::Helpers` operate on a copy of `@ARGV`. A `global_argv` import option has been added as well. This is a flag to enable what is now the current behavior, operating on the global `@ARGV` at import time, unless `delay_argv` is specified. Migrate all the argument processing into it's own `cli_helpers_initialize()` function. This is called during import unless `delay_argv` is passed as an import flag. ---------------------------------------- version 1.6 at 2019-06-25 02:24:08 +0000 ---------------------------------------- Change: ebc44e2e79fd7fc99fc1c810ea2ebfa630e97db7 Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2019-06-24 19:24:08 +0000 Default to sane privacy settings * An explicit --nopaste-service OR environment variable (NOPASTE_SERVICES) must be present for the paste to happen. * Default all pastes to private unless the --nopaste-public option is specified. * Process --tags before the `kv` option is processed * Instead of using `@input`, use a color stripped `@output` for the content of the paste ---------------------------------------- version 1.5 at 2019-06-24 16:33:14 +0000 ---------------------------------------- Change: c138ce745818524db2ce8f4193b2d5c5ee16640d Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2019-06-24 09:33:14 +0000 Version 1.5 to fix handling of service pass through To facilitate both environment variables and a sane default of a working paste service, I reworked how the `service` parameter is passed to `App::Nopaste`. Now the correct thing will happen given: * `$ENV{NOPASTE_SERVICES}` is set it will be used unless * `--nopaste-service` is set, in which case it'll be parsed as comma separated list * Barring those cases, `App::Nopaste::Service::Shadowcat` will be used ---------------------------------------- version 1.4 at 2019-06-22 04:16:30 +0000 ---------------------------------------- Change: c5891e80dab8a6426fa7c2a2f599e33857be0e0b Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2019-06-21 21:16:30 +0000 Release Version 1.4 Ready * Adding --tags to support selective output using tagged messages * Add optional App::Nopaste support to the module * If App::Nopaste is installed and --nopaste is specified paste to Shadowcat * Convert from IPC::Run3 to Capture::Tiny * Documentation and testing updates Change: 423e3c5dadb8d00151cf9038715b8e5b86f3acc0 Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2018-11-12 21:27:46 +0000 POD and test fixups POD spelling and tests fix-up. Change: d06aaad52cc48dbf611654ec67dbab66b7e8639f Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2018-11-12 21:18:03 +0000 Add spelling checks Change: 51122cb1672978d31f0993311f98a1284aaafd2a Author: Brad Lhotsky <brad@divisionbyzero.net> Date : 2018-11-13 06:17:05 +0000 More fixes for dist.ini ================================================= Plus 13 releases after 2018-03-30 00:00:00 +0000. ================================================= | https://web-stage.metacpan.org/release/BLHOTSKY/CLI-Helpers-1.8/source/Changes | CC-MAIN-2022-05 | refinedweb | 883 | 55.54 |
Introduction
In this blog post, you will learn how to create a React app and WebSocket that connects to the Flask server, and visualize streaming data in real-time using D3.js. I decided to write this blog post as a part of my learning path, and I hope to help anyone struggling with the same problems while trying to implement something similar. I decided to tackle on the frontend implementation by visualizing Twitter users who retweeted something with the hashtag #christmas. Each community of users is presented with a different color which allowed me to notice the important communities in the Twitter network.
The frontend service is a part of a web application that you can find in the GitHub repository. Besides that, the repository also holds a visualization that discovers the most Christmassy person on Twitter using the dynamic PageRank algorithm.
Prerequisites and app architecture
If you are using Windows, you need to install Windows Subsystem for Linux (WSL) and then Docker Desktop. On the other hand, if you are a Linux user, just install Docker and Docker Compose.
The app is dockerized and it consists of five services:
stream: A Python script collects new retweets with the hashtag #christmas and sends them to a Kafka cluster.
kafka: A Kafka cluster consisting of one topic named
retweets.
memgraph-mage: The graph analytics platform where we store the incoming Twitter data from Kafka and perform dynamic PageRank and dynamic community detection on all Twitter users.
backend-app: A Flask server that sends all the data we query from
memgraph-mageto the
frontend-app. It also consumes the Kafka stream and sends it to the
frontend-app.
frontend-app: A React app that visualizes the Twitter network using the D3.js library.
Project structure
You can see the whole project structure in the GitHub repository. The blog post focuses on the frontend service and explains how the visualization was created.
| docker-compose.yml | +---backend | Dockerfile | +---server | +---tests | +---frontend | | .dockerignore | | Dockerfile | | package.json | | package-lock.json | +---node_modules | +---public | +---src | +---memgraph | | Dockerfile | | requirements.txt | +---procedures | +---transformations | +---stream | | Dockerfile | | kafka_utils.py | | produce.py | | requirements.txt | +---data
The
frontend folder was created using the
create-react-app
npm package. If you are starting from scratch and want to create a React app follow these steps:
- Place yourself in the root folder of your project.
- Run
npm install -g create-react-app(if you don’t want to install the latest version, you can specify the version of the
create-react-app, for example,
- Next, run
npm init react-app frontend --use-npm, which will initialize the
react-apppackage in the
frontendfolder.
- In the end, place yourself in the
frontendfolder by running
cd frontendand start the app with
npm start.
Even a simpler way of creating a React app is by using
npx - a package runner tool that comes with
npm 5.2+. Then you just have to run:
npx create-react-app frontend cd frontend npm start
Socket.IO library
I have used
[email protected] since I had issues with the latest version. I am going to explain the process on the
CommunityDetection component, since it’s very similar to the
PageRank component. If you are running the frontend application locally, and not using the provided dockerized application, make sure to install the library by running:
npm install [email protected]
Don’t forget that Node.js is a prerequisite for using
npm.
First, we are going to import the socket we’re using on the client side. Backend is implemented with Flask.
import io from "socket.io-client"
After that, we are initializing the socket.
var socket = io("", { transports: ["websocket", "polling"] })
We set the socket to listen to the server running at. Then we established the connection to the server with
websocket first. If
websocket is not available, connection to the server will be established with
HTTP
long-polling - successive
HTTP requests (
POST for writing,
GET for reading). Next, we need to handle different events with our socket are handled. When the connection is established, the socket is emitting the
consumer signal. This signal is also emitted on the server side, whenever a new message is sent. This configuration allows the socket to receive all messages related to
consumer signal.
socket.on("connect", () => { socket.emit('consumer') console.log("Connected to socket ", socket.id) }); socket.on("connect_error", (err) => { console.log(err) // try reconnecting socket.connect() }); socket.on("disconnect", () => { console.log("Disconnected from socket.") }); socket.on("consumer", (msg) => { console.log('Received a message from the WebSocket service: ', msg.data); }
React.Component lifecycle
You may ask yourself where to place all this
socket.io code within a React component. First, I initialized the socket in the component’s constructor. After that I have placed the socket events in
componentDidMount() lifecycle method. This part of the
React.Component lifecyle is invoked once, immediately after a component is mounted. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. This method is also a good place to set up any subscriptions. That’s why I have decided to place all socket events there. On each
consumer emit, the state of the component will be updated and that will trigger an extra rendering which will happen before the browser updates the screen, so the user won’t see the intermediate state. Before I set up the socket, at the beginning of the
componentDidMount(), I have made a simple
HTTP request that will trigger the backend to start producing the needed data.
firstRequest() { fetch("") .then((res) => res.json()) .then((result) => console.log(result)) }
After that, I initialized everything that was necessary for drawing using
D3.js in the
initializeGraph() method. By setting a new state of nodes and links with
setState() on each
consumer emit,
componentDidUpdate() lifecycle method will be called. In that method we are updating the graph by drawing new incoming nodes and links. This lifecycle method is not called for the initial render, and that’s the reason why we initialized everything in the
initializeGraph() method.
In the end, when the component unmounts (for example, when we click on the button to switch to the PageRank), the
componentWillUnmount() lifecycle method is called and the client disconnects from the server.
componentWillUnmount() { this.socket.emit('disconnect'); this.socket.disconnect(); }
If you want to learn more about
React.Componentlifecycle methods, check out the React official docs.
Visualizing with D3.js
We want to draw the graph on
svg using
D3.js within the class component. We are going to do that by creating a reference in the component constructor which will be attached to the
svg via the
ref attribute. In constructor we have to use
createRef() method.
constructor(props) { super(props); this.myReference = React.createRef(); this.state = { nodes: [], links: [] } this.socket = io("", { transports: ["websocket", "polling"] }) }
Then, in the component’s
render() method we are adding the
ref attribute with value
this.myReference to the
svg.
render() { return (<div> <h1>Community Detection</h1> <p>Number of users that retweeted so far: {this.state.nodes.length}</p> <svg ref={this.myReference} style={{ height: 500, //width: "100%" width: 900, marginRight: "0px", marginLeft: "0px", background: "white" }}></svg></div> ); }
Now, by selecting the current attribute of the reference, it’s easy to get the
svg on which we are going to draw our graph.
var svg = d3.select(this.myReference.current);
If you want to know how to use
D3.jswithin function component, check out one of my previous blog posts - Twitch Streaming Graph Analysis - Part 2.
In the
updateGraph() method we have to draw the nodes and relationships using
D3.js, where nodes will be colored depending on the community they belong to. We are receiving the community information through the
cluster property of each node.
// Remove old nodes node.exit().remove(); // Update existing nodes node = node.data(nodes, (d) => d.id); node = node .enter() .append('circle') .attr("r", function (d) { return 7; }) .attr('fill', function (d) { if (!clusterColors.hasOwnProperty(d.cluster)) { clusterColors[d.cluster] = "#" + Math.floor(Math.random() * 16777215).toString(16) } return clusterColors[d.cluster] }) .on("mouseover", function (d) { tooltip.text(d.srcElement["__data__"]["username"]) tooltip.style("visibility", "visible") }) .on("mousemove", function (event, d) { return tooltip.style("top", (event.y - 10) + "px").style("left", (event.x + 10) + "px"); }) .on("mouseout", function (event, d) { return tooltip.style("visibility", "hidden"); }) .call(this.drag()) .merge(node);
First we are removing the old nodes and setting the
node value to the new nodes data. Next, we want each node to be a circle with radius 7 (that’s just a random value which seemed quite okay to me). After that, we want each node to be colored depending on the cluster it belongs to. We have previously created a map of colors called
clusterColors. When new cluster appears, a new key value pair is created in the map, where key is the cluster number and value is a randomly generated color. If the cluster of the node already exists, then the color of the node will be the value of that cluster key in the
clusterColors map. Then if we want to see usernames on hover, we need
mouseover,
mousemove and
mouseout events. In the next line, we are calling the
drag() method which allows us to drag the nodes. At the end, new nodes are being merged with the old ones with the
merge() method. We will add the links between the nodes in a similar manner. All that’s left to do is to create the simulation on updated nodes and links.
try { simulation .nodes(nodes) .force('link', d3.forceLink(links).id(function (n) { return n.id; })) .force( 'collide', d3 .forceCollide() .radius(function (d) { return 20; }) ) .force('charge', d3.forceManyBody()) .force('center', d3.forceCenter(width / 2, height / 2)); } catch (err) { console.log('err', err); }
Here we are creating the force between the nodes and links, where each link has an unique id which we created by adding the attribute id
.attr('id', (d) => d.source.id + '-' + d.target.id) to each link. That id is created from the id’s of the nodes the certain link is connecting. Collide force is there so that the nodes are not overlapping, considering the size of their radius. Here we have set the radius to size 20, which is larger than 7 - the radius of the nodes. Charge force is causing the nodes in the graph to repel each other, that is, it prevents the nodes from overlapping each other in the visualization. In the end, we have a center force, which is forcing the nodes and links to appear at the middle of the
svg.
And how this actually looks? Check out the
GIF below for the preview, and if you want to start the app all by yourself, follow the instructions at the README in the repository.
The PageRank visualization code is similar, the notable difference is in the radius of each node and the color of the nodes.
node = node .enter() .append('circle') .attr("r", function (d) { return d.rank * 1000; }) .attr('fill', 'url(#gradient)') .on("mouseover", function (d) { tooltip.text(d.srcElement["__data__"]["username"]) tooltip.style("visibility", "visible") }) .on("mousemove", function (event, d) { return tooltip.style("top", (event.y - 15) + "px").style("left", (event.x + 15) + "px"); }) .on("mouseout", function (event, d) { return tooltip.style("visibility", "hidden"); }) .call(this.drag()) .merge(node);
You can see that the attribute
r is proportional to rank (calculated PageRank of each node). Also, the
fill attribute is determined by the
gradient created in the
defineGradient() method.
Conclusion
There is still a lot left to learn regarding the
React,
D3.js and
WebSocket, but creating this demo application gave me a pretty good insight into the real-time visualization. It was fun playing with it, and I’m looking forward to learning more in the future. Also, I would like to emphasize that Reddit network explorer application, developed by my colleagues Ivan, David and Antonio, helped me a lot. There, you can find real-time visualization with frontend in Angular. For any feedback or questions ping me or Memgraph team at our Discord server. | https://memgraph.com/blog/real-time-visualization-with-react-and-d3-js | CC-MAIN-2022-05 | refinedweb | 2,015 | 57.98 |
COSMOS Resource Modeling Meeting Minutes
Minutes for Resource Modeling meetings.
Contents
- 1 Dec 5 2006
- 2 Jan 5 2007
- 3 26 October 2007
- 4 29 April 2008
- 5 13 May 2008
- 6 20 May 2008
- 7 27 May 2008
- 8 3 June 2008
- 9 10 June 2008
- 10 8 July 2008
- 11 15 July 2008
- 12 22 July 2008
- 13 29 July 2008
- 14 5 August 2008
- 15 12 August 2008
- 16 19 August 2008
- 17 26 August 2008
- 18 2 September 2008
- 19 9 September 2008
- 20 16 September 2008
- 21 23 September 2008
- 22 30 September 2008
- 23 7 October 2008
- 24 14 October 2008
- 25 21 October 2008
- 26 28 October 2008
- 27 7 November 2008
Dec 5 2006
- There have been several requests for a SML sample. ACTION: S Jerman to ask SML Group when sample is going to be available. [Done - they will investigate]
- Progress report on Validation, IF inport/export: updates added to Wiki page.
- Next meeting 5th Jan.
Jan 5 2007
Attendees: Mark, Valentina, Steve Discussion:
- Progressing on validator. SML workshop may be delayed which will give more time.
- Need to discuss schedule, interaction with other projects, deliverables at Face2Face. ACTION: Steve to add to agenda.
- Discussed need for more samples.
- Next meeting: 19th Jan
26 October 2007
- Working on documenting interfaces and refining issues related to adopters with different data types
- Working on putting together a demo of our CMDBf extensions
David whiteman.us.ibm.com 14:41, 26 October 2007 (EDT)
29 April 2008
Attendees: Rich Vasconi (IBM), Merri Jensen (SAS), Mark McCraw (SAS), Ali Mehregani (IBM), David Whiteman (IBM)
Discussion:
- Gave brief overview of RM to Merri and Mark, members of the SDD team who are wanting to ramp up on SML
- Started to go through open RM bug list in order to identify high priority items for i11
- Ali and David agreed to split up the investigation and assignment of P1 and P2 defects to determine whether they need a different priority, should be closed, and should be i11 or future.
- When the topic of bug 213635 came up, we discussed how the documentation for SML and other COSMOS areas would be delivered via Eclipse. David explained that the current intent is to provide the whole User Guide and Developer Guide as integrated with Eclipse help. Ali suggested that much of those documents, particularly in the UG, would not make sense in the Eclipse environment, since the actors wanting that information would not be using Eclipse. Rich mentioned that he has the ability to exclude parts of the doc from the Eclipse based online help. David said that it would be tricky to decide what to include and how to package it, and that we should look at how other Eclipse projects handle this. This might need to be revisited at a community call or summit.
- We discussed ideas for restructuring our teams on the project. David suggested that if we were not going to be a toplevel project for 1.0, we can now establish the structure of our "workgroups". He mentioned some ideas he had, most notably breaking up the DC team into two, since there is a significant variance in the scope of that subproject. He also mentioned that part of this activity (or all of it) could be in finding people to lead the subteams that are actively involved in the work on those teams.
- Ali expressed concern that more teams would mean more overhead in the project.
13 May 2008
Attendees: Merri Jensen(SAS), Mark McCraw (SAS), Ali Mehregani (IBM), David Whiteman (IBM)
Discussion:
- No new status to report for RM deliverables, other than what is already on the status wiki page
- David explained to Mary and Mark the current focus of the RM team, which is 1.1 spec compliance and bug fixing
- Mark asked about the Tigerstripe integration, and David pointed out that is future work of interest for building SML resources from graphical templates
20 May 2008
Attendees: Ali (IBM), David (IBM), Mark (SAS), Jason (SAS)
Discussion:
- David suggested SDD meeting should become ME meeting, and that it should precede the community call. Jason to send out new meeting time and subject.
- David suggested possibly should do i11 design review, since we have somewhat gotten out of the practice of reviewing enhancement designs
- Everyone feels comfortable with design process described on the cosmos-dev thread
- Current status is up to date on week 3 build status page
27 May 2008
Attendees: David (IBM), Ali (IBM), Mark (SAS)
Discussion:
- Current status of deliverables
- No status changes to report on RM items since last week
- Ali pointed out that on the release plan, the dev cycle for this iteration ends on June 4, and the test cycle is 3 weeks. We all agreed that it makes sense to lengthen the dev cycle and shorten the test cycle, given that this is no longer the final iteration for 1.0 and that i11 has a focus on stability. TODO: David to raise this issue on community call. David and Ali to meanwhile ensure that high priority i11 items are completed, regardless of the end of the dev cycle.
- John Arwe, SML spec lead, has provided us feedback on possible items for improvement in testing & implementation, and that should result in some additional bug reports forthcoming
- Mark asked for areas where he could contribute to RM and get his feet wet. David suggested that he could look at bug 229890 as a good starting point for validation work, and Ali agreed. Several of the other defects are more related to Eclipse APIs, and bug 232078 is just grunt work to refactor the package names for our API guidelines. David mentioned that CA might be looking to get more involved with RM as well, given its synergy with CMDBf and their participation in the SML workgroup. TODO: Mark will look at 229890 this week and possibly others, and will work with David & Ali to better understand the workitems and to get pointers regarding the RM codebase.
3 June 2008
Attendees: David (IBM), Ali (IBM), Mark (SAS)
Discussion:
- Current status of deliverables
- Ali said he would only be able to get to RM defects during the test cycle and would submit them as patches, due to his enhancement deliverables. These will all be marked as At Risk.
- Mark is making progress on 229890.
- David's remaining SML defects are At Risk due to other responsibilities as well.
10 June 2008
Attendees: David (IBM), Ali (IBM), Mark (SAS), Merri (SAS), Jason (SAS)
Discussion:
8 July 2008
Attendees: David (IBM), Ali (IBM), Mark (SAS), Hubert (IBM), Jason (SAS)
Discussion:
- Introduced Mark to Hubert
- Hubert is setting up SML development environment, and will also read SML specs
- Mark is entering new defects today based on problems and observations he made during i11
- Ali has completed PSVI rework on acyclic builders, validator, and tests. He is modifying document builders to be aware of SML-IF bindings.
- David is working on the substitution builder for the target builders. He also is determining why target instance builder test is failing on IBM JRE. Apparently Xerces needs to be ahead of the JRE on the bootpath. David has the todo to confirm we are legally clear to prereq Xerces.
15 July 2008
Attendees: David (IBM), Ali (IBM), Hubert (IBM)
Discussion:
Status:
- Hubert looked at removing dependencies for SML MDR. He was able to reduce them, especially in the web services. After that we still have some Eclipse dependencies, most of which are EPL. One of them is an OSGi bundle with 3rd party code. Hubert is checking to see if we need an IPZilla for it. The build script has changed to not package the jars and plugins that are not needed.
- Hubert is looking at locid feature. He has made some progress and is looking for some clarifications, from us and maybe John.
- Ali met with Sandy Gao about the validators. He found that our schema bindings should be interpreted differently, that each schema binding should be treated as one validation set, done one at a time. Any references between the sets should be raised as invalid. This requires changes in our framework code. Ali is trying to minimize disruption to the data builders. The net is we might need to parse through a document multiple times.
- David working on target & schematron validators, reworking to implement and reuse parsing of element type data, and developing new JUnits.
- Overall status of PSVI work: on track
- Hubert presented his thoughts on locid. We determined that there does need to be an implementation of it, that it's not simply coming up with an example. We determined more clarification is needed as to how the locale is specified, and whether substitution needs to be supported. Hubert will follow up with John Arwe to determine this. Status information is pending this decision.
22 July 2008
Attendees: David (IBM), Ali (IBM), Hubert (IBM)
Discussion:
Status:
- Hubert finished main work for locid. Needs to integrate with HEAD once the schematron code is activated there, and also to write JUnits. Hubert wanted to know what is next in priority. Ali advised moving to the base64 enhancement.
- David will check with Sandy Gao as to the status of the spec (John Arwe is on vacation), as they seem to be wrapping up a new LC version, and whether the Interop will be based on that, and if xml:base support will be part of that. Also to find out status of Microsoft's interop testcases.
- Ali finished most testcases for the work he has been doing. Next he will continue working through TestMainValidatorLC and TestSMLModelUnits. He will be pulled away for other business temporarily for 2 days this week.
- David has finished work on the target validator, except for possible failures to some tests in TestMainValidatorLC (he moved on from that since it was unclear if those tests were valid, due to them being commented out). He is working now on the SchematronValidator.
- PSVI work is still on track for our original estimate.
29 July 2008
Attendees: David (IBM), Ali (IBM), Hubert (IBM), Mark M. (SAS)
Discussion:
Minutes:
- David working on finishing target and schematron validators. Tests for TestMainValidator pass, but there are failures in the *LC tests. Also need to look at removing an extra builder that might be unnecessary. Will also need to run TPTP tests for i12 iteration.
- Ali temporarily pulled away last week. Now back on RM work, working on existing testcases, expected to be done soon. Then he will move to new testcases.
- David to contact MS (Kumar Pandit) to find out status of testcases for interop.
- Hubert working on merging his locid changes with HEAD. Needs to test with latest code. Also working on base64 enhancement, work in progress.
- Mark hasn't had much time to work on RM, mostly internal stuff. Wants to pitch in, and is open to doing some of the testcases necessary.
- David reminded group of i13 designs needing to be written soon, but it's doubtful there are new designs required for RM.
- Ali to contact Sandy Gao and John Arwe to determine whether our validator needs to support validating schemas that have no corresponding instances. PSVI only operates on instance data, so validating schema-only SML-IF files is difficult.
5 August 2008
Attendees: David (IBM), Ali (IBM), Hubert (IBM), Mark M. (SAS)
Discussion:
Minutes:
- Mark has updated to get the latest code. Hasn't had a chance to look at the JRE issues yet.
- Ali: most old testcases passing. Creating new testcases for schema binding and other areas.
- Hubert: last week worked on base 64, but having problems with testing. Also did some work merging the locid implementation with HEAD. Hubert encountering problems with running schematron validator. Ali was able to recreate these errors, so David will investigate, since he does not see the errors in his workspace. Hubert also reported that the validator is not correctly handling DTDs, which is needed for base 64 support. Ali suggested using Sandy Gao as a reference as to how DTDs should be handled.
- David: working on finishing up target validator cases.
- Ali: sent email to Sandy asking if schemaComplete must be set to true for validating SML-IF documents that don't contain SML instance documents.
12 August 2008
Attendees: David (IBM), Ali (IBM), Hubert (IBM)
Discussion:
- Current status of deliverables
- locid and DTD summary
- test plan status
Minutes:
- Hubert says requirements of locid and DTD (base64) are now clear. He's almost ready to check in his fixes. We need to watch for possible effects of sometimes setting validation to false, and whether we handle schemaComplete="false" (possibly a non-issue). Hubert needs to run testsuite to ensure no regression.
- Sandy at yesterday's meeting suggested we create a DOM representation of the document. David was concerned about the loss of line number information. Ali pointed out that line number information is not a priority for the interop - this is strictly for our problems view in the UI.
- Ali going through the testcases and making sure we have all the tests we need, based on the info received from MS. Also has updated properties files.
- David needs to finish up the target validator, still has some cases that are failing in derivation and same name, after reworking the logic there. Also will change test plan generator to reflect changes made by Ali to metadata.
19 August 2008
Attendees: David (IBM), Hubert (IBM)
Discussion:
- status around the room
Minutes:
- Hubert: bare-names feature () - should be an easy thing to complete; also working on problems with sml:ref. yesterday he found a problem with dangling pointers and fixed it. Hubert will be out of the office Wednesday thru next Monday. After bare-names work, he has to do some testcase cleanup, and also needs to change the code to use the latest version of schematron (basically removing some workarounds that were added for the previous version). He also has one item to work on for the DC subproject ().
- David: since last week's meeting, David has finished the target validator work and has completed some of the testcase changes necessary for the latest spec draft (). Next he will update the export & new SML-IF file create wizard to comply with the latest changes, and will also go through a list of testcase defects that were sent to us by MS. At that point, he will begin work on xml:base ().
- Ali submitted his status via email, as he was unable to attend:
- Completed:
- lax validation when no schemas bound, strict validation otherwise (since related to 244308 incl test cases) [COMPLETE]
- add "noSchemaBindings" element [COMPLETE]
- change schemaBinding/namespaceBinding from 1..1 to 0..n [COMPLETE]
- Addressed all incomplete test cases for acyclic and deref
- Upcoming work:
- There is currently a problem with the Identity validator he is trying to resolve.
- Ali will be attending to the incomplete test cases for identity next. There are some cases here where code modification is needed.
26 August 2008
Attendees: David (IBM), Hubert (IBM), Ali (IBM), John Arwe (IBM / SML workgroup), Paul (CA), Jack (CA)
Discussion:
- status around the room
- SML Overview
Minutes:
- Ali has completed all enhancements and testcases assigned to him.
- Hubert has completed bare names support, and still needs to check in changes to support the latest Schematron version.
- David is about 50% complete with the xml:base support. John mentioned that there is also a usage of xml:base in schema import resolution that needs to be handled. Referenced line 534 of the SML-IF spec.
- This week, we need to fix the following defects in support of the interop, as mentioned in the i13 plan:
- Ali presented an overview of SML, both to introduce the spec and its intent, and also to briefly discuss how the COSMOS implementation is structured.
2 September 2008
Attendees: David (IBM), Paul (CA), Jack (CA)
Minutes:
- We discussed the open i13 and untargeted defect list, of which there were 7. We went through each one and were able to quickly get the list down to 3, as we are retargeting the other 4 to i14. For the other three:
- - we still need to determine the status of this one. it's at least "mostly done".
- - also "mostly done", David will try to get this into good shape for i13 today
- - this one is pending getting the schema and schematron files checked in. We are working on getting the approvals to do this. We hope to be able to close this one out today, since this will make a huge difference in the quality of the i13 build for Resource Modeling.
- Jack and Paul talked about additional CA resources becoming available soon to work on SML tooling, and asked for good starting points to get their feet wet on it. David mentioned that would be interesting to check out if it's not already resolved. There are other UI concerns that haven't been given attention of late, due to the recent focus on the validator. The additional people that would work on SML have a UI background, so that would be a good fit for them. David to put together a list of defects to start with, and we can discuss this at next week's meeting, since the CA people should be available by that point.
9 September 2008
Attendees: David (IBM), Naveen (CA), Ramesh (CA), Jack (CA), Paul (CA), Monica (CA)
Agenda:
- i13 testing status
- Workitems for new team members:
Minutes:
- David went through the SML Overview document again for the new folks
- The new folks have setup bugzilla accounts, etc. already and are working on setting up Eclipse
- We decided that the best way to get them started is to work on, splitting up the work among them. David to answer questions on this bug through bugzilla and general RM/SML questions can be handled by email or on the next RM call
16 September 2008
Attendees: David (IBM), Naveen (CA), Ramesh (CA), Jack (CA), Paul (CA), Monica (CA)
Minutes:
- bug 243026 - Naveen and Ramesh making progress; they have the debug environment working
- Monica still coming up to speed
- Next bug to tackle is writing the manual tests for the SML tooling. Srinivas a good resource to consult with on this.
- We discussed the process for making doc updates, whether we send them to Adriane/Pam or make them directly. Not clear at this time which approach we will take, although it would seem better to send them to Adriane/Pam.
23 September 2008
Attendees: David (IBM), Naveen (CA), Ramesh (CA), Monica (CA), Jack (CA)
Minutes:
- David to transfer to Naveen so he can mark as fixed
- All defects to go into HEAD and COSMOS 1.0 streams, pending David's approval
- - monica having trouble, getting error with test sml-if file - david suggested being sure she launches test workspace, and that she uses one of the files from the validation tests plugin
- - pointed Naveen to manual JUnit tests. others will help with this.
- Jack to email assignments for the week, focusing on the following defects as best starting points:
- 237829 - Error pane cuts off useful info and buttons by default.
- 176187 - SML-IF import locator failure should be a warning, not an error.
- 225165 - Import does not handle xs:any data in <model> element or extra user attributes.
30 September 2008
Attendees: David (IBM), Monica (CA), Paul (CA)
Minutes:
- Monica fixed 196213. Since then, she has been out and is now looking at the next defect.
- Apparently there is a holiday in India because those folks did not attend
7 October 2008
Attendees: David (IBM), Jack (CA), Naveen (CA), Ramesh (CA)
Minutes:
- David to review SML-IF manual tests and check in
- Ramesh deciding between 222225 and 176187
- Naveen looking at 225165
- David handled questions about those specific issues
14 October 2008
Attendees: David (IBM), Jack (CA), Naveen (CA), Ramesh (CA)
Minutes:
- David has multiple bug fixes to review
- David clarified some issues with 225165
- Next two to be assigned 176187 and 209871
- Ramesh mentioned finding other errors when looking at 176187. David suggested opening defects for any other problems found.
- Jack asked David to review Dev Guide so we can identify areas that need updating. David said he would try to this week.
- David suggested that frequent checkins should be made of the docs per Eclipse process. Jack mentioned it's difficult due to a dearth of committers.
21 October 2008
Attendees: David (IBM), Jack (CA), Naveen (CA), Ramesh (CA)
Minutes:
- Multiple defects have patches still waiting for David to review and commit
- Jack made it clear that CMDBf work takes precedence over RM work
- Also, documentation work takes precedence over RM work
- Jack issued a reminder that all CA changes should include a copyright addition (new files) or modification (existing files)
- David to change target of 250781 to future
- David answered questions about 225165 and 176187
28 October 2008
Attendees: David (IBM), Jack (CA)
Minutes:
- Naveen and Ramesh were out due to India holiday
- David is caught up on approving and checking in the CA contributions for bugs 222225 and 176187.
- We discussed recent project-wide topics regarding documentation, CBE, axis2, and tomcat. This led to the creation of bugs:
7 November 2008
Attendees: David (IBM), Jack (CA), Ramesh (CA), John (IBM)
Minutes:
- Ramesh asked for guidance on the mechanics and location of creating a JUnit test for. David showed him how to create the test method using TPTP, and indicated the breakdown of the various SML plugins so he would know where to put the test.
- He also asked for the location of encode/decode methods to help with. David suggested that they should go in the same plugin as the import/export logic, which in this case is the repository plugin.
- We discussed the reconciliation taxonomy (RTx) which was newly contributed to the RM project. Jason Losh of SAS had indicated interest, but did not attend the call. We talked about the process by which changes could be introduced to the RTx. Some process steps are built-in to this being an Eclipse project: committer can check in changes, and changes from other folks should be contributed by attaching a patch to a bugzilla defect or enhancement. Some steps in the process are up to our discretion. Since we want to have some careful control over changes, we will want to discuss each change in the RM calls so we can get agreement on the change before committing, and an RM committer would then apply the patch to CVS. To help identify the changes in bugzilla, we can make use of the whiteboard field to use a special token such as "rtx". Also, we might consider having a wiki page to provide a "cover sheet" for all RTx related activity, with links to relevant bugzillas (or a query link to all bugs with rtx in the whiteboard).
- John indicated that he would like to discuss the process further offline so he and Mark J. could better understand Eclipse and COSMOS processes and how they can be applied to RTx work.
- We discussed that publicity will be key, as this can potentially be an impetus to increased project participation.
TODOs:
- John to follow up with Mark J. about attending next Tuesday's meeting
- David to contact Jason to ensure someone will be there to represent SDD's concerns
- Jack to ask Jimmy who would be the best CA person to begin participating | http://wiki.eclipse.org/index.php?title=COSMOS_Resource_Modeling_Meeting_Minutes&oldid=127578 | CC-MAIN-2017-39 | refinedweb | 3,923 | 67.79 |
0
Hi, I have a working program and I need to answer the following questions:
1:where was polymorphism was used in this application?
2:identify where overriding or overloading was used in this application?
I belive overriding is used by the Runnable method to override the run() method. Would that be a good explenation? I am not sure how to clearly communicate how polymorphism is used. Any ideas on how to explain it?
Thanks
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package treading; /** * * @author Q */ //Runnable is the name of the interface, to use the interface we use the implement keyword. public class Treading implements Runnable { //Thread object is to execute a single method and to execute it just once. //The method is executed in its own thread of control, which can run in parallel with other threads private int cDown = 5; private static int cThread = 6; private int threadNum = --cThread; //constructs opbject that will exicute in a different thread. /** * */ public Treading() { System.out.println("\nStarting thread number => " + cThread + "\n"); } //Overriding was done by the Runnable interface superseeding the previous definition of run() @Override //This run() method defines the task that will be performed by the thread. //This will be called by the start() method. public void run() { while (true) { System.out.println( " Thread: " + threadNum + " ( Countdown = " + cDown + " )"); for (int j = 0; j < 5; j++) { } if (--cDown == 0) { System.out.println( "\nBLAST OFF!" + "\n"); return; } } } //Start() method creates the new thread of control executing the Thread object’s run() method. //Starts all 5 threads. private static void Countdown() throws java.lang.InterruptedException { for (int i = 0; i < 5; i++) { Thread.sleep(1000); Runnable start; start = new Treading(); Thread counting = new Thread(start); counting.start(); } } /** * @param args the command line arguments */ public static void main(String[] args) throws java.lang.InterruptedException { Countdown(); } } | https://www.daniweb.com/programming/software-development/threads/445553/defining-how-polymorphism-is-used-in-this-code | CC-MAIN-2018-17 | refinedweb | 308 | 66.64 |
Created on 2010-04-28 10:44 by dabrahams, last changed 2014-01-17 02:29 by RubyTuesdayDONO.
On POSIX systems, the PATH environment variable is always used to
look up directory-less executable names passed as the first argument to Popen(...), but on Windows, PATH is only considered when shell=True is also passed.
Actually I think it may be slightly weirder than that when
shell=False, because the following holds for me:
C:\>rem ##### Prepare minimal PATH #####
C:\>set "PATH=C:\Python26\Scripts;C:\Python26;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem"
C:\>rem ##### Prepare a minimal, clean environment #####
C:\>virtualenv --no-site-packages e:\zzz
New python executable in e:\zzz\Scripts\python.exe
Installing setuptools................done.
C:\>rem ##### Show that shell=True makes the difference in determining whether PATH is respected #####
C:\>python
Python 2.6.5 (r265:79096, Mar 19 2010, 18:02:59) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.Popen(['python', '-c', 'import sys; print sys.executable'])
<subprocess.Popen object at 0x0000000001DBE080>
>>> C:\Python26\python.exe
>>> subprocess.Popen(['python', '-c', 'import sys; print sys.executable'], env={'PATH':r'e:\zzz\Scripts'})
<subprocess.Popen object at 0x0000000001F05A90>
>>> C:\Python26\python.exe
>>> subprocess.Popen(['python', '-c', 'import sys; print sys.executable'], env={'PATH':r'e:\zzz\Scripts'}, shell=True)
<subprocess.Popen object at 0x0000000001F05B00>
>>> e:\zzz\Scripts\python.exe
That is, it looks like the environment at the time Python is invoked is what counts unless I pass shell=True. I don't even seem to be able to override this behavior by changing os.environ: you can clear() it and pass env={} and subprocess.Popen(['python']) still succeeds.
This is a very important problem for portable code and one that took me hours to suss out. I think:
a) the current behavior needs to be documented
b) it needs to be fixed if possible
c) otherwise, shell=True should be the default
It's worse than I thought; there isn't even one setting for shell that works everywhere. This is what happens on POSIX (tested on Mac and Ubuntu):
$ mkdir /tmp/xxx
$ cd /tmp/xxx
xxx $ virtualenv /tmp/zzz
xxx $ python
Python 2.6.5 (r265:79063, Mar 23 2010, 08:10:08)
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from subprocess import *
>>> p = Popen(['python', '-c', 'import sys;print sys.executable'],
... stdin=PIPE,stdout=PIPE,stderr=PIPE,
... env={'PATH':'/tmp/zzz/bin'})
>>> stdout,stderr = p.communicate(None)
>>> print stdout
/tmp/zzz/bin/python
>>> print stderr
>>> p = Popen(['python', '-c', 'import sys;print sys.executable'], shell=True,
... stdin=PIPE,stdout=PIPE,stderr=PIPE,
... env={'PATH':'/tmp/zzz/bin'})
>>> stdout,stderr = p.communicate(None)
>>> print stdout
>>> print stderr
IMO there's another problem with subprocess portablity---the lack of control over encodings: see issue 6135.
Changing the default value of shell is not an option anyway.
The behavior you describe is exactly what one should expect: the environment in which the executable is located is the environment of the process calling Popen, not the environment passed to Popen. The environment passed to Popen is the environment in which the subprocess executes. When using shell=True, this is the environment in which the shell executes, and the *shell* then looks up the executable in that new environment. As far as I know this behavior is the same on both Windows and Unix, and thus is not a portability issue. (How the shell works can be a portability issue, though.)
I'm not sure that this needs to be documented explicitly, as it is a logical consequence of how subprocesses work, but if you want to suggest a doc update I'll take a look at it.
I suspect your Unix example is about the fragility of the rules for computing sys.executable (there's an issue in the tracker about that...you may get a different result on trunk), but I haven't checked it.
I wrote a Python script (enclosed) to methodically test how these things work, that doesn't rely on peculiarities of sys.executable. The tests did reveal some notable differences on *nix and 'doze:
* When shell=False on windows you must launch the process using a full filename (e.g. "foo.exe", not just "foo", pass --invoke-filename to the script to enable that). This may seem obvious to you, but for me it was surprising that one executable lookup function (looking in PATH) is in effect but not the other (extending unqualified executable names). This should be spelled out in the docs.
* On *nix, with shell=False and the executable is neither in the PATH in the environment at the time of Python's launch nor in os.environ at the time of Popen, passing Popen an explicit env whose PATH includes the executable is enough to cause it to be found. Not so on 'doze.
* On 'doze, when the executable is in the PATH of os.environ but not in that of Popen's explicit env argument, even with shell=False, no Exception is raised (but returncode is nonzero)
Well, it seems I was mistaken when I thought I knew how this worked :)
Checking the os.exec documentation linked from the subprocess page, I see that when an environment is supplied PATH is indeed checked in it. The documentation for CreateProcess, however, indicates that PATH is ignored, and any extension must be supplied explicitly.
At the very least the docs should be updated to clarify that execvpe is used when an environment is passed on posix, and to link to the CreateProcess docs. A discussion of PATH could perhaps be put in a note or footnote (probably footnote, there are enough notes already in those docs!)
I'm not sure how one creates a good portability story out of these pieces. It doesn't seem as though there is any way to harmonize the two, since we are dealing with the semantics of system calls over which we have no control.
For reference, here is (a?) link to CreateProcess docs that I found via Google:
It doesn't look like the kind of link that one could trust to be stable, though, so I'm not sure if we should include it in the docs.
I'm adding Brian Curtin as nosy to see if he knows whether or not there are permalink-like links to the relevant Microsoft documentation that we could use.
You could take the "(VS8.5)" part out of the link which will give the latest version, which may not always be the relevant version (although I doubt this specific API would change).
That's about the best permalink-like feature you'll find, but overall, leaving the link as-is is pretty safe in my experience.
@r.david.murray: did you try running my test? I think it shows that we are pretty darned close to fully portable. I believe we could fix Popen to make it fully portable pretty easily. In fact, there may be a pure-python fix. Documenting the differences would also not be hard. I would discourage you from relying *solely* on a description such as "uses execvpe on POSIX" to describe the semantics. Aside from being a nonportable description, it doesn't help anyone who isn't familiar with the POSIX system calls.
I didn't run the script. I have now, but I'm not clear from its output what each test is actually doing, and don't really have the time to figure it out from the code right now.
I think it is probably more efficient to just ask you what your suggestion is for making things more portable?
As for the docs, the docs link to the os.exec python docs, which explain the PATH semantics. Linking to the Microsoft documentation would equivalently explain the Windows semantics. An explicit footnote discussing the differences in PATH behavior in the subprocess context would probably be helpful.
I've uploaded a new probe.py that contains a win32 Popen wrapper that I think acts just like *nix's Popen w.r.t. PATH and environment (pass --fix to demonstrate). I suggest using this or an equivalent wrapper for Win32, and documenting the fact that with shell=False, filename extensions need to be supplied explicitly on windows.
Not to appear impatient, but...<bump>.
It's a fairly tidy answer, I think :-)
Sorry for my Windows ignorance, but if CreateProcess ignores the PATH, how does updating the PATH fix the problem?
I'm probably as ignorant as you are of Windows issues. I just know what my experiments tell me: if you force the contents of any explicit 'env' argument into os.environ before calling Popen, you get the same behavior as on *nix.
Well, it wouldn't be the first time the microsoft docs were wrong.
There are two questions here: (1) is this behavior consistent across all microsoft platforms we support? (2) is this *change* in behavior of Popen acceptable?
For (1) we need a unit test added to the subprocess unit tests that can check this.
For (2)...well, I think it would be good for the behavior to be as consistent as practical, so I'd be in favor. We need some second opinions, though, to make sure we aren't overlooking some negative consequence. I'm also not sure that this qualifies as a bug fix, so it may only be possible to get it into 3.2, assuming it is acceptable.
Note that I have not tested your program on Windows myself, I'm taking your word for it that it works ;) I'll be more inclined to test things if the tests are in the form of unit tests, which should be much easier to understand than your test program.
R. David Murray wrote:
> There are two questions here: (1) is this behavior consistent across all microsoft platforms we support?
I'll be honest: I don't know.
> (2) is this *change* in behavior of Popen acceptable?
I don't know that either.
> I'll be more inclined to
> test things if the tests are in the form of unit tests, which should
> be much easier to understand than your test program.
I guess no good deed goes unpunished ;-)
I also guess that whether you think unit tests will be easier to
understand depends on what kind of information you expect to glean
from the code. My script was designed to probe for all
inconsistencies between ‘doze and POSIX behaviors, and it is more
revealing in that respect than a unit test would be. The unit test
that would prompt the particular code change I'm suggesting would look
more like:
put directory X in the env argument's PATH (but not in os.environ)
attempt to launch X/some_executable as simply “some_executable”
assert that X/some_executable actually ran
I don't know what Popen's unit tests look like, and to be honest,
right now I just don't have any more time to pour into this particular
issue. Even if it doesn't get fixed in Python I'm going to be using
my wrapper for uniformity. I hope everything I've done so far is
useful to the community but if not, I still have what I need.
Fair enough. Thank you for your detective work, and hopefully someone will be interested enough to pick this up again later.
New data point: in some contexts on Windows (not sure of the exact cause but I was dealing with multiple drives), even this workaround isn't enough. I ended up having to do something like this (i.e. manually search the path) on win32:
def full_executable_path(invoked, environ):
if os.path.splitext(invoked)[1]:
return invoked
explicit_dir = os.path.dirname(invoked)
if explicit_dir:
path = [ explicit_dir ]
else:
path = environ.get('PATH').split(os.path.pathsep)
extensions = environ.get(
'PATHEXT',
# Use *something* in case the environment variable is
# empty. These come from my machine's defaults
'.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PSC1'
).split(os.path.pathsep)
for dir in path:
for ext in extensions:
full_path = os.path.join(dir, invoked+ext)
if os.path.exists( full_path ):
return full_path
return invoked # Not found; invoking it will likely fail
class Popen(subprocess.Popen):
def __init__(
self, args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None,
*args_, **kw):
if executable is None and not shell:
executable = full_executable_path(args[0], env or os.environ)
super(Popen,self).__init__(
args, bufsize, executable, stdin, stdout, stderr,
preexec_fn, close_fds, shell, cwd, env, *args_, **kw) | http://bugs.python.org/issue8557 | CC-MAIN-2014-15 | refinedweb | 2,130 | 64.2 |
>>>>> Heiko Panther writes: >>> I'm targetting an ARM7 TDMI processor, and gcc 3.3.2 complains about >>> this inline asm instruction from function arm_stub.h:v5T_semantics(). >> >> >>> asm volatile ("mrc p15,0,%0,c0,c0,0\n" >>> : "=r" (id) : /* no inputs */); >> >> >>> What's up with this insn, I can't find it in the reference. And what >>> should I correct to make it work? >> >> >> Which reference? It is covered in the ARM Architectural Reference Manual. >> The instruction reads the CPU ID register and is valid for all ARM cpus. > My bad, I only looked in the thumb ref card. So that's an ARM > instruction... I'm compiling with -mthumb. I left away all the > thumb-interwork flags, since I don't need to integrate any ARM code > libs. Could that be a problem? > Otherwise, I would probably have to switch to ARM mode before the mrc. > I'm gonna try that. Or you could try the simpler approach that Daniel Neri used: static int v5T_semantics(void) { #ifdef CYGINT_HAL_ARM_ARCH_ARM7 return 0; #else unsigned id; asm volatile ("mrc p15,0,%0,c0,c0,0\n" : "=r" (id) : /* no inputs */); return ((id >> 16) & 0xff) >= 5; #endif } In general, I'm pretty uncomfortable with running the stub code in thumb mode. For most ARM CPUs, the cache flushes done in the stub use co-proc insns not available in thumb mode. There are also those CPUs with h/w breakpoint/watchpoint support which require the stub to use non-thumb insns to manipulate. --Mark -- Before posting, please read the FAQ: and search the list archive: | https://sourceware.org/pipermail/ecos-discuss/2004-March/025938.html | CC-MAIN-2022-21 | refinedweb | 261 | 74.59 |
Linear regression via the least squares method
Least squares fit implementations
Implementation in (C)Python
Implementation in Fortran
Generating sample data and benchmarking
Verification that all implementations yield similar results
(Note that this chart just reflects my rather objective thoughts after experimenting with Cython, and it is not based on real numbers or benchmarks.)
For this benchmark, we will implement a naive least squares method for linear regression, which is the simplest approach to performing a regression analysis of a dependent and a explanatory variable.
The objective is to find the best-fitting straight line through a set of points that minimizes the sum of the squared offsets from the line.
The offsets come in 2 different flavors: perpendicular and vertical - with respect to the line.
As Michael Burger summarizes it nicely in his article "Problems of Linear Least Square Regression - And Approaches to Handle Them": "the perpendicular offset method delivers a more precise result but is are more complicated to handle. Therefore normally the vertical offsets are used."
Here, we will also use the method of computing the vertical offsets.
In more mathematical terms, our goal is to compute the best fit to n points $(x_i, y_i)$ with $i=1,2,...n,$ via linear equation of the form
$f(x) = a\cdot x + b$.
We further have to assume that the y-component is functionally dependent on the x-component.
In a cartesian coordinate system, $b$ is the intercept of the straight line with the y-axis, and $a$ is the slope of this line.
$a = \frac{S_{x,y}}{\sigma_{x}^{2}}\quad$ (slope)
$b = \bar{y} - a\bar{x}\quad$ (y-axis intercept)
where
$S_{xy} = \sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})\quad$ (covariance)
$\sigma{_x}^{2} = \sum_{i=1}^{n} (x_i - \bar{x})^2\quad$ (variance)
After I experimented with different libraries, the numpy functions, and other tweaks, I decided to go back and implement the least squares fit method in (C)Python without any external libraries - using just the pure standard lib. Python.
For Cython and Fortran, we will be using NumPy
arrays for more efficient memory access.
def python_lstsqr)
Cython (see Cython's C-extensions for Python) is basically a hybrid between C and Python and can be pictured as compiled Python code with type declarations.
Since we are working in an IPython notebook here, we can make use of the very convenient IPython magic: It will take care of the conversion to C code, the compilation, and eventually the loading of the function.
Also, we are adding C type declarations; those type declarations are not necessary for using Cython, however, it will improve the performance of our code significantly.
%load_ext cythonmagic
%%cython import numpy as np cimport numpy as np cimport cython @cython.boundscheck(False) @cython.wraparound(False) @cython.cdivision(True) cpdef cython_lstsqr(x_ary, y_ary): """ Computes the least-squares solution to a linear matrix equation. """ cdef double x_avg, y_avg, var_x, cov_xy,\ slope, y_interc, temp cdef double[:] x = x_ary # memoryview cdef double[:] y = y_ary cdef unsigned long N, i N = x.shape[0] x_avg = 0 y_avg = 0 for i in range(N): x_avg += x[i] y_avg += y[i] x_avg = x_avg/N y_avg = y_avg/N var_x = 0 cov_xy = 0 for i in range(N): temp = (x[i] - x_avg) var_x += temp**2 cov_xy += temp*(y[i] - y_avg) slope = cov_xy / var_x y_interc = y_avg - slope*x_avg return (slope, y_interc)
Thanks to Joshua Adelman and Andreas Mayer for pointing out some flaws in the initial version of the Cython implementation.
Upon request I added the untyped version (identical to the (C)Python implementation) for comparison below:
%%cython cimport cython cpdef cython_lstsqr_untyped)
There is also a convenient IPython magic command for compiling Fortran code. The Fortran magic uses NumPy's
F2PY module for compiling and running the Fortran code. For more information, please see the 'Fortran magic's documentation'.
%install_ext
Installed fortranmagic.py. To use it, type: %load_ext fortranmagic
%load_ext fortranmagic
%%fortran SUBROUTINE fortran_lstsqr(ary_x, ary_y, slope, y_interc) ! Computes the least-squares solution to a linear matrix equation. """ IMPLICIT NONE REAL(8), INTENT(in), DIMENSION(:) :: ary_x, ary_y REAL(8), INTENT(out) :: slope, y_interc REAL(8) :: x_avg, y_avg, var_x, cov_xy, temp INTEGER(8) :: N, i N = SIZE(ary_x) x_avg = SUM(ary_x) / N y_avg = SUM(ary_y) / N var_x = 0 cov_xy = 0 DO i = 1, N temp = ary_x(i) - x_avg var_x = var_x + temp**2 cov_xy = cov_xy + (temp*(ary_y(i) - y_avg)) END DO slope = cov_xy / var_x y_interc = y_avg - slope*x_avg END SUBROUTINE fortran_lstsqr
Building module "_fortran_magic_a044885f2b0c0feac78a230b6b714e2b"... Constructing wrapper function "fortran_lstsqr"... slope,y_interc = fortran_lstsqr(ary_x,ary_y) Wrote C/API module "_fortran_magic_a044885f2b0c0feac78a230b6b714e2b" to file "module.c" Fortran 77 wrappers are saved to "-f2pywrappers.f"
import random import numpy as np random.seed(12345) x = [x_i*random.randrange(8,12)/10 for x_i in range(500)] y = [y_i*random.randrange(8,12)/10 for y_i in range(100,600)] x_ary = np.asarray(x) y_ary = np.asarray(y) reference = python_lstsqr(x_ary, y_ary) funcs = [python_lstsqr, cython_lstsqr, cython_lstsqr_untyped,fortran_lstsqr] for f in funcs: assert(reference == f(x_ary, y_ary)) print('ok')
ok
Just for a visual cheeck for how our dataset is distributed, and how the least squares regression line looks like, we will plot the results in a scatter plot below.
Note that we are only using our "matrix approach" to visualize the results - for simplicity. We expect all 3 approaches to produce similar results, which we confirmed in via the
np.testing.assert_array_almost_equal function above.
%matplotlib inline
from matplotlib import pyplot as plt import random random.seed(12345) x = [x_i*random.randrange(8,12)/10 for x_i in range(500)] y = [y_i*random.randrange(8,12)/10 for y_i in range(100,600)] slope, intercept = python_lstsqr(x, y) line_x = [round(min(x)) - 1, round(max(x)) + 1] line_y = [slope*x_i + intercept for x_i in line_x] plt.figure(figsize=(8,8)) plt.scatter(x,y) plt.plot(line_x, line_y, color='red', lw='2') plt.ylabel('y') plt.xlabel('x') plt.title('Linear regression via least squares fit') ftext = 'y = ax + b = {:.3f} + {:.3f}x'\ .format(slope, intercept) plt.figtext(.15,.8, ftext, fontsize=11, ha='left') plt.show()
Now, finally let us take a look at the effect of different sample sizes on the relative performances for each approach.
import timeit import random random.seed(12345) orders_n = [10**n for n in range(1, 6)] timings = {f.__name__:[] for f in funcs} for n in orders_n: x = ([x_i*np.random.randint(8,12)/10 for x_i in range(n)]) y = ([y_i*np.random.randint(10,14)/10 for y_i in range(n)]) x_ary = np.asarray(x) y_ary = np.asarray(y) x_fary = np.asfortranarray(x) y_fary = np.asfortranarray(y) timings['python_lstsqr'].append(min(timeit.Timer('python_lstsqr(x, y)', 'from __main__ import python_lstsqr, x, y')\ .repeat(repeat=3, number=1000))) timings['cython_lstsqr'].append(min(timeit.Timer('cython_lstsqr(x_ary, y_ary)', 'from __main__ import cython_lstsqr, x_ary, y_ary')\ .repeat(repeat=3, number=1000))) timings['cython_lstsqr_untyped'].append(min(timeit.Timer('cython_lstsqr_untyped(x, y)', 'from __main__ import cython_lstsqr_untyped, x, y')\ .repeat(repeat=3, number=1000))) timings['fortran_lstsqr'].append(min(timeit.Timer('fortran_lstsqr(x_fary, y_fary)', 'from __main__ import fortran_lstsqr, x_fary, y_fary')\ .repeat(repeat=3, number=1000)))
import platform import multiprocessing from cython import __version__ as cython__version__ def print_sysinfo(): print('\nPython version :', platform.python_version()) print('compiler :', platform.python_compiler()) print('Cython version :', cython__version__) print('NumPy version :', np.__version__) print('\nsystem :', platform.system()) print('release :', platform.release()) print('machine :', platform.machine()) print('processor :', platform.processor()) print('CPU count :', multiprocessing.cpu_count()) print('interpreter:', platform.architecture()[0]) print('\n\n')
import matplotlib.pyplot as plt def plot(timings, title, labels, orders_n): plt.rcParams.update({'font.size': 12}) fig = plt.figure(figsize=(11,10)) for lb in labels: plt.plot(orders_n, timings[lb], alpha=0.5, label=labels[lb], marker='o', lw=3) plt.xlabel('sample size n') plt.ylabel('time per computation in milliseconds') plt.xlim([min(orders_n) / 10, max(orders_n)* 10]) plt.legend(loc=2) plt.grid() plt.xscale('log') plt.yscale('log') plt.title(title) plt.show()
import prettytable labels = {'python_lstsqr':'Python (Standard Library func.)', 'cython_lstsqr':'Cython (NumPy arrays)', 'cython_lstsqr_untyped':'Cython untyped (equiv. to Python impl.)', 'fortran_lstsqr': 'Fortran (NumPy arrays)', } def summary_table(funcs): fit_table = prettytable.PrettyTable(['n=%s' %orders_n[-1], 'Implementation' , 'time in msec']) fit_table.align['Implementation'] = 'l' for l in ['python_lstsqr', 'cython_lstsqr_untyped', 'cython_lstsqr', 'fortran_lstsqr']: fit_table.add_row(['', labels[l], '{:.3f}'.format(timings[l][-1])]) print(fit_table)
title = 'Performance of Linear Regression Least Squares Fits in Python, Cython, and Fortran' print_sysinfo() plot(timings, title, labels, orders_n) summary_table(funcs)
Python version : 3.4.1 compiler : GCC 4.2.1 (Apple Inc. build 5577) Cython version : 0.20.1 NumPy version : 1.8.1 system : Darwin release : 13.2.0 machine : x86_64 processor : i386 CPU count : 2 interpreter: 64bit
+----------+-----------------------------------------+--------------+ | n=100000 | Implementation | time in msec | +----------+-----------------------------------------+--------------+ | | Python (Standard Library func.) | 55.369 | | | Cython untyped (equiv. to Python impl.) | 35.196 | | | Cython (NumPy arrays) | 0.527 | | | Fortran (NumPy arrays) | 0.436 | +----------+-----------------------------------------+--------------+
Of course it is not fair to compare the interpreted Python language to compiled C and Fortran code that have static types at compile time.
Here, I was mostly interested to see how the code compiled code via Cython stacks against Fortran via F2PY (of course different compiler version can also cause significant differences). And one can say that both are about equal in terms of performance (at least for this simple benchmark).
It is nice to see that Cython and Fortran code can be used quite conveniently in IPython notebooks, which make them a even more valuable tool for data analyses and algorithm development: Code can be prototyped in Python, and step by step rewritten in context of the original documentation.
In the case of Cython, it is especially nice that Python and C functions can be mixed and matched to get the best out of both: Productivity and code efficiency. | http://nbviewer.ipython.org/github/rasbt/One-Python-benchmark-per-day/blob/master/ipython_nbs/day10_fortran_lstsqr.ipynb?create=1 | CC-MAIN-2015-22 | refinedweb | 1,621 | 50.23 |
This was my 2nd visit to the Nines (1st last Nov) and I got to say. . . I was "WOWED" yet again. My first visit was with my husband and we were celebrating being together 3 years. We arrived to a very friendly staff, beautiful room, and "Happy Anniversary" chocolates. I belong to SPG and SVO and have stayed very nice properties over the past few years (my home resort being the Westin Villas in Maui). I must say I adore The Nines and the unique atmosphere that sets it apart from other hotels.
I was recently at the St Regis Monarch Beach in Dana Point, Ca and was very unimpressed . . . Although it is a beautiful property the staff was not very warm or accommodating. This is complete the reverse at The Nines. The staff always had a smile and welcoming hello and seemed to genuinely want to help and accommodate guests.
I have read the reviews where others have felt a negative impression and I am sorry they have not been able to experience The Nines as it truly should be. This is a great property with much to offer.
After my first stay I was already hooked. So when the opportunity arose for a return trip to Portland I instantly booked The Nines. I was visiting my sister from Longview and my mother also flew to Portland for our visit. I had told her about the hotel but she was still swept away and commented she hadn’t quite expected such a lovely experience.
This time in a club floor room with two queen beds and city view I found the room much larger then my previous King room overlooking the atrium. Most of our time was spent at the hotel with some light shopping and sightseeing around downtown Portland, but The Nines is truly a hotel that offers much to see and enjoy where you almost never need to leave.
We enjoyed evening hors d'oeuvres in the club lounge and then visited the Urban Farmer for samplings off their Cheese Cart. This is a unique experience I highly recommend. My husband and I had also ordered from the cheese cart our first visit. I returned to show my mother. You get a variety of cheese to select from, though $5 per ounce you also receive divine sauces/spreads, nuts, & crackers. This will continue to be an event I make sure to treat my friends and family to each time we visit. If you enjoy cheese then you should love this. The presentation and flavors make for a very memorable experience.
Now to the “Departure” restaurant & lounge, located at the top floor (15) of the hotel. Walking into this place feels like you’ve entered another world altogether. My favorite items here would have to be the Shiu Mai (Pork dumplings) and Calamari Tempura (see pictures). Everyone in our party couldn’t stop raving about the Calamari (recommended by our server), by far the best we’ve all had.
Great location, great restaurants, great accommodations, and lovely staff (especially all the gals working in the club lounge this past weekend. Very pleasant & cordial, and always made sure to keep tables clean).
*Just a side note. Many complain about the lack of a sheet or coffee maker. The hotel is happy to provide both upon request. Just make sure to mention these at check in or even call the hotel before your arrival.
***** in my book. Looking forward to my next return (we'll be back with friends for our upcoming birthdays)
-, Starwood, Expedia, Orbitz, Hotels.com, Travelocity, Ctrip TA, Cheap Tickets, Hotwire, TripOnline SA, | https://www.tripadvisor.com/ShowUserReviews-g52024-d1144098-r58153268-The_Nines_a_Luxury_Collection_Hotel_Portland-Portland_Oregon.html | CC-MAIN-2017-30 | refinedweb | 606 | 72.87 |
Hi Reto, On Thu, Dec 21, 2006 at 10:11:22PM -0800, Reto Kramer wrote: > > I've tried to thread the two states (StateA and StateB) using a chain > of StateT ... StateT ..., but couldn't really make that work. That is how I would write it; I have attached code for your example. > It > seems rather arbitrary in this case which state to make the inner/ > outer one The choice is indeed arbitrary. > and depending on this ordering the "lifts" have to go with > one or the other set of store calls. If you don't mind turning on overlapping and undecidable instances then you don't need to manually lift things at all. Thanks Ian -------------- next part -------------- {-# OPTIONS_GHC -fglasgow-exts -fallow-overlapping-instances -fallow-undecidable-instances #-} import Control.Monad.Trans (MonadTrans) import Control.Monad.State (StateT, evalStateT, get, put, lift) -- StateA type StateA = [Integer] newtype MonadAT m a = MonadAT (StateT StateA m a) deriving (Monad, MonadTrans) class Monad m => MonadA m where getA :: m StateA putA :: StateA -> m () instance Monad m => MonadA (MonadAT m) where getA = MonadAT get putA = MonadAT . put instance (MonadTrans t, MonadA m, Monad (t m)) => MonadA (t m) where getA = lift getA putA = lift . putA evalAT :: Monad m => MonadAT m a -> StateA -> m a evalAT (MonadAT x) = evalStateT x -- StateB type StateB = [Integer] newtype MonadBT m a = MonadBT (StateT StateB m a) deriving (Monad, MonadTrans) class Monad m => MonadB m where getB :: m StateB putB :: StateB -> m () instance Monad m => MonadB (MonadBT m) where getB = MonadBT get putB = MonadBT . put instance (MonadTrans t, MonadB m, Monad (t m)) => MonadB (t m) where getB = lift getB putB = lift . putB evalBT :: Monad m => MonadBT m a -> StateB -> m a evalBT (MonadBT x) = evalStateT x -- The program type Monads = MonadBT (MonadAT IO) main :: IO () main = do res <- evalAT (evalBT exec []) [] print res exec :: Monads (StateA, StateB) exec = do foo bar foo foo bar a <- getA b <- getB return (a, b) foo :: MonadA m => m () foo = do st <- getA putA (1 : st) bar :: MonadB m => m () bar = do st <- getB putB (2 : st) | http://www.haskell.org/pipermail/haskell-cafe/2007-January/021085.html | CC-MAIN-2014-15 | refinedweb | 344 | 62.72 |
Start Writing Embeddable Applications.:
- When using configuration files, use a configuration component that doesn't require use of the global namespace (PEAR's
Config, Solar's
Solar_Config, and Zend Framework's
Zend_Configcome to mind); when coupled with a registry or implemented as a static class property (in PHP5), you can have access to the configuration from anywhere in your application.
- Have your bootstrap script call on class methods or functions to do their work. Don't do any decisioning in the global namespace.
- Better yet, use an MVC pattern in your apps, and have your bootstrap simply dispatch the controller. This can easily be duplicated in somebody else's code, or simply directly included.
- Make sure your templates are easily modified to allow developers to strip out header, footer, and menu elements.
- Create an API to allow retrieving necessary javascript and CSS so that it can later be injected into another system's templates.
- Don't use
$_GLOBALSever. It seems like an easy way to keep variables accessible across classes and functions, but with PHP 5's static properties, or judicious usage of singleton's in PHP 4, there are other ways to accomplish the same effect with fewer side effects.. | https://mwop.net/blog/138-Start-Writing-Embeddable-Applications.html | CC-MAIN-2016-07 | refinedweb | 201 | 52.09 |
Release Notes/077
Build 18880 - Apr 10, 2013 - Gold
Bug Fixes and Improvements
- Fixed crash that occurs when creating uig in some cases.
- Texture 3D TOP - Fix bug where *POffset was calculated to be off by 1.
- Fixed a bug when deleting DATs
- Fixed some licensing bugs.
Build 18780 - Jan 29, 2013 - Gold
New Features
- Added Recheck MIDI Devices button to MIDI Mapper dialog to update the list of connected devices at any time.
Bug Fixes and Improvements
- Modifying panel's width and height now re-layouts its contents without needing to tweak the window size fora refresh.
- Serial DAT properly initializes when starting in Perform Mode.
- Movie In TOP - Fix crash when loading jpeg images in CYMK color-space.
Build 18580 - Sep 10, 2012 - Gold
New Features
- Camera COMP has a new parameter on the View page that allows you to specify a custom projection matrix using either a DAT or CHOP.
- Now runs on 088 keys.
Bug Fixes and Improvements
- Movie In TOP - Fixed stutters that occur when Trimming a movie, when it loops.
- Movie In TOP - Fixed Read Ahead parameter being ignored when Interpolation is used.
- Fixed bug that caused random image artifacts (often pieces of the main TouchDesigner UI) to appear in TOPs in some cases.
- Video In TOP - Fix image flickering issue in some cases, when using the DataPath library.
- Animation COMP extend conditions changed to cycle when using Sequential play mode.
Build 18360 - Aug 1, 2012 - Gold
New Features
- Added .hclassic and .bhclassic file extensions to File SOP list of supported types (for Houdini users).
Bug Fixes and Improvements
- Text TOP - Fixed bug that caused Polygon Texture mode to not work correctly.
- Jump to Export CHOP removed from right-click menu on parameters in a parameter pop-up dialogs.
- Fixes to reduce audio pitch changes when dropping frames
Build 18180 - May 1, 2012 - Gold
New Features
- New
kinecttiltcommand which allows you to control the tilt of your Kinect sensors.
- Kinect TOP: Near mode added for the depth image. Skeletal tracking does not work when this is enabled in the current kinect runtime.
- Kinect CHOP: Add parameters to show skeleton positions in u/v coordinates, and turn off the tracking/clipping status channels
Bug Fixes and Improvements
- When loading a new file from the File menu in a process that was started with GPU affinity, the new process will also start up with GPU affinity.
- New warning added when trying to use GPU affinity on GPUs that don't support it.
- Fixed AMD version check dialog giving incorrect messages.
- Fixed bug that caused blend shapes to not import correctly from FBX files in some cases.
- Kinect CHOP: Fix jittery performance due to filtering parameters not being used correctly.
- Fixed very slow memory leak.
- Fixed a corrupt first frame that shows when loading a movie or image with low timeouts.
- Avoid freeze when opening viewers for nodes that contain load on demand COMPs.
- Small fixes for better Kinect usability and stability.
Build 17780 - Mar 20, 2012 - Gold
New Features
- Kinect CHOP and Kinect TOP added, supports the Microsoft Kinect for Windows SDK
- DMX In CHOP and DMX Out CHOP with support for ArtNet added
- Movie In TOP can now read uncompressed
.avifiles
Backwards Compatibility Issues
- In TOPs the 'Frames' units were incorrectly 0-based. They have been fixed to be 1-based (1 being the first frame) which may cause old files to behave unexpectedly. Frame are 1-based, Index is 0-based.
Bug Fixes and Improvements
- In and Out CHOPs and SOPs defined as filters (to match TOPs and DATs)
- DMX Out cooking bug fixed
- fixed send Command when outputting tables to a file via File Out DAT. It sends return and newline based on
-n -roptions.
- fixed Primitive SOP crash
- fixed crash due to viewer state
- DMX Out CHOP data values clamped to 0..255 with warning if exceeded
- near-far planes in SOP viewers set
- made the temporary fix for a disappearing-geometry issue now permanent and the default
- fixed crash when some nodes were deleted referring to some visible gadgets
- reduced over-cooking when node viewers on
- dropping nodes onto a component node will always prompt with a menu
- some node-to-node data links were not showing up in the networks
- Ramp TOP crash fixed, would crash when ramp dialog is open and the TOP was deleted.
- Object CHOP now cooks every frame if the relevant objects are moving.
- Clock CHOP fixed, no longer stops working after 23 days of runtime
- Fixed issue with panel overlays and crop if panel is in a node viewer
- Touch In/Out CHOPs and DATs now work correctly for ports under 5000
- Fixes for ATI GPU support, Blur TOP now works, Point Sprite rendering now works
- Fixed issue causing nodes not to cook after being edited in 3D modeler
- Speed CHOP no longer become inactive after edge-reset when "smart timeslice" (a command) cooking is enabled
Build 16900 - Dec 21, 2011 - Gold
Bug Fixes and Improvements
- New Ableton Sync Environment demo file.
- New LTC CHOP! Linear Timecode CHOP reads a time code encoded in an audio signal.
- Tweaks to LTC CHOP: Input Rate (default 30), not Input bit rate (default 2400). Output rate now matches specified input rate. Debug channels and user fields now optional. LTC CHOP is now in the Expert group of OPs
- change opsave -d to opsave -t
- When using AMD/ATI GPUs, TouchDesigner requires Catalyst driver 11.11 or later, and will warn on setup if you need to upgrade
- Wiki path now includes software version (ie. wiki077)
- Fixed OSC In CHOP channels not loading from previous builds. Updated to avoid this for all CHOPs in the future
- Fixed Keyframe CHOP rate when set to Output Full Range
- Fixed problem with searching in textport not displaying text and occasionally crashing
- MoviePlayer Component had the text for the current time stretched using some aspect ratios
- Multitouch component added to palette
- Replaced the term "tile" with "node" everywhere in the interface
- Fix for disappearing names
- Fixed Movie In TOP crash when turning off Async Upload to GPU
- Fixed shortcut keys triggering when used inside Field COMPs. Only works when shortcut uses a modifier key now.
- Fixed undercooking bug when First Input Is Index parameter is enabled in the Switch CHOP
- Fixed a crash in Movie In TOP when a CPU movie cache is used
- Fixed update bug when disconnecting and reconnecting to the same node
- Fixed issue with delete key removing characters before the cursor when at the end of an input field
- Fixed a problem where node parameters can access the wrong variable if it is called through a script that has set a variable with the same name. The wrong variable was compiled into the node and the node will error on subsequent cooks. Parameter evaluations can no longer access script variables.
- Fix in y in multitouch to be relative to screen
- Fix issue with the last filename going blank if you cancel a 'Save XX' from the right click menu on an OP
- Fix for dragging an Animation COMP into Animation Editor, it did not call launch script to set correct path
- Fix for disconnected cloned nodes in Import Dialog
- Fix in DATs, fixed a bug with duplicate rows if no rows are selected but Include First Row parameter is checked
- FPS field in timeline changed to rate
Build 16410 - Nov 04, 2011 - Gold
TouchPlayer
TouchPlayer is a new playback solution for TouchDesigner files. It is a new free key-less player for
.toe,
.tox and other media files, enabling you to share your TouchDesigner work and distribute it easily to other parties without the need to register and get a key for TouchDesigner. TouchPlayer is free of charge for non-commercial uses. No license, key, or registration is required to download and use TouchPlayer. It is available as a standalone download, and it is installed any time you install TouchDesigner.
TouchPlayer runs in Perform Mode only, the perform settings are defined by the author of the TouchDesigner file. There is a small control panel added to every TouchPlayer window with controls for play/pause, fullscreen, help, and quit. TouchPlayer can also be used to view and inspect any file types supported by TouchDesigner. TouchPlayer has the same system requirements as TouchDesigner.
TouchDesigner Ableton Live Sync Environment
TouchDesigner Ableton Live Sync Environment is a live performance and animation system developed specifically for artists and musicians to construct and perform live, interactive Audio-Visual performances. Utilizing TouchDesigner and Ableton Live, the environment simplifies the passing of loop, controller, MIDI notes and timing data between Ableton Live to TouchDesigner, and maintains the two packages in sync with each other. The system provides an optimized framework to support collaboration and development of highly dynamic immersive audio visual shows.
Cineform Codec
- Cineform codec from Cineform is a high quality, fast to decode, reasonable size codec. TouchDesigner Pro now decodes Cineform codec video files. The Cineform codec is used in film production, but we're finding it's a great alternative when preservation of image quality in the greatest requirement, while decode time in realtime is an imperative, and 5-to-1 compression ratios are satisfactory. It is designed to provide the highest quality HD footage possible and is high performance enough to handle 4K by 4K resolutions in realtime on fast Intel CPUs.
HD-SDI Video Input and Output
Using the NVIDIA HD-SDI Capture card and output card, TouchDesigner Pro can now deliver the common HD and SD SDI broadcast-formats from/to studio equipment. HD-SDI video input and output is now available in TouchDesigner Pro using these TOPs: SDI In TOP, SDI Out TOP, and SDI Select TOP.
New Components in the Palette
- new components are in the Palette. They include:
Tools/MovieBin– an interface in which you cam perform movie switching. drag-drop movies into this component, then you can select movies to play in each of its 3 outputs.
Tools/Movieplayer– plays movies with scrub bar and other controls.
Tools/Blend– takes 2 TOPs as input, and crossfades between them, with the mid-point mix being a choice of 30+ blend modes, which can be previewed before selecting, useful for live performance.
Tools/AudioSet– sets the audio input device, controls the level, and displays the output level in a VU meter.
Tools/Multitouch– outputs a multi-touch table with one finger per row, and can drive gadgets in a panel.
Tools/ShowCooks– displays cook time, dropout % and memory used
Bug Fixes and Improvements
- When using floating point R, RG, A (and a few other pixel formats), locked TOPs will not longer lose their precision when reloading the .toe file.
- Fix for loading a component .tox file that contained Keyframe CHOPs.
- Fix opdepend so inputs and extra inputs of outputs are not included
- Color space conversion in Movie In TOP uses CCIR 601 colorspace by default now
- Fix to cueing not preloading a frame
- Re-added Quadro crash fix, which was lost in build 16200.
- Fixed potential inaccuaricies of floats and doubles in OSC messages
- FBX Importer now supports importing Emission maps.
- Font searching for the Text TOP and Text SOP is more robust now.
- Beat CHOP: Fix crash when 2nd input has no channels.
- Tile TOP: Fixed Tile X and Tile Y parameters doing the oposite of what's intended. To maintain backwards compatiblity with older files, the parameters have been renamed to Repeat X and Repeat Y.
Build 15820 - Sept 26, 2011 - Gold RC
New Features
- Phong MAT - Emit Map parameter added, you need to have Emit color > 0 to have this affect the output.
- Info CHOP now reports 'fill' and 'borders' for Windows COMP.
- Info CHOP has new
depthchannel when looking at 3D textures or 2D texture arrays.
- Text DAT - the Execute page is removed because it was getting overloaded with specialized parameters, now found in the * Execute DATs:
- Text DAT - Auto-converting Text DAT to the Execute group of DATs - Loading files containing Text DATs with execution parameters set will now auto-convert into the corresponding Execute DAT type. ie: CHOP Execute DAT, DAT Execute DAT, Panel Execute DAT, Parm Execute DAT, or Execute DAT.
- Text DAT can now load files with no file extension in the filename.
- DAT Execute DAT - execute on End Frame option. This ensures the script is only triggered once per frame.
- Render Pick DAT - new parameter merges the input DAT with the output. This is important to sync the incoming select, u and v values to the picked information returned, because the render pick data is sometimes returned a frame later.
- Render Pick DAT - Column headers are always present now, even when no valid picks are occuring
- Serial DAT - added control of DTR and RTS serial lines
- toeread Command -
toeread -rto relaunch file in new process.
Bug Fixes and Improvements
- Quadro users: Added a workaround to avoid the crash in the 270.xx and later Quadro drivers. Rendering is expected to be slower than on a similar powered Geforce card until this workaround can be removed.
- Fixed undercooking bug when a variable doesn't exist anywhere, then comes into existence.
- Movie In TOP - De-interlacing optimizations.
- Movie In TOP - Movie will reload when Reload parameter is turned on, even if the Play parameter is off.
- Movie In TOP - Default unit for Movie In TOP's specify index is now frames instead of indices, which should allow for correct playback right away with
$F
- FTE Non-Commercial gives better warnings when TOPs have their resolutiosn clamped.
- Camera COMP - Window size parameter no longer disabled when using Orthographic projection.
- File CHOP looks at the audio track length, not the container length, when determining file length of audio files.
- Perform CHOP - Window x,y,w,h info for main window is now reported.
- Fix
$TOUCHnot being set correctly for files that need it during load
- Audio Movie CHOP - No longer opens the Movie In TOP if its play parameter is 0.
- Animation COMP - Trim extend conditions will now work correct when using sequential playback mode.
- Animation COMP - Older files set to use Sequential Playback with a Custom Trim range will automatically have their Trim parameters set to Cycle, since that's what sequential always did in older builds.
- CHOP Execute DAT - Frequency parameter enabled during 'Value Change'
- Render TOP - fixed rendering issue when using Rim lighting with backfacing polygons.
- Multi Touch In DAT - Fix a bug where using raw data doesn't work.
- Switch TOP - fixed case where nodes wouldn't cook when they arn't displayed in a network, if a
tab()expression was used in the chain.
- Render Pass TOP - Fixed flashing when using picking on it.
- Blob Track TOP now works correctly if given a Depth TOP as its input.
- Window Component - fix so that borders will appear inside the monitor if Window COMP is set to fill mode. This fix also allows full screen panels in player to toggle between borders & no borders. A set size will still have the borders shown outside the windows panel.
- fixed time dependency issue when blending between non-animated + animated inputs.
- preloadmovie Command optimizations.
- enable
undofor resetting parameters.
- CPlusPlus OPs - Fixed missing
#include <windows.h>in
CPlusPlusBase.h
- added support for
.tsand
.mxfvideo container formats
- new
TOUCH_ALWAYS_STARTenvironment vaiable to always startup without message boxes about GFX settings
- fixed memory leak when using
exitcommand in the middle of a loop.
- substr() expression - fixed negative indices
- convertbase() expression - fixed dropped trailing zeros and a fix for "0" and "-0"
- keyboard shortcuts for playbar disabled when option in preferences disabled
- fixed problem with parameter dialog in a pane not showing up with a scroll bar when nodes are switched.
MovieBin.toxadded to Palette
- MIDI device list now includes the NanoKorg
- saved out missing nodes from
midi.toxto avoid warnings
- Export -.
Build 14300 - June 24, 2011
- Movie In TOP - de-interlacing should work better now.
- Added Extend parameter to the Crop TOP random formatting
- File prompter will now automatically escape special tscript characters contained in filenames (
',
(,
),
$) by prefixing them with
\, when loading a filename.
- keyboard shortcuts for playbar disabled when option in preferences disabled.
- Info CHOP has new
depthchannel when looking at 3D textures or 2D texture arrays.
- Fixed problem with parameter dialog in a pane not showing up with a scroll bar when nodes are switched.
MovieBin.toxadded to Palette
- MIDI device list now also includes NanoKorg
- saved out missing nodes from
midi.toxto avoid warnings
-.
- Fixed a bug with Multi Touch In DAT where using raw data doesn't work.
- Fixed crash in evaluation of floating points in
||statements (e.g. (
0 || 0.1 || 0).
- Fixed problem with drop scripts retaining the first dropped object indefinitely.
- Fixed DAT Execute DAT where multi-row changes caused scripts to not execute.
- added Execute on End Frame option to DAT Execute DAT in case users wants to execute only once per frame per unit.
- Fix so expression field expands on mouse up to allow user to select text as-is.
- Trail CHOP no longer saves out its channel samples in the .toe file.
- Fix time dependency check in Switch OPs to only check those in use.
Build 14080 - June 02, 2011
- Shared Mem In CHOP - Fixed bug with channel names not coming across correctly.
- use of
$HOMEfor TouchDesigner preferences removed and replaced with
$USERPATHwhere
USERPATHis *always* set to:
$HOMEDRIVE/$HOMEPATH/Derivative/TouchDesigner077. If you had a
$HOMEvariable set you will need to reset your preferences.
- Fixed frame range inaccuracies when application left running for a 5 or more days.
- Fixed issues with playback when using Movie In TOP feature 'On Timeout Use Latest Available'.
- Fix memory in Touch In/Out CHOPs when multiple OPs are set to use the same port
Build 13620 - May 13, 2011
- Fix memory in Touch In/Out CHOPs when multiple OPs are set to use the same port.
- Fixed vertical auto-adapt for CHOP viewers with more than 10000 samples.
- Fixed Reset crash on Record CHOP
- Noise CHOP is a bit faster
- Beat CHOP now takes optional ramp input to override the global beat settings.
- General speed increase to rendering in some cases, required Nvidia driver version 270.xx or later. However Quadro users should NOT upgrade to 270.71 as that version seems to cause freezing.
- Texture 3D TOP, fixed starting up at wrong resolution if it's inputs started up a the wrong resolution at the initial $F value.
- Sort SOP: Fixed incorrect parameter disabling in the Primitive tab.
- Speed variation for Audio In and Audio Out CHOPs limited to 3% from normal. This should avoid some tone shifting you may here in some files when large pauses happen in playback.
- midi -g now supports arbitrarily length messages up to 128 bytes. This can be used to send SYSEX messages
Build 13380 - April 27, 2011
- Small fix to menus.
Build 13360 - April 26, 2011
- Fixed new build notification not working correctly all the time.
- Movie In TOP will no longer jump when playing sequentially if it hasn't been displayed for a bit.
- Fixed some pausing issues in movie close
- Fixed case where variable evaluation wouldn't work if the variable was contained in a string, and it was defined at the same level that you were currently 'cc' to in a script.
- Fix overcooking issued caused by some variable changes that occurred a little while ago.
- Fixed audio glitch that occurred sometimes when playing a file using the Audio Stream CHOP.
- Fixed frame stutter on timeline loop when REnd is different then End.
- Sort SOP: Can now sort primitives by type.
- Large Speed increase for Render Pick DAT and Render Pick CHOP.
- Alpha To Coverage no longer always disabled in the Render Pass TOP.
- Fixed bugs with the value ladder that caused it to lock up often.
- Audio In CHOP parameters simplified. Queue parameters replaced with a single 'Buffer Length' parameter.
- Light COMP now has Extend Mode menu for projector map. Useful to create endless projections, such as caustics using the Noise TOP.
- CUDA now works correctly when using GPU affinity.
- Network connections/disconnections have been made much more robust.
Build 12780 - April 1, 2011
- fix to expressions when not evaluating at current frame:
chopf()(evaluate given frame).
chopcf()(evaluate given frame using channel index). They were only giving correct results when the CHOP sample rate was equal to the timeline frames per second. Also chop() was giving the wrong result when the CHOP was not timesliced and the sample rates was different than the timeline's.
- fixed
opinfo()when in Switch and Cross TOPs.
- fixed bug where Render Pick DAT and Render Pick CHOP had bad texture UVs returned where UVs were passed to instances in the Geometry Component Instance page.
- Movie In TOP - the old movie was kept open after you cleared the File parameter.
- added "Mirror" in the Animation Editor as an Extend Condition outside the defined range. (under Add Channels, the choices in the 2 menus for Extending Left/Right for a channel are Hold, Slope, Cycle, Mirror and Default Value.
Build 12660 - March 28, 2011
- new
Count.movin the Map folder. It is 100 frames long with the frame number in each image, and a rotating wheel. Useful for determining playback smoothness.
- The
+operator adds instead of appends the two strings if both parts are numbers. Thus
tab() + tab()adds values as numbers if both results of tab() are numbers.
- new Preference allows CHOP Channels to be displayed in separate graphs. Edit -> Preferences -> CHOPs -> Graph Viewer.
keystate()expression is now case insensitive.
- improvements to display in Animation Editor, Timeline, various dialogs
Build 12600 and earlier
This section includes release notes from build 12600 back to build 4200 inclusive.
Palette components
- new Movieplayer component was added to the Palette in the Tools section. Drag-drop a movie file or TOP onto the component. You can change its internal define table to expose options or manually set the file path.
- Palette Browser and Media Browser updates.
- Palette has new folder and has been reorganized to make it easier to find components.
- Palette now has a suggestion box for user to send in suggestions for new components they would like to see.
- Media Browser has favorites.
UI Changes
- Find Operator Dialog to find a node in the current network. Ctrl-F in a network.
- OP Create Dialog shortcuts to add multiple nodes
- Ctrl-click for adding multiple nodes without the dialog closing.
- Shift-click for adding multiple nodes and wiring them up. This also works with "compatible" nodes (ie. Table DAT -- DAT to CHOP, the DAT parameter is filled in)
- new Search Dialog for easier searching in .toe files. Alt-S or Dialogs -> Search. Uses
findcommand inside.
- new Errors Dialog helps track form node errors. Clicking on errors takes you to their source.
- Nodes will now save their viewer state in a
.toeor
.toxfile and they get restored when you start again. There are new command options to clear the node viewer settings:
view -r nodesReset view settings.
view -R nodesRecursively reset view settings for a component and all its children.
- entering Perform Mode - now turns on power button (formerly knowin as the "
play" command).
- RMB -> Keyframe Parameter... on parameters now creates an Animation component and hooks up the new channel to the parameter.
- New behavior for hierarchical geometry picking to reflect new node picking behavior:
- Handle when parents are invisible or have no geometry.
- Only top level geometry nodes are picked on selection. Lower level nodes will be highlighted in a duller yellow and thier pick flags will be off. Current nodes at the top level of selection will be highlighted in green.
- Shortcuts to stop the timeline in Perform Mode - In the past, the space bar stopped the timeline, possibly a disastrous behavior in live performances when space bar is accidentally pressed. This and the right-arrow (step forward one frame) and left-arrow (step back one frame) now do nothing in Perform Mode. To pause, step forward or backward in Perform Mode, you must hold down Shift at the same time. This is how it works in new
.toefiles, but in existing
.toefiles, you need to add these six rows to
/local/shortcuts:
general.command space general.command left general.command right general.command shift.space space general.command shift.left left general.command shift.right right
- In Designer Mode, the behavior is still the same as before: Space bar pauses, right-arrow steps forward one frame, and left arrow steps back one frame.
- Import File Dialog now lets you enter the animation frame rate when importing FBX files with embedded animation.
- updated Export Movie Dialog functionality, now includes ability to set custom timepath (Time Component).
- new MIDI Mapper Dialog.
- new CHOP Exporter Dialog - on CHOP node, RMB -> CHOP Exporter...
- Animation Editor
- When selecting/deselecting segments in the Animation Editor, the keys bounding that segment will be selected/deselected.
- Added option in Graph COMP to hide slopes when not selected.
- Scale handle will now reset when the graph is zoomed & scrolled. it is also disabled in multi graph view.
- Vertical auto homing has been disabled in the keyframer. To home, use the 'h' or 'v' key.
- Multi-Graphs in Animation Editor via RMB -> Graph per Single Channel. 1-8 graphs visible at once via Number of Graphs
- the arrow on parameter paths now bring up the network in a floating pane
- Preferences are now consolidated in
$HOME/touch/pref.txt(and use new UI)
- easier Remove Export - Added ability to remove exports by right clicking on a parameter and choosing ‘Remove Export’
- file browsers - When you bring up file browsers, it will stay in the same file path folder after you bring it up another time, unique for each file type. So saving a .tox file at one location won't change the path that comes up when you save an image, or open an audio file.
- CHOP graph viewers are a lot faster when displaying many samples (like audio).
- new Pane path gadget - It is now a TouchDesigner panel component and has better navigation capabilities.
- UI Drawing speedup - 1.3x to 3x faster drawing of the UI, particularly networks.
- TUIK is replaced with new version, TUIK 2.0
COMPs - Components
- Replicator component -
- No longer deletes master if its part of the replicated nodes.
- Added an optional script command to run on each replicated node.
- Default script is : "opset -d on $ITEM"
- The variable $ITEM is replaced with each replicant node's name.
- Its run relative to the specified location.
- new Table COMP component - The Table component a grid of similar interactive cells. This is the most powerful feature of this release - grids of interactive buttons with one lightweight component.
- added a second click format for Table Components. The two methods are:
click /table1 5#Click the cell with id 5.
click /table1 2 3#Click the cell in row 2 column 3.
- Animation Component - added Sequential mode, which allows for pausing, speed control, and cueing to specific points.
- Container Component - Align menu Layout Grid was split into Layout Grid Horizontal and Layout Grid Vertical.
- Window Component - 'Viewer Interaction' toggle (default off). Avoids window component interaction from changing SOP/CHOP/TOP/DAT/MAT views.
- Replicator Component - changed the Script parameter functionality (where you can run a script per-item created) to be a string parameter with a menu of typical choices that can be added.
- added variable
$MASTER, which refers to the Replicator master node.
- added Script menu entry to make the replicants be clones of the master:
opparm $ITEM clone ( $MASTER ) ;
- Table Component pop-up help attribute added. Table Component cells are defined by attributes (
label,
bgcolor, etc). The new attribute named
helpdefines rollover help for each cell. i.e. You can define the rollover help for each cell of a Table Component by defining this attribute.
- Table Component - changed the way fields were specified in order to allow an input cell attribute and output cell location. Now allows you more editing control.
- Instancing in the Geometry Component is extended - U, V and W channels were added so you can explicitly set the UVW texture coordinates.
- The state of the 'Save Backup .tox file' parameter is now preserved when loading an external
.toxfile using a COMPs External
.toxfile parameter.
- You can now specify the viewing angle of Camera/Light COMPs using horizontal or vertical FOV, instead of focal length/aperture.
- Window component
- recooks when floating window is resized to allow Info CHOPs to update resolution info dynamically.
- press Esc over a floating window to close it. Window components have the additional option to suppress this Esc key feature.
- Select component mode now fits to the original source resolution, then squashes to its own resolution, instead of just laying out to its own resolution.
- Table component new cell attribute: wordwrap on by default.
- Drag / Drop defaults - All panel components are default "Do Not Allow Drag" and "No Not Allow Drop".
- Keep in Memory after Close new parameter in all panel components speeds up the opening of the panel when opened a second time and thereafter. It will keep in memory the UI objects needed to render/layout the panel.
TOPs - Texture Operators
- libavcodec is now the default movie playback library. QuickTime can be re-enabled in TOP Preferences.
- Note: no Unicode in file names - libavcodec does not read file name that contain Unicode characters.
- new Blob Track TOP - up two blobs in the FTE version, unlimited in the FTE Commercial and Pro versions.
- new Convolve TOP - uses a table of coefficients located in a table DAT.
- new SSAO TOP - Screen Space Ambient Occlusion TOP.
- new Analyze TOP - for basic image analysis like the Analyze CHOP.
- new Luma Blur TOP blurs an image on a per-pixel basis depending on the luminance value of the second input.
- new CPlusPlus TOP (FTE Commercial or higher), allows you to create custom .dlls that can create textures however you want (Using OpenGL for example).
- Cube Maps
- Render TOP renders cube maps in a single image, usable directly as a reflection map in the Phong Material. It forces the field-of-view (FOV) to 90 degrees and renders the scene 6 times, automatically rotating the camera for each cube side. The negative Z side is the direction the camera looks at by default.
- seamless Cube Maps - A cube map made with the Cube Map TOP or the Render TOP's cube map option now interpolate cube side pixels at the edges by default on video cards that support them.
- Render TOP will now give a warning if the resolution isn't square when rendering a Cube Map. It will change the resolution to be square automatically also.
- FBO changes - TouchDesigner graphics run faster due to use of "FBO" (Frame Buffer Objects), an OpenGL structure which is faster than older structures. You can revert to the older structures by enabling TOP Compatibility Render Method in Edit->Preferences->TOPs.
- Support for loading DXT1, 3 and 5 compressed .DDS files added
- Movie In TOP - new
mv_has_audiochannel in the Info CHOP for the Movie In TOP.
- new Movie In TOP Parameter: Cue Behavior. Controls the behavior of the node when the Cue parameter is released.
- Video In TOP - new menu to select which video library to use (DirectShow or Imaging Source), as we were seeing stalls when Imaging Source was attempting to enumerate cameras on a system that didn't have any Imaging Source cameras.
- Shared Mem Out TOP and Shared Mem In TOP pixel formats - many new pixel formats and data formats listed in TOP_SharedMemHeader.h for use with shared memory TOPs.
- Texture 3D TOP now has the ability to directly replace a specific index in the texture.
- Cache TOP now has the ability to directly replace a specific index in the texture.
- Level TOP now has the ability to work on floating point pixel values without pre-clamping the input to [0-1].
- Level TOP is much faster when animating parameters.
- Render TOP now supports outputting to as much as 16 color buffers, if your GPU supports it.
- GLSL TOP now supports outputting to multiple color buffers in a single pass using gl_FragData[] instead of gl_FragColor. Use the Render Select TOP to view the other color buffers.
- GLSL TOP and GLSL MAT both have more array uniform parameters available for use.
- CPlusPlus TOP will now reset some more of the buffer object states to Off so it's easier to write OpenGL code in the CPlusPlus TOP.
- 2D Texture Arrays no longer have their width/height clamped to a low value. They support the same max width/height of a regular 2D texture.
- new clearcaches Command clears any cached CPU or GPU memory that may be hanging around (only GPU memory for now). Use the memory Command to see how much memory is used for caches.
- Movie In TOP folders containing a sequences of images - added support for an
info.xmlfile in the directory with a sequence of images.
info.xmlallows you to specify the frames per second and an audio file to be used with the sequence of images when they are played in the Movie In TOP. Example xml file:
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?> <Settings> <attributes fps="30.0" /> <audio filename="audio.wav" /> </Settings>
- Render TOP - default resolution for a new Render TOP is now 1280x720
- CPlusPlus TOP - The bound FBO index is now passed into the execute() method.
- Movie In TOP - will now stop cooking when it reaches the end of the movie when using Sequential Playback mode and the extend mode is set to Hold.
- Cache TOP - fixed bug where it wouldn't work correctly with Phong MAT (when mipmapping is enabled, which it is by default).
- GLSL TOP - new int uniform called 'uPass' which lets you know which pass you are rendering in a GLSL TOP (when using the Num Passes parameter on the Common page). Starts at 0 and counts up from there.
- SSAO TOP - now has option for Quarter resolution SSAO pass.
- The behavior of the Text TOP when both word-wrap and auto-sizing are enabled has changed. It will first word-wrap the text based on the specified font size, then auto size the resulting block of text.
- Resolution TOP new scale-down type - new High Quality Resize operation available in the Resolution TOP, uses weighted sums, which has less bleeding than mipmapping. (currently in testing)
- Displace TOP accuracy - The midpoint value for Displace TOP is now quantized to match the bit precision of the displacement map (if it's 8 or 10-bit), so for example a midpoint of 0.5 will match a color of 0.5 now.
- GLSL Multi TOP now supports up to 9999 inputs.
- GLSL vertex shaders - new
TouchGetRotationMatrixavailable on vertex shaders, which calculates the rotation matrix needed to rotate from one vector to another.
- CUDA TOP can now return string/numeric values via the Info CHOP and Info DAT
- Movie In TOP - added de-interlacing features
- Field Precedence feature in Movie In TOP for better control of de-interlace feature.
- Video In TOP now supports Imaging Control library from The Imaging Source. If you have Imaging Source cameras (and their drivers installed), the cameras will show up in the Video In TOP camera menu with (IC) after the name. The cameras will usually be listed twice, once through the normal Video In library (DirectShow), and once through the (IC) library.
- Video In TOP has new Async Upload to GPU feature for faster GPU uploads, at the cost of higher GPU memory usage.
- new Blob Track TOP - up two blobs in the FTE version, unlimited in the FTE Commercial and Pro versions.
- Ramp TOP dithering - The new Dither parameter helps avoids banding in gradual ramps.
- TOP field guide - you can overlay a field guide on a TOP via the TOP viewer's RMB menu or the shortcut "f" in the TOP viewer.
- Constant TOP accepts any numbers for RGBA, no longer 0-1. Useful when using TOPs' pixel formats like 32-bit floating point RGBA values.
- Screen Grab TOP parameters are separated as Left, Right, Bottom, Top, like the Crop TOP. (Note its only *partially backward compatible. Saved expressions will be lost, but constant settings are converted
- real-time Noise TOP on GPU - was formerly only slow on CPU. both available.
- added Harmonics parameters to GPU noise functions
- Movie In TOP faster - uploads less memory to GPU when working with movies that decode to YUV colorspace, such as H264.
- Movie In TOP with Audio Movie CHOP plays more steadily as the Movie In TOP and the Audio Movie TOP read independently.
- Movie Out TOP logs total # of dropped frames when it records a movie into a file. It restarts at 0 each time a new movie starts. Use the Info CHOP to get at the values.
- Blur TOP smoother It gives smoother results when outputting 8 bit and 32-bit images. In addition, it now has a Dither parameter which makes 8-bit blurs look smoother.
- Shared Memory TOPs are now in FTE Commercial.
- Render TOP dithering - The new Dithering parameter reduces the banding on gradients in 8-bit images. (You can also make your images output as 16-bit images or more.)
- Text TOP line spacing - The new Line Spacing parameter used to be the Kerning Y parameter. The Kerning Y parameter now kerns in Y per-character, as one would expect. Backward compatible.
- still images from Movie Out TOP - The TOP can produce movie files or still image files like TIFF, JPG and BMP.
- getting alpha into movies with RGB-only formats - Alpha Split in Movie In TOP - You need to construct the movie with alpha in the bottom half of the image, and the movie is double the height resolution. The movie needs to be one of the YUV format movies like H.264, MPEG-4 and others.
- The alpha split code only works with video that decodes to YUV420 or YUV420J. The alpha-rejoining internally is done in a CUDA kernel.
- Bottom Half of Image is Alpha (AAA) flag, enabled if CUDA YUV to RGB is on.
- Render TOP linear depth - The Render TOP now can output linear camera space depth to the Depth TOP (when using FBOs + 32-bit float depth buffer).
- more pixel formats added to TOPs. Look at TOPs' Pixel Format menu for the full set, including single-channel formats (like alpha-only) and packed formats (like 10-bit RGB with 2-bit alpha in 32-bits).
.ddsDirectX Image files - TouchDesigner now supports reading many types of
.ddsfiles. Most combinations of R, G, B and A formats are supported. Luminance formats and YUV formats are not.
- new FreeType text rendering - Text TOP and all UI text now renders with the open source FreeType software, which produces better rendering at small and large point sizes. It supports all TrueType fonts.
- personal TrueType fonts - Text TOP now supports loading .ttf (TrueType font) files, and they work with embedded files via VFS. This means you can control the fonts of your synth by embedding them into the .toe or tox files.
CHOPs - Channel Operators
- Beat CHOP - previously known as the Timing CHOP.
- now generates its own ramps, using its Time Component's BPM value.
- added option 'Locked to Timeline' as opposed to Sequential modes that ignore resets and scrubbing. Split "Sequential" into "Local Sequential" and "Global Sequential".
- Added
baroutput (as in musical "bars").
- Split 'Shape' menu into separate options on an 'Output' parameter page, added "Beats" and "Sixteenths"
- Names now created by type (
bar1,
bar2,
beat1,
beat2), not generically (
chan1,
chan2,
chan3,
chan4)
- new 'Reset Bar Value' parameter which takes into account time Signatures and Period. Eg: Reset Bar Value = 2.25 will hold the output at Bar 2, Beat 1.
- new "Reference Node" parameter lets you get beats as seen by another component.
- Serial In CHOP and Serial In DAT was renamed to Serial CHOP and Serial DAT as they provide both input and output capabilities.
- accuracy of Speed CHOP was increased.
- Audio Out CHOP parameters simplified. Buffer Length parameter replaces Min/Max Targets, Queue Size, and Recovery parameters.
- OSC Out CHOP now supports multiple connected clients when using the UDT protocol.
- You can now use OSC In CHOP, OSC In DAT and UDP In DAT at the same time, on the same port, in the same process and all will receive data.
- Perform CHOP - added
cookrateoutput channel.
- Audio Stream CHOP - added 'Fraction' to all the unit menus to allow 0-1 range for whole audio file.
- Logic CHOP - On Value Change feature in Logic CHOP no longer triggers when the channel name changes. The new On Channel Name Change option added for cases where this behavior is desired.
- Gesture CHOP
- Input lookup wave is now generated internally with time parent BPM value.
- added Reset input, Reset button, and Reset condition.
- removed "Listen Blend", and "Use First Input as Gain When Looping", which were not implemented, and always disabled.
- fixed broken loading of saved data and choppy recording.
- Filter CHOP - remapped the Gaussian curves (which by their nature never reach 0) in order to hit endpoints at zero, to minimize discontinuities.
- Touch Out CHOP, Touch In CHOP - new Unicast UDP (regular UDP) and Multicast UDP feature in Protocol menu of the Touch In/Out CHOPs. It will be extended to other network OPs later. Testing phase right now.
- To use Multicast, make the nodes send and receive using an address between 224.0.0.1 and 239.255.255.255 (these are *not* the actual IP addresses of the machines).
- Touch In CHOP - added 'Recover Outside Range' option which grows/shrinks the queue to the middle of the target zone when it sits outside the range too long.
- Filter CHOP - new 'Ramp Preserve' method to straighten wobbly ramps.
- Logic CHOP - renamed 'First/Last Channel On' to 'Lowest/Highest Index On' in order to clarify its function.
- Timeline CHOP - added more output options for the Time CHOP (bar, beat, sixteenths, ramp_bar, ramp_beat) withing the Time component.
- Object CHOP has new table driven features for better performance. This is much faster for timeslice mode involving several object pairs, as it doesn't have to continually rewind the global time to recook the transform hierarchies.
- You can now specify a two-columned table to specify all the target and reference objects.
- CHOPs with Reset inputs and Reset parameters are unified to behave exactly the same:
- the affected CHOPs are: Oscillator CHOP, Count CHOP, Speed CHOP, Beat CHOP and the new LFO CHOP.
- They all have an extra input, whose label is "Reset".
- new 'Reset Condition' menu (Off to On, While On, On to Off, While Off)
- new Sequencer CHOP - Will sequence data from a number of CHOPs specified in a DAT table.
- Lookup CHOP - Added 'Cyclic Range' menu. (Auto/Yes/No). Yes: For looking up a cyclic output (oscillator, beat driven output etc). No: For looking up a single wave (slider mapping, etc). Auto: Check the right extend condition of each channel. (Assumes type cycle and mirror are cyclic lookups).
- All CHOPs including timesliced CHOPs now use component time and frame rate, not internal frame rate (Example: Object CHOP)
- Render Pick CHOP channel name changed from
instanceIDto
instance.
SOPs - Surface Operators
- Particle SOP will now have 0 points when it is resetting. Added menu to determine what to do while Reset is 1.
- Point SOP - will cycle through points in second input if point numbers don't match.
- Text SOP - now supports newlines and tab characters (
\n,
\t).
- new Text SOP, which will replace the Font SOP once it is more feature complete. This uses the same library as the Text TOP, and can load .ttf files directly.
- DAT to SOP - can now create a particle system primitive.
- Sort SOP - new Particle page for sorting particles for doing things like Z-sorting them.
- Channel SOP has been renamed to CHOP to SOP
- Trail SOP - new Accurate Timing option.
DATs - Data Operators
- new Execute DAT - will execute script on conditions, including at the start or end of every frame:
- On Start (after the process starts)
- On Create (when the DAT is created, like when it is copy-pasted from somewhere else)
- On Frame Start (at the beginning of every frame of the timeline)
- On Frame End (at the end of every frame of the timeline)
- Bypass Flag on an Execute DAT will keep it from executing the script.
- new Multi Touch In DAT - reads Windows 7 multi-finger input events and puts them in a FIFO table (first in, first out). It calls a script you write for every event coming in.
- new Render Pick DAT used with multi-sample points expressed in a DAT.
- new OSC Out DAT and UDP Out DAT
- OSC In DAT, UDP In DAT that had their 'Address' parameter filled in with automatically were changed into OSC/UDP Out DATs, since that's how they were behaving essentially. (Double check your files though).
- OSC and UDP In DATs now support multi-casting.
- new Error DAT - outputs errors generated by TouchDesigner.
- Error DAT - added "Log Current Errors" to capture current node errors.
- Major Change & Performance Improvement - The Select DAT and Evaluate DAT will now support per-cell dependencies, which avoids cooking all nodes that are referencing cells in table unless the particular cell they are interested in has changed.
- String parameters will now reset back to their original value when a DAT export is turned off, instead of keeping the exported value.
- new Touch Out DAT and Touch In DAT for sending full tables across the network, as opposed to messages with the other network based DATs.
- File Out DAT - streaming data into files and minimum overhead
- It now accepts 0 inputs, and supports the
sendcommand, which lets you append a string to a file, or a whole DAT to a file.
- If 'Append' is off, a new file is written every time, if 'Append' is on, the file is appended to, and the file handle remains open.
- In either case 'Write' needs to be on, if not, current file is closed.
- The Sequencer CHOP's defining DAT table now contains a column
requeuewhich when set to 1 re-adds the row to the end of the table after playing.
- Info DAT pointing to the Sequencer CHOP
- added
elapsedcolumn (elapsed time, taking into account speed, pausing, etc)
- added time (current time)
- added
sncolumn (serial number index)
- Multi Touch In DAT - now defaults to output a table that has one row per pressed finger, with a variety of useful columns like U, V, X, Y, times since press, serial number, double-click. Try the quick-start on the Multi Touch In DAT page.
- Web DAT - now supports asynchronous download so that it does not stall while it's fetching a web page, and you get notified when the page is available. Use the Info CHOP to monitor the progress. Use the DAT Execute DAT to respond to a completed download.
- Web DAT now supports using connections.
- Web DAT - now works correctly with more types of web pages that have various character encodings (Pachube for example). Using libiconv.
- Web DAT extended to also use the name/value pairs input table during 'GET' operations. Use this table instead of manually creating a URL link with "?name=value&name2=value2...." extension. This also properly encodes words with spaces, special characters, etc.
- Web DAT has a new timeout feature, defined in milliseconds.
- Substitute DAT
- added Case Sensitive flag, No Auto-Expand option
- a new Expand to String option to substitute in an exact phrase without using backslashes.
- TCP/IP DAT - now supports receiving extended ASCII characters.
- New format for exported DATs which use explicitly named columns. The columns are: path parameter value enable. The enable column is optional and defaults to '1' when blank. Note how the destination parameter is split into two cells, path and parameter. The previous format for exporting DATs is still supported, though a warning will be generated.
An example exported DAT table might contain:
path parameter value enable /project1/geo1 rx $F 1
- CHOP Execute DAT - by default it triggers On Value Change instead of Off to On.
- CHOP Execute DAT - the CHOP sample index is now passed as an arguement to the script when it is triggered. The scripts gets called for every sample that changes, so when rendering one frame, it may get called 2 or more times per channel, depending on how many frames forward TouchDesigner has stepped (see Time Slicing). The sample index is compatible with the
chopi()expression (so it may not necessarily start with 0, but the CHOPs index range).
- Select DAT choose by expression - Parameter for Select DAT to select by condition. Local variables for evaluating condition $S,$R,$C available.
- FIFO DATs - Consolidated all the input FIFO-style (first in, first out) DATs (Midi In, Midi Event, OSC In, UDP In, Serial, TCP IP) -
- The rows now saved in the .toe so its re-starts with the same data as it was saved in.
- All output is under two headings
messageand
value.
valueis the decimal expansion of all the bytes in message.
- You can run a script for every message received. The new Log tab lets you set the script and maximum number of rows of the DAT.
- new Format menu for Serial, TCP, and UDP In DATs - what appears in each row of the DAT -
- Per Byte
- Per Line - null/newline delimited
- Full Message
MATs - Materials
- GLSL MAT - now sends matrices beyond the first one into the shader (on the matrices page).
- GLSL MAT now accepts integer vertex attributes (such as the id attribute created in particle systems).
Panels and UI Building
- Panel Value '
winopen' now reacts to Perform Mode and floating viewers.
- Window Components and the view Command now update Panel width/height parameters and screenw/h panel values.
- panel value
wheel- added "wheel" panel value. Sends a pulse of a positive or negative number and then back to 0
- dissolving out panels with the Display parameter - The Display parameter of all panel components now acts as a partial dissolve between 0 and 1, so you can fade in and out your panels. (Tell us if you don't like it.)\
- default Slider, Button and Field components now contain a few operators to make them immediately functional.
Scripting
- disabling crash files - You can use
TOUCH_DISABLE_CRASH_HANDLERSEnvironment Variable to disable the
.dmpdump file creation and out of memory warning in TouchDesigner.
- Variable evaluation now adds dependencies up the tree as component variables are evaluated, so if a new one comes into existence lower in the tree, it will cause the node to cook and take precedence.
- Added built-in variable
$SYS_MAINMONITORwhich returns the index of the main monitor display.
- Redirecting command output to files -
- Redirecting command output to a file always expects a
FILE:prefix. See Redirecting in Tscript.
- Support explicit echoing to relative or absolute disk paths. Requires a
FILE:prefix to denote that you want to write to a file instead of a DAT
- Always expects a
FILE:prefix, else continues, but outputs warning.
- eg:
echo abc > FILE:C:/abc.txtinstead of
echo abc > C:/abc.txt
- Invalid disk names are:
abc.txt(no colon, assumes DAT)
- echo Command - You can echo to files now, using relative or absolute filesystem paths.
- A "
FILE:" prefix can be used to explicitly denote a disk path.
- A disk path is assumed if it has a colon anywhere in the path.
- Ctrl-Break will get you out of long cooks or scripts that are looping. (Ctrl-Break on a Mac keyboard)
Commands
- view Command -
view -Cwill close topmost parent panel.
- vfs Command -
vfs -L *will now list recursively.
- oprm Command - is now faster when doing a lot of nodes in one go.
- macro Command overhaul - Typing
macrogives a list of macros and their location. New options help you find location of macros. Made fixes to default macro location when issuing
macrocommand, as well as giving more meaningful details when listing macros.
- clearcaches Command - clears any cached CPU or GPU memory that may be hanging around (only GPU memory for now). Use the memory Command to see how much memory is used for caches.
- view Command - open/close node viewers
- vkey Command - input keys virtually. keys will be sent to the current keyboard focus.
- vclick - The
clickposcommand renamed to
vclick.
clickposis deprecated but will stay functional for a while.
- quit Command will no longer prompt to save file, if that option is disabled in preferences.
- exportmap Command - now separate destination path from the parameter.
- new cookrate Command and $COOKRATE to replace old fps Command
- new realtime Command -
realtime on|offto replace
fplayback -r on|off(and made backward compatible)
- fcur, fset, and frange commands for working with frames, timecur, timeset, and timerange commands for working in seconds.
- power Command - operates the 0|1 button at top, replaced
playcommand with
powercommand. Returns current state if no args given.
playcommand continues to work but gives a warning.
- memory Command now reports CUDA memory usage.
- time Command - added
-eoption for time command to show Epoch time (the time in seconds since midnight 1st January 1970, the birth of UNIX).
- removed commands
playand
fplaybackno longer needed, replaced with
powerand
realtimecommands.
- lf Command options to format its list: lf -s (sort), lf -i (case insensitive sort)
- run Command has new
-eoption to specify the delayed script should run at the end of the frame instead of the start of the frame.
- opadd Command and optypes Command will now list all OP types, even Expert ones when Expose Expert nodes isn't turned on.
- toewrite Command extended
- toewrite -s (Same as "File -> Save" from the pulldown menus)
- toewrite -a (Same as "File -> Save As" from the pulldown menus)
- undo command extended:
-u undo the last block of operations. -r redo the last block of operations. -u -l List the name of the last block of undo operations. -r -l List the name of the last block of redo operations.
- findpanel Command and clickpos Command - added priority. Priority in the following order:
- active panel in a floating window
- active panel in a activated opviewer
- active panel in a opviewer top
- inactive panels in the above order
- args Command was extended to allow for single-letter options.
args "-t temperature" name1 name2will let you call a script passing it two arguments and one option,
-twhich gets assigned to the variable
temperature.
- memory Command -m option suppresses 0-meg OPs
- netscope Command - brings up a network in a floating window. the new -v option returns name of new pane.
- new inline Command runs scripts, but unlike the
includecommand, it does not push-pop variables. Like
include,
inlinedoes not change the current folder, whereas the
runcommand changes the current folder to the location of the script it is calling (and
runpushes/pops variables).
- new ex Command will echo what follows and then execute it.
sendcommand sends a message out to TCP/IP, UDP, OSC or the Serial port. The message is the text given on the command line or in a DAT.
- When sending the contents of a table DAT and sending as bytes, each cell of the table is parsed into individual bytes, else each cell of the table is separated by a space and each row is terminated by the specified terminator character. (See its help for more examples).
- data can be sent as raw ASCII data (default), or as (
-d) decimal, (
-h) hexadecimal or (
-o) octal codes.
- output to OSC has an extra option,
-Ofor specially-formatting OSC messages.
sendcommand to output 'carriage_return linefeed'
Expressions
var(path, name)expression now evaluates the variable from the context of the path, instead of assuming its a local variable of the path component directly. Example:
var("/project1", "BPM")
- new
keystate()expression to return state of various keyboard buttons
- new expression
convertbase()- converts a number from one base to another. * Ex: 255 from decimal to hexadecimal:
convertbase("255", 10, 16) = "FF"
- new expressions
tofloat() todouble()- helps with precision problems when dealing with CHOP sample values, etc. Example: You set a Constant CHOP to
.1(a number that doesn't have an exact digital representation, not matter how many bits). CHOPs are stored as 32-bit, expressions compute at 64-bit.
chop()converts from 32-bit to 64-bit which gives
.10000000149012.
tofloat(chop())gives
.1.
- par() expression supports the
par("path:parameter")syntax, preferable to the still-supported
par("path/parameter")syntax.
- all
chop*()expressions now accept arguments of the form:
path:channel. example:
chop("/project1/wave1:chan")
format()expression - changed so blank space is not left in front of positive numbers.
- oproot() and oprootf() - new expressions
oproot(path)
oprootf(path)which returns the root node of the hierarchy containing the node specified by path.
- [[fit()] - no longer clamps the output inside the new range.
- new expressions frametotimecode() and timecodetoframe(). Takes a sample rate and a time expressed in one of the two ways, and converts to the other way.
- new timepath() expression - will return the path to component defining time for the current component. If root is 1, the root time will be returned instead. Examples: timepath(0) // current time path. timepath(1) // root time path. timepath("anypath") // path of any node.
- new parevalpath(parm) returns the full path to the node specified in the parameter. The parameter may contain expressions, and relative paths.
- new cvar() expression - This expression will return a component variable as evaluated from a specific path. The variable may reside in the path, or may reside in in a containing component further up the hierarchy.
- Example: cvar("A", "/project1")
- Example: cvar("TOUCHTIME", "/")
- new panelscreen() expression - You give it a panel name and it gives you the location of its bottom left and top right pixels.
- new backslash() and forwardslash() does string substitution: set path = `noevals(backslash($path))`
New or revised wiki pages
Backwards Compatibility Issues
- The bottom half of the Window Placement Dialog (defining the second monitor) is deleted as it is obsolete. Please use the new and more flexible Window Components. If you need the older functionality, you still have the winplacement Command which we will remain in for the next year.
- CUDA
- Toolkit upgraded to version 3.0. Use of any CUDA feature requires driver 197.00 or later.
- CUDA DLLs for the CUDA TOP will need to recompiled using the 3.0 version of the CUDA Toolkit (not 3.1).
- New Web DAT parameters cause previous settings on Update and Fetch page to be lost. Features from that page have been collapsed onto the first page.
- Expressions used to give Root and Component Variables precedence over script values, if two were named the same. The previous behavior was incorrect and is now fixed. If a script variable is defined it will take precedence over any defined Root or Component Variables.
- Components will no longer look inside themselves when evaluating variables in their parameters. This is also true for the Path Variable parameter, it will no longer be resolved if a component references the variable in the same parameter page. See this forum post for more information:
- The
-Ooption in the send Command has been deprecated and replaced with
-s, which requires both the OSC tag(s) and the OSC address. OSC address is no longer the first argument given after the node path the send command sends through.
- The send Command will now automatically append a null character when sending a string unless some other type of terminating character (null,
\n,
\r) is given using the
-z, -
n,
-roptions. You can disable this behavior using the
-xoption.
- Macros can no longer have characters that are not legal in a regular node name (numbers, letters and underscore).
- exportmap Command reworked to allow for removing of individual destinations. Old usage of the exportmap command will need to be updated.
- The "# of Color Buffers" parameter in the Render TOP and CPlusPlus TOP, as well as the "Color Buffer Index" parameter in the Render Select TOP have been changed to integer sliders. Files should be backwards compatible unless exports are used to set theses parameters. In that case the exports will need to be setup again.
Bug Fixes and Improvements
- fixed bug where OSC In CHOP wouldn't get the correct channel value the first time it received a new channel.
- Fixed Parametric EQ CHOP getting into a bad state when Frequency or Bandwidth parameter get set to
0(by clamping them to
0.00001)
- Fixed -f option in geoimport Command not working correctly.
- Fixed normal and vertex ordering issues of extrude, hole/unhole, font related SOP functions.
- Level TOP bug fixed that caused it to use Linear interpolate even when Nearest was selected. Speed improvement for Lookup when using Luminance.
- Fixed update issues changing the timeline rate with expressions involving $FPS.
- CHOP Execute DAT fixes where it was causing intermittent double executes per frame.
- fixed problems with Near/Far planes getting reset when homing the Geometry Viewer.
- Shared Memory Operators - If you recompile your
.exefiles with the latest
UT_SharedMem.cppand
UT_SharedMem.hincluded in the installer, the OPs should handle clearing the shared memory better when the sender opens/closes.
- GPU Affinity Mode 1 is not longer enabled by default for Windows Vista/7, set it using TOUCH_GPU_AFFINITY_MODE = 1.
- fixed crash when Network OPs have a blank string for their address.
- fixed Memory Leak when Network Out OPs are in an error state.
- Level TOP - Fixed bug where if Step Size was 0 but Threshold wasn't, the result were different than they were in older builds.
- Fixed crash in Point SOP when 2nd input has no points.
- Fixed endless export conflict warning with conflicting DAT exports.
- Displace TOP - Setting the x/y Source to None now works correctly.
- fixed broken Camera Blend COMP
- removed Camera warning from Render TOP
- fixed bug where
$TOUCHvariable is unchanged after opening a project from a different directory.
- Angle CHOP output is now fixed.
- Startup window placement was slightly inaccurate in operating systems with thick window borders, cutting off top menus.
- fixed bug when upgrading exports in old
.toefiles.
- Exports get converted from old
.toefiles better.
- fixed memory corruption in Angle CHOP.
- fixed Blob Track TOP bug that caused it to not work correctly on resolutions that had a width that wasn't a power of 4.
- SSAO TOP Quarter Resolution option is now works correctly.
- added workaround for driver bug on 400 series of Geforces that broke the SSAO TOP.
- The version conflict dialog box will no longer show up more than once per build number.
- Touch Out DAT now cooks less often. It also now correctly sends data to any newly established connection.
- Fix Joystick CHOP values going to 0.5 when they reach 0.
- Fixed bug where chop() expressions wouldn't come alive when channels they were looking for came into existance.
- Fixed Scope parameter not working in the Delay CHOP.
- SOP to CHOP will now have no channels if the source geometry has no points.
- fixed Camera COMPs in files saved in build before 7260 loading up with their viewing angle set incorrectly.
- Movie Out TOP fixed - was not working correctly when recording at a lower FPS than the playbar.
- fixed crash when attaching a SSAO TOP to a Render TOP with no camera.
- fixed bug that caused multiple Render Pick OPs to not be able to target the same Render TOP, in some cases.
- fixed crash when attaching a SSAO TOP to a Render TOP with no camera.
- fixed bug where camera targets wouldn't import correctly via FBX, if they didn't have animation tied to them.
- Save Component dialog will now start at a more logical spot when it's used on a COMP that has an external
.toxfile defined.
- re-implemented
$COOKRATEvariable to allow dependent nodes to recook upon update. Fixes update issues when changing framerate.
- node RMB menu entry 'View / View Borderless' now pops up existing viewer if it exists instead of always creating a new one.
- Fixed the cookEveryFrame feature in the CPlusPlus OPs not working
- Fixed GPU memory leak that occurred when navigating through networks then deleting those networks.
- Fix so that Vertex SOP will cycle through primitives. Vertices per primitive will still have to match. Fixed a crash in Vertex SOP when number of primitives in inputs don't match.
- Fix case where GLSL MAT wouldn't compile correctly when using some instancing functions like getInstanceScale.
- Fix scroll wheel to use Windows setting for number of lines. Currently applies to DAT viewers and tables only
- Fixed the display of TOPs, CHOPs, and Geometry in the network backdrop, more consistently tiled squares when you enable their display flag.
- fixed crash when deleting network background-displayed CHOPs
- Joystick CHOP improvements -
- fixed crash when plugging, unplugging etc.
- Missing sliders now produce default values instead of 0.
- Missing joysticks, DirectX version etc still produce output, though give a warning.
- Keyboard CHOP and Mouse CHOP - fixed bug where they would become inactive after middle and right-clicking on an input field.
- Privacy - fixed bug where some files wouldn't work correctly under Privacy mode.
- Cloning fix - Certain cloned nodes that stay around during a save (In/Out OPs, COMPs) will now correctly clone their masters parameters/flags upon start-up.
- fixed bug that caused nameless nodes to get created when creating a macro without specifying a name.
- Noise CHOP - fixed freezing behavior after long periods of time, and swapped to use better random number generator.
- Phong MAT - better indenting for shaders output.
- Feedback CHOP - Fixed delta channel being added continuously.
- Feedback CHOP - no longer requires a Null CHOP set to cook always as its input to work correctly.
- out-of-memory - TouchDesigner will now display a message box when it discovers it has run out of CPU memory. This will catch most occurrances but not all.
- Movie In TOP - You can now step through a movie when Sequential playback mode is used and your playbar is paused.
- Resolution TOP - fixed GPU memory leak in the High Quality Resize option.
- TouchDesigner now correctly detects different monitors when a Matrix Triple Head 2 Go is used.
- Displace TOP - Three weight factors scale (1) the effect of the input warp image, (2) a constant UV and (3) the UV of the output pixel in determining where to look up in the Source image.
- Offset page has been collapsed onto the first page.
- fixed GPU memory leak when deleting a Blur TOP.
- Double clicking on the name field of an activated node will now enable you to edit the node name. This also works when fixed size operator name is on.
- Maximum Time Slice in CHOP Preferences is now expressed in milliseconds. Old values will be ignored. New default is 100 (msec).
- Files with many network OPs will now close much faster.
- Fixed bug where Render TOP wouldn't re-generate it's mipmap data after the first cook.
- Fixed incorrect playback Movie In TOP when 'Async Upload To GPU' and 'On timeout, use latest avail' parameters were both on.
- Fix long Movie In TOP cook when the movie loops and you're using Loop Crossfade.
- Fix issue with slow panel drawing in some cases.
- Fixed from last build - bad values in Filter CHOP when the Filter Width was 0.
- Fix issue with RMB menu not popping up on open window COMP.
- Fix crash when locking SOPs in some cases.
- numerous Modeler fixes
- Fix so characters as well as integers can be passed to the key panel value.
- Fix so that cursor can be updated during scripting calls (normally updated during redraws).
- Fix bug where Window COMP wouldn't open to the correct borderless size if it was opened bordered previously.
- Fixed crashes when swapping images on Component Table cell backgrounds.
- Fixed behavior where stowing/unstowing *any* window toggled the power button. It should only be the main window.
- Fixed Speed CHOP zig-zag function breaking down after several hours.
- Movie Out TOP will no longer write frames when the playbar is paused. It used to keep writting if the Power button was on.
- Fixed some squelching in the audio playback when seeking.
- Fixed sampling error when auto-merging two channels of different rates.
- Windows opened with Window COMPs won't automatically regain focus if the COMP cooks.
- Fix flickering issue with DAT viewers when clicking on different nodes.
- Fixed bug where the Feedback TOP wouldn't load up correctly if either of the aspect ratio values weren't integers.
- Fix bug where you couldn't properly lock an In TOP that had it's default input connected.
- Geometry display options: Fixed so points can be drawn even when there is no geometry.
- Fix crash when very old driver tries to use blob detection
- Rearrange pivot management section of RMB menu in select state for Geometry Viewer & modeler.
- Added a Reset Pivot to Selection Origin in Geoemtry Viewer.
- Fix so that transform pivot remains in position after re-attachment to geoemtr.
- Fix so geometry in modeler can only be translate with transform handles, and not via dragging.
- Fix issue where a window justified to the mouse location would follow the mouse around the screen if the Window COMP was cooking.
- Envelope CHOP - Fixed Signal Power and Normalize options, which just output junk, including QUAN## errors. Fixed periodic junk output in all cases.
- CUDA memory is now counted in the total used GPU memory tallies.
- Significant performance increase for Merge CHOPs that have merging a large number of channels.
- Script execution has been made ~20-30% faster in most cases.
- Fixed bug where Movie In TOP wouldn't load up correctly when using open timeouts, in some cases.
- Memory leak when deleting a Render TOP that has a Depth TOP looking at it fixed.
- Fixed button release for click command works as if click off is inside button. (Fixes issue with momentary up etc).
- Fixed memory leak when the
- Fixed GLSL TOP rendering out 2D texture arrrays and 3D textures correctly.
- Originate parameter in many network OPs has been renamed to Connection Mode.
- TCP/IP In DAT no longer caused TouchDesigner to freeze if it's deleted before it establishes a connection.
- copy-paste nodes - Nodes that are copied and pasted with inter-connections (node references, exports) will now reference the newly created nodes instead of the original (copying a Ramp TOP + it’s DAT for example).
- floating Panels re-size immediately after their width and height parameters change (before you had to close and re-open the window)
- audio artifacts fixed
- loop-around at end of timeline sometimes produced a pop
- driving the audio by specifying the time index was not accurate. fixed.
- some OPs that were mixing audio were not accurate enough. fixed.
- panels re-open at correct resolution when changing width and height parameters of panels that are open floating.
- click -v was fixed to set the v coordinate of 2D uv gadgets.
- Para EQ CHOP fixed - it rebuilds its filters when the sample rate changes.
- Modeler has 2nd fill light so geometry will look better at certain angles.
- New indicator in the network editor to notify you if you are in a network that is loaded from an external .tox file. Avoids accidentally editing a network that won't get saved when you save the .toe file.
- TOUCH_DOUBLE_DRAW environment variable draws image twice per frame cooked, like for 30 fps synths running on 60fps displays. Gives a more accurate display rate, otherwise it's at the whim of the NVIDIA driver/hardware how many frames each image gets displayed.
- PBO recycling has new environment variable
TOUCH_RECYCLE_PBO_RATIOwhich allows you to control how lax the recycling in when matching a requested buffer size with a recycled buffer. 1 will require an exact match, 0 allows any buffer that is big enough to be used. Defaults to 0.8 when not set.
- not supported: for those of us squinters. This affects only part of the UI...
uioptionscan now adjust parameter dialog and textport size via the font.relative.size option. uioptions -o font.relative.size 0 will set the fonts to its default size. uioptions -o font.relative.size 3 will set the fonts to 3 points larger. fonts are clamped to 5 points larger and 3 points smaller than normal.
- TouchDesigner run on Windows 7 - Dual Monitor works well (via desktop -> RMB -> Screen Resolution). NOTES:
- make sure to clear out your
C:/Users/yourname/AppData/Local/VirtualStore/Derivativefolder to remove unwanted files Windows 7 redirects.
- The installer looks like it's hanging but it's waiting for security confirmation in another window.
- The TouchDesigner window starts slightly too large - edge under taskbar.
- some file choosers go to your project folder versus the location of the files.
- other small things will be documented in the forum.
Older Release Notes
Older Release notes are available here. | http://derivative.ca/wiki077/index.php?title=Release_Notes/077 | CC-MAIN-2013-20 | refinedweb | 12,124 | 64.2 |
According to the 2020 Kaggle Machine Learning and Data Science survey, Matplotlib is the number one data visualization library among Kagglers, leading by a significant margin.
Many courses and tutorials have recently drawn beginner data scientists’ attention to new, shiny, interactive libraries like Plotly, but Matplotlib remains the king of data visualization libraries and, I suspect, will likely continue to be for the foreseeable future.
Because of this, I highly recommend that you learn it and go beyond the basics because the power of Matplotlib becomes more evident when you tap into its more advanced features.
In this tutorial, we will cover some of them and give a solid introduction to the object-oriented (OO) interface of Matplotlib.
What is the object-oriented interface in Matplotlib?
When you first learn Matplotlib, you probably start using the library through its PyPlot interface, which is specifically designed for beginners because it’s user-friendly and requires less code to create visuals.
However, its features fall short when you want to perform advanced customizations on your graphs. That’s where the object-oriented API comes into play.
Under the hood, Matplotlib consists of base classes called artists.
Having unique classes for each element in a visual gives Matplotlib users a ton of flexibility. Each circle-annotated component in the above graph is a separate class that inherits from the base artists. This means that you can tweak every little line, dot, text, or object visible on the plot.
In the following sections, we will learn about the most important of these classes, starting with figure and axes objects.
Figure and axes objects in Matplotlib
Let’s first import Matplotlib and its submodules:
import matplotlib as mpl # pip install matplotlib import matplotlib.pyplot as plt
Next, we create a figure and an axes object using the
subplots function:
>>> fig, ax = plt.subplots()
Now, let’s explain what these objects do.
fig (figure) is the highest-level artist, an object that contains everything. Think of it as the canvas you can draw on. The axes object (
ax) represents a single set of XY coordinate systems. All Matplotlib plots require a coordinate system, so you must create at least one figure and one axes object to draw charts.
plt.subplots is a shorthand for doing this — it creates a single figure and one or more axes objects in a single line of code. A more verbose version of this would be:
>>> fig = plt.figure() >>> ax1 = fig.add_axes() <Figure size 432x288 with 0 Axes>
Because this requires more code, people usually stick to using
subplots. Besides, you can pass extra arguments to it to create multiple axes objects simultaneously:
>>> fig, axes = plt.subplots(nrows=1, ncols=3)
By changing the
nrows and
ncols arguments, you create a set of subplots — multiple axes objects stored in
axes. You can access each one by using a loop or indexing operators.
Learn how to use the subplots function in-depth in its documentation.
Plotting functions in Matplotlib
When you switch from PyPlot to OOP API, the function names for plots do not change. You call them using the axes object:
import seaborn as sns tips = sns.load_dataset("tips") fig, ax = plt.subplots() ax.scatter(tips["tip"], tips["total_bill"]) ax.set( title="Tip vs. Total Bill amount in a restaurant", xlabel="Tip ($)", ylabel="Totalb bill ($)", );
Here, I introduce the
set function, which you can use on any Matplotlib object to tweak its properties.
The above plot is a bit bland and in no way compares to default scatterplots created by Seaborn:
>>> sns.scatterplot(tips["tip"], tips["total_bill"]);
For this reason, let’s discuss two extremely flexible functions you can use to customize your plots in the next section.
get_* functions in Matplotlib
Remember how Matplotlib has separate classes for each plot component? In the next couple of sections, we’ll take advantage of this feature.
While customizing my plots, I generally use this workflow:
- Create the basic plot
- Identify weaknesses of the plot that need customizations
- Extract those weak objects
- Customize them using the
setpfunction (more on this later)
Here, we will discuss the third step — how to extract different components of the plot.
First, let’s create a simple plot:
fig, ax = plt.subplots() # Create the data to plot X = np.linspace(0.5, 3.5, 100) Y1 = 3 + np.cos(X) Y2 = 1 + np.cos(1 + X / 0.75) / 2 Y3 = np.random.uniform(Y1, Y2, len(X)) ax.scatter(X, Y3) ax.plot(X, Y1) ax.plot(X, Y2);
We used the
subplots function to create the figure and axes objects, but let’s assume we don’t have the axes object. How do we find it?
Remember, the figure object is the highest-level artist that contains everything in the plot. So, we will call
dir on the
fig object to see what methods it has:
>>> dir(fig) [ ... 'gca', 'get_agg_filter', 'get_alpha', 'get_animated', 'get_axes', 'get_dpi', 'get_edgecolor', 'get_facecolor', 'get_figheight', 'get_figure', 'get_figwidth', 'get_frameon', 'get_gid', 'get_in_layout' ... ]
In the list, we see the
get_axes method, which is what we need:
axes = fig.get_axes() >>> type(axes) list >>> len(axes) 1
The result from
get_axes is a list containing a single axes object we created in the above plot.
The axes example serves as proof that everything in Matplotlib is just a class. A single plot contains several components implemented as separate classes, and each of those components can have one or more subclasses.
They all have one thing in common: you can extract those classes or subclasses using the relevant
get_* functions. You just have to know their names.
What do you do once you extract those objects? You tweak them!
plt.getp and
plt.setp functions
To tweak the properties of any component, you have to know what arguments it has and what values each argument receives. You will be working with many objects, so visiting the documentation every time can become tiresome.
Fortunately, Matplotlib creators thought of this issue. Once you extract the relevant object, you can see what parameters it accepts using the
plt.getp function. For example, let’s see the properties of the axes object:
fig, _ = plt.subplots() ax = fig.get_axes()[0] >>> plt.getp(ax) ... xlabel = xlim = (0.0, 1.0) xmajorticklabels = [Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), T... xminorticklabels = [] xscale = linear xticklabels = [Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), T... xticklines = <a list of 12 Line2D ticklines objects> xticks = [0. 0.2 0.4 0.6 0.8 1. ] yaxis = YAxis(54.0,36.0) yaxis_transform = BlendedGenericTransform( BboxTransformTo( ... ybound = (0.0, 1.0) ygridlines = <a list of 6 Line2D gridline objects> ylabel = ylim = (0.0, 1.0) ymajorticklabels = [Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), T... yminorticklabels = [] yscale = linear ...
As you can see, the
getp function lists all properties of the object it was called on, displaying their current or default values. We can do the same for the fig object:
>>> plt.getp(fig) ... constrained_layout_pads = (0.04167, 0.04167, 0.02, 0.02) contains = None default_bbox_extra_artists = [<AxesSubplot:>, <matplotlib.spines.Spine object a... dpi = 72.0 edgecolor = (1.0, 1.0, 1.0, 0.0) facecolor = (1.0, 1.0, 1.0, 0.0) figheight = 4.0 figure = Figure(432x288) figwidth = 6.0 frameon = True gid = None in_layout = True label = linewidth = 0.0 path_effects = [] ...
Once you identify which parameters you want to change, you must know what range of values they receive. For this, you can use the
plt.setp function.
Let’s say we want to change the
yscale parameter of the axis object. To see the possible values it accepts, we pass both the axes object and the name of the parameter to
plt.setp:
>>> plt.setp(ax, "yscale") yscale: {"linear", "log", "symlog", "logit", ...} or `.ScaleBase`
As we see, yscale accepts five possible values. That’s much faster than digging through the large docs of Matplotlib.
The
setp function is very flexible. Passing just the object without any other parameters will list that object’s all parameters displaying their possible values:
>>> plt.setp(ax) ... xlabel: str xlim: (bottom: float, top: float) xmargin: float greater than -0.5 xscale: {"linear", "log", "symlog", "logit", ...} or `.ScaleBase` xticklabels: unknown xticks: unknown ybound: unknown ylabel: str ylim: (bottom: float, top: float) ymargin: float greater than -0.5 yscale: {"linear", "log", "symlog", "logit", ...} or `.ScaleBase` yticklabels: unknown yticks: unknown zorder: float ...
Now that we know what parameters we want to change and what values we want to pass to them, we can use the
set or
plt.setp functions:
fig, ax = plt.subplots() # Using `set` ax.set(yscale="log", xlabel="X Axis", ylabel="Y Axis", title="Large Title") # Using setp plt.setp(ax, yscale="log", xlabel="X Axis", ylabel="Y Axis", title="Large Title") plt.setp(fig, size_inches=(10, 10));
Using Line2D objects
The most common figures in any plot are lines and dots. Almost all plots, such as bars, box plots, histograms, scatterplots, etc., use rectangles, hence, lines.
Matplotlib implements a global base class for drawing lines, the Line2D class. You never use it directly in practice, but it gets called every time Matplotlib draws a line, either as a plot or as part of some geometric figure.
As many other classes inherit from this one, it’s beneficial to learn its properties:
from matplotlib.lines import Line2D xs = [1, 2, 3, 4] ys = [1, 2, 3, 4] >>> plt.setp(Line2D(xs, ys)) ... dash_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'} dash_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'} dashes: sequence of floats (on/off ink in points) or (None, None) data: (2, N) array or two 1D arrays drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default' figure: `.Figure` fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'} gid: str in_layout: bool label: object linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...} linewidth or lw: float ...
I recommend paying attention to the
linestyle,
width, and
color arguments, which are used the most.
Customizing axis ticks in Matplotlib
One of the essential aspects of all Matplotlib plots is axis ticks. They don’t draw much attention but silently control how the data is displayed on the plot, making their effect on the plot substantial.
Fortunately, Matplotlib makes it a breeze to customize the axis ticks using the
tick_params method of the axis object. Let’s learn about its parameters:
Change the appearance of ticks, tick labels, and gridlines. Tick properties that are not explicitly set using the keyword arguments remain unchanged unless *reset* is True. Parameters ---------- axis : {'x', 'y', 'both'}, default: 'both' The axis to which the parameters are applied. which : {'major', 'minor', 'both'}, default: 'major' The group of ticks to which the parameters are applied. reset : bool, default: False Whether to reset the ticks to defaults before updating them. Other Parameters ---------------- direction : {'in', 'out', 'inout'} Puts ticks inside the axes, outside the axes, or both. length : float Tick length in points. width : float Tick width in points.
Above is a snippet from its documentation.
The first and most important argument is
axis. It accepts three possible values and represents which axis ticks you want to change. Most of the time, you choose both.
Next, you have
which that directs the tick changes to either minor or major ticks. If minor ticks are not visible on your plot, you can turn them on using
ax.minorticks_on():
fig, ax = plt.subplots(figsize=(10, 10)) ax.minorticks_on()
The rest are fairly self-explanatory. Let’s put all the concepts together in an example:
fig, ax = plt.subplots(figsize=(6, 6)) ax.tick_params(axis="both", which="major", direction="out", width=4, size=10, color="r") ax.minorticks_on() ax.tick_params(axis="both", which="minor", direction="in", width=2, size=8, color="b")
While we are here, you can tweak the spines as well. For example, let’s play around with the top and right spines:
fig, ax = plt.subplots(figsize=(6, 6)) ax.tick_params(axis="both", which="major", direction="out", width=4, size=10, color="r") ax.minorticks_on() ax.tick_params(axis="both", which="minor", direction="in", width=2, size=8, color="b") for spine in ["top", "right"]: plt.setp(ax.spines[spine], ls="--", color="brown", hatch="x", lw=4)
You can access the spines using the
spines attribute of the axes object, and the rest is easy. Because a spine is a line, its properties are the same as that of a Line2D object.
Conclusion
The key to a great plot is in the details. Matplotlib defaults are rarely up to professional standards, so it falls on you to customize them. In this article, we have tapped into the core of Matplotlib to teach you the internals so that you have a better handle on more advanced concepts.
Once you start implementing the ideas in the tutorial, you will hopefully see a dramatic change in how you create your plots and customize them.. | https://blog.logrocket.com/mastering-data-visualization-python-matplotlib/ | CC-MAIN-2022-21 | refinedweb | 2,134 | 58.48 |
Get on the D-BUS
The Kernel Event Layer
The Kernel Event Layer is a kernel-to-user communication mechanism that uses a high-speed netlink socket to communicate asynchronously with user space. This mechanism can be tied into D-BUS, allowing the kernel to send D-BUS signals!
The Kernel Event Layer is tied to sysfs, the tree of kobjects that lives at /sys on modern Linux systems. Each directory in sysfs is tied to a kobject, which is a structure in the kernel used to represent objects; sysfs is an object hierarchy exported as a filesystem.
Each Kernel Event Layer event is modeled as though it originated from a sysfs path. Thus, the events appear as if they emit from kobjects. The sysfs paths are easily translatable to D-BUS paths, making the Kernel Event Layer and D-BUS a natural fit. This Kernel Event Layer was merged into the 2.6.10-rc1 kernel.
Second, the session bus provides a mechanism for IPC and remote method invocation, possibly providing a unified system between GNOME and KDE. D-BUS aims to be a better CORBA than CORBA and a better DCOP than DCOP, satisfying the needs of both projects while providing additional features.
And, D-BUS does all this while remaining simple and efficient.
The core D-BUS API, written in C, is rather low-level and large. On top of this API, bindings integrate with programming languages and environments, including Glib, Python, Qt and Mono. On top of providing language wrappers, the bindings provide environment-specific features. For example, the Glib bindings treat D-BUS connections as GObjects and allow messaging to integrate into the Glib mainloop. The preferred use of D-BUS is definitely using language and environment-specific bindings, both for ease of use and improved functionality.
Let's look at some basic uses of D-BUS in your application. We first look at the C API and then poke at some D-BUS code using the Glib interface.:
DBusMessage *msg; DBusMessageIter iter; /* create a new message of type signal */ msg = dbus_message_new_signal( "org/pirate/parrot/attr", "org.pirate.parrot.attr", "Feathers"); /* build the signal's payload up */ dbus_message_iter_init (msg, &iter); dbus_message_iter_append_string (&iter, "Shiny"); dbus_message_iter_append_string (&iter, "Well Groomed"); /* send the message */ if (!dbus_connection_send (conn, msg, NULL)) fprintf (stderr, "error sending message\n"); /* drop the reference count on the message */ dbus_message_unref (msg); /* flush the connection buffer */ dbus_connection_flush (conn);
This sends the Feathers signal from org.pirate.parrot.attr with a payload consisting of two fields, each strings: Shiny and Well Groomed. Anyone listening on the system message bus with sufficient permissions can subscribe to this service and listen for the signal.
Disconnecting from the system message bus is a single function:
if (conn) dbus_connection_disconnect (conn);
Glib (pronounced gee-lib) is the base library of GNOME. It is on top of Glib that Gtk+ (GNOME's GUI API) and the rest of GNOME is built. Glib provides several convenience functions, portability wrappers, a family of string functions and a complete object and type system—all in C.
The Glib library provides an object system and a mainloop, making object-based, event-driven programming possible, even in C. The D-BUS Glib bindings take advantage of these features. First, we want to include the right header files:
#include <dbus/dbus.h> #include <dbus/dbus-glib.h>
Connecting to a specific message bus with the Glib bindings is easy:
DBusGConnection *conn; GError *err = NULL; conn = dbus_g_bus_get (DBUS_BUS_SESSION, &err); if (!conn) { g_printerr ("Error: %s\n", error->message); g_error_free (error); }
In this example, we connected to the per-user session bus. This call associates the connection with the Glib mainloop, allowing multiplexed I/O with the D-BUS messages.
The Glib bindings use the concept of proxy objects to represent instantiations of D-BUS connections associated with specific services. The proxy object is created with a single call:
DBusGProxy *proxy; proxy = dbus_g_proxy_new_for_service (conn, "org.fruit.apple", "org/fruit/apple", "org.fruit.apple");
This time, instead of sending a signal, let's execute a remote method call. This is done using two functions. The first function invokes the remote method; the second retrieves the return value.
First, let's invoke the Peel remote method:
DBusGPendingCall *call; call = dbus_g_proxy_begin_call (proxy, "Peel", DBUS_TYPE_INVALID);
Now let's retrieve-check for errors and retrieve the results of the method call:
GError *err = NULL; int ret; if (!dbus_g_proxy_end_call (proxy, call, &err, DBUS_TYPE_INT32, &ret, DBUS_TYPE_INVALID)) { g_printerr ("Error: %s\n", err->message); g_error_free (err); }
The Peel function accepts a single parameter, an integer. If this call returned nonzero, it succeeded, and the variable ret holds the return value from this function. The data types that a specific method accepts are determined by the remote method. For example, we could not have passed DBUS_TYPE_STRING instead of DBUS_TYPE_INT32.
The main benefit of the Glib bindings is mainloop integration, allowing developers to manage multiple D-BUS messages intertwined with other I/O and UI events. The header file <dbus/dbus-glib.h> declares multiple functions for connecting D-BUS to the Glib mainloop.... | http://www.linuxjournal.com/article/7744?page=0,1&quicktabs_1=0 | CC-MAIN-2016-26 | refinedweb | 840 | 54.83 |
for an example, i have an array with a filename
- Code: Select all
char fname = "test.txt"
is there anyway to just return ".txt"?
Thank you!
Moderators: SecretSquirrel, just brew it!
char fname = "test.txt"
#include <string>
// ...
std::string s = "example.txt";
std::string ext = (s.find('.') != std::string::npos) ? s.substr(s.find('.')+1) : "";
string fname;
void main(int argc, char **argv)
{
cin>>fname;
}
#define MAX_EXT 4
void main(int argc, char **argv)
{
char fileExt[MAX_EXT];
short i;
//Look for the string starting point since we are doing a reverse lookup.
//Then go from the end of the string to the start looking for '.'
//Does not check for null string.
i = strlen(argv[0]); //Looks at only the first char string in the array of arguments, gets the end count of string
while(i > -1 && argv[0][i] != '.') i--; //Look for the first '.' in from end of string
if (i > -1) strcpy(fileExt, &(argv[0][i+1])); //Copy the extension only.
}
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
if (argc < 2)
{
cout << "no argument specified\n";
return 1;
}
string fname = argv[1];
string efname;
int dot = fname.find_last_of('.');
if (dot != string::npos)
{
efname = fname.substr(dot);
cout << "Result = \"" << efname.c_str() << "\"\n";
}
else
cout << "no dot in argument\n";
return 0;
}
Craig P. wrote:You also need to include <string> in jbi's code -- it's a library implementation feature that it worked without it.
Also, it shouldn't be necessary to insert using the c_str() member, you should be able to insert the string directly.
just brew it! wrote:Also, it shouldn't be necessary to insert using the c_str() member, you should be able to insert the string directly.
Without the c_str() it compiles OK under g++, but gives a compilation error under VC++. (The error message is: "error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or there is no acceptable conversion)"
))
Craig P. wrote:Either <string> or <ostream> ought to take care of this, I believe. I'm pretty sure there's a string inserter, I'm just not sure of where it is.
Return to Developer's Den
Users browsing this forum: No registered users and 2 guests | http://techreport.com/forums/viewtopic.php?f=20&t=10059&p=102749 | CC-MAIN-2015-14 | refinedweb | 384 | 75.5 |
Integer Logarithms
May 7, 2010
Here’s))))))))
Loop1 doubles
lo and
hi until they bracket the logarithm, and
loop2 repeatedly bisects the bracketed range until it finds the solution. Beware that is it easy to get off-by-one errors if you’re not careful (and even if you are). The function shown above was tested by comparing its output to the old version of
ilog for all values of n to a million, for several different bases b.
You can see the
ilog function in the Standard Prelude or at.
[…] Praxis – Integer Logarithms By Remco Niemeijer In today’s Programming Praxis exercise we have to write an algorithm to find the integer logarithm of a […]
My Haskell solution (see for a version with comments):
the link in last email seems to not work:
though the alternate one did …
Python version.
Initially, I bracketed the answer by squaring the base (base, base^2, base^4, …) until it was greater than ‘n’. Then did a binary search between the last two powers. I tried optimize the routine by reusing previously calculated powers of the base. In the end I came up with the routine below, which is about twice as fast as the binary search.
Repeatedly square the base until it is larger than ‘n’, saving the calculated bases and exponents on a stack.
Then, while the stack is not empty, pop a base and exponent off the stack. If the base is <= 'n', divide 'n' by the base and add the exponent to the answer. When the stack is empty, return the answer.
def ilog( n, base=10 ):
k = 1
s = []
while base <= n:
s.append( (base, k) )
base *= base
k *= 2
ans = 0
while s:
base, k = s.pop()
if base <= n:
ans += k
n /= base
return ans
Somehow, I messed up the formatting above.
Clever idea, but I’m not sure about your timings. I found that the cost of handling the base/exponent stack outweighed the algorithmic improvement. It would take a very large n to actually see an improvement.
I went back and checked my timings, and I was correct about the timings for the inputs I had tried (123456789, and 987654321). However, I tried different input and my routine was slower. So I ran a test using lots of randomly selected numbers and bases. For most cases my algorithm was slower.
//
int
ilog ( int b , int n )
{
int lo=0 , b_lo=1 , hi=1 , mid , b_mid ;
long long b_hi=b ;
while ( b_hi 1 )
{
mid = (lo + hi) / 2 ;
b_mid = b_lo * (int) pow( b , mid – lo ) ;
if ( n b_mid ) { lo = mid ; b_lo = b_mid ; }
if ( n == b_mid ) return mid ;
}
return b_hi == n ? hi : lo ;
}
#! /bin/sh
#| Hey Emacs, this is -*-scheme-*- code!
exec mzscheme -l errortrace –require “$0″ –main — ${1+”$@”}
|#
;;
#lang racket
(require rackunit
rackunit/text-ui)
(define (find-zero too-small too-big func)
(define (average a b)
(quotient (+ a b) 2))
(if (equal? too-big (add1 too-small))
too-small
(let* ([median (average too-small too-big)]
[fm (func median)])
(cond
((positive? fm)
(find-zero too-small median func))
((zero? fm)
median)
(else
(find-zero median too-big func))))))
;; Quickly find two numbers: one that is below the ilog of big-number,
;; and one that is above it. We’ll use these as the initial bounds of
;; our binary search.
(define (bracket-log base big-number)
(let loop ([candidate 1]
[probe base])
(if (< big-number probe)
(values (quotient candidate 2) candidate)
(loop (* 2 candidate)
(* probe probe)))))
;; For testing the above
(define (bl-pair base big-number)
(call-with-values (lambda () (bracket-log base (expt base expt)))))
(define-test-suite bracket-log-tests
(check-equal? (bl-pair 10 200) '(128 256))
(check-equal? (bl-pair 2 99) '(64 128))
(check-equal? (bl-pair 33 17) '(16 32)))
(define (ilog b n)
(cond
((exact
(truncate
(/ (log big-number)
(log base))))]
[actual (ilog base big-number)])
(check-equal? actual expected)))))
(define-test-suite all-tests
ilog-tests random-tests)
(define (main . args)
(exit (run-tests all-tests ‘verbose)))
(provide ilog main)
I failed to see why the original algorithm is of complexity O(n). It will take at most log(n) times to execute (quotient n b), right? Even if we assume that (quotient n b) is not of O(1), should we say the algorithm is of pseudo O(log(n))?
On the other hand, the loop alone in the solution that bisects the bracket range will take log(n) times in worst case, no?
Did I miss something?
Thanks,
You are correct that the original algorithm is O(log n). However, the revised algorithm is O(log log n) to bracket the range (it starts from b^hi = b and squares b^hi at each step) and O(log log n) to perform the bisection, for a total time of O(log log n). Here is a timing test showing the difference:
> (define (ilog b n)
(if (zero? n) -1
(+ (ilog b (quotient n b)) 1)))
> (time (ilog 2 #e1e1000))
(time (ilog 2 ...))
no collections
25 ms elapsed cpu time
49 ms elapsed real time
756088 bytes allocated
3321
> ))))))))
> (time (ilog 2 #e1e1000))
(time (ilog 2 ...))
no collections
0 ms elapsed cpu time
0 ms elapsed real time
6032 bytes allocated
3321
Thanks! You’re right. I missed the fact that the loop loop1 in the solution multiplies b^hi by itself every time.
Hi,
I’m new here… My F# solution. Nothing clever here, just straight forward implementation of the algorithm.
let ilog_improved b n =
let rec bracket (lo:float) (hi:float) =
if (b ** hi < n) then bracket hi (hi * 2.0) else (lo, hi)
let rec bisect (lo,hi) =
if (hi – lo < 1.0) then
if (b ** hi = n) then hi else lo
else
let mid = ((lo + hi) / 2.0)
if (b ** mid) > n then
bisect (lo, mid)
else
bisect (mid, hi)
bisect (bracket 0.0 1.0)
If there is a max int size (e.g. C/C++ etc.) there’s no need for binary search… Just check if the number is > wordsize/2, then wordsize/4, then wordsize/8, etc, for base 2 log, and increment a counter for the number of bits you check. (e.g. if a number is 2^16 (65536), add 16 to the log, divide the number by 65536, then check for > 256, etc.) and other logs can be scaled using the identity, log_b(x) = log2(x) / log2(b). (Though if all floating point is disallowed, you need to know what bases to use in advance to have suitable ratios ready.) E.g. (in gforth, 64 bit integers):
create ilog4bit
-1 c, \ log 0
0 c, \ log 1
1 c, 1 c, \ log 2, log 3
2 c, 2 c, 2 c, 2 c, \ log 4 … log 7
3 c, 3 c, 3 c, 3 c, 3 c, 3 c, 3 c, 3 c, \ log 8 … log 15
: log-adjust ( n1 n2 n3 — n1/2^n3 n2+n3 )
swap over + >r rshift r> ;
: ulog ( n — n )
0
over $FFFFFFFF u> negate 5 lshift log-adjust
over $FFFF > negate 4 lshift log-adjust
over $FF > negate 3 lshift log-adjust
over $F > negate 2 lshift log-adjust
swap ilog4bit + c@ + ;
\ — base 10 logs
create pow10
1 ,
10 ,
100 ,
1000 ,
10000 ,
100000 ,
1000000 ,
10000000 ,
100000000 ,
1000000000 ,
10000000000 ,
100000000000 ,
1000000000000 ,
10000000000000 ,
100000000000000 ,
1000000000000000 ,
10000000000000000 ,
100000000000000000 ,
1000000000000000000 ,
: 10** ( n — n ) \ only try up to 18!
dup 18 u> 24 * throw
cells pow10 + @ ;
: log10 ( n — n )
dup ulog 1+ 1233 * 12 rshift \ precice enough, can also use: “8651 28738 */” which is good to 9 decimals.
dup 10** rot > + ;
[/code]
[…] by the code for calculating integer logarithms in the Scheme Standard Prelude. It is described in a Programming Praxis blog entry. They use the doubling technique to figure out which powers of 2 bound the logarithm, and then use […]
[…] by the code for calculating integer logarithms in the Scheme Standard Prelude. It is described in a Programming Praxis blog entry. They use the doubling technique to figure out which powers of 2 bound the logarithm, and then use […]
I found your solution to be very insightful. I compare it to another ancient approach here: | https://programmingpraxis.com/2010/05/07/integer-logarithms/2/ | CC-MAIN-2016-44 | refinedweb | 1,360 | 77.57 |
Tech Tips
August 29, 2000
WELCOME to the Java Developer Connection
(JDC) Tech Tips, August 29, 2000. This issue is about bytecode. Programmers
coding in the Java programming language rarely view the
compiled output of their programs. This is unfortunate, because
the output, Java bytecode, can provide valuable insight when
debugging or troubleshooting performance problems. Moreover,
the JDK makes viewing bytecode easy. This tip shows you how
to view and interpret Java bytecode. It presents the following
topics related to bytecode:
This issue of the JDC Tech Tips is written by Stuart Halloway,
a Java specialist at DevelopMentor
().
These tips were developed using Java 2 SDK,
Standard Edition, v 1.3.
Most Java programmers know that their programs are not typically
compiled into native machine code. Instead, the programs are
compiled into an intermediate bytecode format that is executed by
the Java Virtual Machine*. However, relatively few
programmers have ever seen bytecode because their tools do not
encourage them to look. Most Java debugging tools do not allow
step-by-step execution of bytecode; they either show source code
lines or nothing.
Fortunately, the JDK provides javap, a command-line tool
that makes it easy to view bytecode. Let's see an example:
javap
public class ByteCodeDemo {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
After you compile this class, you could open the .class
file in a hex editor and translate the bytecodes by referring
to the virtual machine specification. Fortunately, there is an easier way.
The JDK includes a command line disassembler called javap,
which will convert the byte codes into human-readable mnemonics. You can get
a bytecode listing by passing the '-c' flag to javap as follows:
.class
'-c'
javap -c ByteCodeDemo
You should see output similar to this:
public class ByteCodeDemo extends java.lang.Object {
public ByteCodeDemo();
public static void main(java.lang.String[]);
}
Method ByteCodeDemo()
0 aload_0
1 invokespecial #1
4 return
Method void main(java.lang.String[])
0 getstatic #2
3 ldc #3
5 invokevirtual #4
8 return
From just this short listing, you can learn a lot about bytecode.
Begin with the first instruction in the main method:
0 getstatic instruction.'
'0'
'getstatic'
Field java.io.PrintStream out
After analyzing the first instruction, it's easy to guess the
meaning of the other instructions. The 'ldc' (load constant)
instruction pushes the constant "Hello, World." onto the operand
stack. The 'invokevirtual' invokes the println
method, which pops its two arguments from the operand stack. Don't forget that an instance method such as println has two arguments: the obvious string argument, plus the implicit 'this' reference.
'ldc'
'invokevirtual'
println
'this'
The Java programming language is frequently touted as a "secure"
language for internet software. Given that the code looks so
much like C++ on the surface, where does this security come
from? It turns out that an important aspect of security is the
prevention of memory-related bugs. Computer criminals exploit
memory bugs to sneak malicious code into otherwise safe programs.
Java bytecode is a first line of defense against this sort of
attack, as the following example demonstrates:
public float add(float f, int n) {
return f + n;
}
If you add this function to the previous example, recompile it, and
run javap, you should see bytecode similar to this:
Method float add(float, int)
0 fload_1
1 iload_2
2 i2f
3 fadd
4 freturn
At the beginning of a Java method, the virtual machine places
method parameters in a data structure called the local variable
table. As its name suggests, the local variable table also
contains any local variables that you declare. In this example,
the method begins with three local variable table entries, these
are for the three arguments to the add method. Slot 0 holds the
this reference, while slots 1 and 2 hold the float and int
arguments, respectively.
In order to actually manipulate the variables, they must be loaded
(pushed) onto the operand stack. The first instruction,
fload_1, pushes the float at slot 1 onto the operand stack.
The second instruction, iload_2, pushes the int at slot
2 onto the operand stack. The interesting thing about these instructions
is in the 'i' and 'f' prefixes, which illustrate
that Java bytecode instructions are strongly typed. If the type of an argument does not match the type of the bytecode, the VM will reject the bytecode as
unsafe. Better still, the bytecodes are designed so that these type-safety
checks need only be performed once, at class load time.
fload_1
iload_2
'i'
'f'
How does this type-safety enhance security? If an attacker could
trick the virtual machine into treating an int as a float, or vice
versa, it would be easy to corrupt calculations in a predictable
way. If these calculations involved bank balances, the security
implications would be obvious. More dangerous still would be
tricking the VM into treating an int as an Object reference. In
most scenarios, this would crash the VM, but an attacker needs to
find only one loophole. And don't forget that the attacker doesn't
have to search by hand--it would be pretty easy to write a program
that generated billions of permutations of bad byte codes, trying
to find the lucky one that compromised the VM.
Another case where bytecode safeguards memory is array
manipulation. The 'aastore' and 'aaload'
bytecodes operate on Java arrays, and they always check array bounds.
These bytecodes throw an ArrayIndexOutOfBoundsException if
the caller passes the end of the array. Perhaps the most important checks
of all apply to the branching instructions, for example, the bytecodes that
begin with 'if.' In bytecode, branching instructions can only
branch to another instruction within the same method. The only
way to transfer control outside a method is to return, throw an
exception, or execute one of the 'invoke' instructions. Not only
does this close the door on many attacks, it also prevents nasty
bugs caused by dangling references or stack corruption. If you have
ever had a system debugger open your program to a random location
in code, you're familiar with these bugs.
'aastore'
'aaload'
ArrayIndexOutOfBoundsException
'if.'
'invoke'
The critical point to remember about all of these checks is that
they are made by the virtual machine at the bytecode level, not
just by the compiler. A compiler for a language such as C++ might
prevent some of the memory errors discussed above, but its
protection applies only at the source code level. Operating
systems will happily load and execute any machine code, whether
the code was generated by a careful C++ compiler or a malicious
attacker. In short, C++ is object-oriented only at the source code
level, however Java's object-oriented features extend down to the
compiled code.
The memory and security protections of Java bytecode are there for
you whether you notice them or not, so why bother looking at the
bytecode? In many cases, knowing how the compiler translates your
code into bytecode can help you write more efficient code, and can
sometimes even prevent insidious bugs. Consider the
following example:
//return the concatenation str1+str2
String concat(String str1, String str2) {
return str1 + str2;
}
//append str2 to str1
void concat(StringBuffer str1, String str2) {
str1.append(str2);
}
Try to guess how many function calls each method requires to
execute. Now compile the methods and run javap. You should see
output like this:
Method java.lang.String concat1(java.lang.String, java.lang.String)
0 new #5
3 dup
4 invokespecial #6
7 aload_1
8 invokevirtual #7
11 aload_2
12 invokevirtual #7
15 invokevirtual #8
18 areturn
Method void concat2(java.lang.StringBuffer, java.lang.String)
0 aload_1
1 aload_2
2 invokevirtual #7
5 pop
6 return
The concat1 method makes five method calls: new,
invokespecial, and three invokevirtuals.
That is quite a bit more work than the concat2 method,
which makes only a single invokevirtual call. Most
Java programmers have been warned that because Strings are
immutable it is more efficient to use StringBuffers for
concatenation. Using javap to analyze this makes the point in
dramatic fashion. If you are unsure whether two language
constructs are equivalent in performance, you should use javap
to analyze the bytecode. Beware of the just-in-time (JIT)
compiler, though. Because the JIT compiler recompiles the
bytecodes into native machine code, it can apply additional
optimizations that your javap analysis does not reveal. Unless
you have the source code for your virtual machine, you need to
supplement your bytecode analysis with performance benchmarks.
concat1
new
invokespecial
invokevirtuals
concat2
invokevirtual
A final example illustrates how examining bytecode can help
prevent bugs in your application. Create two classes as
follows. Make sure they are in separate files.
public class ChangeALot {
public static final boolean debug=false;
public static boolean log=false;
}
public class EternallyConstant {
public static void main(String [] args) {
System.out.println("EternallyConstant beginning execution");
if (ChangeALot.debug)
System.out.println("Debug mode is on");
if (ChangeALot.log)
System.out.println("Logging mode is on");
}
}
If you run the class EternallyConstant you should get the message:
EternallyConstant
EternallyConstant beginning execution.
Now try editing the ChangeALot file, modifying the debug and log
variables to both be true. Recompile only the ChangeALot file.
Run EternallyConstant again, and you will see the following
output:
ChangeALot
EternallyConstant beginning execution
Logging mode is on
What happened to the debugging mode? Even though you set debug to
true, the message "Debug mode is on" didn't appear. The answer is
in the bytecode. Run javap on the EternallyConstant
class, and you will see this:
Method void main(java.lang.String[])
0 getstatic #2
3 ldc #3
5 invokevirtual #4
8 getstatic #5
11 ifeq 22
14 getstatic #2
17 ldc #6
19 invokevirtual #4
22 return
Surprise! While there is an 'ifeq' check on the log field, the
code does not check the debug field at all. Because the debug
field was marked final, the compiler knew that the debug field
could never change at runtime. Therefore, it optimized the 'if'
statement branch by removing it. This is a very useful
optimization indeed, because it allows you to embed debugging
code in your application and pay no runtime penalty when the
switch is set to false. Unfortunately, this optimization can
lead to major compile-time confusion. If you change a final field,
you have to remember to recompile any other class that might
reference the field. That's because the 'reference' might have
been optimized away. Java development environments do not always
detect this subtle dependency, something that can lead to very
odd bugs. So, the old C++ adage is still true for the Java
environment. "When in doubt, rebuild all."
'ifeq'
'if'
'reference'
Knowing a little bytecode is a valuable assist to any programmer
coding in the Java programming language. The javap tool makes it
easy to view bytecodes. Occasionally checking your code with javap can be invaluable in improving performance and catching
particularly elusive bugs. There is substantially more complexity to bytecode and the VM than this tip can cover. To learn more, read Inside the Java
Virtual Machine by Bill Venners.
* As used in this document, the terms "Java virtual machine"
or "JVM" mean a virtual machine for the Java platform.
Note
The names on the JDC
mailing list are used for internal Sun MicrosystemsTMpurposes only. To remove your name from the list,
see Subscribe/Unsubscribe below.
Feedback
Comments? Send your feedback on the JDC Tech Tips to: jdc-webmaster
Subscribe/Unsubscribe
The JDC Tech Tips are sent to you because you elected to subscribe.
To unsubscribe from this and any other JDC Email, select
"Subscribe to free JDC newsletters" on the JDC front page. This
displays the Subscriptions page, where you can change the current
selections.
You need to be a JDC member to subscribe to the Tech Tips. To
become a JDC member, go to:
To subscribe to the Tech Tips and other JDC Email, select
Archives
You'll find the JDC Tech Tips archives at:
901 San Antonio Road, Palo Alto, California 94303 USA.
This Document is protected by copyright. For more information, see: | http://java.sun.com/developer/TechTips/2000/tt0829.html | crawl-002 | refinedweb | 2,020 | 54.63 |
Hi,
i have just started programming with python and i have beken given a task where i must create a python calculator.
So far i have created the code (seen below) however i need help explaining it-e.g. saying what each part of the code does:
from tkinter import * root = Tk() root.title("Python Calculator") button_layout_Design = [ "1","2","3","+", "4","5","6","-", "7","8","9","*", "C","0","=","/" ] r = 1 c = 0 for buttons in button_layout_Design: cmd = lambda key=buttons: onClick(key) Button(root,text=buttons,relief="flat",command=cmd).grid(row=r,column=c) c += 1 if c > 3: r += 1 c = 0 view = Entry(root) view.grid(row=0,column=0,columnspan=4) def onClick(key): if key == "C": view.delete(0,END) elif key == "=": try: ans = eval(view.get()) view.delete(0,END) view.insert(0,ans) except SyntaxError: view.delete(0,END) view.insert(0,"Syntax Error") except ZeroDivisionError: view.delete(0,END) view.insert(0,"You cann't divide by zero!") else: view.insert(END,key)
Any help would be much appreciated! | https://www.daniweb.com/programming/software-development/threads/477111/tkinter-python-calculator | CC-MAIN-2019-09 | refinedweb | 177 | 52.36 |
Oleg Broytmann writes that he thinks methods are inherently "better" than methods. He asks for advantages of a function over a method, after first presenting his arguments for methods over functions: > -- a method is a more natural way to query or manipulate objects; > -- a direct method call is faster than two-level call (len() => .__len__()); > -- unnecessary cluttering of builtin namespace; the namespace should(1) > contains only really global functions (__import__(), eval(), etc.) Responding to your first point, "a more natural way" is not an argument... it's an expression of your personal preference. Your second point (performance) has some merit -- although one would hope the difference is small in a good implementation. And your third point (cluttering the builtin namespace) is a valid and real reason to prefer methods.)); } In other words, some things are less clear when written using the notation used for method invocation. That is particularly true when there are multiple objects involved and no clear reason to prefer one over another as the "object performing the action". In languages with multiple dispatch, like CLOS, everything looks like a function for exactly this reason. My second exhibit is also some Java code:... length, length(), size(). You could put it down to poor interface design by the Java team, but you must admit, individual objects are designed in isolation, but when there exists a common lanugage protocol like Python's builtin len() and __len__, that developers of individual objects go out of their way to make them conform with the common protocol... and in the end that makes them more usable. I'm sure there are additional arguments, but these are the first few I came up with. Of course, in nearly all cases, I prefer using methods... but len() is such a powerful concept applicable across MANY diverse kinds of objects, that I have no objection to granting it space in the builtin namespace. By the way... you write: > (1) I am a perfectionist and I partially disagree with "practicality beats > purity"; I would really love a small uncluttered builtin namespace in > Python.. -- Michael Chermside | https://mail.python.org/pipermail/python-dev/2006-March/062085.html | CC-MAIN-2017-04 | refinedweb | 348 | 61.56 |
This is the mail archive of the elfutils-devel@sourceware.org mailing list for the elfutils project.
On Wed, 2013-12-04 at 21:26 +0100, Jan Kratochvil wrote: > As I see you mean it seriously I would find correct to at least wait with this > patch check-in until IBM ABI authority will comment it. I understand you > think it is unrelated to ABI - but this is the subject of our disagreement. Of course I mean it seriously. I think your solution is too complex and mixes different goals causing your patch to do too much. Which is why I am trying to provide a different solution. Please try to focus on the actual elfutils/libdwfl interfaces and functionality we want to provide. Asking imaginary outside authorities for help if we don't agree on something is just silly. > [...] > > --- a/libdwfl/dwfl_module_getsym.c > > +++ b/libdwfl/dwfl_module_getsym.c > > @@ -113,6 +113,33 @@ dwfl_module_getsym_elf (Dwfl_Module *mod, int ndx, > > alloc = unlikely (shdr == NULL) || (shdr->sh_flags & SHF_ALLOC); > > } > > > > + /* In case of an value in an allocated section the main Elf Ebl > > + might know where the real value is (e.g. for function > > + descriptors). */ > > + if (mod->e_type != ET_REL && alloc > > + && GELF_ST_TYPE (sym->st_info) == STT_FUNC) > > I think STT_GNU_IFUNC is missing here. Yes, if we are looking at ELFOSABI_LINUX. > > + { > > + if (likely (__libdwfl_module_getebl (mod) == DWFL_E_NOERROR)) > > + { > > + GElf_Addr value = sym->st_value; > > + if (elf != mod->main.elf) > > + { > > + value = dwfl_adjusted_st_value (mod, elf, value); > > + value = dwfl_deadjust_st_value (mod, mod->main.elf, value); > > + } > > + > > + if (ebl_resolve_sym_value (mod->ebl, &value)) > > + { > > + elf = mod->main.elf; > > + sym->st_value = value; > > + > > + value = dwfl_adjusted_st_value (mod, mod->main.elf, value); > > + shndx = __libdwfl_find_section_ndx (mod, &value); > > + sym->st_shndx = shndx > SHN_HIRESERVE ? SHN_XINDEX : shndx; > > + } > > + } > > + } > > + > > I am fine with the patch as long as you remove this patch chunk. grin. This is the actual patch :) The rest is just helper functions. It is the main difference between mine and your approach. In your approach there is an extra synthetic symbol table, in my approach the existing symbols are filtered. > This is corrupting existing ELF symbols. Sigh. I can explain again that we are already "corrupting" the symbols since we are already adjusting the values anyway to map them to the address space we chose for the Dwfl_Module. All this patch does is make sure the value is also adjusted for any arch backend indirection. But we went over this multiple times already. What you seem to be saying is that you would also like a new interface that returns "pure" GElf_Syms that aren't adjusted in any way from how they were read from the underlying Elf file. That is not a bad request, but you didn't provide a convincing reason why you needed that new interface. I can certainly see why you might also want that, but as far as I can see nobody is actually needing it right now. But... > It would be OK to create new libdwfl API with such behavior but it must not be > called dwfl_module_getsym* as what this code returns is no longer "sym". I think we will have to introduce a new interface anyway. Not because of your notion of "ELF symbol corruption", but because it is an incompatible change however we implement it. I had hoped that my simpler approach would not cause problems for systemtap, but it looks like stap is just making certain assumptions that can only be satisfied with the original code. So it will be better to invent a new name. I think a new variant on dwfl_module_getsym* is fine though, but please suggest a different one if you have a good idea. It is just a pity since I think it will be a bit confusing to have slightly different functions doing essentially the same thing, except in the case of one specific arch (I guess ia64 would be another). The new ones would be what everybody who wants a name/address lookup in the normal case. But keeping the old ones around would provide you with an alternative "non-resolving" lookup if that is what is wanted. And in the new case we could just never adjust or corrupt the GElf_Sym, and provide the value or offset separately, which would give your "pure" symbol tables as a bonus. > > if (shndxp != NULL) > > /* Yield -1 in case of a non-SHF_ALLOC section. */ > > *shndxp = alloc ? shndx : (GElf_Word) -1; > [...] > > --- a/libebl/libebl.h > > +++ b/libebl/libebl.h > > @@ -402,6 +402,12 @@ extern bool ebl_set_initial_registers_tid (Ebl *ebl, > > extern size_t ebl_frame_nregs (Ebl *ebl) > > __nonnull_attribute__ (1); > > > > +/* Returns true if the value can be resolved to an address in an > > + allocated section, which will be returned in *SHNDXP. > > s/SHNDXP/ADDR/ Fixed. > > + (e.g. function descriptor resolving). */ > > +extern bool ebl_resolve_sym_value (Ebl *ebl, GElf_Addr *addr) > > + __nonnull_attribute__ (2); > > + > > #ifdef __cplusplus > > } > > #endif > [...] > > diff --git a/tests/ChangeLog b/tests/ChangeLog > > index 9bd2fe8..0c881e8 100644 > > --- a/tests/ChangeLog > > +++ b/tests/ChangeLog > > @@ -1,3 +1,14 @@ > > +2013-11-30 Jan Kratochvil <jan.kratochvil@redhat.com> > > You should be written as coauthor here as you modified the files. Added. Cheers, Mark | https://sourceware.org/ml/elfutils-devel/imported/msg03379.html | CC-MAIN-2018-17 | refinedweb | 823 | 63.59 |
composite_sampler - audio sampler/synth plugin (LV2)
The Composite sampler is an audio plugin (LV2) that provides a simple sampling engine. It is identified by the URI ""
The sampler includes the following ports: +-------+-----------+-------------+--------+---------------+ |Name | LV2 Port | Type | Flow | Description | +-------+-----------+-------------+--------+---------------+ |Left | out_left | AudioPort | Output | Left stereo | | | | | | channel | | | | | | output | +-------+-----------+-------------+--------+---------------+ |Right | out_right | AudioPort | Output | Right stereo | | | | | | channel | | | | | | output | +-------+-----------+-------------+--------+---------------+ |MIDI | midi | EventPort | Input | Main MIDI | | | | | | Input | +-------+-----------+-------------+--------+---------------+ |Volume | volume | ControlPort | Input | Master volume | | | | | | [0.0-1.0] | +-------+-----------+-------------+--------+---------------+ sampler responds to MIDI Program Change events. Based on the event that it receives, it will load up another file (e.g. a drumkit). This is how you can select the drumkit that you wish to use. The presets are defined in a file $HOME/.composite/data/presets/default.xml. For the sampler plugin, you can override this by using default-presets.xml, but at the current time there is no need to. When you first load the sampler, it will check for this file. If it doesn't exist, it will create one based on all your user drumkits. The presets file is a simple XML file that allows you to define MIDI banks, and assign different resources for each program change. An example file is as follows: <?xml version="1.0"?> <T:tritium xmlns: <T:presets> <T:bank <T:program> <T:midi_number>0</T:midi_number> <T:resource>tritium:drumkits/GMkit</T:resource> </T:program> <T:program> <T:midi_number>1</T:midi_number> <T:resource>tritium:drumkits/TR808EmulationKit</T:resource> </T:program> </T:bank> </T:presets> </T:tritium> You can define several <bank> elements for the MIDI banks. The attributes coarse and fine correspond to the MIDI CC's 0 and 32. Each <program> section is a preset. The <midi_number> corresponds to the number in the PC message. The <resource> element holds a URI/URL to the thing you want loaded. This will typically be a drum kit, but can be any kind of file that Composite supports (like a .h2song, .h2pattern, etc.). The sampler will do the Right Thing. (For example, when loading an .h2song, the drumkit stored in the song will be loaded.) The URL's supported are file://, tritium:, and file names. The tritium: scheme is designed to create portable URL's to things like drum kits. For example, the URL "tritium:drumkits/GMkit" will load the drumkit "GMkit", whether it's installed in the user directory ($HOME/.composite/data/drumkits/GMkit/drumkit.xml) or in the system directory (/usr/share/composite/data/drumkits/GMkit/drumkit.xml). Note The XML namespace declaration "" is not optional.
This plugin uses the following extensions, and they must be supported by any program (host) that wishes to use this plugin. If the host does not support them, the plugin will fail to load. o Events <> o Midi Events <>
/usr/share/composite/data/ -- This is the main folder where system data (drumkits, presets, etc.) are stored for Composite and Composite Sampler. $HOME/.composite/data/ -- This is the main folder where user data (drumkits, presets, etc.) are stored for Composite and Composite Sampler. $HOME/.composite/data/drumkits/ -- This is the main folder where user drumkits are stored. Each drumkit has its own folder, and each folder has a file 'drumkit.xml' that describes the drumkit. $HOME/.composite/data/presets/default.xml -- This is the default presets file for Composite. If it does not exist, it will be created automatically using all of your installed drumkits. $HOME/.composite/data/presets/default.xml -- This is the default presets file for Composite. If it does not exist, it will be created automatically using all of your installed drumkits. $HOME/.composite/data/presets/default-plugin.xml -- This is the default presets file for the Composite Sampler. If it does not exist, then $HOME/.composite/data/presets/default.xml is used.
Loading a .h2song through the presets is not happening in a real-time safe manner. Loading drumkits works fine.
composite_midi(7), lv2_jack_host(1)
Gabriel M. Beddingfield <gabriel@teuton.org> | http://huge-man-linux.net/man1/composite_sampler.html | CC-MAIN-2018-26 | refinedweb | 653 | 50.53 |
solvemethod must be invoked to solve the problem. More...
#include <VolVolume.hpp>
Collaboration diagram for VOL_problem:
solvemethod must be invoked to solve the problem.
The INPUT fields must be filled out completely before
solve is invoked.
dsol have to be filled out if and only if the last argument to
solve is
true.
Definition at line 600 of file VolVolume76 of file VolVolume.hpp.
Referenced by OsiVolSolverInterface::getIterationCount().
returns the value of alpha
Definition at line 678 of file VolVolume.hpp.
returns the value of lambda
Definition at line 680 of file VolVolume 630 of file VolVolume.hpp.
value of lambda
Definition at line 632 of file VolVolume.hpp.
iteration number
Definition at line 637 of file VolVolume.hpp.
Definition at line 638 of file VolVolume.hpp.
value of alpha
final lagrangian value (OUTPUT)
Definition at line 647 of file VolVolume.hpp.
final dual solution (INPUT/OUTPUT)
Definition at line 649 of file VolVolume.hpp.
final primal solution (OUTPUT)
Definition at line 651 of file VolVolume.hpp.
violations (b-Ax) for the relaxed constraints
Definition at line 653 of file VolVolume.hpp.
The parameters controlling the Volume Algorithm (INPUT).
Definition at line 659 of file VolVolume.hpp.
length of primal solution (INPUT)
Definition at line 661 of file VolVolume.hpp.
length of dual solution (INPUT)
Definition at line 663 of file VolVolume.hpp.
lower bounds for the duals (if 0 length, then filled with -inf) (INPUT)
Definition at line 666 of file VolVolume.hpp.
upper bounds for the duals (if 0 length, then filled with +inf) (INPUT)
Definition at line 669 of file VolVolume.hpp. | http://www.coin-or.org/Doxygen/CoinAll/class_v_o_l__problem.html | crawl-003 | refinedweb | 265 | 51.14 |
Java provides several ways to write to file. We can use FileWriter, BufferedWriter, java 7 Files and FileOutputStream to write a file in Java.
Table of Contents
Java
package com.journaldev.files; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFile { /** * This class shows how to write file in java * @param args * @throws IOException */ public static void main(String[] args) { String data = "I will write this String to File in Java"; int noOfLines = 10000; writeUsingFileWriter(data); writeUsingBufferedWriter(data, noOfLines); writeUsingFiles(data); writeUsingOutputStream(data); System.out.println("DONE"); } /** * Use Streams when you are dealing with raw data * @param data */ private static void writeUsingOutputStream(String data) { OutputStream os = null; try { os = new FileOutputStream(new File("/Users/pankaj/os.txt")); os.write(data.getBytes(), 0, data.length()); } catch (IOException e) { e.printStackTrace(); }finally{ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Use Files class from Java 1.7 to write files, internally uses OutputStream * @param data */ private static void writeUsingFiles(String data) { try { Files.write(Paths.get("/Users/pankaj/files.txt"), data.getBytes()); } catch (IOException e) { e.printStackTrace(); } } /** * Use BufferedWriter when number of write operations are more * It uses internal buffer to reduce real IO operations and saves time * @param data * @param noOfLines */ private static void writeUsingBufferedWriter(String data, int noOfLines) { File file = new File("/Users/pankaj/BufferedWriter.txt"); FileWriter fr = null; BufferedWriter br = null; String dataWithNewLine=data+System.getProperty("line.separator"); try{ fr = new FileWriter(file); br = new BufferedWriter(fr); for(int i = noOfLines; i>0; i--){ br.write(dataWithNewLine); } } catch (IOException e) { e.printStackTrace(); }finally{ try { br.close(); fr.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Use FileWriter when number of write operations are less * @param data */ private static void writeUsingFileWriter(String data) { File file = new File("/Users/pankaj/FileWriter.txt"); FileWriter fr = null; try { fr = new FileWriter(file); fr.write(data); } catch (IOException e) { e.printStackTrace(); }finally{ //close resources try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
These are the standard methods to write a file in java and you should choose any one of these based on your project requirements. That’s all for Java write to file example.
You can checkout more Java IO examples from our GitHub Repository.
how can I write in the next line using writeusingfilewriter?
I know if I add true in (file) I can save any new value, but, how can I do the previous step?
I am not sure what do you mean. If you want to write a new line, just write newline character i.e. /n
it’s ” \n ” or System.lineSeparator()
Thanks for correcting my typo in the comment. Yes, it’s “\n”
how we use this “\n” or System.lineseparator to write data with new line. Can you show the way of writting this with a line. ??
Hello,
Can we store real time output into a text file.
I mean that, i am working on NMEA data and this data is continuously coming from GPS device in my computer through USB port, but i am not storing this data into a text file.
can we store this real continuous output into a text file in java.
explained nice!! but when i try to write some data in file it delete previous data…what should i do if i want to keep previous data..
use true in constructor of file
e.g FileWriter fr=new FileWriter(file,true);
this will append new data with previous data instead of deleting
Hi…
How can i copy/write the result from the SQLquery of the data base, which is in the form of list (List objList = DBRepositories.getME1Object(dbSession, “H612O2GN” )), in to the file???
Please reply…..
nice tutorial but is it possible to do simultaneous read and write on same file in java ?
You have to go for NIO | https://www.journaldev.com/878/java-write-to-file | CC-MAIN-2019-39 | refinedweb | 654 | 60.61 |
Related
Tutorial
Progressive Image Loading spent any time on Medium (and I know you have, you’re a developer,) you’ve probably at least noticed their image loading technique. First a very low-resolution image is loaded, and is then displayed to the client highly blurred as a placeholder. Once the full-resolution image loads, the placeholder fades out to reveal it. The resulting transition is very smooth and easy on the eyes.
(If you’re interested in learning more about this technique and alternatives, take a look at this post by José M. Pérez.)
Turns out, of course, that there’s a plugin for Vue (by @ccforward) that implements this effect.
Installation
Install progressive-image in your Vue.js project with Yarn or NPM:
# Yarn $ yarn add progressive-image # NPM $ npm install progressive-image --save
You’ll need to import the CSS in your page first. Use whatever method you’d like. (The most basic method being a direct import.)
<link href="./node_modules/progressive-image/dist/index.css" rel="stylesheet" type="text/css">
Now, in your app’s main file, enable the
ProgressiveImage plugin.
import Vue from 'vue'; import ProgressiveImage from 'progressive-image/dist/vue' import App from 'App.vue'; Vue.use(ProgressiveImage, { removePreview: true }); new Vue({ el: '#app', render: h => h(App) });
Usage
From there, it’s a cinch to add a preview to your component. Assuming you have a full-size and low-resolution image already prepared,
<template> <div class="my-component"> <!-- Render a progressive image --> <div class="progressive"> <img class="preview" v- </div> </div> </template>
Bindings are fully supported, so it’s also a cinch to render images from an array or data set.
Bonus: srcset support.
As an added bonus, progressive-image supports srcset usage for responsive images. (If you’re not familiar with what that is, here’s a great article on the subject.)
You can use it directly through a data attribute or a binding.
<template> <div class="my-component"> <!-- Render a progressive image --> <div class="progressive"> <img class="preview" v-progressive="'./example.png'" src="./example-preview.png" data-/> </div> </div> </template>
Have fun with super simple, great looking responsive images! | https://www.digitalocean.com/community/tutorials/vuejs-progressive-image-loader | CC-MAIN-2020-34 | refinedweb | 358 | 57.27 |
The KDE Look and Feel Project is a GPL-licenced Swing pluggable look and feel which uses Qt and KDE for the drawing of widgets. KDE Look and Feel implements most of the Java Look and Feel API including dialogs (ColorChooser, FileChooser, etc.).
KDE Look and Feel for Java
About The Author
Thom Holwerda
Follow me on Twitter @thomholwerda
33 Comments
2006-04-11 7:35 pmJacobMunoz
Like I said “I’ve alread been poisoned by .Net” – so its mostly me.
But the objects I’m mostly referring to are JOptionPane, JPanel, and all of the J(something) objects. It would have been just slightly more intuitive to remove the ‘J’ prefix, I don’t think Microsoft has copyrighted those quite yet.
And the Import JavaX (javax? is that java extension? or just another random suffix?)
2006-04-11 8:04 pmsmitty
I guess I’m one of the few people who likes both Windows.Forms and Swing. Complaining about having to put a J in front of the objects names and importing the javax instead of java is pretty silly, imo. I mean its not like it is confusing or anything. Stick to complaining about speed and aesthetics – you are on much safer ground there.
2006-04-11 8:37 pmJacobMunoz
“its not like it is confusing or anything”
– it really shouldn’t be confusing. But since the object is cleary ‘a text box’ it’s unnecessary (imo) to delcare that it is ‘a text box in java’ – there is no other ‘textbox’ object, so why the ‘J’? ‘unique’ – with some unforseen consequences. It never ‘took.
2006-04-11 9:07 pmtmack.
2006-04-11 9:45 pmunoengborg
But the objects I’m mostly referring to are JOptionPane, JPanel, and all of the J(something) objects.
The reason for the “J” is probably that Sun needed some way to descriminate between the old java.awt component set that used the native platform for rendering and the new javax.swing components. I.e. there was allready a java.awt.Panel when JPanel was named.
2006-04-12 12:36 amdarcysmith
“It would have been just slightly more intuitive to remove the ‘J’?
2006-04-11 7:56 pmJacobMunoz
“so he’s not used to things like”
– as we’ve never met, I can safely say you don’t know what I’m used to…
“clean design”
– is something that you can do in any platform/framework, no matter how bass-ackwords it is. The ‘namespace’ and ‘region’.
2006-04-11 9:37 pmSimba
>..
2006-04-11 9:04 pmsituation.
2006-04-11 10:48 pmdongdongdog
Totally agree. I think that KDE theme is even uglier than Java Swing’s Metal. Maybe kids under 15 with a lot of body piecings will appreciate it.
2006-04-12 7:26 pmdongdongdog
>?
2006-04-12 12:01 amtmack.
2006-04-12 12:14 amSimba
>.
If you’re developing GPL’ed software, you could use the QtJava-binding the kdebinding-project/package are providing.
Yeah, I know Qt3 only and not official Trolltech-binding.
Edited 2006-04-12 01:47
“I am curious though, if this look and feel matches the theme currently in use by QT. The GTK look and feel theme typically doesn’t work with all GTK themes (or even the most common ones). ”
I tried the demo and yes, the look and feel is native Qt. I have plastik, for instance and it shows all widgets as that of plastik including theme colors etc. ‘fine’
Icons work and all.
Edited 2006-04-12 09:16
2006-04-12 5:44 pmSimba
>.
It’s good to see a project to produce a KDE Look and Feel for Swing, since so far most of the “native” L&F effors on Linux have been targetting Gnome / Gtk.
What about the licenses? Is only valid for GPL products?
I know Java needs an independant graphical interface, but the whole swing branch of the framwork (to me) is ugly as sin.
I’ve probably just been poisoned by .Net Winforms, but the object and method names in swing seem rather meaningless and vague. I’ve worked on about twenty very small Java applications and swing just left me angry and (more) crazy.
I do hope they can unify the appearance – that’s a great accomplishment for the platform in general. I’ve heard many people complain that Linux looks ‘badly thrown together’ when it comes to the interface.
This does look pretty. | https://www.osnews.com/story/14303/kde-look-and-feel-for-java/ | CC-MAIN-2019-51 | refinedweb | 747 | 75.71 |
Login error - getaddrinfo: The requested name is valid, but no data of the requested type was found.Justin Funk Sep 11, 2012 12:37 PM
I have a rhomobile app that is connecting to a rhoconnect app. It's still largely the tutorial code, with the rhoconnect app having one source defined and is also using rhoplugin for a second source running on my Rails server. The rhoplugin source came in first and was running with no problems. I then added the rhoconnect source and ran into authentication issues (Rails server is also the api data source for my rhoconnect source, so this was to be expected). I went to add in token authentication to my source query (using this tutorial for the rails side: and this for the rhomobile side:) and now I'm getting the error in the title. I took out all the newly added code for the rhomobile side (Rails server is never getting hit at this point) and am still getting the error. I'm scratching my head on how to fix because it gives very little info.
The error comes from the mobile app's login_callback method, so the error is being generated by the rhoconnect app, however I can't find anyway to get puts or debug info to come out of that.
Re: Login error - getaddrinfo: The requested name is valid, but no data of the requested type was found.Maxim Zverev Sep 11, 2012 3:00 PM (in response to Justin Funk)
This error indicates that Socket can not establish the connection.
Try to reset both Rhodes and Rhoconnect app.
If you're running RhoSimulator - delete the rhosimulator subdirectory to clean everything.
For RhoConnect - do 'rhoconnect flushdb'
Also, check the RhoConnect logs - does the login request comes at all to the server?
Max.
Re: Login error - getaddrinfo: The requested name is valid, but no data of the requested type was found.Justin Funk Sep 12, 2012 6:27 AM (in response to Maxim Zverev)
I've done the reset as described, cleaned the rhosimulator folder from my client app, and did rhoconnect flushdb. Still getting the error.
I'm not sure where to find the rhoconnect logs, I don't see a file anywhere, but here is the output from the console window when I attempt to login:
[09:25:10 AM 2012-09-12] Use of the POST /application/clientlogin is deprecated. Use Rhoconnect API v1 instead.
127.0.0.1 - - [12/Sep/2012 09:25:13] "POST /application/clientlogin HTTP/1.1" 500 87 2.5641
So it does appear that the login request is hitting the rhoconnect server
Re: Login error - getaddrinfo: The requested name is valid, but no data of the requested type was found.Alexander Babichev Sep 14, 2012 11:32 AM (in response to Justin Funk)
Apparently, you have issues in tour code. Request "POST /application/clientlogin HTTP/1.1" is sent by rhodes app and rhoconect returns 500 (internal server error).
You should start with very basic code and make sure it works for you.
In rhoconnect
class Application < Rhoconnect::Base
class << self
def authenticate(username,password,session)
true
end
# ...
end
In back-end plugin code
Rhoconnect.configure do |config|
# ...
config.authenticate = lambda { |credentials| true }
# ...
end
Then tweak above code
class Application < Rhoconnect::Base
class << self
def authenticate(username, password, session)
# Rhoconnect.api_token is a value of your :api_token field in settings.yml
hash = {:login => username, :password => password, :api_token => Rhoconnect.api_token}.to_json
headers = {:content_type => :json, :accept => :json}
RestClient.post "#{Rhoconnect.appserver}/rhoconnect/authenticate", hash, headers
end
# ...
end
And
config.authenticate = lambda { |credentials|
# validate user/password: credentials['login']/credentials['password']
# return credentials['login'] if they are valid
# otherwise
# Rails.logger.error "Rhoconnect#authenticate: Invalid user credentials: #{credentials['login']}/#{credentials['password']}"
# return false
}
Re: Login error - getaddrinfo: The requested name is valid, but no data of the requested type was found.Justin Funk Sep 17, 2012 11:35 AM (in response to Alexander Babichev)
I was really hoping for a way to debug Rhoconnect to find out what the issue was. I had already planned on going back to the tutorial code and re-building out in smaller steps to see where the issue is. Frankly, I'm not thrilled about it. We're having concerns here about the stability and workability of Rhoconnect and the rest of the platform, and this inability to debug what seems like a key component is not helping things.
Re: Login error - getaddrinfo: The requested name is valid, but no data of the requested type was found.Alexander Babichev Sep 17, 2012 5:19 PM (in response to Justin Funk)
You actually do not need debugger. You should use simple logging tools: in rhoconnect code you can insert puts "..." statements in your source adapter code, in rails add Rails.logger calls in your plugin authenticate method.
If you want debugging, open irb console and do clientlogin manually:
require "jason"
require "rest_client"
hash = {:login => 'some_backend_user', password => "users_password", :api_token => "your_api_token"}.to_json
headers = {:content_type => :json, :accept => :json}
# rhoconnet running on the localhost
response = RestClient.post "", hash, headers // get response body
response.code
response.headers
...
FYI, Method def authenticate(username, password, session) in Application class will never been called if you are using RhoConnect Plugin. So you have troubleshoot only auth method in plugin code. | https://developer.zebra.com/thread/2202 | CC-MAIN-2017-34 | refinedweb | 881 | 55.84 |
I'm working on a problem where I am trying to validate the user input to verify only digits have been used. I'm trying to use the ASCII code to do so, but I'm stuck. I would greatly appreciate any help that can be provided. Thank you in advance!!!
*Delilah*
#include <iostream> using namespace std; int main() { char number[11]; int x = 0; cout << "Please enter the phone number: "; cin >> number; while (number[x] != '\0') { if ((int(number[x]) > 46 || int(number[x]) < 58) cout << int(number[x]); x++; } else { cout << "Invalid characters"; }//end if system("pause"); return 0; } | https://www.daniweb.com/programming/software-development/threads/292408/validating-user-input-using-ascii-code | CC-MAIN-2019-04 | refinedweb | 101 | 73.37 |
Question 26 :-name
For example:^SalesOrder
Your application can then base its processing on these longer names. For example, the code:
public void startElement(String elementName, AttributeList attrs) throws SAXException{ ... if (elementName.equals("SalesOrder")){ // Add new database record. } ... } might become: public void startElement(String elementName, AttributeList attrs) throws SAXException { ... if (elementName.equals("^SalesOrder")){ // Add new database record. } ... } or: public void startElement(String elementName, AttributeList attrs) throws SAXException { ... // getURI() and getLocalName() are utility functions // to parse.
Question 27 :.
Question 28 :
Where can qualified names appear?
Qualified names can appear anywhere an element type or attribute name can appear: in start and end tags, as the document element type, and in element type and attribute declarations in the DTD. For example:
<!DOCTYPE foo:A [ <!ELEMENT foo:A (foo:B)> <!ATTLIST foo:A foo:C CDATA #IMPLIED> <!ELEMENT foo:B (#PCDATA)> ]> <foo:A xmlns: <foo:B>abcd <foo:A>
Qualified names cannot appear as entity names, notation names, or processing instruction targets.
Question 29 :
Can qualified names be used in attribute values?
Yes, but they have no special significance. That is, they are not necessarily recognized as such and mapped to universal names. For example, the value of the C attribute in the following is the string "foo:D", not the universal name {}D.
<foo:A xmlns:
<foo:B
<foo:A>
In spite of this, there is nothing to stop an application from recognizing a qualified name in an attribute value and processing it as such. This is being done in various technologies today. For example, in the following XML Schemas definition, the attribute value xsd:string identifies the type of the foo attribute as the universal name {}string.
<xsd:attribute
There are two potential problems with this. First, the application must be able to retrieve the prefix mappings currently in effect. Fortunately, both SAX 2.0 and DOM level 2 support this capability. Second, any general purpose transformation tool, such as one that writes an XML document in canonical form and changes namespace prefixes in the process, will not recognize qualified names in attribute values and therefore not transform them correctly. Although this may be solved in the future by the introduction of the QName (qualified name) data type in XML Schemas, it is a problem today.
Question 30 :
<foo:A>
If a qualified name in the body of a document does not include a prefix and a default XML namespace is in scope then one of two things happens. If the name is used as an element tag, it is mapped to a name in the default XML namespace. If it is used as an attribute name, it is not in any XML namespace. For example, in the following, A and B are in the namespace and C is not in any XML namespace:
<?xml version="1.0" ?>
<A xmlns="" C="bar">
<B>abcd</B>
<A>
If a qualified name in the body of a document does not include a prefix and no default XML namespace is in scope, then that name is not in any XML namespace. For example, in the following, A, B, and C are not in any XML namespace:
<?xml version="1.0" ?>
<A C="bar">
<B>abcd</B>
<A>
Qualified names in the DTD are never mapped to names in an XML namespace because they are never in the scope of an XML namespace declaration. | http://www.indiaparinam.com/xml-question-answer-xml-interview-questions/set-4/page5 | CC-MAIN-2019-13 | refinedweb | 559 | 63.39 |
Geert Uytterhoeven <geert@linux-m68k.org> writes:
> Hi Stephen, David,
>
> On Wed, Aug 22, 2012 at 5:11 AM, Stephen Rothwell <sfr@canb.auug.org.au>
> wrote:
>> Today's linux-next merge of the rr tree got a conflict in
>> arch/mips/kernel/module.c between commit c54de490a2e4 ("MIPS: Module:
>> Deal with malformed HI16/LO16 relocation sequences") from the mips tree
>> and commit 9db0bbe072c8 ("MIPS: Fix module.c build for 32 bit") from the
>> rr tree.
>>
>> Just context changes (I think). I fixed it up (see below) and can carry
>> the fix as necessary.
>
>> + #endif
>
> At first I thought this merge conflict resolution introduced the bogus #endif:
>
> arch/mips/kernel/module.c:247:2: error: #endif without #if
That was my bad rebase against another patch.
Fixed now, thanks.
Rusty. | http://www.linux-mips.org/archives/linux-mips/2012-08/msg00355.html | CC-MAIN-2015-40 | refinedweb | 130 | 68.97 |
Write a Java interface named Searchable with two abstract methods: one named Way2Search that returns a String and another named MaxTime that returns an Integer. Be sure your code compiles and runs as expected. Name your Java file Searchable.java.
Although there is no compilitation errors, or any errors throughout the program. I do feel like this is not the right way. Please, any assistance will help out.
Searchable.java
package searchable; public class Searchable { public static void main(String[] args) { Search s = new Search() { @Override public void Way2Search(String Topic) { System.out.print("How many times have the Packers won the Superbowl?"); } @Override public void MaxTime(int Number) { System.out.print(" 4"); } }; s.Way2Search("How many times have the packers won the superbowl"); s.MaxTime( 4); } }
Search.java
package searchable; public abstract class Search { public Search(){ System.out.print("Print: "); } public abstract void Way2Search(String Topic); public abstract void MaxTime(int Number); } | https://www.daniweb.com/programming/software-development/threads/420192/interface-and-abstract-methods-need-help | CC-MAIN-2017-09 | refinedweb | 153 | 61.73 |
I am trying to read a comma separated file in scala and convert that into list of Json object. The code is working if all the records are valid. How do i catch the exception for the records which are not valid in my function below. If a record is not valid it should throw and exception and continue reading the file. but in my case once an invalid record comes the application stops.
def parseFile(file: String): List[JsObject] = {
val bufferedSource = Source.fromFile(file)
try {
bufferedSource.getLines().map(line => {
val cols = line.split(",").map(_.trim)
(Json.obj("Name" -> cols(0), "Media" -> cols(1), "Gender" -> cols(2), "Age" -> cols(3).toInt)) // Need to handle io exception here.
}).toList
}
finally {
bufferedSource.close()
}
}
I think you may benefit from using Option () and the Try object ()
What you are doing here is stopping all work when an error happens (ie you throw to outside the map) a better option is to isolate the failure and return some object that we can filer out. Below is a quick implementation I made
package csv import play.api.libs.json.{JsObject, Json} import scala.io.Source import scala.util.Try object CsvParser extends App { //Because a bad row can either != 4 columns or the age can not be a int we want to return an option that will be ignored by our caller def toTuple(array : Array[String]): Option[(String, String, String, Int)] = { array match { //if our array has exactly 4 columns case Array(name, media, gender, age) => Try((name, media, gender, age.toInt)).toOption // any other array size will be ignored case _ => None } } def toJson(line: String): Option[JsObject] = { val cols = line.split(",").map(_.trim) toTuple(cols) match { case Some((name: String, media: String, gender: String, age: Int)) => Some(Json.obj("Name" -> name, "Media" -> media, "Gender" -> gender, "Age" -> age)) case _ => None } } def parseFile(file: String): List[JsObject] = { val bufferedSource = Source.fromFile(file) bufferedSource.getLines().map(toJson).toList.flatten } parseFile("my/csv/file/path") }
The above code will ignore any rows where there not exactly 4 columns. It will also contain the NumberFormatException from .toInt.
The idea is to isolate the failure and pass back some type that the caller can either work with when the row was parsed...or ignore when a failure happened. | https://codedump.io/share/fefPe5GMswrV/1/scala-io-exception-handling | CC-MAIN-2017-17 | refinedweb | 383 | 57.77 |
252
Hi,
On 30.08.09 22:06, Keith Marshall wrote:
>).
Ah, indeed, that's the problem.
After adding --export-all-symbols I get a working dll.a. :-)
I tried to find the "wrong" dllexport, I think I found it but removing it did
not help. Strange.
But I guess using --export-all-symbols is easier anyway as I don't have to touch
the source code.
Thanks!
--
Martin
On Monday 31 August 2009 12:32:28 Chris Sutcliffe wrote:
> >?
Like Chris says, setenv() and unsetenv() are not supported in MinGW,
because they aren't supported by the MSVCRT runtime library. The
usual alternative choice is putenv() -- it's somewhat more portable
than any Microsoft specific choice; putenv( "FOO=value" ) is the
alternative to setenv( "FOO", "value", 1 ), while putenv( "FOO=" )
has a rather less portable effect similar to unsetenv( "FOO" ).
--
Regards,
Keith.
> I'm cross compiling mingw on ubuntu (runtime 3.12-1)
>
>?
> where is the definitve copy of the runtime source? I don't seem to know
> where its stored (I don't know where its stored -- I found LOTS of other things)
The mingwrt is stored in Cygwin CVS () in
the winsup/mingw directory. You can browse it online:
Chris
--
Chris Sutcliffe
Hello,
I searched the gmane links about the error in the subject but I
couldn't find anything.
Also I have searched in google and found this :
My original code was working with VS 2008.
After trying with Qt Creator (with mingw), I got the same error in above post.
Huseyin
This is the function that registers the device notifications :
-------------------------------------------------------------------------------------
#include <windows.h> // from C:\Qt\2009.03\mingw\include\windows.h
#include <Dbt.h> // from C:\Qt\2009.03\mingw\include\dbt.h
// ...other header files
// ...other functions
void MainWindow::RegisterForDeviceNotifications(void)
{
DEV_BROADCAST_DEVICEINTERFACE DevBroadcastDeviceInterface = {0};
HDEVNOTIFY DeviceNotificationHandle;
DevBroadcastDeviceInterface.dbcc_size = sizeof(DevBroadcastDeviceInterface);
DevBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
DevBroadcastDeviceInterface.dbcc_classguid = GetHidGuid();
DeviceNotificationHandle = RegisterDeviceNotification(winId(),
&DevBroadcastDeviceInterface, DEVICE_NOTIFY_WINDOW_HANDLE);
}
And this is the error codes after compiling:
----------------------------------------------------------------
MainWindow.cpp: In member function `void
MainWindow::RegisterForDeviceNotifications()':
MainWindow.cpp:2073: error: `DEV_BROADCAST_DEVICEINTERFACE' was not
declared in this scope
MainWindow.cpp:2073: error: expected `;' before "DevBroadcastDeviceInterface"
MainWindow.cpp:2076: error: `DevBroadcastDeviceInterface' was not
declared in this scope
MainWindow.cpp:2077: error: `DBT_DEVTYP_DEVICEINTERFACE' was not
declared in this scope
MainWindow.cpp:2081: error: `DEVICE_NOTIFY_WINDOW_HANDLE' was not
declared in this scope
MainWindow.cpp:2081: error: `RegisterDeviceNotificationW' was not
declared in this scope
------------------------------------------------------------------------------------------------------------------------------------------------------
I'm cross compiling mingw on ubuntu (runtime 3.12-1)
A few questions:
setenv/unsetenv seems to be in libiberty (is that GPL or free to use in
proprietary applications?
where is the definitve copy of the runtime source? I don't seem to know
where
its stored (I don't know where its stored -- I found LOTS of other things)
marty).
--
Regards,
Keith.
On 23.08.09 23:02, Martin Hauner wrote:
> Hi,
>
> I'm trying to build apr& apr-util (1.3.x branch from svn) with mingw (gcc 4.4.0
> etc.).
>
> With a few tweaks to libtool (--no-undefined) it builds the shared libraries for
> both. The tests of apr run. Unfortunately the import lib for apr-util
> (libarputil-1.dll.a) is broken, it is just 1.5 kbyte large and includes only 2
> exports. When I run make check in apr-util linking of the test program fails.
Interesting is, that after removing two object files from the libtool linker
input it creates a proper dll and a dll.a file. It doesn't link the test program
(of course) because it has a few missing symbols defined in the two left out
object files. But otherwise it looks ok. Depends.exe properly lists all other
symbols as present in the dll.
(dll.a size: 165.782 dll size: 337.275)?
--
Martin
Hi all,
I have a linking problem when using -D__USE_MINGW_ANSI_STDIO.
I get "multiple definition of `_printf'" link-time error when linking several
objects which all use std::printf().
To reproduce:
File test_printf1.cpp :
----------------------------------------------------
#include <cstdio>
int main()
{
std::printf("hello\n");
return 0;
}
----------------------------------------------------
File test_printf2.cpp :
----------------------------------------------------
#include <cstdio>
void func()
{
std::printf("world\n");
}
----------------------------------------------------
$ i386-pc-mingw32-g++ -D__USE_MINGW_ANSI_STDIO test_printf1.cpp -c -o test_printf1.o
$ i386-pc-mingw32-g++ -D__USE_MINGW_ANSI_STDIO test_printf2.cpp -c -o test_printf2.o
$ i386-pc-mingw32-g++ test_printf1.o test_printf2.o -o test_printf.exe
test_printf2.o:test_printf2.cpp:(.text+0x14): multiple definition of `_printf'
test_printf1.o:test_printf1.cpp:(.text+0x3e): first defined here
collect2: ld returned 1 exit status
$ i386-pc-mingw32-nm test_printf1.o
00000000 b .bss
00000000 d .data
00000000 r .rdata
00000000 t .text
U ___main
U ___mingw_vprintf
U __alloca
00000000 T _main
0000003e T _printf
$ i386-pc-mingw32-nm test_printf2.o
00000000 b .bss
00000000 d .data
00000000 r .rdata
00000000 t .text
00000000 T __Z4funcv
U ___mingw_vprintf
00000014 T _printf
I'm using gcc 3.4.5 (mingw version) cross-compiler (from linux),
binutils-2.19.1, mingwrt-3.16, w32api-3.13.
Thanks,
Alexander
Hello,
The MS documentation at
specifies that AttachConsole() is available since windows xp.
However, wincon.h from mingwrt-3.16 says:
#if (_WIN32_WINNT >= 0x0500)
#define ATTACH_PARENT_PROCESS ((DWORD)-1)
BOOL WINAPI AttachConsole(DWORD);
#endif
AFAIK, 0x0500 is win2k, right?
I guess it should be 0x0501.
Note that when running an application which uses AttachConsole()
on win2k, I get:
"The procedure entry point AttachConsole could not be located
in the dynamic link library KERNEL32.dll."
Thanks,
Alexander
Hello,
It seems that the prototype of _open_osfhandle() is incorrect
in io.h (from mingwrt-3.16).
It says:
_CRTIMP int __cdecl __MINGW_NOTHROW _open_osfhandle (long, int);
The MS documentation, on the other hand, says:
int _open_osfhandle (
intptr_t osfhandle,
int flags
);
That's from .
Thanks,
Alexander
> I used PExports to extract the symbols for the DEF file and wondered why it
> wasn't part of the MingGW utilities -- but I guess, if one is already
> familiar with the contents of DEF files, that it's easy enough to edit up
> such a file from the list of undefined references emitted by the linker. As
> a convenience for novice users, an enhancement to dlltool would be to read a
> DLL and output _both_ a DEF (for reference purposes) and an import library
> in a single step.
>
> But then again, better documentation of how and when to create import
> libraries would have solved the problem.
Perhaps there's a wiki you could update to help the rest of us :)
-r
On 2009-08-28 22:15Z, Ajay Lele wrote:
>
> SOCKET type is defined as u_int in MinGW winsock2.h whereas it is UINT_PTR
> in Windows SDK version of it. Is there a reason for having it different in
> MinGW winsock2.h?
Please don't quote any part of a copyrighted MS file here,
because that taints any developer who reads it. See, e.g.:
Fortunately, this information can be found on msdn:
| SOCKET is a UINT_PTR.
Hi,
SOCKET type is defined as u_int in MinGW winsock2.h whereas it is UINT_PTR
in Windows SDK version of it. Is there a reason for having it different in
MinGW winsock2.h?
Thanks
Ajay
On Friday 28 August 2009 07:16:30 Chris Sutcliffe wrote:
> >.
With respect Chris, I strongly disagree.
The definition of _finddata_t properly belongs in a system header,
and user code should #include the appropriate header, to get the
definition. If it isn't there, then user code should simply assume
that it isn't supported, (and neither is any API associated with
it); in any such case, the user code should be prepared to handle
the situation without any reference to the missing API. Unless
Microsoft themselves document, on MSDN, that a particular guard
macro is defined to indicate the availability of a particular API,
(and a search for _FINDDATA_T_DEFINED on MSDN finds no references),
then no application should ever rely on the existence, or absence of
any such macro. It certainly isn't appropriate to kludge around an
*apparent* absence of an API, simply because some arbitrary guard
macro isn't defined, and no developer has any right to expect that
the system implementor would define any particular magic guard macro
to facilitate such a kludge.
The correct approach here is for the application maintainer to add a
configuration check to his build machinery, to determine beforehand
if a required API is supported, (by attempting to compile a code
fragment which refers to the actual data structures required), and
then provide his own private set of conditionals, to handle the
cases where it isn't. (Hint: autoconf is good at this).
If you start adding magic guard macros for every typedef some rogue
application's maintainer asks for, where do you stop? Logically,
you would have to provide one for *every* typedef in *every* header
in the system include path. The idea is preposterous; the OP should
ask the maintainer of the application in question to fix his code.
--
Regards,
Keith.
Charles Wilson wrote:
> Pau Climent i Pérez wrote:
>
>> libstdc++.la points to "libstdc++.dll.a" (library name), but this file
>> does not exist in the directory where libstdc++.la is found.
>>
>> I'm getting errors. I read on a forum to change library name from
>> ".dll.a" to "_s.a". But I think it gets worse.
>>
>> Can anyone help me?
>>
>
> Known problem. Not yet resolved. See:
>
>
> You might try simply deleting (or, moving to a safe hidden location) the
> .la files.
>
>
> --
> Chuck
>
Actually, it's better to change it to "library_names=" (empty string)
>>. Can you please let me know what additional guards are
looked for and I will add them accordingly?
Cheers!
Chris
--
Chris Sutcliffe
On Thu, 27 Aug 2009, Chris Sutcliffe wrote:
>> ok, i'll ask the author to add guards when using mingw
>
>.
Vincent Torri
I have been lucky enough to survive this process, writing a DLL (which you already have) and writing a GUI to use access it. You would want to create a separate class (header and C++ files) for abstracting your DLL. Then your main module can instantiate the DLL "wrapper" or interface. Here is my code for interfacing to my DLL, which you can modify for your own use:
//======== Include File ========//
#ifndef FX2DLL_H
#define FX2DLL_H
// This module is a wrapper for interfacing to my FX2 EEPROM DLL
#include "windows.h"
#define FX2DLL_PATH "C:\\Program Files\\msfx2\\fx2eep.dll"
typedef struct VID_PID
{
UINT vid;
UINT pid;
};
// define dll function prototypes
typedef UINT (__cdecl *FX2DLL_INIT)(VOID); // DLL Init Function
typedef CHAR *(__cdecl *FX2DLL_GET_PROBE_NAME)(VOID); // DLL GetProbeName Function
typedef VOID (__cdecl *FX2DLL_SELECT_PROBE)(UCHAR); // DLL SelectProbe Function
typedef UCHAR *(__cdecl *FX2DLL_GET_BUFFER)(VOID); // DLL GetBuffer Function
typedef VOID (__cdecl *FX2DLL_WRITE_BLOCK)(UCHAR); // DLL WriteBlock Function
typedef VOID (__cdecl *FX2DLL_READ_BLOCK)(UCHAR); // DLL ReadBlock Function
typedef VOID (__cdecl *FX2DLL_WRITE_VID_PID)(VID_PID*); // DLL WriteVidPid Function
typedef VOID (__cdecl *FX2DLL_READ_VID_PID)(VID_PID*); // DLL ReadVidPid Function
typedef VOID (__cdecl *FX2DLL_WRITE_SERIAL)(CHAR *); // DLL WriteSerial Function
typedef CHAR *(__cdecl *FX2DLL_READ_SERIAL)(VOID); // DLL ReadSerial Function
class Fx2Dll
{
private:
// declare dll functions
FX2DLL_INIT Fx2DllInit;
FX2DLL_GET_PROBE_NAME Fx2DllGetProbeName;
FX2DLL_SELECT_PROBE Fx2DllSelectProbe;
FX2DLL_GET_BUFFER Fx2DllGetBuffer;
FX2DLL_WRITE_BLOCK Fx2DllWriteBlock;
FX2DLL_READ_BLOCK Fx2DllReadBlock;
FX2DLL_WRITE_VID_PID Fx2DllWriteVidPid;
FX2DLL_READ_VID_PID Fx2DllReadVidPid;
FX2DLL_WRITE_SERIAL Fx2DllWriteSerial;
FX2DLL_READ_SERIAL Fx2DllReadSerial;
public:
Fx2Dll();
~Fx2Dll();
CHAR *fx2dll_path;
CHAR wcpSerial[80];
BOOL fFreeResult;
BOOL fRunTimeLinkSuccess;
HINSTANCE hFx2Dll;
// declare local functions connected to dll functions
// try to make callable function names the same as in dll
UINT Init();
CHAR *GetProbeName();
VOID SelectProbe(UCHAR);
UCHAR *GetBuffer();
VOID WriteBlock(UCHAR);
VOID ReadBlock(UCHAR);
VOID WriteVidPid(VID_PID *);
VOID ReadVidPid(VID_PID *);
VOID WriteSerial(CHAR *);
CHAR *ReadSerial();
};
#endif // FX2DLL_H
// ====== CPP File =======//
#include "fx2dll.h"
Fx2Dll::Fx2Dll()
{
fFreeResult = FALSE;
fRunTimeLinkSuccess = FALSE;
hFx2Dll = LoadLibrary( TEXT(FX2DLL_PATH) );
if (hFx2Dll != NULL)
{
Fx2DllInit = (FX2DLL_INIT) GetProcAddress(hFx2Dll, "Init");
if (Fx2DllInit != NULL)
{
fRunTimeLinkSuccess = TRUE;
// Connect up all the DLL function pointers
Fx2DllGetProbeName = (FX2DLL_GET_PROBE_NAME) GetProcAddress(hFx2Dll, "GetProbeName");
Fx2DllSelectProbe = (FX2DLL_SELECT_PROBE) GetProcAddress(hFx2Dll, "SelectProbe");
Fx2DllGetBuffer = (FX2DLL_GET_BUFFER) GetProcAddress(hFx2Dll, "GetBuffer");
Fx2DllWriteBlock = (FX2DLL_WRITE_BLOCK) GetProcAddress(hFx2Dll, "WriteBlock");
Fx2DllReadBlock = (FX2DLL_READ_BLOCK) GetProcAddress(hFx2Dll, "ReadBlock");
Fx2DllWriteVidPid = (FX2DLL_WRITE_VID_PID) GetProcAddress(hFx2Dll, "WriteVidPid");
Fx2DllReadVidPid = (FX2DLL_READ_VID_PID) GetProcAddress(hFx2Dll, "ReadVidPid");
Fx2DllWriteSerial = (FX2DLL_WRITE_SERIAL) GetProcAddress(hFx2Dll, "WriteSerial");
Fx2DllReadSerial = (FX2DLL_READ_SERIAL) GetProcAddress(hFx2Dll, "ReadSerial");
}
}
}
Fx2Dll::~Fx2Dll()
{
fFreeResult = FreeLibrary(hFx2Dll);
return;
}
UINT Fx2Dll::Init()
{
return (Fx2DllInit) ();
}
CHAR *Fx2Dll::GetProbeName()
{
return (Fx2DllGetProbeName) ();
}
VOID Fx2Dll::SelectProbe(UCHAR prb)
{
(Fx2DllSelectProbe) (prb);
return;
}
UCHAR *Fx2Dll::GetBuffer()
{
return (Fx2DllGetBuffer) ();
}
VOID Fx2Dll::WriteBlock(UCHAR block)
{
(Fx2DllWriteBlock) (block);
return;
}
VOID Fx2Dll::ReadBlock(UCHAR block)
{
(Fx2DllReadBlock) (block);
return;
}
VOID Fx2Dll::WriteVidPid(VID_PID *vp)
{
(Fx2DllWriteVidPid) (vp);
return;
}
VOID Fx2Dll::ReadVidPid(VID_PID *vp)
{
return (Fx2DllReadVidPid) (vp);
}
VOID Fx2Dll::WriteSerial(CHAR *ser)
{
(Fx2DllWriteSerial) (ser);
return;
}
CHAR *Fx2Dll::ReadSerial()
{
CHAR* serial = (Fx2DllReadSerial) ();
return serial;
}
//====================//
Sorry I would have posted file somewhere but I don't have an account anywhere to host files.
To access standard Windows DLL's you don't have to go to quite as much effort, this is for a custom DLL.
I've uploaded new versions of several existing MSYS packages to
sourceforge. These packages were all part of the 'MSYS Supplementary
Tools: Technology Preview, Tools for MSYS-1.0.11' release, which in turn
provided updated versions of the components of the MSYS-DTK 1.0.1.
The new versions have been updated to the latest upstream release when
possible, and packaged according to the new standard package format and
naming scheme.
As usual, you'll find the new packages at the FRS in
the following folders:
MSYS gmp 4.2.2 -> 4.3.1
MSYS guile 1.8.4 -> 1.8.7
MSYS autogen [*] 5.9.2
The new packages satisfy the latest MinGW/MSYS packaging standards,
allowing a more granular installation in keeping with the "minimal"
nature of MinGW/MSYS. See for more information.
However, until an installer capable of managing the granular selections
is available (which will happen eventually), what we have is a whole lot
of packages, which you the user have to download separately and manually
unpack. So what should you install?
Short version: *in general* if it has "-dll" or "-rtm" (runtime) in the
name, you'll probably need it at some point, so download and install all
of those. The -doc and -lic packages are obviously optional. As always,
the *-msys-*-dev packages are of interest only to those developing MSYS
applications using the MSYS DVLPR environment.
In *this case* (that is, gmp/guile/autogen) you really only need any of
these packages if (a) you have need to use autogen, or (b) you use the
guile scripting language, or (c) you have already installed the MSYS-DTK
and want to "update" all of its elements, whether you personally use
them or not.
[*] Not updated, just recompiled and repackaged. The reason is that even
the existing MSYS autogen (5.9.2) has long had a problem on both cygwin
and msys: it coredumps every time you run it, *after* successfully
generating the correct output. On cygwin, this was reported to be
fixable by recompiling guile and autogen with a gcc from a more recent
epoch (gcc-3.4.4-2 or newer), which fixed a problem on cygwin with
gcc-3.4.4-1. Unfortunately, on msys there is no known fix for the gcc
bug applicable to msys's ancient gcc-2.95.3.
Well, it may be annoying -- but at least it's usable. However, when
updating to autogen-5.9.7, I found that the same bug seems to have even
worse effects: autogen doesn't coredump -- instead, it fails *before*
generating any output. This is not an improvement.
Therefore, I stuck with 5.9.2, and will wait to update autogen (and
recompile guile) until we have a newer version of gcc for msys. I don't
see any need for hurry, here, tho. The current 5.9.2 behavior, while
inconvenient, has sufficed for two years already...
So, what's next?
For the repackaged DTK, only:
lpr
However, I have a proposal/RFC concerning that one, so stay tuned.
For msysCORE, there's really just
[1] bash
[2] coreutils
[3] (cp)make
[4] and, of course, msyscore-base
Which Cesar has graciously consented to handle.
In the "much later" category, I plan eventually to update ssh to a more
recent version, and msys-perl to 5.8.8 following the lead of the msysGit
team (from the current msys-perl-5.6.1).
--
Chuck
P.S. Here's the list:
libgmp-4.3.1-1-msys-1.0.11-dll-3.tar.lzma
libgmp-4.3.1-1-msys-1.0.11-dev.tar.lzma
gmp-4.3.1-1-msys-1.0.11-doc.tar.lzma
gmp-4.3.1-1-msys-1.0.11-lic.tar.lzma
gmp-4.3.1-1-msys-1.0.11-src.tar.lzma
guile-1.8.7-1-msys-1.0.11-bin.tar.lzma
libguile-1.8.7-1-msys-1.0.11-dll-17.tar.lzma
libguile-1.8.7-1-msys-1.0.11-rtm.tar.lzma
libguile-1.8.7-1-msys-1.0.11-dev.tar.lzma
guile-1.8.7-1-msys-1.0.11-doc.tar.lzma
guile-1.8.7-1-msys-1.0.11-lic.tar.lzma
guile-1.8.7-1-msys-1.0.11-src.tar.lzma
autogen-5.9.2-2-msys-1.0.11-bin.tar.lzma
autogen-5.9.2-2-msys-1.0.11-doc.tar.lzma
autogen-5.9.2-2-msys-1.0.11-lic.tar.lzma
libguileopts-5.9.2-2-msys-1.0.11-dll-0.tar.lzma
libopts-5.9.2-2-msys-1.0.11-dev.tar.lzma
libopts-5.9.2-2-msys-1.0.11-dll-25.tar.lzma
autogen-5.9.2-2-msys-1.0.11-src.tar.lzma
Jim if you find the answer I sure would like to know too. I asked a
similar question last week and have still been searching for the
answer.
Norm
On 8/27/09, James Moody <moody@...> wrote:
> I've just started working with msys/mingw, please forgive if this is
> answered elsewhere (I looked - I really did!).
>
> I have a device, a Windows DLL for this device, and an ansi-c header
> file (which the company considers a complete enough API). I already have
> the device driver installed on my Windows system. I'd like to use
> msys/mingw to write a small test program (open the device, read some
> registers, set some configuration bits, then exit cleanly).
>
> How do I get gcc or g++ to use the DLL file as the library? Is there a
> special flag on the compile line? Or do I have to create a library from
> the DLL?
>
> I can't believe I'm the first person to ask this, but I could not find
> answers or examples anywhere (or maybe I just did not understand what I
> found!).
>
> Thanks.
> --Jim
>
>
>
>
>
>
>
> ------------------------------------------------------------------------------
>:
>
>
--
Sent from my mobile device
> ok, i'll ask the author to add guards when using mingw
Are there existing guards around those functions in the code you are
trying to compile (or does it set a define)?
Chris
--
Chris Sutcliffe
John Klehm wrote:
> On Thu, Aug 27, 2009 at 6:22 AM, James Moody<email-address-certain-someone-feels-should-be-shown> wrote:
>> How do I get gcc or g++ to use the DLL file as the library? Is there a
>> special flag on the compile line? Or do I have to create a library from
>> the DLL?
>
> You use a set of system calls to access the dll, GetModuleHandle (or
> LoadLibrary if youre not sure the dll has been loaded once already)
>
> Then you call GetProcAddress using the handle you got from one of the
> above calls and the function signature you want to use from your dlls
> header.
>
> MSDN has a reasonable example:
>
>
> Note you should call FreeLibrary at some point if you go the LoadLibrary route.
I think the OP means normal linking:
(via "How do I...")
You may also need to search for information on
import libraries and .def files if you get linking errors.
--
Tuomo
... Features should be discovered, not documented
Op 08/26/2009 02:02 PM, pclimentperez schreef:
> Hi people,
>
> Sorry if this isn't new, but, I didn't find anything on google.
>
> I'm working on a project which works with UTF8 files fine under GNU/Linux
> (apertium). Now we're porting it to Win32, using mingw+msys.
>
> A guy on that project, added some _setmode(whatever, _O_U8TEXT); calls, to
> force the win kernel to read files in UTF8.
>
> The mingw compilers now complain about this _O_U8TEXT not being defined.
>
> I've found that, this _O_U8TEXT is defined in fcntl.h, but it's inside an
> #if(__MSVCRT_VERSION__ >= ...)
>
> Is there any way to avoid msvcrt8.dll AND being able to read files in UTF8
> under Windows?
>
> Pau.
>
Hi,
UTF-8 is a stream of bytes, so you can read UTF-8 encoded files as a
normal text file, same as on Linux. No need to use _setmode(). To
convert the utf8 data to wide characters use
MultiByteToWideChar(CP_UTF8, ...) instead of mbstowcs(), because MINGW
mbstowcs() will assume your data is encoded in the Windows ansi system
code page regardless of LANG or LC_CTYPE environment variables. For an
example you can have a look at my latest wcd version 5.1.0
().
Cygwin 1.7 has excellent UTF-8 support. There UTF-8 works out of the box
when you convert from Linux.
best regards,
Erwin Waterlander
On Thu, 27 Aug 2009, Chris Sutcliffe wrote:
>> well, i compiled a code that redefine these structures, and guarded them.
>> Hence, i had redefinition of struct and compilation error
>>
>> your answer could be : fix that stupid code :)
>
> I think that's a better approach. ;)
ok, i'll ask the author to add guards when using mingw
thank you
Vincent Torri
> well, i compiled a code that redefine these structures, and guarded them.
> Hence, i had redefinition of struct and compilation error
>
> your answer could be : fix that stupid code :)
I think that's a better approach. ;) | https://sourceforge.net/p/mingw/mailman/mingw-users/?viewmonth=200908 | CC-MAIN-2016-30 | refinedweb | 3,613 | 56.05 |
At ZEIT, we are passionate about making developers from all backgrounds productive. Earlier this week, we announced our Rust Builder,
@now/rust, and got very positive feedback from the community.
Today, we are once again very excited as we announce support for Go modules on
@now/go.
The case for Go modules
Modules record precise dependency requirements and create reproducible builds. With Modules, you can be confident that the dependencies used in the production build of your Go project are exactly the same version as the ones you used in development. By preventing the inclusion of an incompatible version, you can maintain the reliability of your Go application.
To showcase the use of Go modules with Now, we implemented an Image to ASCII converter in Golang, and deployed it serverless using
@now/go. The converter can also be run from the command line using CURL.
To run Image to ASCII through the command line, run:
curl.
Using modules
If you haven't worked with them yet, the Go wiki explains Go Modules well.
To use and deploy Go Modules with Now, we start by first creating a module:
$ go mod init module-name
go mod init
helps initiate a Go module.
It accepts the module name as an argument.
To add packages we are interested in, we use
go get package-nameand then import them within
index.go. In the case of Image to ASCII, the
importsection is structured as follows:
import ( "bytes" "encoding/json" "image" "image/jpeg" "image/png" "io/ioutil" "net/http" "strconv" "strings" "github.com/mattes/go-asciibot" ascii "github.com/sophearak/goasciiart" ui "github.com/zeit/now-examples/go-image-to-ascii/ui" )
The
index.go
file in Image to ASCII includes multiple external packages. Examples include
go-asciibot and
goasciiart.
Package names
Previously, we enforced that all
@now/gopackages be named
mainfor
@now/goto be able to build it. Since the Builder supplies the
mainfunction and it isn't explicitly defined on the source Go file, some text editors warned about the missing
main.
Using the previously required
main
as the package name resulted in a warning by text editors.
With the newly introduced support for Go Modules, we no longer require the package to be called
main. All package names are supported, and unless the name used is
main, text editors will no longer throw the warning.
package ascii import ( "fmt" "net/http" ) func Handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<h1>Custom: Hello from Go on Now!</h1>") }
In this example, we are calling the package
ascii.
Conclusion and further reading
Now that
@now/goofficially supports Go modules, we are very keen to discover the Go applications you build and deploy with it. Please do let us know about the interesting projects you are building, and how we can be of further service. You can reach out with feedback and comments around
@now/goover Twitter or on Spectrum. The
@now/goBuilder is completely open source. We welcome contributions and encourage you to create your own Builders for your favourite technology - we also have a detailed guide in place to help you.
- You can read more about Go modules on the Golang official wiki
- Official docs for
@now/gocan be found on our docs site | https://zeit.co/blog/introducing-go-modules-on-now-go | CC-MAIN-2020-16 | refinedweb | 544 | 56.55 |
C++ is a very in depth language and can be used for very complex operations, but as with learning any new skill, it is necessary to first learn the fundamentals. This aim of this tutorial is to teach novice programmers how to write simple cin and cout statements. Cin statements are used to receive input from the user of the program, while cout statements output information to the user. These are two very important elements of code in the C++ language. To complete this tutorial, you will need a C++ compiler program, such as Microsoft Visual Studio, or Xcode if you are using a Mac.
Steps
Part One of Three:
Setting Up the Main Function
- 1Include preprocessor directives. These are the first lines of code in the program and are preceded by a hash sign. They are needed for the program to properly compile. In this case the only preprocessor directive needed is iostream, formatted as shown below. Notice that there is no semicolon used at the end of this statement.
- 2Use standard namespace. In addition to preprocessor directives, the first lines of the code must also define the namespace being used. The standard namespace, formatted as shown below, is sufficient for this code. Note that this line ends with a semicolon.
- 3Define the main function. To create the main function, type “int main()” as shown below. The parentheses are for setting the parameters of the function, but here no parameters are needed and thus the parentheses are empty. There is no semicolon after the function definition.
- 4Make curly braces immediately following the function. On the next line, make a set of curly braces as shown in the graphic. Everything included within these curly brackets is part of the main function. The code up to this point should look something like the picture below.Advertisement
Part Two of Three:
Writing Cout Statements
- 1Know the syntax. Cout is used with the insertion operator, which is written as << (two “less than” signs). The actual output then follows, written within quotation marks. The line must end with a semicolon.
- 2Write the cout statement. Within the main function, type the cout statement using the proper syntax. For example: cout << “type text here”;
- 3Become familiar with other uses of cout. Cout can also be used to output the values of variables, as long the variable has already been defined. Simply write the name of the variable after the insertion operator as shown below.
- 4Use multiple insertion operators in a single statement. Insertion operators can be simply chained together, one after the other as shown in the figure.Advertisement
Part Three of Three:
Writing Cin Statements
- 1Know the syntax. Cin is used with the extraction operator, which is written as >> (two “greater than” signs). The operator is then followed by a variable where the inputted data is stored. The line must end with a semicolon.
- 2Write the cin statement. First declare a variable. Then write a cin statement to define a value for the variable as shown. When the program runs, the input that user enters will be assigned to the variable. Note that the cin statement does not output any text onto the monitor.
- 3Combine cin and cout statements. Cin and cout statements can and should be used together. For instance, a cout statement may be used to prompt the user to assign a value to a variable, which is then assigned through a cin statement as shown in the figure.Advertisement
Community Q&A
Search
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.Submit
Advertisement
Warnings
- Note that the green text following the two forward slashes is referred to as a comment. These are simply notes for your own reference, but are not actually a part of the code. This text of the comment is not outputted on the monitor.
- Ensure preprocessor directives and namespace are defined. The code will not properly compile unless the preprocessor directive iostream has been included and the standard namespace is being used. See steps 1-2 in part I for more information.
- Check for missing semicolons. All cin and cout lines must end with a semicolon. However, the preprocessor directive and function definition statements should not end with a semicolon. The compiler should issue an error identifying the location of missing or unneeded semicolons.
- Verify proper syntax. Make sure that all parts of the code strictly follow the syntax laid out in the examples. A single character missing or misplaced can cause the compiler to output an error message.
Advertisement
About This Article
References
Is this article up to date?
Yes
No
Advertisement | https://m.wikihow.com/Use-C%2B%2B-to-Write-Cin-and-Cout-Statements | CC-MAIN-2019-39 | refinedweb | 776 | 67.15 |
Am 11. Januar 2012 08:42 schrieb Isaac Dupree < ml at isaac.cedarswampstudios.org>: >". > Exactly. More specific, the type must be of the form T a1 ... an, where T is a type constructor. The a_i are not needed for field selection, but of course *if* a field is found in namespace T, and the construct was r.f then the type checker is going to check (T.f r), hence the type of r must fit the first argument of T.f in the usual way. The type of T.f itself is of course already known (just like that of any other function the currently typechecked function depends on). >)? > I think that the way it is done in the current Frege compiler (note that the language does not prescribe any particular order or way of typechecking) is the one with the worst percentage of "hits", because it's the most simple approach. -- Ingo -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | http://www.haskell.org/pipermail/glasgow-haskell-users/2012-January/021519.html | CC-MAIN-2014-41 | refinedweb | 162 | 82.65 |
Had a couple ask about my MSDN Flash editorial about what I am going to miss in Australia when i leave so i have enclosed it below…
After having been in Australia for the best 6 years of my life, my wife has decided I have been too happy and it is time we went back to the US. After much negotiation, we finally agreed this coming February will be when we make our return (although, I was hoping for the year 2050 and my wife was hoping for a white Christmas!) In either case, it got me thinking about what am I going to miss the most about Australia – like the weather, the water, the reefs, the diving, the fishing, OMG the beautiful red wines, Finula, the blue veined brie’s, the spicy laksas, the late night kebabs and the list goes on. I then decided what I am going to miss the most about Australia is the people and their “Barby on the Beach” mentality and how it seems to permeates everything Australians do. If you treat everything as a social barbecue and everybody as fellow merry makers, it really changes your outlook on life. It is with no surprise that the latest developer satisfaction surveys found Australians to be the happiest developers on the planet. I am guessing that as a result of this survey, I was named Developer evangelist of the year. But let’s be honest…Glover, Coatsy or any of the Australian user group presidents deserved it every bit as much as I!
Jealously guarding my last 3 months!
Christmas came early this year! November has been a big month: I crashed my motorcycle , flew to the
According to our most recent surveys the happiest developers in the world are now in Brasil! (They knocked | https://blogs.msdn.microsoft.com/charles_sterling/2007/11/28/what-am-i-going-to-miss-the-most-from-australia/ | CC-MAIN-2019-30 | refinedweb | 301 | 60.89 |
Hi, I just downloaded Allegro a few minutes ago, and I am using a jGRASP editor to write my code. I am trying to test it out by creating a program that creates a white background screen, and draws two circles, two rectangles, and two triangles. One of each will be not colored in, and one of each will be filled in with a color. The problem is when I try to compile this program it comes up with an error that says
"allegro.h: No such file or directory"
So, I was wondering if any one could tell me how to install or use allegro with the jGRASP editor?
Thanks for all your responses!!!
oh and here is a copy of the program that I wrote. Just in case you need to see it to help me out.
Do you have allegro.h in your include directory to the compiler you are using. Also I usually do "allegro.h" not <allegro.h>, not sure if that does anything or not.
========================================================Actually I think I'm a tad ugly, but some women disagree, mostly Asians for some reason.
I tried writing
"allegro.h"
and the same error came up, so I guess that doesn't really matter, but Anyway, I think I need to know how to do what you suggested. See I am pretty much a complete noob when it comes to this stuff, and I have learned the basics of C++, and now I want to get into some light game programming. I just need to know how to include the allegro files into my compiler so it knows where to find the allegro files. By the way I am using a
g++ - MinGW (C:\mingw\bin)
compiler, and I am using jGRASP as an editor.I go from setting < compiler setting < workspace, I am sure I am able to add in the allegro files to my compiler I just don't know how to do it!!!
If you are using the prebuilt allegro binaries, the zip contains 3 folders
bin
include
lib
Copy the "include" and "lib" directories to your c:\mingw directory.Explorer or whatever filemanager you use might say "include already exists", its okay, it is not going to overwrite anything since its all new files.
After copying those directories, you should have allegro.h in your c:\mingw\include directory.Also a new directory, c:\mingw\include\allegro.
The bin directory contains the DLL files allegro uses when you compile a dynamic version of your game/program. Personally, I copy these to c:\windows\system32. Someone might object to that because it "clutters" your harddrive If you don't copy them to c:\windows\system32\ copy them to the project directory like:c:\documents and settings\ixilom\allegrostuff\mygame\
Now you should be able to do
#include <allegro.h>
___________________________________________Democracy in Sweden? Not since 2008-Jun-18.<someone> The lesbians next door bought me a rolex for my birthday.<someone> I think they misunderstood when I said I wanna watch...
Also I usually do "allegro.h" not <allegro.h>, not sure if that does anything or not.
You use "" quotes for local includes (headers specific to the current project, that are located in the project's folder or one of its subfolders), and <> brackets to include headers from the compiler's include directory - stdlib, stl, and all libraries you have installed.When installing allegro, you need to run "make install"; if you have configured your compiler environment correctly, this will copy allegro.h to the correct folder. Please take the time to read the allegro installation instructions.
---Me make music: Triofobie---"We need Tobias and his awesome trombone, too." - Johan Halmén | http://www.allegro.cc/forums/thread/589179/636627#target | crawl-003 | refinedweb | 617 | 65.32 |
This blog post was originally published on datahub.io by Rufus Pollock, Meiran Zhiyenbayev & Anuar Ustayev.
The “Core Data” project provides essential data for the data wranglers and data science community. Its online home is on the DataHub:
This post introduces you to the Core Data, presents a couple of examples and shows you how you can access and use core data easily from your own tools and systems including R, Python, Pandas and more.
- Why Core Data
- Examples
- Use Core Data from your favorite language or tool
- Conclusion
Why Core Data
If you build data driven applications or data driven insight you regularly find yourself wanting common “core” data, things like lists of countries, populations, geographic boundaries and more.
However, finding good quality data has always been challenging. Professionals can spend lots of time finding and preparing data before they get to do any real work analysing or presenting.
Recently the Core Data project has got even better with a new home on the newly upgraded DataHub and has expanded thanks to new partners like Datopian and John Snow Labs (more on this in a future post!).
Examples
There are dozens of core datasets already available and many more being worked on, including a list of countries and their 2 digit codes, and a more extensive version.
List of Countries
Ever needed to build a drop-down list of countries in a web application? Or ever needed to add country name labels for a graph and only had country codes?
Then these datasets are for you!
First up is the very simple “country-list” dataset:
You can see a preview table for the dataset on the showcase page:
You can download it in either CSV or JSON formats:
- CSV:
- JSON:
Country Codes
Maybe the simple list of countries is not enough for you. Perhaps you need phone codes for each country, or want to know their currencies?
We’ve got you covered with the more extensive country codes dataset:
All the countries from Country List including number of associated codes - ISO 3166 codes, ITU dialing codes, ISO 4217 currency codes, and many others. This dataset includes 26 different codes and associated information.
You can also preview the data and download in different formats just like it is described for Country List dataset above:
- CSV:
- JSON:
Population
This is another useful dataset for people: you regularly need population in order to do normalisations and calculate per capita figures as part of a statistical analysis.
This dataset includes population figures for countries, regions (e.g. Asia) and the world. Data comes originally from World Bank and has been converted into standard tabular data package with CSV data and a table schema:
Preview the data on the showcase page:
Get the data in CSV or JSON formats just like for any other Core Datasets:
- CSV:
- JSON:
Use Core Data from your favorite language or tool
We have made Core Data easy-to-use from various programming languages and tools. We will walk through using our Country List example. But you can apply these instructions to any other Core Data in the DataHub.
CSV and JSON
If you just need to get data, you have a direct link usable from any tool or app e.g. for the country list:
- CSV -
- JSON -
cURL
Following commands help you to get the data using “cURL” tool. Use
-L flag so “cURL” follows redirects:
# Get the data: curl -L # datapackage.json provides metadata and a list of all data files curl -L # See just the available data files (resources): curl -L | jq ".resources"
R
If you are using R here’s how to get the data you want quickly loaded:
install.packages("jsonlite") library("jsonlite") json_file <- "" json_data <- fromJSON(paste(readLines(json_file), collapse="")) # access csv file by the index starting from 1 path_to_file = json_data$resources[[1]]$path data <- read.csv(url(path_to_file)) print(data)
Python
Here we take a look at how to get Country List in Python programming language:
For Python, first install the
datapackage library (all the datasets on DataHub are Data Packages):
pip install datapackage
Again, we’ll use the
country-list dataset:
from datapackage import Package package = Package('') # get list of resources: resources = package.descriptor['resources'] resourceList = [resources[x]['name'] for x in range(0, len(resources))] print(resourceList) data = package.resources[0].read() print(data)
Pandas
In order to work with Data Packages in Pandas you need to install the Frictionless Data data package library and the pandas extension:
pip install datapackage pip install jsontableschema-pandas
To get the data run following code:
import datapackage data_url = "" # to load Data Package into storage storage = datapackage.push_datapackage(data_url, 'pandas') # data frames available (corresponding to data files in original dataset) storage.buckets # you can access datasets inside storage, e.g. the first one: storage[storage.buckets[0]]
Ruby, JavaScript and many more
We also have support for JavaScript, SQL, Ruby and PHP. See our “Getting Data” tutorial for more:
Conclusion
This post has shown how you can import datasets in a high quality, standard form quickly and easily.
There are many more datasets to explore than the three we showed you here. You can find a full list here:
Finally, we would love collaborators to help us curate even more core datasets. If you’re interested you can find out more about the Core Data Curator program here:
If you have questions, comments or feedback join DataHub’s chat channel or open an issue on DataHub’s tracker. | http://okfnlabs.org/blog/2017/11/03/core-data.html | CC-MAIN-2017-47 | refinedweb | 913 | 57.4 |
Serialization, MonoBehaviour constructors and Unity 5.4
Starting with Unity 5.4, we have added new errors that are displayed when calling the Unity API from constructors/field initializers and during deserialization (loading). The purpose of these errors is to make the Unity API usage requirements clear and avoid any side effects incorrect usage might have.
The majority of the Unity API should only be called from the main thread, e.g. from Start/Update/etc on MonoBehaviour. Similarly, only a subset of the Unity API should be called from script constructors/field initializers, like Debug.Log or Mathf. As Unity will invoke constructors when creating an instance of a class during deserialization (load), which might run on a non-main thread.
These requirements were not strictly enforced in versions of Unity prior to 5.4. Which could lead to crashes, race conditions and issues that were hard to diagnose and reproduce.
In Unity 5.4, the new errors will in most cases not throw a managed exception and will not interrupt the execution flow of your scripts. This approach has been taken to reduce the amount of friction caused by upgrading your projects to Unity 5.4. These errors will throw a managed exception in a future release of Unity. We recommend that you fix these errors (if any) in your project when upgrading to 5.4.
The new errors are documented in the “Script Serialization Errors” section on the Script Serialization page in the manual.
Let’s have a look at the new serialization errors in some common scenarios and how to fix them.
Calling Unity API from constructor/field initializers
When Unity creates an instance of your MonoBehaviour/ScriptableObject derived class, it calls the default constructor to create the managed object. When this happens, we are not yet in the main loop and the scene has not been fully loaded yet. Field initializers are also called when calling the default constructor of a managed object. Calling the Unity API from a constructor is considered unsafe for the majority of the Unity API.
Examples:
In these case we will get the the error “Find is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call in in Awake or Start instead. …”. The fix is to put the call to the Unity API in MonoBehaviour.Start.
Calling Unity API during deserialization (loading)
When Unity loads a scene, it recreates the managed objects from the saved scene and populates them with the saved values (deserializing). In order to create the managed objects, the default constructor for the objects must be called. If a field referencing an object is saved (serialized) and the object default constructor calls the Unity API you will get an error when loading the scene. As in the previous error, we are not yet in the main loop and the scene is not fully loaded. This is considered unsafe for the majority of the Unity API.
Example:
public class SerializationAPICallBehaviour : MonoBehaviour
Here we get the error “Find is not allowed to be called during serialization, call it from Awake or Start instead.” Fixing this issue requires us to refactor the code to make sure that no Unity API calls are made in any constructors for any serialized objects. If it is necessary to call the Unity API for some objects, then this must be done in the main thread from one of the MonoBehaviour callbacks, such as Start, Awake or Update.
Feedback
If you have any comments, questions or general feedback on these errors, you can post them here in this “Script Serialization Errors Feedback” thread on the Unity 5.4 beta forums.
Related posts
10 CommentsSubscribe to comments
ImiJune 7, 2016 at 9:42 am
Thanks for the post. In-depth articles are always appreciated :).
One warning though: Adding any log message is NOT an unintrusive thing.
In the best case, they give some helpful hint to few people of a team.
In the normal case, they just bother all other team members and everyone who can’t do anything against these messages (and making people just ignore all warnings/errors. Also, errors make the “Error Pause” function quite useless).
In the worst case, they simply crash (or rather freeze) the editor/game when occurring too frequently.
Suggestion: What about some “Outstanding Problems” window that just lists all static problems found in a scene? It would not add the same problem twice, ideally recognizing “same problem” before the need to capture any stack trace.
AdamJune 7, 2016 at 3:13 am
I’m very happy to see these errors/warnings finally introduced to core Unity. Obviously, a working Serializer would be many times more awesome – or being allowed to debug the current weak one – but simply having reliable warnings goes a very long way to allowing us to find and fix (or workaround) the problems ourselves.
I’ve written extensively about the IMHO very bad Serializer in Unity, and all the many critical bugs and problems (including corrupted projects) it causes. With this update, I can finally start reviewing entire codebases looking for places where this stuff is happening accidentally – including all the 3rd party code (I’m assuming it triggers even on code that you don’t have the source for, e.g. pre-built DLL’s from the asset store?)
Thanks, guys.
Andrew Raphael LukasikJune 6, 2016 at 5:23 pm
In 5.4 I started to see these errors in OnValidate when building apk. I managed to get around them by putting everything there inside [code] if( this.gameObject.activeInHierarchy ) { } [/code] statement. Can you explain how is that connected and will OnValidate change or maybe become obsolete?
Lukasz PaczkowskiJune 6, 2016 at 6:01 pm
Without knowing the details of your project, I believe this issue with the serialization errors being reported while building apk/players/asset bundles is a bug that was recently fixed and the fix should be available in one of the next 5.4 releases.
Robert CummingsJune 6, 2016 at 4:01 pm
Thanks for doing this. I really dislike ambiguous results (in fact I’m not even sure why unity allows execution at all with errors).
So this is handy. I would also like more where applicable, anything to create less guesswork :)
RedbreadcatJune 6, 2016 at 3:42 pm
Very handy. Since development is being done in this area, does this mean one day more API calls be usable in non-main threads? I don’t understand the underlying engine architecture, but it’s bothersome that some functions such as sprite creation must be called in the main thread. Especially because they eat into frame time so much.
Lukasz PaczkowskiJune 6, 2016 at 6:12 pm
I suggest posting ideas about changes to the Unity API on Unity Feedback, so the appropriate teams can respond.
Joachim AnteJune 6, 2016 at 9:47 pm
There is no way we can safely expose the whole engine API threadsafe, without introducing massive performance regressions. We will likely start exposing small newer lower level functionality API’s over time which has specific requires on how it is used. When we do we want to make sure we can enforce safe usage.
Today the right approach to multithreading game code, is to create your own cached data structures / tightly packed arrays. Operate in jobs on that data and then integrate the data back later on in the frame when the jobs have completed.
ImiJune 7, 2016 at 9:47 am
Now as you mention it… there wasn’t anything on the Unite Wishlist/Roadmap talk about the “multi-threading jobs and tight arrays with a similar-to-shader declarative syntax but everything written in C#”.
Is this feature being worked on? Whom do I have to bribe for more info or even alpha access? :D
Adas LJune 7, 2016 at 10:17 am
I understand there is no smart way of working with game object in non main thread. But few small things would make our life much easier.
1st – things like Application.dataPath, this is static readonly, no problem with exposing it to other threads.
2nd – objects independent from game object like Texture2D – sometimes we need to work a little bit on those textures and this eat heavily frame time. Allowing moving such things to other thread would be helpful a lot. Now I am using ugly interface where main thread need to convert format when exchanging data with other thread.
3rd – some smart way of loading stuff from local storage. It also hurts performance and should be done in background. | https://blogs.unity3d.com/2016/06/06/serialization-monobehaviour-constructors-and-unity-5-4/ | CC-MAIN-2018-09 | refinedweb | 1,433 | 62.27 |
Hi Yury, This is really cool. Some notes on a first read: 1. Excellent work on optimizing dict, that seems valuable independent of the rest of the details here. 2. The text doesn't mention async generators at all. I assume they also have an agi_isolated_execution_context flag that can be set, to enable @asyncontextmanager? 2a. Speaking of which I wonder if it's possible for async_generator to emulate this flag... I don't know if this matters -- at this point the main reason to use async_generator is for code that wants to support PyPy. If PyPy gains native async generator support before CPython 3.7 comes out then async_generator may be entirely irrelevant before PEP 550 matters. But right now async_generator is still quite handy... 2b. BTW, the contextmanager trick is quite nice -- I actually noticed last week that PEP 521 had a problem here, but didn't think of a solution :-). 3. You're right that numpy is *very* performance sensitive about accessing the context -- the errstate object is needed extremely frequently, even on trivial operations like adding two scalars, so a dict lookup is very noticeable. (Imagine adding a dict lookup to float.__add__.) Right now, the errstate object get stored in the threadstate dict, and then there are some dubious-looking hacks involving a global (not thread-local) counter to let us skip the lookup entirely if we think that no errstate object has been set. Really what we ought to be doing (currently, in a non PEP 550 world) is storing the errstate in a __thread variable -- it'd certainly be worth it. Adopting PEP 550 would definitely be easier if we knew that it wasn't ruling out that level of optimization. 4. I'm worried that all of your examples use string keys. One of the great things about threading.local objects is that each one is a new namespace, which is a honking great idea -- here it prevents accidental collisions between unrelated libraries. And while it's possible to implement threading.local in terms of the threadstate dict (that's how they work now!), it requires some extremely finicky code to get the memory management right: It seems like you're imagining that this API will be used directly by user code? Is that true? ...Are you sure that's a good idea? Are we just assuming that not many keys will be used and the keys will generally be immortal anyway, so leaking entries is OK? Maybe this is nit-picking, but this is hooking into the language semantics in such a deep way that I sorta feel like it would be bad to end up with something where we can never get garbage collection right. The suggested index-based API for super fast C lookup also has this problem, but that would be such a low-level API -- and not part of the language definition -- that the right answer is probably just to document that there's no way to unallocate indices so any given C library should only allocate, like... 1 of them. Maybe provide an explicit API to release an index, if we really want to get fancy. 5. Is there some performance-related reason that the API for getting/setting isn't just sys.get_execution_context()[...] = ...? Or even sys.execution_context[...]? 5a. Speaking of which I'm not a big fan of the None-means-delete behavior. Not only does Python have a nice standard way to describe all the mapping operations without such hacks, but you're actually implementing that whole interface anyway. Why not use it? 6. Should Thread.start inherit the execution context from the spawning thread? 7. Compatibility: it does sort of break 3rd party contextmanager implementations (contextlib2, asyncio_extras's acontextmanager, trio's internal acontextmanager, ...). This is extremely minor though. 8. You discuss how this works for asyncio and gevent. Have you looked at how it will interact with tornado's context handling system? Can they use this? It's the most important extant context implementation I can think of (aside from thread local storage itself). 9. OK, my big question, about semantics. The PEP's design is based on the assumption that all context-local state is scalar-like, and contexts split but never join. But there are some cases where this isn't true, in particular for values that have "stack-like" semantics. These are terms I just made up, but let me give some examples. Python's sys.exc_info is one. Another I ran into recently is for trio's cancel scopes. So basically the background is, in trio you can wrap a context manager around any arbitrary chunk of code and then set a timeout or explicitly cancel that code. It's called a "cancel scope". These are fully nestable. Full details here: Currently, the implementation involves keeping a stack of cancel scopes in Task-local storage. This works fine for regular async code because when we switch Tasks, we also switch the cancel scope stack. But of course it falls apart for generators/async generators: async def agen(): with fail_after(10): # 10 second timeout for finishing this block await some_blocking_operation() yield await another_blocking_operation() async def caller(): with fail_after(20): ag = agen() await ag.__anext__() # now that cancel scope is on the stack, even though we're not # inside the context manager! this will not end well. await some_blocking_operation() # this might get cancelled when it shouldn't # even if it doesn't, we'll crash here when exiting the context manager # because we try to pop a cancel scope that isn't at the top of the stack So I was thinking about whether I could implement this using PEP 550. It requires some cleverness, but I could switch to representing the stack as a singly-linked list, and then snapshot it and pass it back to the coroutine runner every time I yield. That would fix the case above. But, I think there's another case that's kind of a showstopper. async def agen(): await some_blocking_operation() yield async def caller(): ag = agen() # context is captured here with fail_after(10): await ag.__anext__() Currently this case works correctly: the timeout is applied to the __anext__ call, as you'd expect. But with PEP 550, it wouldn't work: the generator's timeouts would all be fixed when it was instantiated, and we wouldn't be able to detect that the second call has a timeout imposed on it. So that's a pretty nasty footgun. Any time you have code that's supposed to have a timeout applied, but in fact has no timeout applied, then that's a really serious bug -- it can lead to hangs, trivial DoS, pagers going off, etc. Another problem is code like: async def caller(): with fail_after(10): ag = agen() # then exit the scope Can we clean up the cancel scope? (e.g., remove it from the global priority queue that tracks timeouts?) Normally yes, that's what __exit__ blocks are for, letting you know deterministically that an object can be cleaned up. But here it got captured by the async generator. I really don't want to have to rely on the GC, because on PyPy it means that we could leak an unbounded number of cancel scopes for a finite but unbounded number of time, and all those extra entries in the global timeout priority queue aren't free. (And sys.exc_info has had buggy behavior in analogous situations.) So, I'm wondering if you (or anyone) have any ideas how to fix this :-). Technically, PEP 521 is powerful enough to do it, but in practice the performance would be catastrophically bad. It's one thing to have some extra cost to yielding out of an np.errstate block, those are rare and yielding out of them is rare. But cancel scopes are different: essentially all code in trio runs inside one or more of them, so every coroutine suspend/resume would have to call all those suspend/resume hooks up and down the stack. OTOH PEP 550 is fast, but AFAICT its semantics are wrong for this use case. The basic invariant I want is: if at any given moment you stop and take a backtrace, and then look at the syntactic surroundings of each line in the backtrace and write down a list of all the 'with' blocks that the code *looks* like it's inside, then context lookups should give the same result as they would if you simply entered all of those with blocks in order. Generators make it tricky to maintain this invariant, because a generator frame's backtrace changes every time you call next(). But those are the semantics that make the most sense to me, and seem least surprising in practice. These are also IIUC the semantics that exc_info is supposed to follow (though historically the interaction of exc_info and generators has had lots of bugs, not sure if that's been fixed or not). ...and now that I've written that down, I sort of feel like that might be what you want for all the other sorts of context object too? Like, here's a convoluted example: def gen(): a = decimal.Decimal("1.111") b = decimal.Decimal("2.222") print(a + b) yield print(a + b) def caller(): # let's pretend this context manager exists, the actual API is more complicated with decimal_context_precision(3): g = gen() with decimal_context_precision(2): next(g) with decimal_context_precision(1): next(g) Currently, this will print "3.3 3", because when the generator is resumed it inherits the context of the resuming site. With PEP 550, it would print "3.33 3.33" (or maybe "3.3 3.3"? it's not totally clear from the text), because it inherits the context when the generator is created and then ignores the calling context. It's hard to get strong intuitions, but I feel like the current behavior is actually more sensible -- each time the generator gets resumed, the next bit of code runs in the context of whoever called next(), and the generator is just passively inheriting context, so ... that makes sense. OTOH of course if you change the generator code to: def gen(): a = decimal.Decimal("1.111") b = decimal.Decimal("2.222") with decimal_context_precision(4): print(a + b) yield print(a + b) then it should print "3.333 3.333", because the generator is overriding the caller -- now when we resume the frame we're re-entering the decimal_context_precision(4) block, so it should take priority. So ... maybe all context variables are "stack-like"? -n -- Nathaniel J. Smith -- | https://mail.python.org/pipermail/python-ideas/2017-August/046736.html | CC-MAIN-2020-29 | refinedweb | 1,770 | 62.48 |
Wolfgang Ha"felinger wrote:
> Hey,
>
>>> Ant's purpose is as a build tools, not a Java library.
>
> Perhaps time to change. After all, there must be a reason why
> Maven's community is growing :-)
Ahh, we arent going to go there.
>>> <presetdef> is just syntactic sugar, and is better not used
>>> IMHO.
>
> I disagree. It's very cool. Almost as cool as "macrodef" which
> I really love.
They are good, but work best if you put stuff into new namespaces as
otherwise you are redefining default things. Just like in C++, this can
get you into trouble. Just like in C++, they do give you near unlimited
power.
Regarding private vs public, private stuff is primarily there to let the
team changing things without fear of breaking stuff. There is a general
assumption that public method calls should stay around, purely for
people using Ant programmatically.
If you can make a good case for something becoming public, it will get
changed, or the underlying cause of your problems may get fixed in some
other way.
-steve
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org
For additional commands, e-mail: dev-help@ant.apache.org | http://mail-archives.apache.org/mod_mbox/ant-dev/200605.mbox/%3C44732B81.8040204@apache.org%3E | CC-MAIN-2017-09 | refinedweb | 195 | 66.84 |
deletedEdited Jan 31, 2014 at 13:58 UTC
Sounds like roaming profile trouble.
Those are not folder redirection profiles, they are roaming profiles which are horrible. Folder redirection does not have these.
5 Replies
You could verify your settings are correct using hvremote by going into an elevated command prompt and typing
cscript hvremote.wsf /show /target:TARGET
where TARGET is the server host from your workstation and your workstation from the server.
I have also found that using the cmdkey command will help these issues.
After looking up the root\cimv2 message i found
"I was having trouble with the "Connect to root\cimv2 WMI namespace" test. As it turns out I had a password with a special character (/) and the password wasn't stored correctly in the cmdkey utility. I changed the password on the Hyperv server and on the client to something else and everything worked fine."
Do you think this applies? | https://community.spiceworks.com/topic/146935-hyper-v-manager-permissions | CC-MAIN-2019-09 | refinedweb | 155 | 64.81 |
I have a screenshot program I made, and for some reason it "draws" to the screen. It really does that thing that Windows likes to do(and I hate it) when it freezes up and you can see random crap like the edge of your window that isn't there anymore.
The only problem is, it does this, and takes a screenshot when I look away from the program.
Here is my code:
BTW, sorry for the name of the topic, I meant "Screenshot wont draw to form" :LBTW, sorry for the name of the topic, I meant "Screenshot wont draw to form" :Limport java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import javax.swing.JFrame; public class GuiStart extends JFrame { private static final long serialVersionUID = -621866894461974337L; public static BufferedImage remoteDisplayImage; public GuiStart() { Thread updateThread = new Thread(new UpdateScreen()); updateThread.start(); } @Override public void paint(Graphics g) { Image img = remoteDisplayImage; g.drawImage(img, 0, 0, this); } } class UpdateScreen implements Runnable { public void run() { while (true) { try { Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension screenSize = toolkit.getScreenSize(); Rectangle rectangle = new Rectangle(0, 0, (int)screenSize.getWidth(), (int)screenSize.getHeight()); Robot robot = new Robot(); BufferedImage shot = robot.createScreenCapture(rectangle); GuiStart.remoteDisplayImage = shot; } catch(Exception ex) { ex.printStackTrace(); } } } } | http://www.javaprogrammingforums.com/whats-wrong-my-code/13252-screenshot-wont-draw-picture.html | CC-MAIN-2015-18 | refinedweb | 223 | 52.46 |
Check out Manish’s blog on NetcfSvcUtil.exe crashing on some operating systems and the uploaded fix for it here.
Year: 2009
Back to basics GC series
Check out the Back to basics GC series published a while ago by Abhinaba!!
WCF for mobile whitepaper
Check out Mahathi’s blog about a WCF for mobile whitepaper published recently by one of the MVPs.
HTTPS related hotfix
Manish has posted regarding a hotfix for the HTTPS related issue discussed in a previous post. The hotfix was recently given out to WM based devices on NETCF 3.5. Check out his post!
Back to the NETCF blog
We would like to revive the NETCF team blog and post here instead of the mobile developer blog as we noted earlier. Welcome back to the team blog. – NETCF team.
NETCF 3.5 namespace poster updated | https://blogs.msdn.microsoft.com/netcfteam/?m=20096 | CC-MAIN-2017-47 | refinedweb | 141 | 74.59 |
// ex2.cppDownload Example 2
//
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
int * a= new int[10];
int * b=new int(89) ;
cout << "*b=" << *b << endl;
int * c = new (nothrow) int [1000000000];
if (!c)
{
cout << "Failed to allocate memory" << endl;
}
*(a+5)=9;
cout << "a[5]=" << *(a+5) << endl;
delete [] a;
delete b;
delete [] c;
return 0;
}
The array a is allocated space for 10 ints but arrays cannot have an initial value. The int pointer b is allocated space for an int and given an initial value of 89. Next, there is a doomed attempt to allocate a billion ints on my 1GB RAM PC. As an int takes 4 bytes that would require 4GB. Also under 32 bit Windows you are limited to 2GB of RAM.
The (nothrow) prevents an exception occurring and the failed message is almost certain to be displayed, unless you are blessed with a 64 Bit computer and a surfeit of RAM.
The array a is tested by setting and displaying an array element. Just as in C, an array and a pointer can be considered the same-they are addresses. Adding 5 to the pointer is the same as indexing an array by [5].
Finally the three delete statements free up allocated memory. In the case of the filed c variable, freeing up a zero pointer is ok. Note the use of [] for a and c. Forget those on array pointer variables (even char *) and you will experience memory problems.
On the next page : Some Rules for using Pointers | http://cplus.about.com/od/learning1/ss/pointers_7.htm | crawl-002 | refinedweb | 261 | 71.44 |
Created on 2019-11-05 05:43 by benjamin.peterson, last changed 2019-11-09 09:57 by yan12125.
Recent versions of Linux has built out support for pidfd, a way to do process management with file descriptors. I wanted to try it out, so implemented a pidfd-based child watcher for asyncio.
My WIP progress patch is attached. It passes all asyncio tests.
Awesome!
I think the patch can be splitted in os.pidfd_open() and asyncio part itself.
os modification is clear.
asyncio part looks correct after the brief view.
My the main question is: how to detect if the new watcher can be used or asyncio should fallback to threaded based solution?
Nathaniel, you may be interested in the pidfd_open(), at least in adding the function to os module.
I like the idea of exposing pidfd_open() syscall as os.pidfd_open().
Benjamin: Would you mind to create a PR based on your patch, but without your asyncio change?
> +#ifndef __NR_pidfd_open
I would prefer to avoid this part of the patch.
You should accept an optional flags parameter, no?
+ self._loop._remove_reader(pidfd)
+ os.close(pidfd)
Note: Maybe do these operations in the reverse order. I expect a higher risk of exception when calling Python self._loop._remove_reader(), than on closing a FD that we opened.
Thanks for the CC.
It would be nice to get `pidfd_send_signal` as well, while we're at it. But that could be a separate PR.
AFAICT the other bits of the pidfd API right now are some extra flags to clone, and an extra flag to waitid. The waitid flag is nice-to-have but not really urgent, since it's easy enough to use a flag even if the stdlib doesn't explicitly expose it. The clone flags are super interesting, but before we can use them, we need to have some way to access clone itself, and that's a big complicated project, so we definitely shouldn't worry about it here.
Yes, I will be submitting followup changes for pidfd_send_signal and the other goodies.
I would like to use pidfds in subprocess, but as you as you say, that's another kettle of fish.
See also bpo-38630 "subprocess.Popen.send_signal() should poll the process".
> My the main question is: how to detect if the new watcher can be used or asyncio should fallback to threaded based solution?
Perhaps in the __init__ we could do something like this:
class PidfdChildWatcher(AbstractChildWatcher):
def __init__(self):
if not hasattr(os, "pidfd_open"):
raise RuntimeError("os.pidfd_open() is unavailable.")
...
Thoughts?
> My WIP progress patch is attached. It passes all asyncio tests.
I think we could also specifically look for race conditions with `./python -m test test_asyncio.test_subprocess -F -j4`, rather than relying on the tests passing with a single job. The other child watchers have been particularly infamous when it comes race conditions and resource leaks.
I'd be glad to work on testing and opening a PR to asyncio if needed (while giving Benjamin credit for the patch of course).
hasattr is useful for supporting old versions of the os module, but asyncio doesn't have to care about that. You should probably try calling pidfd_open and see whether you get -ESYSCALL, and also maybe try passing it to poll(), since I think there might have been a release where the syscall existed but it wasn't pollable. Not sure what the error for that looks like.
pidfd_open was added after pidfd pollling, so it should suffice to make sure pidfd_open doesn't ENOSYS.
New changeset 6c4c45efaeb40f4f837570f57d90a0b3429c6ae9 by Benjamin Peterson in branch 'master':
bpo-38692: Add os.pidfd_open. (GH-17063)
Would it be useful to use a pidfd in subprocess.Popen to fix bpo-38630 root issue, when pidfd is available?
On Wed, Nov 6, 2019, at 09:57, STINNER Victor wrote:
>
> STINNER Victor <vstinner@python.org> added the comment:
>
> Would it be useful to use a pidfd in subprocess.Popen to fix bpo-38630
> root issue, when pidfd is available?
Probably, but as noted above, we need to figure out the best way to integrate pidfds into subprocess. (Probably not in this issue.)
I got a failure in newly added test_pidfd_open:
======================================================================
FAIL: test_pidfd_open (test.test_posix.PosixTester)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/build/python-git/src/cpython/Lib/test/test_posix.py", line 1479, in test_pidfd_open
self.assertEqual(cm.exception.errno, errno.EINVAL)
AssertionError: 1 != 22
----------------------------------------------------------------------
I'm running kernel 5.3.7-x86_64-linode130 with Arch Linux. At first I suspect that it's related to system call filters from systemd as tests are run in a systemd-nspawn container. However, there are still failures after patching systemd with.
How about also skipping the test if pidfd_open returns EPERM?
I think you must still be experiencing some sort of sandboxing. I don't know how else you would get an EPERM out of pidfd_open.
> I got a failure in newly added test_pidfd_open:
> I'm running kernel 5.3.7-x86_64-linode130 with Arch Linux.
> I think you must still be experiencing some sort of sandboxing. I don't know how else you would get an EPERM out of pidfd_open.
I believe Benjamin is correct. On a native install of Arch Linux with kernel 5.3.7 (using latest updates from the official repos), I received no failures in test_posix.
[aeros:~/repos/benjaminp-cpython]$ ./python -m test test_posix (asyncio-pidfd)
0:00:00 load avg: 1.86 Run tests sequentially
0:00:00 load avg: 1.86 [1/1] test_posix
== Tests result: SUCCESS ==
1 test OK.
Total duration: 544 ms
Tests result: SUCCESS
To confirm there weren't intermittent failures, I also ran test_posix indefinitely, sending SIGINT after ~2500 iterations. No failures occurred:
[aeros:~/repos/benjaminp-cpython]$ ./python -m test test_pty -F (asyncio-pidfd)
...
0:01:31 load avg: 1.57 [2506] test_pty
0:01:31 load avg: 1.57 [2507] test_pty
^C
== Tests result: INTERRUPTED ==
Test suite interrupted by signal SIGINT.
2506 tests OK.
Total duration: 1 min 31 sec
Tests result: INTERRUPTED
It seems that the issue is likely specific to Chih-Hsuan Yen's environment.
> [aeros:~/repos/benjaminp-cpython]$ ./python -m test test_pty -F (asyncio-pidfd)
...
0:01:31 load avg: 1.57 [2506] test_pty
0:01:31 load avg: 1.57 [2507] test_pty
Oops, looks like I copied the wrong results of a separate test I was running earlier. I'll post the results of ~1000 iterations of test_posix below, once it is completed again.
[aeros:~/repos/benjaminp-cpython]$ ./python -m test test_posix -F (asyncio-pidfd)
...
0:08:52 load avg: 1.89 [1008] test_posix
0:08:52 load avg: 2.22 [1009] test_posix
...
1008 tests OK.
Total duration: 8 min 52 sec
Tests result: INTERRUPTED
It seems like systemd-nspawn is just breaking everything:
Benjamin Peterson, Kyle Stanley: Thank you both very much for intensive testing and helpful information! Yes on my Arch Linux box tests are also fine without systemd-nspawn. However, as I have to use systemd-nspawn for some reasons, and investigating how it blocks system calls is beyond my ability, I just add a workaround for now:. | https://bugs.python.org/issue38692 | CC-MAIN-2019-47 | refinedweb | 1,182 | 68.47 |
On Sun, 2009-03-22 at 13:03 -0400, Chet Ramey wrote: > Lubomir Rintel wrote: > > > Bash Version: 4.0 > > Patch Level: 10 > > Release Status: release > > > > Description: > > If the heredoc input is terminted with end-of-file by pressing ^D > > while history is on, bash enters an infinite loop (due to NULL > > dereference along with a rather sick SIGSEGV handling, which will > > probably be subject to a subsequent patch). > > The SIGSEGV just needs to be handled immediately, the problem of doing > "too much" in a signal handler be damned: > > *** ../bash-4.0-patched/sig.c 2009-01-04 14:32:41.000000000 -0500 > --- sig.c 2009-03-21 14:31:30.000000000 -0400 > *************** > *** 449,452 **** > --- 449,457 ---- > int sig; > { > + /* If we get called twice with the same signal before handling it, > + terminate right away. */ > + if (sig == terminating_signal) > + terminate_immediately = 1; > + > terminating_signal = sig; I was thinking about distinguishing between signals that are triggered by the instruction at the handler's return address and the asynchronous ones somehow, but clearly your solution seems much more clever. Still I'm not sure if this is not a regression. I can imagine valid use cases where you deal with lot of signals, while sometimes not being able to have your portion of CPU share served. Just dying is probably not acceptable there. I'm attaching my change merged with yours, just in case. --- bash-4.0.orig/sig.c 2009-01-04 20:32:41.000000000 +0100 +++ bash-4.0/sig.c 2009-03-22 18:51:01.021314888 +0100 @@ -448,6 +448,51 @@ sighandler termsig_sighandler (sig) int sig; { + /* If we get called twice with the same signal before handling it, + there's a good chance we're stuck in an endless loop, due to + returning to the same instruction that trigger the signal. + Terminate right away, unless the signal is on the whitelist of + signals that are known to be always delivered asynchronously. */ + if ( +#ifdef SIGHUP + sig != SIGHUP && +#endif +#ifdef SIGINT + sig != SIGINT && +#endif +#ifdef SIGDANGER + sig != SIGDANGER && +#endif +#ifdef SIGPIPE + sig != SIGPIPE && +#endif +#ifdef SIGALRM + sig != SIGALRM && +#endif +#ifdef SIGTERM + sig != SIGTERM && +#endif +#ifdef SIGXCPU + sig != SIGXCPU && +#endif +#ifdef SIGXFSZ + sig != SIGXFSZ && +#endif +#ifdef SIGVTALRM + sig != SIGVTALRM && +#endif +#ifdef SIGLOST + sig != SIGLOST && +#endif +#ifdef SIGUSR1 + sig != SIGUSR1 && +#endif +#ifdef SIGUSR2 + sig != SIGUSR2 && +#endif + sig == terminating_signal + ) terminate_immediately = 1; + terminating_signal = sig; /* XXX - should this also trigger when interrupt_immediately is set? */ -- Lubomir Rintel <address@hidden> | http://lists.gnu.org/archive/html/bug-bash/2009-03/msg00180.html | crawl-003 | refinedweb | 398 | 68.57 |
taskqueue -- asynchronous task execution
#include <sys/param.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/queue.h>
#include <sys/taskqueue.h>
typedef void (*task_fn)(void *context, int pending);
typedef void (*taskqueue_enqueue_fn)(void *context);
struct task {
STAILQ_ENTRY(task) ta_link; /* link for queue */
int ta_pending; /* count times queued */
int ta_priority; /* priority of task in queue */
task_fn);
void
taskqueue_run(struct taskqueue *queue);
TASK_INIT(struct task *task, int priority, task_fn_t *func,
void *context);
TASKQUEUE_DECLARE(name);
TASKQUEUE_DEFINE(name, taskqueue_enqueue_fn enqueue, void *context,
init);
These functions provide a simple interface for asynchronous execution of
code.
The function taskqueue_create() is used to create new queues. The arguments
to taskqueue_create() include a name which should be unique, a set
of malloc(9) flags which
which are on the queue will be executed at this time..
A convenience macro, TASK_INIT(task, priority, func, context) is provided
to initialise a task structure. The values of priority, func, and
context are simply copied into the task structure fields and the
ta_pending field is cleared.
Two macros TASKQUEUE_DECLARE(name) and TASKQUEUE_DEFINE(name, enqueue,
context, init) are used to declare a reference to a global queue and to
define the implementation of the queue. system provides three global taskqueues, taskqueue_swi,
taskqueue_swi_giant, and taskqueue_thread. The swi taskqueues are run
via a software interrupt mechanism. The taskqueue_swi queue runs without
the protection of the Giant kernel lock, and the taskqueue_swi_giant
queue runs with the protection of the Giant kernel lock. The thread
taskqueue.)
This interface first appeared in FreeBSD 5.0. There is a similar facility
called tqueue in the Linux kernel.
This man page was written by Doug Rabson.
FreeBSD 5.2.1 May 12, 2000 FreeBSD 5.2.1 | http://nixdoc.net/man-pages/FreeBSD/man9/taskqueue_free.9.html | CC-MAIN-2015-32 | refinedweb | 279 | 66.44 |
Welcome to part 3 of the Google Cloud tutorial series. In this tutorial, we're going to address more about the vision API.
What we've seen so far is just a quick, general, "idea" of what our image contains, but the vision API gives us quite a bit more. To begin, again, you can use any image you like for this, but I would like to illustrate a quick method for just seeing if your image happens to have any text and, if so, what that text is. To do this, we'll use the following image:
To get this, do
wget.
Running similar code to before, only changing the image:
import io from google.cloud import vision vision_client = vision.Client() file_name = 'machine-learning-playlist.png' with io.open(file_name, 'rb') as image_file: content = image_file.read() image = vision_client.image( content=content, )
We could investigate our
image object a bit further:
dir(image)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_content', '_detect_annotation', '_detect_annotation_from_pb', '_source', 'as_dict', 'client', 'content', 'detect', 'detect_crop_hints', 'detect_faces', 'detect_full_text', 'detect_labels', 'detect_landmarks', 'detect_logos', 'detect_properties', 'detect_safe_search', 'detect_text', 'detect_web', 'source']
This will give us all of the methods (if you're in an interactive mode, if not, then you would do
print(dir(image))). As you can see, there are quite a few, and I imagine more might get added over time. Regardless, there are a few interesting ones like
detect_logos,
detect_landmarks, and
detect_text. Let's try that last one for now, but also lets see what we'd get from that:
dir(image.detect_text())
>>> dir(image.detect_text()) ['_']
Interesting, we see a bunch of methods that clearly suggest this is an iterable. Let's check it out:
for text in image.detect_text(): print(text.description)
u'Machine\nLearning\n' u'Machine' u'Learning'
As you can see, the first found text is the full text, then we have each word separately. In this case, we'd use this method moreso if our image might just happen to have some text, but we might also have an image that we know is just a bunch of text, like a scanned page...etc. To do this, let's consider a new image:
To get this, do
wget.
import io from google.cloud import vision vision_client = vision.Client() file_name = 'block-of-text.png' with io.open(file_name, 'rb') as image_file: content = image_file.read() image = vision_client.image( content=content, ) print(image.detect_full_text().text)
What you should get back here is the text that is contained in the image (including new lines even).
There are many other methods here, and I can't go through all of them, but I encourage you to investigate with
dir() to find other interesting things. One more thing I'll point out is the .score attribute that quite a few methods will produce. For example, when we do:
import io from google.cloud import vision vision_client = vision.Client() file_name = '375px-Guido_van_Rossum_OSCON_2006_cropped.png' with io.open(file_name, 'rb') as image_file: content = image_file.read() image = vision_client.image( content=content, ) labels = image.detect_labels() for label in labels: print(label.description, label.score)
(u'hair', 0.9756743907928467) (u'face', 0.9537844657897949) (u'person', 0.9195896983146667) (u'facial hair', 0.9065206050872803) (u'nose', 0.8576061725616455) (u'chin', 0.8183086514472961) (u'hairstyle', 0.8074049353599548) (u'beard', 0.7863172292709351) (u'head', 0.7453241944313049) (u'senior citizen', 0.7407116889953613)
We could also include
label.score, which will give us a sort of "confidence" about whether or not that label is actually present in the image. Doing this also suggests to us that the labels are provided to us based on descending scores.
For now, however, we're going to move on to another API, the Natural Language API. | https://pythonprogramming.net/vision-api-contd-google-cloud-tutorial/?completed=/vision-api-intro-google-cloud-tutorial/ | CC-MAIN-2021-39 | refinedweb | 622 | 61.22 |
QHostInfo Class Reference
The QHostInfo class provides static functions for host name lookups. More...
#include <QHostInfo>
Note: All functions in this class are reentrant.
Public Types
Public Functions
Static Public Members
Detailed Descriptiontt.nokia.com");
QHostInfo supports Internationalized Domain Names (IDNs) through the IDNA and Punycode standards.
To retrieve the name of the local host, use the static QHostInfo::localHostName() function.
Note: Since Qt 4.6.1 QHostInfo is using multiple threads for DNS lookup instead of one dedicated DNS thread. This improves performance, but also changes the order of signal emissions when using lookupHost() compared to previous versions of Qt. Note: Since Qt 4.6.3 QHostInfo is using a small internal 60 second DNS cache for performance improvements.
See also QAbstractSocket and RFC 3492..
void QHostInfo::abortHostLookup ( int id ) [static]().
QHostInfo QHostInfo::fromName ( const QString & name ) [static]().
QString QHostInfo::hostName () const
Returns the name of the host whose IP addresses were looked up.
See also setHostName() and localHostName().
QString QHostInfo::localDomainName () [static]
Returns the DNS domain of this machine.
Note: DNS domains are not related to domain names found in Windows networks.
QString QHostInfo::localHostName () [static]
Returns the host name of this machine.
int QHostInfo::lookupHost ( const QString & name, QObject * receiver, const char * member ) [static] (const it.
No notes | http://qt-project.org/doc/qt-4.8/qhostinfo.html | crawl-003 | refinedweb | 211 | 60.92 |
Draft Trimex
Description
The
Draft Trimex command trims or extends a selected object. Intersections with the edge of another object can be used to determine new endpoints. The command can also be used to extrude a face, in which case it creates a Part Extrude object.
Top: a Draft Wire extended and then trimmed. Bottom: a face extruded into a solid body.
Trim or extend
Usage
- Optionally select one object. The object must be a Draft Line, a Draft Wire, a Draft Arc or a Draft Circle (which can only be trimmed). If the selected object is closed it must have its DataMake Face property set to
false.
- There are several ways to invoke the command:
- Press the
Draft Trimex button.
- Select the Modification →
Trimex option from the menu.
- Use the keyboard shortcut: T then R.
- If you have not yet selected an object: select an object in the 3D view.
- The Trimex task panel opens. See Options for more information.
- Move the pointer in the 3D view so that the preview matches the desired result. If required use the modifier keys as explained in the Options.
- Do one of the following:
- Pick a point in the 3D view.
- Enter a Distance or an Angle. The distance is a delta distance. This option does not work if modifier keys are used.
- Move the pointer over an edge belonging to another object, and click when this edge is highlighted, to trim or extend the selected object using an intersection with the highlighted edge as the new endpoint. Note that Draft Snaps can have an undesirable impact here. In some cases it may be required to turn them off temporarily.
Options
The single character keyboard shortcut and the modifier keys mentioned here can be changed. See Draft Preferences.
- The solution with the largest length determines the default direction of the command. Hold down Alt to invert this direction.
- Hold down Shift to restrict the operation to the current segment of a Draft Wire.
- Press S to switch Draft snapping on or off.
Here is an example to explain the modifier keys. The left edge or the bottom edge of the U-shaped wire was extended. All Draft Snaps were turned off.
- The arc was clicked near the bottom left corner of the wire. This is the default behavior.
- Alt was held down while the arc was clicked near the bottom left corner of the wire.
- Y was pressed, and while hovering over the left edge Shift was held down and then the arc was clicked. Pressing Y is only required for edges that are more or less parallel to the Y axis.
Extrude
Usage
See also: Draft Snap and Draft Constrain.
- It can be helpful to first change the Draft working plane so that it is not coplanar with the face you want to extrude.
- Optionally select a single face or an object with a single face.
- There are several ways to invoke the command:
- Press the
Draft Trimex button.
- Select the Modification →
Trimex option from the menu.
- Use the keyboard shortcut: T then R.
- If you have not yet selected an object or a face: select an object with a single face in the 3D view.
- The Trimex task panel opens. See Options for more information.
- To define the extrusion direction and distance do one of the following:
Options
The modifier key mentioned here can be changed. See Draft Preferences.
- Hold Shift to extrude in a direction that is not parallel to the normal of the face.
Preferences
See also: Preferences Editor and Draft Preferences.
- To change the number of decimals used for the input of the distance: Edit → Preferences... → General → Units → Units settings → Number of decimals.
Scripting
See also: Autogenerated API documentation and FreeCAD Scripting Basics.
There is no Python method to trim objects. To extrude objects use the
extrude method of the Draft module.
extrusion = extrude(obj, vector, solid=False)
objis the object to be extruded.
vectoris the extrusion direction and distance.
- If
solidis
Truea solid is created instead of a shell.
extrusionis returned with the created object.
Example:
import FreeCAD as App import Draft doc = App.newDocument() rectangle = Draft.make_rectangle(1500, 500) doc.recompute() vector = App.Vector(0, 0, 300) solid = Draft.extrude(rectangle, vector, | https://wiki.freecadweb.org/Draft_Trimex | CC-MAIN-2021-43 | refinedweb | 707 | 68.87 |
#!/usr/bin/env python # png.py - PNG encoder/decoder in pure Python # # Copyright (C) 2006 Johann C. Rocholl <johann@browsershots.org> # Portions Copyright (C) 2009 David Jones <drj@pobox.com> # And probably portions Copyright (C) 2006 Nicko van Someren <nicko@nicko.org> # # Original concept by Johann C. Rocholl. # #. """ Pure Python PNG Reader/Writer This Python module implements support for PNG images (see PNG specification at ). It reads and writes PNG files with all allowable bit depths (1/2/4/8/16/24/32/48/64 bits per pixel) and colour combinations: greyscale (1/2/4/8/16 bit); RGB, RGBA, LA (greyscale with alpha) with 8/16 bits per channel; colour mapped images (1/2/4/8 bit). Adam7 interlacing is supported for reading and writing. A number of optional chunks can be specified (when writing) and understood (when reading): ``tRNS``, ``bKGD``, ``gAMA``. For help, type ``import png; help(png)`` in your python interpreter. A good place to start is the :class:`Reader` and :class:`Writer` classes. Requires Python 2.3. Limited support is available for Python 2.2, but not everything works. Best with Python 2.4 and higher. Installation is trivial, but see the ``README.txt`` file (with the source distribution) for details. This file can also be used as a command-line utility to convert `Netpbm <>`_ PNM files to PNG, and the reverse conversion from PNG to PNM. The interface is similar to that of the ``pnmtopng`` program from Netpbm. Type ``python png.py --help`` at the shell prompt for usage and a list of options. A note on spelling and terminology ---------------------------------- Generally British English spelling is used in the documentation. So that's "greyscale" and "colour". This not only matches the author's native language, it's also used by the PNG specification. The major colour models supported by PNG (and hence by PyPNG) are: greyscale, RGB, greyscale--alpha, RGB--alpha. These are sometimes referred to using the abbreviations: L, RGB, LA, RGBA. In this case each letter abbreviates a single channel: *L* is for Luminance or Luma or Lightness which is the channel used in greyscale images; *R*, *G*, *B* stand for Red, Green, Blue, the components of a colour image; *A* stands for Alpha, the opacity channel (used for transparency effects, but higher values are more opaque, so it makes sense to call it opacity). A note on formats ----------------- When getting pixel data out of this module (reading) and presenting data to this module (writing) there are a number of ways the data could be represented as a Python value. Generally this module uses one of three formats called "flat row flat pixel", "boxed row flat pixel", and "boxed row boxed pixel". Basically the concern is whether each pixel and each row comes in its own little tuple (box), or not. Consider an image that is 3 pixels wide by 2 pixels high, and each pixel has RGB components: Boxed row flat pixel:: list([R,G,B, R,G,B, R,G,B], [R,G,B, R,G,B, R,G,B]) Each row appears as its own list, but the pixels are flattened so that three values for one pixel simply follow the three values for the previous pixel. This is the most common format used, because it provides a good compromise between space and convenience. PyPNG regards itself as at liberty to replace any sequence type with any sufficiently compatible other sequence type; in practice each row is an array (from the array module), and the outer list is sometimes an iterator rather than an explicit list (so that streaming is possible). Flat row flat pixel:: [R,G,B, R,G,B, R,G,B, R,G,B, R,G,B, R,G,B] The entire image is one single giant sequence of colour values. Generally an array will be used (to save space), not a list. Boxed row boxed pixel:: list([ (R,G,B), (R,G,B), (R,G,B) ], [ (R,G,B), (R,G,B), (R,G,B) ]) Each row appears in its own list, but each pixel also appears in its own tuple. A serious memory burn in Python. In all cases the top row comes first, and for each row the pixels are ordered from left-to-right. Within a pixel the values appear in the order, R-G-B-A (or L-A for greyscale--alpha). There is a fourth format, mentioned because it is used internally, is close to what lies inside a PNG file itself, and has some support from the public API. This format is called packed. When packed, each row is a sequence of bytes (integers from 0 to 255), just as it is before PNG scanline filtering is applied. When the bit depth is 8 this is essentially the same as boxed row flat pixel; when the bit depth is less than 8, several pixels are packed into each byte; when the bit depth is 16 (the only value more than 8 that is supported by the PNG image format) each pixel value is decomposed into 2 bytes (and `packed` is a misnomer). This format is used by the :meth:`Writer.write_packed` method. It isn't usually a convenient format, but may be just right if the source data for the PNG image comes from something that uses a similar format (for example, 1-bit BMPs, or another PNG file). And now, my famous members -------------------------- """ # from __future__ import generators __version__ = "0.0.16" from array import array try: # See :pyver:old import itertools except ImportError: pass import math # import operator import struct import sys import zlib # import warnings try: # `cpngfilters` is a Cython module: it must be compiled by # Cython for this import to work. # If this import does work, then it overrides pure-python # filtering functions defined later in this file (see `class # pngfilters`). import cpngfilters as pngfilters except ImportError: pass __all__ = ['Image', 'Reader', 'Writer', 'write_chunks', 'from_array'] # The PNG signature. # _signature = struct.pack('8B', 137, 80, 78, 71, 13, 10, 26, 10) _adam7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)) def group(s, n): # See return zip(*[iter(s)]*n) def isarray(x): """Same as ``isinstance(x, array)`` except on Python 2.2, where it always returns ``False``. This helps PyPNG work on Python 2.2. """ try: return isinstance(x, array) except TypeError: # Because on Python 2.2 array.array is not a type. return False try: array.tobytes except AttributeError: try: # see :pyver:old array.tostring except AttributeError: def tostring(row): l = len(row) return struct.pack('%dB' % l, *row) else: def tostring(row): """Convert row of bytes to string. Expects `row` to be an ``array``. """ return row.tostring() else: def tostring(row): """ Python3 definition, array.tostring() is deprecated in Python3 """ return row.tobytes() # Conditionally convert to bytes. Works on Python 2 and Python 3. try: bytes('', 'ascii') def strtobytes(x): return bytes(x, 'iso8859-1') def bytestostr(x): return str(x, 'iso8859-1') except (NameError, TypeError): # We get NameError when bytes() does not exist (most Python # 2.x versions), and TypeError when bytes() exists but is on # Python 2.x (when it is an alias for str() and takes at most # one argument). strtobytes = str bytestostr = str def interleave_planes(ipixels, apixels, ipsize, apsize): """ Interleave (colour) planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the `ipsize` elements of data from each pixel in `ipixels` followed by the `apsize` elements of data from each pixel in `apixels`. Conventionally `ipixels` and `apixels` are byte arrays so the sizes are bytes, but it actually works with any arrays of the same type. The returned array is the same type as the input arrays which should be the same type as each other. """ itotal = len(ipixels) atotal = len(apixels) newtotal = itotal + atotal newpsize = ipsize + apsize # Set up the output buffer # See out = array(ipixels.typecode) # It's annoying that there is no cheap way to set the array size :-( out.extend(ipixels) out.extend(apixels) # Interleave in the pixel data for i in range(ipsize): out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize] for i in range(apsize): out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize] return out def check_palette(palette): """Check a palette argument (to the :class:`Writer` class) for validity. Returns the palette as a list if okay; raises an exception otherwise. """ # None is the default and is allowed. if palette is None: return None p = list(palette) if not (0 < len(p) <= 256): raise ValueError("a palette must have between 1 and 256 entries") seen_triple = False for i,t in enumerate(p): if len(t) not in (3,4): raise ValueError( "palette entry %d: entries must be 3- or 4-tuples." % i) if len(t) == 3: seen_triple = True if seen_triple and len(t) == 4: raise ValueError( "palette entry %d: all 4-tuples must precede all 3-tuples" % i) for x in t: if int(x) != x or not(0 <= x <= 255): raise ValueError( "palette entry %d: values must be integer: 0 <= x <= 255" % i) return p def check_sizes(size, width, height): """Check that these arguments, in supplied, are consistent. Return a (width, height) pair. """ if not size: return width, height if len(size) != 2: raise ValueError( "size argument should be a pair (width, height)") if width is not None and width != size[0]: raise ValueError( "size[0] (%r) and width (%r) should match when both are used." % (size[0], width)) if height is not None and height != size[1]: raise ValueError( "size[1] (%r) and height (%r) should match when both are used." % (size[1], height)) return size def check_color(c, greyscale, which): """Checks that a colour argument for transparent or background options is the right form. Returns the colour (which, if it's a bar integer, is "corrected" to a 1-tuple). """ if c is None: return c if greyscale: try: l = len(c) except TypeError: c = (c,) if len(c) != 1: raise ValueError("%s for greyscale must be 1-tuple" % which) if not isinteger(c[0]): raise ValueError( "%s colour for greyscale must be integer" % which) else: if not (len(c) == 3 and isinteger(c[0]) and isinteger(c[1]) and isinteger(c[2])): raise ValueError( "%s colour must be a triple of integers" % which) return c class Error(Exception): def __str__(self): return self.__class__.__name__ + ': ' + ' '.join(self.args) class FormatError(Error): """Problem with input file format. In other words, PNG file does not conform to the specification in some way and is invalid. """ class ChunkError(FormatError): pass class Writer: """ PNG encoder in pure Python. """ def __init__(self, width=None, height=None, size=None, greyscale=False, alpha=False, bitdepth=8, palette=None, transparent=None, background=None, gamma=None, compression=None, interlace=False, bytes_per_sample=None, # deprecated planes=None, colormap=None, maxval=None, chunk_limit=2**20): """ Create a PNG encoder object. Arguments: width, height Image size in pixels, as two separate arguments. size Image size (w,h) in pixels, as single argument. greyscale Input data is greyscale, not RGB. alpha Input data has alpha channel (RGBA or LA). bitdepth Bit depth: from 1 to 16. palette Create a palette for a colour mapped image (colour type 3). transparent Specify a transparent colour (create a ``tRNS`` chunk). background Specify a default background colour (create a ``bKGD`` chunk). gamma Specify a gamma value (create a ``gAMA`` chunk). compression zlib compression level: 0 (none) to 9 (more compressed); default: -1 or None. interlace Create an interlaced image. chunk_limit Write multiple ``IDAT`` chunks to save memory. The image size (in pixels) can be specified either by using the `width` and `height` arguments, or with the single `size` argument. If `size` is used it should be a pair (*width*, *height*). `greyscale` and `alpha` are booleans that specify whether an image is greyscale (or colour), and whether it has an alpha channel (or not). `bitdepth` specifies the bit depth of the source pixel values. Each source pixel value must be an integer between 0 and ``2**bitdepth-1``. For example, 8-bit images have values between 0 and 255. PNG only stores images with bit depths of 1,2,4,8, or 16. When `bitdepth` is not one of these values, the next highest valid bit depth is selected, and an ``sBIT`` (significant bits) chunk is generated that specifies the original precision of the source image. In this case the supplied pixel values will be rescaled to fit the range of the selected bit depth. The details of which bit depth / colour model combinations the PNG file format supports directly, are somewhat arcane (refer to the PNG specification for full details). Briefly: "small" bit depths (1,2,4) are only allowed with greyscale and colour mapped images; colour mapped images cannot have bit depth 16. For colour mapped images (in other words, when the `palette` argument is specified) the `bitdepth` argument must match one of the valid PNG bit depths: 1, 2, 4, or 8. (It is valid to have a PNG image with a palette and an ``sBIT`` chunk, but the meaning is slightly different; it would be awkward to press the `bitdepth` argument into service for this.) The `palette` option, when specified, causes a colour mapped image to be created: the PNG colour type is set to 3; greyscale must not be set; alpha must not be set; transparent must not be set; the bit depth must be 1,2,4, or 8. When a colour mapped image is created, the pixel values are palette indexes and the `bitdepth` argument specifies the size of these indexes (not the size of the colour values in the palette). The palette argument value should be a sequence of 3- or 4-tuples. 3-tuples specify RGB palette entries; 4-tuples specify RGBA palette entries. If both 4-tuples and 3-tuples appear in the sequence then all the 4-tuples must come before all the 3-tuples. A ``PLTE`` chunk is created; if there are 4-tuples then a ``tRNS`` chunk is created as well. The ``PLTE`` chunk will contain all the RGB triples in the same sequence; the ``tRNS`` chunk will contain the alpha channel for all the 4-tuples, in the same sequence. Palette entries are always 8-bit. If specified, the `transparent` and `background` parameters must be a tuple with three integer values for red, green, blue, or a simple integer (or singleton tuple) for a greyscale image. If specified, the `gamma` parameter must be a positive number (generally, a float). A ``gAMA`` chunk will be created. Note that this will not change the values of the pixels as they appear in the PNG file, they are assumed to have already been converted appropriately for the gamma specified. The `compression` argument specifies the compression level to be used by the ``zlib`` module. Values from 1 to 9 specify compression, with 9 being "more compressed" (usually smaller and slower, but it doesn't always work out that way). 0 means no compression. -1 and ``None`` both mean that the default level of compession will be picked by the ``zlib`` module (which is generally acceptable). If `interlace` is true then an interlaced image is created (using PNG's so far only interace method, *Adam7*). This does not affect how the pixels should be presented to the encoder, rather it changes how they are arranged into the PNG file. On slow connexions interlaced images can be partially decoded by the browser to give a rough view of the image that is successively refined as more image data appears. .. note :: Enabling the `interlace` option requires the entire image to be processed in working memory. `chunk_limit` is used to limit the amount of memory used whilst compressing the image. In order to avoid using large amounts of memory, multiple ``IDAT`` chunks may be created. """ # At the moment the `planes` argument is ignored; # its purpose is to act as a dummy so that # ``Writer(x, y, **info)`` works, where `info` is a dictionary # returned by Reader.read and friends. # Ditto for `colormap`. width, height = check_sizes(size, width, height) del size if width <= 0 or height <= 0: raise ValueError("width and height must be greater than zero") if not isinteger(width) or not isinteger(height): raise ValueError("width and height must be integers") # if width > 2**32-1 or height > 2**32-1: raise ValueError("width and height cannot exceed 2**32-1") if alpha and transparent is not None: raise ValueError( "transparent colour not allowed with alpha channel") if bytes_per_sample is not None: warnings.warn('please use bitdepth instead of bytes_per_sample', DeprecationWarning) if bytes_per_sample not in (0.125, 0.25, 0.5, 1, 2): raise ValueError( "bytes per sample must be .125, .25, .5, 1, or 2") bitdepth = int(8*bytes_per_sample) del bytes_per_sample if not isinteger(bitdepth) or bitdepth < 1 or 16 < bitdepth: raise ValueError("bitdepth (%r) must be a postive integer <= 16" % bitdepth) self.rescale = None if palette: if bitdepth not in (1,2,4,8): raise ValueError("with palette, bitdepth must be 1, 2, 4, or 8") if transparent is not None: raise ValueError("transparent and palette not compatible") if alpha: raise ValueError("alpha and palette not compatible") if greyscale: raise ValueError("greyscale and palette not compatible") else: # No palette, check for sBIT chunk generation. if alpha or not greyscale: if bitdepth not in (8,16): targetbitdepth = (8,16)[bitdepth > 8] self.rescale = (bitdepth, targetbitdepth) bitdepth = targetbitdepth del targetbitdepth else: assert greyscale assert not alpha if bitdepth not in (1,2,4,8,16): if bitdepth > 8: targetbitdepth = 16 elif bitdepth == 3: targetbitdepth = 4 else: assert bitdepth in (5,6,7) targetbitdepth = 8 self.rescale = (bitdepth, targetbitdepth) bitdepth = targetbitdepth del targetbitdepth if bitdepth < 8 and (alpha or not greyscale and not palette): raise ValueError( "bitdepth < 8 only permitted with greyscale or palette") if bitdepth > 8 and palette: raise ValueError( "bit depth must be 8 or less for images with palette") transparent = check_color(transparent, greyscale, 'transparent') background = check_color(background, greyscale, 'background') # It's important that the true boolean values (greyscale, alpha, # colormap, interlace) are converted to bool because Iverson's # convention is relied upon later on. self.width = width self.height = height self.transparent = transparent self.background = background self.gamma = gamma self.greyscale = bool(greyscale) self.alpha = bool(alpha) self.colormap = bool(palette) self.bitdepth = int(bitdepth) self.compression = compression self.chunk_limit = chunk_limit self.interlace = bool(interlace) self.palette = check_palette(palette) self.color_type = 4*self.alpha + 2*(not greyscale) + 1*self.colormap assert self.color_type in (0,2,3,4,6) self.color_planes = (3,1)[self.greyscale or self.colormap] self.planes = self.color_planes + self.alpha # :todo: fix for bitdepth < 8 self.psize = (self.bitdepth/8) * self.planes def make_palette(self): """Create the byte sequences for a ``PLTE`` and if necessary a ``tRNS`` chunk. Returned as a pair (*p*, *t*). *t* will be ``None`` if no ``tRNS`` chunk is necessary. """ p = array('B') t = array('B') for x in self.palette: p.extend(x[0:3]) if len(x) > 3: t.append(x[3]) p = tostring(p) t = tostring(t) if t: return p,t return p,None def write(self, outfile, rows): """Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. .. note :: Interlacing will require the entire image to be in working memory. """ if self.interlace:%dH' % vpr def line(): return array('H', struct.unpack(fmt, infile.read(row_bytes))) else: def line(): scanline = array('B', infile.read(row_bytes)) return scanline for y in range(self.height): yield line() def array_scanlines(self, pixels): """ Generates boxed rows (flat pixels) from flat rows (flat pixels) in an array. """ # Values per row vpr = self.width * self.planes stop = 0 for y in range(self.height): start = stop stop = start + vpr yield pixels[start:stop] def array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format. """ # # Array type.%d' % vpr if maxval > 0xff: fmt = fmt + 'H' else: fmt = fmt + 'B' for row in pixels: file.write(struct.pack(fmt, *row)) file.flush() def color_triple(color): """ Convert a command line colour value to a RGB triple of integers. FIXME: Somewhere we need support for greyscale backgrounds etc. """ if color.startswith('#') and len(color) == 4: return (int(color[1], 16), int(color[2], 16), int(color[3], 16)) if color.startswith('#') and len(color) == 7: return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)) elif color.startswith('#') and len(color) == 13: return (int(color[1:5], 16), int(color[5:9], 16), int(color[9:13], 16)) def _add_common_options(parser): """Call *parser.add_option* for each of the options that are common between this PNG--PNM conversion tool and the gen tool. """ parser.add_option("-i", "--interlace", default=False, action="store_true", help="create an interlaced PNG file (Adam7)") parser.add_option("-t", "--transparent", action="store", type="string", metavar="#RRGGBB", help="mark the specified colour as transparent") parser.add_option("-b", "--background", action="store", type="string", metavar="#RRGGBB", help="save the specified background colour") parser.add_option("-g", "--gamma", action="store", type="float", metavar="value", help="save the specified gamma value") parser.add_option("-c", "--compression", action="store", type="int", metavar="level", help="zlib compression level (0-9)") return parser def _main(argv): """ Run the PNG encoder with options from the command line. """ # Parse command line arguments from optparse import OptionParser import re version = '%prog ' + __version__ parser = OptionParser(version=version) parser.set_usage("%prog [options] [imagefile]") parser.add_option('-r', '--read-png', default=False, action='store_true', help='Read PNG, write PNM') parser.add_option("-a", "--alpha", action="store", type="string", metavar="pgmfile", help="alpha channel transparency (RGBA)") _add_common_options(parser) (options, args) = parser.parse_args(args=argv[1:]) # Convert options if options.transparent is not None: options.transparent = color_triple(options.transparent) if options.background is not None: options.background = color_triple(options.background) # Prepare input and output files if len(args) == 0: infilename = '-' infile = sys.stdin elif len(args) == 1: infilename = args[0] infile = open(infilename, 'rb') else: parser.error("more than one input file") outfile = sys.stdout if sys.platform == "win32": import msvcrt, os msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) if options.read_png: # Encode PNG to PPM png = Reader(file=infile) width,height,pixels,meta = png.asDirect() write_pnm(outfile, width, height, pixels, meta) else: # Encode PNM to PNG format, width, height, depth, maxval = \ read_pnm_header(infile, ('P5','P6','P7')) # When it comes to the variety of input formats, we do something # rather rude. Observe that L, LA, RGB, RGBA are the 4 colour # types supported by PNG and that they correspond to 1, 2, 3, 4 # channels respectively. So we use the number of channels in # the source image to determine which one we have. We do not # care about TUPLTYPE. greyscale = depth <= 2 pamalpha = depth in (2,4) supported = map(lambda x: 2**x-1, range(1,17)) try: mi = supported.index(maxval) except ValueError: raise NotImplementedError( 'your maxval (%s) not in supported list %s' % (maxval, str(supported))) bitdepth = mi+1 writer = Writer(width, height, greyscale=greyscale, bitdepth=bitdepth, interlace=options.interlace, transparent=options.transparent, background=options.background, alpha=bool(pamalpha or options.alpha), gamma=options.gamma, compression=options.compression) if options.alpha: pgmfile = open(options.alpha, 'rb') format, awidth, aheight, adepth, amaxval = \ read_pnm_header(pgmfile, 'P5') if amaxval != '255': raise NotImplementedError( 'maxval %s not supported for alpha channel' % amaxval) if (awidth, aheight) != (width, height): raise ValueError("alpha channel image size mismatch" " (%s has %sx%s but %s has %sx%s)" % (infilename, width, height, options.alpha, awidth, aheight)) writer.convert_ppm_and_pgm(infile, pgmfile, outfile) else: writer.convert_pnm(infile, outfile) if __name__ == '__main__': try: _main(sys.argv) except Error, e: print >>sys.stderr, e | https://www.programcreek.com/python/?code=appleseedhq%2Fblenderseed%2Fblenderseed-master%2Fscripts%2Fruntestsuite%2Fpng.py | CC-MAIN-2021-04 | refinedweb | 4,016 | 56.45 |
Problem: You have a catalog of items with discrete ratings (thumbs up/thumbs down, or 5-star ratings, etc.), and you want to display them in the “right” order.
Solution: In Python
''' score: [int], [int], [float] -> float Return the expected value of the rating for an item with known ratings specified by `ratings`, prior belief specified by `rating_prior`, and a utility function specified by `rating_utility`, assuming the ratings are a multinomial distribution and the prior belief is a Dirichlet distribution. ''' def score(self, ratings, rating_prior, rating_utility): ratings = [r + p for (r, p) in zip(ratings, rating_prior)] score = sum(r * u for (r, u) in zip(ratings, rating_utility)) return score / sum(ratings)
Discussion: This deceptively short solution can lead you on a long and winding path into the depths of statistics. I will do my best to give a short, clear version of the story.
As a working example I chose merely because I recently listened to a related podcast, say you’re selling mass-market romance novels—which, by all accounts, is a predictable genre. You have a list of books, each of which has been rated on a scale of 0-5 stars by some number of users. You want to display the top books first, so that time-constrained readers can experience the most titillating novels first, and newbies to the genre can get the best first time experience and be incentivized to buy more.
The setup required to arrive at the above code is the following, which I’ll phrase as a story.
Users’ feelings about a book, and subsequent votes, are independent draws from a known distribution (with unknown parameters). I will just call these distributions “discrete” distributions. So given a book and user, there is some unknown list
of probabilities (
) for each possible rating a user could give for that book.
But how do users get these probabilities? In this story, the probabilities are the output of a randomized procedure that generates distributions. That modeling assumption is called a “Dirichlet prior,” with Dirichlet meaning it generates discrete distributions, and prior meaning it encodes domain-specific information (such as the fraction of 4-star ratings for a typical romance novel).
So the story is you have a book, and that book gets a Dirichlet distribution (unknown to us), and then when a user comes along they sample from the Dirichlet distribution to get a discrete distribution, which they then draw from to choose a rating. We observe the ratings, and we need to find the book’s underlying Dirichlet. We start by assigning it some default Dirichlet (the prior) and update that Dirichlet as we observe new ratings. Some other assumptions:
- Books are indistinguishable except in the parameters of their Dirichlet distribution.
- The parameters of a book’s Dirichlet distribution don’t change over time, and inherently reflect the book’s value.
So a Dirichlet distribution is a process that produces discrete distributions. For simplicity, in this post we will say a Dirichlet distribution is parameterized by a list of six integers
, one for each possible star rating. These values represent our belief in the “typical” distribution of votes for a new book. We’ll discuss more about how to set the values later. Sampling a value (a book’s list of probabilities) from the Dirichlet distribution is not trivial, but we don’t need to do that for this program. Rather, we need to be able to interpret a fixed Dirichlet distribution, and update it given some observed votes.
The interpretation we use for a Dirichlet distribution is its expected value, which, recall, is the parameters of a discrete distribution. In particular if
, then the expected value is a discrete distribution whose probabilities are
So you can think of each integer in the specification of a Dirichlet as “ghost ratings,” sometimes called pseudocounts, and we’re saying the probability is proportional to the count.
This is great, because if we knew the true Dirichlet distribution for a book, we could compute its ranking without a second thought. The ranking would simply be the expected star rating:
def simple_score(distribution): return sum(i * p for (i, p) in enumerate(distribution))
Putting books with the highest score on top would maximize the expected happiness of a user visiting the site, provided that happiness matches the user’s voting behavior, since the simple_score is just the expected vote.
Also note that all the rating system needs to make this work is that the rating options are linearly ordered. So a thumbs up/down (heaving bosom/flaccid member?) would work, too. We don’t need to know how happy it makes them to see a 5-star vs 4-star book. However, because as we’ll see next we have to approximate the distribution, and hence have uncertainty for scores of books with only a few ratings, it helps to incorporate numerical utility values (we’ll see this at the end).
Next, to update a given Dirichlet distribution with the results of some observed ratings, we have to dig a bit deeper into Bayes rule and the formulas for sampling from a Dirichlet distribution. Rather than do that, I’ll point you to this nice writeup by Jonathan Huang, where the core of the derivation is in Section 2.3 (page 4), and remark that the rule for updating for a new observation is to just add it to the existing counts.
Theorem: Given a Dirichlet distribution with parameters
and a new observation of outcome
, the updated Dirichlet distribution has parameters
. That is, you just update the
-th entry by adding
to it.
This particular arithmetic to do the update is a mathematical consequence (derived in the link above) of the philosophical assumption that Bayes rule is how you should model your beliefs about uncertainty, coupled with the assumption that the Dirichlet process is how the users actually arrive at their votes.
The initial values
for star ratings should be picked so that they represent the average rating distribution among all prior books, since this is used as the default voting distribution for a new, unknown book. If you have more information about whether a book is likely to be popular, you can use a different prior. For example, if JK Rowling wrote a Harry Potter Romance novel that was part of the canon, you could pretty much guarantee it would be popular, and set
high compared to
. Of course, if it were actually popular you could just wait for the good ratings to stream in, so tinkering with these values on a per-book basis might not help much. On the other hand, most books by unknown authors are bad, and
should be close to zero. Selecting a prior dictates how influential ratings of new items are compared to ratings of items with many votes. The more pseudocounts you add to the prior, the less new votes count.
This gets us to the following code for star ratings.
def score(self, ratings, rating_prior): ratings = [r + p for (r, p) in zip(ratings, rating_prior)] score = sum(i * u for (i, u) in enumerate(ratings)) return score / sum(ratings)
The only thing missing from the solution at the beginning is the utilities. The utilities are useful for two reasons. First, because books with few ratings encode a lot of uncertainty, having an idea about how extreme a feeling is implied by a specific rating allows one to give better rankings of new books.
Second, for many services, such as taxi rides on Lyft, the default star rating tends to be a 5-star, and 4-star or lower mean something went wrong. For books, 3-4 stars is a default while 5-star means you were very happy.
The utilities parameter allows you to weight rating outcomes appropriately. So if you are in a Lyft-like scenario, you might specify utilities like [-10, -5, -3, -2, 1] to denote that a 4-star rating has the same negative impact as two 5-star ratings would positively contribute. On the other hand, for books the gap between 4-star and 5-star is much less than the gap between 3-star and 4-star. The utilities simply allow you to calibrate how the votes should be valued in comparison to each other, instead of using their literal star counts.
So, basically, for a repartition $(n_0, \dots, n_5)$ of rates, with $n = n_0 + \dots n_5$, we just say that the new user will give it a score of $(0 * n_0 + \dots + 5 * n_5) / n$? I’m not really sure the Dirichlet distributions add any hindsight to this. Did I miss something?
I think this post is about explaining that the Dirichlet distribution is a conjugate prior, that is the prior and the posterior distribution are both Dirichlet, and also that when the parameters are interpreted as counts of occurrences then the Bayes’ update rule is simple recount. Perhaps giving the example of the beta distribution would be more clear, I think the first step is to introduce the reader into Bayesian statistic, in which parameters are not numbers but random variables. I think that conjugate priors like beta an Dirichlet are a very good way to introduce the readers into the bayesian point of view, but once the reader consider parameters as counting number of ocurrences, the applications seems trivial. Perhaps there is more content that I didn’t understand.
That’s because it *is* trivial.
The point of this post is to cleanly separate the algorithm, mathematical model, and philosophy in the context of a concrete example. Spouting “the algorithm works because the Dirichlet is a conjugate prior” is the quickest way to blur the lines. And my personal opinion is that (albeit in the interest of generality) the clear, trivial ideas in statistics are obfuscated by the jargon.
In other words, this post is not for you, and I’m ignoring your advice on purpose.
I learned about conjugate prior reading the free book Think Stats, is a book about statistics for programming and it use Python. Later I read more about conjugate prior, for example a post in John Cook page. When I read your post I looked up in the wikipedia the Dirichlet distribution and I discovered it was a generalization of the beta distribution and also a good and simple example of conjugate prior. That is my humble voyage to learn that stuff. Maybe this post is not for me, but I hope to follow enjoying your posts ).
Sorry, the book I was referring to is Think Bayes,
Thanks for the recommendation!
From a pedagogical, wouldn’t it be nice to work out the beta-binomial model as a special case (also beta(0.5, 0.5) is the simplest jeffrey’s prior)?
Btw, your blog is fantastic! I know little to nothing about algorithms and your expositions are very helpful. | https://jeremykun.com/2017/03/13/bayesian-ranking-for-rated-items/?replytocom=55957 | CC-MAIN-2021-21 | refinedweb | 1,814 | 57.71 |
Actionable insights to resolve Python performance bottlenecks and errors. See the full picture of any Python exception so you can diagnose, fix, and optimize performance in the Python debugging process.
Grab the Sentry Python SDK:
pip install --upgrade sentry-sdk
Configure your DSN:
import sentry_sdk sentry_sdk.init( "https://<key>@sentry.io/<project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )
That’s it. There’s no step three. Don’t believe us? Check out our Documentation.See all platforms
Within minutes after installing Sentry, software teams are able to trace Python performance issues back to a poor performing API call as well as surface all related code errors. Engineering Managers and Developers now have a single tool to optimize the performance of their code and deliver fast customer experiences.
See local variables in the stack for prod errors, just like in your dev environment. Introspect more deeply into the runtime and jump into the frame to get additional data for any local variable. Filter and group Python exceptions intuitively to eliminate noise.
Expose the important events that led to each Python exception: SQL queries, debug logs, network requests, past errors. Improve debugging workflow with a full view of releases so you can mark errors as resolved and prioritize live issues.
”The time to resolve errors went from days to minutes.”
Aggregate errors by details like HTTP request, hostname, and app version to see what’s new, a priority, or a trend.
Assign custom tags to reproduce the error environment specific to your application, business, and users.
Answer the most important questions: In which app release did thePython bug occur? Was it the kraken?. | https://sentry.io/for/python | CC-MAIN-2021-21 | refinedweb | 288 | 58.79 |
When adding new functionality to the manager you'll want to add items for your new page in the menu. The menu class is a
static singleton object that can be changed or updated from anywhere, at any time. However, since the menu is the same for all users, changing it in runtime for the state of a single user will not work.
If you are building a custom module, our recommendation is that you add your menu items in the
Init() method of your module. This will ensure that it will only be execute once in the application lifecycle.
If you are just adding menu items in your application we recommend that you do it in your
Startup.cs after
Piranha.App.Init() has been called.
Please note that empty menu sections will not be rendered. The same also applies for menu sections only containing items that the current user don't have access to.
The following code will add a new section after the default Settings section.
using Piranha.Manager; Menu.Items.Insert(2, new MenuItem { InternalId = "MyModule", Name = "My Module", Css = "fas fa-fish" });
The following code will add a menu item under our new group we create in the previous step.
using Piranha.Manager; Menu.Items["MyModule"].Items.Add(new MenuItem { InternalId = "MyCustomItem", Name = "My Custom Item", Route = "~/manager/mycustomitem", Css = "fas fa-brain", Policy = "MyCustomPolicy" });
The
MenuItem class has the following properties that you should set when adding a new item to the menu.
menuItem.InternalId = "MyCustomItem";
As the menu is ordered into sections, at least the topmost level of items should have an Internal Id so that it's easy to access them when adding child items.
menuItem.Name = "My Custom Item";
This is the display name that will printed out in the menu when it is folded out.
menuItem.Route = "~/manager/mycustomitem";
The route that the generated link should point to. As the topmost levels of items are only used as section, this property is not needed for these items.
menuItem.Css = "fas fa-fish";
The css class that will be added to the icon for the menu item. The manager interface uses the font icons from Font Awesome, so any of the icons there will work.
menuItem.Policy = "MyCustomPolicy";
If you want to restrict the menu item depending on the claims of the currently logged in user. Please note that each item can only have one policy, a policy can however be a set of several claims. | https://piranhacms.org/docs/manager-extensions/menu | CC-MAIN-2020-40 | refinedweb | 415 | 61.16 |
Complete freedom in creating the user experience can be a double-edged sword, but a little bit of artistry can transform an application's usability.
Howard Dierking
MSDN Magazine August 2008
Read more!
This month we explain how pseudo variables and format specifiers provide a wealth of information for use in debugging.
Kenny Kerr.
The System.Windows.Shapes namespace is Charles Petzold's namespace of choice for rendering two-dimensional vector graphics in WPF. Here he explains why.
Charles Petzold
MSDN Magazine March 2008
There’s a strong similarity between Web-based Silverlight 2 applications and desktop WPF applications. Enabling easy code reuse between the two is Dino’s focus here.
Dino Esposito
MSDN Magazine October 2008
This month Dino looks at AJAX control extenders again, adding more advanced features including masked editing and autocompletion.
MSDN Magazine February 2008
This month Dino builds a service layer that authenticates users of Silverlight 2 and ASP.NET AJAX services to prevent illegal access to sensitive back-end services.
MSDN Magazine September 2008
AJAX Extenders extend the behavior and features of ordinary Web controls so you can reduce postbacks and control input even better than with AJAX alone.
MSDN Magazine January 2008
This month Dino tackles the problem of large download size for Silverlight applications, explaining when to use streaming, when to divide the download, and other techniques for better performance over the wire.
MSDN Magazine January 2009ason Clark
MSDN Magazine July 2003
WPF is one of the most important new technologies in the .NET Framework 3.0. This month John Papa introduces its data binding capabilities.
John Papa
MSDN Magazine December 2007
The original goal of the registryâ"the systemwide data repositoryâ"was to replace INI files that were used in the early days of Windows to store user and application configuration data. There were several good reasons to replace INI files. First of all, they are text-based and easily edited in a text editor. As such, they are subject to unauthorized access and easy tampering. Additionally, information that needed to be stored in a structured, hierarchical way was saved as flat text in an INI file. XML would have been a good way to combine the usability of INI files with a rather complex data description, but XML had not been developed five years ago. Third, INI files force a decentralization of information. Without clear and fixed rules for organizing documents and folders, there is a risk that valuable information will get lost, duplicated, corrupted, or simply become more difficult to retrieve. Furthermore, INI files impose size restrictions; you cannot store more than 64KB of data in a single entry. This limitation is not due to the INI file itself, but to the API functions that read and return the values from the file. Unless you want to write your own version of functions like GetPrivateProfileString, bear in mind that these functions can't address buffers larger than 64KB. In contrast to all this, the registry is subject to security policies and can be manipulated only through special tools (like the Registry Editor) and API functions. Such a programming interface shields developers from having to change their code should Microsoft modify the internal registry structure.
Figure 1 Registry Size Information
Size restrictions are not a problem in the Windows registry, even though its size isn't unlimited. Figure 1 shows the system dialog that allows you to see the current size of the registry and change the maximum amount of space it can use. This dialog box appears when you right-click on My Computer, select Properties, select the Advanced Tab, open the Performance Options dialog, and then click the Change button to change the current settings. This option is only available in Windows NT® and Windows 2000, and only if you log in with administrator privileges. I'll say more about registry size later in this article.
Upon installation, the operating system also creates a system.1st file in the root directory of the C drive. This file is a snapshot of the registry taken at the moment that Windows is correctly installed, but before you start using the system. You can rely on that file to be an early backup copy of the registry. In case of serious registry damage, the existing system.dat file can be replaced with system.1st, and all applications can be reinstalled. The Knowledge Base article Q131431 describes troubleshooting the registry in more detail. Actually, system.1st is not necessary for the proper operation of Windows, so you could delete it. However, this file should be saved as a backup of the registry. In Windows 2000, all these files disappeared, but the programming interface for the registry is still the same.
Figure 2 Registry Backup in Windows 2000
The procedure doesn't even attempt to copy the current registry to a floppyâ"an impossible operation since the average size of the registry on many machines is close to 20MB. Instead, the backup procedure makes a copy of the registry files in the system repair folder: c:\winnt\repair. All the information stored in this folder is necessary to repair a damaged Windows 2000 installation and shouldn't be deleted or modified. In particular, the latest registry backup is saved in the RegBack subfolder. To restore correct registry information, you should run the Restore Wizard from the Backup utility and follow its instructions. Use the previously created ERD if you cannot start and log on to Windows. Through the Backup utility, you can also schedule the registry backup at predetermined intervals. For the Windows 2000 Backup tool, the system state includes at least the registry, the COM+ Class Registration database, and the system boot files. It also includes the Certificate Services database if the server is operating as a certificate server. If it is acting as a domain controller, then the directory services database is automatically part of the backup. For more information about the system state backup and restore under Windows NT 4.0 and earlier, refer to the Knowledge Base articles Q129037 and Q126464. The standard backup procedures copy all the registry files. To back up small portions of the registry, such as a node or a subtree, you can use the Export Registry File menu command of the Registry Editor (regedit). It allows you to select the branch to save and creates a text file with a REG extension. A REG file can also be used to enter registry settings later. The Import/Export Registry Editor feature is another option for backing up small branches of the registry before you test potentially harmful code.
Figure 3 Regedit
The programmer's window into the system registry, the Registry Editor, is shown in Figure 3. It is a collection of root nodes containing different types of information. Each node expands into a number of subnodes or keys. All nodes can have any number of named entries and exactly one unnamed entryâ"often referred to as the default entry. An entry is a name-value pair. Each entry can have a type chosen from a collection of possible types. The most important types are those listed in Figure 4. Notice that a REG_MULTI_SZ entry can be created only through the API functions, while a REG_EXPAND_SZ entry can also be created through the Windows Script Host object model. Only binary, text, and numeric entries can be created through visual tools such as the Registry Editor. You access a specific key or entry through a path name that identifies a logical path from one root node to the actual leaf. Both the Registry Editor and the Win32® Registry API provide a sort of virtualization of the registry content. The root nodes, keys, and entries you see represented don't correspond exactly to the actual files that make up the Windows 2000 registry. The structure of these component files is significantly different from the tree you usually see in visual editors and API functions. For example, neither the HKEY_CLASSES_ROOT (HKCR) nor the HKEY_CURRENT_USER (HKCU) nodes have a physical counterpart in any of the registry files. The information they show through the API virtualization is mirrored from a subtree of the HKEY_LOCAL_MACHINE (HKLM) and the HKEY_USERS (HKU) node respectively. In other words, HKCR and HKCU are aliases for HKEY_LOCAL_MACHINE\SOFTWARE\Classes and HKEY_USERS\.default. This also explains why in Windows 9x there are only two files: system.dat and user.dat. Their content corresponds to HKLM and HKU, which covers all the information accessible by the API and the Registry Editor. The virtual view provided by the Win32 API makes it possible for developers to work with different registries using the same tools even though the Windows 9x and Windows 2000 registries are structurally different.
Figure 5 File-type Variety
All the files that form the Windows 2000 registry are stored in the \system32\config directory. If you look at the actual contents of the folder (see Figure 5), you can see several files with different extensions. Files without extensions contain the actual data for a root node. The content of the various registry root nodes are also known as hives (see Figure 6). Files with a .sav extension contain a copy of the specific registry node data that exists at the end of the text-mode setup stage. During the Windows 2000 startup you can distinguish two distinct stages: the text-mode stage and the graphics stage. When the system is about to leave the text-mode procedure, it saves the hives to the respective .sav files. If problems occur during the next graphic-mode step, the system restarts, but it doesn't repeat the whole setup procedure. It skips the text-mode step and reads the content of the registry hives from the respective .sav files. Files with the .log extension contain a transaction log of all the changes to the keys and value entries in the hive. Despite the extension that might make you think this is a text file, the content of the .log files is binary. The registry folder also contains one file with an extension of .alt. This .alt file is a backup copy of the most critical data in the HKLM hive. Windows 2000 utilizes only one ALT file, system.alt, which is a safety backup copy of the HKLM\System node. Figure 7 shows how the hives that are visible from the Registry Editor map to physical files.
In the registry folder (\system32\config) you won't find a file that appears to contain user information. The content of HKCU and the content of the hives for other users are stored in different folders. In particular, you'll find files called ntuser.dat and ntuser.log.dat in user-specific folders under C:\Documents and Settings. For example, the HKCU settings for the Administrator can be found under C:\Documents and Settings\Administrator.
HKLM
\System
\CurrentControlSet
\Control
\Session Manager
\Memory Management
HKLM
\System
\CurrentControlSet
\Control
The Knowledge Base articles Q94993 and Q124594 describe in detail how to get and set the registry size limit programmatically. Don't forget, however, that you need to restart the machine for the changes to take effect.
C:\Documents and Settings
\User Name
\Application Data
\Company Name
\Product Name
Registry data is grouped into root nodes roughly following the schema depicted in Figure 8. In most cases, the same information can be set and read through API functions without directly accessing the registry. However, this is not necessarily true of all the information you might want to access. Knowing where to search for useful information can save you time and allow you to better integrate with the rest of the system. All the available information about registered file types and system objects is stored in the HKCR hive. This is also the hive to explore if you need to verify whether a certain COM object exists and is correctly installed. HKCR contains a node with all CLSIDs and ProgIDs. In the remainder of the article, I'll examine a few stumbling blocks and provide tips to accomplish tasks that would be impossible without modifying the registry. In doing so, I'll discuss little-known keys and entries. I'll talk about access to file classes, current settings for system objects, infotips, and regedit's lastkey behavior. Let's start with the * key. As I just mentioned, HKCR contains information about file types. You can refer to the article "Fusing Your App to the System Through the Windows 95 Shell" by Jeffrey Richter in the April 1996 issue of MSJ for basic information on file types and their registration. This has not changed since Windows 95. Due to limitations inherent in the file system architecture, the only way to group files into classes is by the file extension. All the files with a given extension belong to a certain class, regardless of their actual content. A Windows file type is identified by a HKCR node whose name matches the file's extension. For example, HKCR\.bmp identifies the node for bitmap files. Not all the class information for bitmaps is stored under the .bmp node, however. For a more flexible programming interface, an extension node points to another node that gathers all the information about the file class. The name of the file class for a certain file extension is stored in the unnamed default entry for the file type. For example, the file class for bitmap files is usually Paint.Picture. This is where you should search for information about bitmap images such as the icon, description, context menu, and shell extensions. The decoupling of extension and class allows different programs to register as the default handler for those files by changing a single entry and without overriding other programs' settings. Along with file classes and COM objects, the HKCR hive also contains the current settings for a number of system objects such as folders, directories, drives, and printers. You can update the standard configuration of any of these objects individually, but you can also apply the same changes to groups of objects. The * key is a pseudo system object that groups together all files of all possible classes. The Folder key includes both folders and file system directories. The Directory key refers only to file system directories. Windows 2000 introduces a new system object called AllFileSystemObjects, under which you can enter configuration information for both files and directories. You've probably noticed that infotips abound in the Windows 2000 Explorer, and not only for those file classes for which an infotip shell extension has been registered. Explorer, in fact, provides standard infotips for any file that appears in the shell view. The text displayed doesn't come from a systemwide infotip extension; it's read from various locations within the registry. Figure 9 shows the standard infotip for a VBScript file (.vbs). For more details and source code about infotip shell extensions, please refer to my article "Enhance Your User's Experience with New Infotip and Icon Overlay Shell Extensions" in the March 2000 issue.
Figure 9 Standard Infotip for VBScript Files
Once the Windows 2000 shell detects the file type, it attempts to locate and load an infotip shell extension for that class. If it fails, it then searches for an Infotip entry under the file class node. For example, the default file class for ASP files is aspfile. An Infotip entry under HKCR\aspfile (see Figure 10) results in the behavior shown in Figure 11. If it fails again, the standard infotip is used.
Figure 10 ASP Infotip Settings
Figure 11 Simple Infotip
Interestingly, the standard infotip is customizable. It is defined by the Infotip entry of the HKCR\* node. Its text looks like this:
prop:Type;Author;Title;Subject;Comment;Size
Figure 12 Extended Infotip
On an NTFS volume, extra fields such as Author and Subject are stored through multiple data streams for any type of file that doesn't contain a SummaryInformation block in its own body. More information on this can be found in my article, "A Programmer's Perspective of NTFS 2000: Streams and Hard Links" in the March/April 2000 issue of MSDN® News. The structure of the HKCR\* Infotip entry is customizable and can be adapted to your own needs. In particular, you can alter the order in which the information is rendered and you can add new fields as well. For example,
prop:Size;Type;Modified;Author;Attributes
Figure 13 New Custom Infotip
If you use the Registry Editor on a daily basis there's another feature that you might find annoying over time: the automatic selection of the last accessed key. The name of the last key is stored in the LastKey entry under the Regedit node. Deleting this key is of no help since the key is overwritten or created upon exit. A partial solution is using regedt32.exe to change the permissions on the Regedit key. In particular, you can deny write access to the key to any users or groups you want, as shown in Figure 14. Make sure you apply the restriction to the Regedit key only, not to all of its subkeys. If you restrict the subkeys, you'll be unable to add and delete items to and from the favorites list.
Figure 14 Regedit Permissions
At this point, you've successfully stopped the Registry Editor from selecting the last accessed key, but you also introduced a couple of predictable side effects. Since write permissions to the registry can be granted or denied only at the key level, there's no way to lock individual registry entries. Blocking the Regedit node also prevents the application from using the other two entries defined at the same level of LastKey: FindFlags and, more importantly, View. FindFlags maintains the state of the Find dialog, whereas View remembers the size and position of the program's window. This information will become unavailable once you deny writing permissions to the Regedit node. Henceforth, the program can't reopen where you closed it, nor can it remember the last find settings. You'll have to decide if these settings are important for you to maintain.
In this section I'll explain how to selectively set the visibility of file extensions (show or hide), set default behavior for double-clicking, control the Open With menu behavior, and manage connected HTML files, which I'll define later. As you know, there are folder properties to hide or show the extension for known file types. There might be circumstances, however, in which you don't want the same setting to apply to all file classes. For example, suppose you want to hide the extension for the majority of files, but not for a couple of classes, say, .xyz and .abc. By defining an AlwaysShowExt entry in the class node, you force the shell to override the current setting and always show the extension for those files. There's no need to assign a value to the entry, but you must create it as type REG_SZ. Conversely, if you always want to show the file extension except in a few instances, create a NeverShowExt entry in the appropriate class node. For a practical demonstration of this feature, consider shortcut files. By design, Explorer never shows the .lnk extension regardless of the shell-wide setting for known (registered) file types. If you look in the registry under HKCR\lnkfile, you'll find a NeverShowExt REG_SZ entry. In Figure 15 you can see that if you remove the entry, the .lnk extension is displayed on the Start menu. Note that for NeverShowExt/AlwaysShowExt changes to take effect, you need to reboot or at least log off.
Figure 15 Start Menu
Another way to use registry entries to set behavior is to define the action of a double mouse click. The Windows 2000 Application Specification documentation recommends that you always associate an action for double clicking on a file. This usually means defining an Open command for the file. If you don't want users to open files of a given type, you should designate those files as NoOpen. When someone attempts to open a NoOpen file, a message box like Figure 16 will appear.
Figure 16 NoOpen Message
To enable this feature, locate the class file in the registry and add a NoOpen REG_SZ entry with the custom text you want to be displayed in the caution message box. The NoOpen clause will be in effect only if there are no other shell commands defined for the file class. Furthermore, the NoOpen entry is ignored as soon as you define the first shell command. Another interesting feature in Windows 2000 is the Open With popup menu that allows you to choose which program should handle a certain document type. Once again, you can programmatically control those lists through the registry. The subtree is:
HKEY_CURRENT_USER
\Software
\Microsoft
\Windows
\CurrentVersion
\Explorer
\FileExts
Figure 18 Open With Menu
To add an item to an existing list, you should determine the first letter available, then modify the MRUList entry. Notice that deleting registry nodes is different under Windows 9x, Windows NT, and Windows 2000. Deletion is automatically recursive under Windows 9x and deletes the entire subtree. Under Windows 2000, however, you can delete a registry node only if it doesn't contain child nodes. Entries don't affect node deletion. You can also change the behavior of connected files (which I'll define in a minute) through the registry. You've probably already run into a rather intriguing feature using HTML files in Windows 2000. Open an HTML page with Microsoft Internet Explorer 5.0 and then save it locally using the Save As menu command. Internet Explorer 5.0 saves only the main HTML page in the folder you specified, and creates a subdirectory where it stores all other files such as images, scripts, Cascading Style Sheets, and so on. It also automatically provides for redirecting internal tags to the newly created subfolder. The child folder has the name of the default page followed by _files. Interestingly, if you delete the default page or the subfolder, both disappear from the disk. The HTML page and its child folder are connected; the Windows 2000 shell is aware of this and acts accordingly. This feature is enabled only for HTML files, and only if you make your deletion through the shell or programmatically through the SHFileOperation function. It doesn't work if you delete either the page or the folder via the DeleteFile API function or the MS-DOS DEL command. This HTML auto-delete feature is controlled by a new flag supported by the Windows 2000 version of SHFileOperation. While calling the function, you can now employ the FOF_NO_CONNECTED_ELEMENTS flag. The effect is that the function doesn't move or delete connected files as an individual file; it only moves or deletes the specified files. Windows 2000 designates HTML pages as connected files since they often have a number of associated files that you need to copy, move, or delete as a whole to avoid breaking links. Such a feature is enabled by default and can be disabled as needed by setting the FOF_NO_CONNECTED_ELEMENTS flag before calling SHFileOperation. If you want to turn it off altogether, then go to
HKEY_CURRENT_USER
\Software
\Microsoft
\Windows
\CurrentVersion
\Explorer
You can use the registry to customize application behavior. For example, through the registry you can get Windows 2000 and Windows 98 to use the same Outlook® Express e-mail folders and rename Favorites links. In this section, I'll show you how. The registry is the recommended place to store configuration data for both the system and applications. In general, an application should provide users with a public interface (such as an MMC snap-in or a Customize dialog box) to set all possible preferences. This approach often turns out to be a bit impractical, however, because of the large number of settings, time constraints, or because developers don't want certain parameters to be easily configured by users. Nevertheless, understanding an application's registry data can help you implement features that would otherwise be impossible to implement. I'll provide two examples of how tweaking the registry can help to enhance the user's experience of Windows 2000. One of my clients had multi-boot computers and wanted to use the same e-mail archives from both Windows 2000 and Windows 98. By default, on a multi-boot machine you'll have two completely separate installations of Outlook Express using separate folders. Outlook Express utilizes the registry to persist all sorts of parameters, including the store root directoryâ"the path of the folder where all messages are kept. To solve both problems, I had to figure out the physical path for Outlook Express archives and devise a way to redirect it. On my machine Outlook Express stored lots of configuration information under:
HKEY_CURRENT_USER
\Identities
\{ACCC8CB2-2152-4378-A1A2-9F0C11D7CF76}
\Software
\Microsoft
\Outlook Express
\5.0
HKEY_CURRENT_USER
\Software
\Microsoft
\Windows
\CurrentVersion
\Applets
\Regedit
\Favorites
Now I can go there with a click and rename items through the Registry Editor's user interface.
OPENFILENAME ofn;
ofn.FlagsEx = OFN_EX_NOPLACESBAR;
HKEY_CURRENT_USER
\Software
\Microsoft
\Windows
\CurrentVersion
\Policies
\ComDlg32
Figure 19 Custom Places Bar
If you want to specify an absolute file system path, create a REG_SZ or REG_EXPAND_SZ entry. If you plan to use a CSIDL, then a REG_DWORD entry is mandatory. CSIDL values are defined in shlobj.h. Make sure you get the one that ships with the latest Platform SDK if you want the new IDs specific to Windows 2000. The PlacesBar key does not exist by default. In this case GetOpenFileName displays the usual five folders. Figure 19 shows a new places bar that displays the folders I have chosen (Articles, WINNT, My Documents, Favorites, My Computer).
IQueryAssociations *pQA=NULL;
AssocCreate(CLSID_QueryAssociations,
IID_IQueryAssociations, &pQA);
pQA->Init(NULL, _T(".txt"), NULL, NULL);
To improve setup programs and, more importantly, their interaction with the rest of the system, Microsoft introduced a new API called RegOverridePredefKey. Its purpose is to temporarily remap one of the registry's root nodes to a user-defined subtree. In this way, a setup program can checkâ"and possibly denyâ"all the registry settings that an installing component might want to create. Remapping HKCU or HKLM to a temporary key doesn't change anything for the component; it doesn't even realize it is writing to a different key. For all purposes, the remapped key evaluates to the original one. Once the component finishes updating the registry, the setup program can controlâ"and possibly fixâ"the entries before restoring the original root node and copying the entries from the temporary key to the right place. While the MSDN documentation emphasizes its use mostly within installation programs, I think that RegOverridePredefKey could be just as effectively used to accomplish less noble, but necessary tasks such as subclassing, discovery of program internals, and customization of existing programsâ"all the dirty tasks that your users often ask for, but which aren't well documented. I'll explain how this works. The prototype of the function is rather straightforward:
LONG RegOverridePredefKey(
HKEY hKey,
HKEY hNewHKey
);
RegOpenKeyEx(HKEY_CURRENT_USER, "Dino", 0, KEY_ALL_ACCESS, &hkMyCU);
RegOverridePredefKey(HKEY_CURRENT_USER, hkMyCU);
RegOverridePredefKey(HKEY_CURRENT_USER, NULL);
RegOpenKeyEx(HKEY_CURRENT_USER,
"YourTempKey", 0, KEY_ALL_ACCESS, &hkTemp);
RegOverridePredefKey(HKEY_CURRENT_USER,
hkTemp);
\Software
\Microsoft
\Windows
\CurrentVersion
\Applets
\Regedit
I described this example only for educational purposes and to help you understand the overall role of this official documented API function. Interprocess subclassing and hooking are not a recommended practice in Win32 and should be employed only when strictly necessary. For more information on this topic, refer to the book Advanced Windows by Jeffrey Richter (Microsoft Press, 1997).
Figure 20 Creating XML and HTML Files
In Figure 20 you can see a program that helps create new HTML and XML files. Let's see how to register this program to handle the creation of new documents. Suppose you want it to generate XML files. Go to HKCR\.xml\ShellNew, create a REG_SZ Command entry, and make it point to the executable's name. Use the %1 symbol so it receives the suggested name for the new file on the command line.
From the November 2000 issue of MSDN Magazine. | http://msdn.microsoft.com/en-us/magazine/bb985037.aspx | crawl-002 | refinedweb | 4,710 | 53.61 |
?
The?
How can I flatten just a specific sublist of each list in a list of lists?
So if I had this data
[ [']]]
How can I make it be
[ [']]
Been looking around but most solutions just entirely flatten everything. This was popular on SO but yeah it flattens everything I want to be more selective
def flatten(lst):
for elem in lst:
if type(elem) in (tuple, list):
for i in flatten(elem):
yield i
else:
yield elem
What I am thinking is that if for each list the sublist should be at index 1, so
[0][1]
[1][1]
[2][1]
for item in list:
item[1] - somehow flatten.
Any Idea or pointer?
Forgot Your Password?
2018 © Queryhome | https://www.queryhome.com/tech/68677/python-how-do-i-convert-between-tuples-and-lists | CC-MAIN-2021-04 | refinedweb | 119 | 74.12 |
Python is free, it is open source, and it has a huge community.
Python is one of the most popular and loved programming languages in the world!
Many blogs come out every year listing the most popular programming languages. Python has been among the top choices for at least 5 years now. For example: The 7 Most In-Demand Programming Languages of 2018, by CodingDojo; or the post The Most In-Demand Programming Languages of 2018, on Third Republic.
Python can be used for many things: managing databases, creating graphical user interfaces, making websites, and much more… including science. Because of the many uses, the world of Python includes many, many Libraries (you load the parts that you need, when you need them).
In science, the two libraries that are king and queen of the world are: NumPy, and Matplotlib.
NumPy is for working with data in the form of arrays (vectors, matrices). It has a myriad built-in functions or methods that work on arrays directly. To load the library into your current session of interactive Python, into a saved Python script, or into a Jupyter notebook, you use:
import numpy
Tips:
[1.0, 0.5, 2.5]
[[ 1.0, 0.5, 2.5], [ 0.5, 1.1, 2.0]]
:means "all elements in this dimension"
numpyis loaded, its built-in functions are called like this:
numpy.function(arg)(where
argis the function argument: arrays to operats on, and parameters)
Try it!
import numpy
# By the way: comments in code cells start with a hash. # here are two arrays, saved as variables x and y: x = numpy.array([1.0, 0.5, 2.5]) y = numpy.array([[ 1.0, 0.5, 2.5], [ 0.5, 1.1, 2.0]])
# The print function works on arrays: print(x)
[ 1. 0.5 2.5]
print(y)
[[ 1. 0.5 2.5] [ 0.5 1.1 2. ]]
numpy.shape(y)
(2, 3)
numpy.shape(x)
(3,)
Let's review what happened there. We first loaded
numpy, giving us the full power to use arrays. We created two arrays:
x and
y… then we print
x and we print
y. They look nice.
Numpy has a built-in function to find out the "shape" of an array, which means: how many elements does this array have in each dimension? We find that
y is a two-by-three array (it has two dimensions).
What is the first element of
x? We can use square brackets and the zero-index to find out:
x[0]
1.0
Exercise: Now, try it yourself. What is the first element of
y?
Right. The first element of
y is a 3-wide array of numbers. If we want to access the first element of this now, we use:
y[0][0]
1.0
Exercise: Try picking out different elements of the array
y…
Matplotlib is for making all kinds of plots. To get an idea of the great variety of plots possibe, have a look at the online Gallery. You can see that Matplotlib itself is a pretty big library. We can load a portion of the library (called a module) that has the basic plotting funtions with:
from matplotlib import pyplot
Once the
pyplot module is loaded, its built-in functions are called like this:
pyplot.function(arg) (where arg is the function argument).
Did you know that the size of households—that is, the number of people living in each household—has been steadily decreasing in the US and many other countries? This has perhaps surprising consequences. Even if population growth slows down, or stops altogether, the number of households keeps increasing at a fast rate.
More households means more $CO_2$ emissions! This is bad for the planet.
#Load the data from local disk year, av_size = numpy.loadtxt(fname='data/statistic_id183648.csv', delimiter=',', skiprows=1, unpack=True)
print(year)
[ 2016. 2015. 2014. 2013. 2012. 2011. 2010. 2009. 2008. 2007. 2006. 2005. 2004. 2003. 2002. 2001. 2000. 1999. 1998. 1997. 1996. 1995. 1994. 1993. 1992. 1991. 1990. 1989. 1988. 1987. 1986. 1985. 1984. 1983. 1982. 1981. 1980. 1979. 1978. 1977. 1976. 1975. 1974. 1973. 1972. 1971. 1970. 1960.]
Exercise: Now print the variable
av_size, correspondig to the average size of households (in numbers of people) for each year:
Great! The next thing we want to do is make a plot of the changing size of households over the years. To do that, we need to load the
Matplotlib module called
pyplot:
from matplotlib import pyplot %matplotlib inline
pyplot.plot(year, av_size)
[<matplotlib.lines.Line2D at 0x10ff57978>]
But what if we'd like to get a title on this plot, or add labels to the axes? (We should always have labelled axes!). Also, we notice a long jump from the year 1960 to 1970: let's add markers to the plot and change the line style to a dotted line.
pyplot.plot(year, av_size, linestyle=':', marker='o') pyplot.title("Household size in the US, 1960–2016 \n", fontsize=16) pyplot.ylabel("Average number of people per household")
<matplotlib.text.Text at 0x110238fd0>
Exercise: In the same cell above, now add a label on the x-axis, using the
pyplot.xlabel() function, and re-execute it.
(c) 2017 Lorena A. Barba, Natalia Clementi. Free to use under the Creative Commons Attribution CC-BY 4.0 License. Written for the tutorial "Data Science for a Better World", at the GW _Caminos al Futuro_ Summer program. | http://nbviewer.jupyter.org/github/barbagroup/Caminos/blob/master/2--Python_for_Science.ipynb | CC-MAIN-2018-51 | refinedweb | 906 | 74.29 |
59721/unable-execute-exported-exported-eclipse-selenium-webdriver
package devops;
//import org.openqa.selenium.By;
//import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class htmlunitdriver {
public static void main(String[] args) {
HtmlUnitDriver driver = new HtmlUnitDriver(true);
driver.get("");
//WebElement linkByText = driver.findElement(By.linkText("About Us"));
// linkByText.click();
if(driver.getPageSource().contains("ijaz"))
System.out.println("Text is present in the page");
else
System.err.println("Text is not present in the page");
driver.quit();
}
This code executes immaculately within eclipse. But when I tried to execute from the Linux terminal it throws errors. The error is as follows
Hi Ijaz
Looks like when you are executing on the local machine, you have included the chrome driver. While executing it on the Linux terminal which does not have a GUI, the driver fails.
In this case, you will have to include the HTML driver instead of the chrome driver and package it the right way. It will run for sure . i have tried it on my project and it has worked.
Follow the steps mentioned in the link and you should be able to achieve it very easily
Regards,
RRR
PS: If this post solved your query or was useful in anyway, please upvote or mark it as answer.
Hi@Ankit,
According to my knowledge of a pipeline ...READ MORE
You can run curl within the ...READ MORE
For your unable to find the TargetArguments ...READ MORE
Try the following script:
Do the second time ...READ MORE
This happens because your docker containers are ...READ MORE
This is simple, just follow the below ...READ MORE
All you need to do is mount ...READ MORE
Two ways to expose a service from ...READ MORE
Try this:
docker update --cpu-shares 5120 -m 3000M ...READ MORE
Here are the explanations for all the ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/59721/unable-execute-exported-exported-eclipse-selenium-webdriver | CC-MAIN-2021-10 | refinedweb | 314 | 61.12 |
Updating a Title To update a particular title, call DBAdapter's updateTitle() method by passing the ID of the title you want to update as well as the values of the new fields (Listing 6).
A message is displayed to indicate if the update is successful. At the same time, you retrieve the title that you have just updated to verify that the update is indeed correct.
To delete a title, use the deleteTitle()method in the DBAdapter class by passing the ID of the title you want to delete:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
//---delete a title---
db.open();
if (db.deleteTitle(1))
Toast.makeText(this, "Delete successful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Delete failed.",
Toast.LENGTH_LONG).show();
db.close();
}
A message is displayed to indicate if the deletion is successful.
To upgrade the database, change the DATABASE_VERSION constant in the DBAdapter class to a value higher than the previous one. For example, if its previous value was 1, change it to 2:
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_ISBN = "isbn";
public static final String KEY_TITLE = "title";
public static final String KEY_PUBLISHER = "publisher";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "books";
private static final String DATABASE_TABLE = "titles";
//---change this to a higher value---
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table titles (_id integer primary key autoincrement, "
+ "isbn text not null, title text not null, "
+ "publisher text not null);";
When you run the application one more time, you will see the message in Eclipse's LogCat window (see Figure 5) indicating that the database has been upgraded.
Using the DBAdapter class pattern defined in this article, you can easily access database records for your own Android applications. One important thing to note is that all SQLite databases created in Android are visible only to the application that created it. If you need to share common data, you need to use a content provider, a topic that will be covered in a future article.
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
Your name/nickname
Your email
WebSite
Subject
(Maximum characters: 1200). You have 1200 characters left. | http://www.devx.com/wireless/Article/40842/0/page/3 | CC-MAIN-2014-10 | refinedweb | 385 | 52.09 |
This is the second release with the new Java based graphical user interface (GUI) server for newLISP. Since newLISP-GS appeared for the first time in release 9.2 new functions have been added, many bugs where fixed, and the newLISP-GS based multi tab editor has much improved behavior when launching applications. The monitor area at the bottom of the editor now works as an interactive newLISP shell.
The new way of doing Graphics and GUIs in newLISP using the Java based newLISP-GS module has been well received by the community. newLISP can also still be used with GTK-Server or Tcl/Tk.
As in previous releases, most new functionality and changes where asked for or contributed by the community of newLISP users.
This version has a new set of functions for managing nested association lists. Nested association lists are frequently the result from converting XML into Lisp s-expressions. XML has established itself as a format for data interchange on the internet. The new functions permit access, modification and deletion of associations in nested association lists. These functions also work together with FOOP, which represents objects as associations.
Using the : colon operator to implement polymorphism in method application and using context namespaces to encapsulate all methods of an object class, an object oriented programming system for newLISP has been designed. Thanks to Michael Michaels from neglOOk for designing most of this new way of object oriented programming in newLISP and for creating the training video series: “Towards FOOP”. FOOP melts contexts, the new colon operator : and functional programming into a simple and efficient way of object oriented programming in newLISP. The system features polymorphism and inheritance and can have anonymous objects, which are memory managed automatically by newLISP.
A very short description of FOOP can be found in the Users Manual. For a more in depth treatment of this topic see Michael Michaels's video series accessible from the newLISP documentation page and the neglOOk website.
assoc-set, set-assoc, pop-assoc – change or delete an association, handle nested associations.
bind – the function binds expressions to symbols from an association list and is normally used in logic programming together with unify. This function was already present in earlier versions, but was not documented.
destroy – destroys a process addressed by the process id returned by yhr newLISP functions process or fork.
dostring – iterates over a string with the character value in the loop variable. On UTF-8 compiled newLISP UTF8 character values are returned by the loop variable.
NEWLISPDIR - this environment variable will be registered on startup as /usr/share/newlisp on Unix and Unix like OSs and as %PROGRAMFILES%/newlisp on Win32. This allows writing platform independent code for loading modules. An already existing definition of NEWLISPDIR will not be overwritten during startup.
ref-set, set-ref, ref-set-all – these functions modify one or all elements in a list searched by a key. The key can be any type of expression and unify, match or a user-defined function can be specified as comparison function. Like the nth, set-nth and nth-set family of functions these new list search-and-replace functions can pass lists by reference using a context name which is interpreted as a default functor.
when – works like if without the else clause evaluating a block conditionally and without the necessity of begin.
The : (colon) now also works as a function and can be attached to a symbol following it. The operator forms a context symbol from the symbol following it and the context symbol found as the first element of the list contained in the next argument. The colon operator is used to implement polymorphism in FOOP.
assoc – now handles nested multilevel associations.
count – has been rewritten to be many times faster on Unix and Unix like OSs.
dup - without the repetition parameter will assume 2.
find – when used with a comparison functor puts the last found expression into $0.
find-all – can now be used on lists too.
get-url, post-url, put-url, delete-url - have been extended and reworked to return more error information as supplied by the server and have improved debugging support.
last, nth, nth-set, set-nth – now have last element speed optimization as previously only present in push and pop.
nth, set-nth, nth-set, push, pop – when used on lists, indices overshooting the beginning or the end of the list now will cause an error to be thrown. Before, out of range indices would pick the first or last element in a list. The new behavior is consistent with the behavior of indexing arrays.
pack – now can take lists for data.
process – this reworked function now creates the new process without the previous time and memory overhead on Unix. No extra newLISP fork will be created to launch the new process. In most cases the full path must now be given for the command in process.
rand – integer random number generation with better statistical quality on Win32.
ref – when used with a comparison function puts the last found expression into $0.
set-assoc – renamed replace-assoc changes an association, handles nested associations.
set-nth, nth-set – now return the old list or value when the second argument is not present. They behave now like set without the value argument. Before both, set-nth and nth-set returned nil when the value argument was missing.
signal – the nil flag now specifies SIG_IGN and the true flag SIG_DFL. Before 9.3 nil would specify an empty newLISP handler and the true flag was not available. This allows to reset the signal handler for a specific signal to its OS default.
newlisp.vim – the syntax highlighting and editing control file for the VIM text editor has been much improved by Cyril Slobin.
crypto.lsp – this module has been expanded to offer hmac encryption using MD5 or SHA-1 hashing.
amazon.lsp – this new module interfaces to the Amazon Web Services, S3 storage API.
newlispdoc – this utility has been improved to handle indices and links to external module collections.
wordnet.lsp - this new module interfaces to the WordNet 3.o datebase
The amazon.lsp and wordet.lsp modules are not part of the distribution, but can be accessed in the new section.
Many bugs have been fixed in this release stabilizing some of the new features in the previous 9.2 release and fixing older previously undetected bugs. For more detail on bug fixes and changes see the CHANGES file in the source distribution of newLISP v.9.3.0 in newlisp-9.3.0/doc/CHANGES. This file details fixes changes for the development versions between 9.2.0 and to 9.3.0.
§ | http://www.newlisp.org/downloads/previous-release-notes/newLISP-9.3-Release.html | CC-MAIN-2015-18 | refinedweb | 1,118 | 56.35 |
How does Argument-Dependent-Lookup work for namespace-scope friend fucntion?
Discussion in 'C++' started by neverhoodboy, Mar 4, 2012.
Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
- Similar Threads
argument dependent lookupMartin Vorbrodt, Oct 25, 2005, in forum: C++
- Replies:
- 13
- Views:
- 542
- Default User
- Oct 25, 2005
- Replies:
- 1
- Views:
- 367
- Old Wolf
- May 14, 2007
- Replies:
- 4
- Views:
- 519
- James Kanze
- May 15, 2007
user-defined conversion combined with argument-dependent lookupBelebele, Nov 30, 2007, in forum: C++
- Replies:
- 6
- Views:
- 452
- Belebele
- Dec 11, 2007
Argument Dependent Lookup inside a template class, Apr 8, 2009, in forum: C++
- Replies:
- 2
- Views:
- 463
- Balog Pal
- Apr 9, 2009 | http://www.thecodingforums.com/threads/how-does-argument-dependent-lookup-work-for-namespace-scope-friend-fucntion.869022/ | CC-MAIN-2014-52 | refinedweb | 147 | 64.75 |
Sunday, September 12, 2010 | $1
NEW DAY AT FLEA MARKET
Lutherans gather to consider new option Denomination formed in protest of gay clergy seeks to ‘do what we ought to do as Christians’ BY EMILY FORD eford@salisburypost.com
JON C. LAKEY/SALISBURY POST
Webb Road Flea Market vendors returned Saturday as the rubble pile from the massive fire remained.
Vendors will return to sell wares today BY EMILY FORD
ty the day after the fire to view the remains and again the next day to share condolences with Next to a mangled mass of the vendors, many of whom charred metal, vendors at the have become friends over the Webb Road Flea Market were years. open for business Saturday, “It was one of those curves just a week after an epic fire that life throws at you,” said destroyed much of their liveliJamal Snead, a vendor for hood. three years. “You just have to The open-air market constay strong.” tinues today from 8 a.m. to 5 Snead, like others who lost p.m. their booths in the market’s market owners Flea patchwork of buildings, set up launched an extensive media shop outside this weekend. campaign this week to adverAbout 200 vendors were extise the reopening, including pected Saturday. Before the press releases, newspaper ads, fire, the flea market averaged radio spots, and signs and banabout 350 vendors. ners. They’re fighting a pubPermanent vendors who lic relations nightmare — the had been inside the buildings shocking sight from I-85 of were given first dibs at a spot burned-out buildings, leveled Jackie Garmany operates Floral Design by Jackie out of a 28-foot storage in the open-air market, said when the three-alarm fire building in the outside sales area of the flea market Saturday. James Coody of China Grove, raced through Sept. 3. who sells hunting and camping A steady stream of cars turned into the equipment. Owners have asked patrons of the 25-yearold market to show their support for vendors market on Webb Road, where orange fencSome week-to-week vendors who normalwho were victimized by the fire by shopping ing wrapped the expanse of debris. A Pepsi ly set up outside and were not affected by this weekend and throughout the coming machine, charred but recognizable, stood the fire were pushed back to make room. But sentry. months. Jerry Christy said he didn’t mind. Customers Gail and Ron Hill of Albemar“We’re doing what we can to spread the Most customers walk the entire market word,” said Catherine Popp, who owns the le heeded the call and returned to the flea anyway, said Christy, who has sold fishing market with her sister and brother-in-law, market, ready to buy a birthday present for equipment outside for about 10 years. a neighbor. Libby and Chris Stephens. Vendors thanked the owners for moving “They said they would be open Saturday, quickly to provide an open-air market. Many Finding a way to safely reopen this weekend was their top priority, Libby Stephens and I couldn’t believe it,” Ron Hill said. “I vendors relied on the flea market as their said, ‘We’ll have to be there.’ ” said. The Hills have been shopping at the mar“A lot of these people lost everything,” See VENDORS, 2A ket for 17 years. They drove to Rowan Counshe said. eford@salisburypost.com
Fire officials say response went as planned BY SHELLEY SMITH ssmith@salisburypost.com
When fire broke out at the Webb Road Flea Market on Sept. 3, more than 180 firefighters and other emergency personnel responded. Mike Zimmerman, incident commander and chief of Bostian Heights Fire Department, said the response went exactly as planned. Emergency responders followed Zimmerman’s response plan correctly, he said, and the plan is something he’s been updating since the Salisbury Millwork fire in 2008 claimed the lives of two firefighters. After the Salisbury Millwork fire, all Rowan County fire departments rethought their plans for structures within their jurisdictions. Zimmerman said he’s upgraded the response plan for the Webb Road Flea Market for his department at least twice since the Millwork fire. “I’ve done a lot since the mill fire to increase some responses,” he said, noting that 18 fire departments responded to the blaze. “I
[|xbIAHD y0 0 2ozX
JON C. LAKEY/SALISBURY POST
Charred remains of the Webb Road Flea Market served as a reminder Saturday of the fire that left only rubble behind. looked at it in 2008, and I’ve probably changed the response plan two or three times since then, and I’m in the process of changing it again. It’s one of those things that’s never ending.” Zimmerman said plans also change because mutual aid departments are constantly changToday’s forecast 85º/58º Cloudy, foggy
Deaths
ing equipment. Although Zimmerman said he learned from the Millwork fire, he cannot compare the two. “The flea market and the mill are totally unique and different,” he said. “If you think about a company, you’ve got so many employees that are there and they’re not
Edith Miller Eagle Billy Ray Hancock Paul Koone Dorothy Gretta Linton
going to be rushing to leave to get out of there. “The flea market has a lot of people in a small area. You put that amount of people in cars in that acreage, and there’s nowhere for them to go.” Frank Thomason, emergency services director for Rowan County, agreed that the two fires were completely different. “All the emergency service agencies in the county, we are all continually either as a group or individually, we continue to look for better ways to do things, more efficient ways to do things, and we are looking at those trends,” Thomason said. “The exercises and drills that we have throughout every year are ways that we test our responses. And we have those exercises to show us (how we can improve).” Because Zimmerman knew no one was inside the flea market at the time of the fire, and because the fire was very aggressive, firefighters took a defensive approach.
James “Jim” M. Long Carl Craig Lyerly, Sr. Annie Pearl D. McClure Don A. Stancil
See PLANNED, 2A Edna Rae S. Taylor Council Weddington, Sr. Lewis Richard Wilson
The leader of a conservative activist group that launched a new Lutheran denomination two weeks ago spoke Saturday at St. Paul’s Lutheran Church. The Rev. Mark Chavez, director of the Lutheran Coalition of Renewal, drew nearly 200 people from more than a dozen Lutheran churches. In response to mainline Lutheran acceptance of gay clergy and other practices viewed as immoral, Chavez’s organization last month created the North American Lutheran Church, a fledgling denomination of churches formerly affiliated with the Evangelical Lutheran Church in America. “There will be a steady departure of churches from the ELCA,” Chavez said. By far the largest Lutheran denomination in the United States with 10,239 churches, the ELCA angered many when delegates voted to allow noncelibate gays to be pastors. Nearly 200 congregations have left the ELCA, and 136 more are on their way out. A 1,700-member congregation in Iowa was two votes shy of ending its affiliation. St. Paul’s Lutheran was one of the first North Carolina churches to leave, the Rev. William Ketchie said. “The congregation had a sense of relief when we left the ELCA because we’ve been fighting this for many years,” Ketchie said. “There is a new sense of peace in the congregation.”
See LUTHERANS, 7A
Tears, songs fill day of remembrance NEW YORK (AP) — Rites of remembrance and loss marked the ninth anniversary of the Sept. 11 attacks, familiar in their sorrow but observed for the first time Saturday in a nation torn over the prospect of a mosque near ground zero and the role of Islam in society. Under Firefighters’ lost and down to place memorial among flowers in a reflecting local sites holding pool in their honor. ceremonies, 3A. Within hours of the city’s memorial service near ground zero, groups of protesters had taken up positions in lower Manhattan, blocks apart and representing both sides of the debate over a mosque. in 2001 and the national unity that followed.
Local gathering
Contents
Business Celebrations Classifieds Deaths
1C 2E 4C 4A
Opinion People Sports Television
2D 1E 1B 9C
FROM 1a
PLANNED FROM 1a “We went defensive pretty much on the get-go,” he said. “Our goal had been from day one, that if the building was on fire, find a way to cut it off and stop it. “It blew by us before we could get in place. We didn’t have a chance. About 80 percent of that building was burning when we got on scene, and there was so much force in the fire.” Zimmerman said someone told him the fire was burning a building a minute. And, he said, it would have been a “nightmare” if the fire would have happened on a weekend. “I can visualize it,” he said. “We would have been sitting a half mile away because we wouldn’t have been able to get in. People would be inside either trying to get out or trying to save stuff. “I could see cars going everywhere, people hitting each other — everyone just bottlenecking. We could have had all kinds of possibilities out there.” Zimmerman said that over the years when he responded to medical calls, he thought about a fire hitting. “When I go out there, I go in looking around thinking about what would happen during a fire,” he said. “This was always in the back of my mind. “I’m so thankful it happened when it did and that nobody was there. It would have been chaos. It would have been a disaster.” The Salisbury Fire Depart-
JON C. LAKEY/SaLISBURY POST
Libby and Chris Stephens, left, are co-owners of the Webb Road Flea Market with Catherine Popp. all three stood near a Krispy Kreme stand that was giving out coffee and doughnuts to vendors on the first day back to business Saturday. it delivered to the flea market. With set-up, she spent $6,200. She lost all of her fall floral arrangements and Christmas trees in the fire, but she stores materials at home and immediately began making
creations to sell from her new location. “When the Lord closes one door, he opens another, and this is it,” she said. Harry Huang rented 16 spaces inside the flea market
ment received new radios, locators and thermal imaging cameras after the mill fire, and Zimmerman said Bostian Heights and other departments have similar equipment. Thomason said although the flea market fire response “went extremely well,” he is sure the departments and responding agencies will find ways of tweaking things. “We’re always very cognizant of the way the operation goes,” he said. “We look back.” Both Thomason and Zimmerman are very grateful for the county’s departments, and everyone who volunteered their time to help during and after the fire. “We are very blessed in Rowan County with the number of fire departments that we have,” Thomason said, “and the resources that we have.” “I’m so pleased with the county, with the support we had,” Zimmerman said. “It was unbelievable. “I’ve been in the fire service for 34 years and this is the largest scale operation I’ve been involved with. To be able to pump 4,000 gallons a minute — that’s remarkable in itself.” Zimmerman called Rowan County “blessed” to have the equipment it has and the excellent training the firefighters and responders receive. “The water point operations and water hauling — we’ve trained on that for years,” he said. “And it showed last Friday.” The Webb Road Flea Market fire began around 7:30 a.m. and firefighters fought the flames for five hours, us-
ing 900,000 gallons of water — “The most I’ve ever been involved with in the history of Bostian Heights Fire Department,” Zimmerman said. Thankfully no one was injured, Zimmerman said. “If we can leave a scene, and no one was hurt, and no equipment was damaged, we had a good day,” he said.
Posters Deadline for posters is 5 p.m. • Descendents of John Robert and Emma Ritchie Patterson holding reunion, Sept. 19, at Mount Mitchell United Methodist Church Fellowship Hall at 1 p.m. Bring basket of food. • The family of the late Lawson Alexander and Lula Moore Trexler, 60th annual Trexler Reunion, Sept. 19, 1 p.m., Rockwell Park. Bring a well-filled picnic basket. Drinks and paper products will be furnished. Bring pictures to put on display. Put names on pictures. • Keller Memorial Lodge 657 will hold a stated communication on Monday. Lodge will open at 7:30 p.m. • Ball Park area, Kannapolis, holding reunion Oct. 9 at First Wesleyan Church Fellowship Center, 301 Bethpage Road. Covered-dish, 11 am-3 pm. For more information, 704-933-2452. • Southern City Tabernacle AME Zion Church Stewardess Board Bus Trip to Shatley Springs in Crumpler, Cheese Factory, Frescos of Last Supper. Saturday, Oct. 16. Leaving 6:30 a.m., returning 7 p.m. $40. First payment due Sept. 16. Call Valerie Foxx, 704-6300922; Jean Kennedy, 704-633-7428; church, 704-636-9043.
Lottery numbers —
RALEIGH (AP) — These North Carolina lotteries were drawn Saturday: Cash 5: 15-17-26-29-39 Pick 4: 6-2-2-3 Evening Pick 3: 1-2-3 Midday Pick 3: 0-1-3 Powerball: 07-17-20-36-59, Powerball: 33, Power Play: 4 Estimated Powerball jackpot: $79 Million
and lost inventory worth $30,000 in the fire. He chose not to display his cell phone accessories and $1 items Saturday for fear of rain, and he eyed Garmany’s new building with envy. He said he could not afford to purchase one but was considering renting a smaller building for $220 a month. Regardless, Huang said he would open for business again soon. “The next three following months are our biggest sales of the year,” he said. “I would like to see them rebuild before Christmas and holidays, but I don’t think they’re going to make it.” Owners are working to rebuild as quickly as possible, Chris Stephens said, but it’s a long and complicated process. Until then, they will operate the open-air market from 8 a.m. to 5 p.m. Saturdays and Sundays. Contact Emily Ford at 704797-4264.
Douglas A. Smith for District Court Judge
INTEGRITY • IMPARTIALITY • EFFICIENCY
Only
FOR 4 MONTHS*
The Holiday Season is just around the corner but there’s still time to lose 30 to 40 lbs!
Body Wrap Sale!
Did you know the average American gains 5-7 lbs during the holidays?
99
$
*EXCLUDES START UP KIT
call for details
R125128
R126871
VENDORS only source of income. “I’m happy they took the initiative,” said Snead, who makes a living selling shoes, caps and other items at Webb Road and similar markets in Hickory and Lexington. With free Krispy Kreme doughnuts and coffee delivered by volunteers from Catawba College, vendors sold their wares and wandered around, checking out set-ups by friends and competitors. Some vendors just used tables, provided by the market. Others covered them with tents. Still others, like Jackie Garmany of Salisbury, came up with a more permanent solution. Owner of Floral Designs by Jackie, Garmany bought a 14by-28 square foot building from Bunce Buildings and had
SALISBURY POST
CONTINUED
Let us help you prepare by losing weight the right way!
• Lose 2-3 Lbs. Per Week Safe & Effective • NO PREPACKAGED FOOD • Enjoy Restaurant & Grocery Store Foods • ONE-ON-ONE COUNSELING • Boost Your Metabolism • Member Of The American Diabetic Assoc. • NC State Board Certified • Affordable Plans For Everyone
EAT REAL FOOD… GET REAL RESULTS
704/637-3111 1933 Jake Alexander Blvd. Salisbury, NC
R124561
2A • SUNDAY, SEPTEMBER 12, 2010
BUY ONE 0!)2/&',!33%3 GET ONE
FREE !.9&2!-%3s!.9,%.3%3
./%8#,53)/.3 Men’s & Women’s frames including DESIGNER BRANDS with your choice of single-vision, all bifocals including no-lines, trifocals, polarized, Transitions® and non-glare lenses. Offers expire 10/02/10
Plus! Great Deal on One Pair
59
ANY FRAMES $ 9/52#(/)#%s./%8#,53)/.3 Even our best designer frames priced at $229 and higher. This offer is good with the purchase of any prescription lenses at our everyday low prices.
We Accept
1 Hour Service
Any Doctor’s Prescription
In Most Cases Including Bifocals
95®. Arboretum Shopping Center (at the intersection of Highway 16 and 51) (704) 542-5069
CHARLOTTE, NC The Village at University Place 8701 Clay Blvd. (in front of Wal-Mart) (704) 510-0818125539
SECONDFRONT
The
SUNDAY September 12, 2010
SALISBURY POST
3A
Anniversary of 9/11 attacks
WAyne HinSHAW/For tHe SALiSBUry PoSt
Monte Quillman of the honor guard salutes the flag at the 9/11 Fallen Heroes Memorial Service at the firefighter’s memorial at Chestnut Hill Cemetery.
Nine years after terrorist attack, people gather to reflect, remember BY HUGH FISHER hfisher@salisburypost.com
A wreath was placed beneath a United States flag flying at half-staff. The notes of “Amazing Grace” played, as men and women stood and reflected. In Salisbury, at the firefighters’ memorial by the Chestnut Hill Cemetery, the ninth anniversary of the Sept. 11 terrorist attacks was a time to reflect on the lives lost on that fateful day. And it was a time to recall the sacrifices that continue to be made by those who dedicate their lives, and sometimes lay down their lives, to keep Americans safe. Honor guards made up of police officers, sheriff’s deputies and firefighters took part in the presentation of the flag. The annual ceremony at Chestnut Hill was one of several observances around Rowan County paying tribute to the 2,977 innocent men and women who died as a result of the attacks in New York, Pennsylvania and Washington, D.C. Youths, firefighters and spectators taking part in the annual Junior Fire Muster at Miller’s Ferry Volunteer Fire Department paid tribute to the victims of 9/11 before the morning’s events began. At noon, the Rowan County chapter of the Disabled American Veterans was scheduled to hold another public observance at the Salisbury Mall. Remembrances of 9/11 take on an added significance when the thousands of U.S. troops who’ve died fighting in the War on Terror are taken into account. Salisbury Mayor Susan Kluttz said she hoped all citizens would take the time to remember those who died on Sept. 11, 2001. “I’m here to speak for them (the people), to
A large crowd gathered for the 9/11 Fallen Heroes Memorial Service. thank the EMS, firefighters and law enforcement for what they do,” Kluttz said. She also spoke of the courage of emergency services personnel here at home, especially firefighters Victor Isler and Justin Monroe. They died in the line of duty on March 7, 2008. “This reminds us of the sacrifices our emergency personnel continue to make for us,” Kluttz said. Salisbury Fire Chief Bob Parnell brought a vivid reminder of the events of that day: a piece
of the steel structure of the World Trade Center. It was given to him by New York firefighters during a visit to the lower Manhattan site. This was the first time he’s brought it to a 9/11 memorial service. After the ceremony, people held the metal briefly, cradling it in their hands. “I hope (locals) remember the sacrifices the emergency services have made from Sept. 11, 2001 onward,” Parnell said.
“We pray for those families who were permanently affected.” And, for those who work saving lives closer to home, Parnell said it was important for locals to reach out and thank them for their bravery and dedication. “There’s plenty of chance for people to shake their hands,” Parnell said. “That same sacrifice could be made again, any day, that was made on Sept. 11.” Remembering the events of that dark day becomes even more important now that most of a decade has passed. Children who were just old enough to remember the attacks are now teenagers, and Sept. 11 takes on a whole new meaning for them. Chasity Comer, a member of the Salisbury Police Explorers post, grew up in a unique family. Members of the Explorer post took part in the ceremony. Her father, Wayne Comer, is a Spencer police officer and a member of the Spencer Fire Department, she said. Sept. 11, she said, reminds us of the hard work and dedication of firefighters and police officers — “knowing that we’re safe because of them.” Joseph Scrip, assistant commander of the Salisbury Police Explorers, said that 9/11 would forever be a part of the nation’s history. “We need to learn as much as we can about it,” Scrip said, “and honor those who lost their lives.” Local residents Bob and Colleen Morris, who moved to Salisbury from Tampa, Fla., five years ago, said that Saturday was a day of sadness and remembrance. “But I look at these young people, and I realize that there is hope for our future,” Colleen said.
Travel Associates leaves downtown after dispute over signage BY EMILY FORD eford@salisburypost.com
After a dispute over signage and a shared lobby, a travel agency is leaving downtown and moving to Concord. Travel Associates has been on the Square for 18 years inside the Plaza, a building owned by the city.
2010 Mustang GT
Manager Donna Wilcoxson sent an email to customers this past week and posted it on her window saying her lease was not renewed and the business would have to move. The e-mail also suggests watching for new development on the corner. Wilcoxson is the only employee at Travel Associates, which had
0%
R126507
Financing
Over
$
7,0S0R0P!
OFF M
TAuto, V8, Sync Voice Controls Stk # I1171 *Dealer retains all rebates
five agents at one time. Although the lease was not renewed, Travel Associates could have stayed in the Plaza on a month-to-month basis, said Randy Hemann, executive director for Downtown Salisbury. The city contracts with Downtown Salisbury to act as the leasing agent for the Plaza.
HILBISH Since 1954
FORD MERCURY LINCOLN
Hemann said he has no one to fill the vacancy. Travel Associates has shared the 1,200-square-foot location — and the rent — with F&M Bank since the bank installed an ATM machine outside the Plaza in 2003. In a gentleman’s agreement, F&M rents half the space inside the building, including an office, break
room and half the lobby, although the bank has never staffed the location with an employee. Hemann last year prepared a formal lease, which would have given F&M a voice in the appearance of the lobby.
See DISPUTE, 5A
704.938.3121 YOUR CABARRUS/ROWAN FORD STORE
I-85 S • Exit 58B (US29) • Kannapolis • 1 Mile Minutes from Salisbury
DEAL DIRECTLY NEW - HERBERT WITH MANAGERS: USED - RICK
2007 Fusion Certified 100K Mile Warranty. Stk # J10621 $
14,435
4A • SUNDAY, SEPTEMBER 12, 2010 Don A. Stancil James “Jim” M. Long
FOREST CITY — Paul Koone, age 87, of Forest City, died Friday, Sept. 10, 2010, at Hospice House of Rutherford County. A native of Rutherford County he was the son of the late Joe and Ola Mae Rollins Koone. He was a member of the Mount Vernon Baptist Church, was retired from Stonecutter Mills and was a United States Army Veteran of World War II. He was the widower of Doris Butler Koone. He is survived by one daughter, Dianne Shepherd of Rockwell; granddaughter, Angie Strode; grandson, Adam Shepherd; a special friend, Thelma (Sis) Lyles; three sisters, Myrtle Padgett of Falls Church, Va., Ruby Cole of Hendersonville and Daisy Daughtrey of Forest City; three brothers, Joe Koone of Hendersonville, Clyde Koone of Shelby and Bill Koone of Forest City. Visitation: The family will receive friends on Monday, Sept. 13, from 3:30-4 p.m. at Mount Vernon Baptist Church. Service and Burial: The funeral service will follow at Mount Vernon Baptist Church at 4 p.m. with the Rev. Richard Bass officiating. Burial will follow in the church cemetery. McMahan's Funeral Home & Cremation Services is in charge of arrangements. Online condolences may be made at.
Carl Craig Lyerly, Sr.
Annie Pearl D. McClure
SALISBURY — Carl Craig Lyerly, Sr., 88, of Salisbury, passed away Thursday, Sept. 9, 2010, at Kindred Hospital in Greensboro. Born Oct. 15, 1921, in Rowan County, he was the son of the late Harry Craig Lyerly and Pearl Winecoff Lyerly. Educated in Mount Ulla schools, he attended Rowan-Cabarrus Community College. Serving in the United States Army during World War II, he fought in Italy and North Africa, receiving two Bronze Stars and American Defense Service Medal. Mr. Lyerly was the owner of Lyerly Construction Company and earlier worked for Savings Supply Company. He also was an officer for Salisbury Police Department. A member of Haven Lutheran Church, he was also a member of Harold B. Jarrett American Legion and the Fulton Masonic Lodge. Preceding him in death were his sisters, Mabel Lyerly Wilkinson, Frances Lyerly Edminston, Kathleen Lyerly Cashion; and son-in-law Bob Campbell. Survivors include his wife, Margaret Cranfield Lyerly, whom he married Feb. 12, 1946; sons Craig Lyerly, Jr. (Debi) and Mark Lyerly (Mercy); daughters Carol Campbell and Jan Edwards (George), all of Salisbury; brothers Norman “Bub” Lyerly of Biscoe and Joe “Dick” Lyerly (Helen) of Mooresville; eight grandchildren, Amy Edwards (Bryan) of Mount Ulla, Eric Campbell (Misty) of Eielson AFB, Alaska, Candace-Craig Lyerly, Camantha-Rea Lyerly, Ashley Lyerly, Jonathan Lyerly, Jordan-Leigh Davis, all of Salisbury, and Jimbo Davis of Virginia; and two great-grandchildren, Callee Edwards of Mount Ulla and Brynlee Campbell of Eielson AFB, Alaska. Also surviving are nieces and nephews. Visitation: 10:30-11:30 a.m. Tuesday, Sept. 14 at Lyerly Funeral Home. Service: Following the visitation at 12 p.m. in the James C. Lyerly Chapel. The Rev. Darrell Norris will officiate. Burial will follow at Salisbury National Cemetery, 501 Statesville Blvd., Salisbury, NC 28144, where Military and Masonic honors will be performed. Memorials: In lieu of flowers, memorials may be made to Haven Lutheran Church, 207 W. Harrison St., Salisbury, NC 28144; or charity of donor's choice. Lyerly Funeral Home is serving the Lyerly family. Online condolences may be made at
SALISBURY — Annie Pearl Davis McClure, age 71, of 420 North Boundary ES St., East Winds Apartments, passed away Thursday, Sept. 9, 2010, at her residence. Born June 17, 1939, in Gaffney, S.C., she was the daughter of the late John and Lucille Rodgers Davis. She was a graduate of Dunbar High School and Carolina Beauty College. She retired from Dixie Furniture, Linwood. She previously worked for Doctors Webb, Mason and Corpening. Mrs. McClure was a member of North Congregation of Jehovah's Witnesses. In addition to her parents, she is also preceded in death by brothers, James M. Davis and Ervin Jerome Davis; and sisters, Eunice M. Davis and Johnnie Lucille Davis. Survivors include a daughter, Vanessa Davis Gordon of Black Mountain; grandchildren, Provita Davis of Salisbury and Delvin Davis of Yanceyville; brother, LeVance "Stickman" Davis (Yvonne) of Lexington; sister, Vivian R. Davis of Salisbury; brothers-in-law; sisters-inlaws; seven great-grandchildren; and a host of nieces, nephews, cousins and friends. Service: Memorial service will be 2 p.m. Wednesday at North Congregation of Jehovah Witness Union Church Rd, Salisbury with Jawiba Keisu, officiating. Visitation: The family will receive friends Tuesday from 5-7 p.m. at Hairston Funeral Home, Inc. The family will be at the home of the granddaughter, Provita Davis, of 835 North Church St., Salisbury. Services entrusted to Hairston Funeral Home, Inc. Online condolences may be made at.
Dorothy Gretta Linton
SALISBURY — Dorothy Gretta Linton, 92, passed away Tuesday, Sept. 7, 2010, at the Kate B. Reynolds Hospice & Palliative Care Center in WinstonSalem. Born Jan. 7, 1918, in Winston-Salem, she was one of - Army Staff Sgt. Vinson B. Adkinson two children III, 26, of Harper, Kan.; and of the late William and Eunice - Army Sgt. Raymond C. Alcaraz, 20, Brannic. Mrs. Linton spent of Redlands, Calif.; and - Army Pfc. Matthew E. George, 22, most of her life as a loving of Greensboro, N.C.; and wife to the late Elmo Linton - Army Pfc. James A. Page, 23, of Tiand was a domestic worker. tusville, Fla., died Aug. 31 in Logar province, Afghanistan, of wounds sufMrs. Linton was an avid fered when enemy forces attacked their bowler and traveled in severvehicle with an improvised explosive al states participating in tourdevice. -----------naments. She worked on the - Army Pfc. Diego M. Montoya, 20, of usher board at Galilee MisSan Antonio, Texas, died Sept. 2 in Laghman province, Afghanistan, of wounds sionary Baptist Church besuffered when insurgents attacked his fore her health failed her and unit with indirect fire. she moved to Salisbury. She ------------ Army Capt. Jason T. McMahon, 35, enjoyed her work in the of Mulvane, Kan., died Sept. 5 in church. Bagram, Afghanistan, of wounds sufMrs. Linton was preceded fered when insurgents attacked his unit with indirect fire in Jalalabad. in death by her husband, -----------Elmo; two daughters, Barbara - Marine Lance Cpl. Ross S. Carver, 21, of Rocky Point, N.C., died Sept. 3 Jean and Gretta Jowers; and a while conducting combat operations in grandson, John Jowers, Jr. Helmand province, Afghanistan. She is survived by three ------------ Marine Cpl. Philip G. E. Charte, 22, daughters, Rosetta (Willie) of Goffstown, N.H., died Sept. 7 while Glover of Hillsborough, conducting combat operations in Helmand province, Afghanistan. Martha (Johnny) Legrand of -----------Salisbury and Maria (George) - Marine Sgt. Jesse M. Balthaser, 23, Perkins of Smithfield, Va.; of Columbus, Ohio, died Sept. 4 while conducting combat operations in Helone son, Elmo Reece Linton, mand province, Afghanistan. Jr. of the home; and a host of ------------ Army Sgt. Philip C. Jenkins, 26, of grandchildren, other relatives Decatur, Ind.; and and friends. - Army Pvt. James F. McClamrock, Service: Funeral services 22, of Huntersville, N.C., died Sept. 7 at Balad, Iraq, of wounds suffered from will be held at 1 p.m. Monday, small arms fire. Sept. 13, at Galilee Missionary ------------ Marine Cpl. John C. Bishop, 25, of Baptist Church with Dr. Columbus, Ind., died Sept. 8 while conNathan Scovens officiating. ducting combat operations in Helmand Interment will follow in Everprovince, Afghanistan. green Cemetery. Visitation: The family visitation will be held from 12 noon-1 p.m. on Monday at the Billy Ray Hancock Church. KANNAPOLIS — Billy Online condolences can be Ray Hancock, 78, passed made at- away Friday, Sept. 10, 2010, at alservice.com. Carolinas Medical Center– NorthEast. Service and Burial: 12:30 Edna Rae Taylor p.m. Monday at Lady's FunerCLEVELAND — Edna Rae al Home Chapel. Burial will Stroupe Taylor, 94, of Cleve- follow in Carolina Memorial land, died Saturday, Sept. 11, Park. 2010, at the Gordon Hospice Visitation: 11:30-12:30 p.m. Council Weddington, Sr House in Statesville. Funeral Monday at Lady's Funeral ROCKWELL — Council arrangements are incomplete Home. Haywood Weddington, Sr., 83, and will be announced by Lady's Funeral Home is asof Rockwell passed away on Bunch-Johnson Funeral sisting the Hancock Family. Saturday, Sept. 11, 2010, at Home, Statesville, which is The Lutheran Home at Trini- serving the family. More obits on Page 5A ty Oaks. Funeral arrangements are incomplete at this time. Powles Funeral Home of Rockwell is assisting the Weddington family.
Lewis Richard Wilson SALISBURY — Lewis Richard Wilson, age 87, of 7006 Mooresville Rd., Salisbury, passed away Friday, Sept. 10, 2010, at Rowan Regional Medical Center. Arrangements are incomplete and will be announced at a later date by Noble and Kelsey Funeral Home, Inc.
Mrs. Patricia Lowder Ribelin
Serving Cabarrus & Rowan Counties Since 1913
Funeral Service: 2 PM Sun Enon Baptist Church -
Mrs. Elva “Tex” Turner-Glenn Cremation
Tradition.
Mrs. Debrah Everett Shipton Graveside Service 2:00 PM Monday Enon Baptist Ch. Cemetery
• TRADITIONAL FUNERALS • CREMATION SERVICES • ADVANCE PLANNING
——
Hairston Funeral Home, Inc.
Mr. Carl Craig Lyerly, Sr. Visitation: 10:30-11:30 AM Tuesday Service: 12:00 Noon James C. Lyerly Chapel
1748 Dale Earnhardt Blvd. Kannapolis, NC 28023 704-933-2222
R117895
Family Owned & Operated
SEPARATE HUMAN AND PET CREMATORIES Talk to us today about the benefits of pre-planning final arrangements.
Tommy H. Hairston, President PRE-ARRANGED SERVICES INSURANCE TRADITIONAL & NON-TRADITIONAL SERVICES & CREMATIONS MONUMENTS, NOTARY PUBLIC, SERVING ALL CULTURES
704-638-6464
523 S. Main Street, Ste. 2 Salisbury, NC 28144 704.633.0059
FUNERAL & CREMATION SERVICES
Serving Rowan & Surrounding Counties R104040
Paul Koone
KANNAPOLIS — Don A. Stancil, age 79, of 716 Deaton St., died Friday, Sept. 10, 2010, at Bob and Carolyn Tucker Hospice House after a period of declining health. Don was born May 28, 1931, in Mecklenburg County, he was the son of the late Sim C. Stancil and the late Ruth Hartsell Stancil Efird. He was a life long area resident. Don worked for Cannon Mills Co. and then served in the United States Army during the Korean conflict. After Korea he worked as an overseer at Corriher Mills in Landis and then for 5 Oaks Nursing Center, Concord. He enjoyed attending Homestead Baptist Church and he loved his family. Don was a loving and devoted husband, father, grandfather, brother and friend. He will be dearly missed. In addition to his parents he was preceded in death by two brothers; and one sister. Don is survived by his wife of 27 years, Tallie Bethea Stancil of the family home; his sons, Michael Stancil of Wilmington, Brett Stancil of Kannapolis and Michael “Gene” Bethea (Jennie) of Hampstead; grandchildren, Joshua Stancil (Ragan) of China Grove, Kellie Stancil and Jared Stancil and David, Wyatt and Hannah Bethea; greatgrandson, Jonah Stancil; two sisters, Myrtle Smith and Janie Roberts; one brother, Johnny “Dowd” Stancil, all of Kannapolis; daughter-in-law, Janet Stancil of Rockwell; and two special friends, Debby Bost and Joe Keogh. Service and Burial: Funeral services will be held at 2 p.m. Monday, Sept. 13, at Homestead Baptist Church, the body will lie in state one half hour prior to the service in the church. Rev. Terry Brown will officiate. Burial will follow at West Lawn Memorial Park in China Grove. Visitation: The family will receive friends from 7-9 p.m. Sunday, Sept. 12, at Whitley's Funeral Home. At other times they will be at the family home. Memorials: Memorial donations may be made to Hospice and Palliative Care of Cabarrus Co., 5003 Hospice Lane, Kannapolis NC 28081. Whitley's Funeral Home is assisting the Stancil Family. Online condolences may be made at.
R112479
TROUTMAN — James “Jim” Marshall Long, age 89, of Troutman, passed away Friday, Sept. 10, 2010, at Rowan Regional Medical Center in Salisbury. Born in Iredell County on Dec. 23, 1920, he was the son of the late Thomas Lester and Beulah Conally Knox Long, Jim served our country in the European theater of World War II and later retired from the textile industry. He was a renowned bird dog trainer for much of his life and was an avid quail hunter. He developed many friendships over the years as a result of his talent and knowledge of bird dogs and their training. In addition to his parents, he was preceded in death by his wife, Mildred Aldaine Rimmer; three sisters, Katherine Lowrance, Myrtle Long and Roberta Long; and six brothers, Sam, Thomas, Frank, Ross, Shelton and Harlee Long. He is survived by his daughter, Karen Ann Long of Statesville; sister-in-laws, Ruby Long of Raleigh and Julia Long of Statesville; nephew, Frank Long, Jr. of Statesville; and a number of other nieces and nephews. Service and Burial: Graveside services with full military rites presented by the Veterans Iredell County Council Burial Detail will be held at 2 p.m. on Tuesday, Sept. 14, at Iredell Memorial Gardens in Statesville with the Rev. Joe Woodward officiating. Visitation: The family will receive friends at the graveside immediately following the service. Pallbearers will be Bill Johnson, Hal Landreth, Phil McGuire, Derek Ostwalt, Andy Cook, Jimmy Millsaps, Kenny Icenhour and Madge Sides. Honorary pallbearers will be J. C. Brooks, Ed Little, Joe Little, Roger McGuire and Gene Frye. Memorials: In lieu of flowers, contributions in Jim's memory may be made to the American Diabetes Association, 222 S. Church St., Suite 336M, Charlotte, NC 28202. The family would like to express their gratitude to the staff at the North Carolina Veterans Home in Salisbury for their care of Jim over the past three years. Also, to Dr. Chris Agner and his staff at Rowan Regional for their loving care and compassion for Jim in his last week. Troutman Funeral Home is serving the family of Jim Long. Online condolences may be sent to the family at.
SALISBURY POST
OBITS
515 S. Main Street Salisbury, NC 28144 704.633.9031 R121881
SALISBURY POST
OBITUARIES
DISPUTE
FROM 4a
FROM 4a
CHINA GROVE — Edith Miller Eagle, 94, of Shue Road, passed away Friday, Sept. 10, 2010, at the Meadows of Rockwell. Born Jan. 3, 1916, in McGrady's Gap, Va., she was the daughter of the late Jordan Miller and Eliza Yates Miller. She attended McGrady's Gap school and was a homemaker. She loved her flowers, sewing and quilting. She was a member of the First United Methodist Church in China Grove. Preceding her in death was her husband, John Kirby Eagle, who died June 22, 1987. They had been married 50 years. Survivors include son, Donald Kirby Eagle and wife, Lynda of Ocean Isle Beach, and son, John Dean Eagle of Charlotte; daughters, Patricia Eagle Dodd and husband, John of Spartanburg, S.C. and Sondra Eagle McDaniel and husband, Gary T. of Liberty; six grandchildren; seven great-grandchildren; and one great-great-grandchild. Visitation, Service and Burial: Visitation will be Sunday, Sept. 12, from 2-3 p.m. at the First United Methodist Church with the service to follow. Burial will be in Greenlawn Cemetery China Grove. Memorials: Memorials may be made to First United Methodist Church 110 West Church Street, China Grove, NC 28023 or Rowan Regional Hospice, 720 Grove Street, Salisbury, NC 28144. Linn Honeycutt Funeral Home in China Grove is serving the family.
“The office is decorated to reflect a travel agency, not half a travel agency and half a bank.”
the bank uses to operate the ATM, so Hemann can market a more desirable 1,200-squarefoot location, he said. Depending on upfit, rent for the space will range from $1,200 to $1,400 per month, he said. “I’m saddened to see any business close downtown,” Hemann said. The travel agency has gone from five employees to one, so “it makes a lot of sense for them to combine and cut their overhead,” he said. “I understand their need for change.” Travel Associates will close Sept. 24 and reopen Oct. 4 as part of VIP Travel in Concord.
DENTURES Most Insurance Accepted
Wilcoxson balked. Now Accepting Medicaid “I do my business inside, Same they do their business outDay side,” she said. “The office Service is decorated to reflect a travOn Repairs el agency, not half a travel and Relines DONNA WILCOXSON agency and half a bank.” Repairs $50 & up manager, Travel Associates While Wilcoxson said she had no reason to think F&M Relines $175 per Denture would interfere in her business, the language in the tion system in a room used Dentures $475 ea.; $950 set lease concerned her. by the travel agency. The Partials $495 & up Signage outside the buildbank pays $550 per month, Extractions $150 & up ing reading “F&M 24-hour and the agency pays $341 banking” already had caused Dr. B. D. Smith, per month. a problem for the travel General Dentistry Hemann agreed it would be agency, she said. 1905 N. Cannon Blvd., Kannapolis easier to lease the location to (704) 938-6136 People think the location R103631 a single tenant. Downtown Salis a bank, not just an ATM, isbury is negotiating with F&M Contact Emily Ford at she said. She is interrupted to reduce the amount of space 704-797-4264. about five times a day by people who want to make financial transactions or have a card stuck in the ATM . In a joint venture with FUN FOR September 18, 2010 the previous owners of ALL AGES 8:00am — 2:00pm GREAT FOOD! Travel Associates, F&M agreed to take over half the Rain or Shine! Burgers, Hotdogs, rent to enable the travel Fried Chips Make a difference in the life of a child… agency to stay in that locaAUCTION BY: Pork Tenderloin & tion, F&M President Steve BBQ Sandwiches, Bostic Auction Services Breakfast Sandwiches Fisher said. at Noon The current owner is Call 704-568-9753 for more information. David Riggins of Charlotte. “Their business was de3430 Old US Hwy 70, Cleveland, NC R126701 clining at the time,” Fisher said. “Our intent was to prolong their business in that location by deflecting some of the cost.” F&M installed the ATM as a service to downtown, he said, and takes a loss on it because volume is too low. The bank’s signage was not intended to be misleading, he said. “If it is, I have never known a retail-based establishment who went out of business because too many people were walking in the front door,” he said. “Most retail-based establishments like traffic.”
COUNTRY FAIR
Hillbilly Olympics
BE A FOSTER PARENT!
Christ Episcopal Church
RED HOT
“The Best Insulated”
le Sa
Downtown Salisbury will have a hard time leasing the space because of the signage and shared lobby arrangement, Wilcoxson said. Few businesses would agree to those stipulations, she said. Wilcoxson said she eventually did agree to language in the lease, but Hemann revoked the offer. Hemann wrote in December 2009 that he would not extend a lease to Travel Associates and was exploring all of his options for the space. F&M has had half the space and half the signage because the bank pays half the rent, Hemann told the Post. F&M actually pays more rent now than Travel Associates, because the city installed a backflow preven-
R126616
Edith Miller Eagle
ll Fa
SUNDAY, SEPTEMBER 12, 2010 • 5A
CONTINUED
WINDOWS
& FREE.
$15 0 red 0
Don’t miss out. Offers end September 30th!
Tax C
it
All Styles • Doors 100 Styles & Colors
FACTORY DIRECT DISCOUNTS
Switch now and get any of these devices
J.A. FISHER 704-788-3217
Salisbury
R124210
A Specialty Contractor Since 1979 With Over 6000 Completed Jobs Kannapolis
FREE. FREE.
A.
Final Chance
Buy a Samsung Fascinate and get ANY phone
After mail-in rebate debit card and new 2-yr. activation.
SALE One Last Day
60–75% OFF
Free phone after up to $100 mail-in rebate debit card. Free phone must be of equal or lesser value. New 2-yr. activation req’d per phone.
B.
Furniture, Lamps, Gifts, Accessories
R126978
R126105
Saturday, Sept. 18 • 10AM–3PM
116 Statesville Blvd Salisbury
C.
NEW! Samsung Fascinate™ a Galaxy S™ phone
D.
Android™ muscle behind a super AMOLED screen
HEALTH EXPERTS RECOMMEND EATING 7-13 SERVINGS OF FRUITS & VEGETABLES A DAY FOR MAXIMUM NUTRITIONAL HEALTH Do you, your spouse or kids dislike, can’t eat or won’t eat those daily servings?
19999
$ A. BlackBerry® Curve™ 8530
- Good or poor health begins in the kitchen! How can I make it good? - How can I cook healthy, fast meals for my family and leave out the harmful fats and oils? - Are there really inexpensive natural health alternatives available for ACID REFLUX that could work for me? - Overweight for years! Can I finally begin to lose it without drugs, chemicals, wraps, fad diets or gimmicks? - I don't eat that much. Why am I fat or obese, feel tired and unhealthy, diabetic with high blood pressure ? Call & reserve your seat today for our FREE local 2 hour Health, Wellness and Nutrition Dinner Seminar. Space Limited! Foods served! Spouses, guests and health conscious friends welcome.
All the essentials plus trackpad navigation $100 2-yr. price – $100 mail-in rebate debit card. Requires a $29.99 data package.
C. LG Cosmos™
$299.99 2-yr. price – $100 mail-in rebate debit card. Requires a $29.99 data package.
B. MiFi™ 2200 Intelligent Mobile Hotspot Be your own hotspot, connect up to 5 devices $50 2-yr. price – $50 mail-in rebate debit card. Requires a Mobile Broadband Plan.
D. LG Chocolate® TOUCH
Socially skilled text specialist
Texter with the musical touch
$50 2-yr. price – $50 mail-in rebate debit card.
$50 2-yr. price – $50 mail-in rebate debit card. Requires a $9.99 data package. All devices require new 2-yr. activation. While supplies last.
“Touching Hearts”
Your signal reigns on America’s Largest and Most Reliable Wireless Network. “Changing Lives”
1.800.256.4646
1-866-715-8438 Email dennissipp@aol.com for a FREE Health & Wellness Newsletter
R126986
VISIT US AT THE SENIOR EXPO Sept 14 10am-2pm Salisbury Mall Fountain Entrance
•
VERIZONWIRELESS.COM
•
VZW.COM/STORELOCATOR
Activation fee/line: $35 IMPORTANT CONSUMER INFORMATION: Subject to Cust Agmt, Calling Plan, rebate form & credit approval. Up to $350 early termination fee/line & add’l charges apply to device capabilities. are the property of their respective owners. Android is a trademark of Google, Inc. MiFi is a trademark of Novatel Wireless, Inc. Samsung, Fascinate and Galaxy S are registered trademarks of Samsung Electronics America, Inc. and its related entities. © 2010 Verizon Wireless. REDS
R126705
Landis Town Board to meet BY SHAVONNE POTTS spotts@salisburypost.com
LANDIS — The Landis Town Board will discuss a hazard mitigation plan, which other boards have talked about also. The plan includes guidelines for natural hazards that may occur and how emergency personnel and municipalities will respond to them. It is a multi-jurisdictional plan that has to be updated every five years to qualify for mitigation grants and disaster assistance funding. The federal government mandates that a plan be submitted. Rowan County Emergency Services Director Frank Thomason is informing other municipalities of this plan.
The board will also discuss: • A recycling program for local businesses. The town already has a successful residential recycling program, which got underway in August. • Discuss the renewable energy fees. The board meets Monday at 7 p.m., at town hall, 312 S. Main St.
SALISBURY POST
AREA
Nazareth Children’s Home receives two grants Nazareth Children’s Home Inc. has been chosen by two local charitable foundations to receive grants of support for the 104-year- old mission to change the lives of disadvantaged children. The first gift received was from the Salisbury-based Blanche & Hubert Ritchie Foundation in the amount of $6,000. This gift will provide up to 60 boys and girls with $100 each to help them purchase new clothing for school. The second gift received was a $15,000 grant from the David Boyd Davis Charitable Trust of Spencer. This gift was given to further enable Nazareth to continue its high standards of service, care and commitment to children and families, which was very important in the life of David Boyd Davis. The mission of Nazareth Chil’dren’s Home is to provide love, sta-
bility and guidance to the chil- whenever possible with their dren who come to the home families or other permanent for help, reuniting them placement.
! OVER y D a L d n E H s Su d n E Sale
SALISBURY
MOORESVILLE
317 FAITH ROAD
168-U NORMAN STATION BLVD.
Next to Lowes, The Movies at Innes St. Market
Consumer Sq. Shop Ctr., across from Wal-Mart
CONCORD MILLS
CHARLOTTE
10001 WEDDINGTON RD.
6153 INDEPENDENCE
704-979-1112
704-535-8383
704-639-1009
Speedway Blvd. at Garden Ridge
Food distribution planned for Wednesday
N.C. Republican Leadership is taking part in a “whistle stop” Tuesday at the Wrenn House at noon. Salisbury is among the locations for “whistle stops” by state Republican Party Chairman Tom Fetzer, House Minority Leader Skip Stam and others. The Wrenn House buffet lunch is $6.99.
rotini pasta, cheddar cheese. In agreement with federal laws and policies of the Department of Agriculture, this agency prohibits any discrimination based on race, skin color, nationality, sex, age or physical disability. Do not form a line before 4 a.m., when police officers will be present. Sponsored by the Altrusa Club of Salisbury and the Salisbury Department of Parks and Recreation.
Between Harris Blvd. & Idlewild Rd.
Open M-F 9:30-8 • Sat 9:30-6 • Sun 1:30-5 *Sold In Sets *OAC * Discount Do Not Apply to Tempeurpedic & Closeouts *On Same Model
Douglas A. Smith for District Court Judge
16th Annual Festival
INTEGRITY • IMPARTIALITY • EFFICIENCY
Friday & Saturday ••• ••• September 17th & 18th Iron Peddlers Antique Tractor Show Tours of Narrows Dam • Run the Valley • Kids’ Inflatables Friday Night Street Dance featuring The E’ssentials Heritage Days Exhibit • Smokey the Bear • Craft & Food Vendors Live Bands & Entertainment • Saturday Evening Fireworks
S46137 S46125
Republicans meeting Tuesday
vious food distributions. • Family of 1 person: $1,805 • Family of 2 persons: $2,428. • Family of 4 persons: $3,675. • Family of 6 persons: $4,922. Available foods: apple sauce, apple juice, ground beef (frozen), pork patties (frozen), cheddar cheese soup, corn, green beans, orange juice, pears, sliced potatoes,
R126699
There will be a food distribution on Wednesday for Rowan County residents only at Salisbury Civic Center, 315 Martin Luther King Ave., 9 a.m.-1 p.m. or until all the food is gone. Food stamp recipients should bring the letters they received. All others who do not receive food stamps can come to Salisbury Civic Center because they may also be eligible for free food. They must disclose their total gross monthly household income. The following are examples of the income guidelines. Please note changes from pre-
factorymattressusa.com 30 Carolina Locations Since 1974
704-660-3900
R126974
6A • SUNDAY, SEPTEMBER 12, 2010
••• NO PETS PLEASE ••• Visit for more information!
R126490
SALISBURY POST
SUNDAY, SEPTEMBER 12, 2010 • 7A
CONTINUED
R125084 katie scarvey/SALISBURY POST
Firefighters enter the house that was on fire Saturday at 608 Maupin Ave. No one was injured.
Kitchen fire damages Maupin Avenue house When Judy Newman noticed smoke coming from her neighbor’s house Saturday evening, she called to her husband. Hank Newman ran two doors down to 608 Maupin Ave. with a fire extinguisher, entered through the back door and sprayed the stove, which was ablaze. “I thought I put the thing out,” Newman said. But the fire flared up again and Newman, his fire extinguisher empty, left as the house filled with smoke. Cleo Dick and her daughter, Janice Blackwell, escaped without injury. Blackwell said she moved to Salisbury a year ago to help care for her mother, who lost her husband, Bob Dick, two years ago. Cleo Dick was cooking at the stove when it caught fire, Blackwell said. Blackwell
LUTHERANS FROM 1A
Excellence E x c e l l e n c e iin nH Healthcare ealthcare A Awards wards When iitt ccomes When omes tto o eevaluating valuating tthe he q quality uality o off m medical edical ccare, are, who wh ho better to judge than physi physicians icians and medical staff? That’s T hat’s w why hy R Rowan owan R Regional egional M Medical edical C Center enter iiss p proud roud tto o bee aawarded b warded 2 22 2h healthcare ealthcare aawards wards b byy P Professional rofessional R Research esearch hospitals Consultants C onsultants ((PRC), PRC), a ccompany ompanyy tthat hat rrecognizes ecognizes h ospitals n ationw wide tthat hat d emonstrate eexcellence xcellence iin np atient ccare are aand nd nationwide demonstrate patient aare re ggreat reat p laces tto ow ork. T hese aawards wards aare re b ased o n ssurvey urvey places work. These based on rresults esults o rea p hyysicians aand nd eemployees mployees o owan R egional. off aarea physicians off R Rowan Regional. W re p roud o hese aachievements chievements aand nd tthe he ffact act tthat hat iitt iiss Wee aare proud off tthese tthe he d irect rresult esult o igh rratings atings ffrom rom tthe he ssame ame p hyysicians direct off h high physicians aand nd m edical sstaff taff w ho ccare are ffor or yyou ou aand nd yyour our ffamily. amily. medical who
Winner of 22 Awards
inate confusion over numerous groups and abbreviations. While the names and acronyms of a half-dozen Lutheran organizations rolled off Chavez’s tongue for two hours, many people are having a hard time keeping up. And deciding where to send their check. “How long are we going to be able to sustain all these organizations?” asked the Rev. Floyd Bost, former pastor at St. Paul’s. Chavez acknowledged the confusion. There will be multiple Lutheran organizations for several years, he predicted, but eventually some will merge and the way will become clear. “This is not an easy time,” he said.
Overall O verall T Top op P Performer erformer A Award ward EEmployee mployee Training Training & Professional Professional Development Development
St. Paul’s is now considering affiliating with the new North American Lutheran Church, he said. So far, 28 congregations have joined the new denomination, Chavez said, and the staff of 10 has been flooded with e-mails and phone calls. Lutheran Coalition of Renewal launched the new church when it became clear they couldn’t change the ELCA, he said. The mainline Lutheran church is headed the same direction as the United Church of Christ and the Episcopal Church, Chavez said, which teach that “God is love” and “everyone is welcome just the way you are.” Contact Emily Ford at 704These churches embrace, 797-4264. preach and teach a false gospel, while churches like St. Paul’s “do what we ought to do as Christians,” he said. “Hold the line and make our core values clear.” The creation of a new church has drawn more attention than expected, Chavez said, with special interest from Lutherans in Africa. The Roman Catholic Church also is closely following the transition, he said. The new church comes “at a time when our culture is taking a very determined and forceful stand against a biblical world view,” he said. The culture denies a belief in absolute truth, and the ELCA has conformed to the culture by allowing “idolatry of the self,” Chavez said. “We become the ultimate authority in all things.” Questions from the audience focused on church leadership. If an ELCA congregation would not call a lesbian or homosexual pastor, why should the members consider affiliating with the North American Lutheran Church, one man asked. Whether a pastor is homosexual is “trivial” compared to what the pastor will preach and teach, Chavez said. What lies beneath the ELCA’s acceptance of gay clergy and gay marriage “is • Floral Designs for the Complete Wedding an explicit rejection of Christian faith,” he said. • Balloon Designs, Arches, Spirals, Chavez predicted there will Columns and more be a “glut” of pastors available to serve congregations that leave the mainline church and affiliate with the North American Lutheran Church. The Rev. Marty Ramey said she resigned from the ELCA three weeks ago and wants to serve the new 1628 W. INNES STREET • KETNER CENTER • SALISBURY church. 704-633-5310 • 800-992-5310 S40653 She also offered to give her “alphabet soup” presentation to area churches to help elim-
Let us make your special day memorable.
“We want to be your flower shop.”
Employee Perce Perception eption A Awards wards w
5-Star Awards A A lace tto oW ork • O verall P atient C are • EEmployee mployee EEmpowerment mpowerment Ass a P Place Work Overall Patient Care Employee Training & Prof fessional Development Professional Communication • Immediate Su upervisor • Senior Leadership Supervisor Tea amwork Between Departments • Teamwork Within Departmentss Teamwork 4 -Star A ward 4-Star Award T otal C ompensation P ackage Total Compensation Package
Physician Perception Perception Awards Aw wards 5-Star 5-Star Awards Awards Anesthesia Services Services • Laboratory Laboratory Services Services • Pathology Pathology Services Services Anesthesia 4-Star 4-Star Awards Awards Overall Quality Care Ass a P Place Medicine Overall Q uality of of Care Care • Nursing Nursing C are • A lace to to Practice Practice M edicine Emergency Emergency Services Services • Patient Patient Safety Safety • Radiology Radiology Services Services Medical Medical Records Records • Administration Administration
Rowan
REGIONAL MEDICAL CENTER
Box an/quality
Think Outside of the
Wedding Favor
Most. • Candy: Skip the almonds and go for something guests are sure to enjoy ... chocolate. Custom engrave chocolate bars to feature your wedding date information and your names. Or how about setting up a candy bar where guests can fill up their own goodie bags with favorite treats?
•.
R126976
• Plants: Send guests home with something they can plant, whether flower seeds, seedlings or a small houseplant. As your love grows, so will the plants in every guest’s home.
•.
• Let them eat cake: Inquire whether your baker can make miniature wedding cakes in the likeness of your larger one. Then everyone can take home a replica. • Personalized photo: One of the easiest ways for guests to remember your wedding is to have a photo reminder. Engraved frames with a photo of the happy couple will be classic gifts. ♥
Features wraparound interior balcony, outdoor balcony & exterior garden. Create your memorable event in Historic Downtown Salisbury! Appropriate ABC permits required
For more information call 704.633.5946
R126349
eford@salisburypost.com
poured two containers of salt on the flames to no avail and then forced her mother to leave the house, she said. Firefighters were still working in the house at 6:30 p.m. and had not determined the extent of damage, Salisbury Fire Department Battalion Chief Currie Butler said. The blaze was contained to the kitchen, Butler said. Firefighters were conducting salvage operations, covering furniture and forcing smoke from the home. Locke and Granite Quarry departments also responded. Located in the Fulton Heights neighborhood, the fire brought many residents to their sidewalks and front porches. A group of neighbors encircled Dick and Blackwell, and plans were under way to line up meals and donate clothing. “We’ll take care of her,” neighbor Pat Marsh said. Contact Emily Ford at 704797-4264.
If you offer bridal event planning, photography, venues for weddings, gowns, tuxedos, flower arrangements, music or any variety of bridal fair must haves call Karen Hurst 704-797-4242 to advertise on this page, Bridal Services. Publishes the second Sunday of each month.
ROWAN MUSEUM, INC. • 202 N. MAIN ST.
S44219
BY EMILY FORD
2 0011 0
Online for 2 weeks.
AREA
Sadie and Jack Russell terrier ready for good homes The Rowan County Animal Shelter has several animals waiting to be adopted and taken to a good home. Dog: Just a little ball of energy that’s full of affection is the best way to describe this female Jack Russell terrier. She arrived at the shelter as a stray so we do not have any further background information about her. We estimate her to be 2-3 years old. Cat: She is spayed, she is declawed, she is 3 years old and she is free to adopt. Her name is Sadie. When her owners could no longer afford to care for her they had to surrender her to the shelter. From rescued animals to those abandoned by owners who couldn’t afford them, and all others in between, the Animal Shelter has them all. Adoption fees are $70, a
To learn more about adopting a pet, call the shelter at 704-216-7768, or visit the shelter at 1465 Julian Road, Salisbury. You can also visit the shelter’s website at .us/animalshelter/. Photos by Fran Pepper.
SADIE
JACK RUSSELL TERRIER
down paymentonday-Friday, 11 a.m-4 p.m.; and Saturdays, 8-11 a.m. Office hours are MondayFriday, 11 a.m.-4:30 p.m. and Saturday, 8-11:30 a.m.
Back-to-School Gel Nails ...................$2999 Full Set......................$1999 Fill-in ........................$1299
SALISBURY POST Pedicure.........................$1999 Kid Spa ............................$1500 New Spa Head ............... $2999 Massage Available
FREE Hot Stone Massage with pedicure service
Eyelashes .............................$1999 Refreshments Served
R126205
8A • SUNDAY, SEPTEMBER 12, 2010
OPEN SUNDAY 12-5
1040 Freeland Dr., Ste 112 Salisbury, NC 28144
704.636.0390
Please bring ad to receive special pricing. Exp. 09/30/10
SC man charged after shooting deer decoy A South Carolina man used a spotlight early Saturday morning to freeze a deer and then shoot it, authorities say. The “deer” turned out to be a decoy, apparently planted by wildlife resource agents to deter the illegal practice of lighting deer at night to get an easy
shot. Andrew Scott Allison, 18, of Inman, S.C., is charged with night deer hunting and using false information to obtain a hunting license. The incident occurred in Rowan County. It wasn’t clear if a gun or crossbow was used to shoot the decoy.
salisburypost.com/news/blogs
Compassionate And Professional Attention For All Your Familyʼs Healthcare Needs.
• Care for general medical problems and management for adults and children, including immunizations, school and sports physicals, employment physicals, and yearly check-ups. • In-house lab testing and x-rays. • Minor surgical procedures, including treatment of skin cancers, warts, in-grown toenails, minor lacerations, etc. • Allergy testing and treatment • Evidence based treatment of diabetes, asthma, high blood pressure, thyroid disorders, high cholesterol and depression.
In connection with Vesta, Looking Glass Artists Collective and Rowan Regional Hospice are presenting the art show, “From the Heart of Hospice.” It will run from September 10 to September 30 and will feature works by hospice patients, staff members and their families. The exhibit can be viewed at the Looking Glass Artists Collective, Thursday through Saturday 12-4 at 405 North Lee Street, Salisbury.
R126979
Kevin B. Vanhoy, P.A.C., Ronald C. Huffman, M.D.
Accepting New Patients Monday - Friday 8:00am - 5:00pm
R125587
Saturday 8:00am - Noon
R126434
(closed 12 - 1:30pm for lunch)
Remarkable R emarkab able Medicine Meedicin ne is is Growing Growing in n Our Our Community Comm munity
R126981
SALISBURY POST
SUNDAY, SEPTEMBER 12, 2010 • 9A
A R E A / N AT I O N
BBB issues warning about 2012 Olympics scam The Better Business Bureau warns people to be on the lookout for e-mails that proclaim you have won tickets to the 2012 Olympics in London. Although the e-mail may look real, you have NOT won tickets to the Olympics. Every big event brings scammers out of the woodwork and the BBB is now seeing one of the first scams related to the 2012 Olympics which will be held in London. “This is yet another phishing scam,� said BBB President Tom Bartholomy. “All the scammers are doing is using a new ‘hook’ to lure you into giving them your personal information so they can steal your identity.� This phishing scam uses the U.K. National Lottery logo so that the e-mail looks legitimate. The bait is the prize announcement that “you are one of ten people who won a lot-
tery for tickets to the Olympics in London in 2012.� The trick is that real tickets to the 2012 Olympics will in fact be given away through the National Lottery, and they will also be sold through a ticket lottery system. So, this scam is similar enough to the actual ticket distribution system that it can fool you into thinking it may be real and get you to call or click on the links contained in the e-mail. If you call the number provided, you will be asked for enough personal information for the scammers to steal your identity. You may also be asked for a credit card number to pay taxes or fees to claim your “prize.� If you click on the links in the scam e-mail, your computer will almost certainly be infected with malware or spyware viruses that can
3rd Annual
Cleveland Heritage Week Cleveland Town Park
help the scammers find enough information on your computer hard drive to steal your identity. “It happens every day,â€? Bartholomy added. The BBB has some simple advice to keep you safe: • If you did not enter a lottery or contest, you did not win it. • NEVER click on links contained in e-mails you receive from someone you don’t know, even if the e-mail looks real. • NEVER give out personal information over the telephone or online to someone you don’t know. • Make sure your computer has up to date, anti-virus software because new scams are created every day. • When in doubt, check it out with the BBB. It’s fast, and free to check on companies out at.
300 Clement Street, Cleveland, NC 27013
Saturday October 16th – Noon-6PM: Entertainment, Skills & Trade Demonstrations, Great Food, Crafts, Vendors & Much More!
Saturday October 23rd – Noon-6PM: Old Timey Tractor Pull
ll Fa
le a S
Kendrick and the Swans,â€? He was one of the originals. named for Brown’s drummer. He was one of the roots, and Besides working with I’m one of his fruits.â€? Brown, Coleman also released numerous singles of his own during his singing career, including “Mashed Potato Manâ€? ONLY1200 and “The Boo Boo Song.â€? LE Coleman also performed KETS AVAILAB IC T with many other rhythm and blues legends, such as B.B. King and Jackie Wilson. He performed at venues all over the country, including the legendary Apollo Theater in New York. Coleman’s son, Tony, went on to become B.B. King’s drummer. “I can say that I’m proud to be his son,â€? Tony Coleman said of his father. “I’m proud to be working with his colleagues. • ww.salisburypost.com Lexington Memorial Hospital Foundation along with Honorary Chairmen
RICHARD CHILDRESS and BOB TIMBERLAKE Ticket Pri ce: $ 100
Present
No Leaf
Saturday, October 30, 2010 Lexington Historic Southern Railway Freight Depot 1:00 p.m. Arctic Cat ATV 4 Wheeler 1:40 p.m. Beretta AL391 12 Ga. Shotgun 1:05 p.m. 1,000 Cash Gift Certificate 1:45 p.m. 1,000 Bass Pro Shop t e G 1:10 p.m. TC Bone Collector Muzzleloader Rifle 1:55 p.m. Sun 20’ Pontoon Party Barge ToTracker t f e with 40 hp Motor & Trailer L s 2:00 p.m. Savagek y ! a t e D .17 HMR Rifle + BSA Scope 1:15 p.m. 1,000 Bass Pro Shop Gift3 Certificate c i T y l d n r p.m. 1,000 Cash i2:05 OStainless Steel Grill CaperFear 1:20 p.m. Wilmington Series B y l 2:15 p.m. Browning Citori 20 Ga. over & under Shotgun a E 1:25 p.m. Remington 700 VTRu .308 Rifle r o 2:20 p.m. 1,000 Cash 1:30 p.m. $1,000 CashY
Gutter
FREE FLOWING WATER CONTROL
J.A. FISHER
$
704-788-3217
R124211
A Specialty Contractor Since 1979 With Over 6000 Completed Jobs Salisbury
R126509
Sat. Oct. 9th
R&B pioneer King Coleman dies in Miami; was 78 MIAMI (AP) — Carlton “King� Coleman, a pioneer in American rhythm and blues, died Saturday morning from heart failure at a Miami hospice, his son said. He was 78. Coleman was known for providing the lead vocals on the 1959 hit “(Do The) Mashed Potatoes,� recorded with James Brown’s band. According to a 2003 Miami New Times article, Brown had initially planned to do the vocals himself, but a dispute with his record label made that impossible. To avoid any lawsuits from Brown’s label, a Miami producer had Coleman sing on the mostly instrumental track, while the group officially credited with the song was “Nat
Lots of Family Fun!
$
$
Kannapolis
$
$
2:25 p.m. 2010 Chevrolet Silverado Truck 4 x 4
1:35 p.m. Tracker 12’ Boat +5 hp Motor & Trailer
You Do Not have to be Present to Win ~ Early Bird Draws at 12:00 Noon - Drawings Begin at 1:00 p.m. You must be age 18+ to purchase a ticket - Ticket Price: $100 Phone: 336-238-4559 for information ~ Event doors open at 11:00 a.m. - Food, beverages, entertainment
Purchase your tickets by September 15th and be eligible for the Early Bird Drawings: Kawasaki Mule, Two Drawings for $1,000 Cash, Two Drawings for $1,000 Bass Pro Shop Gift Certificates. Early Bird winning tickets placed back in the drum and are eligible for main drawings.
R85721
Crafts • Games • Children’s Area • Heritage Village Area Performances: Sat. 3:30-5PM “TOO MUCH SYLVIAâ€?; Sun. 1:30-3PM “SUPERGLIDEâ€? & 4-5:30PM “LEGENDS OF BEACHâ€?
All proceeds benefit the expansion of physical therapy services at Lexington Memorial Hospital.
R126706
Tickets can be purchased at the following Lexington locations: Lexington Area Chamber of Commerce office, Uptown Lexington, Inc., Bob Timberlake Gallery, Childress Vineyards, Parrot Insurance, NewBridge Bank (main office in Lexington), Bank of North Carolina, BB&T, Team Rental, Heritage Custom Window Fashions, Lexington barbecue, Carolane Propane, Lanier Hardware, Lexington Tourism, and the Lexington YMCA. — OR CLIP and MAIL THE REQUEST FORM BELOW —
Make checks payable to: Lexington Memorial Hospital Foundation P.O. Box 1817 Lexington, NC 27293-1817
FOR INFORMATION CALL (704) 216-7803 How To Get The Perfect Shoe Fit
serves Granite Quarry, Rockwell, Faith and linking with the Salisbury Transit System
Zip
Number of Tickets Requested R124560
• Free transfer passes to Salisbury Transit & EXPRESS South • No charge for children under 5 years of age • Children under 12 must be accompanied by an adult • RTS information is available in alternative formats • TTY Users 1-800-735-2962 or 711
connects China Grove, Landis, Kannapolis and the CK Rider Transit System
SCHEDULE Monday - Friday
R122864
Salisbury to East Area Departure Times $0
6DOLVEXU\'HSRW6W+($/7+'(37 *UDQLWH4XDUU\*UDQLWH4XDUU\6$/((%<),6+(5(DVW5RZDQ5RFNZHOO6$/((%<),6+(5)DLWK*UDQLWH4XDUU\*UDQLWH4XDUU\+($/7+'(37 6DOLVEXU\'HSRW6W %8667$7,2162&,$/6(59,&(6)5('¡6%5,1./(<&(17(5<0&$/,%5$5<)22'/,21<0&$%$37,67&+85&+%5,1./(<&(17(5)5('¡662&,$/6(59,&(6%8667$7,21
30
at
State
ROWAN EXPRESS EAST
ROWAN EXPRESS SOUTH go to view the
Please Print Clearly Name Mailing Address City Phone Email Address Do you plan to attend â?‘Yes â?‘No
4XHVWLRQV"&RQWDFW5RZDQ([SUHVV&XVWRPHU6HUYLFH$W
R126088
10A • SUNDAY, SEPTEMBER 12, 2010
SALISBURY POST
Thank you to the generosity of sponsors, the Rowan Regional Medical Center Foundation's Annual Patrons Ball raised $87,000. The total proceeds benefit Rowan Regional Breast Center. The event was held on Saturday, September 11th from 7 p.m. to midnight at The Country Club of Salisbury. SPONSORS Thank you to the following sponsors for making this year’s Sponsorship Program very successful. SILVER SPONSORS Mid-Carolina Cardiology, PA
BRONZE SPONSORS F&M Bank Farrington Family Medical Center Gary L. Davis, CPA, PA Piedmont Natural Gas Robins & Morton Summersett Funeral Home, Inc. & Crematory
PEWTER SPONSORS Fisher Realty, Inc. F&M Bank Ketner Center, Inc. Miller Davis Studios, Inc.
UNDERWRITERS
The following businesses, physician groups and individuals haveunderwritten specific segments of the 2010 Patrons Ball.
OPPORTUNITY
UNDERWRITER
Library .................................................................Rowan Diagnostic Clinic, PA Bar – Ballroom...........................................................Taylor Clay Products, Inc. Bar – Club’s Main Bar.................................................................SunTrust Bank Bar – Main Dining Room..............Salisbury Anesthesia and PainConsultants, PA Elvis Impersonator ........................................Southeast Radiation Oncology, PA Front Lawn ..............................................................................TEAM Chevrolet Pianist ...........................................................Salisbury Ear, Nose, & Throat, PA Photography...................................................Salisbury Pediatric Associates, PA
Hors d’oeuvres .................................................................................Food Lion Ice Sculpture - Tent .............................................Salisbury Urological Clinic, PA Ice Sculpture – Ballroom...........................Piedmont Radiological Associates, PA Invitations ...................................................................Summit Developers, Inc. Menu ...............................................................................Dixon Hughes, PLLC Valet Parking ..........................................................Community Bank of Rowan Media ..................................................................................The Salisbury Post
PATRONS OF THE BALL
Thank you to the following individuals for making this year’s Patrons Participation Program successful. PLATINUM PATRONS GOLD PATRONS
Mr. and Mrs. Richard H. Smith, Jr. Mr. and Mrs. William C. Stanback Mr. and Mrs. Paul D. Weisler Mr. James G. Whitton
Mr. and Mrs. William M. Graham Mr. and Mrs. D. Kenan Smith
PEWTER PATRONS
Mr. and Mrs. Fred J. Stanback, Jr.
BRONZE PATRONS Mr. and Mrs. Burl Brady Mr. and Mrs. Robert L. Cook, Jr. Dr. and Mrs. Robert B. Fazia Mr. and Mrs. James M. Freeman Mr. and Mrs. George D. Glover Dr. and Mrs. Dennis L. Hill Mrs. Diane D. Hooper Mr. and Mrs. Rick D. Parker Mrs. Patricia P. Rendlemen Mr. and Mrs. Charles C. Ritchie Dr. and Mrs. David N. Smith
Mr. and Mrs. Clyde A. Bristow Dr. and Mrs. Thomas K. Carlton Mr. and Mrs. David S. Clay Mrs. Digna Freirich Dr. and Mrs. Myron R. Goodman Mr. and Mrs. Todd Hildebran Mr. and Mrs. Tim S. Messinger Mr. and Mrs. Edward P. Norvell Mr. and Mrs. Ronald L. Smith Dr. and Mrs. Thomas F. Trahey Mr. and Mrs. Robert L. Young, Sr.
CONTRIBUTORS Anderson Dental Group Ms. Frances D. Bearden Dr. and Mrs. Robert Bertram Mr. and Mrs. David Y. Bingham Mrs. Verna Bragg Mr. and Mrs. Thomas C. Childress Mr. Butch H. Clement & Ms. Elaine C. Hewitt Mr. and Mrs. Raymond Coltrain Mr. and Mrs. Keller V. Epting Mrs. Peggy N. Feezor Dr. and Mrs. Donald R. Fortner, Jr. Godley’s Garden Center & Nursery Mr. and Mrs. Richard P. Goodman Ms. Catherine C. Hall Mr. and Mrs. T. Michael Harrington Mr. and Mrs. Robert E. Ingram, Jr. Dr. and Mrs. Atlee R. Johnson Mr. and Mrs. William D. Kenerly
Mr. Ralph W. Ketner Dr. and Mrs. Elmer B. Lagg Mrs. Mary H. Messinger Dr. and Mrs. James T. Mitchell The Dr. Rev. and Mrs. David P. Nelson Mr. and Mrs. Charles A. Peacock Mr. and Mrs. Mark Perry Mrs. Jean Ray Mr. and Mrs. Richard R. Reamer Mr. and Mrs. Raymond Ritchie Mr. and Mrs. Hap Roberts, Jr. Mr. and Mrs. Don Sayers Mr. and Mrs. John M. Smith Mr. and Mrs. Max Spear Mr. and Mrs. Wilborn S. Swaim Mr. and Mrs. D. Robert Trundle Mrs. Louise R. Walser Mr. and Mrs. Charles D. White, Jr.
Patrons Ball Committee Chairmen Mr. Mrs. William M. Graham Mr. and Mrs. William F. Clark Mrs. Susan K. Cloninger Mr. and Mrs. Linn Evans Dr. and Mrs. Larry Gish Mr. and Mrs. Ted Goins
Mr. and Mrs. John Helms Mr. and Mrs. John Henderlite Miss Carrie Poole Mr. and Mrs. Timothy Proper Mr. and Mrs. D. Kenan Smith
Mr. and Mrs. Miles J. Smith Mr. and Mrs. David N. Smith Mr. and Mrs. Mark W. Wineka
Foundation Staff Monica W. Cameron Special Events & Gifts Coordinator
Devona F. Smith Administrative Specialist
R125441
Diane Dillon Hooper Executive Director
SPORTSSUNDAY SALISBURY POST
Ronnie Gallagher, Sports Editor, 704-797-4287 rgallagher@salisburypost.com
102 points Associated Press
WINSTON-SALEM — No m a t t e r W. Forest 54 who’s at Duke 48 q u a r t e r back, Wake Forest showed it can still do two things: Pile up points, and beat Duke. Backup Tanner Price threw three touchdown passes and ran for another, and the Demon Deacons held off the Blue Devils 54-48 on Saturday for its 11th straight victory in the series. Price was 12 of 19 for 190 yards with scoring passes covering 13, 38 and 23 yards and an early 1-yard scoring run
1B
Wolfpack beats Central Florida
Wake wins shootout with Blue Devils BY JOEDY MCCREARY
SUNDAY September 12, 2010
for Wake Forest (2-0, 1-0 Atlantic Coast Conference), which posted the first consecutive 50-point games in school history and won the secondhighest-scoring game in league history. “As a football coach, your worst nightmare is when you get into those shootouts,” Wake Forest coach Jim Grobe said. “Your comfort zone’s around your defense being stingy, and so I think it was a great TV game. If you’re sitting at home watching it, you’re loving it because that score keeps going up.” Wake Forest outgained the Blue Devils 500-487. During
Turnovers help N.C. State as QB Wilson goes just 10 of 30 BY JOEDY MCCREARY Associated Press
ASSOCIATeD PReSS
Ted Stachitas (13) of Wake Forest runs 23 yards for a See WAKE, 4B touchdown during first-quarter action.
ORLANDO — North Carolina N.C. State 28 S t a t e C. Florida 21 c a p i t a l ized on five turnovers, including a 43-yard interception return by C.J. Wilson, to beat Central Florida 28-21 on Saturday night. N.C. State quarter-
back
See N.C. STATE, 3B
MAYOR’S CUP
Things never change e didn’t expect much from winless Livingstone Saturday night — and we received even less. The Blue Bears have never been much of a match for Catawba in what has become an anual public flogDAVID ging. But SHAW raise your hand if you thought LC would master the art of self-destruction and suffer a 59-8 wipeout at Alumni Stadium. “Not me,” first-year coach Elvin James said outside the shell-shocked Livingstone dressing room. “I didn’t see this coming at all.” Who did? This game was 21-0 before they turned the lights on, fueled by a 65-yard fumble return for a touchdown and a 25-yard interception return for another score 90 seconds later. When Catawba’s Brandon Bunn hauled in a 12-yard TD pass late in the opening quarter, the guests had a 28-0 lead and four end zone appearances in less than seven minutes. And that, ladies and gentlemen, was more head-spinning than The Exorcist. “This team right here,” starting quarterback Curtis Edens said after the drilling was finished. “This team beat itself. I don’t blame anybody. I blame every-
W
See SHAW, 3B
wayne hinshaw/SALISBURY POST
Catawba's Brandon Sutton, on the bottom, and LJ McCray, left, force a Curtis edens fumble that Kewone Harris picked up and ran for a touchdown.
Catawba routs Blue Bears Livingstone was down 49-0 at halftime BY MIKE LONDON mlondon@salisburypost.com
Livingstone finally scored against Catawba with 3:39 remaining Catawba 59 when linebacker Bryan AyLivingstone 8 coth crashed through to record a safety. Wilson Cherry, Livingstone’s long-time public address announcer, is famous for the resounding, throaty growl he emits whenever the Blue Bears score, but this time he declined the opportunity. “Sorry, not gonna growl about a safety to make it 59-2,” Cherry explained. Livingstone didn’t make any noise, growls
or otherwise, at Alumni Stadium on Saturday. Catawba was comfortably ahead 49-0 at halftime and cruised 59-8. The Indians scored four TDs on defense. Catawba SID Jim Lewis wasn’t sure if that had ever happened before in the school’s long football history, but it’s a certainty it hasn’t happened frequently. If you laid a pregame bet on Catawba backup outside linebacker Jacob Hanes to be the Mayor’s Cup game’s leading scorer, you won a billion dollars. Hanes took two interceptions to the house. He edged Catawba kicker Thomas Trexler, who had eight PATS and a wayne hinshaw/SALISBURY POST
See CATAWBA, 3B
Homeboy Hamlin wins BY JENNA FRYER Associated Press
RICHMOND, Va. —
Bryan Aycoth (13) pressures Catawba QB Patrick Dennis.
Young Panthers-driv-
Giants open new $1.6 billion stadium against Carolina BY TOM CANAVAN Associated Press
ASSOCIATeD PReSS
See RACE, 3B Denny Hamlin celebrates.
EAST RUTHERFORD, N.J. — today when they face
New York in the Giants’ first regular-season NFL game at their new $1.6 billion, 82,500seat stadium. . The Giants are well aware of the recent history this game carries with it.
See PANTHERS, 5B
2B • SUNDAY, SEPTEMBER 12, 2010
TV Sports Sunday, Sept. 12 HIGH SCHOOL FOOTBALL 11:30 a.m. WMYT55 — Salisbury at West Rowan NFL FOOTBALL 1 p.m. FOX — Carolina at New York Giants CBS — Cincinnati at New England 4:15 p.m. FOX — Green Bay at Philadelphia 8:15 p.m. NBC — Dallas at Washington BASKETBALL Noon ESPN CLASSIC — Worlds, Bronze 2:30 p.m. ESPN — Worlds, Gold Medal game GOLF 2 p.m. NBC — PGA Tour, BMW Championship 4 p.m. TGC — LPGA, NW Arkansas Champ. MAJOR LEAGUE BASEBALL 2 p.m. WGN — Chicago Cubs at Milwaukee 3 p.m. TBS — N.Y. Yankees at Texas 8 p.m. ESPN — St. Louis at Atlanta TENNIS 1 p.m. ESPN2 — U.S. Open, women’s doubles 4 p.m. CBS — U.S. Open, men’s singles final WNBA BASKETBALL 3 p.m. ABC — Finals, Atlanta at Seattle
Prep tennis Salisbury 9, W. Davidson 0 Singles — Joy Loeblein (S) d. Melinda Athey 6-0, 6-0; Erika Nelson (S) d. Katie Allen 6-0, 6-0; Katelyn Storey (S) d. Rachel Tam 6-0, 6-0; Madeline Hoskins (S) d. Madyson Prevette 6-0, 6-0; Anna Page (S) d. Nicole Michael 6-1, 6-0; Anna Flynn (S) d. Felicia Daley 6-1, 6-0 Doubles — Loeblein-Nelson (S) d. Athey-Allen 8-0; Storey-Hoskins (S) d. Tam-Prevette 8-0; Page-Flynn (S) d. Michael-Daley 8-0
Prep football Saturday’s scores Ardrey Kell 32, Weddington 17 Charlotte Providence 41, Hopewell 21 Garinger 21, Hough 10 Matthews Butler 21, Richmond County 7 South Mecklenburg 42, Harding 12 West Charlotte 48, Independence 33 West Mecklenburg 13, East Meck 6
Friday’s games 1A Yadkin Valley North Rowan at Salisbury Mount Pleasant at South Stanly Chatham Central at Wake Christian North Moore at Jordan-Matthews 2A Central Carolina North Rowan at Salisbury Davie at Thomasville North Davidson at Lexington Central Davidson at McMichael West Davidson at Ledford East Davidson at Wheatmore 3A North Piedmont Carson at Robinson Cox Mill at East Rowan South Rowan at Central Cabarrus Mooresville at West Rowan North Iredell at Lake Norman 3A South Piedmont A.L. Brown at Kings Mountain Parkwood at NW Cabarrus Cox Mill at East Rowan South Rowan at Central Cabarrus Carson at Robinson Mt. Pleasant at South Stanly Porter Ridge at Hickory Ridge
College football Regional SAC Saturday’s games Mars Hill 41, St. Augustine’s 12 Catawba 59, Livingstone 8 Tusculum 54, Western Carolina 30 Valdosta State 45, Newberry 17 Lenoir-Rhyne 41, Davidson 13 Thursday’s games Concordia at Carson-Newman, 7 p.m. Newberry at Samford, 8 p.m. Next Saturday’s games Urbana at Tusculum, 1 p.m. Mars Hill at Charleston Southern, 1:30 p.m. UNC Pembroke at Wingate, 1:30 p.m. Brevard at Johnson C. Smith, 2 p.m. Shaw at Catawba, 7 p.m. Lenoir-Rhyne at North Greenville, 7 p.m.
CIAA Saturday’s games UNC Pembroke 42, St. Paul’s 14 New Haven 30, Lincoln 0 Virginia State 34, West Virginia State 21 J.C. Smith 45, West Virginia Tech 21 Mars Hill 41, St. Augustine’s 12 Catawba 59, Livingstone 8 Elon 55, Shaw 26 Winston-Salem St. 34, N.C. Central 27 Fayetteville State 27, Bowie State 7 Next Saturday’s games Chowan at Winston-Salem State, TBA Lincoln at Virginia Union, 1 p.m. Bowie State at Livingstone, 1 p.m. St. Paul’s at St. Augustine’s, 1:30 p.m. Brevard at J.C. Smith, 2 p.m. Fay. State vs. Elizabeth City State, 4 p.m. Virginia State at Norfolk State, 6 p.m. Catawba at Shaw, 7 p.m.
Southern Saturday’s games Appalachian St. 45, Jacksonville 14 Wofford 34, Charleston Southern 23 Furman 45, Colgate 15 Navy 13, Georgia Southern 7 Tusculum 54, Western Carolina 30 Samford 19, Northwestern State 7 Elon 55, Shaw 26 Jacksonville State 21, Chattanooga 17 The Citadel at Arizona, late Thursday’s game Newberry at Samford, 8 p.m. Next Saturday’s games Elon at Richmond, 1 p.m. N.C. Central at App. State, 3:30 p.m. Eastern Kentucky at Chattanooga, 6 p.m. W. Carolina at Gardner-Webb, 6 p.m. Ga. Southern at Coastal Carolina, 6 p.m. Presbyterian at The Citadel, 7 p.m. Union at Wofford, 7 p.m. Furman at South Carolina, 7 p.m.
ACC Saturday’s games Wake Forest 54, Duke 48 Kansas 28, Georgia Tech 25 James Madison 21, Virginia Tech 16 Oklahoma 47, Florida State 17 Boston College 26, Kent St. 13 Clemson 58, Presbyterian 21 Ohio State 36, Miami 24 Maryland 62, Morgan State 3 N.C. State 28, UCF 21 Virginia at USC, late Thursday’s game Cincinnati at N.C. State, 7:30 p.m. Next Saturday’s games Georgia Tech at North Carolina, Noon Maryland at West Virginia, Noon East Carolina at Virginia Tech, 1:30 p.m. Alabama at Duke, 3:30 p.m. BYU at Florida State, 3:30 p.m. Clemson at Auburn, 7 p.m. Wake Forest at Stanford, 11:15 p.m.
Conference USA Saturday’s games East Carolina 49, Memphis 27 Tulsa 33, Bowling Green 20 Southern Miss 34, Prairie View 7 Rice 32, North Texas 31 N.C. State 28, UCF 21 SMU 28, UAB 7 Mississippi 27, Tulane 13
SEC Saturday’s games South Carolina 17, Georgia 6 Florida 38, South Florida 14 Alabama 24, Penn State 3 LSU 27, Vanderbilt 3 Arkansas 31, Louisiana-Monroe 7 Oregon 48, Tennessee 13 Kentucky 63, Western Kentucky 28
Mississippi 27, Tulane 13 Next Saturday’s games Arkansas at Georgia, Noon Vanderbilt at Mississippi, 12:20 p.m. Alabama at Duke, 3:30 p.m. Florida at Tennessee, 3:30 p.m. Clemson at Auburn, 7 p.m. Akron at Kentucky, 7 p.m. Furman at South Carolina, 7 p.m. Mississippi State at LSU, 7 p.m.
Other scores EAST Connecticut 62, Texas Southern 3 Hawaii 31, Army 28 Pittsburgh 38, New Hampshire 16 Towson 47, Coastal Carolina 45, 5OT SOUTH Norfolk St. 23, N. Carolina A&T 14 Old Dominion 44, Campbell 13 MIDWEST Cincinnati 40, Indiana St. 7 Grand Valley St. 44, Hillsdale 41 Iowa 35, Iowa St. 7 Kansas St. 48, Missouri St. 24 Michigan 28, Notre Dame 24 Missouri 50, McNeese St. 6 Nebraska 38, Idaho 17 Purdue 31, W. Illinois 21 South Dakota 41, Minnesota 38 Wisconsin 27, San Jose St. 14 SOUTHWEST Baylor 34, Buffalo 6 Oklahoma St. 41, Troy 38 TCU 62, Tennessee Tech 7 Texas 34, Wyoming 7 Texas A&M 48, Louisiana Tech 16 FAR WEST Air Force 35, BYU 14 California 52, Colorado 7 Utah 38, UNLV 10 Washington 41, Syracuse 20 Washington St. 23, Montana St. 22
Notable sums N.C. State 28, UCF 21 N.C. State UCF
7 14 7 0 — 28 0 7 0 14 — 21 First Quarter NCSt—Haynes 4 run (Czajkowski kick), 2:38. Second Quarter NCSt—Davis 26 pass from R.Wilson (Czajkowski kick), 9:39. NCSt—Greene 21 run (Czajkowski kick), 3:26. UCF—McDuffie 93 kickoff return (Cattoi kick), 3:12. Third Quarter NCSt—C.Wilson 43 interception return (Czajkowski kick), 5:22. Fourth Quarter UCF—Godfrey 6 run (Cattoi kick), 14:19. UCF—Godfrey 1 run (Cattoi kick), 4:29. A—43,020. UCF NCSt Rushes-yards 40-134 34-95 Passing 105 213 10-30-0 17-29-3 Comp-Att-Int Return Yards 94 0 Punts-Avg. 10-33.7 6-42.7 1-0 3-2 Fumbles-Lost Penalties-Yards 7-36 5-30 INDIVIDUAL STATISTICS RUSHING—N.C. State, Greene 14-55, Haynes 10-49, R.Wilson 13-35, Team 3-(minus 5). UCF, Godfrey 10-53, J.Davis 16-32, Guyton 1-9, Calabrese 5-1, Weaver 2-0. PASSING—N.C. State, R.Wilson 10-30-0-105. UCF, Calabrese 10-18-2-106, Godfrey 7-10-0-107, Flores 0-1-1-0. RECEIVING—N.C. State, Bryan 3-35, Davis 2-38, Williams 2-15, J.Smith 1-7, Greene 1-6, Graham 1-4. UCF, Watters 6-88, Aiken 5-50, McDuffie 2-26, Newsome 1-29, Nissley 1-9, Guyton 1-6, J.Davis 1-5.
Wake Forest 54, Duke 48 Duke Wake Forest
14 21 3 10 — 48 7 28 6 13 — 54 First Quarter Wake—Stachitas 23 run (Newman kick), 11:13. Duke—Connette 4 run (Snyderwine kick), 7:37. Duke—Helfet 9 pass from Renfree (Snyderwine kick), 3:26. Second Quarter Wake—Givens 18 fumble return (Newman kick), 14:13. Wake—Price 1 run (Newman kick), 8:07. Duke—Vernon 70 pass from Renfree (Snyderwine kick), 7:52. Wake—Givens 81 pass from Ma.Williams (Newman kick), 7:39. Wake—Ma.Williams 13 pass from Price (Newman kick), 5:17. Duke—D.Scott 63 run (Snyderwine kick), 2:43. Duke—Kelly 13 pass from Renfree (Snyderwine kick), :41. Third Quarter Wake—Ma.Williams 38 pass from Price (run failed), 8:12. Duke—FG Snyderwine 46, 3:13. Fourth Quarter Wake—Dembry 23 pass from Price (Newman kick), 13:58. Duke—FG Snyderwine 38, 8:45. Wake—Brown 6 run (run failed), 2:53. Duke—Vernon 51 pass from Renfree (Snyderwine kick), 1:39. A—31,673. Duke Wake Rushes-yards 29-129 53-229 358 271 Passing Comp-Att-Int 28-44-3 13-24-2 INDIVIDUAL STATISTICS RUSHING—Duke, D.Scott 11-122, Connette 6-15, Snead 5-14, Hollingsworth 1-8, Thompson 2-1, Renfree 3-(minus 5), Team 1-(minus 26). Wake Forest, Stachitas 9-77, Price 10-56, J.Harris 12-50, Brown 6-29, Pendergrass 2-8, Adams 6-7, Bohanon 2-4, Givens 2-4, Team 4-(minus 6). PASSING—Duke, Renfree 28-44-3-358. Wake Forest, Price 12-19-1-190, Stachitas 0-4-1-0, Ma.Williams 1-1-0-81. RECEIVING—Duke, Kelly 10-73, Vernon 8-181, Varner 6-51, Helfet 2-17, D.Scott 1-31, Huffman 1-5. Wake Forest, Givens 4-159, Brown 4-30, Ma.Williams 2-51, Dembry 2-29, Campanaro 1-2.
App. State 45, J’Ville 14 Jacksonville 0 7 7 0 — 14 10 7 14 14 — 45 Appalachian St. First Quarter App—FG Vitaris 22, 1:38. App—Quick 41 pass from Presley (Vitaris kick), :05. Second Quarter Jckv—Small 30 pass from McGregor (Hostetler kick), 7:56. App—Quick 15 pass from Presley (Vitaris kick), 2:45. Third Quarter Jckv—Laster 2 run (Hostetler kick), 10:02. App—D.Moore 2 run (Vitaris kick), 5:45. App—Quick 41 pass from Presley (Vitaris kick), 1:48. Fourth Quarter App—Jorden 6 pass from Presley (Vitaris kick), 10:18. App—Jackson 3 run (Vitaris kick), 5:58. A—28,708. Jckv App Rushes-yards 25-76 55-292 Passing 181 328 Fumbles-Lost 0-0 6-2 ASU INDIVIDUAL STATISTICS RUSHING—Appalachian St., Presley 16-101, Jackson 7-49, Cadet 9-49, D.Moore 11-39, C.Baker 7-38, Chisholm 4-18, Hardee 1-(minus 2). PASSING— Appalachian St., Presley 20-31-0-285, Jackson 2-2-0-43. RECEIVING—Appalachian St., Quick 6-132, Jorden 3-43, Hardee 2-31, C.Baker 2-25, Cadet 2-24, Elder 2-18, Cline 2-9, Washington 1-32, Peacock 1-11, Moore 1-3.
ECU 49, Memphis 27 Memphis 3 7 7 10 — 27 East Carolina 28 7 7 7 — 49 First Quarter ECU—Ruffin 11 pass from D.Davis (Barbour kick), 10:59. ECU—Blacknall 46 interception return (Barbour kick), 9:37. Mem—FG Henriques 38, 6:20. ECU—Harris 5 pass from D.Davis (Barbour kick), 3:04. ECU—J.Williams 2 run (Barbour kick), :23. Second Quarter Mem—Ray 32 pass from R.Williams (Henriques kick), 13:40. ECU—D.Davis 1 run (Barbour kick), 11:13. Third Quarter Mem—Rucker 13 pass from R.Williams (Henriques kick), 4:19. ECU—D.Davis 8 run (Barbour kick), 1:05. Fourth Quarter Mem—Rhodes 35 pass from R.Williams (Henriques kick), 13:15. ECU—Bowman 5 pass from D.Davis (Barbour kick), 6:03.
SALISBURY POST
SPORTS Mem—FG Henriques 42, 1:01. A—48,123. Mem ECU 37-101 37-173 Rushes-yards Passing 312 252 Comp-Att-Int 21-31-1 28-40-0 4-2 1-0 Fumbles-Lost ECU INDIVIDUAL STATISTICS RUSHING— East Carolina, J.Williams 17-109, Ruffin 4-23, Dobson 2-19, Bowman 1-12, D.Davis 13-10. PASSING—ECU, D.Davis 27-38-0-244, Wornick 1-2-0-8. RECEIVING—East Carolina, Harris 6-54, J.Williams 6-50, Bodenheimer 4-43, Bowman 4-23, Lewis 3-26, Ruffin 2-32, Arrington 1-9, Price 1-8, Womack 1-7.
S. Carolina 17, Georgia 6
Ark—Wingo 35 pass from Mallett (Hocker kick), 3:23. A—55,705.
JMU 21, Virginia Tech 16
James Madison 0 7 7 7 — 21 7 6 3 0 — 16 Virginia Tech First Quarter VT—Boykin 9 pass from T.Taylor (Hazley kick), 3:24. Second Quarter VT—FG Hazley 30, 7:03. JMU—Sullivan 77 pass from Dudzik (Wright kick), 4:53. VT—FG Hazley 41, :19. Third Quarter VT—FG Hazley 28, 11:32. JMU—Dudzik 7 run (Wright kick), 4:06. Fourth Quarter JMU—Dudzik 12 run (Wright kick), 13:45.
Georgia 3 0 3 0— 6 South Carolina 7 7 0 3 — 17 First Quarter SC—Lattimore 2 run (Lanning kick), 6:58. Geo—FG Walsh 27, :38. Second Quarter SC—Lattimore 2 run (Lanning kick), 1:34. Third Quarter Geo—FG Walsh 26, 8:17. Fourth Quarter SC—FG Lanning 24, 1:12. INDIVIDUAL LEADERS RUSHING—Georgia, Ealey 19-75. South Carolina, Lattimore 37-182. PASSING—Georgia, A.Murray 14-21-0-192. South Carolina, Garcia 12-17-0-165. RECEIVING—Georgia, Durham 3-76. South Carolina, A.Jeffery 7-103, Lattimore 1-16
Gardner-Webb 3 14 7 7 7 — 38 Akron 14 7 10 0 6 — 37 Fourth Quarter GWb—Perry 13 pass from Browning (Gates kick), 5:05. Overtime Akr—Allen 9 run (kick blocked). GWb—Blount 4 run (Gates kick). G-W INDIVIDUAL LEADERS RUSHING—Gardner-Webb, Blount 18-69, PASSING—Gardner-Webb, Browning 18-28-0-207, Rock 7-15-1-83. RECEIVING—G-Webb, Perry 10-125
Michigan 28, N. Dame 24
Presbyterian Clemson
Michigan Notre Dame
CLEMSON INDIVIDUAL LEADERS RUSHING—Clemson, McDowell 9-86, D.Barnes 11-79, Boyd 6-25, J.Brown 1-23, Ellington 3-11, Harper 3-9. PASSING—Clemson, Parker 6-9-0-114, Boyd 4-9-1-87. RECEIVING—Clemson, Allen 2-66.
14 7 0 7 — 28 7 0 10 7 — 24 First Quarter ND—Crist 1 run (Ruffer kick), 11:19. Mich—Roundtree 31 pass from D.Robinson (Gibbons kick), 8:06. Mich—Hopkins 1 run (Gibbons kick), 1:26. Second Quarter Mich—D.Robinson 87 run (Gibbons kick), 1:51. Third Quarter ND—Jones 53 pass from Crist (Ruffer kick), 12:42. ND—FG Ruffer 24, 8:48. Fourth Quarter ND—Rudolph 95 pass from Crist (Ruffer kick), 3:41. Mich—D.Robinson 2 run (Broekhuizen kick), :27. INDIVIDUAL STATISTICS RUSHING—Michigan, D.Robinson 28-258, Smith 7-17, Shaw 5-12, Hopkins 1-1. Notre Dame, Allen 15-89, Montana 4-23, Crist 4-19, J.Gray 1-10, C.Wood 6-10, Riddick 2-3. PASSING—Michigan, D.Robinson 24-40-0-244. Notre Dame, Crist 13-25-1-277, Montana 8-17-1-104, Rees 0-2-1-0. RECEIVING—Michigan, Roundtree 8-82, Odoms 7-91, Stonum 4-33, Shaw 3-28, Grady 1-7, Smith 1-3. Notre Dame, Rudolph 8-164, Floyd 5-66, Jones 3-73, Riddick 2-39, Eifert 1-17, J.Gray 1-13, Allen 1-9.
Oklahoma 47, FSU 17 Florida St. Oklahoma
7 0 0 10 — 17 14 20 10 3 — 47 First Quarter Okl—Murray 1 run (O’Hara kick), 10:15. FSU—Thomas 1 run (Hopkins kick), 5:25. Okl—Broyles 18 pass from L.Jones (O’Hara kick), 1:44. Second Quarter Okl—Kenney 36 pass from L.Jones (O’Hara kick), 14:44. Okl—Hanna 46 pass from L.Jones (kick failed), 7:44. Okl—Murray 1 run (O’Hara kick), :28. Third Quarter Okl—Ratterree 7 pass from L.Jones (O’Hara kick), 8:46. Okl—FG O’Hara 39, 6:38. Fourth Quarter FSU—FG Hopkins 52, 11:57. Okl—FG O’Hara 38, 4:49. FSU—Easterling 47 pass from Manuel (Hopkins kick), :00. PASSING STATISTICS PASSING—FSU, Ponder 11-28-2-113, Manuel 4-8-0-109. Oklahoma, L.Jones 30-40-0-380, Allen 2-2-0-14.
Alabama 24, Penn State 3 Penn St. Alabama
0 0 0 3— 3 7 10 0 7 — 24 First Quarter Ala—Norwood 36 pass from McElroy (Shelley kick), 8:35. Second Quarter Ala—Dial 14 pass from McElroy (Shelley kick), 14:55. Ala—FG Shelley 31, 3:54. Fourth Quarter Ala—Richardson 1 run (Shelley kick), 14:10. PSU—FG Wagner 36, 9:47. A—101,821. PSU Ala 17 19 First downs Rushes-yards 31-127 34-180 Passing 156 229 3-1 1-1 Fumbles-Lost INDIVIDUAL STATISTICS RUSHING—Penn St., Royster 9-32, Redd 5-26, Kersey 1-24, Green 5-13, Bolden 6-12, Newsome 2-9, Smith 2-8, Zordich 1-3. Alabama, Richardson 22-144, Lacy 6-21, McElroy 5-8, Maze 1-7. PASSING—Penn St., Bolden 13-29-2-144, Newsome 1-1-0-12, Brown 0-1-1-0. Alabama, McElroy 16-24-0-229. RECEIVING—Penn St., Smith 5-47, Moye 3-69, Powell 2-9, Royster 2-(minus 6), Brown 1-20, Brackett 1-17. Alabama, J.Jones 4-49, Richardson 4-46, Hanks 3-52, Maze 2-28, Dial 2-18, Norwood 1-36.
Ohio State 36, Miami 24 Miami Ohio St.
7 10 0 7 — 24 3 23 10 0 — 36 First Quarter OSU—FG Barclay 24, 5:57. Mia—Miller 88 kickoff return (Bosher kick), 5:45. Second Quarter Mia—FG Bosher 51, 13:05. OSU—Saine 18 pass from Pryor (Barclay kick), 12:23. OSU—FG Barclay 41, 7:03. OSU—Herron 4 run (Barclay kick), 6:17. Mia—Benjamin 79 punt return (Bosher kick), 3:04. OSU—FG Barclay 21, 1:01. OSU—FG Barclay 24, :00. Third Quarter OSU—Pryor 13 run (Barclay kick), 10:16. OSU—FG Barclay 24, 1:29. Fourth Quarter Mia—Ford 9 pass from J.Harris (Bosher kick), 14:52. INDIVIDUAL LEADERS RUSHING—Miami, Berry 16-94. Ohio St., Pryor 20-113, Herron 14-66. PASSING—Miami, J.Harris 22-39-4-232. Ohio St., Pryor 12-27-0-233, Team 0-1-0-0. RECEIVING—Miami, Hankerson 7-90. Ohio St., Posey 4-105, Sanzenbacher 3-37.
Oregon 48, Tennessee 13 Oregon Tennessee
3 10 14 21 — 48 6 7 0 0 — 13 First Quarter Tenn—FG Lincoln 48, 11:13. Tenn—FG Lincoln 35, 8:53. Ore—FG Beard 37, 1:25. Second Quarter Tenn—Poole 1 run (Lincoln kick), 14:21. Ore—FG Beard 42, 2:56. Ore—Paulson 27 pass from Thomas (Beard kick), 1:04. Third Quarter Ore—James 72 run (Beard kick), 10:10. Ore—C.Harris 76 interception return (Beard kick), 6:27. Fourth Quarter Ore—Tuinei 29 pass from Thomas (Beard kick), 13:28. Ore—Barner 80 punt return (Beard kick), 11:39. Ore—Alston 2 run (Beard kick), 3:54. A—102,035. INDIVIDUAL STATISTICS LEADERS RUSHING—Oregon, James 16-134. Tennessee, Poole 23-162, D.Rogers 1-21. PASSING—Oregon, Thomas 17-32-0-202. Tennessee, Simms 15-29-1-151. RECEIVING—Oregon, Maehl 5-50. Tennessee, Moore 4-37, Z.Rogers 3-45.
Arkansas 31, La-Monroe 7 Louisiana-Monroe 0 0 0 7— 7 Arkansas 7 0 7 17 — 31 First Quarter Ark—Childs 19 pass from Mallett (Hocker kick), 5:48. Third Quarter Ark—Mallett 1 run (Hocker kick), 6:12. Fourth Quarter Ark—FG Hocker 26, 12:53. Ark—Childs 18 pass from Mallett (Hocker kick), 8:46. ULM—Ambrose 25 pass from Browning (Jabour kick), 5:12.
G-Webb 38, Akron 37 (OT)
Clemson 58, Presby. 21 0 0 7 14 — 21 21 21 10 6 — 58
NFL Regular season Thursday, Sept. 9 New Orleans 14, Minnesota 9 Sunday, Sept. 12 Miami at Buffalo, 1 p.m. Detroit at Chicago, 1 p.m. Indianapolis at Houston, 1 p.m. Denver at Jacksonville, 1 p.m. Cincinnati at New England, 1 p.m., CBS Carolina at N.Y. Giants, 1 p.m., FOX Atlanta at Pittsburgh, 1 p.m. Cleveland at Tampa Bay, 1 p.m. Oakland at Tennessee, 1 p.m. Green Bay at Philadelphia, 4:15 p.m., FOX Arizona at St. Louis, 4:15 p.m. San Francisco at Seattle, 4:15 p.m. Dallas at Washington, 8:20 p.m., NBC Monday, Sept. 13 Baltimore at N.Y. Jets, 7 p.m. San Diego at Kansas City, 10:15 p.m.
Minor Leagues South Atlantic Playoffs First Round (Best-of-3) Northern Division Wednesday: Lakewood 7, Hickory 0 Friday: Hickory 2, Lakewood 1 (10) Saturday: Lakewood 6, Hickory 0 Southern Division Wednesday: Greenville 8, Savannah 3 Friday: Greenville 5, Savannah 4
Major Leagues American League Saturday’s Games Tampa Bay 13, Toronto 1 Baltimore 5, Detroit 3 Kansas City 8, Chicago White Sox 2 Oakland 4, Boston 3 L.A. Angels 7, Seattle 4 Minnesota 1, Cleveland 0, 12 innings N.Y. Yankees at Texas, late Sunday’s Games Baltimore (Tillman 1-4) at Detroit (Verlander 15-8), 1:05 p.m. Minnesota (Slowey 11-6) at Cleveland (Talbot 9-11), 1:05 p.m. Tampa Bay (Niemann 10-6) at Toronto (Marcum 12-7), 1:07 p.m. Kansas City (O’Sullivan 2-5) at Chicago White Sox (Harrell 1-0), 2:05 p.m. N.Y. Yankees (Moseley 4-2) at Texas (Cl.Lee 10-8), 3:05 p.m. Seattle (J.Vargas 9-9) at L.A. Angels (Haren 2-4), 3:35 p.m. Boston (Beckett 4-4) at Oakland (Braden 9-11), 4:05 p.m.
National League Saturday’s Games Florida 4, Washington 1 N.Y. Mets 4, Philadelphia 3 San Diego 1, San Francisco 0 Atlanta 6, St. Louis 3, 12 innings L.A. Dodgers 6, Houston 3 Chicago Cubs 1, Milwaukee 0 Cincinnati 5, Pittsburgh 4, 10 innings Colorado 2, Arizona 1 Sunday’s Games Philadelphia (Oswalt 11-13) at N.Y. Mets (Niese 9-7), 1:10 p.m. Pittsburgh (Burres 3-3) at Cincinnati (Cueto 12-5), 1:10 p.m. Florida (Volstad 9-9) at Washington (Zimmermann 0-0), 1:35 p.m. L.A. Dodgers (Monasterios 3-5) at Houston (Figueroa 5-2), 2:05 p.m. Chicago Cubs (Coleman 1-1) at Milwaukee (Gallardo 11-7), 2:10 p.m. Arizona (I.Kennedy 9-9) at Colorado (J.Chacin 8-9), 3:10 p.m. San Francisco (Lincecum 13-9) at San Diego (Latos 14-5), 4:05 p.m. St. Louis (Lohse 2-7) at Atlanta (T.Hudson 15-7), 8:05 p.m.
Saturday’s boxes Rays 13, Blue Jays 1 r 0 0 0 0 0 0 0 1 0 0 0 0 0 0
h bi 0 0 3 0 0 0 0 0 0 0 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 0
1 7 1
Tampa Bay 000 612 040—13 Toronto 000 100 000— 1 Dp—Tampa Bay 1. Lob—Tampa Bay 6, Toronto 8. 2b—Jennings (1), Zobrist 2 (21), C.pena (16), Y.escobar (7). 3b—Bartlett (3), Crawford (12). Hr—Hawpe (2), Shoppach (4), Overbay (19). IP H R ER BB SO Tampa Bay Davis W,12-9 7 7 1 1 3 6 Wheeler 1 0 0 0 0 0 Ekstrom 1 0 0 0 0 0 Toronto Romero L,12-9 4 3 6 6 3 7 Mills 3 3 3 3 2 3 1 R.Lewis ⁄3 4 4 4 1 0 2 Purcey 1 ⁄3 0 0 0 1 3 HBP—by R.Romero (Crawford, Shoppach). WP—R.Romero, Purcey. PB—Shoppach, J.Molina.
Royals 8, White Sox 2 Kansas City ab r GBlanc cf 5 2 Maier rf 6 0 BButler dh 6 1 Kaaihu 1b 4 2 Betemt 3b 4 1 Gordon lf 4 1 B.Pena c 5 0 Getz 2b 5 1 YBtncr ss 4 0
Totals
Chicago h bi ab 3 1 Pierre lf 5 3 1 Vizquel 3b 3 1 0 Viciedo ph 1 3 0 Rios cf 4 3 1 Konerk 1b 3 2 1 MnRmr dh 4 2 2 Przyns c 4 1 1 Flowrs c 0 0 1 Kotsay rf 4 AlRmrz ss 4 Bckhm 2b 3 De Aza ph 1 43 818 8 Totals 36
Kansas City 121 Chicago 000
011 100
Athletics 4, Red Sox 3 Boston ab Scutaro 2b5 DMcDn rf 4 Nava ph 1 VMrtnz 1b 4 ABeltre 3b 3 EPtrsn pr 0 Lowell dh 4 D.Ortiz ph 1 Lowrie ss 4 Sltlmch c 4 Hall lf 4 Kalish cf 4 Totals 38
Oakland r h bi ab 1 1 1 Crisp cf 3 0 2 0 Barton 1b 3 0 0 0 KSuzuk c 3 1 2 0 Cust dh 4 0 2 1 M.Ellis 2b 3 0 0 0 Hermid rf 3 0 0 0 Carson rf 1 0 0 0 RDavis lf 3 1 1 0 Larish 3b 3 0 0 0 Tollesn 3b 0 0 0 0 Pnngtn ss 3 0 2 1 310 3 Totals 29
r 1 1 0 1 1 0 0 0 0 0 0
h bi 0 0 1 0 0 0 2 2 2 1 1 0 0 0 1 1 0 0 0 0 0 0
4 7 4
Boston 001 001 001—3 000 000 31x—4 Oakland E—Hall (11). Dp—Boston 1. Lob— Boston 11, Oakland 5. 2b—D.mcdonald (15), V.martinez (30), A.beltre (40), Lowrie (9), Kalish (7), Barton (31), Hermida (9). 3b—R.davis (3). Hr—Scutaro (11). Sb— Crisp (28), Barton (7). IP H R ER BB SO Boston Lackey L,12-10 7 6 3 3 0 6 2 D.Bard ⁄3 1 1 1 4 1 1 ⁄3 0 0 0 0 0 Okajima Oakland 8 2 2 3 5 Anderson W,5-6 7 Breslow H,14 1 0 0 0 0 1 2 1 1 0 3 Bailey S,23-26 1
Reds 5, Pirates 4 (10) Pittsburgh ab AMcCt cf 3 Tabata lf 4 NWalkr 2b 4 Jones 1b 3 Alvrez 3b 4 Doumt rf-c 4 Cdeno ss 4 CSnydr c 2 Bwker rf 2 Morton p 2 Resop p 0 DlwYn ph 1 Meek p 0 Moss ph 1 JThms p 0 Totals 34
r 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 4
Cincinnati h bi ab 0 0 BPhllps 2b 4 2 1 OCarer ss 5 1 2 Votto 1b 3 0 0 Rolen 3b 4 0 0 Gomes lf 4 0 0 RHrndz c 2 1 0 Valaika pr 0 0 0 FCordr p 0 1 1 Stubbs cf 3 0 0 Cairo rf 2 0 0 Heisey rf 1 0 0 Volquez p 2 0 0 Alonso ph 1 0 0 Chpmn p 0 0 0 Hanign ph-c1 5 4 Totals 32
r h bi 0 0 0 0 1 0 1 1 1 2 2 0 1 2 0 0 1 1 0 0 0 0 0 0 1 2 1 0 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 5 10 5
0—4 Pittsburgh 000 000 040 Cincinnati 010 000 201 1—5 No outs when winning run scored. E—Alvarez (13). Dp—Pittsburgh 2. Lob—Pittsburgh 2, Cincinnati 7. 2b—Bowker (4), Rolen 2 (33), Stubbs (18), Heisey (9). Hr—Votto (33). Sb—A.mccutchen (31), Tabata (17). Cs—N.walker (3). Sf—R.hernandez, Stubbs, Cairo. IP H R ER BB SO Pittsburgh Morton 61⁄3 6 3 3 1 2 2 Resop ⁄3 0 0 0 0 0 Meek H,14 1 1 0 0 1 2 Hanrahan Bs,4-8 1 2 1 1 1 0 J.thomas L,0-1 0 1 1 1 0 0 Cincinnati Volquez 7 1 0 0 1 10 2 Masset H,18 ⁄3 3 4 4 1 1 1 1 0 0 0 2 Chapman BS,1-1 1 ⁄3 F.cordero W,6-4 1 0 0 0 0 0 J.Thomas pitched to 1 batter in the 10th. HBP—by Morton (R.Hernandez).
Padres 1, Giants 0
Schedule
Tampa Bay Toronto ab r h bi ab BUpton cf 3 1 0 0 FLewis rf 3 Jnngscf 2 1 1 0 YEscor ss 4 Bartlett ss 4 2 1 1 JMcDnl ss 0 Wheelr p 0 0 0 0 JBautst 3b 3 Ekstrm p 0 0 0 0 JHoffpr 3b 0 Crwfrd lf 3 1 1 2 V.Wells cf 3 Joyce lf 1 0 0 1 Wise ph-cf 1 Lngori 3b 4 0 1 0 Overay 1b 4 Ayar 3b 0 0 0 0 A.Hill 2b 3 Zobrist 1b 4 2 2 2 McCoy 2b 1 CPena 1b 3 1 1 1 Lind dh 3 Brignc ss 1 0 0 0 JMolin c 3 Rdrgz 2b 4 1 0 0 Arencii c 1 Hawpe rf 5 2 2 4 Snider lf 4 Shppch c 3 2 1 2 Totals 37131013 Totals 33
E—Y.betancourt (16). Dp—Chicago 1. Lob—Kansas City 13, Chicago 9. 2b— G.blanco (5), Betemit (18), Gordon (8), B.pena (8), Konerko (29). 3b—G.blanco (2). Hr—Konerko (34). Sb—Getz (14), Rios (33). Sf—Y.betancourt. IP H R ER BB SO Kansas City Davies W,8-9 6 5 1 1 2 5 2 3 1 1 0 2 Meche Soria 1 0 0 0 0 1 Chicago Jackson L,3-1 5 13 6 6 1 3 21⁄3 4 2 2 3 3 T.Pena 2 ⁄3 0 0 0 0 0 Linebrink 1 1 0 0 0 1 G.Infante E.Jackson pitched to 2 batters in the 6th. WP—E.Jackson, T.Pena.
r 0 0 0 0 2 0 0 0 0 0 0 0 2
020—8 010—2
h bi 0 0 0 0 0 0 1 0 2 1 1 0 2 0 0 0 0 0 1 1 1 0 0 0 8 2
San Francisco San Diego ab ab r h bi ATorrs cf 4 0 0 0 Denorfi cf 4 Snchz 2b 3 0 0 0 Eckstn 2b 3 Sndovl ph 1 0 0 0 Ludwck rf 3 A.Huff 1b 3 0 1 0 Venale rf 0 Ford pr 0 0 0 0 AdGnzl 1b 3 Posey c 4 0 0 0 MTejad ss 3 JGuilln rf 3 0 1 0 Salazar lf 2 Burrell lf 1 0 0 0 Cnghm lf 1 Uribe 3b 3 0 1 0 Headly 3b 3 Renteri ss 3 0 0 0 Torreal c 3 Bmgrn p 2 0 0 0 Stauffr p 1 Fntent ph 1 0 0 0 Hairstn ph 1 Stairs ph 1 Totals 28 0 3 0 Totals 28
r 0 0 0 0 0 0 0 0 0 1 0 0 0 1
h bi 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 2 1 0 0 0 0 1 0 5 1
San Fran 000 000 000—0 San Diego 001 000 00x—1 Dp—San Francisco 1, San Diego 2. Lob— San Francisco 4, San Diego 3. 2b—J.guillen (4). Hr—Torrealba (5). Cs—Ford (1). IP H R ER BB SO San Francisco Bumgarner L,5-5 7 3 1 1 0 4 R.Ramirez 1 2 0 0 0 0 San Diego 3 0 0 2 5 Stauffer W,4-3 6 Gregerson H,34 1 0 0 0 0 2 1 0 0 0 0 2 Adams H,31 0 0 0 0 1 H.bell S,40-43 1 HBP—by H.Bell (A.Huff).
Marlins 4, Nationals 1 Florida
Washington h bi ab 2 2 Espinos 2b 3 1 1 Dsmnd ss 4 1 0 Zmrmn 3b 4 0 0 A.Dunn 1b 4 2 0 Berndn lf 4 1 0 Morse rf 3 1 0 Morgan cf 3 0 0 WRams c 3 0 0 Maxwll pr 0 0 0 Batista p 0 0 0 Clipprd p 0 0 0 Marqus p 1 AlGnzlz ph 1 WHarrs ph 1 36 4 8 3 Totals 31
ab Bnifac 3b 5 Morrsn lf 5 HRmrz ss 4 Uggla 2b 3 Tracy 1b 4 Stanton rf 4 Maybin cf 3 BDavis c 4 AnSnch p 3 Veras p 0 Csns ph 1 Hensly p 0 Totals
r 1 0 0 0 1 1 1 0 0 0 0 0
r 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1
h bi 0 0 0 0 2 0 0 0 0 0 1 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 5 1
Florida 000 020 011—4 Washington 000 000 010—1 E—Ani.sanchez (4), A.dunn 2 (10). Dp— Florida 1, Washington 1. Lob—Florida 7, Washington 4. 2b—Bonifacio (6), Morse (10), W.ramos (2). 3b—Maybin (3). Sb— Bonifacio (8), B.davis (1). IP H R ER BB SO Florida 4 1 1 0 4 Snchez W,12-9 72⁄3 1 Veras H,15 ⁄3 0 0 0 0 0 Hensley S,2-5 1 1 0 0 1 1 Washington Marquis L,2-8 6 5 2 2 1 8 Stammen 1 2 1 1 0 2 Balester 1 0 0 0 1 2 1 ⁄3 1 1 0 0 0 Batista 2 Clippard ⁄3 0 0 0 0 2 Stammen pitched to 2 batters in the 8th. WP—Balester 2. PB—W.Ramos.
Braves 6, Cardinals 3 (12) St. Louis ab Shmkr 2b 3 Greene ph 0 Frnkln p 0 Winn ph 1 McCllln p 0 Miles 2b 0 Jay rf 3 Feliz 3b 2 Pujols 1b 5 Hollidy lf 5 Rasms cf 4 FLopez rf 4 YMolin c 5 Westrk p 2 DReyes p 0 Motte p 0 Stavinh rf 3 MBggs p 0 B.Ryan ss 5 Totals 42
r 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 3
Atlanta h bi ab 1 0 OInfant 2b 5 0 0 Heywrd rf 4 0 0 Prado 3b 5 0 0 McCnn c 6 0 0 D.Lee 1b 3 0 0 Ankiel cf 1 0 0 McLoth cf 2 0 0 Venters p 0 1 3 Moylan p 0 1 0 Wagner p 0 0 0 Saito p 0 1 0 Conrad ph 1 0 0 Frnswr p 0 0 0 Kimrel p 0 0 0 Hinske ph 1 0 0 AlGnzlz ss 6 1 0 MeCarr lf 5 0 0 Hanson p 3 2 0 Fremn 1b 2 7 3 Totals 44
r h bi 0 2 0 1 1 1 2 2 0 0 2 0 0 1 0 1 0 0 0 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 3 0 0 0 0 0 0 0 0 0 6 11 6
St. Louis 000 002 010 000—3 Atlanta 100 010 100 003—6 One out when winning run scored. E—Prado (10), Hanson (3). Dp—St. Louis 1. Lob—St. Louis 6, Atlanta 12. 2b— Pujols (34), D.lee (28). 3b—Mclouth (1). Hr—Heyward (17), Ale.gonzalez (5). Cs— Pujols (4), O.infante (6). S—F.lopez. IP H R ER BB SO St. Louis Westbrook 6 7 2 2 5 3 2 ⁄3 1 1 1 0 1 D.Reyes 1 ⁄3 1 0 0 1 1 Motte Franklin 2 0 0 0 0 3 McClellan 2 0 0 0 1 1 2 3 3 1 1 M.boggs L,2-3 1⁄3 Atlanta Hanson 7 5 2 2 0 5 1 ⁄3 1 1 0 0 0 Venters H,20 0 0 0 0 0 Moylan Bs,3-4 2⁄3 Wagner 1 0 0 0 1 1 Saito 1 0 0 0 0 0
1 1 0 0 0 0 Farnsworth Kimbrel W,3-0 1 0 0 0 0 2 HBP—by Venters (Greene). WP—Westbrook. PB—Y.Molina.
Mets 4, Phillies 3 Philadelphia ab r Victorn cf 4 1 Polanc 3b 4 1 Utley 2b 3 0 Hward 1b 4 0 Werth rf 4 0 Ibanez lf 4 0 Schndr c 3 0 MSwny ph 1 0 Mayrry pr 0 0 WValdz ss 4 0 Kndrck p 1 0 Dobbs ph 1 0 Gload ph 1 1 C.Ruiz ph 1 0 Totals 35 3
New York h bi ab 1 1 JosRys ss 4 1 0 JFelicn rf 4 1 0 Pagan cf 4 1 2 DWrght 3b 2 0 0 I.Davis 1b 4 2 0 Thole c 4 1 0 Duda lf 2 1 0 J.Arias ph 0 0 0 Carter ph 0 0 0 NEvns pr-lf 1 0 0 LHrndz 2b 3 0 0 Pelfrey p 3 1 0 0 0 9 3 Totals 31
r 1 2 1 0 0 0 0 0 0 0 0 0
h bi 1 1 2 0 1 0 1 0 4 3 1 0 0 0 0 0 0 0 0 0 0 0 1 0
4 11 4
Philadelphia 000 000 030—3 New York 101 000 20x—4 E—Ibanez (2), I.davis (8). Dp—Philadelphia 3, New York 2. Lob—Philadelphia 6, New York 10. 2b—M.sweeney (2), Gload (7), I.davis (29). Hr—Jos.reyes (9). Sb— Jos.reyes (29). S—L.castillo. H R ER BB SO IP Philadelphia 5 2 2 2 1 K.kendrick L,9-9 5 Herndon 0 1 0 0 0 0 1 ⁄3 1 0 0 0 1 Bastardo 2 2 2 2 1 Contreras 11⁄3 J.Romero 0 2 0 0 0 0 1 Durbin ⁄3 0 0 0 0 1 Madson 1 0 0 0 2 0 New York 1 6 2 2 0 5 Pelfrey W,14-9 7 ⁄3 0 1 1 1 0 0 Parnell 1 0 0 0 0 P.feliciano H,17 1⁄3 1 Acosta H,1 ⁄3 0 0 0 0 1 Takahashi S,6-6 1 1 0 0 0 0 Parnell pitched to 1 batter in the 8th. Herndon pitched to 1 batter in the 6th. J.Romero pitched to 2 batters in the 7th. HBP—by Pelfrey (Utley).
Cubs 1, Brewers 0 Chicago ab JeBakr 3b 4 Castro ss 4 Byrd cf 4 Soto c 4 Nady 1b 3 Fukdm rf 3 ASorin lf 2 Fuld lf 0 DeWitt 2b 3 Dmpstr p 2 Colvin ph 1 Totals 30
r 0 0 0 0 1 0 0 0 0 0 0 1
Milwaukee h bi ab 2 0 Weeks 2b 4 0 0 Hart rf 3 1 0 Braun lf 4 0 0 Fielder 1b 4 1 1 McGeh 3b 3 0 0 L.Cain cf 3 0 0 AEscor ss 4 0 0 Kottars c 3 0 0 RaWolf p 2 0 0 Inglett ph 0 0 0 CGomz pr 0 4 1 Totals 30
r 0 0 0 0 0 0 0 0 0 0 0 0
h bi 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 3 0
000 000 100—1 Chicago Milwaukee 000 000 000—0 Dp—Milwaukee 1. Lob—Chicago 3, Milwaukee 7. 2b—Je.baker (11). Hr—Nady (6). Sb—C.gomez (12). IP H R ER BB SO Chicago Dmpstr W,13-10 7 3 0 0 2 8 2 Cashner H,12 ⁄3 0 0 0 1 2 1 ⁄3 0 0 0 0 1 Marshall H,19 0 0 0 0 1 Marmol S,30-35 1 Milwaukee Ra.wolf L,11-11 8 4 1 1 1 6 Jeffress 1 0 0 0 0 0 HBP—by Cashner (Inglett).
Dodgers 6, Astros 3 Los Angeles ab r Furcal ss 3 0 Theriot 2b 5 0 Blake 3b 5 1 Kemp cf 3 0 Gions lf 4 1 Kuo p 0 0 Lindsy 1b 3 0 Sherrill p 0 0 Belisari p 0 0 Oeltjen lf 0 1 RJhnsn rf 4 2 A.Ellis c 3 1 Ely p 2 0 Mitchll 1b 1 0 Loney 1b 1 0 Totals 34 6
Houston h bi ab 0 0 Bourn cf 3 0 0 Kppngr 2b 4 1 1 Pence rf 4 0 0 Ca.Lee lf 4 2 0 Blum 3b 3 0 0 Wallac 1b 4 0 0 AngSnc ss 4 0 0 JaCastr c 2 0 0 Michals ph 1 0 0 WRdrg p 1 2 1 Bogsvc ph 1 1 1 Lndstr p 0 0 0 Lyon p 0 0 0 Byrdak p 0 1 1 Fulchin p 0 7 4 Totals 31
r 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 3
h bi 1 1 2 1 0 0 0 0 0 0 1 1 2 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 3
Los Angeles 000 300 003—6 000 120 000—3 Houston E—Lyon (1), Wallace (3). Dp—Los Angeles 1. Lob—Los Angeles 6, Houston 4. 2b—Loney (39), Ang.sanchez (9). 3b— Bourn (6). Hr—Blake (15), Wallace (2). Sb—Theriot 2 (20), Re.johnson (2). S—A.ellis, W.rodriguez. IP H R ER BB SO Los Angeles 6 6 3 3 1 4 Ely 1 ⁄3 1 0 0 0 0 Sherrill 2 Belisario ⁄3 0 0 0 0 1 1 0 0 0 0 0 Jansen W,1-0 1 0 0 0 1 2 Kuo S,9-10 Houston W.Rodriguez 7 5 3 3 3 10 Lindstrom 1 0 0 0 0 1 Lyon L,6-6 0 1 3 2 1 0 1 Byrdak ⁄3 1 0 0 0 0 2 ⁄3 0 0 0 0 1 Fulchino Lyon pitched to 3 batters in the 9th. WP—Kuo.
Rockies 2, D’backs 1 Arizona ab S.Drew ss 4 TAreu 3b 4 KJhnsn 2b3 CYoung cf 4 AdLRc 1b 4 Monter c 4 J.Upton pr 0 Allen lf 1 Rorts ph-lf 1 MrRynl ph 0 GParra rf 4 RLopez p 2 Church ph 1 Totals 32
r 0 0 0 0 0 0 0 1 0 0 0 0 0 1
Colorado h bi ab 1 1 EYong 2b 3 1 0 Barmes 2b 0 1 0 Fowler cf 3 0 0 Tlwtzk ss 4 1 0 Giambi 1b 3 1 0 Helton 1b 0 0 0 S.Smith rf 3 1 0 CGnzlz lf 0 1 0 Mora 3b 4 0 0 Splrghs lrf 3 0 0 Olivo c 3 1 0 Jimenz p 2 0 0 RBtncr p 0 8 1 Totals 28
r 0 0 0 0 0 0 0 0 1 1 0 0 0 2
h bi 2 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 2 0 1 0 1 1 0 0 0 0 8 2
Arizona 000 010 000—1 000 000 20x—2 Colorado Dp—Arizona 2. Lob—Arizona 8, Colorado 7. 2b—S.drew (30), T.abreu (9), S.smith (18), Spilborghs (19). Sb—J.upton (16). Cs—K.johnson (7). S—K.johnson, R.lopez, Fowler. Sf—J.herrera. IP H R ER BB SO Arizona R.lopez L,5-14 61⁄3 7 2 2 1 4 2 ⁄3 0 0 0 0 0 Hampton Vasquez 1 1 0 0 2 1 Colorado Jimenez 6 6 1 1 1 8 Reynolds W,1-0 1 1 0 0 0 1 Betancourt H,20 1 0 0 0 0 2 Street S,18-22 1 1 0 0 1 2 WP—Jimenez.
Auto racing Sprint Cup Air Guard 400, Richmond (Start position in parentheses) Name followed by laps & driver rating 1. (14) Denny Hamlin, 400 laps, 141.5 2. (32) Kyle Busch, 400, 110.4 3. (11) Jimmie Johnson, 400, 120.9 4. (6) Joey Logano, 400, 100.1 5. (13) Marcos Ambrose, 400, 100.1 6. (4) Clint Bowyer, 400, 122.9 7. (2) Juan Pablo Montoya, 400, 110.8 8. (3) A J Allmendinger, 400, 108.9 9. (20) Kevin Harvick, 400, 92.2 10. (1) Carl Edwards, 400, 105.8 11. (23) Ryan Newman, 400, 88.2 12. (22) Jeff Gordon, 400, 78.7 13. (25) Jeff Burton, 400, 84.9 14. (12) Matt Kenseth, 400, 95.8 15. (8) Brad Keselowski, 399, 79.6 16. (15) Tony Stewart, 399, 87.6 17. (34) Jamie McMurray, 399, 74 18. (21) Kurt Busch, 399, 79.2 19. (5) David Reutimann, 398, 74.3 20. (19) Mark Martin, 398, 66.1 21. (18) Casey Mears, 398, 66.7 22. (29) Martin Truex Jr., 398, 62.7 23. (26) David Ragan, 398, 59 24. (31) Scott Speed, 398, 55.2 25. (17) Regan Smith, 398, 67.5 26. (7) Paul Menard, 397, 72.8 27. (36) Elliott Sadler, 397, 47.7 28. (33) Sam Hornish Jr., 397, 54.5 29. (10) Kasey Kahne, 396, 57.9 30. (27) Dave Blaney, 396, 48.4 31. (42) Mattias Ekstrom, 396, 41.5 32. (24) Greg Biffle, 395, 53 33. (28) Landon Cassill, 395, 43.5 34. (9) Dale Earnhardt Jr., 394, 50.3 35. (38) Travis Kvapil, 393, 35.1 36. (16) Jeff Green, 393, 34 37. (39) David Gilliland, 393, 31.6 38. (40) Tony Raines, 392, 33.8 39. (43) Bobby Labonte, electric, 324, 44.1 40. (37) Terry Labonte, accident, 143, 27 41. (41) Kevin Conway, brakes, 118, 27.9 42. (30) Joe Nemechek, rear gear, 61, 32.4 43. (35) Jason Leffler, brakes, 30, 26.8 Top 12 in Points 1. D.Hamlin, 5,060; 2. J.Johnson, 5,050;
Padres remain in first Associated Press
SAN DIEGO — Tim Stauffer threw six sparkling innings, Yorvit Torrealba homered in the third and the San Diego Padres beat San Francisco 1-0 to stay in first in the NL West. The Padres (80-61) snapped a virtual tie for the top spot in the division. Stauffer, the club’s long reliever, made just his third start of the season. He yielded three hits and pitched out of his only jam in the second. Braves 6, Cards 3 (12) ATLANTA — Alex Gonzalez hit a three-run homer in the 12th inning and the Braves moved into a tie for the NL East lead. The Braves improved their major league-best home record to 51-20. Mets 4, Phillies 3 NEW YORK — Mike Pelfrey was dominant into the eighth to earn his careerhigh 14th victory, and the Mets stopped the Phillies’ four-game winning streak. Marlins 4, Nationals 1 WASHINGTON — Anibal Sanchez remained unbeaten against Washington, allowing four hits in 72⁄3 innings to beat the Nationals for the fifth straight time. Dodgers 6, Astros 3 HOUSTON — Houston reliever Brandon Lyon’s threw away a bunt for a tiebreaking two-run error in a three-run ninth inning. Reds 5, Pirates 4 (10) CINCINNATI — Joey Votto led off the bottom of the 10th with his 33rd homer, sending the Reds to a wild win that extended their NL Central lead to a daunting seven games. Neil Walker’s two-run single past Aroldis Chapman completed Pittsburgh’s rally to a 4-3 lead in the eighth. Joel Hanrahan blew the save chance, giving up a tying double by Chris Heisey in the ninth. Cubs 1, Brewers 0 MILWAUKEE — Ryan Dempster struck out eight in seven crisp innings, earning his 100th career win, and Xavier Nady homered. Rockies 2, D’backs 1 DENVER — Pinch-hitter Jonathan Herrera’s sacrifice fly off Mike Hampton broke a seventh-inning tie. AMERICAN LEAGUE Rays 13, Blue Jays 1 TORONTO — Brad Hawpe hit a grand slam and Wade Davis won his seventh straight decision. Royals 8, White Sox 2 CHICAGO — Kyle Davies pitched six solid innings, and the Royals roughed up Edwin Jackson on their way to 18 hits. Orioles 5, Tigers 3 DETROIT — Adam Jones had four hits and Jeremy Guthrie pitched seven shutout innings. Twins 1, Indians 0 (12) CLEVELAND — Jim Thome hit his 587th homer, passing Hall of Famer Frank Robinson for eighth place on the career list, to lift the Minnesota Twins over the Cleveland Indians in 12 innings. Thome hit a 2-0 pitch from Justin Germano (0-2) into the Cleveland bullpen in center field, snapping the Twins’ 21-inning scoreless streak. It was the only extra-base hit of the game. Both clubs had eight hits. Athletics 4, Red Sox 3 OAKLAND, Calif. — Rajai Davis hit a tiebreaking RBI triple in the seventh inning and Andrew Bailey struck out David Ortiz with the tying run on second to end the game. Adrian Beltre doubled in Victor Martinez with two out in the ninth to get Boston within one, but pinch-hitter Ortiz looked at a called third strike, giving Bailey his 23rd save in 26 opportunities this season. Angels 7, Mariners 4 ANAHEIM, Calif. — Hideki Matsui homered and Torii Hunter had four RBIs to lead the Los Angeles Angels to a victory over Felix Hernandez and Seattle. Ervin Santana (16-9) tied a career high for wins, allowing three runs and five hits over 71⁄3 innings.
SALISBURY POST
U.S. in final vs. Turkey
RACE FROM 1B er field just 30 laps into Saturday night when start.
SUNDAY, SEPTEMBER 12, 2010 • 3B
SPORTS
Associated Press
ASSOCIATED PRESS
Roger Federer won’t face Rafael Nadal.
Federer upset Associated Press
NEWseeded. With the crowd in Arthur Ashe Stadium trying to will Federer to victory — probably because of the tantalizing prospect of a final between him and Nadal — the owner of a record 16 Grand Slam ti-
tlesold Spaniard also can become the seventh man in tennis history to own at least one championship from each Grand Slam tournament. “I won’t watch,” Federer said, “but I hope he wins.”
ISTANBUL —.” Durant soared over defenders or stepped away from them for 3-pointers, scoring 17 in the first quarter to stake the Americans to an early lead that was never seriously challenged. He went on to surpass Carmelo Anthony’s single-game record of 35 points and raise his average in the tournament to 22.1, which would be the best ever by a U.S. player. “I’ve seen him score 45, 35, back-toback,” guard and NBA teammate Russell Westbrook said. “It doesn’t surprise me at all what he’s been doing.” More importantly, Durant guaranteed the Americans a chance at their first world title since 1994. They will play today against Turkey, which beat Serbia 83-82 in the other semifinal.
GOLF LEMONT, Ill. — Ryan oneshot lead over Dustin Johnson (68), Matt Kuchar (70) and Charlie Wi (70). Tiger Woods finally broke par with a 3-under 68, but he needed much more. Woods was tied for 22nd at even-par 213, some seven shots behind where he needs to
ASSOCIATED PRESS
Kevin Durant reacts during the semifinal win against Lithuania. finish to advance to the FedEx Cup finale. Otherwise, it will be his last PGA Tour round of the year in America. About his only drama Sunday will be playing alongside Phil Mickelson, who shot a 70 to also finish at even par. • ROGERS, Ark. (AP) — Michelle Wie shot a 7-under 64 — playing her first nine holes in 7-under 28 — to take the secondround lead in the Northwest Arkansas Championship. • INCHEON, South Korea (AP) — Fred Funk shot a 5-under 67 to take the lead in the rain-soaked Songdo Championship, the Champions Tour’s first event in Asia.
BaseBaLL CINCINNATI — Pete Rose stood on first base and tipped his cap to the screaming crowd — a little bit like 25 years ago. The banished hits king made a rare onfield appearance Saturday while the lessthan-capacity crowd stood and cheered. Rose broke Ty Cobb’s hits record with his single off San Diego’s Eric Show on Sept. 11, 1985.
U.s. OPen wOMen NEW YORK — NEW YORK — Kim Clijsters’.
CATAWBA
SHAW
FROM 1B
FROM 1B
27-yard field goal, for scoring honors. Hanes, a true freshman who earned all-conference accolades for 4AA state champ Matthews Butler last fall, grinned through braces about his amazing outing. “I’ve never done anything like that,” he said. “But I knew if I got in my spots and was where I was supposed to be, I could make plays. I’ve learned from (veterans) Cory Johnson and Lakeem Perry. They’re coaches on the field.” Livingstone (0-3) actually had more first downs, more passing yards and won time of possession by a ton, but five turnovers, including four picks, prevented the Blue Bears from competing with their neighbors. “I was super-glad for our defense because they built confidence, but I was getting a little bit irritated with them for scoring so much,” Catawba quarterback Patrick Dennis joked. “The offense needed to put some drives together, and we really didn’t get a lot of series out there.” Free safety Kewone Harris had a 65-yard fumble return for a touchdown, and backup corner Scottie Floyd scored on a 25-yard interception return. The defensive TDs by Harris and Floyd came 87 seconds apart in the first quarter to make it 21-0 and removed all doubt. “Livingstone has some quality talent, but I feel for them because they’re just so young,” Catawba coach Chip Hester said. “When you’re young, starting fast in a game is so awfully important, and we were the ones that got off to that fast start. I thought our special teams were a big edge early (Brandon Bunn set up a TD with a punt return), and that was key. We’ve been on the other side of that.” Catawba’s offense scored on its first possession. Josh Wright powered through gaping holes, and Dennis had time to text friends back home as he waited for receivers to get open. Dennis was 9-for-10 passing, including a 12-yard touchdown pass to Brandon Bunn to make it 28-0, before he called it a night. On the TD to Bunn, the 23rd of Bunn’s great career, he beat a safety one-on-one and sprinted across the end
body.” Edens did his part. Catawba scored four defensive touchdowns, two on knuckleball passes the 190-pound junior wished he could have back. “Those were bad, bad throws on my part,” he said. “I was trying to force them, trying to make plays. You can’t do that at this level because it’ll bite you in the butt.” It can and it did. “What I think happened,” James said, “is we got out there and just lost focus. The coaches can’t block for them, can’t run for them, can’t do it for them. They have to focus and execute. We told them, ‘If you don’t, you’re gonna get yourself in a hole. Just do the simple things right.’” That’s often easier said than done — even against a Catawba squad that has been less-than-spectacular the past few seasons. James and his staff devised what they believed was a promising game plan, one they hoped would help Livingstone break into the win column in this one-sided series. “The coaches were really excited about playing this game,” wideout Anthony Holland said after making six receptions for a game-best 90 yards. “You should have seen them. They wanted to strap up and get out there themselves. They had us prepared to win.” Instead, the Stone’s home-opener wasn’t lost. It was given away. The Blue Bears may have drowned themselves, but Catawba helped fill the pool. Four LC interceptions and a fumble made this an exercise in frustration. “Catawba capitalized on every opportunity we handed them,” junior Omar McFadden said. “And we handed it out on a silver platter.” By halftime it was 49-0, the last score coming when freshman linebacker Jacob Hanes confiscated an errant Edens pass on the right side and skipped 18 yards for a TD. It got worse in the third quarter when reserve QB Ray-
wayne hinshaw/SALISBURY POST
There will be better days for Livingstone’s first-year head coach Elvin James. Catawba 59, Livingstone 8 First downs Rushing yardage Passing yardage Passing (C-A-I) Punting Fumbles-Lost Penalties Catawba Livingstone
wayne hinshaw/SALISBURY POST
Jacob Hanes (54) scored twice — and made some big hits. zone to meet Dennis’ pass. “That was a great job in pass protection by our offensive line,” Dennis said. “No sacks last week, and they were solid again tonight. We realize there are tough challenges ahead of us, but we did a lot tonight we can build on.” Brian Terwilliger, a quick receiver who was a high school QB, scored out of Catawba’s “Wildcat” look in the second quarter, and backup QB Daniel Griffith fired a TD pass to Ronnie Williams for a 42-0 lead. Hanes’ first pick-6 made it 49-0 at the half. “A freshman gets two interceptions for two TDs — there’s not a lot more you can say,” said Catawba defensive captain Brandon Sutton. “Hanes gets picks in practice
too, and he works on returning them like he’s in a game.” Hanes’ second TD came with 9:45 remaining in the third quarter and ended the scoring for the Indians. He got that interception because Brandon Weedon was draped around the legs of LC backup quarterback Raymond Mallos, who had taken over for starter Curtis Edens. “The receivers were kidding me,” Hanes said. “They wanted to know how in the world a linebacker scores two touchdowns.” A fumble recovery by LC’s Devonta Harmon changed field position and set up Aycoth’s safety. Then, with 1:09 remaining, Mallos tossed a 20yard TD pass to Kevin Self for the final score.
Ls 15 38 185 16-32-4 6-34.2 2-1 8-73
CaT 13 118 119 4-11-0 2-44.0 1-1 7-79 28 21 10 0 0 0
0 8
— 59 — 8
C — Wright 4 run (Trexler kick), 8:57, 1st C — Harris 65 fumble return (Trexler kick), 7;18, 1st C — Floyd 25 interception return (Trexler kick), 5:51, 1st C — Bunn 12 pass from Dennis (Trexler kick), 2:15, 1st C — Terwilliger 13 run (Trexler kick), 8:31, 2nd C — Williams 7 pass from Griffith (Trexler kick), 5:40, 2nd C — Hanes 18 interception return (Trexler kick), 2:41, 2nd C — Trexler FG 27, 11:07, 3rd C — Hanes 10 interception return (Trexler kick), 9:45, 3rd L — Safety, (Aycoth) tackle in end zone, 3:39, 4th L — Self 20 pass from Mallos (rush failed), 1:09, 4th individual statistics Rushing — CAT: Wright 8-66; Gaither 243; Terwilliger 2-19; Morrison 2-6; Griffith 1-4; Green 2-(minus 1); Branch 1-(minus 2); Hall 10-(minus 3); Dennis 1-(minus 6); Team 1-(minus 8). LC: Moore 9-30; Edens 3-9; Smith 1-6; Dickens 1-4; Mallos 54; Harris 11-(minus 15). Passing — CAT: Dennis 9-10-0, 79; Friffith 2-4-0, 40; Green 0-0-0, 0. LC: Edens 6-18-3, 85; Mallos 10-14-1, 100. Pass receiving — CAT: Terwilliger 3-32; Wright 2-11; Charest 1-12; Bunn 1-11; Bryant 1-11; Gaither 1-7; Williams 1-7; Morman 1-6. LC: Holland 6-90; McFadden 644; Shelf 2-34; Mishoe 1-11; Harris 1-6.
“Last week (20-17 vs. St. Augustine’s) we beat ourselves, but we came together.” Sutton said. “Our chemistry was great tonight and we won all three phases of the game. I’m satisfied.” The one sobering note for Catawba was one of the scores Cherry reported: Mars Hill 41, St. Augustine’s 12.
wayne hinshaw/SALISBURY POST
Catawba's Kewone Harris celebrates in the end zone after scoring on a fumble return. mond Mallos, effective for the most part, threw a similar-looking interception that Hanes picked off and returned 10 yards for a score. An extra point later it was 59-0, but outcome had long been cemented. “I think when they went up 14-0 in the first quarter, everybody just EDENS went into the tank,” said Edens. “They quit fighting.” Not McFadden. “My reaction was to keep fighting,” he said. “But after so many negative things, it was hard. It started to hurt.” There were, of course, a few positives for the Blue Bears. They got on the scoreboard when linebacker Bryan Aycoth made a fourth-quarter tackle in the end zone. And their lone touchdown came when Mallos spiraled a 20-yard pass to senior Kevin Shelf with 1:09 remaining. But other than that, this was like watching the History Channel. It was something we had all seen before. Some of the verses may have changed, but the song remained the same. “I know our fans aren’t happy with us,” McFadden said. “The truth is we work as hard as any other team in the CIAA. We have no problem executing Monday through Friday in practice. But you have to be able to keep doing it at a high level on Saturday. We have to turn this around. There’s
4B • SUNDAY, SEPTEMBER 12, 2010
SALISBURY POST
COLLEGE FOOTBALL
Say what? Hokies lose to JMU Associated Press
AssOciAted pRess
Alabama's Will Lowery (29) reacts after intercepting a penn state pass in the second quarter.
Tide rolls Associated Press
The Top 25 roundup ... T. No. 2 Ohio St. 36, No. 12 Miami 24 COLUMBUS, Ohio — Eight seasons later, the rematch wasn’t nearly as close. Terrelle Pryor ran for 113 yards and a touchdown and passed for another and No. 2 Ohio State intercepted Jacory Harris four times in a 36-24 victory over 12th-ranked Miami.. No. 4 TCU 62, Tennessee Tech 7 FORT WORTH, Texas — Matthew Tucker ran for two touchdowns and Andy Dalton threw for a score while setting another TCU record. No. 5 Texas 34, Wyoming 7 AUSTIN, Texas — Garrett Gilbert passed for 222 yards and a touchdown and Texas shook off another slow start to beat Wyoming. Gilbert was 22 of 35 with a 45-yard touchdown to freshman receiver Mike Davis in the second quarter. Fozzy Whittaker scored on a 39-yard run. No. 6 Nebraska 38, Idaho 17 LINCOLN, Neb. — Taylor Martinez ran for 157 yards and two touchdowns and Nebraska’s defense intercepted five of Nathan Enderle’s passes and had seven sacks. Martinez went over 100 yards rushing for the second straight game and Roy Helu Jr. added 107 yards and a touchdown on the ground for Nebraska. No. 9 Iowa 35, Iowa State 7 IOWA CITY, Iowa — Adam Robinson rushed for a careerhigh 156 yards and a touchdown on 14 carries as Iowa beat Iowa State for the third straight time. No. 10 Oklahoma 47, No. 17 Florida State 17 NORMAN, Okla. — Landry Jones outplayed Christian Ponder by throwing for 380 yards and four touchdowns, and No. 10 Oklahoma moved past a shaky season opener with a 4710. No. 11 Wisconsin 27, San Jose State 14 MADISON, Wis. — John Clay ran for 137 yards and two touchdowns, and Wisconsin beat San Jose State, but lost receiver David Gilreath early in the game with a concussion. It was Clay’s eighth straight 100-yard rushing game as the Badgers won their 15th straight home opener. No. 14 Arkansas 31, Louisiana-Monroe 7 LITTLE ROCK, Ark. — Ryan Mallett completed 28 of 43 passes for 400 yards and two touchdowns as Arkansas came on strong in the second half. Arkansas (2-0) struggled to move the ball and led only 70 at the break. Kansas 28, No. 15 Georgia Tech 25. No. 19 LSU 27, Vanderbilt 3 NASHVILLE, Tenn. — Stevan Ridley scored a 65-yard touchdown and ran for 144 of his 159 yards in the second half for LSU. It was the Tigers’ seventh straight win in this series in the Southeastern Conference opener for both teams. No. 20 Utah 38, UNLV 10 SALT LAKE CITY — Terrance Cain passed for two touchdowns in his first start in almost a year and Shaky Smithson returned a punt 77 yards for a score for Utah. No. 24 South Carolina 17, No. 22 Georgia 6.
BLACKSBURG, Va. — Two games J. Madison 21 into the seaVa. Tech 16 son,
AssOciAted pRess
Virginia tech’s darren evans agonizes on the bench as the clock runs down in the Hokies’ 21-16 loss. ranked team to lose to a lower division team. The first was No. 5 Michigan, which fell 3432 won in the final minute. The Dukes needed no such late-game heroics, hanging onto the ball for the last 5:23 to finish off the Hokies. Leavander Jones and his team-
matesdown play. “We need to block better and we need to tackle better,” Frank Beamer said after his team’s first home loss in 33 games against a non-league opponent. “Execute. We need to execute.”
Spread offense has ECU at 0-2 Associated Press
GREENVILLE— East Caro l i n a ’ s 49 spread ofECU is Memphis 27 fense showing plenty of bite while its inexperienced defense is proving it can make a few plays of its own. First-year coach Ruffin McNeill will soon learn if his Pirates can keep that going on the road, too. Dominique Davis threw three touchdown passes and ran for two scores to help East Carolina beat Memphis 49-27 on Saturday, keeping McNeill
unbeaten at his alma mater while giving the two-time defending Conference USA champion a fast start in league play. Derek Blacknall returned an interception 46 yards for a touchdown in a dominating start for the Pirates (2-0, 2-0 C-USA), who last week needed a last-play touchdown pass to beat Tulsa 51-49 at DowdyFicklen Stadium. This time, the Pirates ran out to a 28-3 first-quarter lead and coasted the rest of the way in front of another big home crowd. “Even I heard, ’Good game last week,’ as I was walking to
the stadium, so I know the players got it on campus,” McNeill said. “And deservedly so, but that’s one thing I did worry about: them having a hangover from that win.” Memphis never got within two possessions after the opening period. The Pirates, at least, have some positives to build on heading into a three-game road trip. First comes a pair of games against No. 13 Virginia Tech and instate rival North Carolina of the Atlantic Coast Conference, then a league road game at Southern Mississippi.
AssOciAted pRess
east carolina quarterback dominique davis points to the sky as he celebrates a pirate touchdown.
Appalachian State rolls to ‘Quick’ win over Jacksonville Associated Press
BOONE — DeAndre Presley passed for 285 yards and four touchdowns, three to Brian Quick, as Appalachian State beat Jacksonville 45-14 Saturday. Presley passed for two touchdowns in each half as the Mountaineers (2-0), who are 59-19-2 in home openers, took a 17-7 halftime lead over the Dolphins (1-1), then put the game away with four second-half scores. Quick, who had six receptions for 132 yards, scored the Mountaineers’ first touchdown on a 41-yard reception, then caught a 15-yard scoring pass with 2:45 left in the first half. He scored on another 41-yarder with 1:48 left in the third quarter for a 31-14 lead. Michigan 28, Notre Dame 24 SOUTH. Clemson 58, Presbyterian 21 CLEMSON, S.C. — Kyle Parker threw for 114 yards and two touchdowns in just four possessions to lead Clemson to a 58-21 win over Presbyterian. Maryland 62, Morgan St 3 COLLEGE PARK, Md. — Backup Danny O’Brien threw three touchdown passes in a 45-point first half, and Maryland enjoyed its highest-scoring performance in 35 years, a 62-3 rout. Boston College 26, Kent State 13 BOSTON — Dave Shinskie returned after being taken out in the first half and threw a pair of third-quarter touchdown passes, and Boston College took advantage of five Kent State turnovers to win 26-13.
Tusculum 54, Western Carolina 30 CULLOWHEE — Bo Cordell threw for 410 yards and four touchdowns and rushed for one as Tusculum defeated Western Carolina 54-30. The Division II Pioneers (3-0) jumped out to a 27-0 lead as the teams played for the first time since 1949. Winston-Salem St. 34, NCCU 27 DURHAM — Kameron Smith threw his fifth touchdown pass of the game with 1:34 left Saturday as WinstonSalem State came back to beat North Carolina Central 34-27. Lenoir-Rhyne 41, Davidson 13 HICKORY — James Pone scored on a 59-yard run and first-half turnovers led to three additional touchdowns by Lenoir-Rhyne in a 41-13 victory over Davidson on Saturday night. Pone, who rushed for 70 yards on five carries, scored on the Bears’ first play after the Wildcats’ only first-half touchdown, a 9-yard run by Kenny Mantuo, who had 12 carries for 89 yards.
WAKE
N.C. STATE
FROM 1B
FROM 1B
an early 5-minute stretch, the teams combined for three touchdowns of at least 60 yards. “We’ve got to tackle better to begin with. And (have) the discipline to be consistent enough not to give up huge plays,” Duke coach David Cutcliffe said. “We got the ball run at us, and we got the ball thrown at us. A lot of it was not tackling very well.” Sean Renfree was 28 of 44 for 358 yards with four touchdowns and three interceptions for Duke (1-1, 0-1). Conner Vernon caught two TDs, covering 70 and 51 yards. Renfree’s second scoring pass to Vernon made it a sixpoint41 with 8:45 remaining. Price 210 pos-
AssOciAted pRess
Wake’s devon Brown races upfield for yardage. then led them on a 13-play, 79-yard drive that chewed up nearly 6 minutes and ended with Devon Brown’s 6-yard touchdown run. Price and Ted Stachitas were among the leaders in the preseason race to replace record-setter and graduated four-year starter Riley Skinner. The two shared time in the first half before Stachitas bruised his left (nonthrowing) hand — a troublesome injury for a key member of an offense that runs so many pitches to both sides of the field. Price, who played the entire second half, put the Demon Deacons ahead to stay midway through the third quarter by finding a wideopen Williams streaking down the right sideline from
session,11,.
SALISBURY POST
SUNDAY, SEPTEMBER 12, 2010 • 5B
NFL
FISH DAY!!! NOW IS THE TIME FOR STOCKING! Channel Catfish • Largemouth Bass Redear • Bluegill (BREAM) • Minnows Black Crappie (IF AVAIL) • Grass Carp • Koi
THURS., SEPTEMBER 23, 2010 Rockwell Feed Service Goodman Farm Supply In Rockwell, NC From: 8 - 9 am
Steele Feed & Seed
In China Grove, NC From: 2:15 - 3:15 pm
In Mt. Ulla, NC From: 4 - 5 PM
TO PLACE AN ORDER CALL
1-800-247-2615
FARLEYS ARKANSAS PONDSTOCKERS, INC.
Teresa Rusher
Which number are you?
Prostate cancer is one of the most frequently occurring cancers in men and the second leading cause of cancer death. Fortunately, many cases are curable if the disease is diagnosed in its early stages. Learn about the warning signs and risk factors for prostate cancer and take advantage of a free screening by physicians from Salisbury Urological Clinic. Every man over the age of 40 should have an annual prostate examination.
GOLF BENEFIT Saturday, September 18th
at Foxwood Golf Course 940 Potneck Rd, Woodleaf
Captains Choice Shotgun Start @ 1:00pm Lunch will be provided at 12pm
TEE BUSTERS • MULLIGANS • DOOR PRIZES TROPHIES • 50/50 DRAWING LONGEST DRIVE CONTEST
One out of every six men develops prostate cancer.
Do not miss this important free health screening.
ROCK! FALL Saturday, September 18 • 8 - 11 a.m. 6DWXUGD\6HSWHPEHU‡DP
Entry Fees: $40 per person • $160 per team
TO ENTER YOUR TEAM CALL:
Outpatient Surgery Center at Rowan Regional Medical Park on Julian Rd., Exit 74 off I-85, Salisbury
Call 704-210-5628 schedule an appointment Call 1-800-335-4921, pressto option 1 to schedule an appointment.
R126982
Kathy Spry 336-391-2225 Erin Spry 336-391-8065 Billie Weathers 704-213-6294 Foxwood Golf Course 704-637-2528
GET READY TO
“They beat our butts,� place-kicker Lawrence Tynes said. “For the guys that were here, the coaches and organization, this one is pretty important. The way we finished last year was unacceptable.� Both teams have a lot to prove this season. After winning their divisions in 2008 with 12-4 records, the Giants and Panthers each slipped to 8-8 last season and missed the playoffs. The Panthers have undergone major changes. Quarterback Jake Delhomme and defensive end Julius Peppers are playing elsewhere in a shakeup that has seen Carolina emerge as the league’s. Veteran Steve Smith, who broke his left arm in last year’s game against the Giants and broke it again playing flag football in June, isn’t concerned. “It’s mistakes, just leaving plays on the field,� the fourtime Pro Bowler said. “We’ve had dropped balls, overthrown balls, missed routes. I just think errors, and I think that’s what the preseason is there for, to make those errors so you can have them corrected once the season starts.� Despite losing Peppers to free agency, the Panthers had 19 sacks in four preseason games. “I like the way we’ve grown through the preseason,� said Fox, who is in the final year of his contract. “I think we’re a young football team. In particular there are some guys that have not seen a lot of playing time for us, albeit they’ve been with us. I’ve liked their progress as we prepare for the season opener.� The strength of the Giants is their offense. Eli Manning had a career year, throwing for 4,021 yards and 27 touchdowns and receiver Steve
eran who has started 87 straight games. “.�
R126696
FROM 1B’s game. “I look at it as a new season,� said the seven-year vet-
R126511
PANTHERS
Now N ow yyou’ve ou’ve ggot ot m more ore
OPTIONS! O PTIONS! With W ith New New M Mid-Day id-Day TTrain rain Service Service
SENIOR
EXPO LIVE ENTERTAINMENT PROVIDED!
)RUEHVWIDUHVERRNHDUO\ )RUEHVWIDUHVERRNHDUO\ E\WUDLQRUJ \WUDLQRUJIIRULQIR RULQIR 9LVLW 9 LVLWE
VISIT THESE BUSINESSES AT THEIR BOOTHS FOR INFORMATION ON PRODUCTS AND SERVICES Rowan County Senior Services Rufty-Holmes Senior Center Rowan County Senior Games Salisbury Audiology Powles Funeral Home National Active and Retired Federal Employees Chapter 0720 Piedmont Behavorial Health Care Cabarrus Eye Center Health Solutions Unlimited Penrod Medical Equipment, LLC
Now N ow O Offering fffering N New ew M Mid-Day id-Day Train Train S Service ervice Southbound d
Train Train 73
Train Train 75 5
Train Train 79
Raleigh
6:50am
11:50am m
4:50pm
Cary
7:02am
12:02pm m
5:03pm
Durham
7:22am
12:22pm m
5:24pm
Burlington
7:58am
12:58pm m
6:01pm
Greensboro Greensboro
8:23am
1:23pm m
6:32pm
High Point
8:40am
1:40pm m
6:49pm
Salisbury
9:14am
2:14pm m
7:25pm
Kannapolis
9:30am
2:30pm m
7:42pm
Charlotte
Northbound d
(ar)10:02am (ar)10:02am
(ar)3:02pm (ar)3:02pm
Train Train 80
Train Train 74 7
(ar)8:14pm (ar)8:14pm
Train Train 76
Charlotte
7:30am
12:30pm m
5:15pm
Kannapolis
7:57am
12:57pm m
5:42pm
Salisbury
8:15am
1:13pm m
5:58pm
High Point
8:48am
1:45pm m
6:30pm
Greensboro Greensboro
9:11am
2:06pm m
6:51pm
Burlington
9:33am
2:27pm m
7:12pm
Durham
10:13am
3:04pm m
7:49pm
Cary
10:33am
3:24pm m
8:09pm
(ar)10:48am (ar)10:48am
(ar) 3:43pm m
(ar) 8:28pm
Raleigh
Miracle Ear Doug Smith The Meadows of Rockwell Genesis Healthcare Rowan Regional Medical Center Beltone Hearing Aid Carillon Assisted Living Comfort Keepers Liberty Commons Home Instead Oak Park Retirement
TUESDAY, SEPTEMBER 14, 10 AM-2 PM AT THE SALISBURY MALL THE SENIOR EXPO IS SPONSORED BY
R125374
PRIME TIME
R126668
TTrain rain Schedule S chedule
6B • SUNDAY, SEPTEMBER 12, 2010
SALISBURY POST
NFL
Put up or shut up for two teams town with the Broncos, and they didn’t work on special plays for the former Florida star all summer not to use him.. San Diego at Kansas City (Monday night) Who is missing from the Chargers is as noteworthy as who is on hand for the overwhelming AFC West favorites. Still around are QB Philip Rivers, TE Antonio Gates, LBs Shawne Merriman and Shaun Phillips, probably enough to handle KC. Miami at Buffalo A terse three-sentence statement announced Bill Parcells’ move into a consultant’s role this week. If the Tuna could have gotten away with no mention of the shift at all, he would have. Arizona at St. Louis Top overall pick Sam Brad-
ONLINE QUOTES: Auto Homeowners Fire Vacant Dwelling Flood Churches
General Liability Worker’s Compensation Umbrella Life Health Bonds
Business - Property - Liability - Group Health
for
Rowan County School Board • Opposed to redistricting • Believes in prudent budget policies
$850 – $2500
LOANS AVAILABLE NOW!
NFC
National Finance Company
VOTE FOR CRAIG PIERCE on November 2nd
440 Jake Alexander Blvd. West • Salisbury, NC 28147 Phone: (704) 633-5291 Fax: (704) 637-5532 Mary H. Smith, Mgr.
@ S R H 4 2 SHOP .com y
---NOTARY PUBLIC---
• Will work to improve graduation rates and academic levels
Come and Visit Our Friendly Staff Today!
R126223
R118952
CRAIG PIERCE
Need Money for Back To School Expenses?
hev c g n i k y r r a l
ford makes his debut against the most newsworthy team of the preseason. Unless the Rams’ offensive line comes together quickly, Bradford will spend a lot of time on his back or being chased out of the pocket.. Cleveland at Tampa Bay An early opportunity for two bad teams to get off to a good start. Jake Delhomme takes over at quarterback in Cleveland, which should be an improvement, but who will he be throwing to?
R107415
NFL this week ... today. Houston is 1-15 against Peyton Manning since entering the league in 2002.. • Green Bay at Philadelphia Few teams are getting the
Super Bowl hype that Green Bay is. The Packers really seem to be grasping the 3-4 defense that coordinator Dom Capers installed last year, and quarterback Aaron Rodgers looks primed for a huge season.. Atlanta at Pittsburgh A major opportunity for the Falcons with Pittsburgh starting untested QB Dennis Dixon as Ben Roethlisberger begins his 4-game suspension. Denver at Jacksonville Here’s one way to guarantee the Jaguars aren’t blacked out locally: Tim Tebow. The QB comes to his home-
Paid for by the Committee to Elect Craig Pierce
R126486
Associated Press
$
49
Family Owned & Operated KANNAPOLIS
OVER INVOICE
Brand New
Experience the Difference at Larry King Chevrolet!
Brand New
HHR
on any new car or truck in stock and you keep the
HUGE REBATES!!
Malibu 2010 and 2011
$49
OVER INVOICE has been extended and includes ALL 2010 and 2011’s
!
Brand New
Cobalt
2010 & 2011 Equinox’s in Stock 3 to Choose From
2010
No Games ★★★ No Gimmicks ★★★ GOOD PEOPLE TO DEAL WITH ★★★ Save Up To $13,000 NEW 2010 & 2011
Silverado
07 CHEVY IMPALA LT Clean Local Trade In With Lots Of Options
10,980
Auto, AC, Low Miles and More!! Stk#P1440
Auto, AC, CD, Low Miles & More! Stk#P1465
04 Kia Sorento EX 4WD, Auto, Leather, Sunroof & Much More
$
10,995
Camaro
AC, Very Clean, Stk#5210A Stk#P1464
09 Chrysler Sebring LX
12,990
Traverse
07 Chevrolet Aveo LS 07 Ford Focus SE 05 Ford Taurus SEL GM Certified, Auto, AC, and More, Leather, Value, V6, & Only 24K
8,990 09 Hyundai Elantra GLS
$
NEW 2010 and 2011
$
$
8,990
Miles! Stk#5665A
$
9,995
08 Chevrolet Canyon SL Ext Cab GM Certified, Very Clean & Low Miles, Stk#5604A
$
11,990
09 Pontiac G6 08 Dodge Charger 06 Chrysler Pacifica Touring GM Certified, Auto, Power Pkg & Much More! This Sporty Automatic has Stk#P1461
Lots of Options! Stk#P1462
$
Has It All! Leather, Rear DVD, 3rd Row Seating, Low Miles & More! Stk#5674
NEW 2010
NEW 2010
Tahoe LT
Impala
06 Chevrolet Colorado
GM Certified, Auto, AC and More! Stk#5644a
$
12,450 06 Buick Lacrosse CX
Fully Equipped, Clean Car with Low Miles! Stk#P1463
$ 13,990 $ $ 12,990 13,990 12,990 14,450 08 Nissan Altima 07 Ford Edge SE 09 Jeep Grand 05 SILVERADO SS 07 Chevrolet 3.5 SE Silverado 4WD Cherokee Laredo Local Trade, Low Miles, Power Pkg EXT CAB Crew Cab LT, Chrome Everywhere, Sunroof, Spray Auto, Power Pkg, Low Miles and More! 4WD, Local One Owner Trade and More! VERY CLEAN & VERY FAST!!! Bedliner, Bed Rails, Boards & More! Stk#5682A with Low Miles, Stk#P140 Stk#P1400 $ $ $ 16,995 $ $ 19,990 23,990 18,990 16,450 $
07 G2500 Express Van Only 20K, Local One Owner, Very Clean
$
14,995
09 Dodge Avenger SE Only 29K, One Owner, Very Clean
$
14,450 05 Chevy Tahoe Z71
$
13,990
704-933-1104 800-467-1104 Toll Free
I-85 Exit 58 - 1 Mile • 1520 South Cannon Blvd. • KANNAPOLIS
SHOP 24 HRS @
KANNAPOLIS
ALL PRICES ARE PLUS TAX,TAG AND $499 DOC FEE. $49 OVER INVOICE EXCLUDES EQUINOX
C47262
$
NEW 2010 and 2011
BUSINESS
SUNDAY September 12, 2010
SALISBURY POST
Paris Goodnight, Business Page Editor, 704-797-4255 pgoodnight@salisburypost.com
GROWING SEASON Pattersons optimize capital, labor on farm BY LINDA BAILEY Miller Davis Agency
andall Patterson doesn’t slow down often to think about Patterson Farm’s growth in the last two decades. He knows that for a modern-day farm to be successful it has to optimize all capital. “Everything has to be maxed out to be efficient,” he says. Today, that means diversification, efficient processes and a good labor force. Tomorrow, that may mean something different. Patterson Farm knows that it has to be an agent of change with its business practices. Patterson Farm, now farming 450 acres, is the largest vegetable farm in Rowan
R
County. It has experienced a growth rate of more than 300 percent under the direction of subMitted pHoto the late Carl E. Patterson, and now his sons, Randall and randall patterson, left, walks with carlos amezquita, field Doug. That’s 110 different operations manager, among the fall crop of tomatoes. fields in the Millbridge, Mount Ulla and China Grove communities. Each dad’s vision mainly because of the employcontains 4 to 4.5 acres, and the farm manees that we have. They are what Patterson agers go through a 50-step process for each Farm is.” Some of the Latino workers have field during pre-planting, planting and post- been with Patterson for 20 years. “These planting seasons. are the guys that keep the place running,” The sons say that they are carrying out says Randall. They know government comtheir dad’s vision. “He knew that we had to pliance regulations and follow them. We do grow to stay in business,” Randall says. “La- everything legally and correctly. We have a bor is the main factor in our growth,” says good track record with our workers.” Randall. “We’re very proud of our workers. See GROWING, 3c We are able to go forward and meet my
S
September
Heart Group, Sanger merge
Brady qualifies for Sierra level
associated press
oracle ceo Larry ellison, right, and (then) Hewlett packard ceo Mark Hurd, on screen, appear at an oracle open World conference in san Francisco earlier. as co-president at oracle corp., ousted Hewlett-packard co. ceo Mark Hurd will have to adapt to his new role.
See ORACLE, 2c
Eric Brady, a financial representative with Thrivent Financial for Lutherans, has qualified for the organization’s prestigious Sierra level for 2009 achievements. Brady, with Thrivent Financial’s Southeast Regional Financial Office, has demonstrated outstanding sales and service to members. Nearly 650 of Thrivent Financial’s 2,500 financial representatives qualified for the Sierra level. Brady has been with Thrivent Financial and its predecessor organizations for 19 years and has been recognized for his performance 14 times.
Team Chevrolet classic car show Team Chevrolet, 404 Jake Alexander Blvd. S., is holding a classic car show Sept. 25 from 8 a.m.-6 p.m. Entry fee is $10. Spectators get in free. Vehicles drive in Sept. 24 from 3-8 p.m. Judging starts at noon on Sept. 25. Free car washes are offered with Hooters’ girls and “Midlife Crisis” plays from 25 p.m. Donations of diapers, clothes and other items will be accepted for Rowan Helping Ministries. All proceeds go to charity. For more information, visit www. TeamAutoGroup.com or call 888-746-9597.
New equipment at Air Master Air Master Technologies has a new line of heating and air conditioning equipment
See ROUNDUP, 2c
Don’t pay to get out of dreaded triple timeshare trouble BY BRUCE WILLIAMS
13 — chamber of commerce’s business after Hours, bayada Nurses at el patron Mexican restaurant, 1030 Freeland drive (behind cracker barrel), 5-7 p.m. call 704-633-4221 for reservations 14 — chamber small business counseling, chamber, 9:30 a.m.noon. call 704-633-4221 for appointment 15 — chamber Workforce development alliance, chamber, 8 a.m. 16 — chamber Leadership rowan ‘Future perspectives’ day, 8 a.m.5 p.m. 17 — chamber federal and state affairs committee, chamber, 8 a.m. 20 — chamber board of directors, chamber, noon 21 — chamber business council ‘social Networking roundtable,’ chamber, 9 a.m.
Forced to retire from the Superior Court bench due to the state court system’s mandatory retirement age of 72, John Holshouser has accepted an invitation to join Kluttz Reamer Hayes Randolph Adkins & Carter, a Salisbury law firm. “Retirement can wait,” HOLSHOUSER Holshouser said. Holshouser will begin work in October.
Business Roundup
Co-president gig may test friendship
Business calendar
Holshouser says he’s not ready for retirement
Heart Group of the Carolinas, with offices in Concord and Albemarle, has merged with Sanger Heart and Vascular Institute. The practice will operate under the Sanger name. Office locations will not be affected. Offices are currently located on the campus of CMC-NorthEast in Concord and at 307 Yadkin Street in Albemarle. Physicians will continue to see existing patients and new patients are always welcome. The staff includes 10 physicians, six mid-level providers and 48 staff members, including clinical staff, cardiac imaging technicians, cardiac nuclear medicine technicians and exercise specialists.
Who will be top dog at Oracle? AN FRANCISCO (AP) — As co-president at Oracle Corp., ousted HewlettPackfounded
1C
Smart money
United Feature Syndicate
DEAR BRUCE: I own three timeshares in three states. I am 65 years old, married and still working. I have recently begun to consider selling, which I’m told is next to impossible. I attended a seminar from companies that say they can help me out from under. They do say that an owner cannot get out of his contracted obligation to continue paying and his heir’s cannot get out of paying these yearly fees. Is this true? Both companies propose to get an individual out of his deeded timeshares with an upfront fee of many thousands of dollars. With this fee, it is promised/guaranteed to save many years of paying fees by my heirs and myself. Would this really be true? — Hugh Macomb, Ill.
DEAR HUGH: Three timeshares? Really? It’s true that it’s very difficult for an owner to get out from under just one. It depends on the contract that you’ve signed. Generally, you can’t give back a timeshare to
the family home and will continue until she is unable to do so. When mom died, he and his lawn company were replacing the roof on the home. It was decided at the time of her death that he and his company would be paid upon the death of our sister and/or the sale of the family home, whichever comes first. It may be a long time before my sister either goes to a nursing home or passes away. We have a sister who agreed to do this, but she keeps saying she will fight this. Can she really fight this when four out of the five of us are in total agreement? My brother has worked very hard to do the right thing. — Michelle,
avoid yearly fees, and selling one is, as you’ve heard is next to impossible. There is no way that you can obligate your heirs, unless maybe the timeshare people take the position that this is ongoing debt. If you have an estate, that is a matter for your attorney, but I wouldn’t pay anybody thousands of dollars to get out from under. Maybe you can give these things to charity. The charities sometimes raffle off these wonderful deals. I would consult an attorney and devia e-mail termine whether there is a way your heirs could be held responsible. If this is true, then maybe Dear Michelle: I feel like a broken record. This your estate planning will have to take a different is yet another example of why you don’t leave unturn. divided property to a bunch of siblings. You have DEAR BRUCE: My mother died six years ago, one sister who is obviously irresponsible at the leaving us with our sister, who is mentally and very least who feels that somebody else would physically disabled. She had a trust, which my take care of her responsibilities. Your brother is brother is trustee of. He is also my sister’s legal clearly the good guy here and should be accomguardian. He makes all her decisions and makes modated. There is no reason to freeze this other sure she is well taken care of. He includes the oth- sister out. You could go to the court and require er siblings in large decisions, especially regardSee MONEY, 2c ing medical decisions. My sister is still living in
2C • SUNDAY, SEPTEMBER 12, 2010
ROUNDUP FROM 1C designed for the climate in North Carolina. Located at 1912 S. Main St., Air Master has been in business since 1975. The new equipment will be on display at the Rowan County Fair. information Submit about new businesses, honors and management promotions to bizbriefs@salisburypost.com. Include a daytime phone number.
MONEY FROM 1C that this house be sold and the proceeds could be split among all of you, or the four or five that are decent could then repurchase the home and you guys would split it, less the money owed to your brother. You should see an attorney. An agreement between the four of you should be legitimized in writing, and if the lawyer determines that there are further legal processes needed to ensure that your brother gets paid, then by all means you should pursue them. Given the fact that the family knew that you had a mentally and physically disabled sibling, these things should have been addressed during your mother’s lifetime. Send your questions to: Smart Money, P.O. Box 2095, Elfers, FL 34680. E-mail to: bruce@brucewilliams.com. Questions of general interest will be answered in future columns.
Are you losing sleep because of an overactive bladder?
United FeatURe SyndiCate inC.
Our local study doctors are currently conducting a clinical research study for adults with overactive bladder, known as OAB. The purpose of this clinical research study is to compare the safety and effectiveness of flexible dose regiment of an approved medication to placebo (inactive substance) on night-time urinary urgency in adults with overactive bladder. To qualify you must be at least 18 years old and have had overactive bladder symptoms for at least 3 months and night-time urinary urgency. This study requires 5 office visits over a 16 week period. Volunteers will receive at no cost: • Study related examinations • Lab Tests • Study Medication or Placebo Financial compensation may be provided for time and travel.
R124046
the day the CEO of Oracle is Larry Ellison,� Freeman said. Oracle declined to make Hurd and Ellison available for interviews. Ellison and Hurd have grown close in Hurd’s five years in Silicon Valley, working as partners to make sure HP’s computers run smoothly with Oracle’s software. They’ve also bonded over their love of tennis. Hurd was a collegiate athlete, and Ellison practices with pros and even bought a tennis tournament last year to keep it from moving out of the U.S. Ellison’s decision to bring Hurd aboard at Oracle is fraying a quarter-century alliance between the two companies, one already rocky since Oracle started competing with HP by selling computer servers with Oracle’s $7.4 billion purchase of Sun Microsystems last year. HP sued Hurd in a California court on Tuesday, a day after he joined Oracle. HP argues that Hurd won’t be able to do his job at Oracle without spilling HP’s trade secrets. Although courts in California typically side with workers who want to take their skills to rival companies, Hurd’s intimate knowledge of HP’s businesses, and his severance package from HP that could top $40 million, could work against him. Still, it’s unlikely that HP would succeed beyond delaying Hurd’s
because Ellison — the world’s sixth-richest man with a fortune of $28 billion, according to Forbes magazine — has much of his wealth tied up in Oracle stock. That gives Ellison incentive not to alienate an executive he may be grooming as a replacement.
MA0904736
FROM 1C
each year for the next five years. Hurd is an operations expert who relentlessly cuts costs —’s defense, calling the HP board’s decision to shove aside Hurd the worst personnel decision since Apple Inc. forced out another of Ellison’s close friends, Steve Jobs, 25 years ago. (In a show of Ellison’s
Salisbury • 704-647-9913
R116398
ORACLE
SALISBURY POST
BUSINESS
Or reach us on the web at Located - Salisbury One Block from Hospital
:HNQRZZHRIIHUWKH
%HVW*UDFLRXV5HWLUHPHQW/LIHVW\OHLQ6DOLVEXU\ EXWGRQ¡WWDNHRXUZRUGIRULW :KHQRXUPRWKHUWXUQHGDQGVWRSSHGGULYLQJZHUHDOL]HGWKDWVKHZRXOGEHDORQHDQGKRXVHERXQG 7KLVZDVDVKRFNWRXVEHFDXVHZHKDGDOZD\VWKRXJKWRIKHUDV\RXWKIXODQGDFWLYH)RUWXQDWHO\DODUJH DWWUDFWLYHUHWLUHPHQWFRPPXQLW\ZDVEHLQJEXLOWQHDUE\:HZHQWWRORRNDW2DN3DUNVHYHUDOWLPHVDQG IRXQGLWWREHVSDFLRXVDQGHOHJDQWZLWKFRPSOHWHVHUYLFHVOLNHWDVW\PHDOVUHFUHDWLRQDQGWUDQVSRUWD WLRQ2XUNH\UHTXLUHPHQWVVHFXULW\DQGFRPSDQLRQVKLSZRXOGEHPHWKHUH0RPFRXOGFRQWLQXHWR EH\RXWKIXODQGDFWLYHEXWZRXOGEHVDIHDQGDPRQJIULHQGV$IWHUVKHPRYHGLQZHUHDOL]HGWKHEHVW WKLQJDERXW2DN3DUNZDVWKHFRQFHUQHGDQGFDULQJVWDII7KH\FUHDWHDIDPLO\HQYLURQPHQWDQGWKDWLV ZKDWHYHU\SHUVRQQHHGVUHJDUGOHVVRIDJH:LWKWKLVOHYHORIFDUHZHH[SHFWPRPWROLYHWR a-XG\('DYLVRQ ,QIROORZLQJDOLIHFKDQJLQJLQFLGHQW,EHFDPH DUHVLGHQWRI2DN3DUN5HWLUHPHQW&RPPXQLW\ %HFRPLQJDUHVLGHQWZDVRQHRIWKH EHVWWKLQJV,¡YHHYHUGRQH,QVWHDGRI EHLQJDORQHLQP\KRXVH,DPQRZ VXUURXQGHGE\HQHUJHWLFDQG FRXUWHRXVVWDIIIULHQGVDQGGDLO\ DFWLYLWLHVJHDUHGWRZDUGVHQLRUV 2DN3DUNLVP\QHZKRPHDQG,¡P SURXGWREHDSDUWRIWKHIDPLO\ a7KRPDV+$OFRFN-U 0\ZLIHDQG,PDGHWKHPRYHWR 2DN3DUNDQGIRXQGRXWKRZPXFK ZHOLNHGLW6RPHRQHLVVHUYLFLQJXV IRUDFKDQJH7KHIRRGLVH[FHOOHQW VRFLDOOLIHKDVSLFNHGXSUHOD[DWLRQ LVÀQDOO\SRVVLEOH<D¡OOFRPHMRLQXV a5ROODQG%%DUWKRORPHZ
6HHIRU\RXUVHOI &DOOQRZIRU\RXUFRPSOLPHQWDU\PHDO SHUVRQDOWRXU :KLWH2DNV'ULYH6DOLVEXU\1&
R124564
SUNDAY, SEPTEMBER 12, 2010 • 3C
BUSINESS
Join the
Bingham-Smith Lumber Co.
R123200
MON - FRI 9AM-6PM SAT 9AM-4PM Old Mocksville Rd., Salisbury (2.4 miles from hospital)
Auto Doctor For You!
$10.00 per sheet 980-234-8093 Zion Church Rd. Gold Hill
36 95
R
12
Hwy. 52 Granite Quarry
Receive a Gift Card!
Hands-on help with your accounts or specific advice when you need it. You decide. We deliver.
Club
Clubs for Ages 2-Grade 12 Clubs meet Wednesdays at 6:45 to 8:15pm Starts Wednesday, September 15th
FIRST BAPTIST CHURCH • ROCKWELL 8630 Hillcrest Drive Rockwell • 704.279.6120 Air Master Technologies, Inc Announces Arrival of New Equipment, Designed Specifically For North Carolina’s Weather
(North Carolina) – Air Master Technologies announced the introduction of a new line of heating and air conditioning equipment today that’s designed specifically for the North Carolina area. “Climate varies dramatically across the country and manufacturers tend to build one-size-fits-all products,” said Scott Lashua, General Manager of Air Master Technologies. “Our conditions are unique enough that we decided to design a system specifically for North Carolina and work with manufacturers to produce a product to our specification. When we had the system design we wanted, we chose to call it ‘The Elite System.’” The outside air conditioner is only part of the system Air Master Technologies offers, explained Scott. Heating and air conditioning systems are comprised of a number of components that are field engineered to work together optimally for comfort and energy savings. The components are not always interchangeable. Mismatched components and an improperly designed system might work, for a while. But it will use more energy and reduce the equipment life. “When I buy a household appliance,” explained Scott, “I can take it home, plug it in, and it works. Heating and air conditioning systems are much more complex. The outside components must be matched to the components located inside the house. The design of the system can also be affected by a number of house specific factors including the house’s humidity, how well it’s sealed, the orientation of windows, and so on. We’ve worked with a domestic manufacturer operating in an ISO 9000 factory to produce products that we engineer into a system, specifically designed for North Carolina and further refined for each house.” The Elite Series is available exclusively through Air Master Technologies. For more information on the new Elite Series of heating and air conditioning equipment, or for a complementary engineering analysis of your home or business, contact Scott Lashua at 704-637-7777. You can also visit the website at. PAID ADVERTISEMENT
Whatever your banking needs may be, Marla Rayfield can help you meet them. Come see why CommunityONE is happy to have Marla on our team and why our customers appreciate her expertise. Marla Rayfield, Faith Road 647-0303, Marla.Rayfield@MyYesBank.com
Salisbury
Kannapolis
225 Faith Rd. 704-647-0303
100 S Enochville Ave. 704-933-1176
China Grove
Salisbury
200 N Main St. 704-857-1176
1938 Jake Alexander Blvd. W 704-633-0091
näänÇΣ£ÇÓÊUÊÞ9ià >°V ©2010 CommunityONE Bank, N.A., Equal Housing Lender, Member FDIC R126504
R126889
Appearing Sunday, Sept. 26th It's time to get ready for the
To advertise in this directory call
704-797-4220
Home & Lifestyles magazine’s Fall Home Improvement Services Page!
Be on the lookout for our special Home Improvement Services pages that will be inside our fall edition Home & Lifestyle magazine!
P.O. Box 1621 Concord, North Carolina 28026 Ph: 704-239-2074 jlbarch@ctc.net
Loaded with ideas and info on prepping your home and lawn for fall, who to call, where to buy and what to do, our services page is sure to be a keeper!
S42814
Jack’s Furniture & Piano Restoration
Don't be left out!
Deadline: Wednesday, Sept. 15 Publishes: Sunday, September 26
Call Classified at 704-797-4220 to be included in this special section!
We buy, sell, and move pianos We offer Steinway, Baldwin, Mason & Hamlin, & more Showroom located at 2143 C&E Statesville Blvd.
704.637.3367 • 704.754.2287
Ads are 3 columns (3.625”) X 2”
S45590
and include
Employment opportunities may be available upon successful completion. Fee for the 3 volume set of books.
209-6331
&
Premium Lattice
Register now for Liberty Tax’s 8-week class.
704/
from 3-7 pm
Dedicated To Saving You Money!
TUITION FREE TAX SCHOOL
Granite Auto Parts & Service
th
th Sept. 8 - Sept. 13
Dimensional Lumber Decking Boards Agricultural Fence Posts
Complete Piano Restoration
We’re The
Jake Alexander & Spencer
Specializing in treated lumber
Home Grown Tomatoes, Cucumbers, Squash, Zucchini, Hot Peppers, Okra & More! 704-239-0097 or 704-213-4926
Come Into
WHOLESALE & RETAIL SALES
R126034
Patterson Farm has earned Gold Star Grower status, which means it meets U.S. Labor Department standards. That’s a lot of paperwork and deadlines and it’s not easy to maintain the rigid standards, some of which have not been updated in 15 years, Randall says. Through state organizations, he is working to reform the current H2A program to make it easier for farmers to secure their workforce. He serves on the N.C. Commissioner of Agriculture’s Inner Circle, a group of 30 farmers who meet quarterly to discuss challenges facing farmers, such as food safety and the labor market. He is an Agriculture Commissioner appointee to the N.C. Sustainable Local Food Advisory Council. He is past president of the N.C. Tomato Growers Association and a board member of the N.C. Vegetable Growers Association and the N.C. Growers Association. “I feel responsible for the workers that we bring in,” says Randall. “We need to have enough work to keep them busy to support their families.” That meant diversification and Patterson Farm is achieving it in several ways. “We have a system of management of finding a profitable crop and a window of marketability,” says Randall. “With any one crop failure, you need to have something to fall back on.” Patterson previously was a 90 percent tomato farm with the growing season from mid-June until mid-October. Now it’s 60 percent, with strawberries, peppers, squash, sweet corn, cucumbers, cantaloupe, processing peppers and pumpkins added. Processing peppers are shipped directly to Mt. Olive Pickle Co. Doug and Randall also began a repack business on Millbridge Road four years ago. “We wanted to be able to supply our customers with tomatoes in the off-season,” says Randall. “When our season was over, we were cutting ties until the next spring.” The new business also enables them to keep a workforce intact year-round and to add income during winter. “Now, we follow the harvest cycle of the tomato industry,” Randall adds, which means buying tomatoes from South Carolina, Florida, and sometimes Mexico. It’s a highly competitive business, but so is everything about farming. The repack manager, Melissa Roach, has to know what her customers, mostly chain stores, will need in a given week, and during the Patterson off-season order the product to fit the need. During the Patterson season, the product is taken directly from the field to repack. “We had the facility in place for this operation to exist,” Randall says. “We use our coolers and packing house equipment which was
with my dad on the farm as a 6-year-old kid. Then, there’s a picture of me carrying a flat of strawberries on my head. I was 7 years old. “When I was 14, my dad rented me a five-acre field to raise cantaloupe and corn, and I made money. We started growing those crops afterwards.” He finished N.C. State University in 1982 with an agriculture engineering degree and came back to help out. “I got caught up in the vision,” he says. When he takes a rare moment to reflect, he thinks about how much farming has changed and how hard it is to involve youngsters at an early age to have the experience that he did. “The average farmer is 56 years old,” he says. “There are hundreds of farms going under. We need to involve youngsters to continue farming, and we need to figure out ways to preserve farmland.”
R124678
FROM 1C
sitting idle during the winter months. Now it continues to run and continues to be profitable.” It promotes the Patterson Farm name year-round. “We get a higher quality, fresher product to the consumer quicker,” Randall says. Other measures of exposure and diversification are Patterson Farm Landscape and Patterson Farm Market & Tours, which is open spring through late fall. Produce is sold at the market in Mount Ulla and up to 20,000 students and others visit the farm each year for tours and entertainment. The landscape business works in commercial and residential markets with its trees, shrubs and design work. Randall grew up wanting to be a farmer. “As a kid I helped my dad and uncle out at Twin Oak Farms that was started by my grandfather, James A. Patterson. My earliest memory was me going
R121038
GROWING
R105922
SALISBURY POST
24,000 Copies In Print!
Classes will be held at 718 N. Cannon Blvd., Kannapolis Classes start 9-13-10
Afternoon and evening available. Call 704-932-8822 for more info.
S45632
Online for 3 Months!
FREE COLOR
for only $88.50! (Actual size of each block.)
4C • SUNDAY, SEPTEMBER 12, 2010
SALISBURY POST
CLASSIFIED
Furniture & Appliances Dyer – needs heat element, $25. Stove – 1 burner out, $25. Please call 704-279-6260
Yard Sale Area 4 Davis Flea Market in Randleman, NC (30/45 minutes from Salisbury) is expanding & looking for new vendors. Visit us: 336-498-5200
Davie-Clemmons Yard Sales
Hard to read ads don’t work well. Abbreviations lead to slower sales.
Employment
Employment
Employment
Employment
Employment
Make Your Ad Pop!
Healthcare
Child Care & Domestics
$10 to start. Earn 40%. 704-754-2731 or 704278-2399
Employment Other
HOUSECLEANERS Residential Up to $10/Hour to Start Paid Travel Time Paid Mileage Full Time Car Required Mon-Fri Days Only EOE 704-603-4190
Employment
Healthcare
Dietary Aide Dietary Aide performs a variety of food service functions in maintaining clean and sanitary conditions of food service areas, facilities, and equipment. Assists in some aspects of food preparation. Casual and flexible hours. Apply on the Genesishcc.com website or fax resume to 704-636-8464.
Construction
Immediate opening for Project Costing position at Construction Company located in Salisbury. Proficient at Microsoft Excel is required. Compensation will be based on experience. Good benefits. Submit a resume to Blind Box 388 in c/o Salisbury Post PO Box 4639, Salisbury, NC 28144 Debt Recovery Specialist needed, experience preferred. Salary + commission. Serious inquiries only. Fax resume to 704857-6700 or email: Collect@vnet.net
Maintenance Tech needed full-time for apartments. Must have knowledge of apartment repairs, A/C, plumbing, cleaning & grounds. Must pass drug test, credit & criminal check. Please send résumé to: Blind Box 387, c/o Salisbury Post, PO Box 4639, Salisbury, NC 28145
NGK CERAMICS USA, INC. MOORESVILLE, NC
Part-Time Dental Assistant CDA or DA II needed for general dental office. Experience with Dentrix and digital x-rays helpful. Must have the ability to work with other rather ornery dental team members. The successful applicant must laugh at the doctor's stale jokes and work with the existing dental team daily to convince the doctor that he cannot really walk on water. Allowing the doctor to believe that any new ideas were his could be beneficial. Send resume to Dr. David Mayberry, 1539 East Innes Street, Salisbury, NC 28146 or fax to 704-637-0446. Email resumes to: gail@davidmayberrydds.com No phone calls please.
$8.00 - $20.00/hour Assemblers F Window/Door Mfg Warehouse Workers F Material Handlers Loaders/Unloaders F Inspectors, Packers Cherry Pickers F CNC Lathe Operators CNC Mill Operators F Machine Operators 1st, 2nd, 3rd & 12 hour shifts Welcome, Lexington, Linwood, Thomasville Apply online at:
Driver
Female team driver needed. 2 yrs CDL exper & HAZMAT & doubles endorsements. $1,000-$1,200/wk. 352-410-2661
Current applicants call TR Lexington office
(336) 243-5249. An Equal Opportunity Employer
DRIVER Republic Waste Services, Inc is seeking a full-time driver for its Davie division. Qualified candidates should possess: • Class-
A or B CDL driving record • Good work history • Experience preferred • Safe
Republic Services offers competitive pay and excellent benefits including health and 401(k). Apply in person Monday through Friday between 9:00am and 3:00pm at: Republic Services 131 Industrial Blvd Mocksville, NC 27028 EOE/AA/M/F/D/V and Drug-Free Workplace
FIND IT SELL IT RENT IT in the Classifieds
F
Available for Stylist or Nail Tech. Fusion Salon. 704-797-0098 Healthcare
Certified Pharmacy Technician Experience, bilingual abilities and strong computer skills a plus. Please call Jon at 704-603-1056 Healthcare
Dishwasher/Cook Needed part-time at an assisted living facility. Please apply in person at 1915 Mooresville Road, Salisbury. Healthcare
Full-Time Dental Asst. needed for a busy office. Applicant must have dental background, be energetic and willing to learn. Hours are Mon-Thur. 8am-5pm. Fax resume to 704-637-2351 Insurance
F/T Customer Service Rep. for insurance agency. Must have good communication and math skills and be computer literate. Insurance license not req'd to start. Hours 9-5 Mon.-Fri. Send resumes to Larry Nixon, PO Box 310, Rockwell, NC 28138
Healthcare
Positions Available RN & LPN F/T & P/T No phone calls, please. Apply in person
Brightmoor Nursing Center 610 West Fisher St., Salisbury Sales
Are you a hard working, self-motivated door to door salesman! Would you be interested in learning how to sell heating, air conditioning and indoor air quality systems? This is a P/T position to start, but could turn into a F/T position. Does your current commission average over $300 per sale? With this commission based sales opportunity along with our average ticket you should average over $300 per sale! Well are you interested yet? Then call Air Master Technologies at 704-637-7777 ext. 206..
Rowan-Cabarrus Community College seeks applications for a
Early College High School Liaison for Cabarrus/Kannapolis Early College High School. Required: Bachelor's degree in career guidance or counseling, education, administration, higher education or an academic or technical discipline; possess general knowledge of higher education and/or knowledge of and experience in community college education including the community college environment and educational practices. Deadline for applications: September 27, 2010. For further information and to apply visit our employment web site at. EOE. Education
Adjunct Faculty Positions Livingstone College is seeking to hire several adjunct instructors for the following areas: Business: (Instructors are needed to teach any of the following business courses). Retailing • Accounting • International Business • Money & Banking • Business Management Mathematics F English F Biology Open until filled. Applicants should submit their vita with a letter explaining their interest in the position, and the names and contact information of at least two references. Applicant material should be sent to: Human Resources, Livingstone College 710 West Monroe Street Salisbury, North Carolina 28144-5213 Law Enforcement
Education
Required: Bachelor's degree in Engineering/Computer Science or related field and five or more years of experience in the administrative information systems; three years of experience in management of a Datatel Colleague environment, Internet application development and project management; strong verbal, written and interpersonal communication skills; and demonstrated ability to work independently and reliably to ensure activities are completed to customer satisfaction.
Director, Client Services Required: Minimum Bachelor's degree in Computer Science or related field; 6 years of experience in information technology.
Infrastructure Systems Analyst I Required: High school diploma or GED and 30 hours of completed college-level coursework in Information Technology or related discipline. Associate degree preferred; industry specific certification required if lacking Associate's degree; 1 year of related work experience.
Associate's degree in computer science or information technology related field. A combination of completed college-level coursework (at least 30 hours) and experience may substitute for the degree; industry certification; 2 to 4 years of related experience.
Infrastructure Systems Supervisor Bachelor's degree in Information Technology or related field; 4 to 6 years of experience in information technology, and industry specific certification; supervisory experience preferred.
Information Systems Analyst I Required: High school diploma or GED; associate degree preferred; industry specific certification required if lacking associate's degree; 1 to 2 years of experience.
Information Systems Analyst II Required: Associate's degree in Computer Science or related field; a combination of college-level coursework and experience may substitute for the degree; industry specific certification; 2 to 4 years of related experience.
Information Systems Analyst III Required: Associate's degree in Information Technology or related field, a combination of completed college-related coursework (at least 30 hours) and experience may substitute for the degree; industry specific certification; 3 to 5 years of related experience.
Coordinator Technology Planning Deployment
Town of China Grove
Salary is DOQ; starting pay grade: $26,728. Must pass pre-employment background check, physical, drug screen and psychological exam. EOE. Please send your resume and application to: Town of China Grove, 205 Swink Street, China Grove, NC 28023 c/o Amanda A. Eller, Town Clerk. Applications accepted through September 24, 2010.
Baby Items
Web Designer Required: Associate's degree and 1 to 2 years of related experience or combination of two years of course work and experience in web design
Network Systems Administrator Associate's degree from an accredited institution in computer science or information technology related field; 2 years of experience in network or infrastructure administration or support, a combination of at least 18 semester hours of courses in computer science completed and 4 years of related experience may substitute for the associate's degree; industry certification related to network administration preferred.
Programmer Analyst I Required: Associate's degree in computer programming, computer science or information technology related field and 1 year of full-time related work experience or 3 years of any combination of collegelevel coursework and experience in computer programming or closely related disciplines. Deadline for applications: September 21, 2010. For more information and to apply, visit our employment web site at:. EOE.
Great Bargains! Wall unit $30, baby bed $35, Bassett twin beds $75. Huntersville area. Call after 5:30p.m. 704-274-9528 Oven. Frigidaire Wall Oven Gas, White, 24" with broiler. Used approx 2 yrs. $250. 704-642-1328 Sofa, 3 piece sectional $265; 42” console RCA TV $160; rug, 34”x10' $35. 704-637-1928
Games and Toys Pool table. Large. Side plastic pockets. Complete with sticks, etc. $450. Please call 910-975-9142 for more information.
Baby crib, oak wood. $75. China Grove area. Please call 704-857-3073 for more information.
PSP 2 slim, Xbox, nin64 consoles, guitar games cheap 336-751-5279, jenny
Dresser – 3 Drawers with changing table $40; Infant radio flyer bike $20. Please Call 704431-4241
Slide, Little Tykes, $40 & Boat sand box $50; toddler bike $25. Please call 704-638-2548
Infant car seat $25. Breast pump $40. Please call 704-267-4926 for more information.
Lawn and Garden
Building Equip. & Supplies Factory Clearance Sale on Steel Arch Buildings! Save thousands! All Inventory MUST GO! Additional Discounts offered through our Display Program! Call Now! 1-866352-0469
Agri-Fab Leaf Machine Includes deck adapter and owners manual. Holds 32 cubic feet of leaves and grass. $500. Call Hal, 704-637-1395 bcarlsen@carolina.rr.com
Computers & Software
Holshouser Cycle Shop Lawn mower repairs and trimmer sharpening. Pick up & delivery. (704)637-2856
Computer - Complete Emachine. $175 Please Call 704-267-4731
Lawn mower, riding. Rally. Good condition. $450. Please call 910-975-9142 for more information.
Gateway mini laptop computer. Warranty, Windows 7, Office 2007, Wireless. $250. (704)7621043
Want to buy your low priced, unused or fixable lawn mowers & tillers. Also, I do repairs. 704-431-4837. Swisher Trail Mower, 44" cut, 11hp Briggs & Stratton engine, bought new at Tractor Supply. $400. 336 998-3721, 336 909-2626.
Machine & Tools Riding Mower – 14 hp, 38 inch cut. $275 Please Call 704-636-6437
Medical Equipment Wheelchair, excellent condition, top of the line. $125. Please Call 704-636-6437
Misc For Sale ANDERSON'S SEW & SO, Husqvarna, Viking Sewing Machines. Patterns, Notions, Fabrics. 10104 Old Beatty Ford Rd., Rockwell. 704-279-3647 Bedrails, 5 pair, $10 each; bookcase $15. Please Call 704-640-4373
Infrastructure Systems Analyst II
Required: Associate's degree from an accredited college or university in Computer Science or Information technology related field and 2 years of information technology experience.
Police Officer wanted for the Town of China Grove, North Carolina..
Older cameras to trade for same 35mm. Call 704-637-5563 or email gringudo@yahoo.com
Rowan-Cabarrus Community College seeks applications for the following full-time positions:
Police Officer Population: 4397
Antiques & Collectibles
An Equal Opportunity Employer
Associate CIO
Education
Booth Rental.
Entertainment center, 4 pc. Cherry. $250. Patio set w/umbrella. $200. Please call 704-857-5143
Standard Antique bed. Mahogony $150.00 Call (704) 278-2588
Skilled Labor
12 hr shift.
Health & Beauty
F
*some restrictions apply
Strength in PLC Electrical troubleshooting required, preferably Allen-Bradley & Mitsubishi
2nd/3rd and 12 hr am/pm shifts
SKILLED LABOR Immediate need! Grounds maintenance laborer. Must have some previous experience. Call 704-2130177 between 4:005:30 pm M-F. No weekend calls!!!
Color backgrounds as low as $5 extra* 704-797-4220
MULTICRAFT MAINTENANCE TECHNICIAN
VARIOUS PRODUCTION POSITIONS
Healthcare
CNA's NEEDED Primary Health Concepts, Jake Alexander Blvd., 704-637-9461
NGK CERAMICS USA, INC. MOORESVILLE, NC
Skilled Labor
EOE/AAE
Accounting/Finance
Tax preparers needed, exp. or will train. 25 full & part time positions to fill. Please call 704-890-4587
Other
Albemarle. 40818 Stony Gap Rd. Albemarle Flea Market Fridays, Saturdays, & Sundays ~ 10am-8pm. Dealers ~ Booth space available. Visa/MasterCard. 704-982-5022
Electric Fireplace. Heats and looks like real. Works great. Only $100. 704-245-8843
Tractor for sale: Kubota L285 diesel tractor, $2995. Please call 704-855-1200 Monday-Friday or 704-9326284 weekends
Furniture & Appliances Air Conditioners, Washers, Dryers, Ranges, Frig. $65 & up. Used TV & Appliance Center Service after the sale. 704-279-6500 Bedroom suite, new 5 piece. All for $297.97. Hometown Furniture, 322 S. Main St. 704-633-7777 Bunk beds; twin size, hardwood, brand new steps as form of ladder. $250-$300 (best offer) Call 704-433-8112 Cabinet. White china cabinet w/ butcher counter top; needs paint $65.00 704-278-2722 after 3. Chairs, 4 wing back. Good condition. $50 each. 3 desk chairs, $20. Call 336-492-5559 Desk, beautiful rustic Brazilian pine, 4 regular drawers, 1 file drawer. 5'8”. $175. 704-640-5030 Dining oval oak table with two leaves and six chairs. Good Condition. $75. 336-998-8913, Mocksville
Books. Danielle Steel, hard and soft copies. Ten for $10. Call for more information 336-751-5171 Boots, Ladies' Wrangler, size 6.5, $5; one new standard window, 52x30, $60. 704-938-3027. Camper top high rise red 94 GMC short bed, like new, well kept, leave message. $500. 704279-4106 704-798-7306 Camper top. High rise red, shortbed. 1994 GMC Sierra $500. Kept covered. 704-279-4106 or 704-798-7306 Lv. Msg. Carpet 12x12 rose color. Never used. $75.00 336-998-8913, Mocksville CD Players, (2) car CD players $50 each; speakers & amp $250; radar detector $15. Please call 704-638-2548 Free rugs, room size. Braided. Multi-colored. Padding included. Please call 704-278-2325. Gas Heater, Glo Warm, ductless, new. $70; new wh. door 32x80 with mirror. $35. 845-3376900
Have a Seat! Benches, backless, (3) 4 ft. long, $11-12 each. (1) 5 ft. long. $15. Call 704431-4550
SALISBURY POST
SUNDAY, SEPTEMBER 12, 2010 • 5C
CLASSIFIED
Barbara
SALISBURYPOST.com is Rowan’s most visited local site with more than 2.5 million page views per month
JOBS
AUTOS
SUNDAY & WEDNESDAY
Sell It Faster with an Attention Getter!
Choose an “eye-catching” image and make your ad stand out in print and online!
REAL ESTATE
FRIDAY
SATURDAY
YOUR CLASSIFIED LISTINGS…
Kristin
Charla
SERVICES DAILY
LEGALS DAILY
797.4220
Call 704.
Employment Pets & Livestock Notices Garage & Yard Sales Transportation Real Estate or Online Merchandise for Sale Service Directory Rentals Sporting Goods
Misc For Sale
Misc For Sale
Misc For Sale
Headphones, new $3; coffee table $8; bedside commode $9; pumpkin cake pan $3; little mermaid cake pan $3 704-245-8032
Skil saw 2.4 HP with case, $35. 4 Dinette chairs, $28. 704-9332228
Truck Bed Cover, combination, fits Ford, Chevy or Dodge. Short bed $375. Please Call 704-267-4731
Golf. Used golf balls for sale. 100 for $35.00. All clean. Please call 704202-9192.
TV – 32” $100; (2) 19” TVs $35 each; GPS $50; VCR $15; Please Call 704-638-2548
Want to Buy Merchandise
Hitch. 16 disc hare 3 point hitch $285. Please call 336-692-4682 for more information.
Just a swingin' Swing set, 1 year old, 6 post, $50. Video camera $40; hobby horse $15. 704-279-8561. Light fixtures, two new, antique brass finish, $15 each. Please call 704636-9098 METAL: Angle, Channel, Pipe, Sheet & Plate Shear Fabrication & Welding FAB DESIGNS 2231 Old Wilkesboro Rd Open Mon-Fri 7-3:30 704-636-2349 Pop up Bed springs. Goes under daybed or single bed. $75. Call 704630-9286 Set of World Books & Encyclopedias; plus have lawyer books. $75. 704279-6260
Show off your
Tiller. 6 hp motor. Tilling mechanism broken. 7 years old. $60. Please call 704-279-8194
Washing machine $100; bathroom vanity & faucets $25; bookcase $10, singing machine $50. 704-6420512 Weight Machines (2) $65 each; walk machine $30; AB lounge $30; restaurant kitchen tables (2) & sink $50 each. 704638-2548 Wheels for push lawn mower, $2 for all. Bedding, $2 for all. Commode (tank made before gov. reg.) $5. 7' table with formica top, $10. Call 704-932-5008
Business Opportunities AVON - Buy or Sell Call Lisa 1-800-258-1815 or Tony 1-877-289-4437 thebennetts1@comcast.net
AA Antiques. Buying anything old, scrap gold & silver. Will help with your estate or yard sale. 704-433-1951.
COKE & M&M VENDING ROUTES! 100% Fin. Do You Earn $2K/Wk? Loc's in Salis. 800-367-2106 x 6020
All Coin Collections Silver, gold & copper. Will buy foreign & scrap gold. 704-636-8123
J.Y. Monk Real Estate School-Get licensed fast, Charlotte/Concord courses. $399 tuition fee. Free Brochure. 800-849-0932
Timber wanted - Pine or hardwood. 5 acres or more select or clear cut. Shaver Wood Products, Inc. Call 704-278-9291.
Free Stuff
Watches – and scrap gold jewelry. 704-636-9277 or cell 704-239-9298
Free Stuff Entertainment/Television stand free. Call 704-267-4926 Free firewood. Must be able to cut & split a gum tree. Advance area. Please call 336-940-2232 Free kittens. Approx. 8 weeks old. 2 males, 1 female. No shots. Litter trained. Weaned. Raised indoors. 704-682-5302
Notices
Found dog. St. Bernard mix, male, about 2 yrs old, Hwy 29, September 7. Call to identify. 704640-6976
Bedroom Set Girls Moving Sale 7 pc set. Please call 704-7620345. $275 OBO
dog. Walker Found Coon Hound. Tri-colored male. Found Old Concord Rd. before Rogers Rd. the evening of 9/9. Please call 704-652-8021 to identify.
Notices
FOUND Pit Bull, male. Mostly fawn with a bit of white. If this is your dog, please call 704-314-0304 Lost cat. Male, brown & black striped tabby. Very large. Answers to “Thomas.” Lost in Briggs Rd. area. 704-791-0801
The Rowan County Housing Authority will be accepting applications for: Send us a photo and description we'll advertise it in the paper for 15 days, and online for 30 days for only
30*!
$
Call today about our Private Party Special!
704-797-4220
Section 8 Project Based Housing Assistance
Let us know! We will run your ad with a photo for 15 days in print and 30 days online. Cost is just $30.
X
*some restrictions apply
SOLD We sold our items within 3 hours of the ad coming out in the paper! Amazing! ~ G.K., Salisbury
SOLD
Trampoline, 15', $150; GE Upright freezer, 20 cu. ft. $150; electric dryer, $140. Please Call 704-798-1926
The more you tell, the surer you’ll sell.
9:00 am - 11:00 am and 2:00 pm - 4:00 pm
LOST DOG! Pomeranian Female named Pebbles; golden brown; blue collar. Lost in Spencer on Sept. 3rd. Children miss her! 704637-8697 or 704-2795560 ext 0
Wednesday, September 8, 2010 Wednesday, September 15, 2010 Wednesday, September 22, 2010 Wednesday, September 29, 2010
dog. Black LOST Pomeranian, female. 7 lbs. Has medical issues. Answers to “Shadow.” Please call 704-637-3568 or return to Pinewood Ave.
On the following dates at the times stated
Call the Salisbury Post Classified Department at 704-797-4220 or email classads@salisburypost.com Music Sales & Service
No applications will be accepted without the following documents:
Washer & dryer set, Whirlpool $250. Great shape! Leave message 704-279-7318
1002 Timber Run Dr., Beautiful Salisbury. custom built home for sale in one of East Rowan's finest developments, Timber Run. Just under 2600 sq ft. 4 BR, 3.5 BA. Call 704-796-5566
292 & 294 Jones Road, Mocksville. Two homes located on 3.94 acres and can be sold together or separately. 3BR, 2BA modular w/ garage, above ground pool and multiple storage bldgs. 1,064 sf 2BR, 2BA mobile w/ carport. Both homes are in immaculate condition and meet FHA financing requirements. Teresa Rufty, TMR Realty, 704-433-2582
Please help! LOST money at Walmart on Arlington Rd. on Sat. 9/4, 2pm-4pm. Can identify exact amount & order money was in. This was my social security money & all I had for the month. 704-239-4172
Whispering Oaks is restricted to those 55 years of age or older
704-797-4220
BUYER BEWARE The Salisbury Post Classified Advertising staff monitors all ad submissions for honesty and integrity. However, some fraudulent ads are not detectable. Please protect yourself by checking the validity of any offer before you invest money in a business opportunity, job offer or purchase.
HEATED POOL
McCall Heights
ACREAGE
PRICE REDUCED – 365 D. Earnhardt Rd. Rockwell, East Rowan - 3 BR, 2 Baths, Located on 3.11 acres, Large rooms with great closet/storage space, oversized garage. A definite must see!! Price reduced $15k!! MLS #50302 Teresa Rufty, TMR Realty, Inc. (704) 433-2582
Salisbury. 3 BR, 1.5 BA, large living room and den with wood burning fireplace, new roof, new updated central heat & air unit, large storage bldg. R51042A $134,900 B&R Realty. Monica Poole 704.245.4628
Motivated Seller
ALEXANDER PLACE
Lost Dog. Male yellow lab mix from St. Matthews Ch. Rd Area 704-636-6230
• Birth Certificate • Social Security Card • North Carolina Drivers License or pictured ID
To advertise in this directory call
Found cat. Friendly, black and white male cat; in Mount Ulla area, close to Elementary school. (704) 278-0282
Free puppy, Pit Bull. Male. Approx. 9 weeks. 1st shots. Beginning house training. To good home only. 704-245-1044
Notices
Homes for Sale
Lost & Found
Free puppies to good home. Have been unable to find owner. Trying to find home for them. 704431-4539
Application Procedures For Whispering Oaks Apartments Only (A Senior Community)
With our
Become a CNA Today! Fast & affordable instruction by local nurses. 704-2134514.
Found dog. Boxer, male. Not neutered. Tri-color. White on face. Black mask. Body is fawn. Found in Rockwell area on Sept. 3rd . 336-9814373 to identify
GOING ON VACATION? Send Us Photos Of You with your Salisbury Post to: famous@salisburypost.com
Homes for Sale
Instruction
China Grove, 3 homes available: 2 under construction, 1 move in ready. All 3 BR, 2 BA. Call for details. $109,900 to $114,900 B&R Realty 704.633.2394
For Sale By Owner
Salisbury, Henderson Estates, 3 BR, 2.5 BA, Basement, Double Attached Carport, R48766 $159,900 Monica Poole 704.245.4628 B&R Realty
Motivated Seller
C47209
Monument & Cemetery Lots Garden Mausoleum Crypt for Two. Rowan Memorial Park Bldg A Lakeside location. Heart level, includes marker. Perfect Above Ground Burial. No More Crypts available. 704-637-2023 after 6pm
• Pay your subscription online: salisburypost.com/renew • Place a vacation hold: salisburypost.com/subscription
P.O. Box 1621 Concord, North Carolina 28026 Ph: 704-239-2074 jlbarch@ctc.net
Jack’s Furniture & Piano Restoration Complete Piano Restoration
Showroom located at 2143 C&E Statesville Blvd.
704.637.3367 • 704.754.2287
S45590
TUITION FREE TAX SCHOOL Register now for Liberty Tax’s 8-week class. Employment opportunities may be available upon successful completion. Fee for the 3 volume set of books.
Classes will be held at 718 N. Cannon Blvd., Kannapolis
Chatham County, looking for 10 members only. New hunting land. Call 704-933-4301 for more information.
Could you use
10 ,000 extra this year?
*
$
We buy, sell, and move pianos We offer Steinway, Baldwin, Mason & Hamlin, & more
Want to attract attention?
*Profits vary and could be more or less than this amount
C43576
S45632
Move In Ready
Fulton Heights - 3 BR, 2 BA, Attached carport, Rocking Chair front porch, nice yard. R50846 $129,900 Monica Poole 704.245.4628 B&R Realty
Move In Ready
HEATED POOL:
If interested, please come by the Post at 131 W. Innes Street, Salisbury and fill out an application or give us a call at the Circulation Department (704) 797-4213, Monday - Friday 8 am - 5 pm
Concord, 1.5 story, level lot, nice subdivision. Thousands below tax value. Tons of extras, crown molding, work island in kitchen, office upstairs, bonus room. 3 BR, 2.5 Baths. $244,750. Dream Weaver Properties of NC LLC 704-906-7207
Classes start 9-13-10
Afternoon and evening available. Call 704-932-8822 for more info.
New Hunting Club! C44624
S42814
Salisbury, Henderson Estates, 3 BR, 2.5 BA, Basement, Double Attached Carport, R48766 $159,900 Monica Poole 704.245.4628 B&R Realty
FORECLOSURE
Notices
• Send any comments: salisburypost.com/subscription
West schools. 2,200 sq. ft. nice 3 BR, 2BA, large den with stone fireplace. Large sunroom, kitchen, dining, living and laundry rooms. Ceramic, Pergo and carpeted floors. Priced to sell. Must see! Move in ready. Make offer. 704-775-2395 and 704-279-6400
Get Bigger Type!
Fulton Heights - 3 BR, 2 BA, Attached carport, Rocking Chair front porch, nice yard. R50846 $129,900 Monica Poole 704.245.4628 B&R Realty
New Home
Salisbury. Forest Creek. 3 Bedroom, 1.5 bath. New home priced at only $98,900. R48764 B&R Realty 704.633.2394
6C • SUNDAY, SEPTEMBER 12, 2010 Homes for Sale 512 Gold Hill Dr. 1BA. $74,000. 2BR, Please Call 704-855-5353
Homes for Sale
Homes for Sale
Homes for Sale
New Listing
E. Schools. Lease purchase house. 3BR, 2BA. Garage, kit. appl., Please call 704-638-0108
SALISBURY
Rockwell 3 BR, 2 BA in Hunters Pointe. Above ground pool, garage, huge area that could easily finished upstairs. R51150A. $179,900. B&R Realty 704-633-2394
PRICED TO SELL Salis. 1414 Devonmere Pl., 3BR/2 ½BA “The Reserve”. Master on main, Beautiful hard-wood floors. 2,350 sq. ft. Fireplace, bonus room, many extras! 0.17 acre. Open floor plan. A must see! Great price at $193,000. 704-224-9052. FSBO
Over $10K below tax value!
Rockwell. 2 BR, 1 BA, hardwood floors, detached carport, handicap ramp. $99,900 R47208 B&R Realty 704.633.2394
SALISBURY
Granite Quarry-Garland Place, 3 BR, 2 BA, triple attached garage, single detached garage, whole house generator. Nice yard. R50640 $164,900 B&R Realty 704.633.2394
3 BR, 2 BA. Brand new, very functional floor plan, laundry room, kitchen and living room. R51068 Monica Poole B&R Realty. 704.245.4628
Salisbury, 3 BR, 2 BA. Well cared for, kitchen with granite, eat at bar, dining area, large living mature trees, room, garden spot, 2 car garage plus storage bldgs. $154,000. Monica Poole 704.245.4628 B&R Realty
PRIVACY
PRICE REDUCED
Reduced $20k
Tastefully decorated. 2BR, 2BA. Hardwood floors, great room w/gas logs and vaulted ceilings, Custom kitchen cabinets with builtin desk, dining room, Gorgeous sunroom, fenced concrete patio area. R49515A $169,900 B&R Realty Monica Poole 704.245.4628
Carolina's Auction Rod Poole, NCAL#2446 Salisbury (704)633-7369
1320 Rachel Lane. Over 2,100 sf – 4 BR 2 Bath, Great Room, Kitchen/ Dining Combo, Den, Large Master BR and Bath with huge walk in closet. Convenient to I-85. Certified for FHA financing. MLS #49776. Teresa Rufty, TMR Realty, Inc. (704) 433-2582
Perry's Overhead Doors Sales, Service & Installation, Residential / Commercial. Wesley Perry 704-279-7325
H H H H H
OLYMPIC DRYWALL Residential & Commercial Repair Service
704-279-2600
C.R. General Cleaning Service. Comm. & residential. Insured, Bonded. Spring Cleaning Specials! 704-433-1858
We Build Garages, 24x24 = $12,500. All sizes built! ~ 704-633-5033 ~
Christian mom for cleaning jobs & ironing. Great rates. 704-932-1069 or 704791-9185
Child Care and Nursery Schools
Pat's Cleaning Service 704-857-2891
Quality Affordable Childcare Clean, smokefree, reliable
WOW! Clean Again! September Special! Lowest Prices in Town, Veteran's Discount, Residential/Commercial References available upon request. For more info call 704-762-1402
6 wks & up! All Shifts Reasonable rates. 17 years experience.
Michelle, 704-603-7490 FReferences AvailableF
Cleaning Services
Classifeds 704-797-4220
H
Auctions
H
704-633-9295 FREE ESTIMATES Licensed, bonded and insured. Since 1985.
Auctions
Due to non-payment of rent Rowan Mini Storage will conduct an Auction on Sept. 14th , 9:30a.m. Any questions call 704-855-2443. Unit 504 - Darrell Martin Unit 521 – Kent Martin Unit 803 – Alexis Cowan
H H
Will do In-Home private Nursing. Call 704-8557491 or 980-234-8046
Lippard Garage Doors Installations, repairs, electric openers. 704636-7603 / 704-798-7603
Drastically Reduced! Salisbury & Shelby, 2, 3 & 4 BR, starting at $29,900! Must see! Call today 704-633-6035. Genesis Realty Homes 704-933-5000 for Sale genesisrealtyco.com Foreclosure Experts
Drywall Services
Caregiving Services
Carport and Garages
For Sale By Owner
Got a good web site? Include the URL in your ad.
Homes for Sale
New Construction! 3 acres!
Lake Property High Rock Lake
Fabulous View
Southwestern Rowan County, Barnhardt Meadows. Quality home sites in country setting, restricted, pool and pool House complete. Use your builder or let us build for you. Lots start at $24,900. B&R Realty 704-633-2394
Manufactured Home Sales
Beautifully Landscaped
Cleaning Services
Call Zonia 704-239-2770
H
Homes for Sale
Will also consider leasing with option to buy
Woodleaf
OPEN SUNDAY 2-4 PM
Free Estimates References Available
Rowan Auction Co. Professional Auction Services: Salis., NC 704-633-0809 Kip Jennings NCAL 6340.
Salisbury, 2 BR, 1 BA, Almost all new windows, some new carpet, nice home on dead end street, detached garage with dirt floor, beautiful large trees, nice sized lot. $79,900 B&R 51047 Realty. Dale Yontz 704.202.3663
Salisbury. 2 or 3 bedroom Townhomes. For information, call Summit Developers, Inc. 704-797-0200
Cameron Glen. Be amazed at the quality! New construction on 3 acres. Hardwood floors throughout main level, beautiful kitchen cabinetry. Main floor master with a fantastic bath. 4 bedrooms 2 fulll baths up. Priced at $319,900. Call Jane Bryan @ 704-798-4474
More Details = Faster Sales!
Land for Sale
Waterfront High Rock Lake. 3BR, 2BA manufactured home. Big fenced yard w/ lots of trees. Deck, pier, floater, metal roof, & new ac unit. $270,000. Lazy Lane/Rowan Cty. 336-239-2287 Jill Conrad Uwharrie Real Estate
Land for Sale
South Rowan area. 220 Corriher Grange Rd. 3BR, 2BA. 3.4 acres. Fenced-in, great for livestock. Closed in patio. Double garage and carport. 2 buildings, and a lot more. $179,000. 704-920-9563
Country Paradise
Residential & Commercial
Heritage Auction Co. Glenn M.Hester NC#4453 Salisbury (704)636-9277
Homes for Sale
Lots for Sale
25 Acres Beautiful Land for Sale by Owner
Carport and Garages Auctions
Classifeds 704-797-4220, Nice home for price. 3 Bedrooms, 2 Baths, wooded lot, big rooms. 51017 $119,900 B&R Realty. Dale Yontz 704.202.3663
REDUCED
3BR, 2BA with 2 car garage in a nice neighborhood. Corner lot, hardwood floors, formal dining room, fenced back yard, rocking chair front porch. $149,900. Call 704-633-6824
Auction Thursday 12pm 429 N. Lee St. Salisbury Antiques, Collectibles, Used Furniture 704-213-4101
Salisbury, Nice home for price. 3 Bedrooms, 2 Baths, wooded lot, big rooms. 51017 $119,900 B&R Realty. Dale Yontz 704.202.3663
3 BR, 2 BA. Brand new, very functional floor plan, laundry room, kitchen and living room. R51068 Monica Poole B&R Realty. 704.245.4628
Salisbury, 2 BR, 1 BA, Almost all new windows, some new carpet, nice home on dead end street, detached garage with dirt beautiful large floor, trees, nice sized lot. 51047 $79,900 B&R Dale Yontz Realty. 704.202.3663
Land for Sale W. Rowan 1.19 acs. Old Stony Knob Rd. Possible owner financing. Reduced: $19,900. 704-640-3222
Salisbury
Salisbury, 3 BR, 2 BA. Well cared for, kitchen with granite, eat at bar, dining area, large living room, mature trees, garden spot, 2 car garage plus storage bldgs. $154,000. Monica Poole 704.245.4628 B&R Realty
Salisbury. 145 Equestrian Drive. 3BR, 2BA. 2 car garage, gutter guards, gas logs, laundry room, library. All new appliances, vaulted ceilings, chandeliers in each room. Large dressing room in master bedroom, water closet in master bath. Quiet area. Must see to appreciate! $149,000. 704-637-6567
Homes for Sale
Homes for Sale
Motivated Seller in Plantation Ridge
Close To Hospital
PRIVACY
Price Just Reduced!
Homes for Sale
Homes for Sale
Salisbury
Salisbury, 4BR/2BA Master BR has 2 closets, LR, bonus room, kitchen, D/R, hardwood floors & tile, sunroom, fireplace. Close to Hospitals, Parks, town & shopping ctrs. $129,000 or best offer. Owner will assist with closing if price is right. Call 828-448-7754 or 828-390-0835.
Proud of your company? Put your logo in the ad.
REDUCED
Bank Foreclosures & Distress Sales. These homes need work! For a FREE list:
Open House Sun., Sept. 12, 2-5pm.
SALISBURY POST
CLASSIFIED
Concrete Work
All types concrete work ~ Insured ~ NO JOB TOO SMALL! Call Curt LeBlanc today for Free Estimates
Getting first shot at qualified prospects is the fastest path to good results!
Since 1955 olympicdrywall@aol.com olympicdrywallcompany.com
Fencing Free Estimates Bud Shuler & Sons Fence Co. 225 W Kerr St 704-633-6620 or 704-638-2000 Price Leader since 1963
Reliable Fence All Your Fencing Needs, Reasonable Rates, 21 years experience. (704)640-0223
Financial Services “We can remove bankruptcies, judgments, liens, and bad loans from your credit file forever!”.
Salisbury. 130 Pine Hill Rd. Total Remodel. 3BR, 2BA. Gourmet kitchen with solid surface counter tops, Jenn Air range w/grill, custom cabinets, wood & tile floors, large walk-in closet, sunroom & sun porch, fireplace, large fenced yard, huge screen porch w/Baja hot tub. 28x28 garage w/insulated walls/doors/ceiling. $40K + in landscaping. Within 2 miles of North Hills, Scared Heart & Isenberg schools but no city taxes. 704-202-5022 Owner is Broker/Realtor
Beaver Grading Quality work, reasonable rates. Free Estimates 704-6364592 Grading, Clearing, Hauling, and Topsoil. Please Call 704-633-1088
Heating and Air Conditioning Piedmont AC & Heating Electrical Services Lowest prices in town!! 704-213-4022
Home Improvement
Home Improvement
Junk Removal
A HANDYMAN & MOORE Kitchen & Bath remodeling Quality Home Improvements Carpentry, Plumbing, Electric Clark Moore 704-213-4471
HMC Handyman Services No Job too Large or Small. Please call 704-239-4883
CASH FOR JUNK CARS And batteries. Call 704-279-7480 or 704-798-2930
Around the House Repairs Carpentry. Electrical. Plumbing. H & H Construction 704-633-2219
Brisson - HandyMan Home Repair, Carpentry, Plumbing, Electrical, etc. Insured. 704-798-8199
Kitchens, Baths, Sunrooms, Remodel, Additions, Wood & Composite Decks, Garages, Vinyl Rails, Windows, Siding. & Roofing. ~ 704-633-5033 ~
Browning ConstructionStructural repair, flooring installations, additions, decks, garages. 704-637-1578 LGC
House Cleaning
Garages, new homes, remodeling, roofing, siding, back hoe, loader 704-6369569 Maddry Const Lic G.C. Hometown Lawn Care & Handyman Service. Mowing, pressure washing, gutter cleaning, odd jobs ~inside & out. Comm, res. Insured. Free estimates. “No job too small” 704-433-7514 Larry Sheets, owner
Professional Services Unlimited Licensed Gen. Contractor #17608. Complete contracting service specializing in foundation & structural floor repairs, basement & crawlspace waterproofing & removal, termite & rot damage, ventilation. 35 yrs exper. Call Duke @ 704-6333584. Visit our website:-
Lawn Equipment Repair Services
Lawn Maint. & Landscaping Brown's Landscape & Bush Hogging, plowing & tilling for gardens & yards. Free Est. 704-224-6558
Earl's Lawn Care 3 Mowing 3 Seeding 3 Trimming Bushes
3 Landscaping 3Core Aeration 3Fertilizing
Junk Removal
FREE Estimates
704-636-3415 704-640-3842 GAYLOR'S LAWNCARE For ALL your lawn care needs! *FREE ESTIMATES* 704-639-9925/ 704-640-0542
$ $ $ $ $ $ $ $ $ $ We Buy Any Type of Scrap Metal At the Best Prices...
We will come to you! F David, 704-314-7846
Outdoors by overcash Mowing, Mulching, Leaf Removal. Free Estimates. 704-630-0120
Lawn Maint. & Landscaping
Yard Work & more! Painting, window cleaning. All jobs welcome! Free estimates. 704-837-5069
Guaranteed! F
Miscellaneous Services
Large Groups Welcome!
Moving and Storage TH Jones Mini-Max Storage 116 Balfour Street Granite Quarry Please 704-279-3808
Painting and Decorating Bowen Painting Interior and Exterior Painting 704-630-6976. Cathy's Painting Service Interior & exterior, new & repaints. 704-279-5335
SEAMLESS GUTTER Licensed Contractor C.M. Walton Construction, 704-202-8181.
• Stoner Painting Contractor
The Floor Doctor
Ads that work pay for themselves. Ads that don’t work are expensive. Description brings results!
Roofing and Guttering
BowenPainting@yahoo.com
alservicesunltd.com
Complete crawlspace work, Wood floor leveling, jacks installed, rotten wood replaced due to water or termites, brick/block/tile work, foundations, etc. 704-933-3494
15 minutes N. of Salisbury. 2001 model singlewide 3 bdr/2 bath on large treed lot in quiet neighborhood. $1,200 start-up, $475/mo includes lot rent, home payment, taxes, insurance. RENT or RENTTO-OWN. 704-210-8176.
* 1 Day Class *
Lyerly's ATV & Mower Repair Free estimates. All types of repairs Pickup/delivery avail. 704-642-2787
Home Maid Cleaning Service, 10 yrs. exp, Free Estimates & References. Call Regina 704.791.0046
A message from the Salisbury Post and the FTC.
Grading & Hauling. Safe distance from cities. Needs to be sold this year. No reasonable offer refused. Owner phone: 336-766-6779, or E-mail to: hjthabet@cs.com See photos and directions at:
• 25 years exp. • Int./Ext. painting • Pressure washing • Staining • Insured & Bonded 704-239-7553
Junk Removal
Manufactured Home Services
Pools and Supplies
Anthony's Scrap Metal Service. Top prices paid for any type of metal or batteries. Free haul away. 704-433-1951
Mobile Home Supplies~ City Consignment Company New & Used Furniture. Please Call 704636-2004
Bost Pools – Call me about your swimming pool. Installation, service, liner & replacement. (704) 637-1617.
Manufactured Home Sales $500 Down moves you in. Call and ask me how? Please call (704) 225-8850 NEW Government Approved Homes. Online Pre-qualification. For Info (888) 350-0035 Salisbury Area 3 or 4 bedroom, 2 baths, $500 down under $700 per month. 704-225-8850
Real Estate Commercial
Real Estate Services Allen Tate Realtors Daniel Almazan, Broker 704-202-0091 Arey RealtyREAL Service in Real Estate 704-633-5334
Downtown Salis, 2300 sf office space, remodeled, off street pking. 633-7300
Wanted: Real Estate
China Grove. One room eff. w/ private bathroom & kitchenette. All utilities incl'd. $379/mo. + $100 deposit. 704-857-8112
Granite Quarry. 2BR duplex. Appli. furnished. W/D hook up. $425. No pets. 704-279-3406
1BR & 3BR units avail. HVAC. Application req'd. $475 - $800/mo. Call 704-239-4883. Broker
Meadowbrook. 3 BR, 1.5 BA, central heat/ac. $725/mo. + $725 deposit. Lease references req'd. Serious inquiries only. 704-279-5382
*Cash in 7 days or less *Facing or In Foreclosure *Properties in any condition *No property too small/large Call 24 hours, 7 days ** 704-239-2033 ** $$$$$$ Are you trying to sell your property? We guarantee a sale within 1430 days. 704-245-2604
CLANCY HILLS APARTMENTS 1, 2 & 3 BR, conveniently located in Salisbury. Handicap accessible units available. Section 8 assistance available. 704-6366408. Office Hours: M–F 9:00-12:00. TDD Relay 1-800-735-2962 Equal Housing Opportunity. Clancy-hills@cmc-nc.com
Clean, well maint., 2 BR Duplex. Central heat/air, all electric. Section 8 welcome. 704-202-5790
Apartments $$ $ $ $ $ $-232-0994 112-A Overbrook Rd, 2BR, Lg. 2 story, $535/mo, refs & lease. 9am-5pm, M-F 704-637-0775 128-138 Pearl St. 2 BR, All electric. $450. Please call 704-213-3963 or 704279-2679 2BR, 1BA apt. Very large. Has gas heat. We furnish refrig, stove, yard maint, and garbage pick up. No pets. Rent $400. Deposit $400. Call Rowan Properties 704633-0446
Airport Rd. Duplex. 2BR, 2BA. $575/mo. 2BR, 1BA $550/mo., lease + dep., water furnished. No pets. Call 704-637-0370
OFFICE SPACE
BEST VALUE Quiet & Convenient, 2 bedroom town house, 1½ baths. All Electric, Central heat/air, no pets, pool. $550/mo. Includes water & basic cable.
Colonial Village Apts. “A Good Place to Live” 1, 2, & 3 Bedrooms Affordable & Spacious Water Included 704-636-8385 Cone Mill area. 3 Shive St. 3 room furnished apt for rent. Please call 704-633-5397
East Rowan. 2 bedrooms, 1bath townhouse with basement. Stove and refrigerator furnished, Washer / Dryer connections. Located across from Granite Quarry Elem. School, close to I-85 and shopping. $450 per month. Flowe Realty & Development. Call 704-2797848 or 704-640-6869
Eastwind Apartments Low Rent Available For Elderly & Disabled. Rent Based on Social Security Income *Spacious 1 BR *Located on bus line *Washer/Dryer Hookups Call Fisher Realty at: 704-636-7485 for more information. Heights Fleming Apartments 55 & older 704-636-5655 Mon.-Fri. 2pm-5pm. Call for more information. Equal Housing Opportunity. TDD Sect. 8 vouchers accepted. 800-735-2962
Condos and Townhomes Back to School Specials!
2BR RENT TO OWN Central heat/AC. Hardwoods, fireplace, siding. $2,500 down. $550/mo. 704-630-0695 314 North Ave, Kann - 3 BR, 2 BA $850/mo. 804 Hillcrest, Kann. 4BR, 2.5BA $990/mo. KREA 704-933-2231 317 MLK Jr. Blvd. Beautiful completely remodeled 4BR / 1½BA home nr pk, shopping & food. Gas heat, a/c, stove & fridge w/ice. $850/mo. + dep. 704-633-3584 529 East Liberty St. 3BR, 2BA. $600/mo.Gas heat. Electric air. No pets. 704-633-0425 530 West Franklin St. 3BR, 2BA. $600/mo. Gas heat. Electric air. No pets. 704-633-0425 5BR, 2 ½ BA. RENT TO OWN. 3000 sq. ft. +/basement, garage, fenced. $8,000 down. $998/mo. 704-630-0695 Available for rent – Homes and Apartments. Eddie Hampton 704-640-7575
Salisbury off I-85, 2BR / 1BA, country setting, water furnished, $475/mo + dep. 704-640-5750
Carolina Blvd. 2BR/2BA + ofc, all appls incl, 4 car carport, big yd. $800/mo + dep. 704-637-6618
Spencer. 2 BR, 1 BA spacious. apt. $400/mo. No pets. Please call 704798-3896
China Grove 2BR/1BA, appls furnished, storage bldg. Section 8 okay. No pets. 704-279-3990½BA Condo. All appl., W/D, patio. Near Jake & I-85. Pool, Tennis. $600/ mo., $500 dep. Freshly painted & carpet cleaned. For sale or lease. 336210-5862 Wiltshire Village Condo for Rent, $700. 2nd floor. Looking for 2BR, 2BA in a quiet community setting? Call Bryce, Wallace Realty 704-2021319
Wiltshire Village. 2BR. New appliances, carpet. Pool & tennis. $595/mo. 704-642-2554
China Grove. 2BR, 2BA. All electric. Clean & safe. No pets. $575/month + deposit. 704-202-0605
Salisbury & Mocksville HUD – Section 8 Nice 2 to 5 BR homes. Call us 1st. 704-630-0695 Salisbury 2BR. $525 and up. GOODMAN RENTALS 704-633-4802 Salisbury 4BR/2BA, brick ranch, basement, 2,000 SF, garage, nice area. $1,195/mo. 704-630-0695 Salisbury City Limits. 2 Bedroom, central heat and air. $500 per month + deposit. 704-232-9121 Salisbury, in country. 3BR, 2BA. With in-law apartment. $1000/mo. No pets. Deposit & ref. 704855-2100 Salisbury- Hidden Creek. 2 bedrooms/2 baths. Ground level across from Clubhouse. No pets or smokers. $750.00 Call Waggoner Realty Co. at 704-633-0462
China Grove Nice & Clean. 3 BR, 2 BA, 1840 square feet. 10 rooms, recently remodeled, stove, fridge, dishwasher. All electric HVAC, garages & storage buildings. Nice Area. NO PETS. $800/mo + deposit 704-857-7699 Concord, 3BR/2BA & lg fenced in yd, new linoleum, carpet and paint. $700/mo + $500 dep. 704-798-6821 East area. 2BR, 1BA. year Outbuildings. 1 lease. $695/month + 704-279-5602 deposit. East Rowan. Nice 2BR. Lots of storage. Quiet area. Private back yard. $565/mo. 704-279-5018 EXCEPTIONAL HOME FOR RENT
520 East Salisbury. Liberty St. & 550 Hope Hill Rd. Double wide mobile home. 3BR. $500/mo. ea 704-645-9986 Salisbury. Meadowbrook. 4BR, 2½BA. Off Statesville Blvd., close to Catawba College, convenient to city & I-85. Quiet neighborhood. Call 252-916-1841
Colony Garden Apartments 2BR and 1-1/2 BA Town Homes $575/mo. College Students Welcome! Near Salisbury VA Hospital 704-762-0795
3 BR,1 BA, Private Country setting, completely renovated older home, detached 1.5 car garage. All appliances included. $750 per month plus security deposit. Call 704-798-5959 FREE RENT Carolina Piedmont Properties. Call for details. Sec 8 OK. 704-248-4878
Which is ‘better?’ Print or online? It’s a great debate. One thing’s for sure: Salisbury Post and SalisburyPost.com provide you with the latest latest updates to all the breaking news in Salisbury and Rowan County - plus video from local high school sports teams, and more! Log on to or call 704-633-8950 to subscribe!
Office Space
Salisbury. We have office suites available in the Executive Center. With all utilities from $250 and up. Lots of amenities. Call Karen Rufty at B & R Realty 704-202-6041
Restaurant fully equipped. 85 feat In china grove. $1700 per month. 704-855-2100
Salisbury, Kent Executive Park office suites, $100 & up. Utilities paid. Conference room, internet access, break room, ample parking. 704-202-5879
5,000 or 10,000 sq. ft. distribution bldg., loading docks, office & restrooms. Bradshaw Real Estate 704-633-9011
Commercial warehouses available. 1,400 sq. ft. w/dock. Gated w/security cameras. Convenient to I-85. Olympic Crown Storage. 704-630-0066
Corner Lot
Autos
West Rowan area. Large 4 BR 2BA manufactured home for rent with option to buy. Call for more info. 704-855-2300
Rooms for Rent MILLER HOTEL Rooms for Rent Weekly $110 & up 704-855-2100
07 KIA SORENTO LX **1 Owner**, Clean Carfax, V6, Auto, PW, PL, Tilt, A/C, CD, Alloys. $11,993 Stk. #10K135A 704.637.9090
Salis. Bus line, A/C & cable No Drugs! Discount if paid monthly. Please call 704-640-5154
Wanted: To Rent Need 4-5 Bedroom home, rent or lease, East Rowan school district, required. 704-591-8118 anytime
08 FORD FOCUS S 4 cyl., auto., ac, cd, great on gas. Only $9991. 704.637.9090
Autos
03 FORD TAURUS SEL V6, auto., leather, power sunroof, pw, pl, tilt, cruise, loaded, low miles, $9990. 704.637.9090
03 MERCURY SABLE GS **Low Miles** Local Trade, Clean Carfax, V6, Auto, PW, PL, Tilt, Cruise, A/C, Alloys. $6,996 Stk. # 10H711A 704.637.9090
Cadillac, 2003 Deville Bronze Mist on Oatmeal leather 4.6 V8 North Star with auto tranny am, fm, cd, tape, all power options, like new inside & out RUNS & DRIVE NEW! 704-603-4255
Cadillac, 2005 STS V6 Sedan. Convertible. 5 speed auto. $16,418. 1-800-542-9758 Stock #T10687A 2 Year Warranty
Manufactured Home Lot Rentals
W Rowan & Woodleaf school district. 2BR/1BA house. Taking applications. No pets. 704-754-7421
Office and Commercial Rental
Manufactured Home for Rent
Salisbury 848 S. Main St., 1,000 SF previously restaurant w/drive-in window, lg pkg area, $800/mo 704-202-5879
South Rowan area. Attractive mobile home lots. Water, garbage, sewer furnished. $160/mo. 704636-1312 or 704-798-0497
China Grove. 1200 sq ft. $800/mo + deposit. Call 704-855-2100
My ‘better’ half.
Office and Commercial Rental
Salisbury/Spencer 2, 4 & 5 BR $450-$850/mo. 704202-3644 or leave message. No calls after 7pm
$$$$$$ $$$$$$$ Rockwell Offices 3 months free 704-239-0691
704-633-1234 China Grove 2BR Apt. $550/month. Includes water and garbage pickup. Call 704-857-2415.
Rockwell. 3BR, 2BA. Neighborhood. Central air. $750/mo. 704-6409636 or 704-637-9562
Salisbury. 515 Park Ave. 3BR, 1BA. Heat/AC. No pets. $650/mo. & $650 dep. 704-857-3347
West Side Manor Robert Cobb Rentals 2345 Statesville Blvd. Near Salisbury Mall
Salisbury. Off 13th St. Huge lot. Could be nice home, too. Conveniently located. 1200+ sq. ft. with lots of extras. Call our office for more information. C48040. $129,900. B&R Realty 704-6332394
Houses for Rent Houses: 3BRs, 1BA. Apartments: 2 & 3 BRs, 1BA Deposit req'd. Faith Realty 704-630-9650
US Realty 516 W. Innes, Salisbury 704-636-9303
Real Estate Commercial
Houses for Rent $$$$$$$$$$$$$$ 2 Spectacular Homes $950-$1300 704-239-0691
Airport Rd. 1BR, 1BA. Water, trash and yard care included. $395/mo, 704-633-0425
William R. Kennedy Realty 428 E. Fisher Street 704-638-0673
Apartments Granite Quarry 1 & 3 BR rentals available. Appliances included. Call 704638-0108
Rowan Realty, Professional, Accountable, Personable . 704-633-1071
Apartments China Grove. Nice 2BR, 1BA. $525/month + deposit & references. No pets. 704-279-8428
Salisbury. 2BR, 1BA older mobile home for sale - all ready set up in park. $2,000. 704-232-1480 TRADE your HOME or USE your LAND. Land Homes. Well & septic can be incl'd. 704-984-6607
SUNDAY, SEPTEMBER 12, 2010 • 7C
CLASSIFIED
Cooleemee 2BR $100 / wk, $400 dep on ½ ac lot. 336-998-8797, 704-9751579 or 704-489-8840
05 CADILLAC CTS 3.6 V6, auto, leather, moonroof, PW, PL, tile, cruise, chrome wheels, loaded $14,994 704.637.9090
Chevy, 2003 Cavalier Base blue with grey cloth interior am,fm,cd, 2.2 auto trans, cylinder runs&drives great. Perfect for the first time buyer! 704-603-4255
East Area. 2BR, water, trash. Limit 2. Dep. req. No pets. Call 704-6367531 or 704-202-4991 Faith 2BR/1BA, $375/mo + dep. 2BR/2BA Kannapolis $475/mo. + dep. No pets. 704-239-2833 Faith 2BR/2BA, 1 ac priv land, refrig. & stove. 3 people limit. No pets. $495/mo + dep. 704-239-5569
05 CHEVROLET AVEO LS 1.6 4 cyl., auto., AM/FM stereo, low, low miles, super gas saver. $7998. 704.637.9090
Gold Hill, 2 bedroom, trash and lawn service included. No pets. $450 month. 704-433-1255 High Rock Lake. 155 Sunshine Ln. 3BR, 2BA Cent. heat/AC. $450/mo. + dep. 704-279-2299 after 3pm Hurley School Rd area 2BR/1BA, nice subdivision, large lot. $460/mo + dep. 704-640-5750 Landis. 3BR,2BA laminate throughout, hardwoods nice quiet neighborhood. $580/mo. 704-855-2443
06 HONDA ACCORD EX-L 4 cyl, Auto, Leather, Moonroof, PW, PL, Tilt, Cruise, Alloys, CD, like new $11,747 704.637.9090
Chrysler, 2005 300 C Hemi engine tip tronic trans, all power, duel power and heated leather seats, am, fm, cd, tape, mp3, chrome rims A REAL HEAD TURNER! 704-603-4255
Ford 2004 Thunderbird, hard top convertible, all the amenities, V-8 3.9 Merlot color, liter, excellent condition 3,500 miles, has been kept in garage. $22,000. Call 707-310-1082
Rockwell. 2BR, 1BA. Appl., water, sewer, trash service incl. $500/mo. + dep. Pets OK. 704-279-7463
12,000 sq ft building on Jake Alexander Blvd. Could be office or retail. Heat and air. Call 704-279-8377
South area. 2BR mobile home, remodel w/ A/C, $425/mo., $200 deposit. No pets. 704-857-2649
Granite Quarry Special Commercial Metal Bldgs for Small Trade Business, hobby shop space or storage. Units avail up to 1800 sq ft w/ office area. Video surveillance and ample parking. 704279-4422
Statesville Blvd. 2BR, 1BA. Appliances, water, sewer incl. $450/mo. + $450 dep. 704-279-7463 West & South Rowan. 2 & 3 BR. No pets. Perfect for 3. Water included. Please call 704-857-6951
PRIOR TO RENTING VISIT or CALL A PA R T M E N T S We Offer
06 NISSAN SENTRA 1.8 S **1 Owner**Clean Carfax** V6, Auto, PW, PL, Tilt, Cruise, A/C, Alloys. $8,997 Stk. # 11J1A 704.637.9090
07 CHEV. MALIBU LT **Local Trade** Clean Carfax** 4 Cyl, Auto, PW, PL, Tilt, Cruise, Great on Gas $11,944 Stk. # 10D61C 704.637.9090
Ford, 2003 Taurus SE $7,918. 1-800-542-9758 Stock # F10473A 2 Year Warranty
Honda, 2007 Accord LX 2.4 4 cylinder auto trans, am, fm, cd, white on tan cloth, power options, like new tires. A REAL MUST SEE!! 704-603-4255
PRICE~QUALITY~LOCATION 2BR ~ 1.5 BA ~ Starting at $555
Senior Discount
Water, Sewage & Garbage included
704-637-5588 WITH 12 MONTH LEASE
2205 Woodleaf Rd., Salisbury, NC 28147 Located at Woodleaf Road & Holly Avenue
C46365
SALISBURY POST
07 CHRYSLER TOWN & COUNTRY **1 Owner** Clean Carfax, Local Trade, 4 Cyl, Auto, PW, PL, Tilt, Cruise, A/C, Alloys. $10,997 Stk # 10H510A 704.637.9090
No. 60400 NOTICE TO CREDITORS Having qualified as Executor for the Estate of Geneva B. Goodnight, 112 North Arbor St., Kannapolis, NC 28081. This is to notify all persons, firms and corporations having claims against the said decedent to exhibit them to the undersigned on or before the 26th day of November, 2010, or this notice will be pleaded in bar of their recovery. All persons, firms and corporations indebted to said estate are notified to make immediate payment. This the 19th day of August, 2010. Floyd David Goodnight, III, Executor for the estate of Geneva B. Goodnight, File #10E838, 1614 W. C St., Kannapolis, NC 28081
Nissan, 2005 Maxima SL LOADED 3.5 V6 auto tiptronic trans, bose audio system, all power options, all HEATED OPTIONS, Duel power leather seats. Real head turner.704-6034255
Toyota, 2004 Corolla 1.8 4 cylinder auto trans, am, fm, cd. White over gray cloth, power options, GAS SAVER, runs and drives awesomely! Affordable, reliable transportation! 704-603-4255
8C • SUNDAY, SEPTEMBER 12, 2010 Autos
Autos
Service & Parts NEED CASH? We buy cars & scrap metal by the pound. Call for latest prices. Stricklin Auto & Truck Parts. Call 704-278-1122 or 888-378-1122
Pontiac, 2004 Grand Prix GT2 Sedan. Front wheel drive. $8,418. 1-800-542-9758 Stock # F10352A 2 Year Warranty
Transportation Dealerships
WE BUY VEHICLES FOR CASH! ******** ALL MAKES, ALL MODELS ********
Transportation Financing
Trucks, SUVs & Vans
Trucks, SUVs & Vans
Chevrolet, 1978, 1 Ton & flat bed. Built for pulling 5th wheel trailer. 4 speed, 350 crate engine. 15,000 on new engine. Trailer brakes, reese hitch. Good truck. $3500 obo. 704-633-3822
Ford, 2004 F-150 Heritage XL Regular cab 1-800-542-9758 Stock #F10417A 2 Year Warranty
Troutman Motor Co. Highway 29 South, Concord, NC 704-782-3105
Transportation Financing
Chevy, 2005 Tahoe LS white w/ tan cloth interior 5.3 V8 auto trans, all pwr options, am, fm, tape, cd, 3rd seat, duel pwr seats, clean, cruise, alloy rims, drives great. Ready for retail! 704-603-4255
ELLIS AUTO AUCTION 10 miles N. of Salisbury, Hwy 601, Sale Every Wednesday night 6 pm.
Boats & Watercraft 1984 Mariner 90 Horse power boat motor. $750. Call 704-797-0193 between 6 - 9pm
Dodge, 2006 Durango LIMITED 4.7. V8 auto 4x4 Leather,DVD, all pwr options, duel power/ heated seats, rear POWER LIFT GATE, good tires, DON'T WANT TO MISS THIS ONE! 704-603-4255 2003 Ford Escape XLT 4x4 Silver on gray cloth 3.0 v6 auto tans, am, fm, cd changer, cruise, cold ac, alloy rims, good tires, RUNS & DRIVES WITH THE BEST OF THEM 704-603-4255
Buick, 2005 Rendezous CXL SUV. All wheel drive w/ locking. $12,718. 1-800-542-9758 Stock #P7533A 2 Year Warranty
Ford, 1998 Expedition Eddie Bauer Edition LOADED 5.4 V8 auto trans, LEATHER, lighted running boards, all pwr ops, cd changer, chrome rims good tires, 4X4 runs & drives great. 704-603-4255
Volvo, 2002 S80 2.9L6 TWIN TURBO auto tiptronic trans, am, fm, tape, cd, SUNROOF, alloy rims good tires, all power option, LEATHER, cold ac, COME DRIVE TODAY! 704-603-4255
Ford, 1999 Explorer XLT 4WD. 5 Speed auto. $7,918. 1-800-542-9758 Stock # F10325A 2 Year Warranty
Dump Trucks. 1988 Freightliner dump truck, $17,000. 1995 Kentworth dump truck $17,500. 336492-5764, 336-469-8409 or 704-929-7106
Service & Parts
EZGO Authorized
Call Classifieds to place your yard sale ad... 704-797-4220
Toyota, 2007 Sienna CE 4 door passenger van. $18,718. Stock #P7544 1-800-542-9758 2 Year Warranty
Want to Buy: Transportation DONATED passenger van or bus needed for newly formed Youth Group. Call Pastor Rob at 980-721-3371. Thanks for letting your love shine!
Chevy, 1999 Silverado 2500 hd extended 6.0 engine auto trans, am/fm radio, lighted running boards, camper top, towing pkg. 73,628 LOW MILES for this vehicle!! 704-603-4255
Chevy, 2003 Silverado V8 with auto tranny am, fm, cd, cold ac, bed liner, like new tires. Extra Clean Inside & Out! 704-603-4255
Ford, 2010 Ranger Extended cab. 5 speed auto, RWD $19,918. 1-800-542-9758 Stock # T10690A 2 Year Warranty
Dogs
Dogs
Got puppies or kittens for sale?
Schnauzer Miniature Puppies. Silver and black. $200-$250. Call 704-6370694
Cats
matter
GREAT FAMILY DOG!
Free kittens. 9 weeks old; friendly & playful. Several colors. 704-8578356 Free kittens. Approx. 8 weeks old. 2 males, 1 female. No shots. Litter trained. Weaned. Raised indoors. 704-682-5302 Free kittens. Beautiful, affectionate, litter box trained. First shots. 9 weeks old. 980-234-7759
Ford, 2003 Explorer 2 dr XLT sport. Good tires. Excellent condition. Clean & well maintained. 140,000 miles. $4,900. Call 704638-0226
Need home Urgently!
Ford, 2003 Ranger 4.0L, V6 4 x 4, Ext cab, 4-door. 86K, Tilt, PS, PW, Keyless, cruise, alloy wheels, bed liner, bed cover. $8,995. Call 704633-8184 (home) or 704637-7327
Mercedes, 2005 ML350 3.7 V6 Tiptronic trans, duel power and memory leather seats, SUNROOF, am, fm, cd, alloy rims good tires, EXTRA CLEAN!! 704-603-4255
Want to get results? Use
Headline type
to show your stuff!
look
Puppies, English Mastiff. AKC registered. Shots and wormed. Fawn and apricot colors. $600. Mocksville. 336391-2176
Lots of Love
Kittens: 1 female tabby cat and 2 tabby kittens. Free to a good home. Please call 704-209-1858
KIA, 2006 Sorento 3.5 V6 auto, 4x4, cloth seats, CD, towing pkg, good tires, all power, luggage rack, runs& drives NICE!! 704-603-4255
SOLD We sold our puppies in 2 days! Another great response after placing our Salisbury Post ad. ~ C.A., Salisbury
SOLD
Giving away kittens or puppies?
Jeep, 2000 Grand CherokeeLimited SUV $10,918. 1-800-542-9758 Stock #T11086A 2 Year Warranty
you
Puppies. Free to good Home. German Shepherd and Boxer mixed puppies. Male & Female left. Rockwell area. Call 704- 754-3204
Shih-Tzu, CKC registered. Very cute, playful, good w/kids, black & white. 6 weeks old & ready to go. First shot, wormed. (4 females, 4 males). Parents on-site. 704-640-4528 Salisbury location Mini Schnuazers. Gorgeous pups. Up-todate on shots, etc. AKC registered. $250 and up. Please call 704-232-2607
Free kittens. We found 5 kittens on 9/3. They have no mom & only about 2 wks old! Pls help save one! 336-909-0759
Commercial Vehicles & Trailers
Volkswagen, 2007 New Beetle 2.5 Convertible 6 speed automatic. $16,918. 1-800-542-9758 Stock #F10485A 2 Year Warranty
No
1330 W. JAKE ALEXANDER BLVD. ******** BILL BOUDREU
Free Kittens! Beautiful & playful male & female indoor, litter trained need loving kittens, Call Brenda homes. @336-671-3799
Trucks, SUVs & Vans
OVER 75 VEHICLES IN STOCK ********
Immaculate!
Toyota, 2004 Tacoma cab. Rear Extended wheel drive. $13,518. 1-800-542-9758 Stock #T11063A 2 Year Warranty
Ford, 2006 Expedition Eddie Bauer Edition. 22 Inch rims, Cd, DVD, sunroof, duel heated seats, power 3rd seat, luggage rack. Steering wheel controls, nonsmoker. Like new. MUST SEE! 704603-4255
Bentley, 1996, Brooklands. 72,500 miles. 2nd owner. All service records. Must see! $35,000. 704305-1901
100% Guaranteed Credit Approval ********* Sign language capable for the deaf *********
how
Call Steve today! 704-603-4255 Visit us at:
1330 W. JAKE ALEXANDER BLVD. ******** 100% GUARANTEED CREDIT APPROVAL ********
Autos
Trucks, SUVs & Vans
Bad Credit? No Credit? No Problem! Tim Marburger Dodge 877-792-9700
Nissa, 2007 Altima 2.5S $15,818. 1-800-542-9758 Stock # P7545 2 Year Warranty
Toyota, 2004 Corolla 1.8 4 cylinder auto trans, am, fm, cd. White over gray cloth, power options, GAS SAVER, runs and drives awesomely! Affordable, reliable transportation! 704-603-4255
Trucks, SUVs & Vans
1330 W. JAKE ALEXANDER BLVD. ********
SALISBURY POST
CLASSIFIED
Black Lab Collie Mix, free to a good home. Call 704-232-5063 for more information.
Chinese Pug Male, 2-3 years old. Housebroken. Shots. Needs a good home. Call 704-855-3578
Mini Rat Terrier puppies. UKC Registered. Tan Sable Tuxedo male and female. First shots, dewormed. $150. 704-2134756 Patented Happy Jack Flea Beacon: Control Fleas in the home without toxic chemicals or costly exterminators. Results GOODMAN overnight! FARM SUPPLY (857 5938)
Chow, red male, full blood, 1 ½ years old. Please Call 845-3376900 Dog. Free Malamute to a good home. Beautiful female needs love, yard, and a lap. 704-279-0169 Free puppies to good home. Have been unable to find owner. Trying to find home for them. 704431-4539
Very Small Toy Poodles
These sweet puppies are very small and beautiful. 2 black and 2 chocolate 1st shots and Worming. CKC reg. $400. Call Barbara, 704-970-8731
Dogs
Pit Bulls. Full blooded. CKC registered. All shots & dewormed. Parents on site. $125 neogtiable. Ready to go. Adults for sale also. Call Dale 704467-1945 Serious inquiries only.
at
Other Pets **********FREE********** Free Hamsters and Gerbils. Call 704-8578556. Please no calls after 9pm
it... it really doesn’t have bugs!
$ $ $ $ $ $ $
Cars, Homes, Services, Jobs & Exterminators
ALL
Supplies and Services
are found here
20% off Spay & Neuters in September. Call for appointment. $10/shot. Salisbury Animal Hospital 1500 E. Innes St. 704-637-0227
Classifieds!
salisburyanimalhospital.com
TO ADVERTISE CALL
(704) 797-4220
SUNDAY, SEPTEMBER 12, 2010 FOR FREE BIRTHDAY GREETINGS Please Fax, hand deliver or fill out form online 18 WORDS MAX. Number of free greetings per person may be limited, combined or excluded, contingent on space available.
A 2”x3” greeting with photo is only $20, and includes 4 copies of the Post
MawMaws Kozy Kitchen
Club Sandwich, Fries ....................$5.29 Grilled Hamburger Steak, 2 Sides & Tea ............................$5.99
Every Night Kids Under 12 eat for 99¢ with 2 paying Adults
Happy 30th birthday to our wonderful daughter, Amanda Long Reavis. Say goodbye to the 20's and hello 30's. We love you. Mom and Dad Happy Birthday, Dena Valisa Crowder! Wishing you God's best! Y our LCC family & Auntie
704-797-4220 birthday@salisburypost.com
Happy Birthday, Kolisha "KoKo" Sheffield! Wishing you many more! Your LCC family & Auntie
25 WINGS $
GRILLED CHICKEN SANDWICH $3.99
13.99
HOTDOGS – SATURDAY 11AM-4PM $
Happy Birthday Shannon, Have a great one! from nick & lisa
1.00
5550 Hwy 601 • Salisbury, NC 28147 • 704-647-9807 HOURS: Mon, Tues, Thurs, Fri, Sat: 11AM-8PM Wednesday 11AM-3PM • Closed on Sundays S46245
Team Bounce
FUN
Birthday? ...
We Deliver Parties, Church Events, Etc.)
Hours of daily personal attention and doggie fun at our safe 20 acre facility. Professional homestyle boarding, training, and play days with a certified handler/trainer who loves dogs as much as you do.
S45263
HAPPY BIRTHDAY!
Happy Birthday, Beulah Smith! Have a wonderful day! Your LCC family and Auntie 704-202-6200
We want to be your flower shop!
Salisbury Flower Shop S38321
Tell Someone
Happy 60th Birthday, Jean Partee! Wishing you many more "Cus!" Love, Agnes & Ralph
1628 West Innes St. Salisbury, NC • 704-633-5310
S40137
SALISBURY POST SUNDAY EVENING SEPTEMBER 12, 2010 A
SUNDAY, SEPTEMBER 12, 2010 • 9C
TV/HOROSCOPE
6:30
7:00
7:30
A - Time Warner/Salisbury/Metrolina
8:00
8:30
9:00
9:30
10:00
10:30
11:00
11:30
BROADCAST CHANNELS Tennis
^
60 Minutes (N) (In Stereo) Å
Big Brother The nomination cer- Undercover Boss Company presi- CSI: Miami A suburban mother is News 2 at 11 (:35) CSI: NY emony takes place. (N) (N) Å “Jamalot” dent collects garbage. murdered. (In Stereo) Å 60 Minutes (N) (In Stereo) Å (4:00) Tennis Big Brother The nomination Undercover Boss “Waste CSI: Miami “Mommie Deadest” A WBTV 3 News (:20) Point After U.S. Open, Men’s ceremony takes place. (N) (In Management” Company president suburban mother is murdered. (In at 11 PM (N) With D and D Final. Stereo) Å collects garbage. Å Stereo) Å (4:00) NFL Football Regional The OT (In The Simpsons The Cleveland Family Guy FOX 8 10:00 News (N) Family Guy TMZ (N) (In Stereo) Å Coverage. (In Stereo Live) Å Stereo Live) Å “American “Jerome Is the Stewie attends a Show Å History X-cellent” New Black” concert. ABC World America’s Funniest Home Videos America’s Funniest Home Videos Extreme Makeover: Home Edition The Gates “Surfacing” Nick’s past Eyewitness (:35) Hot Topic News Sunday (In Stereo) Å Daredevils’ stunts go awry. (In “Morris Family” Rebuilding a home comes back to haunt him. (N) (In News Tonight (Live). (N) Å Stereo) Å and daycare. Å Stereo) Å (N) Å NBC Nightly Football Night in America With (:15) NFL Football Dallas Cowboys at Washington Redskins. From FedEx Field in Landover, Md. (In Stereo Live) Å WXII 12 News at News (N) (In Bob Costas, Tony Dungy, Rodney 11 (N) Å Stereo) Å Harrison and Dan Patrick. Family Guy Fox News at Fox News Got The Ernest Angley Hour (4:00) NFL Football Regional The OT (In The Simpsons The Cleveland Family Guy Game Show Å Coverage. (In Stereo Live) Å Stereo Live) Å “American “Jerome Is the Stewie attends a 10 (N) concert. History X-cellent” New Black” NBC Nightly Football Night in America With (:15) NFL Football Dallas Cowboys at Washington Redskins. From FedEx Field in Landover, Md. (In Stereo Live) Å NewsChannel News (N) (In Bob Costas, Tony Dungy, Rodney 36 News at Stereo) Å Harrison and Dan Patrick. 11:00 (N) (:00) Healthwise Adventure Lodges of North A Summer of Birds (In Stereo) Å The Blue Ridge Parkway: A Long Solar Car: The Secrets of RA7 (In Depression: Out of the Shadows America Å & Winding Road Å Stereo) Å (In Stereo) Å America’s Funniest Home Videos America’s Funniest Home Videos Extreme Makeover: Home Edition The Gates “Surfacing” Nick’s past Frasier (In ABC World N.C. State Stereo) Å News Sunday (In Stereo) Å (In Stereo) Å “Morris Family” Å comes back to haunt him. Coaches Show Tim McCarver Family Guy (In Smash Cuts Smash Cuts Movie: ››‡ “Out of Time” (2003) Denzel Washington, Eva Mendes, WJZY News at (:35) Charlotte (:05) NCSU Coaches Show Show Now 10 (N) Stereo) Å (N) Å (N) Å Sanaa Lathan. Desp.-Wives NUMB3RS (In Stereo) Å Deadliest Catch “Man vs. Ice” Legend of the Seeker Å Triad Today According-Jim Jack Van Impe Paid Program (:00) Da Vinci’s Lost “Across the Sea” Locke’s That ’70s Show That ’70s Show Frasier A caller’s Seinfeld Jerry Boston Legal Alan defends Denny, George Lopez George Lopez catches Uncle who has been arrested for illegally Carmen dates a “Fishing Cubans” Inquest (In motives are finally explained. (In “Christmas” Å “I’m a Boy” Å ex confronts popular boy. Leo shoplifting. shipping human fat. Å Stereo) Å Stereo) Å Frasier. Great Performances “Pavarotti: A Life in Seven Arias” Italian tenor (:00) Ed Sullivan’s Rock and Roll Andy Williams: Moon River and Me Musical perEastEnders (In EastEnders (In Luciano Pavarotti’s international success. (In Stereo) Å Classics: The 60s Å formances from the singer’s Emmy-winning series Stereo) Å Stereo) Å include “Moon River” and “Danny Boy.”
CABLE CHANNELS A&E
Criminal 36 (:00) Minds Å
AMC
27
ANIM BET BRAVO CNBC CNN
38 59 37 34 32
DISC
35
DISN
54
E!
49
ESPN
39
ESPN2
68
FAM
29
FSCR FX FXNWS GOLF HALL HGTV
Criminal Minds “Catching Out” Criminal Minds “Reckoner” A case Criminal Minds “Hopeless” The The Glades A dead man in a The Glades A dead man in a Serial killer jumps trains. Å in Rossi’s hometown. swimming pool. Å BAU goes on a manhunt. swimming pool. (N) Å Movie: ›› “Broken Arrow” (1996) John Travolta, Christian Slater, Samantha Mathis. Rubicon Miles and Tanya go on a Mad Men “The Summer Man” A (:02) Mad Men “The Summer Man” Premiere. high-jinx in the office. (N) CIA mission. (N) Å A high-jinx in the office. Confessions Pit Boss Shorty helps Jordan. The Haunted “Lady in White” The Haunted “Leave House” The Haunted “The Door” The Haunted “Lady in White” (5:30) Movie: “The Great Debaters” (2007) Movie: “The Ditchdigger’s Daughters” (1997) Carl Lumbly. Changing Lanes Inspiration Peter Popoff (:00) Top Chef Top Chef “Covert Cuisine” Top Chef “Gastro-nauts” Law & Order: Criminal Intent Top Chef Å Top Chef “Finale” Å Paid Program Diabetes Life Wall Street As Seen on TV Biography on CNBC Å Tom Brokaw Reports: Boomer$! Newsroom Newsroom State of the Union Larry King Live Newsroom State of the Union (:00) Dual Dual Survival Surviving a hurriMovie: ››› “Earth” (2007) Narrated by James Earl Jones. Premiere. Mysteries of the Mediterranean Movie: ››› “Earth” (2007) (In Survival Å cane’s aftermath. Å (In Stereo) Å (N) (In Stereo) Å Stereo) Å Wizards of The Suite Life The Suite Life Hannah Montana Good Luck Jonas L.A. “Boat Sonny With a Hannah Montana Hannah Montana Good Luck Good Luck Waverly Place on Deck Å on Deck Å Forever Charlie (N) Forever Charlie Trip” (N) Forever Charlie Chance Deaths E! Curse of the Lottery 2 Kardashian Kardashian Kardashian Kardashian Kardashian The Spin Fashion Police The Soup (:00) Baseball SportsCenter (Live) Å MLB Baseball St. Louis Cardinals at Atlanta Braves. From Turner Field in Atlanta. (Live) SportsCenter (Live) Å Tonight Å Basketball Basketball FIBA World Championship, Final: Teams TBA. SportsCenter (Live) 2010 World Series of Poker “Snow White” Movie: ››› “Cars” (2006) Voices of Owen Wilson, Paul Newman, Bonnie Hunt. Å Movie: ››› “Cars” (2006) Voices of Owen Wilson, Paul Newman, Bonnie Hunt. Å
40 (:00) College Football Louisiana-Monroe at Arkansas.
World Poker Tour: Season 8 Golden Age Final Score College Foot Final Score Movie: ››› “Cloverfield” (2008) Michael Stahl-David, Mike Vogel, Movie: ›‡ “Jumper” (2008) Hayden Christensen, Jamie Bell, Samuel Sons of Anarchy “So” The aftermath of Abel’s kidnapping. Odette Yustman. L. Jackson. Fox News Huckabee FOX Report Huckabee Hannity Geraldo at Large Å Golf Central PGA Tour Golf Nationwide: Utah Championship, Final Round. From Sandy, Utah. Ryder Cup Highlights Ryder Cup Highlights Golf Central (5:00) Class Movie: “Fairfield Road” (2010) Jesse Metcalfe. Å Movie: “Class” (2010) Å Movie: “Ice Dreams” (2010) Jessica Cauffiel, Brady Smith. Å Designed-Sell House Hunters House Hunters Lien on Me (N) Å All American Handyman (N) House Hunters House Hunters Income Prop. Income Prop. America the Story of Us Cannibalism Secrets Revealed America the Pawn Stars Å Pawn Stars Å Ice Road Truckers “Convoy to Swamp People Joe and Tommy “Millennium” Å Story of Us Hell” (N) Å face the cannibal gator. Å Turning Point Victory-Christ Fellowship In Touch W/Charles Stanley Paid Program Ankerberg Giving Hope Manna-Fest Helpline Today Judy Jacobs. (5:00) “The Movie: ›› “Mad Money” (2008) Diane Keaton, Queen Latifah, Katie Movie: ›› “Bringing Down the House” (2003) Steve Martin, Queen Movie: ›› “Bringing Down the Client List” Å Holmes. Å Latifah, Eugene Levy. Å House” (2003) Å (:00) Movie: ›› “The Perfect Nanny” (2000) Dana Movie: “The Perfect Teacher” (2010) David Charvet. Premiere. A teen’s Movie: “The Perfect Assistant” (2008) Rachel Hunter, Chris Potter, Josie Davis. Å Barron, Susan Blakely. Å increasing obsession for her teacher leads to danger. Caught Caught on Camera Caught on Camera I Married the Beltway Sniper Predator Raw: Unseen Tapes The Skyjacker Alaska State Troopers Alaska State Troopers Alaska State Troopers Alaska State Troopers Alaska State Troopers George Lopez George Lopez The Nanny (In The Nanny (In Everybody The Troop (In iCarly (In Stereo) True Jackson, My Wife and My Wife and Everybody Hates Chris Stereo) Å VP Å Kids Å Kids Å Hates Chris Stereo) Å Stereo) Å Å Å Å (:00) Snapped Snapped “Amanda McGhee” Snapped “Yesenia Patino” Snapped “Michelle Hall” Å Snapped “Stacey Castor” (N) Snapped “Stacey Castor” Ultimate Fight The Ultimate Fighter (In Stereo) The Ultimate Fighter (In Stereo) Derek Dooley Spurrier College Football Georgia at South Carolina. College Football Oregon at Tennessee. Movie: “Ghost Town” (2009) Jessica Rose, Randy Wayne. Deadly (5:00) “The Movie: “Goblin” (2010) Camille Sullivan. A vacation becomes a night- Movie: “Carny” (2009) Lou ghosts terrorize a group of college students. Å Diamond Phillips. Å Seamstress” mare when a malevolent sprite steals a family’s baby. Movie: ››‡ “Last Holiday” My Boys “My (5:30) Movie: ››› “Hitch” (2005) Will Smith, Eva Movie: ››‡ “Last Holiday” (2006) Queen Latifah, Gérard Depardieu, My Boys (N) Men” (N) Mendes, Kevin James. Å LL Cool J. (2006) Å Movie: ››› “Bachelor in Paradise” (1961) Bob Hope, Lana Turner, (:15) Movie: ››› “Pat and Mike” (1952) Spencer Movie: ››› “Sex and the Single Girl” (1964) Tony Curtis, Natalie Tracy, Aldo Ray. Å (DVS) Wood, Henry Fonda. Janis Paige. Å (:00) LA Ink Hoarding: Buried Alive (N) The Man With Half a Body Hoarding: Buried Alive Å Freaky Eaters Freaky Eaters Hoarding: Buried Alive Å (4:15) Movie: ›››‡ “The Lord of the Rings: The Movie: ›››‡ “The Lord of the Rings: The Return of the King” (2003) Elijah Wood. Frodo and Sam march toward Mount Doom to destroy Two Towers” (2002) the ring, while Gandalf and warriors prepare for a final confrontation with Sauron and his allies. Police Video Cops Å Cops Å Cops Å Cops Å Cops Å Over the Limit Over the Limit Forensic Files Forensic Files Cops Å EverybodyEverybodyEverybodyEverybodyThe Andy The Andy The Andy M*A*S*H “A Full M*A*S*H Å M*A*S*H Å M*A*S*H Raymond Raymond Raymond Raymond Griffith Show Å Griffith Show Å Griffith Show Å Rich Day” “Bombed” Law & Order: Law & Order: Special Victims Law & Order: Special Victims Law & Order: Special Victims Law & Order: Special Victims Movie: ›› “National Treasure” Unit “Debt” (In Stereo) Å SVU Unit Condemned man. Å Unit Boy is abducted. Å Unit “Fault” (In Stereo) Å (2004) Nicolas Cage. Desp.-Wives Grey’s Anatomy Å House “Son of Coma Guy” Inside Edition Comedy.TV (In Stereo) Å Eyewitness NUMB3RS (In Stereo) Å WGN News at (:40) Instant Curb Your Curb Your Becker “Once Becker “Chris- Curb Your Curb Your Curb Your Becker “Blind Curb Your Nine (N) Å Enthusiasm Mess” Å Enthusiasm Upon a Time” Enthusiasm Enthusiasm Injustice” Enthusiasm Replay Å Enthusiasm
The 45 “X-Men: Last Stand”
PREMIUM CHANNELS
HBO2
Countdown to True Blood Eric plots his revenge Hung (Season Entourage (In (:05) Hung (In (:35) True Blood Å against Russell. Å Stereo) Å True Blood Finale) (N) Stereo) Å (:00) Boxing Yuriorkis Gamboa vs. Orlando Salido, Movie: ›› “The Time Traveler’s Wife” (2009) Rachel McAdams, Eric Movie: ›› “Ghosts of Girlfriends Past” (2009) Making Featherweights. (In Stereo) Å Bana, Arliss Howard. (In Stereo) Å Matthew McConaughey. Å Boardwalk Movie: ››‡ “Mission: Impossible” (1996) Tom Cruise, Jon Voight, “You Don’t Movie: ›› “Jennifer’s Body” (2009) Megan Fox. (:45) What to Movie: ›› “Gothika” (2003) Know Jack” Emmanuelle Béart. (In Stereo) Å Premiere. (In Stereo) Å Watch Å Halle Berry. (In Stereo) (5:50) Movie: ››› “The (:45) Movie: ››‡ “Sherlock Holmes” (2009) Robert Downey Jr., Jude Law, Rachel Movie: ›› “Fast & Furious” (2009) Vin Diesel, Paul Walker, Michelle Hangover” (2009) Å McAdams. (In Stereo) Å Rodriguez. (In Stereo) Å Movie: ›››‡ “Inglourious Basterds” (2009) Brad Pitt, Mélanie Dexter “Hello, Dexter Morgan” (5:30) “Disaster Movie: ››‡ “Tyler Perry’s the Family That Preys” (2008) Kathy Dexter takes drastic actions. Movie” Bates, Alfre Woodard. iTV. (In Stereo) Laurent, Christoph Waltz. iTV. (In Stereo)
(:45) Movie: ›‡ “Couples Retreat” (2009) Vince Vaughn, Jason 15 Bateman, Jon Favreau. (In Stereo) Å
302
HBO3
304
MAX
320
SHOW
340
Swift to sing about West debacle this year at VMAs tified because of the sensitivity of the matter. The song is on Swift’s upcoming album “Speak Now,” due out in October. SWIFT The source said Swift performed it during a secret rehearsal in Los Angeles for the VMAs on Friday. Though the West-Swift moment only lasted but a few minutes, it has endured for
Gallery shows both sides of Ansel Adams dispute
Next to the garage-sale find, the gallery will hang the work of photo-hobbyist Earl Brooks, who Adams’ family says is the real photographer behind Norsigian’s images.
R126702 opened.
Faith Road @ I-85 Exit 76 • Now Open Mon-Thurs at 1:45 PM
*AMERICAN, THE (R) 11:35AM 2:05PM 4:30PM 7:05PM 9:35PM EAT, PRAY, LOVE (PG-13) 2:30PM 8:15PM EXPENDABLES, THE (R) 11:50AM 2:25PM 5:05PM 7:40PM 10:05PM *FLIPPED (PG) 12:15PM 2:35PM 4:55PM 7:05PM 9:20PM *GOING THE DISTANCE (R)
11:30AM 2:00PM 4:25PM 7:00PM 9:30PM
*LAST EXORCISM, THE (PG-13)
12:25PM 2:40PM 4:45PM 7:15PM 9:25PM LOTTERY TICKET (PG-13) 12:10PM 2:50PM 5:10PM 7:35PM 10:00PM *MACHETE (R) 11:55AM 2:20PM 5:00PM 7:30PM 9:55PM
NANNY McPHEE RETURNS (PG) 12:20PM 5:40PM
OTHER GUYS, THE (PG-13) 12:05PM 5:45PM.
*RESIDENT EVIL: AFTERLIFE (3D)
(R) 12:00PM 2:25PM 4:50PM
Salisbury Gardens’ Respite Care Program and Innovative Senior CareSM (ISC) are here for you. We provide care in a homelike environment with the medical and therapy services needed to recover from an illness, a hospital stay or a recent surgery. Convenient Short-Term Stay Options with No Minimum Stay Required Affordable Daily Rates Physical, Speech and Occupational Therapies Available Through ISC Professional Nursing Staff Available 24/7 Three Daily Meals
2:15PM 4:40PM 7:10PM 9:45PM
TAKERS (PG-13) 11:40AM 2:10PM 4:35PM 7:25PM 9:50PM
TWILIGHT SAGA: ECLIPSE, THE (PG-13) 2:55PM 8:30PM VAMPIRES SUCK (PG-13) 12:30PM 2:45PM 4:50PM 6:55PM 9:05PM
Actor Dickie Moore (“Our Gang” films) is 85. Actor Ian Holm (“Lord of the Rings,” “Chariots of Fire”) is 79. Country singer George Jones is 79. Actress Linda Gray is 70. Singer Maria Muldaur is 67. Actor Joe Pantoliano is 59. Singer-guitarist Gerry Beckley of America is 58. Drummer Neil Peart of Rush is 58. Actor Peter Scolari is 55. Actress Rachel Ward is 53. Actress Amy Yasbeck is 48. Bassist Norwood Fisher of Fishbone is 45. Actor Darren E. Burrows (“Northern Exposure”) is 44. Singer Ben Folds is 44. Guitarist Larry LaLonde of Primus is 42. Actor Paul Walker is 37. Country singer Jennifer Nettles of Sugarland is 36. Actor Benjamin McKenzie (“The O.C.”) is 32.
Harry Warren Experienced Conservative Republican
To schedule a personal visit or for more information, please contact Kathleen Rooney at (704) 636-0588. Personalized Assisted Living Respect for Individual PreferencesSM 2201 Statesville Boulevard Salisbury, North Carolina 28147 (704) 636-0588 Innovative Senior Care and Respect for Individual Preferences are Service Marks of Brookdale Senior Living Inc., Nashville, TN, USA. 18450-ROP01-0910
VOTE FOR
House of Representatives District 77
7:20PM 9:40PM
SWITCH, THE (PG-13) 11:45AM
Today‘s celebrity birthdays
Recent hospital stay? Pending surgery?
*RESIDENT EVIL: AFTERLIFE (R)
1:10PM 3:35PM 6:00PM 8:25PM
United FeatUre Syndicate inc.
Rejuvenate. Revive. Restore.
R124542
NEW YORK (AP) — Be warned, Kanye: Taylor Swift has written a song about you, and she’s singing it at tonight iden-
Experiences are likely to come in many shapes and sizes in the year ahead and will be both good and bad, but they all can be used to expand your vision and establish greater stability in your affairs as the year unfolds. Virgo (Aug. 23-Sept. 22) — You’re likely to be happiest spending your time on arrangements or projects you personally direct. Instead of waiting for someone to tell you what to do, take control yourself. Libra (Sept. 23-Oct. 23) — Wait until the other guy makes the first move when it comes to negotiating something. You’ll know right away where things stand, and you will better comprehend what you’re dealing with. Scorpio (Oct. 24-Nov. 22) — It doesn’t have to be just a so-so day. Plan something serene and special to do with someone who means a lot to you, and you can turn it into a memorable time. Sagittarius (Nov. 23-Dec. 21) — There is little need to be fearful of challenging conditions. In fact, they could bring out the smarts you didn’t know you possessed, to overcome opposition and/or remove impediments. Capricorn (Dec. 22-Jan. 19) — Even though you might not be aware of it, you could have more than a few admirers observing you. This favorable impression will occur from just simply being yourself. Aquarius (Jan. 20-Feb. 19) — In situations where you are more motivated to achieve something than others might be, you’ll easily come out the winner. Be single-minded and keep your eyes focused on the target. Pisces (Feb. 20-March 20) — Your successes can be considerably enhanced simply by treating others as you would wish to be treated. It’s an old method, but it always works out to be an advantage. Aries (March 21-April 19) — Don’t think you have to live with something that has been unproductive for far too long. Use your smarts and ingenuity to make whatever changes are called for to improve matters. Taurus (April 20-May 20) — If you care enough to be an astute observer, you can learn something about handling abrasive issues. Once you see how easy it is to be a diplomat, you’ll never resort to a negative response again. Gemini (May 21-June 20) — Even though this might be a day of rest, you won’t be content with failing to utilize your time and talents productively. Plan to tackle a project or to be of service to someone who needs help. Cancer (June 21-July 22) — Even if you have to take it upon yourself to make plans for the entire family, do it. Others are looking to have some fun and to do something different, but they don’t have the imagination to come up with the ideas. Leo (July 23-Aug. 22) — The bargains are out there if you’re inclined to go shopping, and you should be able to make some good buys. If nothing more, hitting the retail outlets could prove to be fun.
R122513
HBO
Sunday, Sept. 12
Paid for by Harry WarrenNC77 - Melissa Hill Treasurer
R125129
10C • SUNDAY, SEPTEMBER 12, 2010
SALISBURY POST
W E AT H E R
Call 704-855-2122 1410 North Main St., China Grove, NC Call 704-637-7721
TOWNE & COUNTRY THE GOLD STANDARD
474 Jake Alexander Blvd., Salisbury, NC
NEW LISTINGS
OPEN HOUSES SUNDAY 2-4PM
Great home located in Pine Valley-3 Bd-2.5 Ba-1950 sqft-$139,900R51198
Hickory St-Landis-3 Bd-2 Ba-1248 sqft-$16,400-Call Jerry Davis-R51197
Brick 3 Bd-1.5 Bath with den. Updated heat/air, roof, windows and much more. Fenced back yard w/storage building. $99,500.Call Sue Maclamroc!
Milford Hills-3 Bd-1.5 Ba-$110,900-Call Cathy or Trent Griffin! R51165
Foggy Hollow Road-High Rock Lake-4 Bd-2.5 Ba-$339,000-Call Cathy or Trent Griffin! R51166
Morningside Drive-3 Bd-2 Ba-$112,900-R51169-Call Cathy or Trent Griffin! R51169
412 WILLOW ROAD This home has a lot to offer. The oversized main level master suite has huge walk in closet, new wood flooring and updated and beautifully decorated master bath. Kitchen has gorgeous granite counter tops, new stainless appliances and wonderful cabinet and pantry space. Lovely stacked stone fireplace. Something for everyone. Come take a look. DIRECTIONS: Jake Alexander to left on Woodleaf Road, left on Enon Church Road, left on White Oak, left on Willow house on the left.
250 DELTA DOWNS Are you picky and fussy? Then you will be delighted with this immaculate, ready to move into 3 bedroom, 2 bath home with greatroom, fireplace, well appointed eat-in kitchen, double garage and storage building. Sitting on a lovely landscaped lot. A must see home. $134,900. DIRECTIONS: West Innes Street, past Catawba College, right on Sells Rd, Follow Sells Road, to right on Delta Downs. Home on right.
Davis Farm-1.38 acres-4 Bd-3.5 Ba-$297,500-Call Jane Bryan ! R51181
No Long Street-3 Bd-2 Ba-$98,000-Call Mitzi CraneR51178
Chantilly Lane-3 Bd-2 Ba-$124,900-Call Heather Gurley! R51188
PRICE CHANGES
1141 GLENFIELD DRIVE
Richmond Road-4 Bd-3.5 Ba-REDUCED TO $409,000-R50424
Lovely 3 bedroom home. Formal dining, kitchen with lots of cabinets, greatroom with fireplace. Generous sized rooms & extra large master bath. Lots of closets! Some hardwood flooring. Screened rear porch & deck. 2 car attached garage PLUS 1 car detached. Great for workshop, etc. This home is a real treasure. Come by today! Directions: Hwy 150 West. Right on Sherrills Ford Rd., Left into Cameron Glen. Turn onto Glenfield. Home on left.
Sunset Pointe-5 Bd-4 Ba-REDUCED TO $398,000-R51000
Plantation Ridge-4 Bd-2.5 Ba-REDUCED TO $209,900-R50856
Jayne Land
C41150
Our professional team of agents can help you with all of your real estate needs
AGENTS ON DUTY
AGENTS
Jerry Davis
Mitzi Crane
REALTOR, GRI
REALTOR
REALTOR, GRI
704-433-6621
704-213-0826
704-798-4506 WENDY CARLTON, REALTOR............................704-640-9557 HEATHER GURLEY, REALTOR...........................704-640-3998 KATHERINE FLEMING, REALTOR .....................704-798-3429
5-Day 5-D ay Forecast for for Salisbury Salisbury Today
5th Street-4 Bd-2 Ba-$69,000-Call Sue Maclamroc! R51208
TRENT GRIFFIN, REALTOR ..............................704-798-4868 MILLIE STOUT, REALTOR, GRI .........................704-213-9601 BRANDON HIATT, REALTOR ............................704-798-4073
National Cities
Tonight
Monday
Tuesday
Wednesday
Thursday
High 85°
Low 58°
83°/ 58°
85°/ 56°
83°/ 54°
83°/ 61°
Patchy fog
Clear tonight
Sunny
Sunny and light winds
Mostly sunny
Partly cloudy
Today Hi Lo W 89 64 pc 72 58 sh 71 57 sh 79 46 pc 65 55 pc 78 59 pc 70 55 pc 92 74 pc 85 51 pc 74 56 pc 68 34 pc 93 77 t
City Atlanta Atlantic City Baltimore Billings Boston Chicago Cleveland Dallas Denver Detroit Fairbanks Houston
Today City Hi Lo W Indianapolis 80 59 s Kansas City 84 63 s Las Vegas 97 72 s Miami 90 76 t Minneapolis 77 54 pc New Orleans 91 74 t Omaha 85 60 s Philadelphia 69 60 r Phoenix 102 79 pc Salt Lake City 83 53 s Tucson 97 70 pc Washington, DC 73 61 sh
Tomorrow Hi Lo W 88 67 pc 81 59 pc 81 60 pc 80 47 pc 68 59 pc 75 53 pc 78 54 pc 94 74 pc 88 51 pc 76 52 pc 68 39 pc 92 76 t
Tomorrow Hi Lo W 82 57 pc 82 66 pc 100 73 s 90 77 t 70 50 pc 92 76 s 80 60 pc 80 61 pc 103 80 pc 87 55 pc 99 71 pc 83 62 pc
World Cities Today Hi Lo W 66 53 r 89 64 s 75 55 pc 60 50 pc 62 50 pc 93 68 s
City Amsterdam Beijing Berlin Buenos Aires Dublin Jerusalem
Tomorrow Hi Lo W 66 55 r 93 64 s 68 50 pc 62 53 pc 68 53 r 89 66 s
Knoxville Kn K le 83/56
Frank Franklin n 77 7 77/50 0
Winston Win Wins Salem a 83/ 6 83/56
Data from Salisbury through ough 6 p.m. yest. Temperature
Boone 76/ 76/47
Hi Hickory kkory 85/56
A Asheville s ville v lle 7 76 76/50
Ral Raleigh al 8 83/59
Salisbury Salisb S al sb b y bury 85/58 58 Charlotte ha t e 86/58
Sp Spartanburg nb 88/5 88/59
Kit Kitty Haw H Hawk w wk 76 76/67 6//67 6 7
Danville D l 81/56 Greensboro o Durham D h m 85/58 83/58 58 8
Cape Ha C Hatteras atter atte attera ter era ra ra ass 79 7 79/6 79/68 9/6 9/ /68 6
L Lumberton b be 88 88/65 5
G Greenville n e 85/61 61 Atlanta 86/61
SUN AND MOON
W Wilmington to 85/65 Co C Col Columbia bia 90/ 90/67
Darlin D Darli Darlington 90/63 /6 /63
Augusta Au A u ug 9 92 92/ 92/67 2/ 7 2/67
Sunset tonight.................... 7:33 p.m..................... ..... Moonrise today................... 11:57 a.m.................... A Allendale llen e ll Moonset today.................... 10:07 p.m..................... ............... . . . Al
9 90/65 /65 65
Savannah na ah 88/72 2
Mo M Mor Morehead o ehea oreh orehea hea h ad C ad Ci Cit City ittyy ity 8 7 81/67
Southport outh uth 8 85/67
Ch Charleston le les es 8 85 85/70 H Hilton n He Head e 8 85/ 85/76 5///76 6 Shown is today’s weather. Temperatures are today’s highs and tonight’s lows.
Lake
Observed
Above/Below Full Pool
High Rock Lake............. 650.57. -4.4299999999999 Badin Lake.................. 540.07. -1.9299999999999 Tuckertown Lake............ 595.1........... -0.9 Tillery Lake................... 278.............. ..............-1 -1 Blewett Falls.................177.9 ................. 177.9........... -1.1 Lake Norman................. 96.7............ -3.3
Locall W Weather. Weather eather. Global Community Community..
Charlotte e Yesterday.... 48 ........ good .......... ozone Today..... 43 ...... good N. C. Dept. of Environment and Natural Resources 0-50 good, 51-100 moderate, 101-150 unhealthy for sensitive grps., 151-200 unhealthy, 201-300 verryy unhealthy, 301-500 haazzardous
Seattle S ttle e Se e eat ea at atttle lle 67/55 6 67 7 7///5 5 55 5
10s San Sa an n Francisco Francisco Fr rancisco anc ncis isc scco o
30s
6 68/52 68 8 8/ 8/5 //5 5 52 2
H
Denver D e en n nver ver
71/61 71 7 1 1/61 //6 61
7 74/56 74 4//5 5 56 6
8 85 85/51 5//5 5 51 1
L 6 78//6 78/60 60 0
85/65 85/65 5//65 65
Cold Front
L
Washington W a asssh hin ng gttton g o on n 73/61 6 1 7 73 3//6 3/ 61
Kansas K Ka a ansas n nsssas as City as Ciitty
ng e e Los Los os A Angeles An ge ellle ess
60s
H A Atlanta tlla an an nttta a
Ell P E Paso aso
90s Warm Front 110s
LNNew e ew wY York Yo o orrrkk Detroit D e etroit ttroit rroit oiitt
50s
100s
77/54 7 7//5 5 4 77 54 78/59 7 8 8///5 5 59 9
40s
80s
Minneapolis M iin o liiss n nn n ne e ea ap po oli
79 9 9///4 46 79/46 7 4 6
Chicago C h hiiiccca a ag g go o
20s
70s
B Billings iilllllin in ng g gss
89/64 6 4 8 89 9//6 9/ 64
93/68 93 9 3 3//6 68 8 Miia Miami a am m mii 90//7 76 90/76 7 6
Stationary Front
Showers T-storms
H Houston ousstton
Rain Flurries
Snow Ice
Weather W eather eath Under Underground ground is pr proud oud to pr provide ovide The Salisbury Post with the very best weather information available
wunderground.com wundergr ound.com
Air Quality Ind Index ex
24 hours through 8 p.m. yest........... 0.02" 0.14" Month to date................................... ...................................0.14"
-0s
LAKE LEVELS
Today: 8.6 - med-high Monday: 10.2 - high Tuesday: 9.4 - med-high
Precipitation
-10s
Forecasts and graphics provided by Weather Underground @2010
Salisburry y
High.................................................... 71° Low..................................................... 66° Last year's high.................................. 81° Last year's low.................................... 57° ....................................57° Normal high........................................ 84° Normal low......................................... 65° Record high........................... 96° in 1925 Record low............................. 49° in 1956 .............................49° Humidity at noon............................... 64% ...............................64%
0s
Myrtle yr le yrtl eB Be Bea Beach ea each 8 86 86/67 6//67 6/6 6 /6
Aiken ken en ... ... .. ...... . .90 Sunrise-.............................. 7:02 a.m............................... 9 90/ 90/65 /6 6
Sep 15 Sep 23 Sep 30 Oct 7 First F Full Last New
Go Goldsboro bo b 83/63
Tomorrow Hi Lo W 68 57 s 62 44 pc 69 53 pc 82 66 pc 80 64 r 89 75 pc
Pollen Index
Almanac Regional Regio g onal W Weather eather
Today Hi Lo W 68 51 s 62 48 pc 69 44 r 80 64 pc 80 69 r 89 78 pc
City London Moscow Paris Rio Seoul Tokyo
93/77 9 93 3//7 77
INSIGHT
Chris Verner, Editorial Page Editor, 704-797-4262 cverner@salisburypost.com
Books Domestic violence drives the plot of Joshilyn Jackson’s new novel/5D, 6D
SUNDAY September 12, 2010
SALISBURY POST
1D
Ground Zero, nine years later BY SAMANTHA GROSS Associated Press
EW YORK — af-
N
The crumbling stone-and-mud walls of an ancient village lie adjacent to Bagram Airfield, north of Kabul.
Views of Afghanistan Ancient ruins and satellite dishes are part of a vivid countryside ack during my first week in country, I had the opportunity to travel around the eastern part of Afghanistan by UH60 helicopter. As a former Blackhawk pilot, it is my favorite way of getting around. I caught a ride with a National Guard outfit from one of the New England states over to Kabul. In order to get back, I had a ride lined up for late that afternoon, but I finished my business early, and when a pair of helicopters showed up at the airport I talked my way into a seat. I was basically a hitchhiker that day, and the sure thing sitting on the ramp with the blades turning seemed a better bet than the one that was supposed to show up a few hours later. They warned me that they had a number of stops to make and would be out for a couple of hours, but I told them I didn’t mind as long as my filling a seat wouldn’t affect their mission. Afghanistan is not Iraq. I had been there twice before, and from flying missions in
B
This is a blog posting by Lt. Col. Rodger T. Duncan, a career Army officer currently stationed in Afghanistan, at Bagram Airfield. Duncan is a graduate of East Rowan High (1975) and Appalachian State University (1985). You can find additional postings at the northern mountains in ’91 to working in downtown Baghdad in ’06 it looked more or less the same. The countryside was different between the north and the capital, but it all looked like
Iraq. There were villages and towns with electricity, automobiles, and often the roads were paved. The homes and shops reminded me of the old movies where the bazaar was bustling with people; and the buildings, while not necessarily modern by our standards, were still built in a recognizable fashion. I wish I had found the opportunity to travel more and see what other parts of Iraq were like, but overall it had entered the 20th century in most outward ways. However, all I had read of Afghanistan indicated that it was entirely different, and I wasn’t disappointed. As a quick piece of background, there are the ruins of an ancient village next to Bagram (my current “home”). The walls that are standing are built of stone and covered with mud. There are holes in the upper walls of some of the tall, two story structures, I assume for air circulation in the heat
An Afghan man and child appear as interested in the See AFGHANISTAN, 4D cameraman as he was in them.
Photos by Lt. Col. Rodger T. Duncan
The burned-out hulk of a Soviet military truck bears witness to an earlier war, while the red sign warns of hidden dangers.
See SITE, 4D
OPINION
2D • SUNDAY, SEPTEMBER 12, 2010
Forums feature Rowan candidates lection 2010 is so lively and important that we have three candidate forums scheduled in the coming weeks. The “we” includes Catawba College, the Rowan County Chamber of Commerce and the Salisbury Post. We’re teaming up again to help voters learn about the candidates and where they stand on the issues. All three forums will be held in the Tom Smith Auditorium in the Ketner School of Business building at Catawba College. Once again, our moderator will be the unflappable Dr. Michael ELIZABETH Bitzer, associate professor of political science and hisCOOK tory. He also chairs Catawba’s Department of History and Politics. Here’s the schedule: • Sept. 28, 6-8:15 p.m. Rowan County district attorney and sheriff and N.C.House District 77. We’ll focus on the D.A. and sheriff’s race in the first hour of this forum, 6-7 p.m., since both play key roles in Rowan County law and order. With D.A. Bill Kenerly retiring, two assistant D.A.s are competing for his job, Karen Biernacki from Kenerly’s office and Brandy Cook from the Cabarrus D.A.’s office. The sheriff’s race is always a hot one. Though last spring’s crowded slate of wannabes has narrowed from 11 to two, there’s still a great deal of interest in who’s going to be the county’s top law man. Republican Kevin Auten has the advantage of having been appointed sheriff to fulfill George Wilhelm’s unexpired term. Democrat John Noble, also an experienced law enforcement officer, proved in the spring that he can pull in a lot more votes than conventional wisdom might expect. The race is not over until they count the ballots. After a 15-minute break, the forum will focus on the race for one of Rowan’s two seats in the N.C. House, the one held by Democrat Lorene Coates. She’ll face Republican challenger Harry Warren. If the spring forums were any indication, Warren will make sure this is no cakewalk for Coates. Incumbency is a two-edged sword in this year of voter dissatisfaction. Coates must envy Fred Steen, the county’s other
Salisbury Post E
ISLAM AND CHRISTIANITY
Extremism is the threat ounting tension broke Thursday when the Rev. Terry Jones announced that his Florida church would not burn copies of the Quran on Sept. 11. The symbolic protest threatened to set off a destructive chain of events. That same day, we saw troubling local evidence of Christian doctrine being twisted to destructive ends. The FBI arrested 26-year-old Justin Carl Moose, accused in a plot to bomb a women’s clinic in North Carolina. Fortunately, the person seeking Moose’s expertise was an FBI plant. But Moose’s intention to “save a life, terminate an abortionist,” as he says on his Facebook page, was as real as the instructions he gave for building a bomb. Millions of Christians sing “Onward, Christian Soldier” and take its talk of war as metaphor, much like the Salvation Army. Millions study the Bible and find a message of peace to embrace. But, just as Islam can spawn terrorism by extremists, Christianity has its radicals. Moose is said to be a member of the Army of God, a Christian group that advocates violence in its quest to stop abortion. The Army of God claimed responsibility for the bombings committed by Eric Rudolph and has been connected to other violent acts. Many people abhor abortion and work to end it in peaceful ways. They open pregnancy support centers, lobby Congress and hold demonstrations. Christianity is not the threat; extremism is. “You don’t overcome murdering by murdering,” says Flip Benham, national director of Operation Rescue. Benham’s organization has been accused of encouraging violence, a charge it denies. Army of God adherents openly advocate violence. Moose’s arrest brings that threat uncomfortably close to home. He graduated from South Rowan High School and lives in Concord. If what the FBI says is true, he is a homegrown terrorist. Compare that to another Concord man who made headlines last week, Private First Class James McClamrock. McClamrock was one of the first U.S. soldiers to die in Iraq since the official end of combat operations. Only 22 and a preacher’s son, he joined the Army a year ago. He was “one of the good ones,” a family friend said. “He had his head on straight.” The country has millions more homegrown patriots than terrorists, more churches advocating harmony than threatening to burn Qurans. The wayward minority gets the attention, though, and shapes outside opinions. The extremists are the threat — to their own religion.
M
Common sense
(Or uncommon wisdom, as the case may be) “An eye for an eye makes the whole world blind.” — Gandhi
Moderately Confused
SALISBURY POST
House member, who has no opposition for re-election. • Oct. 5, 6-7:30 p.m., Rowan County Board of Education. Three seats are up for election on the school board, and with only one involving an incumbent, these races look wide open. With Karen Carpenter not seeking re-election to the North seat, Richard Miller, William Owens and Craig Pierce are competing to represent the district. Reversing the decline of enrollment at North Rowan High School has stumped the school board for the past few years, though not for lack of mulling it over. Voters from all parts of the county will have an interest in how these North area candidates would like to solve the problem. Like Carpenter, Patty Williams is not seeking re-election to the South seat. Seeking to replace her are Mike Caskey, L.A. Overcash and Troy Rushing. This should be interesting. Overcash has served on the board; been there, done that. Caskey has run before; been there, wanted to do that. And Rushing, executive director of Church of God Children’s Home in Concord for 16 years, brings a fresh perspective. Should be interesting. The third seat, representing West, has been a safe bet for incumbent Kay Wright Norman for some time; she won her first election to the board 15 years ago. But she has some strong challengers. Eric Trail, an assistant principal in Cabarrus County, used to work in the Rowan-Salisbury system and ran two years ago against Jim Emerson, the board’s chair. The third candidate, Donna Hogue, works in early childhood education and has the perspective of a parent with children in all three levels of the system right now -- elementary, middle and high school. • Oct. 14, 6-7:30 p.m., Rowan County Board of Commissioners. This is the grand finale, the race for the board with the greatest power to set the course for Rowan County and shape its image, the county commission. Three seats on the five-member board are up for election. On the Republican side, incumbent Tina Hall was eliminated in the primary, leaving Jon Barber and Chad Mitchell to seek re-election. The other Republican who survived the primary is Jim Sides, a twotime veteran of the board. Democrats also
have experience on the ticket: Leda Belk is a former board member, and Bill Burgin has served on Salisbury City Council and the Rowan-Salisbury Board of Education. • • • Post readers are inquisitive and plugged-in, and you have provided the best questions to ask candidates at our forums. So, please, ponder these races and send us questions that Dr. Bitzer can ask the candidates. Send as many as you want. What are the most important issues to you in this election? Let us hear about them. Here’s how to get questions to us: • E-mail: editor@salisburypost.com • Mail: Editor, Salisbury Post. P.O. Box 4839, Salisbury, NC 28144 • Deliver by hand to the Post at 131 W. Innes St. • Fax: 704-633-0009 • Call me: 704-797-4244 • Post your questions as comments at the end of this column at. I will forward all of the questions to Dr. Bitzer as soon as I get them. My interest in handling the questions is to learn what issues are on voters’ minds so we can address them in the Post’s election coverage. We hope to begin our series of candidate stories Sept. 13 with a district court judge race and finish by Oct. 13 with county commissioners — just in time for early voting. News happens, so the schedule of stories might change or stretch out. Voter dissatisfaction and frustration over the economy will play big roles in the 2010 elections, according to national pundits. Rowanvoters can at least be happy that they have good options. The slate shows depth of experience, from sheriff to county commission. This is different from the off years when yahoos come out of the woodwork to get their name on the ballot, never to be heard from again. Many of this year’s candidates have poured years of their lives into public service, and they’re asking for more. So send us your questions, study up on the candidates and vote. Early voting starts Oct. 14; the general election is Nov. 2. It’s your right. Use it. • • • Elizabeth Cook is editor of the Salisbury Post. E-mail: editor@salisburypost.com or 704-797-4244.
Mook’s Place/Mark Brincefield
School budget outcome always precarious This is a continuing series of articles addressing “frequently asked questions.”
cuts close to $1.5 million over the year before.
Question 2: What was the final outcome of the school system’s budget and how many teachers were cut? What will the school system do with the new federal JOBS funds to bring back teachers?
To balance the budget
A: Discussions on the school system budget begin each year around January. The budget must be presented to various stakeholders and approved by the Board of Education by April in order to be sent to the Board of County Commissioners in early May. Due to this restrictive time frame, there are many unknowns in the budget. This past year was even more uncertain than previous years due to the economic climate and the state budget deficits. JUDY Many people have forGRISSOM gotten that the school system handled a loss in funds greater than $10 million last year and an additional loss of $1.5 million this current school year. The cuts that were made last year were not restored this year. So, we began our budget development knowing that the cuts could not be counted again. The funding from the Rowan County Board of Commissioners was “held harmless” with an increase only covering mandatory increases in health insurance and retirement matches for locally paid staff. We began our final budget development requiring additional
The $1.5 million cut for the 2010-2011 school year was handled through: • Freezing positions of retiring administrators at the central office, meaning that our remaining employees have assumed even more responsibilities. • Elimination of hiring incentives in the areas of exceptional children, math and science. • Elimination of 20 assistants that were funded by the American Recovery and Reinvestment Act. • Two and a half assistant principals. • Locally paid field trips. We were able to reduce our utilities budget through energy savings created with implementing a four 10-hour day workweek for all system sites during the summer. With a grant from the Blanche and Julian Robertson Family Foundation, we were able to replace the funding cut for elementary field trips. To balance the budget, it was necessary to use $709,082 from the school system’s fund balance. The school system’s fund balance is like a savings account. Spending fund balance for recurring salaries or other initiatives will soon deplete the account. Although there is no requirement by law for the school system to have a fund balance, it is recommended that 8 percent of the overall operating budget be available for emergencies, and the auditors certainly check
to see that we keep an appropriate amount. Our employees will continue to be conservative to keep from digging deeper into the fund balance because of future needs. We will continue to seek grant funding to help with major system initiatives.
JOBS Initiative The news that North Carolina and the Rowan-Salisbury School System would be receiving funding from the JOBS Initiative is exciting. The reason for the excitement is that the federal stimulus funds will not be available next year, resulting in our school system losing an additional $6 million dollars or 176 positions. The JOBS Initiative funding will cover only $4 million. So as exciting as it is, the amount will still not cover anticipated additional losses for next year. The funding is available until September of 2012, so we will be recommending to the school board that we do not spend these funds until next school year. Reserving these funds will prevent sending home huge numbers of teachers and other staff members during the 2011-2012 school year. Because of cuts made at the central office and using a portion of the fund balance, the school system is beginning the school year without cutting classroom teachers and without raising class sizes. The focus is and will continue to be on the needs of our students. • • • Dr. Judy Grissom is superintendent of the Rowan-Salisbury School System.
SALISBURY POST
SUNDAY, SEPTEMBER 12, 2010 • 3D
INSIGHT
Obama’s glowing villain T
Protecting kids when the storm hits the federal level has gotten the message that children can’t be treated as short adults in emergencies, that they have different needs than grown-ups. That’s the good news. The bad news? With the worst of the hurricane season upon us, Congress hasn’t gotten around to doing anything to STEVE AND protect those COKIE ROBERTS kids. The sad Katrina stories about homeless dogs and cats or desperate people refusing to leave their flooded homes without their pets moved lawmakers to act with what can be considered lightning speed for Capitol Hill. Only a little more than a year after the storm, President Bush signed the PETS law, which requires FEMA to ensure “emergency preparedness operational plans (including evacuation plans) take into account the needs of individuals with household pets and service animals.” The law also authorizes funding “for animal emergency-preparedness purposes, including the procurement, construction, leasing or renovating of emergency shelter facilities” to accommodate people with their pets and service animals in an evacuation. We’re happy for the dogs and cats; we wouldn’t want to leave our dog behind in an emergency, either. But we just wish the kids had some similar consideration. Katrina separated more than 5,000 kids from their parents. Think how terrifying that would be. Some families didn’t find their kids for six months. But more than half the states still don’t require schools and daycare centers to have plans in place to reach children’s families in an emergency and reunite them with their kids. Daycare centers also aren’t required to have an evacuation and relocation plan in
I
LETTERS
ASSOCIATED PRESS
Workers board up windows in Nags Head on Sept. 2 as Hurricane Earl churned along the coast. most states, and there are few provisions in place for kids with disabilities. Some improvements did follow on the Katrina fiasco. In the storm’s aftermath, children in shelters saw and heard things children should never see and hear. There was no way to shield kids from what was going on around them — families with infants and toddlers lived in open spaces next to single young men. There weren’t enough cribs, diapers, bottles and pediatric medicines. There certainly were no toys or programs in place to deal with children’s fears or simply to occupy their time. In international disasters, nongovernmental organizations instantly swing into action to provide all of those things for children and to embark on family reunification. Some of those organizations, such as Save the Children, where Cokie is a trustee, have prevailed on emergency-preparedness officials in this country to be more mindful of the problems of kids in shelters or FEMA trailer compounds.
TO THE EDITOR
Why not help preserve some businesses? I am in full support of comments made by the Rev. Stephen Haines and Dr. Clyde Young concerning construction of the addition of First United Methodist Church. If not for interference from the Historic Preservation Commission, that project might well have been completed by now. Furthermore, Salisbury presents a very unfriendly business environment from hysteric (yes, the spelling is correct) oversight to county building inspections to sign ordinances. This is a very business un-friendly town. In fact, all of North Carolina can fall under that heading. We just returned from vacation in Gatlinburg, Tenn., where we enjoyed gasoline prices that were 20 to 30 cents less per gallon than in Rowan County, some of which is due to lower fuel taxes in Tennessee. In its June 24, 2009, edition, the Post published an article about a meeting in which more than 400 ideas for growing business in Salisbury were put forth. All that does is reek of more local government regulations and red tape for business owners or prospective owners to wade through. The ideal situation would be a two-year moratorium on all regs, including those for the people who would turn Salisbury into one big historic relic. A moratorium also would include no sign ordinances, no interference from the uptown Salisbury gang, City Council, Chamber of Commerce, EDC and others. In other words, if someone wants to open a business, let them do as they please and trust them to blend in with surrounding structures. What Salisbury needs as much as anything is an uptown parking deck. There are few places to park and not enough handicapped parking and accessibility. A parking deck should be a priority consideration before a convention center, which this town doesn’t really need. — Bill Ward Salisbury
Praying for peace Sept. 21 has been designated by the United Nations as International Day of Prayer for Peace.
Letters policy The World Council of Churches as well as the North Carolina Council of Churches are encouraging people of faith in communities everywhere to observe this day with prayer vigils or other activities to focus on the importance of prayer in combating violence in our communities and our world. The Covenant Community Connection has sponsored the planting of four Peace Poles in Salisbury and Rowan County. The first pole is located at the City Park near the gazebo. The second is in the Bell Tower Park in downtown. The third is located at Dan Nicholas Park near the carrousel. The fourth Peace Pole is located at Sloan Park in the western end of the county. All the poles proclaim the message “May Peace Prevail on Earth.” The CCC would like to invite citizens to gather in circles of silence at 12 noon at one of these poles to pray for peace for our community and our world. It would be wonderful if the Post could do a feature on IDPP. Would it not be a glorious thing if our community could be united in prayer if only for one minute at 12 noon on Sept. 21? You may research this subject at these websites: /2010/08international-day-ofprayer-for-peace-sept-21 There is an old saying, “If we all prayed the same prayer, God would grant it.” May it be so. Peace. — Betty Jo Hardy Salisbury
Hardy is a member of the Covenant Community Connection.
Through their efforts, Congress created a National Commission on Children and Disasters, and the Red Cross and FEMA have worked with the commission to make shelters safer and friendlier for children. Still, at a recent commission meeting, FEMA’s Fugate admitted: “Children are a part of every community, but too often in the past they’ve been left out of emergency planning or thought of only after the initial plan has been written.” He pledged to work to change that. But FEMA can only do so much. Congress must act if localities are to have the money to get schools up and running as quickly as possible — after Katrina, more than 50,000 kids only erratically attended school for an entire year — and fund daycare for small children so their parents can get back to work. In the Senate, Democrat Mary Landrieu and Republican Lamar Alexander have introduced a bill that would do just that, plus provide medical care and mentalhealth counseling for kids. But it’s
in legislative limbo because of differences among Democrats about whether payments for schools in affected areas would include nonpublic schools. That disagreement is keeping the Congress from ensuring that states have adequate emergency plans in place to evacuate kids from schools and get them back together with their families as the legislation requires — that’s the very least that the lawmakers should insist on for our kids. Otherwise, when the next big storm comes along — and one will hit sooner or later — we could once again find children in unsafe situations, months elapsing before they find their families and out of school for far too long. But hey, there’s something to be grateful for — the pets should do all right this time around. • • • Steve Roberts’ most recent book is “From Every End of This Earth” (HarperCollins). Contact Steve and Cokie Roberts via e-mail at stevecokie@gmail.com.
More debt isn’t the answer P resident Obama says “some powerful special interests” have been talking about him “like a dog,” and it’s true, especially that incredibly, awesomely powerful interest known as the American public, but there is a way out. He can quit coming up with policy ideas like an immediate $50 billion, anti-recession expenditure to be part of the creation of a major new federal apparatus known as an infrastructure bank. It’s an absurdity on all kinds of grounds, not the least of which is that we’ve heard infrastructure promises before. The original, $862 billion stimulus JAY was supposed to be AMBROSE. Things don’t work that way. Recessions usually fix themselves without a lot of hocus pocus from the government except for the magic of retreat, which is to say, spending less. Germany tried austerity. Austerity worked. We tried the opposite, and watch out for those Washington blusterers whose calculations would have you stand up and applaud. They did not get to their estimates of millions of jobs saved mostly through empirically based head counts, but by using the same formula that was used to justify the experiment in the first place. It’s like proving a theory by repeating what it says. The stimulus most likely worsened the recession, helping to make these last few months less the “recovery
summer” that Obama pledged than a summer of charade and excuses. This expenditure contributed mightily to a debt that could ultimately wreck us and is currently part of what’s keeping businesses from expanding. They’re worried about inflation, the burden of thousands of new regulations and a health-care remake likely to impose myriad new costs and complications into their lives. Not least of all they are worried about higher taxes. Obama is talking now about lowering investment taxes for businesses, a potentially good thing, but ASSOCIATED PRESS why does he President Obama has also want to called for a $50 billion give us still more debt infrastructure bank to through inimprove the nation’s creased transportation netspending? works. You’d think that if he is serious about the need for billions more on transportation infrastructure, he would work with Congress to redirect some of the stimulus billions still unspent, and you would think, too, that he would put this bank on hold until he has a definite, concrete plan to cut spending significantly elsewhere. If he and his Democratic Congress could perform that feat, he could calm the concerns of small business owners about reinstituting rates at top levels in existence prior to the Bush tax cuts. Investment tax reductions will be unlikely to make up for that, and if fiscal responsibility demands more revenue, and if the Democrats really believe their laughable lie that the Bush cuts did little to help the middle class, well, reinstitute all those taxes prior to November. The result would be yet more widespread outrage, and not just because of fat cat power blocs. That claim of our overly clever, highly partisan, blame-Bush-for-everything president is aimed at making it seem there are no disinterested critiques of his policies and no legitimate populist anger. Guess again. • • • Jay Ambrose is the former Washington director of editorial policy for Scripps Howard newspapers.
he Obama White House is badly in need of a villain. It needs someone to rail against. During the 2008 campaign, Barack Obama had President George W. Bush to blame for all the nation’s ills. He still does, but blaming the previous president quickly gets old in American politics. And Bush has been admirably reticent in American politics, refusing to DALE comment on MCFEATTERS his successor’s performance in office, although he must be sorely tempted. Bush has kept busy on his book and his library, only emerging in public life to cochair, along with former President Bill Clinton, the Clinton Bush Haiti Fund. And how can you demonize a guy looking out for impoverished earthquake victims? No, Bush’s days as a demon are pretty much over. The likely Republican presidential candidates aren’t in positions where they really do or decide anything. And with the exception of superstar Sarah Palin, most Americans couldn’t pick the GOP presidential hopefuls out of a police lineup. Tim Pawlenty? Mitch Daniels? Now the White House thinks it has found its villain: House Republican leader John Boehner, a 20-year veteran of Congress. Boehner would have an obscurity problem — a poll this spring found that 55 percent of the American people had never heard of him — except for two things: It’s quite possible he’ll be the next speaker of the House, a very powerful position and third in line to the president. And he has this deep, alarmingly unnatural tan. The man, depending on the TV lighting, is close to being orange. Obama even made a joke about it at the White House correspondents’ dinner this spring. Said the president, “In the next hundred days our bipartisan outreach will be so successful that even John Boehner will consider becoming a Democrat. After all, we have a lot in common. He is a person of color — although not a color that appears in the natural world.” Boehner says he comes by his tan from mowing his grass and mountain-biking. But he doesn’t look like a man whose leisure activities include cutting grass and riding a bicycle. He looks like a man who smokes, drinks and plays golf and would make a convincing pit boss in a movie about Las Vegas — all qualities, by the way, that Washington appreciates. Remember, the president was — and maybe still is — a secret smoker. The golf and the beer we already know about. Just recently Boehner gave a speech in Cleveland blasting Obama’s handling of the economy and suggested that the president fire his entire economic team. This week Obama returned to the same venue. Reported Politico, “The fact that the White House has admitted that Wednesday’s trip is a direct response to Boehner’s Cleveland speech of Aug. 24 shows that the president is honing in on Boehner as a political punching bag.” The newspaper The Hill headlined its story about Obama going after Boehner, “Seeking bogeyman, Dems’ eyes fall on would-be Speaker.” In his speech, Obama took the unusual step of repeatedly singling out Boehner by name as a friend of the rich and the special interests whose policies would be “bad for America.” Boehner’s office appeared pleased by the presidential attention. Aides said the “unprecedented” attacks smacked of panic and desperation. Maybe so, but every president needs a villain or two and it appears Obama has found his. • • • Dale McFeatters writes for Scripps Howard News Service.
4D • SUNDAY, SEPTEMBER 12, 2010
SITE FRoM 1d ter has staked fam-
ilystring.
Across 1 Cuba libre ingredient 5 Grocery unit 8 Govt. securities 14 Pester 19 Former Israeli president Weizman 20 Flabbergast 21 Greek sun god 22 Steer clear of 23 Place to park a parka 25 Wiring woes? 27 Like Humpty Dumpty, ultimately 28 Places to go in Gloucester? 29 Ballot fallout 30 Pickle processor's invitation? 33 British pop singer Lewis 34 Spring mo. 35 Constitutional aid? 36 Holiday veggies 37 Denali et al.: Abbr. 40 Disguise for illegal activities 43 Eponymous dish inventor 45 Hi from a float 46 Duff 47 Common Market inits. 48 Bobby Orr, once 49 Fruity medication? 51 Uneasy desire 53 1953 Leslie Caron film 54 Malarkey 55 Prefix with trafficker
SALISBURY POST
CONTINUED
AGHANISTAN FRoM 1d of summer. These mud huts were surrounded by walled-in courtyards. But this village was built around 600 years ago, or so I was told. Before coming here I had seen a lot of pictures of villages in Afghanistan, and quite often they had the same ancient look to them. I assumed the photographer sought out the more picturesque scenes to shoot. But as the aircraft lifted away from the runway, we passed over a local inhabited village, and the only real difference in comparing the ruins to what I saw below me was that the walls were not crumbling, and there were signs of occupation. There were no signs of electricity, very few people were outdoors, and few cars. These “modern” mud huts would have window openings but usually no sign of window frames, glass or screens. Many of the doorways had a door, but not all of them. The yards were almost always enclosed by tall walls — I assume to keep livestock in and predators out. There were few trees but many green fields, and these too were surrounded by short walls. I could see a few workers who were cutting and stacking by hand some form of wheat. To the southwest of the airfield is a town with electricity and ugly cement apartment buildings, but this village harkens back to life as it existed 1,000 or more years before. I crossed a mountain ridge into a large valley, and the cultivated fields began to grow larger. The groupings of houses were larger, and eventually there were some signs of modern buildings. I was nearing the city. But as I passed over them, I realized the larger groupings were simply bigger collections of the same mud huts. The signs of modern buildings and small industries were actually an Afghani military compound. The workers were still in the fields, most working by hand, but now I could see the occasional tractor as well. There was a scrap yard littered with the rusting hulks of Soviet-built armored vehicles left over from the Soviet invasion decades ago. Some I could recognize, while others had been stripped to mere skeletons. Suddenly the homes began to have
Photos by Lt. CoL. RodgeR t. dunCan
there are few trees in the landscape, but green fields offer grazing areas for livestock.
Courtyards and a few vehicles are visible in this aerial photo of a residential area between bagram airfield and Kabul. electricity, satellite dishes, and power lines crisscrossed the landscape. There were modern buildings, but they looked like islands in a sea of stucco structures. Kabul resembled a mix between the cities of eastern Turkey and Baghdad. But unlike
as the author notes, ‘Children are children wherever you go’ — and they’re usually ready to smile for a photograph.
56 Hideous 58 Foot specialist? 59 Toll rd. 61 Black, gooey knolls near Charlotte? 68 Nonverbal syst. 69 Christmas setups 70 "Émile, or On Education" author 71 Lieu 75 Cap'n's crew member 76 "You're So __": Carly Simon hit 77 Ten percenters: Abbr. 78 Factories with good morale? 81 __ State Broncos: Western Athletic Conf. team 82 "__ du lieber!" 83 1975 Pure Prairie League hit 84 Apple with tunes 85 Soldier, in slang 86 Site of India's Red Fort 88 Math proof letters 89 Sweat spot 90 Support gp. created in 1942 91 RVer's refuge 92 Disney's middle name 94 Moonshine equipment that's frozen solid? 100 North Carolina fort 101 Doughnut shapes 102 Chosen one 103 Documents bequeathing tiny exercise
Baghdad, the area was much greener and didn’t have that desert look to it. There were apartment buildings, some painted in shades of teal, red, peach or other bright colors. During my trip back to Bagram, we hopped from FOB (Forward Operating Base) to FOB, and stopped at a couple of COPs (Combat Outposts). As we left the city the scene below quickly transitioned from sturdy homes to villages; villages to secluded tents surrounded by herds of goats and sheep. The villages were still of the same stone/brick construction, covered with a layer of dried mud stucco. But now and then you would see the occasional brightly painted window frame, possibly even with glass in the frames. There were cars and trucks to be seen, but never in any quantity. At the small villages next to the COPs where we landed, children would rush up to the fence to wave at us. Children are children, no matter where you go. A satellite dish on a home with no windows or power lines leading to it means someone has a generator. Modern touches that look totally out of place in a home that was built with 2,000-year-old technology. But the overall impression is one of stepping back in time, much more so that I had experienced in Iraq, and much more so than I had expected.
SUNDAY CROSSWORD
devices? 106 Rocky address 107 Justice since 2006 108 "Mas Que Nada" bandleader 109 Vietnam Veterans Memorial architect 110 One way to store data 111 Eponymous scout Chisholm 112 Elusive big Scot? 113 Calculus prereq. 114 Ken of "Wiseguy"
Down 1 Mining magnate Rhodes 2 Triatomic pollutant 3 Bounded 4 Old guild member 5 Rail amenity 6 "Eight Days __" 7 Skein fliers 8 It's usually disregarded when alphabetizing 9 "I puritani" composer 10 Fútbol shout 11 Williamson of "Excalibur" 12 Things to connect 13 Kazakhstan, once: Abbr. 14 Football party munchies 15 Winged, perhaps 16 Yitzhak Rabin's predecessor 17 Has a cold 18 Jerry Rice's 208, briefly 24 Offer chocolates to, as a dieter 26 Bygone deliverers 31 In "Rent," it starts with "Seasons of Love" 32 "Aw, phooey!" 33 Hot flower 36 Tug 38 Rash protection 39 D-Day target city 40 Simulate 41 Rocket opening 42 Come to pass 43 Original 44 Basel-born mathematician 45 Movie fish 46 New Age music player, often 48 Voting groups 49 "I'd go out with women my age, but
The long and short of it/By Scott Atkinson
there are no women my age" speaker 50 Egyptian crosses 52 Riled (up) 54 Scot's tot 57 Like groves 58 Euphoria 59 One looking for the way? 60 Compote fruit 62 From way back when 63 Prepare for a run
64 Metaphor words 65 By the book 66 Gate fastener 67 It's often served with ginger and wasabi 71 Celt since 8/4/2010 72 Lacking spice 73 Skin graft material 74 Galoot 75 Karate chop, e.g. 76 Speak (for) 79 Desert illusion 80 NYSE events
81 Thin nail 85 Pisa airport name 86 Took two pills, say 87 Have humble pie 89 Hallux 90 __ Fair 91 "Constant Craving" vocalist 93 Endures 94 Fountain contents, often 95 Sanctuaries 96 Try to quiet, as a
persistent squeak 97 Turner memoir 98 Percolate 99 1985-'87 U.S. Open champ 100 Loft bundle 101 Hardly macho, in Manchester 103 Pilgrimage to Mecca 104 LBJ successor 105 Bakersfield-to-L.A. heading
BOOKS SALISBURY POST
Deirdre Parker Smith, Book Page Editor 704-797-4252 dp1@salisburypost.com
Author to sign copies of his debut science fiction novel Murphy author Paul M. Schofield will sign copies of his debut science fiction novel, “Trophy,” at Literary Bookpost, 110 S Main St., on Saturday, Sept. 18, from 1:30-4 p.m. The first in a series of five books, “Trophy” is an action-packed sci-fi adventure story that can be enjoyed by the entire family and has received very favorable comments from readers. In the future, all humanity is governed by the New Victorian Empire, which developed after the 21st century collapse of civilization as we know it. The Empire is managed by a massive computer system, known as CENTRAL, and overseen by the Ten Guardians. As a consequence of the collapse, the human race has been kept alive by extraordinary methods, but is destined for certain extinction. Convinced that time travel will be the means to its salvation, the Empire turns its attention to Louis Franelli, a brilliant ex-Empire engineer now in the employ of villainous Galen Bestmarke. Franelli alone has unraveled the complex secret of time travel through the mysterious Keyhole, an anomaly in space. Bestmarke, a vicious criminal, is testing the use of the Keyhole to develop his evil plan of a slave trade through time, and has captured and turned both animals and men into living trophies during his test journeys through the Keyhole. Now the Empire is hot on his trail. During a daring surprise attack on Bestmarke’s ship as it exits the Keyhole, Lt. Janet Rogerton successfully rescues two of the trophies and captures Franelli. In a series of rapidly moving plot twists, Franelli and a Guardian are abducted by Bestmarke; two of the trophies, the 20th century man Martin and a magnificent black panther, are revitalized by the Guardians with cybernetic bodies, forming a formidable mind-linked team; the sinister businessman Izax enters the story with dreadful consequences for Martin and his father, who is also one of Bestmarke’s living trophies; and the Empire unveils its superior new ship, the Clipper, in its quest to apprehend Bestmarke. For additional information about this event, call 704-630-9788 or visit.
SUNDAY, SEPTEMBER 12, 2010 • 5D
SALISBURY POST
Characters make familiar plot engrossing “Backseat Saints,” by Joshilyn Jackson. Grand Central Publishing of New York and Boston. 344 pp. $24.99. BY ELIZABETH COOK ecook@salisburypost.com
Who is he? Any woman ever dominated by a jealous man knows the real question behind his endless queries. Where has she been? Why did it take so long? Who was there? . Who is he? Those three words rule the life of Ro Grandee, the main character in Joshilyn Jackson’s compelling fourth novel, “Backseat Saints.” To keep her in line, husband Thom Grandee uses his fists, the back of his hand and the toe of his boot, aided and abetted by family members who look the other way. Jackson follows other novelists who have made domestic violence the catalyst for their stories — “The Color Purple” and “The Burning Bed” come to mind. Her victimization is tamer, with little sexual aggression. But her life is very much in danger, and that threat muddles her thinking just the same. Waivering between keeping the peace vs. keeping her sanity, Ro has an encounter that tips the scales. “It was an airport gypsy who told me I had to kill my husband,” Ro says in the first sentence of the book. From the beginning, Jackson weaves together the strands of Ro’s torment — a runaway mother, an abusive father, an affinity for mischief and a hus-
band destined to quash her soul or die trying. This is a good, relatively quick read — darker than “chick lit,” with touches of gallows humor. Its family dynamics have a Southern gothic feel to them — born of ingrained attitudes and destined for tragedy, with a family gun shop thrown in for good measure. But whose tragedy? That’s the real question that propels the reader forward. The plot pits the petite, increasingly malleable Ro against her beefy husband, an exjock who went from ruling the school to kowtowing to his father. Now working under his father’s thumb at the family gun shop, Thom takes his repressed anger home each day, ready to pounce on Ro the minute she overcooks dinner, sounds sassy or looks at him wrong.
The plot is less predictable than it sounds. Ro’s parents are wild cards who add enough twist to the plot to make it unique. Throw in some magical realism, and you have an engrossing story. Jackson’s previous novels in-
clude “gods in Alabama” (the small “g” is correct), “Between, Georgia” and “The Girl Who Stopped Swimming.” Ro is a minor character plucked from the pages of “gods in Alabama” and fleshed out in “Backseat Saints” as a much deeper, more troubled person than the folks back in Alabama ever knew. And who are the backseat saints? They are the ghosts of Ro’s Catholic upbringing, showing up during times of distress. Their value to the story is more comical than spiritual. For example, Ro flees the scene after firing at her husband and finds she has passengers in the car — “Francis, patron saint of cars and drivers” is accompanied by Michael and then one more: “I must have wept out Mary’s name for comfort, because she was in the back seat as well, even though she had to squash into the narrow middle seat with her patient feet on the hump.” Sacrilege? Not really. Jackson just takes the saints off their pedestals and brings them down to Ro’s plane of existence. She needs their help.
Library has variety of computer courses coming up
On Tuesday at 6 p.m., the Kannapolis Bookends Book Club and the Friends of the Kannapolis Library will present Dr. Chris Bramlett, who will discuss the book “Serena.” This bestselling novel by North Carolina author Ron Rash is set in the North Carolina mountains during the Great Depression years. Rash’s novel is a tightly knit tale of industrial development, greed and betrayal. It is a riveting novel to read and discuss. The presentation is free and open to the public. Following the program, Bramlett will lead a question and answer session. For more information, call 704-920-1180.
Rowan Public Library offers free computer classes on beginning to advanced topics. Classes are hands-on and are free and open to the public. All classes are approximately 90 minutes long. For the fall, the library offers: Classes at the Headquarters Library in Salisbury: • Absolute Beginners: Monday, 7 p.m. Have you just bought your first computer or feel like you never really learned learn basic computer skills? You’ll gain an understanding of keyboard functions, practice using your mouse and learn how to open and close programs. • PowerPoint 2003: Monday, Sept. 20, 7 p.m. Learn the basics of putting together a slide presentation. Create new slides, look at templates and insert photos and text. • Library Gems: Discover online resources: Monday, Sept. 27, 7 p.m. Did you know you can learn a foreign language with online resources? The library also has databases to help with car repair, downloadable audiobooks and ebooks, genealogy research, stock information or even to send reminders about when books are due. • Pixlr Part 1: Monday, Oct.
Rowan bestsellers
Learn more about a streamlined, low-maintenance garden
‘Serena’ discussion in Kannapolis
Literary Bookpost
1. Sleep, Little Child, by Marc Hoffman. 2. Mockingjay, by Suzanne Collins. 3. Freedom, by Jonathan Franzen. 4. Eat, Pray, Love, by Elizabeth Gilbert. 5. The Girl with the Dragon Tattoo, by Stieg Larsson. 6. Little Bee, by Chris Cleave. 7. Heads, by Matt Van Fleet. 8. Strength in What Remains, by Tracy Kidder. 9. The Last Child, by John Hart. 10. Zeitoun, by Dave Eggers.
IndieBound bestsellers Fiction 1. Freedom, by Jonathan Franzen. 2. The Girl Who Kicked the Hornet's Nest, by Stieg Larsson. 3. The Help, by Kathryn Stockett. 4. Star Island, by Carl Hiaasen. 5. Three Stations, by Martin Cruz Smith. 6. The Thousand Autumns of Jacob de Zoet, by David Mitchell. 7. Super Sad True Love Story, by Gary Shteyngart. 8. The Red Queen, by Philippa Gregory. 9. The Cookbook Collector, by Allegra Goodman. 10. The Postcard Killers, by James Patterson, Liza Marklund.
Nonfiction 1. Sh*t My Dad Says, by Justin Halpern. 2. Let's Take the Long Way Home, by Gail Caldwell. 3. Empire of the Summer Moon, by S.C. Gwynne. 4. A Journey: My Political Life, by Tony Blair. 5. Women Food and God, by Geneen Roth. 6. Packing for Mars, by Mary Roach. 7. Born to Run, by Christopher McDougall. 8. The Power, by Rhonda Byrne. 9. Medium Raw, by Anthony Bourdain. 10. The Big Short, by Michael Lewis.
BY MARISSA CREAMER Rowan Public Library
It’s been a discouraging summer for many gardeners. After a promising start in the spring, we were overtaken by heat and drought, and now my garden is not what I had envisioned. Perennials have declined and weeds have flourished. Gardens need continual attention; you must always be on the lookout for weeds, pests or signs of disease. Then there’s watering, deadheading and dividing. When the summer heat arrives, it’s easy to avoid these tasks, and before you know it, things seem too far gone. But gardeners are always looking to the future. There’s always a new spring, fresh with promise, to look forward to. As we head into fall, we have the chance to plan and prepare for next year. Perhaps it’s time to take a new approach and find a way to streamline garden maintenance. In “The New Low Maintenance Garden,” Valerie Easton claims she will show you how to have a beautiful, productive garden and the time to enjoy it. Easton is a horticultural librarian and national garden writer, and her garden is her laboratory. When she realized she no longer had the energy or enthusiasm to begin her spring garden, she decided to simplify her approach to gardening. Her goal is a garden that provides a place of respite and qui-
11 at 7 p.m. Edit photos like a pro with this free, web-based program. Like a simplified Photoshop, Pixlr will allow users to alter and manipulate photos. This a two-part program due to the complexity of the program. Basic computer skills are necessary to take this class. • Absolute Beginners: Tuesday, Oct. 19 at 1:30 p.m. Gain an understanding of keyboard functions, practice using the mouse and learn how to open and close programs. • Pixlr Part 2: Monday, Oct. 25 at 7 p.m. Build more knowledge from the first Pixlr class. Continue to edit and experiment with all the tools this program has to offer. Basic computer skills and attendance at Pixlr Part one required. • Computer Help Sessions: Make an appointment for one-onone lessons in basic computer skills. Call 704-216-8243 to schedule a 30-minute session. For more information about computer classes at the Headquarters Library in Salisbury, call 704-2168229. Classes at South Rowan Regional Library in China Grove: Working with Windows: Monday, Sept. 20 at 7 p.m. Learn
et contemplation, and not a source of never-ending chores. Easton provides guidance in lowmaintenance garden design, including hardscaping and appropriate plant choices, as well as tips for simplifying routines and working with nature. She shows you how to incorporate edibles into your garden and how to create beautiful, carefree containers of mixed plantings. The numerous color photographs and profiles of real gardens offer inspiration for your own landscape. If you would like to make more efficient use of rainwater in your garden, you might be interested in the new book “Rain Gardening in the South: Ecologically Designed Gardens for Drought, Deluge and Everything in Between,” by horticulturists Helen Kraus and Anne Spafford. This guide is designed to help you create a landscape that makes use of water that runs off roofs, driveways and other hard surfaces. A rain garden is an ecosystem that filters and uses the rainwater that moves through the landscape. Due to the selection of plants and the ability of a rain garden to store water, this type of garden is actually more drought tolerant than the average garden. Kraus and Spafford guide you through the design aspects of rain gardens, including location, size, garden style and plant selection, and provide tips for mak-
how to use common menus, create shortcuts, open programs and save files. Part two of the Computer Fundamentals series. Creating Resumes: • Thursday, Oct. 7, 11 a.m. Learn how to use ResumeMaker, a free program available from the library’s website that provides resume templates and additional tools to help job seekers. E-mail for Beginners: Monday, Oct. 18 at 7 p.m., sign up for an e-mail account and send the first message. Part three of the Computer Fundamentals series. • Build a Free Website — Part One: Thursday, Nov. 4, 11 a.m. Discover how to create a free website for yourself or an organization. Must have an active email account. Part one of a two part class. • Internet for Beginners: Monday, Nov. 22, 7 p.m. Learn how to use a web browser and a search engine as well as becoming familiar with basic terms. Part four of the Computer Fundamentals series. • Build a Free Website —Part two: Thursday, Dec. 2, 11 a.m. Discover how to create a free website for yourself or an organization. Must have an active email account. Part two of a two-
ing your rain garden low maintenance. There is also a troubleshooting chapter and information on other water-wise options for your garden. Other titles you may be interested in include “50 High-Impact, Low-Care Garden Plants” by Tracy DiSabato-Aust and “Tough Plants for Southern Gardens” by Felder Rushing. Come to Rowan Public Library for these and other books for all your gardening needs. Children’s Storytime: Beginning Monday, running through Nov. 24, weekly story time. For more information, call 704-216-8234. Headquarters — Tuesdays, 10:30 a.m., Toddler Time, (18-35month-olds); Wednesdays, 11 a.m., Baby Time (6- to 23- month-olds); Thursday, 10:30 a.m. Preschool Time (3- to 5-year-olds); 4 p.m., Noodlehead (4- to 8-year-olds). South — Mondays, 4 p.m., Noodlehead (4- to 8-year-olds); Tuesdays, 10:30 a.m., Baby Time (6- to 23- month-olds); 1:30 p.m., Preschool Time, (3- to 5-yearolds); Wednesdays, 10:30 a.m., Toddler Time, (18-35-month-olds). East — Tuesdays, 10:30 a.m., Preschool Time, (3- to 5-yearolds); Wednesdays, 10:30 a.m., Toddler Time, (18-35-montholds); Thursdays, 11 a.m., Baby Time (6- to 23- month-olds). RPL storyteller: Headquarters, Thursday, 7 p.m., Stanback Auditorium. A night of storytelling to celebrate RPL’s 11th annual Stories by the Millstream Festival. Performer Donald Davis will
part class. • Care and Feeding of your Computer: Monday, Dec. 13, 7 p.m. This class focuses on caring for a home PC, topics include maintenance of the hard drive, virus protection, backing up data, as well as external maintenance and cleaning. Part five of the Computer Fundamentals series. For more information about classes at South Rowan Regional Library, call 704-216-7737. Classes at the East Branch Library in Rockwell: • Publisher 2003: Thursday, Sept. 16, 1 p.m. Learn the basics of this versatile Microsoft program. It can make flyers, brochures, invitations, business cards and more! • Trip Planning: Thursday, Oct. 14, 1 p.m. Planning a trip somewhere? Discover how the computer can help organize your next adventure. • Powerpoint 2003: Thursday, Nov. 18, 1 p.m. Learn the basics of putting together a slide presentation. Create new slides, look at templates and insert photos and text. For more information about computer classes at the East Branch, call 704-216-7841.
be at the library. The performance is free and all are welcome. Book Bites Club: South only, Sept. 28, 6:30 p.m., “Mattaponi Queen,” for adults and teens. Book discussion groups for both adults and children at South Rowan Regional Library meet the last Tuesday of each month. The group is open to the public. There is a discussion of the book, as well as light refreshments at each meeting. For more information please call 704-216-8229. JR’s Adventure club: Headquarters, Saturday, Sept. 18, 11 a.m., Build a Lego City. Every month, JR’s Adventure Club will choose a project to build and have books from the library and recommended websites to go along with the project. The club is open to all school age children. They already have a big box of LEGOS, but bring your own if you want. Light refreshments will be served. Teen program: East, Sept. 20, 5:30-7 p.m.; headquarters, Sept. 21, 5:30-7 p.m.; South, Sept. 28, 5:30-7 p.m. Game show minute challenges. Displays: Headquarters — DAR — Literacy Month by Literacy Council; South — woodturning by Barry Russell; East — folk art by Tim and Lisa Kluttz. Literacy: Call the Rowan County Literacy Council at 704-2168266 for more information on teaching or receiving literacy tutoring for English speakers or for those for whom English is a second language.
6D • SUNDAY, SEPTEMBER 12, 2010
SALISBURY POST
BOOKS
A Tribute to Novello keeps festival alive
First-time author brings his philosophy to Pfeiffer’s “Where am I Wearing� is this year’s’s visit, contact Sylvia Hoffmire, assistant professor of English and director of the cultural program at Pfeiffer, at 704-463-3359 or sylvia.hoffmire@pfeiffer.edu.
‘Laugh, Cry, Eat Some Pie’ part self-help, part recipes Laugh, Cry, Eat Some Pie: A Down-to-Earth Recipe for Living Mindfully (Even When the World Feels Half-Baked).� by Deanna Davis. Perigee. $13.95. BY SARAH SKIDMORE
aren’t always pleasant on their own to create something to be savored, Davis argues. “There is no ‘perfect recipe’ for designing your ideal life, only your preferred recipe for ‘living it,’ � she writes. In each chapter, Davis weaves a mix of personal anecdotes and self-help tips with a heavy emphasis on positive psychology. She suggests using the benefits of laughter, friendship and mindfulness to get through life’s rough patches. Each subject has a themed recipe such as “Chocolate Meltdown Pie� and a heavy helping of food puns including a “slice of insight� and “bite by bite� tips for overcoming some of life’s basic mental obstacles. While Davis is familiar with life’s challenges, such as illness, parenthood and death, she relies more heavily on lighthearted stories about speeding tickets, flip-flops and suburban challenges.
Associated Press
Deanna Davis mixes personal anecdotes, positive psychology and pie recipes in her latest book, “Laugh, Cry, Eat Some Pie: A Down-to-Earth Recipe for Living Mindfully.� It is part self-help and part cookbook. But like many recipes, the result is a matter of taste. Davis is a speaker, entertainer and workshop leader. She is the author of other selfhelp books such as “The Law of Attraction in Action� and “Living With Intention.� But her latest effort may be too sweet for some readers. Life — like pie — is about combining ingredients that
A career you can count on. ÂŽ
As a State Farm agent, you run your business your way and have the chance to earn a great living. With so many unknowns in life, your career shouldn’t be one of them.
Schedule Adult events — Friday, Oct. 1, Levine Museum of the New South, 200 E. Seventh St. • 7 to 8:30 p.m.: History Writers Panel featuring the exhibit: Old Stories for a New South - Artist/Author Gail Haley . Haley’s original artwork created for Mountain Jack Tales and other books will be on display along with Southern folktales and paintings Mary Kratt is the author of
Jeff Campbell, CLU, ChFC, CASL Agency Recruiter Phone: 704.759.2382 Fax: 704.759.2346 Jeff.Campbell.GPDN@statefarm.com
Caroline B. Cooney, “Face on the Milk Carton,â€? “If the Witness Liedâ€? and many more. Mark de Castrique, “Death on a Southern Breeze,â€? • 1:15 p.m. Young Adult Carrie Ryan, “Dead-Tossed Waves,â€? “Forest of Hands & Teeth.â€? Karon Luddy, “Spelldown.â€? First Floor Picture Book Panels • 11 a.m. Authors and Illustrators: Tameka Brown, “Around Our Wayâ€? on “Neighbors’ Day.â€? Sherry Neidigh, “Count Down to Fall,â€? “The Best Nestâ€? (illustrator). Gail Haley, “A Story, A Story,â€? “Mountain Jack Tales,â€? “Kokopelli Drum in Belly.â€? Judy Stead, “The Twelve Days of Christmas in North Carolina.â€? • Noon, Carole Boston Weatherford, “Moses: When Harriet Tubman Led Her People to Freedom,â€? “The Beatitudes: From Slavery to Civil Rightsâ€? and more. Gloria Houston, “Year of the Perfect Christmas Tree,â€? “My Great Aunt Arizonaâ€? and more. Kelly Starling Lyons, “One Million Men & Meâ€? and “Eddie’s Ordeal.â€?
• 1:30, Introducing Novello Festival Press’ new bi-lingual children’s book, “Wings and Dreams: the Legend of Angel Fallsâ€? Children’s crafts, activities and appearances by book characters Max and Spot occur throughout the day from 10:30 a.m. to 2 p.m. Information regarding A Tribute to Novello can be found at For more information about the Charlotte Mecklenburg Library, visit. Also look for the Charlotte Mecklenburg Library on Facebook, Twitter, Flickr and YouTube.
DISCOUNT TIRE DISCOUNT T I R E . COM COM
NOW OPEN! SALISBURY SALISBURY 505 Jake Jake A lexander B oulevard W est 505 Alexander Boulevard West
37
$ TIRES FROM
EA
TOURING
PERFORMANCE PERFORMANCE
TRUCK TRUCK
43 46 76 $
P175/70R-13 P185/65R-14 . . $ 52 P195/65R-15 . . $ 59 P205/65R-15 . . $ 60 P225/60R-16 . . $ 67
Home and auto together saves you money.
$
185/60R-14 18 5 / 6 0 R -14 61 195/60R-15 195/ 60R-15 . . . $ 61 205/60R-15 205/ 60R-15 . . . $ 56 205/55R-16 205/55R-16 . . . $72 205/60R-16 205/ 60R-16 . . . $79
P235/75R-15 P235/75R-15 P235/70R-16 P235/70R-16 . .$100 100 P255/70R-16 P255/70R-16 . .$109 109 P265/70R-16 P265/70R-16 . . $113 113 P265/70R-17 P265/70R-17 . .$123 123
60
$
You’re always looking for smart ways to save. Place your
home and auto with Penn National Insurance and save 10%* on your homeowners premium and 5%* on your auto premium. Plus good drivers are eligible for even better auto rates. We offer affordable replacement cost coverage to protect your investment in a new car, and personal umbrella coverage, too. As your local independent agent, we provide the personal service you deserve and the coverage you need, including outstanding claims service and 24/7 online account convenience.
REBATE
ON BFG ON ANY AN A NY N Y SET S SEET ET OF OF 4 B BF FFG G TIRES! TTIIIR RES RE ES S!!
ONLINE REBATE. VALID O NL N LIN I NNEE OR O R MAIL-IN MA MA A LI D 9/ 99/12/10 /12 /1 /1100 TO TO 9/25/10. 99//2 / 2 5/ 5 /10 . SEE S EE EE STORE STO RREE FOR FOORR DETAILS. D ETA TA I LS. S.
Š2009 Penn National Insurance EOE
For an insurance review and quote, call us today.
SALIS SBUR RY SALISBURY
Howard Brown Agency, Inc.
Learn more:
Allen Taylor and Stephen E. Smith (Main Street Rag Press). • 5 to 6:15 p.m., Short Story Writers Panel. Aimee Parkison is an award-winning fiction writer and UNCC professor. Her work has appeared in North American Review, Quarterly West, Other Voices, Fiction International and more. Robert Boisvert is a Charlotte news anchor and is the author of “Long Dead Lover,â€? a short story collection. S. Craig Renfroe teaches English courses at Queens University and is the author of the short story collection, “You Should Get That Looked At.â€? • 6:30 to 8 p.m., Novelists Panel. Judy Goldman is an award-winning author and poet. Her work has been published in many literary journals and in numerous anthologies. Her latest novel is “Early Leaving.â€? Aaron Gwyn is an award-winning author and professor at UNCC. His work has appeared in several journals and anthologies. His latest work is the novel, “The World Beneath.â€? Pat MacEnulty is the author of five books as well as numerous short stories, essays, poems and plays. She is also a teacher, workshop leader, writing coach and freelance editor. She has received several awards for screenplays and fiction writing. • All day, local publishing houses Main Street Rag, Lorimer Press and Novello Festival Press will have booths with books to sell and featured writers. Children’s Events — Saturday, Oct. 9. ImaginOn: The Joe and Joan Martin Center, 300 East Seventh St. • 10:30 a.m., opening entertainment/book characters Max and Spot Studio i Author Panels • 11:15 a.m. Junior Fiction Stephanie Tolan, “Listen!â€?, “Surviving the Applewhites,â€? “Wishworks, Inc.â€? Eleanora E. Tate, “Celeste’s Harlem Renaissance,â€? “The Secret of Gumbo Grove.â€? Melissa Thomson, author of the Keena Ford series. • 12:15 p.m. Young Adult Mystery/Suspense
$
1121 Old Concord Rd., Salisbury, NC
704-638-0610
*Subject to eligibility and underwriting guidelines
R1219’t like the term “sweatshops,â€? whether big-box stores should be boycotted and why he’s not always opposed to child labor. His book “Where am I Wearingâ€? derived from Timmerman’sĂŠ Nast Portfolio, as well as airing on NPR.
more than a dozen books of regional history and poetry. Her prizewinning works include biography, women's history and other stories. Tom Hanchett is the staff historian at the Levine Museum of the New South. John Grooms is an awardwinning writer and former editor of Creative Loafing newspaper. Grooms writes the CL column, “Boomer with Attitude.â€? Mike Lassiter is the author of “Our Vanishing Americana: A North Carolina Portrait.â€? Adult events — Saturday, Oct. 2, Main Library, 310 N. Tryon St., Charlotte. • 10 a.m. to 4 p’ book sale scheduled for Oct. 22-28 at Quail Corners Shopping Center. • 12 to 12:45 p.m., Fantasy Writers Panel. Andrew Hartley is a distinguished professor of Shakespeare at UNCC. His latest book is a fantasy novel, “Act of Will.â€? He is also the writer of several thrillers including his latest, “On the Fifth Day.â€? Faith Hunter is the author of “The Jane Yellowrock Seriesâ€? and other fantasy/science fiction books. • 1 to 1:45 p.m., Romance Writers Panel. Harold Lowry (aka Leigh Greenwood) is the author of the novel “Someone Like You.â€? Lowry was the first male president of the Romance Writers Association of America. AlTonya Washington has been a published romance novelist for six years. Her novel, “Finding Love Again,â€? won the Romantic Times Reviewer’s Choice Award for Best Multicultural Romance in 2004. Her latest novel is “The Book of Scandal.â€? • 2 to 2:45 p.m., Novello Festival Press (NFP) Panel. NFP will showcase one of its its two most recent publications, “Topograph: New Writing from the Carolinas and the Landscape Beyond.â€? The children’s book, “Wings and Dreams: The Legend of Angel Falls.â€? will be showcased on Oct. 9. • 3 to 3:45 p.m., Mystery Writers Panel. Mark de Castrique is an author, playwright, public speaker and television producer. His latest novel is “Fatal Undertaking.â€? Cathy Pickens is a lawyer turned award-winning writer of the Southern Fried Mystery series featuring Avery Andrews. • 4 to 4:45 p.m. Poetry Panel. Tony Abbott, Alex Grant, and Diana Pinckney (Lorimer Press), Irene Honeycutt, Richard
P155/80R-13
Kelsey Timmerman will talk about his book and his clothes at Pfeiffer University on Thursday and Friday.
Thanks to a grass roots effort, A Tribute to Novello is scheduled for Oct. 1, 2 and 9. This effort, being led by University of North Carolina at Charlotte professor Mark West, will keep the spirit of Novello alive as the popular literary festival normally produced by Charlotte Mecklenburg Library will go on hiatus this year due to devastating budget cuts. West contacted Novello organizers as soon as he heard about the possible hiatus. “I felt like the community had benefited from Novello for all these years and maybe it was time for the community to show its appreciation to the library for what the festival has come to mean,â€? said West. Instead of a week’s worth of events, A Tribute to Novello will take place over two consecutive weekends in October. Oct. 1 and 2 will feature adult authors and Oct. 9 will feature young adult and children’s authors. In addition, Novello Festival Press (NFP) will present its two most recent publications: • Oct. 2 — “Topograph: New Writing from the Carolinas and the Landscape Beyond,â€? an anthology edited by Charlotte Viewpoint’s Jeff Jackson. • Oct. 9: The children’s book “Wings and Dreams: The Legend of Angel Fallsâ€? by Irania Macias Patterson with illustrations by Catherine Courtlandt McElvane. Pat Siegfried, a former librarian with the Charlotte Mecklenburg Library and owner of Black Forest Books and Toys, will head up the youth events. West will coordinate the adult events. The focus of A Tribute to Novello will be on wellknown community and regional authors who are willing to donate their time. All events are free, but donations to help the library will be accepted at all events. For more information visit the Library’s website at.
505 Jake Jake Alexander Alexander B lvd. W est 505 Blvd. West
704-633-6363 704-633-6363 - & 3!4 s /6%2 34/2%3 .!4)/.7)$% - & 33!44 s /6%2 34/2%3 .!4)/.7)$%
statefarm.com/careers State Farm, Bloomington, IL
•
An Equal Opportunity Employer
PO97076
AMERICA’S AMERICA’S LLARGEST ARGEST IINDEPENDENT NDEPENDENT TIRE TIRE DEALER DEALER
R126225
R126009
BECOME A STATE FARM AGENT.
S TAT E OR OR LOCAL L OC A L TAXES TA X E S AND, A ND, WHERE W HE R E REQUIRED R EQ U IR E D OR OR CHARGED, C H A RGE D, STATE S TAT E ENVIRONMENTAL E N V IRON M E N TA L OR OR DISPOSAL DISP OS A L FEES F E E S ARE A R E EXTRA. EX TRA. STATE
PEOPLE
Katie Scarvey, Lifestyle Editor, 704-797-4270 kscarvey@salisburypost.com
SUNDAY September 12, 2010
SALISBURY POST
1E
Jon C. Lakey/SaliSBuRy PoSt
Barefoot runner Jon Bolick tapes some of his toes to help minimize the blisters that can develop running on concrete or asphalt surfaces.
Bare yoursole Barefoot running attracting interest as athletes seek to minimize injuries BY KATIE SCARVEY kscarvey@salisburypost.com
o one really looks twice at the many runners who pound the sidewalks of Salisbury, but it’s hard not to do a double-take when you see one with bare feet. If people are gawking at him, Jon Bolick of Greensboro isn’t aware of it, he says. He’s concentrating on his run, and perhaps on avoiding any shards of glass or sharp stones that might pierce his foot. Bolick, whose parents live in Salisbury, is part of a recent trend to embrace barefoot running. A former soccer player at East Rowan High School who went to Catawba College, the 27year-old Bolick says he didn’t start running until his early 20s. At that time, he was practicing martial arts, and he felt running would help him develop speed and quickness. On his first outing, he ran for two hours. “I definitely got the running high,” he says. Still, as he continued running, he had a hard time with shoes, he says. He dealt with pain in his right
N
knee, which he attributes to the cushioning in his running sneakers, which caused him to not totally plant his feet, he believes. He’d heard about barefoot running, and after he read the bestseller “Born to Run” by Christopher McDougall, he began to consider it more seriously. The first time he tried it, he ran only 2.5 miles, less than his normal distance, but he noticed that he ran faster than usual — because he was more comfortable, he believes. The only issue, he said, was that his feet, unused to running on abrasive surfaces, developed blisters. Now, he tapes the toes that are prone to blistering. He runs on a variety of surfaces, from grass to concrete sidewalks. Grass is definitely preferable, he says, and when running through town, he hops off the sidewalk whenever he can to take advantage of a grassy stretch. When running barefoot he usually keeps his distance to five miles or under, he says. Bolick has been running without shoes for about six months now. Eric DiMarzio, a Salisbury native who attends the University of North Carolina at Chapel
“
Every footfall was a cause for celebration, as opposed to every mile.
”
ERIC DIMARZIO On his first barefoot running experience, compared to regular running
Hill, recently tried barefoot running for the first time. A cross-country runner when he attended Salisbury High School, DiMarzio shed his shoes in preparation for an upcoming seminar in Chapel Hill on barefoot running. “It was incredible and far beyond what I expected,” he said of his first barefoot outing. “I was told to run five minutes, planned on 10, and finally made myself stop after 15,” he wrote in a blog entry. “Every footfall was a cause for celebration, as opposed to every mile.” He says he was a bit fearful initially because his quadriceps had been sore, “but lo and behold,” he wrote, “when I tried running barefoot my quads did-
When he’s in town visiting his parents, Jon Bolick can often be seen running without shoes.
n’t feel a thing! “Because I was running with a stride more natural to my body, my quads didn’t have to deal with jarring impact caused by heel-striking.” The worst part of the experience, he said, was having to put his shoes back on. ‘Born to Run’ by Christopher Mc“I planned to do another 40 Dougall has helped fuel interest in minutes or so running with shoes, but the shoes I always barefoot running. loved suddenly felt like I was wearing concrete, and each heel-strike (encouraged by the running, which features more shoe’s shape), no matter how rugged terrain, he will probably subtle, was painful to endure, invest in a pair of Vibrams or and my quadriceps went right something similar. back to protesting.” David Freeze, a veteran of DiMarzio plans to increase his many marathons and president mileage as his feet toughen up. of the Salisbury Rowan Runners, He doesn’t worry much about his doesn’t think that the barefoot feet getting hurt by random running has gained much tracthings in his path. “Luckily glass tion locally. While he runs in shards and acorn fragments are shoes, he’s open to the idea of few and far between,” he said, barefoot running, at least in theoadding that he feels he’ll be able ry. to spot potential hazards. He “I think (it) makes sense, parsays he’s heard of barefoot runticularly for things like plantar ners who carry tweezers and Su- fasciitis,” he says. Plantar fasciperglue in case they get a glass itis is a common injury among sliver (with the Superglue being runners that causes nagging pain used to close up the wound). in the bottom of the heel. “NothSome runners who want to go ing else seems to work,” he adds. the barefoot route, but who can’t Although the topic is open for handle the idea or the reality of debate, many believe there is their bare feet pounding on asample evidence that today’s phalt or concrete, are opting to highly engineered running shoes run in less structured footwear are helping to cause more inthat more closely resembles juries than they are prevented. socks than shoes. Cushioning, support and stabiliOne of the popular brands is ty, the argument goes, cause runVibram Five Fingers, a “barefoot ners, paradoxically, to strike shoe” that is sometimes deharder than they would otherscribed as a glove for the foot. It wise as the foot struggles to features a thin rubber sole and maintain balance, which beslots for each toe. The brand, comes more difficult with a which attempts to give the wear- squishy sole. er the feeling of being barefoot, Barefoot runners avoid “heelwithout some of the drawbacks, striking,” landing instead on the is increasing in popularity. There ball of the foot or the middle of are less pricey alternatives how- the foot. ever, including water shoes, Running gurus like Gerard which are widely available. See BAREFOOT, 4E DiMarzio says that for trail
2E • SUNDAY, SEPTEMBER 12, 2010
PEOPLE
AND
SALISBURY POST
PEOPLE
PLACES
Boyden High class holds 74th reunion
Donna Wiseman, Communities In Schools, launched the biennial theme, “Literacy: The Adventure Of A Lifetime,” at the September Salisbury Woman’s Club luncheon at the club house. Mrs. Wiseman explained the assistance given to students through the program. She also told of the book club she sponsors at North Ele-
BRIDGE
7 from Tuesday’s game: monds contract two tricks for South dealer, both sides the best E/W score on this vulnerable deal. Dick Brisbin and Steve NORTH Moore defeated East’s three A763 hearts contract one trick for Q532 the top N/S score. KQ83 In the Evergreen Club’s A Aug. 27 duplicate game, CarEAST WEST ol and Harold Winecoff took K 10 J82 first place. AJ9 K 10 8 7 4 Other winners were: J94 A Myrnie and John McLaugh J 10 7 5 3 K962 lin, second; Ruth Bowles and Marie Pugh, third; Marvin SOUTH Query and Wade Lowder, Q954 fourth. 6 10 7 6 5 2 Billy Burke is ACBL, Life Q84 Master director of the SalisThe Rimers defeated their bury Woman’s Club weekly South opponent’s four dia- duplicate games.
Local support group meetings If your club information needs to be updated, please email the information to Lifestyles@salisburypost.com with SUPPORT GROUP UPDATE in the subject line, or write to Lifestyles, SUPPORT GROUP UPDATE, Salisbury Post, POBox 4639, Salisbury, NC 28144. • Alzheimer’s Family Support Group , 4 p.m. first Mondays, Lutheran Home at Trinity Oaks. Information, 1-800-888-6671 or 704-633-7862. • Alzheimer’s Family Support Group, 2 p.m. second Sundays, Lutheran Home at Trinity Oaks. Information, Christie Reavis, 704637-3784, extension 730. • Amputee Support Group, 1 p.m. fourth Tuesday of the month, boardroom at the Salisbury Y. Call 704-642-1132 for information. • Autism Society of North Carolina, Rowan chapter, Partners in Learning Child Development Center at Catawba College. Call 7046 Caring Friends Grief Support Group for parents who have lost infants. Meets on an as-needed basis. Information, 704-6367803centered5986. Also, 6:30 p.m. Wednesdays, Trinity Wesleyan Church, 2200 Mooresville Road. Information, 704-209-9968. • Celiac Support Group at Rowan Regional Medical Center. For more information contact Anna DeBoyace, RD at 704-210-5240. • Circle of Hope support group for parents grieving the loss of a child, 7-8:30 p.m. second Thursdays, Ramsay Building, 327 W. Innes St. Information, Lori Yang, 704-630-0319.
• Coping with Grief, group support for anyone mourning the loss of a loved one, 3:30-5 p.m. Tuesdays, Rufty-Homes Senior Center, or 6:30-8:30 p.m. Mondays, Rowan Regional Hospice office, 720 Grove St. Information, 704637-7645. • Diabetes Support Group , 2 p.m. and 6 p.m. first Tuesdays, Education Resource Center, fourth floor in Rowan Regional Medical Center’s patient tower. Offers programs to provide support and education for people with diabetes and their families. Information, 704-210-5771. • Diabetes Support Group, 78:30 p.m. first Mondays, Faith Baptist Church fellowship hall. Refreshments. Group leader: Freda Horne RN, 704-279-2463. • Divorce Care Support Group for individuals facing anger, depression and loneliness. Video sessions and discussion, 6:30 p.m. Monday, First Baptist Church, 223 N. Fulton St. Information, 704-633-0431. • Divorce Care 4 Kids (DC4K) helps children heal from the hurt of divorce. $13 for workbook. Provides a safe, fun place where children can express their emotions appropriately, feel better about themselves, and develop coping skills. Biblically-based, Christ-centered ministry for ages 5-12, 6:30 p.m. Monday, First Baptist Church, 223 N. Fulton St. Information, 704-633-0431. • DivorceCare divorce recovery seminar and support group, 7 p.m. Thursdays, New Hope Presbyterian Church, 602 Stevens St., China Grove. Information, 704-8573211 • Domestic Violence Support Group for women 18 and older who are or have been in abusive relationships, 5-6:30 p.m. Thursdays, First Baptist Church, 223 N. Fulton St. Information, 704-6364718. • God’s Special Angels support group for families with children with Down Syndrome, 6:30 p.m. first Wednesdays, Partners in Learning Center, Catawba College, 2300 W. Innes St. Information, 704-639-0406 or 704-639-1565. • GriefShare: Your Journey from Mourning to Joy: Sheila White, facilitator; 6:30-8 p.m. Mondays. $13 for workbook. Weekly seminar and support group for people who are grieving the death of someone close to them. First Baptist Church, 223 N. Fulton St. Information, 704-633-0431. • HERO Support Group for children ages 5-12 who have witnessed domestic violence, 5-6 p.m.Tuesdays; 5-6:30 p.m. Thursdays, First Baptist Church, 223 N. Fulton St. Information, 704-6364718.
BIRTH
Carlotta Chambers-Ramseur
Salisbury Flower Shop
Carlotta Marie ChambersRamseur of Salisbury graduated summa cum laude from Lesley University of Cambridge, Mass., Concord extension campus Aug. 7, 2010, with a Master of Education in Curriculum and Instruction with concentration in reading, writing and language for grades K-6. She previously graduated cum laude from North Carolina A&T State University with a Bachelor’s degree in English. A member of Zeta Phi Beta Sorority, Inc., she is a seventh grade language arts teacher at Knox Middle School. Carlotta is the wife of Derek Ramseur of Cleveland. R125863
“We Want To Be Your Flower Shop”
Waynesville’s Fall Classic Tournament set for Sept. 10-12 The Senior Citizens Center, Boundary Street, will be the playing site for Waynesville’s Fall Classic Tournament scheduled for Sept. 10-12. Margaret and Charles BILLY Rimer placed BURKE first in the weekly duplicate game last Tuesday evening at the Salisbury Woman’s Club. Other winners were: Stella Shadroui and Marie Pugh, second; Roger Means and Loyd Hill, third. This was the deal on Board
GRADUATION
• Hurts, Habits and Hang-Ups: Celebrate Recovery: Brian Nix, facilitator; 6:30-8 p.m. Mondays $19 for workbook. Open to individuals with addictive, compulsive and dysfunctional behavior and their loved ones. First Baptist Church, 223 N. Fulton St. Information, 704-633-0431. • Incest/Rape Survivors Support Group, 5:30 p.m. second and fourth Thursdays, Room 213, St. John’s Lutheran Church. Information, Family Crisis Council, 704-636-4718. • John Miller Colon Cancer Support Group, 7 p.m. third Tuesdays, St. John’s Lutheran Church Library. Information, Eva White, 704-212-2362. • Living in Pink, support and education group for people with breast cancer and survivors of breast cancer, 6 p.m. first Wednesdays, second floor conference room in Rowan Regional Medical Center’s Patient Tower. Information, 704-210-6870. • Salisbury Lupus Support Group, 1:30 p.m. third Wednesdays, J.F. Hurley YMCA. Information, Joyce Morris, 704-6380401. •. • Multiple Sclerosis Self-Help Support Group "Our Inspiration" for those newly diagnosed and/or with Multiple Sclerosis will meet at 6:30 p.m. the first Monday of every month; except if a holiday falls on that Monday, then the second Monday. J.F. Hurley YMCA, Jake Alexander Blvd., Salisbury. Information, Christine Scotton, scotton1@windstream.net. or 704-798-3341. • NAMI Connection Recovery Support group, 3:30-5 p.m., second and fourth Tuesday, First Baptist Church, 223 N. Fulton St., room 102. Open to all adults living with mental illness. Call Sarah: 704-636-2780 or Major: 704-224-6990. • NarAnon Family Group, 6:308 p.m. Tuesdays,St. John's Lutheran Church, 200 West Innes St., Room 115. For the friends and families concerned with a loved ones drug addiction. Contact 980-234-5413. • Narconon, nonprofit organization dedicated to helping those with drug addictions provides ad-
See SUPPORT, 5E
Benson Alexander Overcash was born Aug. 27, 2010, at Rowan Regional Medical Center. He weighed 7 lbs., 10 oz. and was 19-1/2 in. long. Benson is the son of Micah and Shea Overcash of Salisbury. His grandparents are Ronald and Linda Overcash of China Grove and Randy and Dale Benson of Salisbury. His great-grandparents are Nancy Wood of China Grove and Mary Lynne Shirley and Vernon Benson of Salisbury. R125857
Call (704) 633-5310 • Salisbury
• Say It With Fresh or Silk Flowers • Wilton Cake & Candy Supplies • Balloons • Many Gift Items
FLOWERS
Delivery & Wire Service Available – Weddings
Overcash
How To Get The Perfect Shoe Fit
JM &
FLOWER SHOP, INC. go to view the 504 N. Main St., Salisbury
704-636-4411 at
R122864
Woman’s Club
mentary School. Volunteer opportunities for Communities in School were discussed and members were invited to participate. The recipients of the Lillian C.Peeler Memorial Scholarship were announced. Cheryl Hanson and Bonnie Johnson, students in the nursing program at RCCC, received this year’s scholarships. Angela Bates, president, announced the Fall District Meeting to be held Oct. 2 at Kimball Memorial Luthern Church. Hostesses for the meeting were Wendy McCullough, Becky Ulrich, and Angela Bates.
R57934
B. Fisher, Dorothy B. Gantt, Billy H. Johnson, Edith Weant Peeler and Louise R. Walser. The group discussed whether to have a reunion next year, and it was decided to continue holding one as long as possible.
R116745
The Boyden High School class of 1936 met for their 74th reunion at the Country Club of Salisbury on Wednesday, Sept. 8. Dorothy B. Gantt, former class president, presided. Billy Burke played songs of the ’30s and ’40s during the social hour, which was followed by the class picture, the invocation by Gantt and then lunch. Burke accompanied the group singing familiar songs as well as the class song. Gantt gave the memorial for deceased members and classmates gave impromptu remarks about their experiences since the last reunion. Classmates attending were Valerie M. Chandler, John
Ex’s harassment makes girlfriends flee Dear Amy: I am dating a man (”Larry”) who had an affair with a woman a number of years ago. The problem is that every time he begins dating again, this exlover starts going all psycho and harassing him with texts, ASK phone calls AMY and unannounced visits. She destroys his new relationships. She is now trying to do the same thing with us. Larry says she’s too unstable to break off all contact with her (she threatened to commit suicide a few weeks ago), and he gives her mixed signals by always answering her calls and texts, to the point of disrupting our time together. He has asked me not to confront her, even though I would like to. This has been going on nonstop for two months. What should I do? — Furious in D.C. Dear Furious: In human behavior, any established pattern will continue until someone chooses to act differently. In “Larry’s” case, his ex has laid the groundwork for destroying his romantic relationships. She is playing her part. Larry responds by tacitly encouraging (or at least not discouraging) her behavior. When Larry decides he has had enough, he will do things differently. He will ignore her many points of contact or call the police, for instance, if she menaces him at his home. According to you, he does nothing to change this pattern — and you don’t report that he
has even asked her to stop. These two will do their dance until you’ve had enough and end your relationship. Because he has not attempted to do things differently, I suggest you exit from this drama, sooner rather than later. Dear Amy: I divorced “Steven” several months ago after many years of marriage. Friends were shocked and puzzled by the divorce. One said she always thought we were “the perfect couple.” Unfortunately, my ex-husband is a sex addict. I came up with the names of 50 women (I know there were many more) with whom he had a sexual relationship. At any one time, he was seeing as many as 10 women. He kept a journal that described some of his encounters. Knowing about his promiscuity, I had to be tested for HIV and other sexually transmitted diseases. Here’s my dilemma: I know he’s still seeing as many women as possible. Most are probably clueless about what kind of guy he really is. He met most of the women over the Internet using an alias. He has been seeing some of these women for more than 10 years. I really don’t feel I should interfere in Steven’s life because we’re divorced, but should I alert any of the women as to his true nature? Or should I let them live with their delusions? — Conflicted
husband is sexually involved with, you would be giving them an important health warning (leave their delusions out of it). I suggest you set up a separate e-mail address for yourself and send a message like the following to the women whose contact information you can locate: “I was married to Steven for many years, and it has come to my attention that he has been sexually involved with many other women. If you have had a sexual relationship with him, I suggest you get tested for STDs, as I have done.” Beyond this warning, I would discourage you from getting too drawn in to your ex-husband’s affairs. Dear Amy: I appreciated your response to the grandfather who wrote to you about how to bond with his twin granddaughters. You said to “tell your granddaughters about their father when he was young.” You stated that the grandchildren will be surprised that their grandfather knew their dad when he was little. Several years ago my mother and I were taking my nephew Jordan to the beach in the car. Very seriously, Jordan looked at his grandmother and said to me, “Auntie Su, just how long have you two known each other, anyways?” Jordan is currently defending us as a soldier in Iraq! Out of the mouths of babes! — Susan in Portland, Ore.
Dear Conflicted: If you can Dear Susan: I hope your craft a very simple message mother replied, “Your Aunt Su that is both informative and and I go way back. All the way impersonal, and if you can back.” send this message to other —tribunE mEdia sErvicEs women that you know your ex-
BIRTHS Addison Call A daughter, Addison Grace, was born to Jason and Christy Call of Milwaukee, Wis. on Aug. 24, 2010. She weighed 5 pounds, 8 ounces. Grandparents are David and Brenda Call of China Grove. Great-grandparents are Gonzalee and Helen Misenheimer of Bostian Heights.
Tyrel Robertson A son, Tyrel Lee, was born to Brian and Leslie Hellard Robertson of Woodleaf on Sept. 8, 2010, at Rowan Regional Medical Center. He weighed 6 pounds, 15 ounces. He has a sister, Elizabeth, 2. Grandparents are Carla and Dennis Hellard of Woodleaf, Tammy and Joe Petrea of Salisbury and Richard and Jill Robertson of Mocksville. Great-grandparents are Carl Reeves of Cooleemee, Maisy Yost of Salisbury and Helen Hellard of Woodleaf.
How to submit birth announcements The Post publishes free birth announcements. Forms are available at our office and online at. Please print clearly and include a daytime telephone number. This form can also be mailed, e-mailed or faxed to you. Call Lifestyles at 704-7974243, or e-mail lifestyle@salisburypost.com for more information.
4E • SUNDAY, SEPTEMBER 12, 2010
SALISBURY POST
PEOPLE
BAREFOOT FROM 1E Hartmann, an Irish physical therapist who advises worldclass distance runners, advocate barefoot running as a training tool, according to McDougall in “Born to Run.” Hartmann is one of many voices speaking out against orthotics and structured running shoes, which he believes have led to the “deconditioned musculature of the foot.” McDougall offers the example of runner Alan Webb, who went from flat-footed to high-arched through barefoot running drills, actually going down several shoes sizes as a result. Although many assume that barefoot running would painful, running sans shoes can actually be quite comfortable, with proper technique. Runners who want to try barefoot running are advised by experts to start with limited running sessions, not only because of the possibility of painful blisters but because muscles not called into action much by shoe-wearers will get a workout they’re not accustomed to. Calf and foot muscles need to be built up slowly. Barefoot running isn’t a new phenomenon, of course. Our ancestors undoubtedly ran without benefit of footwear, particularly as they hunted, and in recent times there have been worldclass barefoot runners. Ethiopian runner Abebe Bikila, often considered to be the greatest Olympic marathoner ever, won his first gold medal running barefoot in the 1960 Olympics, setting a world record to boot. (He did later wear shoes, in which he also performed well). Zola Budd of South Africa beat Mary Decker’s world record in the 5,000 meters while running unshod as a 16-year-old. Still, most people viewed these runners as exotic aberrations, not examples to emulate. Then, in 2001, Australian physical therapist Michael Warburton published a paper
Jon C. Lakey/SaliSbuRy POSt
With the short, quick stride common to barefoot runners, Jon bolick runs through downtown Salisbury. called “Barefoot Running,” in which he argued that the extra weight of shoes on one’s feet causes more problems than equivalent extra weight around one’s mid-section. In recent months, McDougall’s book has gotten even more people interested in going shoeless. A runner himself, McDougall set off on an epic journey that he recounts in “Born to Run.” He had a simple goal: to find out why his feet hurt. He couldn’t understand how, as a basically healthy human, he couldn’t manage to run without sustaining frequent and debilitating injuries. He tells the story of the Tarahumara Indians of Mexico’s Copper Canyon
region, whose members can run distances of 100 miles (and often, much more) in sandals made from old tires. He discovered members of the tribe running into their 80s and 90s with few running-related injuries. McDougall argues, with support from a Harvard paleoanthropologist, that humans evolved as distance runners in order to hunt and wear down game animals. He believes that today’s highly structured running shoes cause wearers to run unnaturally, with the heel striking first. The mechanics of barefoot running are different than running in athletic
shoes. Strides are quick and short. The feet and knees should be relaxed, with knees slightly bent. The runner steps straight down and lands on the ball of the foot — the forefoot — not the heel. The back is kept straight and hips slightly forward. The feet should land under the center of gravity, the hips. Many podiatrists, like Dr. James Mazur, are skeptical about barefoot running, although Mazur says that he’s open to learning more about the practice. Running in bare feet, he says, without any support, would likely increase the risk of overuse injuries.
If people do decide to give barefoot running a try, Mazur advises them do it in some type of minimalist footwear, to reduce the chance of their feet being injured by shards of glass or other debris, which can lead to infection. And he cautions that those with diabetes or vascular disease should not run barefoot. Dr. Chris Nagy, an orthopedic surgeon, is convinced that there is a lower incidence of injuries in unshod runners, although he emphasizes that having proper form is key to avoiding injury. Running with shoes can cause changes to the foot, he says, including weakening of the arch and the calf and
Achilles tendon. “Many of the muscles in the foot atrophy because we don’t use them,” he says. The foot is actually “quite flexible and adaptable to terrain,” he says, although that ability is not challenged when the foot is encased in a shoe. Although Nagy isn’t a runner, he does have a pair of Vibram Five Finger shoes and has recommended them to some of his running friends. Barefoot running, he says, decreases stress or pressure across the knee by 38 percent. McDougall advises people to trust their feet, In other words, let your sole be your guide.
barefoot runner Jon bolick hasn’t had a problem with injuries, although he does admit that in the summer, concrete and asphalt can get uncomfortably hot.
Go Green
Sign up to have your Salisbury Post Renewal Notice emailed to you and receive a reusable “green” bag.
PRESCRIBED WEIGHT LOSS AND WELLNESS
life
I changed my in 90 days with Somae
.
JOIN US FOR A FREE 1-HOUR WORKSHOP by Dr. Chris Nagy and learn how you can:
Go to
» Lose 2-5 lbs. a week the safe way » Finally keep the weight off for good » Reduce or eliminate your medications » Improve your family’s health long-term
™
LIMITED SEATING AVAILABLE To register, call 1-888-865-5443
September 14th, 5:30 p.m. Salisbury Orthopaedic Associates 605 Grove Street, Salisbury
Can’t make it on the 14th? Call for more info!
R125540
R121580
SALISBURY POST
SUNDAY, SEPTEMBER 12, 2010 • 5E
PEOPLE
FROM 2E diction.
• Rowan Parkinson's Support Group, 1 p.m., first Tuesdays, First Presbyterian Church Education Building, Fisher Street. Information, Peggy Wilson, 704-6333 Sexual Assault Support Group, 5-6 p.m. Tuesdays, First Baptist Church, 223 N. Fulton St. Information, 704-636-4718. • Support Group for Parents Who Have Lost Children Through Death , 5:30 p.m. Sundays through Nov. 14, Kannapolis First Baptist Church, 101 N. Main St., Kannapolis. Information, 70496918. • Survivors of Suicide Support Group, 6:30 p.m. biweekly Mondays, St. Marks Lutheran Church, N.C. 150. Information, Renee Moore, 704-857-5193 or holygirl7@hotmail.com. Call if you plan to attend. • TOPS (Take Off Pounds Sensibly),; Thursday, Church of God fellowship building, 509 N.C. 152 East, Rockwell, weigh-in 6 p.m., meeting 7 p.m. Leader Vickey Everhart, 704279-5260. Thursday, Farrington Family Medical Center, Faith, weigh in 6:30/ meeting 7 p.m. Leader Terri Deal 704-239-0537. • US TOO! Prostate Support Group, 6 p.m. third Thursdays, Rowan Regional Medical Center Cardiac Rehabilitation and Wellness Center, second floor in Kiser Medical Building. Information, 704-639-0942.
GET READY TO
ROCK! FALL SENIOR
EXPO LIVE ENTERTAINMENT PROVIDED!
Japanese cult director in Venice with samurai film VENICE, Italy (AP) —white Emper-
Rowan County Senior Services Rufty-Homes Senior Services Rowan County Senior Games Salisbury Audiology Powles Funeral Home National Active and Retired Federal Employees Chapter 0720 Piedmont Behavorial Health Care Cabarrus Eye Center Health Solutions Unlimited Penrod Medical Equipment, LLC
Miracle Ear Doug Smith The Meadows of Rockwell Genesis Healthcare Rowan Regional Medical Center Beltone Hearing Aid Carillon Assisted Living Comfort Keepers Liberty Commons Home Instead Oak Park Retirement
Guaranteed Best Prices ONLY for Your Gold! VALID
DRIVER’S LICENSE NEEDED!
“A Name You Can Trust” 314 S. SALISBURY AVE., SPENCER, NC (704) 633-0618
Ribbon By the Roll
Garlands, Swags & Wreaths
INCLUDES ALL RIBBON BY THE ROLL IN OUR WEDDING, SEASONAL, FABRIC & FLORAL DEPARTMENTS.
FEATURING FLOWERING & GREENERY. INCLUDES FALL & CHRISTMAS.
Flowering & Greenery Bushes
Floral
Including Plants & Ferns
Categories Shown
INCLUDES FALL & CHRISTMAS. EXCLUDES POTTED TREES & ARRANGEMENTS.
%
50 Off
Dried Naturals INCLUDES FALL, CHRISTMAS, PRESERVED/DRIED FLOWERS, PODS, BRANCHES, GRASS, STICKS, FEATHERS, FILLERS, GRAINS & BOUQUETS.
Floral Stems Realistic Fruit, Vegetables, Bread & Cheese
INCLUDES FALL, CHRISTMAS, FEATHERS AND ALL STYLES & VARIETIES Entire Stock of IN OUR STEM DEPARTMENT.
INCLUDES PICKS & SPRAYS
Now Marked... Glass Christmas Vases, Bowls & Serving Pieces
Christmas Figurines, Water Globes, Fashion Trees & Photo Frames
Christmas Most Categories Shown
30% Off
40 % Off OUR EVERYDAY LOW PRICES
Portrait Frames & Document Frames with Glass
Poster Frames & Wall Frames with Glass
Collage Frames
Photo Frames
Decorative Knobs, Drawer Pulls, Hooks & Brackets
Decorative Crosses & Balls
50% Off
Glassware
Ceramics, Pottery INCLUDES TABLE TOP, BLUE & WHITE, & Polyresin
INCLUDES GLASS WITH DECORATIVE ACCENTS & GLASS FROM OUR CRAFT & FLORAL DEPARTMENTS. ITEMS $1.99 & HIGHER. EXCLUDES STAINED GLASS
Decorative Clocks
Sterling Silver Beads, Chains, Findings & Wire
Entire Stock of
Traditions, Explorer & Natural Gallery®
Craft Organizers
Entire Stock of
OUR EVERYDAY LOW 1.99
Home Décor Tassels & Tiebacks
Fleece PRINTS, SOLIDS & MICROFIBER
OUR EVERYDAY LOW 6.99 - 14.99 P/YD.
OUR EVERYDAY LOW PRICES
OUR EVERYDAY LOW 2.99
Calico Prints & Solids
%
%
OUR EVERYDAY LOW 8.99
• 45" WIDE • 100% COTTON • INCLUDES APPAREL COTTON PRINTS
%
Fashion Fabric 30 Off Categories Shown OUR EVERYDAY LOW 2.99 - 9.99 P/YD.
Tulle Spools 6” x 25 YDS. 6” x 10 YDS. MATTE GLITTER
1.99
PER SPOOL
OUR EVERYDAY LOW 2.99 P/SPOOL 6” x 25 YDS. - SHINY
2.99
PER SPOOL
OUR EVERYDAY LOW 4.99 P/SPOOL
Tulle 77¢ P/YD. OUR EVERYDAY LOW 1.09
Net 77¢ P/YD. OUR EVERYDAY LOW 1.29
Shiny 99¢ P/YD. EVERYDAY Tulle OURLOW 1.39
54" Home Dec Fabric
Burlap • 48” WIDE • ASSORTED COLORS
2.99
P/YD.
OUR EVERYDAY LOW 3.99
3.99
30% Off
Candle & Soap Making Products
Prints, Solids & Sheers
All Doll Kits & Dollmaking Accessories
Craft Washable Sequins & Paillettes
EXCLUDES 10 LB. WAX AND 5 LB GLYCERIN
INCLUDING WIGS, EYES, CLOTHES, HATS & MORE.
Cricut “Expression” Electronic Die Cut Machine
Scrapbook Page Kits by the Paper Studio®
Entire Stock of
CUTS 12” PAPER WIDTHS
CricutTM Cartridges
264.99
OVER 60 TO CHOOSE FROM!
Single Sheet Paper
the Paper Studio® 12”X12”
5/1.00 3/1.00
Ribbon Trends Epic Die Cut, Scrapbook & Craft Ribbon Emboss, 192 STYLES TO CHOOSE FROM Letterpress Tool
49.99
OUR EVERYDAY LOW 59¢
OUR EVERYDAY LOW 29¢
OUR EVERYDAY LOW 49.99, 69.99 & 79.99
Scrapbooking Categories Shown
PRINTED AND CARDSTOCK. EXCLUDES VELLUM & SPECIALTY PAPERS. 81⁄2”X11”
2/89.99
OUR EVERYDAY LOW 399.99
OUR EVERYDAY LOW 8.99
2/1.00
OUR EVERYDAY LOW 69.99
OUR EVERYDAY LOW 99¢
All Tempera Paint, Window Writers & Poster Paint Markers
All Poster Making Supplies
Art Markers INCLUDES SETS & INDIVIDUALS. FEATURING PRISMACOLOR, SHARPIE & MORE! EXCLUDES COPIC SINGLE MARKERS.
Art Supplies Categories Shown
30% Off
FEATURING MASTER’S TOUCH, WINSOR & NEWTON, GRUMBACHER, ROBERT SIMMONS & MORE!
%
50 Off OUR EVERYDAY LOW PRICES
Entire Stock of
Printed Cotton Duck
30 Off 50 Off 30 Off %
Curved Compartment Organizers
1.47 1.99
25 Off
Crafting Most Categories Shown
All Art Brushes & Brush Sets
50 Off
OUR EVERYDAY LOW PRICES
Make-a-Bear Kits & Accessories
FEATURING ARTSKILL & 3M
%
Vintaj Natural Brass Components
Seasonal EVA Foam Shapes, Sheets, Kits & Buckets INCLUDES EVERYDAY
Swarovski Hot Fix Crystals
4.99
Home Accent Categories Shown
INCLUDES CRYSTALLIZED™ SWAROVSKI ELEMENTS, COLOR GALLERY, CZECH BEADS & MIXES, MAGNETIC HEMATITE & BRILLIANCE
Fall & Christmas Scrapbook Kits, Albums, Stickers & Accessories
OUR EVERYDAY LOW 4.99
INCLUDES OUR ENTIRE SELECTION OF TABLE TOP AND NOVELTY PHOTO FRAMES AS WELL AS ALL WOODEN PHOTO STORAGE
& Craft Kits
30% Off
All Diorama
50 Off
Entire Stock of
Fall, Halloween & Seasonal Packaged Christmas Crafts Ornament Kits Categories Shown
INCLUDING WOODLAND SCENICS, PLASTIC FIGURES, FARM ACCESSORIES AND MORE.
%
Bead Treasures™ Beads, Glass Pendants & Kits
“Make It Christmas” Craft Parts & Materials
(APPLIES TO FRAME ONLY) THIS OFFER AVAILABLE ONLY AT STORE ADDRESSES LISTED BELOW.
Framing
ORIENTAL, SOUTHWEST & SEASONAL AS WELL AS ITEMS FROM OUR CRAFT AND FLORAL DEPARTMENTS.
INCLUDES EVERYDAY
Custom Frames
Categories Shown
Candles, Candle Holders, Reed Diffusers & LED Pillars
Seasonal Felt Shapes, Sheets, Stickers, Bags & Boxes
FURNITURE AVAILABILITY & SELECTION MAY VARY BY STORE.
Christmas Nativity Sets, Stables & Accessories
Christmas Candles, Candle Holders & Candle Rings
INCLUDES FLOWERING, GREENERY, FALL & CHRISTMAS. EXCLUDES CUSTOM DESIGNS.
OUR EVERYDAY LOW PRICES
Robert Stanley Home Decor Collection
50% Off
EXCLUDES TEALIGHTS, VOTIVES & CANDLE VALUE PACKS
Floral Arrangements
Furniture
%
All Construction Paper & Poster Board
All Display Boards & 20x30 Foam Boards
50 % Off OUR EVERYDAY LOW PRICES
COATS ‘N CLARK/SUSAN BATES EVENT! All Coats Zippers & Sewing Threads %
50 Off OUR EVERYDAY LOW PRICES
RED HEART YARNS
EXCLUDES PREVIOUSLY REDUCED ITEMS.
Super Saver
30% Off
2.59
OUR EVERYDAY LOW 2.99 - 44.99 P/YD.
IS OUR EVERYDAY LOW 2.59
5 & 7 oz.
Red Heart Eco Cotton
All Susan Bates Knitting Needles, Crochet Hooks & Accessories Your Choice...
2.88
%
40 Off
Coats Classic Crochet Thread
Red Heart Kids
300 yds. 400 yds.
4 & 5 oz.
3.66
1.88
OUR EVERYDAY LOW 4.49
OUR EVERYDAY LOW 3.49
OUR EVERYDAY LOW PRICES
OUR EVERYDAY LOW 2.49
Curly Q Bulky
Heart & Sole Sock Yarn
Shimmer
Bamboo Ewe
3.5 oz.
3.5 oz.
3 oz.
1.76 oz.
3.99 OUR EVERYDAY LOW 4.99
3.99
3.22
3.99
OUR EVERYDAY LOW 4.99
OUR EVERYDAY LOW 3.99
OUR EVERYDAY LOW 4.99
PRICES GOOD IN STORES ONLY SEPT. 13 THROUGH SEPT. 18, 2010 • SALES SUBJECT TO SUPPLY IN STOCK • SELECTION MAY VARY BY STORE • THIS AD DOES NOT APPLY TO PRE-REDUCED ITEMS • SALE OFFERS NOT AVAILABLE ONLINE
STORE HOURS: 9-8 MONDAY-SATURDAY • CLOSED SUNDAY
KANNAPOLIS / CONCORD 2480 Supercenter Drive NE p
Located in the Northlite Shopping Center Next to Sam’s & Wal-Mart (Dale Earnhardt Blvd. & I-85, Exit , 60 from I-85) 704-262-7964
TUESDAY, SEPTEMBER 14, 10 AM-2 PM AT THE SALISBURY MALL R126668
THE SENIOR EXPO IS SPONSORED BY
PRIME TIME
WE BUY GOLD!
Jewelry Making Most Categories Shown
VISIT THESE BUSINESSES AT THEIR BOOTHS FOR INFORMATION ON PRODUCTS AND SERVICES
or.”.
R124462
SUPPORT
Narcotics Anonymous Helplines, 704-639-8010, 1-800-428-4236, 1-800-876-5985 or 1-800-6503615. • Our Inspirations, multiple sclerosis self-help group for those newly diagnosed or with mild symptoms, 6:30 p.m. first Monday, First United Methodist Church, 110 Church St., China Grove. Information, 704279-7129 or 704-857-9713, extension 21.213-6712.6526 or 704- 788-1616. • PFLAG (Parents, Friends and Families of Lesbians and Gays) Support Group, Salisbury/ Rowan chapter, 10 a.m. second Epilepsy Support Group, 7 p.m. second Thursdays, First United Methodist Church media room, 217 S. Church St. Information, Carole Young, 704-6390847or youngcarole@hotmail.com or toll-free line to Wake Forest University Baptist Medical Center, 1800-642-0500.
STORE HOURS: 9-8 MON-SAT CLOSED SUNDAY
Subscribe for Weekly E-Mail Specials
R126489
$
$
Coupon
Coupon Code:
20 82
$
Coupon
Become a Fan on Facebook
One Regu Any lar Pric tem ed I Online & In-Store
Red
Offer may eemable Coupon One coupon per be used for any item at regular custo at time of purchase mer per day. Must presentprice only. origi discount or prev . Offer is not valid with any othe nal coupon ious r coupon, purc hase custom floral, gift . Excludes custo SLICE™ products,cards, special orders, CRICUTm framing, products, No duplicates perm rentals or class fees. Cash Value itted. Valid only Sept. 13 - Sept. 1/10¢. 18, 2010
$
Follow @hobbylobbystore on Twitter
6E • SUNDAY, SEPTEMBER 12, 2010
SALISBURY POST
PEOPLE
Jon c. Lakey/SALISBURY POST
Carolina Lily is hosting a scarecrow contest with the winner receiving a donation of $250 to the charity of their choice. This is Mustang Sally, cheerleader, by Renee Canup, Brianna Brinkley, Mackenzie Fisher and Nanci Lefko, to benefit East Rowan High School cheerleaders.
If I only had a brain . . . C
arolina Lily is hosting a contest, Scarecrows for Charity. Carolina Lily provided scarecrow frames for participants, whose creations will be displayed in the garden through September. Carolina Lily will award $250 to the group with the best scarecrow, based on the number of votes from visitors of Carolina Lily. Votes will be gathered through September. The entries include: • Cannie the Garden Fairie, by Carole Massey and Sue Davis (Master Gardeners) to benefit 4H; • Faithful Floyd and Scaredy Cat, the dog and cat, by Betti and Jim Carli, Jon Planovsky and Mary Padavick to benefit Faithful Friends Animal Sanctuary; • Scary Skeleton, by Clyde Overcash, Alyssa Klaus, and Tim Watson, to benefit Piedmont Players/Haunted Theater • Museum Lady, by Kaye Hirst, to ben-
efit Rowan Museum; • The Wiz, scarecrow from Wizard of Oz, by Tracy Webb Goodman and Millie Nelson (the blue bear) to benefit Smart Start Rowan; • Mustang Sally, cheerleader, by Renee Canup, Brianna Brinkley, Mackenzie Fisher, and Nanci Lefko, to benefit East Rowan High School cheerleaders • Ynonna, exerciser, partying at the Y, by Barbara Franklin and friends, to benefit Rowan Y; • Mother Nature, flowery woman with leafy skirt, by Joyce Goodwin, to benefit The Center for the Environment at Catawba College • Daisy Dukes, pink-booted daisy girl, by Christa Canup, used as the sample to get everyone started. Carolina Lily is located at 1375 Kern Carlton Road. For more information, call 704639-0033 or go to
t Scary Skeleton, by Clyde Overcash, Alyssa Klaus and Tim Watson, to benefit Piedmont Players/Haunted Theater. u Faithful Floyd and Scaredy Cat, the dog and cat, by Betti and Jim Carli, Jon Planovsky and Mary Padavick to benefit Faithful Friends Animal Sanctuary. q Museum Lady, by Kaye Hirst, to benefit Rowan Museum.
This is Ynonna the exerciser, partying at the Y, by Barbara Franklin and friends, to benefit the Rowan Y.
SALISBURY POST
SUNDAY, SEPTEMBER 12, 2010 • 3E
PEOPLE
ANNIVERSARIES
W E D D I N G S
Connor - Weicht
Cobb - Grissom
LAKE LURE — Kelly Nicole Cobb and Hyatt Norvel Grissom GOLD HILL — Brittney Connor and Eric Weicht were united in were married Aug. 7, 2010, at Rumbling Bald Resort. The Rev. Dr. marriage Friday, Sept. 10, 2010, at Gold Hill United Methodist Ron Williams officiated the 5:30 p.m. ceremony, which was folChurch. The Rev. Richard Grewell and the Rev. Phillip Martin offi- lowed by a reception. ciated the 5 p.m. ceremoThe bride was escorted by her ny, which was followed by father, Jeff Cobb, and attended by a reception at High Rock Leanna Pusey of Pocomoke, Md., Community Church East. as matron of honor. Bridesmaids The bride was escorted were Morgan Grissom, Cherish by her father, Don Connor, Rosas, Brittany Wietbrock and and attended by Julianna Jackie Seter. Thompson of Salisbury as Todd Grissom stood as his maid of honor. Bridesson’s best man. Groomsmen maids included Kristen were T.J. Cobb, Trever Pusey, Collins, Leah Collins and Tyler Dunlap and Brett Hendrix. Trina Hastings, all of The bride is the daughter of Salisbury. Jeff and Susan Cobb of Woodleaf Father of the groom and the granddaughter of Fay Eric Cox stood as best man. and Dale Cobb. A graduate of Groomsmen were Jeffrey West Rowan High School and Haltom, Jarret Smith and Gardner-Webb University, Nicole Stephen Beaver, and ushis employed by Cleveland ers were Darren Cox and County YMCA. Mike Smith. The groom is the son of Todd Abby Cox was flower and Sherra Grissom of China Grove and the grandson of Dorothy girl, and Connor MisenGrissom and Fran and Norvel Sprinkle. A graduate of West Rowan, heimer was ring bearer. he is a senior at Gardner-Webb majoring in religious studies. The bride is the daughR125862 The couple are making their home in Shelby. ter of Darlene and Don Connor of Salisbury and the granddaughter of Dorothy and Charles Connor of Salisbury and Cecil and Donail Cline of Cleveland. A 2007 graduate of East Rowan High School, Brittney received an Associate of Arts in Early Childhood Education from Rowan-Cabarrus Community College in 2010. She is employed by Guiding Stars and is also the Food Lion corporate photographer. The groom is the son of Judy and Eric Cox of Gold Hill and the grandson of Sandra and Richard Grewell of Denton and Judy and Larry Cox of Kannapolis. A 2006 graduate of East Rowan High School, Eric received a degree in Basic Law Enforcement Training from RCCC in 2010. Following a wedding trip to the Caribbean Islands, the couple R125859 will make their home in Granite Quarry.
ENGAGEMENTS Grubb - Taylor
Sheets - Odden
ENGAGEMENTS Honeycutt - Sease
Toby and Rhonda Honeycutt of Rockwell are pleased to announce the engagement of their daughter, Katherine Suzanne Honeycutt, to Christopher Glenn Sease, also of Rockwell. The bride-to-be is the granddaughter of Dorothy and the late Bill Honeycutt of Rockwell and the late Frank and Stella Safrit of Salisbury. A 2005 graduate of East Rowan High School and an N.C. Teaching Fellow, Katherine graduated magna cum laude from Western Carolina University in 2008. She is a Spanish teacher at North Stanly High School. The future groom is the son of Glenn and Kathi Sease of Salisbury and the grandson of Dr. Larry and Sally Warner of Los Alamos, N.M., and Eugene and the late Doris Sease of Huntersville. A 2004 graduate of East Rowan High School, Christopher graduated summa cum laude from Pfeiffer University in 2007 and graduated from the University of North Carolina School of Law in 2010. He is employed by Sherrill and Cameron Law Firm in Salisbury. The couple will wed Oct. 23 at Historic Gold Hill Park. R125867.
Larry Wayne Basinger Sr. and Barbara Beaver Basinger of China Grove celebrated their 50th wedding anniversary at a dinner with their children and grandchildren on Sept. 11, 2010. The Basingers were married Sept. 10, 1960, at Ebenezer Lutheran Church in China Grove by the Rev. Karl Dunn. Larry retired from Estes Express Lines after 23 years, and Barbara retired from Philip Morris after 14 years. Their children are Larry Jr. and wife Starla Basinger of Asheville, David and wife Sabrina Basinger of China Grove and Tonya and husband Jerry Barringer, also of China Grove. They have seven grandchildren, Clint, Luke and Hannah Basinger; Lawson Basinger; Caleb Srackangast; and Cameron and Cassidy Barringer. The couple also plan a week-long trip to Charleston, S.C., to celebrate this milestone in their marriage. R125866
Ribelin 50th Anniversary
Gene and Gail Grubb of Salisbury are pleased to announce the engagement of their daughter, Lauren Elizabeth Grubb, to Adam Gregory Taylor of Woodleaf. The bride-to-be is the granddaughter of Jimmy and Mae Harkey, James and Shirley Livengood and the late Carlton Grubb; and great-granddaughter of Henry Grubb, all of Salisbury. A 2005 graduate of North Rowan High School, Lauren received an associate degree in nursing from Cabarrus College of Health Sciences in 2010. She is employed by Salisbury OB/GYN. The groom is the son of James and Kim Taylor of Woodleaf and the grandson of Harold and Shelby Cartner of Woodleaf, the late Jimmy Mowery and the late Lester and Marie Taylor. A 2004 graduate of West Rowan High School, Adam received a Bachelor of Science in Business Administration from Catawba College in 2008. He is the owner of Taylor Lawn Care, Inc. The couple will marry Oct. 23 at Omwake-Dearborn Chapel on the campus of Catawba College.
Curtis G. and Mary Jane Bollinger Ribelin of Cleveland celebrated their 50th wedding anniversary Aug. 14, 2010, at a dinner with family and friends. They were married Sunday, Aug. 14, 1960, at Cleveland Presbyterian Church in Cleveland by the Rev. Fred Harmon. Curtis is the son of the late Grady and Mary Ettis Ribelin, formerly of Salisbury. He retired from McDonnell Douglas Aircraft of Saudi Royal Airforce, McDonnell Douglas Astronautics Company in Titusville, Fla., and is the retired owner of OTC R125865 Construction Company of Cleveland. Mary Jane is the daughter of Mable Lucille Hartsell Bollinger of Jurney’s retirement home in Statesville, formerly of Cleveland, and the late John Homer Bollinger. She retired as bookkeeper and secDeatrice and Jeff Cauble of Salisbury, along with Rickey and retary of OTC Construction Company. Janie Fraley of Conway, S.C., announce the engagement of their The couple have one son, Kurt Van and wife Heather Ribelin of daughter, Ashley Lynn Fraley, to Philip Scott Owens of Woodleaf. Cleveland; and two grandsons, Charles Evan (Chas) and Chay Ashley is the granddaughEthan Ribelin of Cleveland. R125860 ter of Dickie and Carole Starnes of Marshville, Juanita and the late Robert Wilhoit Sr. of Albemarle and Charles and the late Janet Cauble of Salisbury. Ashley graduated with honors from West Rowan High School in 2008 and graduated with high honors in May 2010 from Forsyth Technical Community College with an Associate Degree in Applied Science. She is a Registered Respiratory Therapist at Thomasville Medical Center. The future groom is the son of Lonnie and Teresa Owens of Woodleaf and the grandson of Leon and Brenda Penninger, the late Homer Head of Cooleemee and the late Walter Eugene and Margaret Parks Owens of Woodleaf. Philip graduated from West Rowan High School in 2007 and is employed as an Auto Body Technician at Sudden Impact Auto Body and Paint. The wedding is Oct. 16 at Nazareth Community Church in Rockwell. R125864 Earl and Betty Sides celebrated their 60th wedding anniversary Sept. 3, 2010. They were married Sept. 3, 1950, at Mount Moriah Lutheran Church in China Grove. Earl retired from First Union, and Betty retired from Hoechst-Celanese. The Sides’ have two children, Larry Earl Sides and wife Luanne of China Grove and Vicky Sides Ritch of Charlotte. Steven and Donna Duffell of China Grove announce the Their five grandchildren are April Sides of Asheville, Mark and engagement of their daughter, Ashley Renee Duffell, to Brad Allen Libby Sides of China Grove and Jennifer and Stephanie Ritch of Shinn of Kannapolis. Charlotte. R125861 The bride-to-be is the granddaughter of Cecil and Phyllis Tucker and Max and Joett Duffell. A Pedicure.........................$1999 graduate of UNC-CharKid Spa ............................$1500 lotte, she is employed by $ 99 New Spa Head ............... $2999 Gel Nails ................... 29 Stocks, Smith, Campbell & Massage Available $ 99 Dendy, P.A. Full Set...................... 19 The future groom is the Fill-in ........................$1299 Eyelashes .............................$1999 son of Barry and Debby FREE Hot Stone Massage with pedicure service Refreshments Served Shinn of Kannapolis and the grandson of Frank and Frances Shinn and Edna OPEN SUNDAY 12-5 and the late W.O. McClary. A graduate of Rowan-Cabarrus Community College, he is employed by Tradition Golf Club. 1040 Freeland Dr., Ste 112 Please bring ad to receive The wedding is Sept. 25 at Dayspring Community Church. Salisbury, NC 28144 704.636.0390
Fraley - Owens
Sides 60th Anniversary
Duffell - Shinn
Back-to-School
R126205
Joe and Tina Sheets are pleased to announce the marriage of their daughter, Corie Elizabeth Sheets, to Michael Gordon Odden, both of Salisbury. Corie is the granddaughter of the late Eunice and Eugene Sheets of Woodleaf, Carlton and Rebecca Rickard of Lexington and the late Betty Rickard of Salisbury. A 2003 graduate of West Rowan High School, she was a 2009 honor graduate of the University of North Carolina, Charlotte, where she received a Bachelor’s degree in Sociology with a minor in Child and Family Development. Corie is currently employed with Martha and Mary in Poulsbo, Wash., as a teacher for M&M Kids. Michael is the son of Eric Jett of Salisbury and Deanna Jett of McDonough, Ga., and the grandson of Margie Bidon and the late Edward Bidon of Covington, Wash. and Gordon Odden of Buckley, Wash. A 2003 graduate of West Rowan High School, Michael is a Missile Technician on the USS Nevada for the U.S. Navy stationed at Naval Base Kitsap, Bangor, Wash. The private wedding was held at Silverdale Beach Park in Silverdale, Wash., Saturday, Aug. 28, 2010, where the couple currently resides. A traditional formal wedding will be held in April 2011 in Salisbury, where family and friends will celebrate the union. R125868
Basinger 50th Anniversary
R125858
special pricing. Exp. 09/30/10 | https://issuu.com/salisburypost/docs/09122010-sls-a01 | CC-MAIN-2017-17 | refinedweb | 66,691 | 74.49 |
In my previous post I promised you to show the combination of ABAP CDS Reader and Python operator. Here we are. In this blog post we are going to extract a standard CDS view from SAP S/4HANA Cloud into SAP Data Intelligence Data Lake. And what the most important is – we want to see headers in the file. This topic is more complicated, than the first one, but I’m sure you will get it 😊 Why I picked this topic? Firstly, I know that some colleagues encountered this problem. Secondly, there isn’t a standard solution for it at the moment. Moreover, this approach will help you to select columns or make some data preparation if it needed. So, let’s go!
For the CDS view extraction from SAP S/4HANA Cloud we are going to use ABAP CDS Reader operator in DI. It is a standard operator using to read data from a CDS view. There is a standard template “CDS View to File” using for data extraction from a CDS view into a csv file (located in the Data Lake in DI):
Problem description:
However, using this pipeline you will not see any headers in the file. It’s bad…very bad ☹
There are three versions of ABAP CDS Reader operator. The main difference here is the output data type. But independent of version you are using, the headers are still not visible in the file. And this problem we are going to solve in this post.
Solution:
Among these three versions only ABAP CDS Reader V2 has an information about fields in its output. So, we are going to use this version. The output data type of this operator is message. A message has a body and attributes. The body of the output deliveries data, and attribute some information about fields, last batch etc (see image below). Because there is not any standard solution to get headers, we must use a custom operator. In this post I’m going to use Custom Python operator. If you don’t know what it is, check my previous blog post.
Below you will see the example how attributes look like (I_COSTCENTERTEXT view):
I’m going to read headers from ‘ABAP’ -> ‘Fields’ -> ‘Name’. The pipeline looks like:
I’m not going to go through back end setup, we will concentrate us on Data Intelligence. Let’s create our Python operator:
1.Step – Create input and output ports for Python operator
Input port: name – inData, type – message
Output port: name – outString, type – string
2.Step – Add some python magic into the “Script”
from io import StringIO import csv import pandas as pd import json def on_input(inData): # read body data = StringIO(inData.body) # read attributes var = json.dumps(inData.attributes) result = json.loads(var) # from here we start json parsing ABAP = result['ABAP'] Fields = ABAP['Fields'] # creating an empty list for headers columns = [] for item in Fields: columns.append(item['Name']) # data mapping using headers & saving into pandas dataframe df = pd.read_csv(data, index_col = False, names = columns) # here you can prepare your data, # e.g. columns selection or records filtering df_csv = df.to_csv(index = False, header = True) api.send('outString', df_csv) api.set_port_callback('inData', on_input)
Note, that you should take care of data types using pandas in python. I don’t consider it in the code. Moreover, don’t forget about last batch if you need it in your use case. In addition, be aware that the “on_input” function will be executed by each data package. So, this approach is appropriate for replication/delta mode (because in the initial load json of attributes looks different after the last package, parsing cannot be done anymore, and the pipeline will fail after the last package). Be aware, that it makes sense to write data with the headers only for the first data package. You can use this approach, if the CDS’s structure will be changed. And, of course, this code can be optimized.
3.Step – Upload a cool icon for your python operator and save it.
Configure “ABAP CDS Reader V2” and “Write to File” operators, save and run your pipeline. You are almost done 😊
Your output with the headers:
Congratulations! As of today, you don’t have any troubles with CDS’s headers 😊 If you have any questions or ideas for the next blog post, feel free to let me know in the comments. Stay tuned!
How to connect SAP S/4HANA with SAP Data Intelligence:
Integrate SAP Data Intelligence and S/4HANA Cloud to utilise CDS Views – Part 1
How To Integrate SAP Data Intelligence and SAP S/4HANA AnyPremise | https://blogs.sap.com/2021/02/15/sap-data-intelligence-how-to-get-headers-of-cds-view/ | CC-MAIN-2021-10 | refinedweb | 770 | 65.22 |
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
meld requires pygtk with glade support:
Traceback (most recent call last):
File "/usr/bin/meld", line 75, in ?
import gtk.glade
ImportError: No module named glade
Reproducible: Always
Steps to Reproduce:
after emerging glade and pygtk again, i was able to run glade ...
i cannot reproduce this problem.
libglade, gnome-python, and pygtk are all deps of meld. Sounds like it was a
local problem with pygtk python modules.
well, it seems, that pygtk won't build with glade by default ...
probably the order:
libglade, pygtk will compile pygtk with glade
while
pygtk, libglade wont ... compile pygtk with glade support
this is possible if the use flag "gnome" is not set ...
currently, it _might_ work fine, but due to special use flag configurations, it
can be broken ...
(possibly the use flag checking has to be improved)
ah, i see now what you mean.
you could have emerged pygtk with -gnome, but you still satisfy the pygtk dep in
the meld ebuild. ( so it will not recompile pygtk and link against the libglade
you recently emerged as part of the requirements in meld).
exactly ... is there a way to force the recompilation of pygtk?
You will now get this if you did not compile pygtk with gnome use flag:
*
* Meld requires pygtk be built with the gnome use flag set.
* Please re-emerge pygtk with the gnome use flag set.
*
!!! ERROR: dev-util/meld-0.9.4.1-r1 failed.
!!! Function pkg_setup, Line 34, Exitcode 0
!!! You need to re-emerge pygtk with gnome use flag.
!!! If you need support, post the topmost build error, NOT this status message.
this is in ~ -r1 version. Thanks for reopening the bug and clarifying what you
meant! | http://bugs.gentoo.org/93437 | crawl-002 | refinedweb | 313 | 83.05 |
Reading, Writing, Ruby? 292?"
Needs Revision. (Score:5, Insightful)
Re:Needs Revision. (Score:4, Informative)
Read the Pi schtick [raspberrypi.org] - they are all about changing computer instruction into something cool, and getting away from making everybody into electronic secretaries.
Re:so what? (Score:5, Insightful)
I find that, in any profession, there are very excellent people who do the job because they love it and there are other excellent people who do it because it pays well. I feel like you need both kinds of people.
Incidentally, there are also really bad people who do it because they love it, and there are plenty of mediocre people who do it for the money. Those people give both groups negative associations.
As for money, it is true that one can be very happy in life with the basics covered. It is also true that more money insulates you from disruptive events... if a new roof only costs a month of take-home pay, you are in much better shape than someone who has to scrimp for a few years to pay off the loan they took out for the new roof. I wouldn't want to give up too much time for money, but I also won't discount the value of more money. Even marriages are statistically more stable if money is not a recurring problem.
Re:Needs Revision. (Score:5, Interesting)..
Re: (Score:3).
When I was 14, our High School comp-sci teacher had the good sense to realize that about 6 of us (out of a graduating class of 200ish) were sufficiently advanced that there was nothing he could teach us in a traditional lecture and homework format, they actually let us have an hour a day of "independent study comp-sci" in place of sleeping through yet another pointless class. Though we weren't required to, most IS people did most of the lecture projects anyway... as I recall, I produced 3 lines of code tha
Re:Needs Revision. (Score:4, Insightful)
I know precisely what you mean. I almost went insane when I did ECDL (just for the piece of paper that said "I know how to switch a computer on"), and after several years of Wordperfect, then Lotus Office, Star Office, then OpenOffice, I was faced with Microsoft Office 2000 and thought to myself "What the fuck is this messy shitpile I've got to work with?". Had to take everything I'd learned about decent interfaces and useful scripting and practically forget it all as I was forced to work with the hammer and chisel that tried to pass itself off as commercial-grade software.
Luckily I could get back to OOo when I took subsequent courses and the funny thing is, the course administrators couldn't tell.
Re: (Score:3)
the school didn't have the courses (or the teachers) to push a real syllabus
And that's the real problem. My mother quit teaching because of all of the bullshit bureaucracy getting in the way of actually teaching children. I've done some lecturing, but there's no way I'd want to become a school teacher - the pay sucks in comparison to a programming job, the stress is higher, and the system seems to be taking the only rewarding part of the job away.
I absolutely agree with TFA's premise. Programming is as much of a life skill now as writing was a hundred years ago. The problem
Re: (Score:3, Funny)
They learn the skills necessary for administration of the empire
:)
Re:Needs Revision. (Score:5, Insightful)
It's not just high school programming that's like this (at least where I'm from). This is happening in post-secondary education.
I took Java EE - "Enterprise Edition" quite recently. We learned how to make enterprise grade web applications... Web forms with database back-ends.
Now, I have a decent programming background (C, shell scripts, and php mostly). Lets just say I can't remember the first thing on how to reproduce anything that was taught in that class. It was all copying and pasting code blobs and lots of "s/oldword/newword", even for our midterm and final exams. Unfortunately they try to make those classes as easy as possible for everyone, but nobody truly learns anything. And fucks over the people who actually would like to learn something. The Java 101 class I took before taught me at least 100x more.
For reference, I have to get my diploma in order to continue working with the current employer I'm with. While there are some things I do learn from these classes, the majority of it I already know.
Re: (Score:2)
There are plenty of good public school programs for teaching computation. Alice for example came from work on Middle School computer programming and was able to teach creativity and discovery and basic concepts in programming. If your local schools suck run for school board.
pure theory is bad as well (Score:2)
The best is some theory and hand on work.
Re:Needs Revision. (Score:5, Insightful)
Programming isn't something that should be started in High School. Programming should be started in elementary school at the same time as math. You wouldn't expect to raise someone until High School on nothing but English Lit and PE and expect them to jump straight into Calculus in High School. Similarly, you can't expect that students will ambiently absorb the background needed to program well.
They've got to start programming simple things when they're young and their brain is still forming.
Re:Needs Revision. (Score:4, Insightful)
Information Science is Science (Score:5, Insightful)
Re: (Score:3).
Bits and bytes matter less and less, they're becoming the sub-atomic particles of Computer Science, interesting to some of the theory guys, but all the practical stuff is made up of bigger chunks. Or, that's the theory, at least. I still manipulate bits in my C++ code, but then, using C++ makes me somewhat archaic, too.
Re: (Score:3)
You might be able to drive a car, but if anything goes wrong, if you don't know anything abut the engine, you're SOL. The same is true of programming. Maybe most of the time you can ignore those "little details" (just like you can your engine), but by Grid you'd better know about them if anything goes wrong. (And if you
Re: (Score:3)
No, they don't "matter less and less". Larger structures are being built around them, but that's like saying the bigger and fancier the car, the less important the engine. It''s nonsense.
...rambling automotive analogy edited for clarity... They matter less and less to the end users, yes. But they don't matter "less" to a programmer, any more than electrons matter "less" to someone doing modern electronics.
Been there, done that with the degrees in electrical and computer engineering, 20 years in the field. I used to write 6502 assembly code by hand and peck in the op-codes in decimal... worked up through looking at compiler generated assembly and tweaking when necessary... I'm currently coding for a custom multi-core system realized in an FPGA and I have "looked under the hood" down to the assembly level exactly never in the last 15 years. gcc generates good working code from C/C++, it has its quirks and fl
Re: (Score:3)
Consumer products aren't measured in subatomic particles. You don't buy n particles of milk when you are at the supermarket. But you do buy computers with hard drives measured in terabytes and you do buy Internet connections measured in megabits per second. If you don't understand the difference between bits and bytes, you can easily be mistaken about the performance of the product or service you are bu
Re: (Score:2)
Re:Information Science is Science (Score:5, Insightful)
Why can my son, very bright, in the 8th grade, tell me the layers of the atmosphere and the earths crust and evolution and basic physics
Pay that no mind. I'm sure he'll forget all of that by next year.
Re: (Score:3)
Re: (Score:3)
Re: (Score:2).
As crazy as the ideas of "coding is Computer Science", "coding is cool" or... oh, God... "coding video games [slashdot.org] is cool".
Re: (Score:3)
Bits and bytes are just the current implementation of digital logic. If I were to give a thousand-foot view, it would be more along the lines of hardware vs software, or a line of code vs a program, or computers versus networks, that sort of thing. The sort of introductory class that keeps a whole generation of kids from confusing 'the internet' with 'Google' (or AOL, or Apple if you prefer).
The number of bits in a byte, or the very fact that computer logic is based on binary, these aren't terribly conseq
Re: (Score:2)
Re: (Score:3, Insightful)
I do agree, however, that if a cheaper (not just workable) way were found to make the internal workings trinary, it is likely that it would be adopted, strictly for internal use. The interface to the machine w
Re: (Score:3)
Re: (Score:3)
Re: (Score:2)
Re: (Score:2)
Except that bits and bytes are no more artificial than ones and zeroes, ie. Boolean algebra. And much less arbitrary than base 10 arithmetic, really. New technologies can help enable concepts like "fuzzy logic", but in the end even that is almost always represented in ones and zeroes...
Re:Information Science is Science (Score:5, Informative)
teachers make the difference (Score:5, Insightful)
With a good teacher there is no need for whiz bang fancy pants hook'em when their your graphics.
They need good teachers. Invest the money in training/sceening teachers properly. Cirriculum and all that other stuff is fluff from the people that want to sell text books and hardware.
Re: (Score:2)
I'd say that an even better investment for that money -- better than textbooks and hardware, better than training and screening -- would be to pay teachers more. Honestly, teaching has got to be the most undervalued job in society today.
First of all, the ability to teach something (especially complex matters) is very rare. Not everyone who understands a topic has the ability and the patience required to communicate it clearly to the uninitiated. So already you have a small pool of potential good teachers
Re: (Score:2)
Re:teachers make the difference (Score:5, Informative)
I am wondering what in the world you are talking about. During the three years I was teaching, a) my highest salary was the munificent sum of $21,800 per year (roughly $40K/year in today's dollars), b) I paid 100% of my health insurance costs (NO district subsidy of the cost), and c) the retirement benefit was 40% of my ginormous salary if I managed to survive 30 years without stroking out, being knifed or shot by one of my students, or being thrown under the bus by a school administrator upset that I cared about whether my students learned or not (and note that I did NOT pay into Social Security and if I had managed to get Social Security via some other job, there's a "double dipper" penalty in the SS formula that would take most of that away from me). In the years since I switched to doing software engineering rather than teaching mathematics I've sometimes worked 60+-hour weeks and multiple all-nighters but never worked anywhere near as hard as I worked as a teacher and get paid more than three times as much money than a teacher. If you paid me the same six-figure salary I make as a senior-level engineer I still wouldn't go back, because the job is thankless, never-ending, and utterly exhausting both physically and intellectually if you're doing it right. My hats off to those teachers who stay on the job and do it well, year after year, because the fools who criticize such teachers have not a clue.
BTW, once you get above 35 students in a classroom, it becomes simply impossible to manage in a way conducive to learning. Above 35 students learning starts dropping off rapidly, past 40 it's just baby-sitting and make-work. Teachers know this the hard way. The fact that politicians and parents talk about 40+ student classrooms as if that were some reasonable solution to the cost of running public schools tells me that either a) they don't care about education, they just want free babysitting to keep kids off the streets, or b) they're clueless cretins who need to be drummed about the head with a clue stick. That is all.
Re: (Score:3)
Health benefits are FAR above what the average citizen sees
Not because the teachers has gone up, but because ours has gone down. That's a fact.
Some of that is changing now, though. There has been something of rebound effect. People are getting very pissed off.
Like crabs in a crab pot trying to pull any escapees back into the pot if they try to climb out. Yea team!
The *BEST* teacher - YOUR OWN WILLINGNESS TO LEARN (Score:3)
With a good teacher there is no need for whiz bang fancy pants hook'em when their your graphics
Speaking from own experience here
There was no one in my own country who could teach me what I wanted to learn
99.9% of the programming I learnt, I learned from many online Gurus
I am not from US nor Europe. I was just an Asian geek who fell in love with technology
When I started to go online, it was something known as "Fidonet"
I graduated from 400 baud to 800 baud to finally 3200 modem.
Then the 3rd world Asian country that I was from started offering "Internet", on 64Kbps broadband.
I posted questions, many man: (Score:2)
The money argument makes no sense.
The teachers we have now, if your asertion is to be believed, teach because they love to teach and don't care about the money - if they did they wouldn't teach, right? How will giving them more money make them better teachers? If you are under the impression that higher salaries might attract people that would be better teachers (a reasonable proposition, IMHO), what will you do with all the lesser teachers that were the best we could previously afford? Are they to be fir
Re:teachers make the difference (Score:5, Insightful)
That's actually not true. Teaching tends to be somewhat cyclical over the last few years there have been a lot of teachers retiring that were hired during the 60s and 70s.
Higher salaries definitely would help, if they're going to continue to stretch the school year out the salaries are going to have to increase to accommodate for the fact that teachers can't have a second job during the summer like they used to. Plus, with increasing demands to keep their teaching certificates there really needs to be more money for the increased workload. In real dollars the pay is fine, but it's all that extra work load that happens outside of class time that needs to be addressed.
As for better and lesser, the issue there is one of certification, we could have better teachers if we paid more. The main reason is that it's hard to justify becoming a teacher when the standards keep increasing without additional support and without additional pay. Typically you're looking at a bachelors plus a teaching certificate and then on top of that you're looking at additional endorsements and certificates.
Sounds like a great idea. (Score:5, Insightful)
Especially if paired with more math.
I was lucky; my dad taught me BASIC and algebra in grade school. I was too young to realize that math was supposed to be hard and un-fun; as a partial result, all these years later, I make a good living off both.
Re: (Score:3)
Good maths is absolutely essential. Without it, you can't understand the relationship between the theory and the practice. I'd say that academic writing skills are also valuable, as that teaches people how to be clear, organized, link appropriately and yet be efficient -- skills essential to quality computing and skills absolutely lacking with today's dweebs.
There's a big dispute over what the terms "computer science" and "software engineering" really mean. I would argue that it doesn't matter, that a quali
Re: (Score:2)
That's why you need both the science and the engineering aspects of computer programming. Combined, they tell you how to use abstraction to get from the core logic to the order of a function, or how to deduce what the order will be given some form of abstract notation. (Teaching 5 year olds Z is probably a but much, but they can certainly handle flow charts.)
Re: (Score:2)
The benefit you got wasn't from the subject, it was the manner of instruction ('d argue). I wonder if your dad taught you auto repair if you might not now find yourself making a comfortable living off of that skil set. Or what if he taught you woodworking skills? Plumbing? Electrical work? Masonry?
Your dad took you under his wing and shared something he valued with you for a long time - that is hadly the same as a classroom with 20-30 students of various interest levels being forced to progress at the pace
Is declining enrollment a problem? (Score:5, Insightful)
I always hear people on slashdot bitching that half the youngsters getting computer science degrees today are incompetent code monkeys at best, and yet then I read stories the next week about the problem of declining interest or falling numbers in comp-sci education.
Which one is the truth? Shouldn't you be happy to see enrollments decline? Aren't you glad to see fewer incompetent, bobble-headed lemmings graduating and going out to make a bad name for all of you self-proclaimed 'competent' computer scientists?
Re: (Score:3)
It's human nature. Everyone wants to whine how those beneath them are incompetent pricks. It makes them feel superior.
Without the lower ranks, the illusion of superiority is gone.
So yes, they want the incompetent people under them and they want to whine.
</sarcasm>
Software development is being offshored/inshored (Score:3)
That is the real reason for declining enrollments. Also the reason that the smarter students are avoiding CS/IT.
Why go through all that trouble only to have your job offshored, or to end up training your H1B replacement?
Re: (Score:2)
Better to study what, exactly?
College/University is not a trade school, intended to prepare a student for a particular job.....
Re: (Score:3)
What makes you think that the people you see on Slashdot "bitching that half the youngsters getting computer science degrees today are incompetent code monkeys" are the same ones who dislike the declining interest or falling numbers in comp-sci education? Or do they all think the same way?
Re: (Score:2)
I prefer to be elitest and think that only a small percentage of the population can actually think abstractly enough to have an aptitude for math and computer science.
While I love wrapping my head around a hard problem (and gain immense satisfaction in solving it) when I describe what I do (sit in a desk most of the day and think about problems) to other people they picture it to be about as fun as water torture.
Re: (Score:2)
The new "bubble degree" is environmental science - it sounds nice, but typically rarely leads to a career & the jobs that there are tend to exist only because of gov't subsidies... Remove the subsidy and the job disappears.
It's not supposed to be a trade school (Score:2)
A fair degree of applied math
Being able to build a formal proof (prove sqrt 2 is irrational)(of which a real math major will laugh at)
Able to write a simple compiler or a simple operating system.
Able to track down a reproducible bug in a medium complexity program
Plenty of people get in it for the wrong reasons, and will cheat their way through the rough stuff.. horrible when I see someone who "passed" compilers not understand what L
Re: (Score:2)
Both is true. Interest in degree is falling, bars for entering and passing are lowered because schools need to fill their classes and the industry asks for graduates, resulting in code monkeys.
Competency and Interest (Score:2)
I am a web developer, do the LAMP thing as well as some ASP, VBscript, Javascript..Flash..yada.. I do pretty well and enjoy it.. I tried to get my kids into it and they had zero interest so it was a no go for them.
I really think you can go a lot further by getting the ones who are motivated and i
Re: (Score:2)
Perhaps... (Score:2)
Having Angelina Jolie and Cameron Diaz fembots teaching Computer Science to the boyz, and Chris Evans and Jason Momoa mandroids for the gurl geeks. You just have to hit teenagers squarely in the hormones!
shop class (Score:5, Interesting)
High school intro to programming should fill the same niche as shop class -- to get students interested in creating stuff.
Re:shop class (Score:5, Insightful)
And be just as optional. Requiring a student to study something like shop or programming they aren't interested in and will likely never do anything with outside of class will ruin it for everyone else as the teachers will need to "dumb-down" the class to drag these folks along, causing the more interested students to become frustrated with the pace of the class.
Re: (Score:2)
The definition of literacy changes every day (Score:2)
As Douglas Rushkoff puts it, "Program or be programmed".
Re: (Score:2)
The vast majority of US college graduates fail to comprehend legal obligations (student loans), compound interest (credit cards), and their current political system (OWS)... I suspect there is a similar "life skill gap" in the U.K. - is it reasonable to propel programming ahead of these other skills?
This line of logic reminds me of the OLPC crowd that is throwing money/support behind the idea of dumping laptops in the laps of under-privlidged children around the world to solve some vaugely-defined problem i
Re: (Score:2)
A wise man.
"Programming" changed its meaning as did literacy. Today, everyone (ok, nearly everyone) is literate on a medieval definition of "literate". For two reasons. First, general education picked up, but it has also become easier. You can "look" at a word and even if you cannot read, as in "connect letters and make out their meaning", but can only deduct from the look of a word what it means, you will be able to "read" it. Due to a standardized spelling system and standardized writing, it has become ea
Programming *was* cool at school (Score:3)
...Back in the 1980's when the programming I did caused a small robot [mit.edu] to draw complex shapes on the floor. I crunched through an insane number of projects in four years, from mathematical problems to friezes for musical productions and outlines for stage sets.
I still remember how to program the Turtle, though the real-world applications of such a skill, I've since found, number precisely zero. It was and is still fun, though.
Re: (Score:3)
I know it's bad form to reply to yourself, but:
One or two side skills I picked up while working with Turtle was in forward planning and troubleshooting. Not to mention a habit I'm still trying to kick, which annoys me greatly: the pursuit of perfection.
Want videogame studios? (Score:2)
Give lots of subsidies to developers and publishers establishing studios in your country and support high-level art and design trade schools. The former attracts them, the latter keeps them around.
It's certainly more simple than reconstructing the curriculum from elementary school up and it definitively paid off in a lot of cases; just look at Montreal. However, I'd say Britain is far from bad. Studios like Creative Assembly, Media Molecule, Studio Liverpool or Codemasters are all excellent.
Re: (Score:2)
I think Media Molecule in particular is pushing this along because they can't find anyone under the age of 25 worth hiring anymore.
Re: (Score:2)
Perhaps Media Molecule should think about hiring some of the 50%+ of UK Computer Science graduates who cannot find a job in the field? When I see statistics that say that 70% of Computer Science graduates are not working in the field five years later, I call balderdash on the notion of a shortage of software engineers in the UK. If Media Molecule truly believes that 50%+ of UK Computer Science graduates are unqualified to write software, it sounds to me as if their beef is with the universities that credent
Re: (Score:2)
If it's anything like in other countries, it's not a shortage of people who graduated from a CS class, it's a shortage of people who can write sensible code.
The two groups have overlapping areas, but they're not congruent. CS doesn't equate programming. I know a fair lot of people with CS degrees that I wouldn't trust enough coding skills to have them write an Excel macro for me.
CS is NOT programming. My university pretty much expects you to know how to program if you come in for their CS classes.
Make it cool by making it mandatory? (Score:2)
"video games and special effects"? (Score:5, Insightful)
Say what? Is this what average people think programmers and software engineers do? Do they think the kids won't catch on that the reality does not look anything like that?
I have nothing against programming as a part of standard education. It is likely beneficial on multiple levels, not just because it teaches a useful skill but because it forces you to reason about and analyze systems in a somewhat rigorous way.
My issue is that they are apparently faking the real rewards at a very superficial level which generates little value in practice. You won't train a generation of great computer scientists by doing a bait and switch, and history suggests that really great computer scientists are rarely motivated by their ability to do parlor tricks for the adoring masses. Like with many other technical disciplines, the deep elegance that makes it rewarding requires long and serious study that most of society will never really appreciate except in a very indirect way.
Re: (Score:3)
I don't know the whole industry stats, but there are a large number of people employed in movie special effects, games, and related things like virtual reality for architecture, etc. Much larger than pro sports, (highly paid) acting/modeling, and the typical wish list.
Re: (Score:2)
I would suspect that there are far more people employed in writing mundane crap like "accounts receivable form generator that Jim made before quitting" than any of the effects areas you mention.
Again? (Score:3)
Forcing students to take courses that 'teach' them things that they are unlikely to ever use because there is a chance that they will use them and/or it might have a tiny impact on their intelligence.
If it's optional, I don't have a problem with it. But I doubt most people are going to actually use this knowledge.
Re: (Score:2)
Interesting anecdotal evidence. Now let me share a bit of mine. I know a few people who either dropped out of school entirely (and never learned much of anything beyond basic math) or just never understood it to begin with. They don't use it or need it (the more advanced math). At all.
I've seen people mention that learning about it makes you more intelligent (or something to that effect) even if you do not need it. My question is, how much more intelligent? Will that work for everyone? A majority? Is it wor
Re: (Score:2)
Is it worth making people learn things that they won't need just so they can see slightly higher test scores (if that)?
If this is really what you think education is about, your education has failed you.
The reason for teaching students interesting topics like programming or maths which may not be of immediate practical use are twofold:
It teaches them that learning can be an end in itself - rewarding, and a pleasure (if they are taught well)
Later in life they may find that programming (for example) becomes essential to their daily life, or would at least make it immensely more satisfying.
For example let's say they end up work
Re: (Score:3)
I agree with what you sed.
Why not... (Score:4, Insightful)
Why not just require every student study engineering, so that England can become an engineering leader? It's an equally simplistic proposal to solve a problem as the "require everyone to study something only a few will ever work with to solve a vaugely-defined non-existant problem"...
programming languages still suck (Score:3)
What programming languages do many generic algorithms textbooks use? Pseudocode! Why?!
Back in the day, Pascal was the teaching language of choice, and BASIC was the default option for amateurs. Pascal started as an improvement on Algol, which is perhaps the original structured programming language. Pascal has quite a number of ugly design decisions. First, it's too verbose and English centric, using "begin" and "end" for blocks. C's curly braces are much, much better. Pascal's data types are very limited. In at least the Turbo Pascal compilers, Pascal's string type was limited to 255 characters because they used a single byte to store the length. Strong typing may be good for keeping novices out of trouble, but it's simply a puritanical limitation for experienced programmers.
As for C, what I mean by boilerplate is stuff like "int main(int argc, char **argv)". And that also demonstrates what I mean about overcomplicated syntax. We know main takes 2 arguments. Why do we have to put parentheses around them? We don't put parentheses around an operator just for that. It's ugly to have to do something like "assign(&c,add(a,b))" instead of "c=a+b". Then there's the redundant requirement for a semicolon. In school, we pound on students to use proper indentation, and to put statements on separate lines. But most languages still require that extra bit of punctuation. May sound like trivial issues, but these little things matter. There's also the pointer nastiness, with those ugly '*' and '&' symbols everywhere. At least C++ cleaned that up a little bit, with the use of '&' for variables named in function prototypes, and Java went a bit further yet. But it all adds up to making programming more tedious than necessary.
The LISP proponents might be feeling a bit smug and superior by now. But you know what? Lots of Idiotic Single Parentheses also blows it on these issues. To do that simple bit of math, have to say "(= c (+ a b))" Make the programmer do it in prefix order. The advantage is that unlike infix, no parentheses are required to unambiguously state a mathematical formula, but then the language requires the miserable parentheses anyway! Ok, so you can have variable numbers of parameters, and say stuff like "(+ a b c d)", but that little compensation is not worth being required to use parentheses everywhere.
The humble command line has its own issues. It has become customary to flag all the parameters with letters of the alphabet, instead of requiring all the parameters be passed, and passed in a specific order. I always struggle to remember inconsistencies like the stream parameter being the first parameter in fprintf, but the last parameter in fputs. They messed themselves up with that one. I suspect they wanted to put the stream parameter at the end to be consistent with fputs, but could not because fprintf is one of the few library functions that takes a variable number of parameters, and the ad hoc way they enabled that meant the stream had to go at the front. This is not an issue with the command line. Scripting has had a revival of sorts, but is still looked upon with contempt. Perhaps Perl is the current scripting language of choice. It has many improvements over bash. I really like the built in hash data type, and everyone likes the regular expression syntax. But it sure borrowed a whopper from shell scripting, requiring these funny glyphs ($, @, and % mostly) for every single use of a variable name.
As for code reuse, look at the mess we have with libraries. OOP couldn't solve this problem, wasn't good enough. I think where OOP really missed was the entire idea of imposing a hierarchy on classes. Ideas such as CORBA didn't cut it either. C is perhaps the clo
Re: (Score:3)!
Perhaps in the languages you use. Ruby doesn't actually have most of the problems you have highlighted -
Parenthesis are optional
Semicolons are optional
Begin/End is optional
No pointers
Glyph prefixes are not required for variables (except @ used for class variables)
No header files
No namespaces (a plus in my book as it adds complication)
Embed c etc if you must, though this will never be painless in any language as it deals with legacy issues from other languages.
I'm sure languages will improve as people realis
Programming is not "technology" (Score:2)
Won't work. For more than one reason. (Score:5, Insightful)
First and foremost, programming isn't for everyone. I had to learn this the hard way, by many frustrating experiences of trying to teach people what is natural for me. Some, actually most, people just don't make good programmers. Yes, you can teach them how to do it, but they'll never be able to come up with sensible code themselves. They will know the functions and commands, but they will never grasp the mindset necessary. They will eventually maybe get the how, but never the why. And that simply isn't enough. That way you get rote programmers who will spend their time hunting for code someone else wrote and do some crappy copy/paste programming job. The only thing you accomplish is that this kind of "programmer" will muscle into the work force, push salaries down to the point where even people who could do some great programming stop aiming for the trade and would rather spend their paid hours in some idiotic number pushing job, simply because it's better paid. Like, say, me turning to IT security management rather than IT security development. I'm a far worse security manager than I was in secdev. But it's better paid. WAY better paid.
Then, coding IS already cool. For those interested in coding. I spend my spare time coding now, think I'd do it if I didn't think it's cool and it's fun? And you'll never make it cool for people who don't get an orgasmic rush from nifty code that works, from an optimization that shaves off 20% of runtime, they don't care. They don't bother. They will create code that "does somehow" what it's supposed to do to get over it. For them, it's not a passion but a burden. You get the kind of output that you get from anyone who has to do work he doesn't really enjoy, the one with the least effort necessary.
And finally, to rephrase the first paragraph and explain why people would rather go for BA majors than for engineering: Salaries. The crappiest BA number pusher gets more money than the best IT engineer. People follow the money, it's that simple. And as long as it's better paid to administrate than to actually do something productive, this is where people will go.
Fools! (Score:2)
The only language to start with is LISP.
Let the Flamewar begin...
A question I can't answer 'cuz... (Score:2)
America has been there, done that. All Hail Carly Fiorina!
*Programming* is already cool (Score:3)
Programming is already cool. It's programmers that aren't, and most people don't want to become a programmer in order to get to the cool programming part.
We're like a colony of Leper Wizards. Everyone's in awe of the fact that we can create fire, but no one really wants to hang out with us long enough to learn how to do it themselves.
Re: (Score:2)
Re: (Score:2)
doesn't it depend on what type of game we're talking about? Polar examples; Space Invaders vs. Risk?
Space Invaders: position your spaceship and shoot sprites that drop down off the top of the screen and shoot back. Computer generated violence in its purest form.
Risk: the epitome of game theory. On saying that, who knows how much a Bluegene/L chess programmer makes?
Re:Games ok now? (Score:5, Interesting)
Re: (Score:2)
* This is EXTREME
Re: (Score:2)
Wow, that's horrible and backwards. I was in CS 90-94, and several of the class projects were specifically designed around "games". Games have always involved a lot of interesting and groundbreaking ideas in user interface, graphics, AI, optimization problems, etc. They are a great platform for teaching the foundations of computer science and programming.
Re: (Score:2)
Dunno why. Games are one of the toughest areas in the field.
Let's be serious now, you can cheat when programming in most areas. Yes, your accounting code may be slow and sluggish, but that won't surface until you have like a thousand people connected or maybe millions, and if it croaks under the load, who cares, plug in a few more cores and it's gonna work fine again. Your code runs like once a day, and nobody cares at 2am whether it needs 10 seconds or 10 minutes to finish.
Try cheating in game programming.
Re: (Score:2)
There's an ADHD problem with this embarrasment of riches. By the time a kid starts getting traction in one technology, he (I'm taking the gender for granted) sees two dozen other hotter technologies and wants to move on, before really becoming expert in the first.
That's actually a great thing if true. Why should a teenager want to boast 10 years of C++ experience, and (for example) understand the difference between a shared pointer and scoped pointer when really there's so many other (language-agnostic) things to learn about?
Re: (Score:2)
Re: (Score:2)
Re: (Score:2, Interesting)
Re: (Score:3)
As someone who uses both, I probably wouldn't choose Ruby for the following reasons:
Lambda functions versus list comprehensions. Ruby has about 60 of the things attached to arrays. Python just has if/for/in and the same set of clauses found elsewhere in the language. Or to put it another way, far less keywords (ok, member functions aren't really keywords, but..).
Speed. Ruby has its uses, unless performance starts to become an issue, where you'll find yourself having to use something else
The indent thing
Re: (Score:2)
I saw my first computer at age 17. I've been making a living writing software or doing other related things for over 20 years now and while I'm no Linus Torvalds, I still don't have any problem finding a job when I need one and making significant contributions everywhere I go. What differentiates those who will be good at writing software from those who will never be has nothing to do with how young you are when you encounter computers, and everything to do with your ability to think in a logical and straig
Re: (Score:2)
As a child during the 80s, I remember a lot of this sort of positive attitude. It seems that children were always having "You can do whatever you set your mind to", and the Army's "Be all you can be" sort of slogans shoved in their face. Sure, not everybody embraced that but I think it had a generally empowering effect.
Then the "don't hurt anybody's feelings by being better than them" and "just because you suck doesn't mean you need to change" mantras rose up and it seems to have a superhero-reducing effe
Re: (Score:3)
Actually, nothing beyond one link was "echoed". And the link was to a BBC interview they contributed to, so I'm sure they are ecstatic that slashdot picked it up.
If you haven't noticed, this has never been a site for investigative journalism and hard hitting original reporting, it's mostly blog that posts links to other articles and lets people comment on them.
Re: (Score:2)
Show me one, just one, education program that is about problem solving and not about cramming information into your head until the test is over. | https://developers.slashdot.org/story/11/11/29/0110241/reading-writing-ruby?sdsrc=prev | CC-MAIN-2016-44 | refinedweb | 6,950 | 69.01 |
User.9b1) Gecko/2007110903 Firefox/3.0b1 The HTML5 globalStorage attribute now refers directly to a Storage object of the current origin, instead of a StorageList like it previously did. This is a very important change that really needs to get into Firefox 3. The sooner this is changed, the lesser the impact on web developers. Reproducible: Always Steps to Reproduce: Evaluate window.globalStorage Actual Results: A StorageList object is returned. Expected Results: A Storage object is returned.. 1a) if we do that it's possible a site used the same value name under two differnet namespaces, we'd have to decide which one wins. 2) do we continue to support the old syntax for those pages, or simply break and force them to adapt. I recommend simply breaking them otherwise we'll have to support the old syntax forever. web pages can do function getStorage(domain) { return (globalStorage instanceof Storage) ? globalStorage // Firefox 3 : globalStorage[domain]; // Firefox 2 }
Blocking on figuring out what type of fix we want here (change spec, change our impl, do nothing)
(In reply to comment #1) >. As of 2.0.0.2, the source hostname is stored in the db. When upgrading from 2.0.0.1, the store hostname is used as the source hostname.
More recently, the spec has changed globalStorage -> localStorage, so we can leave globalStorage around for compatibility. I think it would be reasonable to restrict globalStorage usage to same-domain, so that globalStorage[window.location.host] would be equivalent to localStorage, and globalStorage["not.window.location.host"] would throw a security error. I think we should make that globalStorage change even if the localStorage change can't make it for ffx3, to prevent new developers from starting to rely on the different-domain semantics.
Updating the title to reflect changes discussed in comment 4.
Filed bug 422526 for implementing localStorage.
Created attachment 309113 [details] [diff] [review] Fix
semi-related: is there a bug on using eTLD there now? fixing that would be trivial...
Created attachment 309158 [details] [diff] [review] normalize requested hostname, some unit tests Honza, sorry for the mid-air collision here, I was working on this patch last night. This patch is the same as Honza's, but with a few additions: * It normalizes the requested hostname before trying to string compare it with the current hostname. This solves problems with mismatched case, and also IDN issues. * Unit tests.
Oh, I did have one question; I couldn't figure out why the "localdomain" was added to the requested hostname in CanAccessStorage(). I took it out because the previous check in GetStorageForDomain() should be rejecting anything without a period, so I don't think that case was ever hit. Also, maybe we can just remove the check at the beginning of GetStorageForDomain() - you can no longer access a TLD's storage space anyway unless you are actually served from the TLD.
Marking late-compat, as this would affect anyone trying to use globalStorage for a domain other than the current domain.
Created attachment 309256 [details] [diff] [review] new version This version gets rid of the tld check as mentioned in comment 10, and does the hostname normalization using the nsIIDNService instead of creating a bogus nsIURI object.
Comment on attachment 309256 [details] [diff] [review] new version )?
(In reply to comment #13) > (From update of attachment 309256 [details] [diff] [review]) > )? nsStandardURL deals with a missing IDN service, but maybe things have changed since it was written?
Comment on attachment 309256 [details] [diff] [review] new version +function run() +{ + // This script expects to be loaded as test1.example.org Does the test framework ensure this somehow? Same with the child frame. + try { + storage = globalStorage["test1.EXAMPLE.ORG"]; + } + catch (ex) { + message += "\n failed globalStorage[\"test1.example.org\"]"; Should use the same case here so its easier to debug failures.
(In reply to comment #15) > (From update of attachment 309256 [details] [diff] [review]) > +function run() > +{ > + // This script expects to be loaded as test1.example.org > > Does the test framework ensure this somehow? Same with the child frame. The main test loads the two iframes with the hostnames they expect, but I'll add a test to make sure they are. > > + try { > + storage = globalStorage["test1.EXAMPLE.ORG"]; > + } > + catch (ex) { > + message += "\n failed globalStorage[\"test1.example.org\"]"; > > Should use the same case here so its easier to debug failures. Indeed, thanks.
Created attachment 310081 [details] [diff] [review] fixed for review comments I'm asking for approval since this is late-compat: This changes the implementation of globalStorage to only allow access to same-host storage. The HTML5 spec has removed globalStorage in favor of localStorage, which doesn't allow access to another hostname's storage area. While it's too late to implement this spec change for 1.9, restricting globalStorage will help ease the transition to localStorage and prevent any unintended inter-site communication (a motivating factor in the spec change). This will break any existing website that is currently trying to write to or read from a parent/subdomain's storage area. Before making the spec, Hixie wasn't able to find any use of this capability in the wild. We're the only shipping browser with globalStorage support, although the IE8 preview supports it. I don't know offhand if IE8 is planning to track the spec and replace globalStorage with localStorage for their final release.
This'll need some doc love if it goes in.
Comment on attachment 310081 [details] [diff] [review] fixed for review comments It's a blocker. Don't need approval. Cleared flag.
Created attachment 310269 [details] [diff] [review] fixed for review comments (right patch this time)
Checking in src/storage/nsDOMStorage.cpp; /cvsroot/mozilla/dom/src/storage/nsDOMStorage.cpp,v <-- nsDOMStorage.cpp new revision: 1.25; previous revision: 1.24 done Checking in tests/mochitest/bugs/Makefile.in; /cvsroot/mozilla/dom/tests/mochitest/bugs/Makefile.in,v <-- Makefile.in new revision: 1.24; previous revision: 1.23 done RCS file: /cvsroot/mozilla/dom/tests/mochitest/bugs/iframe_bug407839-1.html,v done Checking in tests/mochitest/bugs/iframe_bug407839-1.html; /cvsroot/mozilla/dom/tests/mochitest/bugs/iframe_bug407839-1.html,v <-- iframe_bug407839-1.html initial revision: 1.1 done RCS file: /cvsroot/mozilla/dom/tests/mochitest/bugs/iframe_bug407839-2.html,v done Checking in tests/mochitest/bugs/iframe_bug407839-2.html; /cvsroot/mozilla/dom/tests/mochitest/bugs/iframe_bug407839-2.html,v <-- iframe_bug407839-2.html initial revision: 1.1 done RCS file: /cvsroot/mozilla/dom/tests/mochitest/bugs/test_bug407839.html,v done Checking in tests/mochitest/bugs/test_bug407839.html; /cvsroot/mozilla/dom/tests/mochitest/bugs/test_bug407839.html,v <-- test_bug407839.html initial revision: 1.1 done
The documentation at Has been updated. Please let me know of any issues with it. | https://bugzilla.mozilla.org/show_bug.cgi?id=407839 | CC-MAIN-2017-17 | refinedweb | 1,118 | 50.53 |
I was having issues with BizTalk’s promoted/distinguished fields today, so I ran a small test, and I’m not sure what I have here.
What I want to see is when I change various values in a message (e.g. promoted property fields, distinguished fields, the message directly), when do the other values (e.g. promoted property fields, distinguished fields, the message directly) get updated? For instance, when I set a promoted value for a message, when does it get “pushed down”?
I have a very simple BizTalk project with a schema, property schema, and orchestration. In the schema I have a field called Node1 and I have both distinguished and promoted that field (into a property field named RoutingNode). In my orchestration, I have a series of activities where I manipulate the message in all sorts of sinister ways. Construct Block #1 has the following code contained (I’ve subtracted most of my trace statements):
SampleSchema_Output1 = SampleSchema_Input;
//print out distinguished value, promoted value, and actual XML content
System.Diagnostics.Debug.WriteLine(“Distinguished: ” + SampleSchema_Output1.Node1 + “; Promoted: ” +
SampleSchema_Output1(BizTalk.Blog.MonitorMessageChanges.RoutingNode));
xmlDoc = SampleSchema_Output1;
System.Diagnostics.Debug.WriteLine(“XML content: ” + xmlDoc.OuterXml);
//change promoted value
SampleSchema_Output1(BizTalk.Blog.MonitorMessageChanges.RoutingNode) = “changed #1”;
//print out distinguished value, promoted value, and actual XML content
System.Diagnostics.Debug.WriteLine(“Distinguished: ” + SampleSchema_Output1.Node1 + “; Promoted: ” +
SampleSchema_Output1(BizTalk.Blog.MonitorMessageChanges.RoutingNode));
System.Diagnostics.Debug.WriteLine(“XML content: ” + xmlDoc.OuterXml);
Got that? So I print out the current values stored in the distinguished field, promoted property field and then the whole message itself. Then I change the promoted property value, and print the whole thing out again. In Construct Block #2 I have the following code (all trace statements removed since you get the point):
SampleSchema_Output2.Node1 = “changed #2”;
So in that one I changed the distinguished field value. Finally, in Construct Block #3 I changed the underlying XML document itself:
//change xml directly
xmlNode = xmlDoc.DocumentElement.SelectSingleNode(“/*[local-name()=’SampleSchema’ and
namespace-uri()=’’%5D/*%5Blocal-name()=’Node1′ and namespace-uri()=”]”);
xmlNode.InnerText = “changed #3”;
So if you’re still with me, you may be interested in the results of this little experiment. What do you expect to be printed out after each Construct block? Here’s what I got:
I don’t think I expected that. From that experiment, it looks like the XLANG message either updates itself automatically, or, when I request the values (like distinguished fields or promoted properties) it’s checking for changes. Did I do something off here, or does this seem right to you people?
Hello Richard,
I’m not too surprised from the outcome. Following snippet is from a MSDN article
“A very important concept to understand is that all messages are immutable in BizTalk Server 2006..”
I’ve blogged about this behaviour quite sometime back at
So, what’s happening in your test?
From your post I can see, inside your Construct block, the very first step you were doing is message assignment
SampleSchema_Output1 = SampleSchema_Input;
SampleSchema_Output2 = SampleSchema_Output1;
SampleSchema_Output3 = SampleSchema_Output2;
This statements will trigger biztalk to create new messages (because of the immutable behaviour of messages inside biztalk). Then whatever changes you make obviously gets reflected on the new messages automatically. That’s the reason why you can only alter the messages inside the construct shape. If you place the same statement inside an expression shape, but outside “Construct” shape, Orchestration designer will throw compilation errors.
Nandri,
Saravana
Thanks for the comment. I guess my initial thoughts were that things would get synched AFTER the construct block was done, not while I was still monkeying with the message within the Assignment shape. BTW, love your new site.
Hi Rich,
I find your blog extremely educative and useful for my BizTalk explorations. Thanks a lot for keeping it updated 🙂
I was wondering if you have any plans to migrate the articles here to your new wordpress blog ? Or are you bound by some NDA with microsoft to not migrate them over ?
-Shiva
Oops. I meant migrating the articles from to the wordpress (this) blog. I tried to contact you from there, and the contact page did nothing….
-Shiva
Hi Shiva, thanks for the note. I thought I updated the “contact” on the old site to come to me.
Microsoft very kindly left the site up, so at the moment, no need to migrate anything over. If they ever disappear, however, you may see them show up here 😉
Did you ever get a definitive answer on this? My guess is that at the point you’re mucking around in the construct shape it’s still just hanging around in an XmlDocument object and thus the promoted and distinguished properties are merely xpath references into your in-memory XmlDocument; at the point the construct shape exits, all your promoted and distinguished fields get committed to the context and become immutable.
You know, I didn’t. Your theory may be correct.
Hi Richard,
This behavior is strange. Do you still have this sample project around? as new xlang dev I might be able to help you out.
Regards,
Anil
Hey Anil,
I don’t, but hopefully it’s very reproduce-able based on the post.
For construction of messages from source message, Xlang implements something similar to copy-on-write. All the message copies refer to same underlying data stream as long as they all are reading. As soon as one copy tries to change something in the message, it gets its own datastream and no longer shares the stream with other messages. In the example above, if you dump all the messages rather than just the one on which the construct block is working,you will see the difference. the newly created datastream would be saved/persisted at next persistence point.
Messages become immutable after code inside construct block is finished executing. Also just assigning the promoted property a value is not enough to promote a property. property just get written. see
Hello sir,
I wish to give my thought on the question raised in this blog (), though after a looong time 🙂 what I feel is that the reason the context properties and the data in the message are kept in sync is probably because of the fact that when you promote a property, lets say field element ‘Name’ from the message body whose initial value is “richard”. then you have a send port that subscribes to this message with filter condition “Name = Richard”. now after promoting ‘Name’ into context you modify ‘Name’ field element value in data using xpath as xpath(msgout,”//root/Name”) = “seroter” then what you expect is that this message should not be picked up by the send port as that port should be actually looking for “richard” messages. but in case if the data and the context do not sync up(as per your intensions in the blog ‘neither should change while the other changes’) then this message would land up in the send port, which would not what we expect(as name got changed). Hence keeping context and message data both in sync could be a feature that is probably intended to work in this way.
Thanks
V.Balachandra | https://seroter.wordpress.com/2007/02/15/synchronizing-biztalk-message-changes/?replytocom=7081 | CC-MAIN-2019-39 | refinedweb | 1,193 | 62.98 |
or, How To Forget To Explode Your Underwear
Hello! Welcome to part 2 of my silly-named series. This article we're going to cover the layout of the engine as a whole, and then move on to two of the most vital parts to an engine: Memory Management and Error Logging.
If you haven't sat down and look at any of the pre-packaged libraries I mentioned last time yet (SDL, SDL_Net, FMOD, and OpenGL), don't worry. We won't be going near them this time, with the exception of a cursory glance when I show you the design of the monster we're going to create.
Enginuity: Overview
The first thing that should jump out at you is the grey bar down the right-hand side. That represents the Application itself - while the rest of the engine will stay the same between projects, the Application part changes - that's how each game is made to be different. The program starts at the App Entry Point (you may know it as main() or WinMain()), and passes control out to the Kernel (almost immediately). Later on, various calls are made back into the application itself, to request the specific bits of data that the engine works with.
Hopefully, you'll also see how it breaks down into some fairly obvious chunks. At the bottom is the double-outlined 'KERNEL' layer - that's our 'foundation layer,' and provides services to the rest of the engine. Next up is the 'task pool,' which contains the tasks to render the screen, update input devices, etc - and also, the 'Appstate' task. The AppState system (or 'Gestalt,' as I like to call it) allows you to switch the 'mode' that your program is in - for example, changing from being in-game to being in a menu would most likely be a change in application state. The AppState system calls back to the AppState factory in the application, allowing you to provide the states for the engine to use.
Next up is the CLIENT/SERVER system. Now, just to get something straight - Client/Server doesn't have to mean *network* Client/Server. Anything providing a 'service' is a Server, and anything using that 'service' is a Client - in truth, the relationship between the Kernel and the rest of the engine is a client/server relationship, in that the Kernel provides 'services' to the engine. In this particular situation, the Server in the C/S system provides a 'common gamestate' - so all clients using that server will effectively be 'in the same game.' Even for a single-player game, this works - it just means that the common gamestate is only being used by one client. The Server will be the point from which AI code is called, and game rules are checked up on - it doesn't make conceptual sense to have the client do this.
Having said all that, the C/S system *does* provide the network support in the engine. If the Client and Server in a game are on the same machine, then the network system picks it up and uses the LocalComm boxes (which move messages from A to B directly in system memory, rather than sending them out to the network drivers, round the loopback, and in again). If they aren't - that is, the player is joining a network game - then it uses the RemoteComm boxes to handle connections to other computers. Both RemoteComm and LocalComm can be used simultaneously (i.e. when hosting *and* playing on one machine).
The C/S boxes also handle common networking tasks - checking that a client is running the same version of the app as the server, enumerating games on the LAN, and so on. They do this through the use of 'messages,' which are simply a numerical code attached to a blob of data. As such, certain message codes are handled by the boxes themselves, but for everything else, there's 'handlers.' And you'll like this: you can pick a number for your message type (assuming it's not already in use), and register a 'handler' for it. That handler gets called whenever a message with that code is received - so you can register IDN_CHAT_MESSAGE to call the handler RecieveChatMessage() (which, clientside, would display the message or something, while serverside it might filter it for profanity or server commands). Because the message handlers are in the app itself, it's more or less totally extendable.
Finally, there's the gamestate itself. The gamestate (as you probably already know) is the blob of data that describes everything you could need to know about the game - not just things like player scores or elapsed time, but player positions or world collision data. It comes in two flavours - both of which are usually pretty similar - one for the client, and one for the server. The information that each part of the game needs to work with is often different (albeit, not by much). An example: in a multiplayer game, the Server will need information on all players, while the Client may only need information about it's own player. A more important example would be bots and AI - all a bot's AI variables should be stored as part of the game state, but there's no point sending that info to the client (as they'll only need the bot's position, say). In any case, you're responsible for creating each gamestate (through the Gamestate Factory), so it's more or less up to you.
Setting up the Build Environment
You're probably going to need some kind of coherent 'project' to keep all your files together (unless you're some kind of hardcore kernel hacker / masochist). I'm familiar with MSVC6 so that's what I'll use, but most of this is applicable to you if you use something else (such as Borland C++ Builder or dev-c++). And although this is all meant to be cross-platform, I'm going to assume we're building under Win32.
Firstly, creation of the project itself. The project type should be 'Win32 Application,' and should be an 'Empty Project.' MSVC generates the project files in the place you picked, and then we dive into the project settings: SDL demands that we use the multithreaded version of the runtime library (Project -> Settings -> C/C++ -> Category: Code Generation -> Use run-time library: Multithreaded DLL).
You also need to set up the linker to link the engine with the required libraries. Either using #pragma commands, or going through the 'Linker' tab in project settings, add sdl.lib, sdlmain.lib, opengl32.lib, glu32.lib, fmodvc.lib, and sdl_net.lib to the list. I assume you already set up the locations of the libraries to be included in the search path (Tools->Options->Directories), along with the include files?
The last thing I'd recommend is to set up the debugging environment a little; specifically, the working directory. Given that you're going to be working with both Debug and Release builds over time, and each build is going to share the same resources, you want to put those resources in a common place. It's also quite useful to keep assets separate from your code. I create a 'runtime' folder as a subdirectory of the project folder, and build up my 'install' of the project's assets in there; the debugger gets set up to use the 'runtime' folder as the working directory (Project->Settings->Debug->Working Directory).
Now that we've got that out of the way, let's move on to the first of our topics du jour - Memory Management.
Memory Management
Memory is one of your top resources. It's your workspace; it's the floor of your room, where you can put toys while you play with them. And if you don't put the toys away once in a while, you'll run out of space and won't be able to play with any more toys. Until your mother comes up with a black binbag and starts putting everything into it shouting that you.. sorry, childhood flashback. *Ahem*. Moving on.
One of the most disrepectful things you can do to a player's system is leak memory. Your program's leaving mess on the pavement, and you're not scooping up after it. Gradually, the player's system gets slower and slower as the OS pages more and more memory to disk; until eventually they have to stop playing and reboot.
So here's the first thing our memory manager needs to do: track memory usage. It needs to keep an eye on all the blocks of memory we carve out, to ensure that said blocks get released again in the proper fashion.
Now, I've been a little, uh, 'economical with the truth.' We don't need to track *all* our memory. There's two types of memory involved: stack memory, and heap memory. Heap memory we worry about; stack memory we don't. There's also a few things that it's fairly impractical to manage - things like Singletons, or other 'large objects' that are so obvious that failing to release them would cause other noticable bad behaviour (things like the Kernel or Application objects). But for most of the objects our engine handles, they could slip away into obscurity at any time, never to be seen again... We need to keep a list of pointers to our objects.
Here's how we approach it. We create a new class, IMMObject:
class IMMObject { private: static std::list<IMMObject *> liveObjects; protected: IMMObject(); virtual ~IMMObject(); public: }; //a 'static initialiser' is needed in one of the source files //to give the std::list a definitive presence std::list<IMMObject *> IMMObject::liveObjects; IMMObject::IMMObject() { liveObjects.push_back(this); } IMMObject::~IMMObject() { // We add an empty virtual destructor to make sure // that the destructors in derived classes work properly. }Righty ho. To clean up all objects floating around at the end of the program, we loop through the liveObjects list, deleteing each pointer - and voila, no memory leaks. So that's ok - except, we can only do that at the end of the program. What if we're in the middle of the game and find ourselves running low on memory? We can't just delete all our objects and start again, but there'll probably be some objects we *could* delete, if we knew about them. So here we get to the next requirement of our memory manager: Garbage Collection. We should be able to remove from memory all the 'orphaned' objects that aren't needed any more.
But wait: how do we tell if an object isn't needed any more? We could have some kind of a flag that the object's user sets when it's done with it, but that's potentially disasterous if objects are being shared around (and they most certainly will be). So, coupled to Garbage Collection is a third requirement: Reference Counting. A system for tracking how many things are using an object, and for marking it as 'collectable' when they all say they're done. So, we try the IMMObject class again:
class IMMObject { private: static std::list<IMMObject *> liveObjects; long refCount; protected: IMMObject(); ~IMMObject(); public: void AddRef(); void Release(); static void CollectGarbage(); }; IMMObject::IMMObject() { liveObjects.push_back(this); //update the constructor to initialise refCount to zero refCount=0; } void IMMObject::AddRef() { ++refCount; } void IMMObject::Release() { --refCount; } void IMMObject::CollectGarbage() { for(std::list< IMMObject *>::iterator it=liveObjects.begin(); it!=liveObjects.end(); ) { IMMObject *ptr=(*it); ++it; if(ptr->refCount<=0) { liveObjects.remove(ptr); delete ptr; } } }There are two problems with this approach. Firstly, there's the rather icky construction in the CollectGarbage() function - the iterator has to be incremented at a weird time to make sure it doesn't get stepped on by the call to remove(). Also, this method is bad when the ratio of live objects to dead objects is high: when you've got 5000 objects being managed, but only 10 of them need removing, that's still 5000 objects being checked; not good. A better solution is to give the liveObjects list a parter - deadObjects:
class IMMObject { private: static std::list<IMMObject *> liveObjects; statid std::list<IMMObject *> deadObjects; long refCount; protected: IMMObject(); ~IMMObject(); public: void AddRef(); void Release(); static void CollectGarbage(); }; std::list<IMMObject *> IMMObject::deadObjects; void IMMObject::Release() { --refCount; if(refCount<=0) { liveObjects.remove(this); deadObjects.push_back(this); } } void IMMObject::CollectGarbage() { for(std::list<IMMObject *>::iterator it=deadObjects.begin(); it!=deadObjects.end(); it++) { delete (*it); } deadObjects.clear(); }Much neater, don't you think? (There's still an optimisation there - liveObjects.remove still searches the list for the object (which can take even longer than the initial method, in fact), so the object should store some kind of iterator allowing the list to remove it directly. But I leave it up to you.)
There's two more things we should add to the IMMObject class before we move on. Firstly, a fail-safe function, to be called at the end of the program, that will purge the liveObjects list (and log anything unreleased, because if there's anything still around at that time then something screwy's going on). Secondly, if we're going to track all the objects that are around, we might as well lay a base for tracking memory usage, too; so we add a pure virtual function, for derived classes to implement, that returns the size of the object.
class IMMObject { private: static std::list<IMMObject *> liveObjects; static std::list<IMMObject *> deadObjects; long refCount; protected: IMMObject(); virtual ~IMMObject(); public: void AddRef(); void Release(); static void CollectGarbage(); static void CollectRemainingObjects(bool bEmitWarnings=false); virtual unsigned long size()=0; }; //define a quick macro to make things easier on derived classes #define AUTO_SIZE unsigned long size(){return sizeof(*this);} void IMMObject::CollectRemainingObjects(bool bEmitWarnings) { CollectGarbage(); for(std::list<IMMObject*>::iterator it=liveObjects.begin(); it!=liveObjects.end(); it++) { IMMObject *o=(*it); if(bEmitWarnings) { //log some kind of error message here //we'll be covering how to log messages later this article } delete o; } liveObjects.clear(); }And there we go: a nice little base class to automatically memory-manage our objects. You might want to polish it up a bit - inline the AddRef()/Release() functions, for example - but again, I leave it up to you.
Smart Pointers
Those memory-managed objects are nice, but they're a bit of a pain to use on their own. Having to call AddRef()/Release() every time you deal with one isn't just tedious - it's asking for trouble. What would be good would be if AddRef and Release would just sort of.. call themselves, and that's where Smart Pointers come in.
Smart Pointers are objects that behave (and, indeed, can be treated) just like pointers - except that they do more than plain variable pointers. In our case, we can set up a Smart Pointer class to call AddRef() on an object when it's assigned to it, and Release() when it lets go of it. Then we can just do 'ptr = obj' in code, and the smart pointer takes care of the reference counting for us!
The faint-hearted amongst you: be warned that this next section uses most of C++'s 'advanced' features. If you're not comfortable with the *whole* language - including operator overloading and templates - leave now, and don't come back till you've bought several heavy books on the subject. Whether you beat yourself to death with them or actually read them is up to you. The rest of us: onward!
Now. The first, most obvious thing to say, is that smart pointers will have a pointer to the object they're pointing at. (I said obvious, not easy). That is, a smart pointer object set to point at object 'cheese' will need to have a pointer member variable that actually points to 'cheese' - without it, we wouldn't get very far. The smart pointer class itself acts something like a wrapper for that pointer. But I ask you: what type should the pointer be? Veteran C programmers amongst you might suggest void*, but we can do better than that. The more astute of you may well say that IMMObject* would be suitable - it's better than void*, but they both suffer from the same problem, which is that I can mix my object types. I can take a pointer to an object of 'CMonkey,' and assign it to a pointer which something expects to have an object of type 'CTable.' (In short, they lack type safety). The best solution is to use templates, and have each smart pointer custom-built to store a particular type of object pointer. So here's the initial code:
template<class T> class CMMPointer { protected: T* obj; public: //Constructors - basic CMMPointer() { obj=0; } //Constructing with a pointer CMMPointer(T *o) { obj=0; *this=o; } //Constructing with another smart pointer (copy constructor) CMMPointer(const CMMPointer<T> &p) { obj=0; *this=p; } //Destructor ~CMMPointer() { if(obj)obj->Release(); } //Assignement operators - assigning a plain pointer inline operator =(T *o) { if(obj)obj->Release(); obj=o; if(obj)obj->AddRef(); } //Assigning another smart pointer inline operator =(const CMMPointer<T> &p) { if(obj)obj->Release(); obj=p.obj; if(obj)obj->AddRef(); } };OK. That will now let us create a smart pointer object, and assign to it an IMMObject* (the thing you assign to it has to be derived from something with AddRef()/Release() methods, at least, otherwise it won't compile). Still, it's pretty useless without some other basic pointer operations - like accessing the pointer. D'oh! Never mind. We can also take the opportunity to catch null pointer exceptions - our accessor functions can simply check that the pointer isn't NULL before returning it. Watch and learn:
template<class T> class CMMPointer { protected: T* obj; public: //Constructors, destructor, and assignments are same as last time //Access as a reference inline T& operator *() const { assert(obj!=0 && "Tried to * on a NULL smart pointer"); return *obj; } //Access as a pointer inline T* operator ->() const { assert(obj!=0 && "Tried to -> on a NULL smart pointer"); return obj; } };Almost there now. We're just missing a few more things - like, for example, a simple way to convert back to normal pointers, or a way to check whether the pointer is NULL without causing an assert() in the process :-)
template<class T> class CMMPointer { protected: T* obj; public: //Constructors, destructor, assignments and accessors same as before //Conversion - allow the smart pointer to be automatically //converted to type T* inline operator T*() const { return obj; } inline bool isValid() const { return (obj!=0); } inline bool operator !() { return !(obj); } inline bool operator ==(const CMMPointer<T> &p) const { return (obj==p.obj); } inline bool operator ==(const T* o) const { return (obj==o); } };That should about do it.I've not included other operators - such as pointer math ops (+/-) - because it doesn't really make sense with smart pointers. You're meant to be pointing to objects, not arbitrary locations in memory. What we've got there, though, should be enough for 95% of the time - it should replace your average normal pointer absolutely transparently, with no need to change things - the only places where it's more complex is when converting one pointer type to another, and the aforementioned pointer math. There's ways of doing both.
When should smart pointers be used? The simple answer is: any time you need to 'retain' a pointer - keep it for any length of time that might include a garbage collection sweep. You don't need to use smart pointers if you're just using the pointer in a single function and then dropping it from the stack. That can be particularly useful when deciding on parameters for functions: if SomeFunction(CMMPointer &p) doesn't keep the pointer somewhere once it's returned, then it'd probably be easier to have it as SomeFunction(SomeObject *p). Accessing the object through a smart pointer obviously incurs a small speed cost, but it builds up; you should bear that in mind in speed-critical parts of the engine.
Now that we have a smart pointer, it's time to create our very first memory-managed object - another part of the memory-manager system!
Aside from actual game objects, the second most common dynamically allocated objects in our engine will be buffers. Buffers for decompressing resources, for serialising network messages.. you name it, there's a buffer for it. But you can't derive int[1000] from IMMObject - looks like we need another wrapper. Two, in fact - one for fixed-size buffers, and one for dynamic-sized (runtime-sized) buffers. The fixed-size one isn't really necessary, but it's *very* easy to do. These 'buffer wrappers' are the objects I affectionately term 'blobs,' and look like this:
template<class T, int i> class CMMBlob : public IMMObject { protected: T buffer[i]; public: inline T& operator [](int index) { assert(index<i && "Bad index on CMMBlob::[]"); return buffer[index]; } inline operator T*() { return buffer; } AUTO_SIZE; }; template<class T> class CMMDynamicBlob : public IMMObject { protected: unsigned long dataSize; T *buffer; public: inline T& operator [](int index) { assert(index<dataSize && "Bad index on CMMDynamicBlob::[]"); return buffer[index]; } inline operator T*() { return buffer; } CMMDynamicBlob(unsigned long size) { dataSize=size; buffer=new T[size]; assert(buffer!=0 && "DynamicBlob buffer could not be created - out of memory?"); } ~CMMDynamicBlob() { if(buffer)delete[] buffer; } unsigned long size() { return dataSize+sizeof(this); } inline unsigned long blobSize() { return dataSize; } };You see now why I said the fixed-size blob would be easy? That's just how easy simple objects are to handle - you can just group together a few variables in a class and have them memory-managed as a discrete object. The fixed-size blob takes the buffer type and size as template parameters; the dynamic blob takes the buffer type as the template parameter, and the buffer size as the constructor argument (so you can work it out at runtime). Note that the fixed-size blob uses the AUTO_SIZE macro, defined above, while the DynamicBlob reports the *actual* size of the object - including both the allocated buffer and the wrapper. If you just want the size of the buffer itself, you should use the seperate blobSize() function - because requiring you to remember to subtract the 8 bytes or so that the wrapper uses is, as usual, asking for problems.
Each class provides access control, for two reasons: firstly, it's far too easy to severly mess things up by reallocating the buffer pointer or deleting it yourself (not that you'd ever want to do that, but accidents happen), so by forcing access to go through the [] and T* operators, we completely protect buffer itself from the outside world. It's still possible to do something like "delete (sometype*)(*obj);" but it's less likely because the syntax is more unweildy. The second reason is those asserts - we have the opportunity to check that we're not trying to access memory outside of the buffer.
Woo! That, ladies and gentlemen, is the end of Memory Management. We now have a (relatively) robust system for tracking objects within our engine, and trust me, we'll be using it. It's totally independent of any other library or class (with the exceptions of the assert() calls), making it ideal for reuse. It doesn't depend on any platform-specific functionality, such as byte order. Looks like we're meeting the spec, then. On to...
Error Logging
There comes a time in every young engine's life when... things don't quite work as they should. Sockets don't connect, resources can't be found... if we're ever going to have a hope of finding and fixing the problems, we are of course going to need to know about them. So we have a system for recording errors as and when they occur - 'error logging.' In truth, logfiles can and should be used for recording all kinds of events, not just errors - if something's going wrong and not recording what, recording the things that *are* working will help you find the problem by process of elimination.
We could just create an ofstream object and store it in a global variable - such a method works (up to a point) but is pretty basic. We can do better than that! Our logging system will support multiple logfiles, predefined localisable messages, and parameter replacement.
Multiple logfiles are just useful. In extreme cases this could mean one logfile per subsystem - one each for video errors, sound errors, etcetera; I'm not going to go that far, and just have 3 logfiles (CLIENT, SERVER, and APP). CLIENT and SERVER will record - you guessed it - log files relevant to the Client or Server portions of the program (Client includes all the Video, Sound, and other 'player-end' tasks - Server will tend to be less used, but will record connections being opened and closed, games being started and stopped, and AI/physics messages), while APP will record Kernel-level messages, along with those messages that don't seem to 'fit' into CLIENT and SERVER. You can, of course, record a message to more than one logfile at a time.
"Predefined localisable messages," more often known as a "string table", allow you to store some common strings somewhere, load them in, and then reference them by ID number - rather than hard-coding the message into your app. This saves a large amount of space (because strings aren't being duplicated), and also makes it very easy to translate all the messages into another language.
"Parameter replacement" is the technique demonstrated by the old C string functions like printf() - special 'field codes' in the string get replaced with actual values that get passed in seperately. So, strings can be more generalised - rather than needing one string for each error number, you could just use a single string with a field code ("Error code %i") and pass the error number in alongside it. We'll be using the printf() syntax for field codes - mainly because we'll be using a special form of the printf() function to build our messages from the strings and arguments. Furthermore, you can store messages with field codes in the strings table - and that's where things start getting really interesting.
For the time being, though, let's get started. There's just one last thing I need to mention - the method of storing the strings file. It's generally a good idea if the strings can be stored where curious users can't tamper with them - adding or removing field codes where they're not expected could cause some serious problems. Under Linux and MacOS, we've not really got anywhere tamper-proof to keep the strings - we'll have to make do with a read-only file. On Windows, however, we can store the string table as a resource, built into the executable. That's why you'll see two versions of the LoadStrings() function; one reads the strings from the resources area, and the other reads from a file on disk. Conditional compilation is used to compile the right one on the right platform.
Enough waffle. Here's the class:
//first, a few predefined constants const int LOG_APP=1; const int LOG_CLIENT=2; const int LOG_SERVER=4; //LOG_USER is used to display the log message to the //user - i.e. in a dialog box const int LOG_USER=8; #define MAX_LOG_STRINGS 256 class CLog { protected: CLog(); std::ofstream appLog; std::ofstream clientLog; std::ofstream serverLog; std::string logStrings[MAX_LOG_STRINGS]; bool LoadStrings(); public: static CLog &Get(); bool Init(); void Write(int target, const char *msg, ...); void Write(int target, unsigned long msgID, ...); };Pretty straightforward. The log is a Singleton, which is why you see a protected constructor and a static Get() function - trying to have more than one CLog object at any time simply wouldn't work, because they'd both be trying to open the same files, and would cause a sharing violation. The files themselves are accessed through std::ofstream objects. The strings table, once loaded by the LoadStrings() function, is stored in the logStrings array - you could use a vector, but I didn't (because it doesn't *really* need to be dynamically expandable.. when are you going to need more than 256 slots for log messages?). Then, moving down to the public section of the class, there's the destructor and aforementioned Get() function; then, an Init() function, which is responsible for actually opening the logfiles and calling the LoadStrings() function - this isn't done by the constructor, because if it fails, there's no way of knowing; with an explicit Init() function, we're reminded to check the return code. It also gives us total control over when the log is started up.
Finally, the Write() functions. Each takes an int that tells you where the message should be logged to (by ORing together the LOG_* codes defined above); then, one takes a string pointer (for hard-coded strings), and one takes a unsigned long (for string table ID number). Then, each takes some kind of nebulous '...'. What's that about, you ask?
'...'s are known as 'ellipses,' and are how we achieve 'variable argument lists.' Given that the message we're using may contain 5 field codes or 50, the number of values we pass with it will vary - and that includes the situation where there are no arguments. So, we use the '...' to denote that any number of arguments can follow the fixed ones (and there must be at least one fixed one, even if it's just a dummy one). We don't actually need to process the list ourselves in the Write() functions - a good thing, because variables being passed in lose all type information and become a pain to work with - we just need to retrieve a pointer to the list, and pass it on to the special printf() function, vsprintf().
Here's the functions themselves:
CLog::CLog() { //the constructor doesn't do anything, but we need //it for our singleton to work correctly } CLog &CLog::Get() { static CLog log; return log; } bool CLog::Init() { appLog.open("applog.txt"); clientLog.open("clntlog.txt"); serverLog.open("srvrlog.txt"); //user errors get logged to client //load the strings file if(!LoadStrings())return false; return true; } void CLog::Write(int target, const char *msg, ...) { va_list args; va_start(args,msg); char szBuf[1024]; vsprintf(szBuf,msg,args); if(target&LOG_APP) { appLog<<szBuf<<"\n"; #ifdef DEBUG appLog.flush(); #endif } if(target&LOG_CLIENT) { clientLog<<szBuf<<"\n"; #ifdef DEBUG clientLog.flush(); #endif } if(target&LOG_SERVER) { serverLog<<szBuf<<"\n"; #ifdef DEBUG serverLog.flush(); #endif } if(target&LOG_USER) { #ifdef WIN32 MessageBox(NULL,szBuf,"Message",MB_OK); #else #error User-level logging is not yet implemented for this platform. #endif } } void CLog::Write(int target, unsigned long msgID, ...) { va_list args; va_start(args, msgID); char szBuf[1024]; vsprintf(szBuf,logStrings[msgID].c_str(),args); Write(target,szBuf); } #ifdef WIN32 //under Win32, the strings get read in from a string table resource bool CLog::LoadStrings() { for(unsigned long i=0;i<MAX_LOG_STRINGS;i++) { char szBuf[1024]; if(!LoadString(GetModuleHandle("engine"),i,szBuf,1024)) break; //returning 0 means no more strings logStrings[i]=szBuf; } return true; } #else //other platforms load the strings in from strings.txt bool CLog::LoadStrings() { std::ifstream in("strings.txt"); if(!in.is_open())return false; DWORD index=0; while(!in.eof()) { char szBuf[1024]; in.getline(szBuf,1024); stringsFile[index++]=szBuf; } return true; } #endifAfter reading that, there's probably a few things you're wondering about:
Firstly, that va_list business. That's how we work with variable argument lists; we create a pointer of type va_list (it maps to char*, in the headers), and use the va_start() macro to get it pointing to the right place, by passing va_start the argument *immediately before* the list - va_start gets a pointer to that, adds on its size, and stores that in va_list (or something along those lines, at least). We can then pass va_list to vsprintf(), which happily processes it for us.
Next, the flush() calls. In theory, this should make sure that the message you've just written actually gets saved to disk, rather than being stored in a cache somewhere; given that your app is still unstable in debug builds, a crash would cause you to lose log messages in that cache (and those log messages would probably tell you how and why you crashed). I say 'in theory,' because it didn't actually *work* for me; I left it in because it's *meant* to. Tracing the flush() call through the documentation gets to basic_streambuf::sync(), which "endeavours to synchronize the controlled streams with any associated external streams," that is, it tries to get the in-memory object into the same state as the file on disk (by changing the file on disk). I would guess that it's failing there; if you can tell me why, kudos.
I didn't mention the LOG_USER option before. You should have figured out what it does by now, but if you haven't - it displays the message to the user (i.e. in a pop-up message box). You can use this for the really important messages, like 'The game failed to start because it's got a hangover.' However, implementation of this is platform-dependent, which is why you see the #ifdef WIN32 lines in there. There's also a #error statement - if you try and build this on a platform other than Windows at the moment, it won't let you build because that LOG_USER functionality isn't implemented. All non-windows users need to do is add an #elif defined MY_PLATFORM_FLAG before the #else line, and they'll be free to implement the message box for their own platform; I've not done any platform other than Windows because I'm not confident I'll get it right.
It's probably worth noting that the string-table-based version of the Write() function uses the plain version to do the actual logging. It's nice like that. It's also an example of passing no arguments in the variable-argument list; the plain Write() function will handle that fine, as you will see.
Miscellanous Utilities
Hmm, that could probably be a good name for a geek band
There are a few base classes that will be used from time to time across the engine; there are a few more which, while I won't cover here, use the same or similar techniques. Many of these base classes are provided by common libraries such as boost (or, in fact, the STL itself) - but I'm here to educate, and a couple of implemented design patterns never hurt anyone. It may not be totally obvious how some of these will be useful at this stage, but I will be using them all; as such, it will help if you can read, understand, and have them ready to hand in later articles.
Functors
A functor (or, to be more precise, a 'bound functor') is a way of wrapping up a function somewhere in an object. Have you ever tried to work with a pointer to a member function? You can't, for example, dereference a function pointer to CLog::Write() without a pointer to the object it needs to be called on (otherwise, what does the 'this' pointer equal?). With functors, you can wrap up the pointer to the object *and* the pointer to the member function within that object, and use the functor to call it in an easy way. So, we have our functor base class:
class Functor : public IMMObject { public: virtual void operator ()()=0; };Firstly, it's memory-managed, meaning that we can throw as many functors as we want around the place and the engine will clean up after us. Secondly, though, it's very obviously an abstract base class for something else. Why? Because the class we're about to derive from it is a templated class:
template<class T> class ObjFunctor : public Functor { protected: T *obj; typedef void (T::*funcType)(); funcType func; public: AUTO_SIZE; ObjFunctor(T *o, funcType f) { obj=o; func=f; } void operator ()() { (obj->*func)(); } };That's more like it. The pointer-to-member-function type is typedef'd for easy use; the AUTO_SIZE macro makes its appearance to satify IMMObject::size(). But what's with this base->derived business? Why bother with the base class at all, and not just have ObjFunctor derived from IMMObject?
It's like this: When you create an ObjFunctor, you'll give the type of the object that it works with - going from our earlier example, ObjFunctor will let you store pointers to functions on any CLog object. Now, let's say you want to keep a generalised list of ObjFunctor objects - say, a list of functions to call in the event that something happens - you'll find you won't be able to. Your std::list< ObjFunctor * > tells you that ObjFunctor requires a template parameter; but if you give it that, you fix the list as being a list of function pointers, or whatever you specify. That's not much good - you want to be able to point to any function, anywhere. That's why we use the base class; you create your list as std::list< Functor * >, and then can store any ObjFunctor in it - and the fact that the () operator is virtual means that calls get passed down in the correct way to the ObjFunctor class.
Lastly, as you may have guessed from the existence of the () operator, the syntax for calling a Functor object (not a pointer, mind) is exactly the same as calling a normal function - fMyFunctor() will call whatever function fMyFunctor is bound to. If fMyFunctor is actually a pointer, rather than an object (as will often be the case), (*fMyFunctor)() will do the trick.
There's one more special case. The ObjFunctor doesn't take into account the reference-counting system; the object that it points to could be freed without its knowledge. Thus, we derive a second class from Functor:
template<class T> class MMObjFunctor : public Functor { protected: CMMPointer<T> obj; typedef int (T::*funcType)(); funcType func; public: AUTO_SIZE; MMObjFunctor(T *o, funcType f) { obj=o; func=f; } int operator ()() { return (obj->*func)(); } };Near-identical, except that the obj pointer is now a CMMPointer. You won't necessarily want to use this all the time, as the other version is slightly faster.
One useful feature I tried to implement (and couldn't, because MSVC doesn't support partial specialization) was the ability to set the functor's return type. If you're using a compiler which supports it, here's a hint: all the Functor classes need to be specialized for the void return type. This is because return (obj->*func) doesn't compile if func returns void. So, you'd have Functor, and then ObjFunctor (which is where MSVC breaks down, because I need to specify the 'void' for R but can't specify anything for T), and so on.
So, the Functor allows us to wrap up a function inside an object. It could be useful for, say, callback handlers when a button is pressed, in a UI system.
Singleton
I give credit for this to Scott Bilas, who presented the technique in Game Programming Gems (an excellent series of books, if I may say so).
You should already know what a singleton is (and if you don't, I apologise - my previous mentioning of the term may have confused you a little). However, it's a bit tedious (to say the least) to have to implement the same singleton code, each time you want a new class as a singleton. Ideally, there should be a Singleton base class - and with the magic of templates, there is.
template<typename T> class Singleton { static T* ms_singleton; public: Singleton() { assert(!ms_singleton); //use a cunning trick to get the singleton pointing to the start of //the whole, rather than the start of the Singleton part of the object int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1; ms_singleton = (T*)((int)this + offset); } ~Singleton() { assert(ms_singleton); ms_singleton=0; } static T& GetSingleton() { assert(ms_singleton); return *ms_singleton; } static T* GetSingletonPtr() { assert(ms_singleton); return ms_singleton; } }; template <typename T> T* Singleton <T>::ms_singleton = 0;To use the singleton class, we derive a class SomeClass from Singleton. One thing to note about this type of singleton is that we - not the loader - are responsible for creating the singleton and destroying it again when we're done. We create it simply by calling new SomeClass() somewhere in code - the constructor takes care of the rest, so we don't even need to store the pointer that new returns. To destroy it, we call delete SomeClass::GetSingletonPtr(); that also sets the singleton pointer back to zero, so we can recreate the singleton if we want.
The Singleton will come in useful for many key engine systems, such as the kernel or settings manager, of which we only ever want one.
Ring buffer
This one I came up with purely on my own.
A ring buffer is, as the name suggests, a 'ring-shaped buffer' - a circular buffer, which has no specific start or end. You create it to store a maximum number of a specific type of object, and then read and write to it like reading or writing to a stream. Obviously, the buffer has to have it's block of storage space as a plain, linear block of memory internally; but it stores read/write pointers, which it 'wraps' to the beginning of the block whenever they pass the end. Provided that the read pointer doesn't catch up to the write pointer (i.e. the buffer is empty), or vice versa (i.e. the buffer is full), then the buffer seems infinitely long. There's no time-consuming memcpy() operations involved; the only limitation is that the size must be determined at compile-time, rather than at runtime (although even that could be fixed, if you needed to).
template<class T, unsigned long bufSize> class ringbuffer { protected: T buf[bufSize]; unsigned long read, write; public: ringbuffer() { read=0; write=1; } bool operator << (T &obj) { buf[write]=obj; ++write; while(write>=bufSize)write-=bufSize; if(write==read) { --write; //make sure this happens next time while(write<0)write+=bufSize; return false; } return true; } bool operator >> (T &res) { ++read; while(read>=bufSize)read-=bufSize; if(read==write) { ++write; //make sure this happens next time //we call and the buf is still empty while(write>=bufSize)write-=bufSize; return false; } res=buf[read]; return true; } unsigned long dataSize() { unsigned long wc=write; while(wc<read)wc+=bufSize; return wc-read-1; } void flood(const T &value) { //loop through all indices, flooding them //this is basically a reset read=0; for(write=0;write<bufSize;++write) { buf[write]=value; } write=1; } };So, reading and writing to the buffer is done through the >> and << operators. There's also a dataSize() function, which will tell you how many elements are available for reading, and a flood() function, which is useful for wiping the buffer (initialising all slots to a particular value).
The ring buffer will prove useful in the C/S systems, eventually. It's like a FIFO (First In First Out) queue, but it doesn't need to allocate any memory, making it quite a bit faster.
Coda: Gangsta Rappa Game Developer
(Geddit? *sigh*)
That's all for this time. Next time we'll finish the kernel layer, I think, if you're up for it - the Settings system and Task Manager / Kernel Core systems await. But now I'm going to go check my email... | http://www.gamedev.net/page/resources/_/technical/game-programming/enginuity-part-ii-r1954?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024 | CC-MAIN-2016-44 | refinedweb | 7,302 | 57.3 |
Building a Video Streaming Service
July 30, 2018
Updated: August 26, 2018
Table of Contents
- Motivation
- Requirements
- philo, a Video Streaming Service
- Choosing a Cloud Provider
- Languages and Tooling
- Service: philo-media-encoder
- Why a Service Bus?
- Logging
- Key Management
- Monitoring: Availability and Health Checks
- Monitoring: Events and Telemetry
- Service: philo-media-service
- User Interface
- Architecture Map
- Demo and Performance
- A/B Testing
- Cost Discussion
- Conclusion
Motivation
A really popular question that seems to go around is "How would you design Netflix"? Normally, in a 45 minute discussion, there really isn't enough time to actually go over specific implementation details. What usually results in such a discussion is a very high-level design of the overall system architecture.
I have personally always wondered: what would happen if we actually attempted to implement a "Netflix", or more generically, an on-demand video streaming service from scratch?
I personally have always had this temptation, but never a "fire" to actually get started until I started reading a few books about cloud computing. Another crazy thought that had always been on my mind was to be able to experiment with a cloud service without much regret on the financial resources that would be spent learning.
So, I decided to commit to two things:
- Commit to implementing a basic on-demand video streaming service with adaptive streaming capabilities.
- Leverage the offerings from a particular cloud service to make it happen! (And keep it reasonably affordable.)
Some of the questions I had in mind before undertaking this project were:
- What type of infrastructure would it take to implement such a service?
- What are some of the unique design decisions that might occur while trying to deliver video content efficiently?
- Would the cloud provider which I choose ultimately affect any of my design and implementation decisions?
Addtionally, I was quite inspired by Dianne Marsh's talk shown at InfoQ on Continuous Delivery at Netflix. . One of the points she discussed which hit home for me was that organizations tend to use cloud computing as a remote data center, where virtual machiness are just spun up to host an application. A lot of organizations tend to stray away from using what really cloud provides: a set of services to continuously improve your application. The ability develop and deploy to production at a higher velocity and create resilient infrastructure on the cheap which then redirects energy and focus on actually developing the product to deliver business value.
Because of the inspiration above, you will find that I have biased myself with a specific cloud service provider. I will be transparent and state that this provider will be Microsoft Azure.
Also, this article was written in bits and pieces. As you read along you will wonder: "What the hell is this article about?". To tell you the truth, I originally started this as a hobby project, but it has changed over time. Over time, the aspiration for philo is to become a teaching tool and template project for those who may want to begin in learning about microservices, and how to leverage cloud-computing to create interesting services and applications. If you do not agree or find the tone of writing to be this way, please provide me with some feedback and suggest how I can make it all better!
So, where to find the code? Well, the code is all here!.
I am currently trying my best to keep it up to date. You can follow along as our journey progresses. Check-ins happen frequently -- almost everyday. Because of the velocity of the development and the nature of it being a side project while I have a day job, you will be unsurprised to see that there are plenty of areas within the codebase that scream "technical debt". You will end up seeing plenty of things such as: lazy coding, lots of technical debt, then commits that kill technical debt, followed by more technical debt incurring due to being lazy, and hardcoding things... then undoing hard-coded things and finally actually having some presentable code. It is the nature of software development and I am not shy to let it all out!
Requirements
In order to keep the scope of the project reasonable, I will define very early, a small set of requirements in which the video streaming service will have. I have divided the implementation to contain two domains: the viewer-focused domain, and the administrator-focused domain.
- Viewer Focused
- Allow on-demand video streaming of the content that is readily available.
- Adaptive streaming of content. The quality of the video should adjust to the current available bandwidth of the viewer.
- Hands-off discovery (dynamic listing) of new content made available by the backend services.
- Administrator Focused
- Ability to push new content to the video streaming platform.
- Content should be made to support adaptive streaming.
- Metadata regarding the video should be kept up to date.
philo, a Video Streaming Service
Sometimes the hardest thing about making a new project is to give it a name. When deciding on a name, I want the project name to be memorable, and simple -- yet, define what it is trying to achieve.
In keeping with my growing interest in history, I decided to name the project philo. The origin of the name comes from one of the key people involved with the invention of the television: Philo Farnsworth.
The name is very appropriate due to television being the ultimate bootstrap of all the multimedia content we now consume day-to-day online.
Choosing a Cloud Provider
One of the earliest decisions I made regarding the high level architecture was that I wanted the system to be composed of services that would interact with each other in a decoupled manner. Naturally, composing the system as a set of microservices was appropriate.
I felt the scope of the project was small enough that I would be able to create a few microservices and learn about some of the benefits and drawbacks on choosing to create a system composed of microservices right from the get-go.
I also wanted to make sure that I would invest my personal budget into a single cloud provider that could provide me the following:
- Content Delivery Network (CDN) of multimedia assets.
- Cheap storage for assets generated by both the user-facing and administrative domains.
- Easy management of web application services. (Polyglot services, containerized deployments, etc)
- Client secrets and key management.
- Video encoding services.
- Asynchronous messaging capability.
- Affordability!
I ultimately chose Microsoft Azure due to the offerings available and the bias in that I am currently a Microsoft employee. The options provided by Azure were not only affordable, but also the libraries for each of the services I wanted to develop with were easy enough to get started with.
Having worked with cloud services from various providers in the past, I knew that the Azure offered mostly the basic things of CDN (Azure CDN), storage (Azure Storage Account), key management (Azure Key Vault), and web applications (Azure Web App Service).
What was really worrying me was whether or not Microsoft Azure actually had a readily available solution with regards to video encoding services. Thankfully, after some quick research, I found out that Azure Media Services provided the services I needed.
Without going too much into detail (you can read the offering information the website), the service allows the features of:
- Encoding and processing video on the cloud.
- Providing a media player integration to the media services account.
- Delivering video from a streaming endpoint through a CDN optimized for multimedia content.
- Invoking service operations through API calls with .NET/Java libraries.
Reading through some of the media services documentation, I realized that I had two versions of the service to choose from: a v2 API, and a newer v3 API.
Of course, the v3 API seemed more interesting to work with, and the documentation had seemed to be written around the v3 API entirely, I decided to go with this specific version.
Languages and Tooling
As for the choice of languages, I was energized early on to learn Spring and take my Java skills to the next level. However, experience told me that not all libraries are created equal. Although I saw that Azure had provided both .NET and Java libraries for the Media Services offering, I was a bit skeptical in seeing what the Java support was really like. (It turns out my skepticism proved to be correct.)
Looking at the MVN repository information, the latest v3 API implementation is 0.9.8 dated back October 2017. This lead me down in even more skeptical path after visiting the GitHub repository and finding out that the version corresponded with the 2018-03-30-PREVIEW API, with the 2018-06-01-PREVIEW implementation being in development.
This was also the newest available library for Java implementing the v3 API. Along with not many sample code floating around to reference for Java, I quickly decided to make the decision on whether to develop the specific service that would interact with Azure Media Services with Java, or .NET.
The method to decide that was to just simply create a test service that would do the suffice the core main requirements:
- Encode a video
- Get the streaming URLs for the output
Anyway, to really give imagery on what happened, I basically spent a day getting to know the API concepts, and libraries and implementing the above requirements through the Java library. I found it to be insufficient and hard to really use. I eventually chucked out the whole idea of writing the service in Java due to the primitive API implementation available paired with the lack of real documentation.
I then found this basic code example that would actually perform the operations I wanted, and was implemented in C#. It was then that I had already made the first implementation decision: go with .NET for the encoding service simply because of:
- Better documentation around the .NET libraries.
- Code examples and ease of implementation.
I was also readily willing to go with .NET for implementing the encoding service because I had reasoned with myself that I could simply write the entry point to kick off the service to send the jobs to Azure with any other type of language or technology. As it turns out and will be discussed later, this was necessary anyway.
With that hard decision finally made, I compromised with myself that I would get to play with whatever exciting technology as it becomes appropriate down the line for the this project. Afterall, with microservices, we can definitely do that.
Now, let's introduce our first service...
Service: philo-media-encoder
I always like to work on solving the most mysterious parts of a project first. Naturally, this became the media encoding service that serves as the main central work-horse of the system.
I really wanted the philo-media-encoder to take a video file and have it encode it to various bitrates to create an adaptive streaming experience similar to the process used by Netflix and YouTube. A viewer never has to adjust the quality of the video based on the current availability of bandwidth, and instead the service itself will deliver the appropriate video content with just the right bitrate for the available bandwidth to create a seamless viewing experience.
I decided that the philo-media-encoder architecture will consist of four main components to encode input media for adaptive streaming.
- philo-media-encoder
- philo-media-encoder-producer
- philo-media-encoder-consumer
- philo-media-service
First, there are pre-conditions before any of the steps within the encoding workflow can execute. The preconditions are that the input asset media files must be located either in Azure storage or through some publicly accessible URL. For the latter statement, this could be a CDN.
To start, the name of the service will be philo-media-encoder-producer. The basic functionality of this service is that it will receive a message with a payload that will contain two pieces of information: the name of the input asset, and the location on where to find the asset.
The input asset name comes from an asset that is already available in Azure through CDN or storage account. The input asset name is the is the name of the asset in the available assets of Azure Media Services.
This producer service receives the name and location and produces a messages that will be placed into the message queue backed by Azure Service Bus. The message will be placed asynchronously, and the producer service will immediately return a response back to the requester.
Each message takes on the following format:
{ "name": "My Video.mp4", "location": "" }
On the other side of the service bus, a consumer service, philo-media-encoder-consumer is running continuously waiting to consume messages that are placed into the service bus queue. Upon receipt of the message, an invocation to the philo-media-encoder module is made. Note that the philo-media-encoder-consumer, and the philo-media-encoder module sit on the same instance.
When the consumer service receives the message from the service bus, the following occurs:
- A philo-media-encoder object is created and the parameters are passed to start the media encoding job on Azure Media Services.
- After each step, which is performed synchronously, metadata about the job is returned. The metadata can be the input ID that correlates to the input asset, output asset, and streaming URL information placed into the persistent store for cataloging and querying by any client side application.
The consumer service is decoupled from the encoder class simply because we want the consumer service to not be blocked by an encoding job. By instantiating the object that will synchronously performed the encoding job, we can process many messages without waiting for the previous job to finish.
Upon knowing the information needed to pass to Azure, the flow in which the encoder is responsible for will then be:
- Encode the media file given by the location.
- Make the assets public through Azure storage.
- Create the streaming URLs which references the assets within Azure storage.
At each step along the way, the consumer class is responsible for using the metadata returned by philo-media-encoder to invoke an external service call to philo-media-service, in which I will introduce later, to store the information to be queried later by client-side applications. But for now, think of philo-media-service as the main orchestrator for manipulating/managing metadata information about a particular output from Azure Media Services in the overall philo ecosystem so that it can be used for video stream delivery.
In order to keep track of the status of the media service job, philo-media-encoder will also periodically poll for the job state.
States which define that the job is not complete are:
- Scheduled
- Queued
- Processing
- Canceling
States which define that job is complete are:
- Finished
- Error
- Canceled
The expectation is that after running philo-media-encoder on a given asset, we should have multiple versions of the same asset available to be delivered for streaming situated in our storage account. For example, if we were to input a 1920x1080 MP4 video file, we should get video files along the lines of: 1280x720, 640x360, 320x180, etc.
With that said, here is the overall high-level system architecture for the encoding workflow.
Let us start with a basic flow of the above.
First, there is some arbitrary invocation call that passes an HTTP POST message to the philo-media-encoder-producer application. This contains a JSON payload defining the name and location of the asset. The payload received during this request is similar to the message that is actually produced by the producer service itself.
After the producer constructs the message to be passed to the service bus, the producer also immediately returns an HTTP OK response back to the requester. At the same time, the consumer is listening for any messages in the service bus.
When the consumer has received a message from the service bus, it then uses that information to start the philo-media-encoder job through object initilization.
The encoder job then interacts with both Azure Media Services and philo-media-service to orchestrate the job state, output asset metadata and streaming URL construction and persistence.
Why a Service Bus?
A question at may come up now is why I have I made the decision to use a service bus and not just have an entry point directly to the philo-media-encoder service with a point-to-point invocation. The decision comes from the fact that direct entry points through some sort of call is synchronous. With calls that result in processes that can be long running, synchronous invocation can lead to timeouts. With video encoding, almost all jobs are long-running processes and need a significant amount of time for completion.
For example, if we were to provide an entry point directly to the philo-media-encoder service through HTTP REST, upon invocation of the POST call, the job will be kicked off. An indeterminate amount of time will pass before receiving a response back from the job. By then, depending on the scale of the job, the calls will time out before the client has any chance to know whether or not something happened.
Therefore, we need to take client timeouts into consideration and introduce asynchronous requests. By providing a service bus between the client requests and responses, we can essentially deliver a response back to the client much faster by notifying them that the job is being processed, and will take some amount of time before the process is done. The request handler is simply responsible for delivering the information needed to start the encoder job to the service bus and just needs to return the response.
A response can be anything in that case. It can be a notification, or something that will invoke an external service, call, etc to check the status of the job. This alleviates the need for the client to "busy-wait" in a sense.
By avoiding a point-to-point communication, we not only get around with avoiding network request timeouts, but we also gain loose-coupling between services: they do not all need to be online at once to be able to function.
Logging
Before we dive deeper into our implementation, I would like to pause for a bit to talk about logging! There is anticipation to have many decoupled services all functioning asynchronously and distributively, it is easy to lose track what is going on as a result of the temporal distortion in execution.
In order to attempt to maintain some sanity in debugging services which are live, one should invest in basic logging within the infrastructure in which is built. In the case of philo, let us use our producer, consumer, and encode services as examples on how we should go about building a logging infrastructure. If you are not really familiar with basic practices of logging, and before we start going down the technical debt minefield, now is a good chance to read a thing or two about high performance logging :).
The goal is not to create anything spectacular, but merely something that will work within our application architecture, and give ourselves something to extend and build upon should our service scale even further.
Since we are using
dotnet core as our platform for philo-media-encoder-producer, philo-media-encoder-consumer, and
philo-media-encoder, let us use
NLog as our primary logging framework. The basic fixture will not be anything that is
super complex. In fact, let us aim for something simple for now -- we want to just log to a file, and then have it be delivered
to a indexing service. (We will use the ELK stack for that.)
Each service will have a
Logger> class which essentially configures NLog to set up a very basic logging component for the
service. For example, here is the philo-media-encoder-consumer
Logger class as an example:
using System; using System.Collections.Generic; using System.Linq; namespace PhiloMediaEncoderProducer { public class Logger { private static NLog.Logger thisLogger; private static String GetDateString() { DateTime currentDateTime = DateTime.Now; String month = currentDateTime.Month < 10 ? "0" + currentDateTime.Month.ToString() : currentDateTime.Month.ToString(); String day = currentDateTime.Day < 10 ? "0" + currentDateTime.Day.ToString() : currentDateTime.Day.ToString(); String year = currentDateTime.Year.ToString(); return $"{year}{month}{day}"; } private static NLog.Logger ConfigureNLog() { var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = $"logs/{Logger.GetDateString()}.producer.log", ArchiveAboveSize = 4000000, MaxArchiveFiles = 10 }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile); config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logconsole); NLog.LogManager.Configuration = config; return NLog.LogManager.GetCurrentClassLogger(); } private static bool NeedsDateRotation() { String currentDateString = Logger.GetDateString(); String[] files = System.IO.Directory.GetFiles($"logs"); foreach(String file in files) { System.IO.FileInfo currentLogFile = new System.IO.FileInfo(file); if(currentLogFile.Name.StartsWith(currentDateString, StringComparison.CurrentCulture)) { return false; } } return true; } public static NLog.Logger GetLogger() { if(Logger.thisLogger == null || Logger.NeedsDateRotation()) { Logger.thisLogger = Logger.ConfigureNLog(); } return Logger.thisLogger; } } }
Basically each service will write a log that is rotating based on filesize to the filesystem. The format of the log is
YYYYMMdd.service.log. For example, in context to the philo-media-encoder-consumer service, a sample log file would be named:
20180802.consumer.log. By invoking the following method,
Logger.GetLogger(), we acquire an NLog logging object
in which we can use throughout the program to log into our flat file.
The following shows sample usage:
static NLog.Logger logger = Logger.GetLogger(); void AnActionMethod() { logger.Debug("This will be a debug output!"); try { ... } catch(Exception ex) { logger.Error("This is an error!"); } }
If we inspect the log file, we will get output similar to the following in our YYYYMMdd.service.log file:
2018-08-03 00:03:22.4114|DEBUG|PhiloMediaEncoderProducer.Logger|This will be a debug output!
In summary, for the logging of the services we will mainly need to keep the following in mind for all our services when it comes to logging:
- .log files being written to the file system and ensuring that new log files are created when a certain file size is hit. For example, 4 MB.
- Initializing the logger only once per run and reusing the logger object to write to our log.
- Appropriate log levels set as to not create too much noise during program execution.
- Logs should be created with the expectation that the log files will eventually be uploaded to an external store. In our case, a blob container in Azure Storage.
With the last point above, we need to think about bringing logs together so that we do not have so many laying around in our filesystem within the web services. Additionally, over time, retaining the logs at those locations will become very expensive as they begin to eat away disk space.
In order to solve this issue, we will now need to write a little tool that will actually upload the logs periodically to a
persistent storage account. We can simply use Azure Storage for this and upload our logs to a blob storage container. We will
call this the
LogIngester, and each service will have a sidecar process that will run periodically and upload the remaining
logs within the filesystem up to cloud storage.
For folks who are familiar with
syslog, you can do that too.
Now, what should we do with all the logs? We should aggregate it all into a searchable distrbuted logging system, of course!
Using the ELK stack, we will be able to create a decent log management platform for our services to make maintenance easier.
We can set up a Bitnami ELK Stack VM on
Azure and then configure it to ingest the logs from Azure Storage using the
logstash-input-azureblob plugin found
here.
Given the pattern, we can configure our input filter to be:
input { azureblob { storage_account_name => "[STORAGE_ACCOUNT_NAME]" storage_access_key => "[STORAGE_ACCESS_KEY]" container => "[STORAGE_CONTAINER_NAME]" codec => line } } filter { mutate { gsub => ["message", "\|", " "] } grok { patterns_dir => ["./patterns"] match => ["message", "%{LOGSTRING_DATE:timestamp} %{LOGLEVEL:priority} %{LOGSTRING_SOURCE:source} %{DATA:data}"] } date { match => ["timestamp", "YYYY-MM-dd HH:mm:ss.SSSS"] } } output { elasticsearch { hosts => ["127.0.0.1:9200"] } }
We are also using custom patterns with the above
grok filter, so let us define those within our custom
patterns
directory:
LOGSTRING_DATA [.+?(?=\n)] LOGSTRING_SOURCE [\w]+[\.][\w]+ LOGSTRING_DATE [\d]{4}[-][\d]{2}[-][\d]{2}[\s][\d]{2}[:][\d]{2}[:][\d]{2}[\.][\d]{4}
Now, basically the flow for log management is:
- Logs are transported to Azure Storage from all services.
- A VM on Azure running the ELK stack will then import the logs.
- Elasticsearch will index the logs, making it available on the Kibana dashboard.
- Now, logs are available on Kibana!
Later on, when the services are ready to be tied together, a good thing to do is to leverage a gateway service such as Netflix Zuul to attach a global correlation context ID in each HTTP request within the headers as it passes through each service. Each service can then read the correlation context ID in the header and use that as the ID for the log entry.
The advantage gained here is that now through our distributed log aggregation service that we have set up, we can tie all logs together and create the coherent flow needed to trace actions relating to a specific request in its context.
Key Management
As the number of individual distinct services increase witin our application ecosystem, credential management becomes very important to the overall security of the microservices architecture we have decided to put in place.
To illustrate my point, there are already several services in
philo-media-encoder which requires a reference to the various
cloud services. This results in a lot of sensitive information being stored within the application settings and/or configuration
files floating around. In small projects, having credentials be located within the individual services and maintaining the entries may be doable,
but not scalable. As the number of services grow, it will start to be cumbersome in managing the settings bounded to the application which are
sensitive.
A good use case of having no credential management and experiencing the effects of having to manually update credentials is when something like a database connection string changes. An administrator would ultimately have to ensure that all services which references a particular database have the most up-to-date credentials sitting within the application. Not only is this a poor way to manage the security settings, but also is not very secure in practice. Things can leak and things will leak.
That is why key management is so important. We can have a master key or certificate which can retrieve a specific credential which is then stored in a secure manner remotely. All common credentials to our services are consolidated. This not only gives us a "source" of truth when it comes to secrets retrieval, but also allows greater ease of updating credentials should we invalidate one.
For our video streaming service, I will use Azure Key Vault to store not only the credentials, but some of the other settings that may change over time such as the database names themselves. Now, to be explicitly clear, having a key management store does not fortify an application architecture from all security threats. A key management system's greatest advantage is that it allows a service to invalidate credentials as needed and invalidate the master certificate or key to reach into the values stored in the key management store without having to update all application settings themselves.
The overall flow is detailed below:
- Each application service makes a request with the master credentials, in this case, the Azure Active Directory credentials to Azure Key Vault
- Azure will authenticate and grant access to the vault.
- From here, the application service can retrieve secrets from Key Vault given the secret identifier.
For our .NET service, we will use the Azure Key Vault libraries available on nuget. For our Java service in which I will go over soon, we can use the Java library hosted on MVN:
Monitoring: Availability and Health Checks
It is no doubt that microservices have made monitoring and telemetry such an integral part in having "production-grade" software. When your architecture consists of many moving parts interacting with each other, it is vital that one broken service does not cause a catastrophic failure on the infrastructure. I am sure many of us have been in the situation where one failed external component referenced by many other services within the system has caused a cascading failure within the overall infrastructure. Additionally, those moments might have led to long hours of debugging and traffic management in stopping the bleeding, figuring out the problem, and bringing the service back up. Almost always in hindsight, the root cause is "obvious". Well, sure it is obvious that it had already happened. But, was it really that obvious when we were designing and developing? Most likely not.
Of course, the best advice is to always follow X-practice and do Y-thing to get your service as stable as possible before going live into production. If you cover all your bases during development, then you are certainly going to be industrial strength, right? How do you know, though? There is never a real way to tell until code hits production and has seen some action.
The reality is that there is always going to be something that will cause failure out in nature that was never considered. That is why we should at least plan to be notified, or alerted about issues that happen in production. At least, then a team can catch problems quickly and then fix the issue resulting in a more resilient system. With even some basic monitoring placed in the deployed infrastructure, we can actually get a lot of useful information that allow us to get an overall picture of the health of the overall system.
An example I can give is a feature that might have been very difficult to implement and is a key operational feature to your service. If a change is made and affects the service's reliability should it not behave as intended, it is best to roll-out in phases to catch any corner cases that might have been missed. Of course, the only way to catch corner cases, or even usage patterns that can give us insight as to whether or not a change has affected the service negatively, or positively is to send telemetry and monitor.
The pattern I prefer to do is to implement my feature, and then provide a feature-gate, or flag that leaves it off. However, telemetry calls are sent at various points of execution within the code as to simulate as if the feature was "on". This gives a good sense of the behavior of the system as if the feature was functioning. It gives some data for engineers to look at and improve, or fix the feature as needed before being turned on.
What about KPIs? Business metrics? What about other metrics like user behavior? Yes, I do know those are just as important to actually growing a service. This is a technical discussion, so let's just say we accounted for all the above there, and that if philo ever takes off, it is something we can definitely implement.
Although I am tempted to actually create a super-resilient infrastructure, philo ultimately is still just a demonstration project. I can easily spend many months developing a monitoring infrastructure for philo, but that would be impractical. I want to finish the project eventually, and with that I have decided to just implement some basic monitoring that will just allow me to determine whether or not the system is behaving correctly at a high level.
In order to make the requirements more concrete, listing them out is perhaps better.
The main things philo must have in monitoring will be:
- Availability tests through health check endpoint calls. This will allow me to know if all the services in philo are actually online.
- Event/Exception telemetry at the service level. I will need to know when exceptional exceptions happen right away and be alerted. Other data being recorded such as latency and time to process a job is useful too.
- Alerting through SMS. Email alerting was thought about here, but SMS text-messaging is more likely to be answered. For the sake of my significant other's sleep, I won't be destroying our life with phone calls for a hobby project.
With all that said, we must choose a tool for monitoring our service. The best tool for the job is basically the tool that fulfills our requirements now, and is easy to use so that we don't have to suffer the overhead in learning complex tooling which could result in lack of motivation to implement good monitoring into the system. I am strongly adhering to keeping things simple here, and for that I have decided that the best tool for the job is basically what I have available in front of me now: Azure Application Insights.
Application Insights has a lot of things already built in such as telemetry processing, and availability tests within Azure. Also there are libraries available to use within our service for .NET, Java and even NodeJS. One can do a lot here.
The easiest thing to do for monitoring is to implement an availability check for all your services. A recommended approach is to define some sort of common endpoint in which your monitoring tool can invoke and inspect the response from your service. A method I like to use is the health endpoint check pattern. It is just the following:
- Define a known endpoint exposed to the monitoring service that will be used to check the availability of the service. For example,
/health
- Define criteria of the response of the
/healthendpoint that will determine whether the service is healthy, or not.
Taking the producer service, philo-media-encoder-producer as an example, our
MediaEncoderController is the main controller of our
REST-based microservice that produces the messages to be sent to the service bus so that the consumer class can read that data and invoke the encoding job.
In order to determine whether, or not the producer class is online and is ready to accept requests, let's define a simple default
HTTP GET handler
to this controller to serve as a health check.
/* *.IdentityModel.Clients.ActiveDirectory; using Microsoft.Azure.KeyVault; namespace PhiloMediaEncoderProducer.Controllers { [Route("api/mediaencoder")] [ApiController] public class MediaEncoderController : ControllerBase { private NLog.Logger logger = Logger.GetLogger(); private static async Task
GetAccessToken(string authority, string resource, string scope) { // ... Logic initializing the appropriate credentials to access Azure resources. } [HttpGet] public string Get() { logger.Debug("HEALTH OK."); return "HEALTH OK"; } [HttpPost] public async Task Post([FromBody] Object value) { // ... Logic dealing with invoking the sending of the message to the service bus to invoke the consumer encoding job. } } }
Now, with the call to the
GET /mediaencoder endpoint, we will be expecting the following to determine that the
philo-media-encoder-producer service is online and healthy:
- HTTP status code 200 is returned.
- The page returns the content:
HEALTH OK
Let's define that test in Application Insights:
Once that test has been created, the test will be invoked regularly to determine the health of the service. This isn't a tutorial on how to use Application Insights, but explore around your tooling to see what alerts you can send when the health of your application degrades, such as downtime for more than 10 minutes, etc.
Since that was easy, we can implement the basic availability health checks on all our current services. :)
If an application begins to experience downtime, the availability health check will then trigger an alert. For example, the philo-media-encoder-producer availability test will send an email notifying me that there has been a number of failed requests. Notice that the reason for the failures is also attached within the email.
Once your service is stable again, the health check will automatically detect the changes after a number of tests have passed:
Monitoring: Events and Telemetry
Assuming we have set up Application Insights to be connected to our service, we can use the Microsoft.ApplicationInights library to begin sending telemetry events from our application to the telemetry service.
Using the API is pretty simple. There is an initial set up involved where we must first configure our .NET Core application to use
Application Insights. This is just an invocation of
services.AddApplicationInsightsTelemetry to register the configuration
into the application. Your telemetry key can be stored in either a configuration file, where you can parse later, or be stored in an
environment varaible.
Keep in mind though that your telemetry key must be valid for the library to work. I have seen instances where an invalid key, or no key at all prevents the application from starting properly.
Here is how the producer service registers the telemetry service to begin sending telemetry events. I have omitted a lot of other code in order to keep the focus on the registration of the telemetry service:
using System.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.ApplicationInsights; using PhiloMediaEncoderKeyVault; namespace PhiloMediaEncoderProducer { public class Startup { private TelemetryClient telemetry = new TelemetryClient(); public static string ApplicationInsightsInstrumentationKey; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // ... // Initialize all configuration here. // ... System.Environment.SetEnvironmentVariable("ApplicationInsightsInstrumentationKey", config["ApplicationInsightsInstrumentationKey"]); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddApplicationInsightsTelemetry(System.Environment.GetEnvironmentVariable("ApplicationInsightsInstrumentation(); app.UseMvc(); telemetry.TrackEvent("PhiloMediaEncoderProducer.Startup", new Dictionary
() { { "Message", "Successfully started the application." } });} } }
After our producer service knows where to send telmetry to, it can then send events and exceptions with a telemetry client. By creating a
TelemetryClient object, we can invoke methods such as
TrackEvent to send the events up to Azure.
/* *.ApplicationInsights; using PhiloMediaEncoderKeyVault; namespace PhiloMediaEncoderProducer.Controllers { [Route("api/mediaencoder")] [ApiController] public class MediaEncoderController : ControllerBase { private NLog.Logger logger = Logger.GetLogger(); private TelemetryClient telemetry = new TelemetryClient(); [HttpGet] public string Get() { logger.Debug("HEALTH OK."); return "HEALTH OK"; } [HttpPost] public async Task
Post([FromBody] Object value) { String requestBody = Newtonsoft.Json.JsonConvert.SerializeObject(value); // Send telemetry event noting that an API call to invoke a message to encode media telemetry.TrackEvent("PhiloMediaEncoderProducer.MediaEncoder", new Dictionary () { { "HttpMethod", "POST" }, { "RequestBody", requestBody }, { "DateTime", DateTime.Now.ToLongDateString() } });// ... // Logic to send the message to the service bus here. // ... } } }
The examples below depicts what our custom events and exceptions look like on Azure. We can see that we are able to send a good amount of information to our telemetry service so that we can track errors, behavior and other interesting events that can allow us get a better idea on how users use the application.
Speaking of which... how do we know what to track? In all the literature I have read, the best advice I have been able to comprehend has been to begin tracking telemetry from the user perspective. In fact, when it comes to microservices, tracking hardware resource usage such as CPU and memory consumption is not as useful as invocation which produce and consume messages along with the flow and error rates.
Think about tracking things such as:
- Application status: starting, started, caches warmed up, or ready to receive requests.
- Authentication events: Who, when and where has access to the key management vault been made?
- Latency of important methods which produces or consume messages. For example, for our producer service, it is good to track the entry point of the request that will lead to sending of the message to the service bus along with the latency before sending the OK response to the user.
- Did the method invocation fail, or was it successful? What was the total time to completion? What was the time taken for any remote API calls?
- Any exceptions resulting in operations that can be invoked by the user with any detail that can help with debugging. Just remember not to store any personal identifiable information.
To add to the last point above regarding exception tracking, it can be helpful to include a correlation ID, or some unique GUID for each service request that can be tagged to each event to allow faster tracing and matching of an exception to a particular past action. In fact, Application Insights already provides features like that built out of the box. But, if your telemetry service does not do that, you can implement it by just adding a property to your event and including the value within your exception should one occur.
If tracking from the front-end application, the most important thing is to always track how fast your page loads. I am not going to try an persuade you on why having a faster page load time will bring better user experience or business, as there are already many case studies detailing that, but just trust me.
Use as many API calls available by the browser as available to send as much useful data as possible. The Navigation Timing API implemented by most browsers can be handy.
Sending telemetry from the back-end, probably in the overall system, tends to be more "wild-west" like. Especially in the context of a distributed system, distributed tracing must be implemented if your tooling doesn't provide it. Additionally, monitoring from the back-end presents a few more interesting metrics which can be generated by the data that is sent. With more data, we need to be able to be smart about how much to send and how to measure, and make sense of it. Brushing up on some basic statistics here, some of the questions to ask can be "should I apply an average here?", "how useful would means and medians be here? would percentiles be a better metric?", etc.
Monitoring is hard. Although philo has some monitoring built-in, the philosophy of monitoring should be to:
- Never leave monitoring as an after-thought. Start thinking about your metrics (health, performance, business, etc) early and as you are developing, bake them in.
- Continually improve your monitoring code. It really does take a while to get comfortable with the tooling and figuring out what really to measure. Just keep a mindset of changing what to send for better data and be open to throwing data away which is not useful.
One final note before I leave this section. I am lucky that philo does not really care about user identifiable information right now. Should your service start to use personal identifiable information (PII), that is, any information belonging to a user which can lead back to the user if leaked, be very careful about sending it. In fact, don't send it at all. The best practice is to anonymize any PII by scrubbing, or hashing the values so that the values stay consistent across telemetry events, but cannot be traced back to the user. I cannot stress how important it is to perform this as a practice. It isn't "best practice" in my opinion, it is the practice.
Service: philo-media-service
At some point, we need to have a way for any clients to actually retrieve all the video content information that gets generated by the philo-media-encoder backend. Conveniently, we have designed the consumer service so that it not only manages the instantiation of the encoder service, but also makes use of any meta-data returned during the encoding process.
The data that is returned by the encoder service is pretty handy. It includes:
- The output asset information such as the output asset name generated by the encoder service, the job name used by Azure Media Service, the streaming locator name and the asset ID.
- The appropriate streaming URLs in which our client media player can reference in order to begin delivering the content to the end-user.
As you might have guessed, we will need a service to handle this information and store it within a database. This service must also be capable of delivering this data via an API call through a HTTP REST request which can be leveraged by the client side. In this context, the client side will be some sort of web application in the form of a very humble Netflix.
This service is what I will call: philo-media-service. It is the service that interfaces the front end code and the back end encoding service and makes the overall user experience coherent. The service is dual purpose in that it writes metadata information and sends it out per request as a content service.
The technology stack I have chosen to implement this is relatively lean:
- Java 8 with Spring Boot - I wanted to learn more about the Java ecosystem. I figured Spring Boot is a good way to start in learning how to code modern Java services.
- Containerized deployments with Docker - Containers are hot right now and I do not have much experience with creating images and deploying them to the cloud.
- Hosting open source technology on Azure. Linux? Java? Docker? Is this all possible on Azure? Why, YES!
Not everything we have chosen will be "latest and greatest" in practice. Since philo-media-service needs a persistent data store to store the content metadata, I have decided to stick with a low-maintenance database technology: SQL. Using Azure SQL backed by Microsoft SQL Server serves our needs perfectly. My reasoning for actually choosing SQL is simply due to the low cost in getting everything up and running. JDBC at this point, is very mature and the MSSQL drivers provided by Microsoft are very good. Additionally, we can always solve any performance issues in the future should they arise as there are many, many resources out there that deal with web application performance in the context of having a SQL data store being the persistent data store.
My strongest defense in using a SQL store is ultimately this: Our data must be stable and is essentially the catalog of all the videos that will exist in our video streaming service. It is much easier to handle this structured data relationally rather than using something along the lines of a NoSQL store.
Now finally, when it comes to data transport between requests and response, normally supporting multiple content types allows for a robust interface. I have decided to
forfeit that here for the sake of simplicity. After all, you do want me to actually finish this project, right? :) For that, I have just decided to use JSON as the content
type for both request response payloads. That is
application/json for all you HTTP nuts out there.
All this and I must remember one thing: philo-media-service cannot do too much. The above requirements in which I listed will be all the functionality that will exist within the service. The temptation is to build more and more onto the service, and that is bad. Keeping our applications as small as possible within a bounded context to solve a business requirement is the goal to making maintainable services that can be pushed to production quickly.
So here is how philo-media-service fits in with the overall system architecture. There is a lot going on here, but it will just basically interact with a few components.
- Azure SQL DB - For persistent data storage.
- Azure Key Vault - For credential management, of course.
- philo-media-encoder-consumer - To receive data to record into the database.
- Azure Application Insights - Monitoring and telemetry.
- ELK stack VM on Azure - Logging and parsing.
Alright, let's implement!
Usually, the first thing I like to do when designing a service which refers to any sort of RDB, is to just design the database schema first. I will not break from my personal pattern here and will quickly discuss what our philo-media-service database can look like.
The database is small. It just has 3 tables: MediaEncoderInput, MediaEncoderOutput, and MediaEncoderOutputStreamUrl. A brief overview of the purpose of each are detailed:
- MediaEncoderInput
- This is the table that will store the registered input assets available within our system. The structure just holds the title of the video and the CDN/storage location endpoint in which to find the media asset file. This is basically an entry within the catalog which lets the encoder service know whether or not a new collection of adaptive streaming assets should be created, or not.
- The reasoning behind this is if a user inputs the AssetName and AssetLocation which already exists within the media encoder input, we can then skip the encoding process. Otherwise, send the job to the service bus.
- The philo-media-encoder-consumer service is in charge of writing data to this input when it consumes a message from the Azure Service Bus. It will make a HTTP REST invocation with a JSON payload to philo-media-service to write to the database.
- MediaEncoderOutput
- Media that is sent to be encoded to the philo-media-encoder service will output metadata information relating to the resources that are created by Azure Media Service. In order to organize and structure this data, we need to have a table that will house this information and have it relate back to the original input.
- This table is a one-to-many relationship with the MediaEncoderInput entry. Although in our implementation, the service is only creating one output asset (the logical grouping of videos of various bitrates) associated with the input, I have left it extensible to create many output assets attached to the input.
- When the Azure Media Services metadata is returned by the philo-media-encoder service, philo-media-encoder-consumer will invoke an HTTP REST call
- MediaEncoderOutputStreamUrl
- This table is likely to be the most relatable, and interesting one for many users. The content within this table consists of all the streaming URLs which are generated by Azure Media Service. A reference will be needed by the web user interface to be able to load the video content. The URL is the source in which to obtain the video.
- Within the implementation of our service, there will be 3 output streaming URLs generated for every output asset. We are interested in using the most general one in the format of:
Knowing all this, we can then make a simple query such as the following to obtain the output stream URLs for every input:
select i.id InputId, o.id OutputId, o.ContainerName, i.AssetName Title, u.Url from MediaEncoderInput i inner join MediaEncoderOutput o on o.InputId = i.Id left outer join MediaEncoderOutputStreamUrl u on u.OutputId = o.Id
A sample output from the above query will return the following table:
InputId OutputId ContainerName Title Url...
We can then have philo-media-service shape the above information into a JSON payload as a response to any content queries.
Implementing the service itself was quite interesting. It was an experience because I had never created any Spring Boot Application before and actually packaged a Docker image from scratch for deployment into a private container registry. In addition to the lack of experience of the previously mentioned, my Java skills had become quite outdated over the past couple of years. I had last worked closely with Java 6 and to a certain degree, Java 7. So going to Java 8, which in retrospect is no longer considered "modern" Java, brought some learning curve.
I followed a simple tutorial to bootstrap myself into a Spring Boot project. The tutorial was very straightforward as it was in the context of building a REST API from scratch. This was perfectly suited for my needs.
In addition to the above tutorial, the following documentation was also very handy for building a Docker image out of my Java service and deploying it out to the private Azure container registry:
- Spring Boot with Docker
- This guided me into building a Docker image for the Spring Boot application.
- Microsoft: Use a custom Docker image for Web App for Containers
- The key tutorial in building a Docker image to push to a private Azure container registry and finally creating a Web Application Service to host it.
Let me first present the first part of philo-media-service -- which is the writing of metadata that is returned by the encoding service as the output asset is being processed and converted into streaming URLs.
We will have one simple REST controller to handle all this called
MediaController within our project. To keep things very small, we will map a specific POST endpoint
to a table. The endpoints are:
POST /input
- This will take in a request body of
application/jsonin the following format:
{ "name": "AssetName", "location": "AssetLocation" }
- The data is simply written to the MediaEncoderInput table. The response is the ID which is associated with the newly created entry in the MediaEncoderInput table.
{ "status": "200", "message": "OK", "result": "45" }
POST /output
- This will take in a request body of
application/jsonin the following format:
{ "assetName": "AssetName", "assetId": "Azure Media Services asset ID", "jobName": "Azure Media Services job name", "containerName": "Azure storage blob container name which the files associated with the output asset are stored", "locatorName": "The associated streaming locator name", "inputId": "The MediaEncoderInput ID" }
- This data is written to the MediaEncoderOutput table after the encoder service has finished processing the output assets. The response is the output ID which is associated with the newly created entry in the MediaEncoderOutput table.
{ "status": "200", "message": "OK", "result": "32" }
POST /url
- This will take in a request body of
application/jsonin the following format:
{ "outputId": "The MediaEncoderOutput ID", "url": "The streaming endpoint referencing the output asset to be used by the Azure Media Player" }
- This data is written to the MediaEncoderOutputStreamUrl table after the encoder service has generated the streaming URLs from Azure Media Service. These URLs will be the
srcURLs used by the Azure Media Player on the client side. The response is the ID which is associated with the newly created entry in the MediaEncoderOutputStreamUrl table.
{ "status": "200", "message": "OK", "result": "5" }
All of this is implemented in one small controller similar to the following:
package philomediaservice; import java.sql.*; import java.util.HashMap; import java.util.Map; import com.microsoft.applicationinsights.TelemetryClient; import org.springframework.web.bind.annotation.*; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @RestController public class MediaController { private String connectionString; private TelemetryClient telemetry; public MediaController() { this.connectionString = (new philomediaservice.ConnectionStringManager()).getConnectionString(); this.telemetry = philomediaservice.TelemetryClientHelper.getClient(); } @RequestMapping(value="/input", method = RequestMethod.POST, consumes = "application/json", produces = "application/json") public String input(@RequestBody Map<String, String> payload) { int resultId = 0; try(Connection connection = DriverManager.getConnection(this.connectionString)) { String assetName = payload.get("name"); String assetLocation = payload.get("location"); String insertStatement = "INSERT INTO MediaEncoderInput (AssetName, AssetLocation) VALUES (?, ?);"; try(PreparedStatement statement = connection.prepareStatement(insertStatement, Statement.RETURN_GENERATED_KEYS) ) { statement.setString(1, assetName); statement.setString(2, assetLocation); statement.executeUpdate(); ResultSet r = statement.getGeneratedKeys(); if(r.next()) { resultId = r.getInt(1); } } catch(Exception e) { this.telemetry.trackException(e); throw e; } } catch(Exception e) { this.telemetry.trackException(e); } HashMap<String, String> response = new HashMap<>(); response.put("status", "200"); response.put("message", "OK"); response.put("result", Integer.toString(resultId)); ObjectMapper mapper = new ObjectMapper(); String responseData; try { responseData = mapper.writeValueAsString(response); } catch(JsonProcessingException ex) { responseData = "{ \"status\": \"500\", \"message\": \"Error\"}"; } return responseData; } @RequestMapping(value="/output", method = RequestMethod.POST, consumes = "application/json", produces = "application/json") public String output(@RequestBody Map<String, String> payload) { // ... Implementation similar to /input } @RequestMapping(value = "/url", method = RequestMethod.POST, consumes = "application/json", produces = "application/json") public String urls(@RequestBody Map<String, String> payload) { // ... Implementation similar to /input } }
The ContentController implementation is a basic REST API that exposes a single endpoint called
GET /content that will output
the metadata needed to properly render a user interface to the user so that they can begin their video streaming experience.
A sample output is shown below.
{ "asset-3323d45a-2789-4ff4-ab5e-df961427735a": { "title": "Caminandes 1 - Llama Drama", "containerName": "asset-3323d45a-2789-4ff4-ab5e-df961427735a", "thumbnail": "", "urls": [ "", "", "" ] } }
I am not going to show the implementation of the ContentService here, but it is fairly straightforward in that it is transformation of the results returned
by the SQL query which I had previously shown. The JSON response returned by the content service call pretty much outputs exactly what would
be returned by the SQL statement, with the exception of 1 attribute, the
thumbnail attribute. For now, our encoder service by default, produces
a JPG file called
Thumbnail000001.jpg, which by finding out through the Azure documentation, is the first interesting thumbnail of the video.
The thumbnail automatically gets created during the encoding process and is included with all the other files within the output asset.
I will go on ahead and say that the portion to generate the thumbnail is hardcoded for now. It suits our needs and we will actually be enhancing it later on to in our A/B experiment section.
response.get(containerName).thumbnail = this.cdnEndpoint + "/" + containerName + "/Thumbnail000001.jpg";
philo-config-service
There is one more service which needs to be implemented... It is a small one -- a configuration service in which
philo-media-service will pull its
configuration data from. To create such a service, I followed this tutorial, and autowired a
ConfigStore object to the philo-media-service code.
I highly suggest researching on the centralized configuration patterns practiced by many microservice implementers. :) At this time, I am not going to go too much in-depth into this, but basically the motivation is the same as I have taken the time to implement key management. Centralized configuration is needed to ensure that all instances of our applications are ephemeral, and configuration changes happening should affect all instances -- thus reducing temptation to make "one-off" configuration changes to a specific instance and forgetting to set it back during for example, an incident mitigation session.
User interface
Now that the services are up and running, there must be some way in which users are allowed to use the philo service in an end-to-end manner. The first challenge is to create an experience where users are allowed to invoke the encoder service to produce streamable videos. The second task is then to create another experience where users can consume these encoded videos through streaming. Both are wildly different experiences, but they basically make a call to philo-media-encoder-producer and philo-media-service respectively.
Since our web applications are quite simple, we can get away with just a static webpage. create-react-app allows easy bootstrapping of React projects with just literally, a single command.
philo-admin
To begin, I will discuss the user experience in which videos are needed to be encoded. Going back to the original specification, philo-media-encoder-producer really takes 2 parameters: the asset name and the asset location. Therefore, a simple user interface can be created using HTML5 and JavaScript, and explicitly, the UI will be composed of React JSX elements.
A picture is worth a thousand words, so here is what it looks like:
Anyway, all this is quite simple. The Submit button will make an HTTP POST
fetch() call to the
philo-media-encoder-producer service,
sending the JSON data to place into the service bus. From here, the familiar flow follows. The asynchronous HTTP POST method is shown below. Note, that this code is
bare-bones and has very basic error-handling. Also notice that we have taken advantage of the Promise object returned by fetch to handle the HTTP response accordingly.
fetch('', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ assetName: mediaTitle, assetLocation: mediaLocation } )}).then((response) => { if(response.status === 200) { alert('Your job has been submitted!'); } else { alert('Something went wrong!'); } button.removeAttribute('disabled'); }).catch((e) => { alert('Something went wrong!'); button.removeAttribute('disabled'); }); }
philo-theater
Next, let us discuss the user interface on the other side, where the client is consuming the video by watching a stream! This component is called
philo theater, and aims to be a "Netflix-lite". It makes use of the
philo-media-service by calling the
GET /content endpoint to
retrieve the list of available video titles processed through the encoding service along with the default thumbnail and streaming URLs. As you may recall,
this data is stored in a SQL database that is queried by the media service.
Since this is a major client application, it would be best to make sure we have the scope of work defined clearly. Here are some basic requirements to create a decent streaming experience:
- When there are no movies to be streamed, the application should display a splash screen notifying the user that there are not yet any movies to be streamed.
- When there are movies to be streamed, the following should show:
- A list of movies should be shown in an aesthetically. Thumbnails and titles are clearly marked, allowing the user to click on the title in which they want to view.
- A nice and large media player that contains user interface controls to: play, pause, adjust volume, choose the appropriate bitrate, and move back and forth across the timeline.
- The ability to resume watching video from anywhere based on the video.
- Consideration of sending telemetry events to get a better understanding of user-behavior, performance, and exceptions in which may occur during the viewing experience.
With all these requirements defined, the hard part is likely to be findng the appropriate media player. Generally, there are two approaches to this. First, we can roll our own media player to suit our needs. This is likely to to be inappropriate as we must be able to have our media player understand the specific streaming URL format in which Azure Media Service generates. We can spend some time to understand and implement, but it is much more resourceful to find something which already exists. Fortunately, Azure Media Services actually offer a built-in video player which natively supports HTML5 and JavaScript. It is available here: Azure Media Player
With the given examples, implementing the video player is trivial for plain JavaScript. However, our front-end application is a React-based front-end and thus there is a bit of work involved in porting the video over to the client application.
First to note, the Azure Media Player, or AMP, loads asynchronously. To make the video player first available, we must include the script within our HTML document.
<link href="//amp.azure.net/libs/amp/2.1.9/skins/amp-default/azuremediaplayer.min.css" rel="stylesheet"> <script src= "//amp.azure.net/libs/amp/2.1.9/azuremediaplayer.min.js"></script>
After some time, the
window.amp object will contain the AMP object which can then create the video player to be loaded onto the HTML document. Since this loading
is done asynchronously, we must take care in that our React component which houses the AMP may not be initialized yet by the time we would like to use it. Therefore we must implement
a loading routine that will safely ensure that the AMP component is properly initialized before the rest of the page is rendered.
The best way to probably solve this problem is to wrap the initalization of the AMP component within a
Promise object. Within the promise, we define a timeout that is
recursively executed for a set amount of times. The timeout should be a small number of milliseconds, as it is not expected that the AMP component should need that much time to initialize.
Writing a
waitDelay timeout function wrapped by a Promise is the implementatio I have decided to commit to.
I have chosen a timeout at 100 ms running for 10 iterations total. The maximum amount of time this asynchronous code can then
run would be about 1 second. From here, if the player is initialized by inspecting the
window.amp property, we can either
resolve the Promise object with the AMP component passed in, or reject the promise
to avoid any unnecessary waiting should the AMP component not be initialized in time. It is best to fail fast in this scenario.
waitForAmpInitialization() { return new Promise((resolve, reject) => { const waitDelay = (currInterval) => { setTimeout(() => { currInterval++; const amp = window.amp; if(amp !== undefined) { return resolve(amp); } else if(currInterval > 10) { return reject(); } waitDelay(currInterval); return null; }, 100); }; waitDelay(0); }); }
From here, we just make an instance variable
videoPlayer available, and resolve the promise in our React rendering lifecycle. Conveniently,
using
componentDidMount is exactly what we need!
componentDidMount() { this.waitForAmpInitialization().then((amp) => { // Per AMP documentation, initialize amp to contain all settings you want. this.videoPlayer = this.createVideoPlayer(amp); // ... // All other interesting operations can go here. // ... }).catch(() => { // log error here }); }
The
createVideoPlayer method essentially configures the AMP component, and returns the initialized AMP. Follow the Azure Media Player documentation
for some of the settings that can be used to tailor AMP to your needs.
createVideoPlayer = (amp) => { const video = amp(this.videoRef, { autoplay: false, controls: true, width: "98%", height: "720px", logo: { enabled: false }, techOrder: [ 'azureHtml5JS', 'html5FairPlayHLS', 'html5', 'flashSS' ], poster: this.state.currMovie.thumbnail }); return video; }
Now that the video player initialization issue is solved, our theater application now must be able to fetch the content from the
philo-media-service API.
The splash screen should display when we fetch the content from philo-media-service and there is no data. This splash screen should also show when all videos are deleted and dynamically refreshes through a polling mechanism.
Creating the JSX element is trivial:
renderNoMoviesView() { return ( <div className='philo-theater_no-movies-view'> <h1>philo theater</h1> <h3>No movies yet.</h3> <p> Come back later to see what's showing! :) </p> <div className='philo-theater_attribution'> (C) 2018 Roger Ngo, <a href="">rogerngo.com</a> </div> </div> ); }
When there are videos available to be streamed, the reel (top component) will show the available videos which can be streamed along with a default thumbnail. Just like how the splash screen disappears through polling of content, the same mechanism is used to update the list of videos.
There are a few variables in which we must keep track of here to maintain the state.
- The list of movies
- The current movie that should be displayed
- Whether or not there is a movie that is currently playing
The current movie in itself has a few properties that our application needs to be aware of: the title, thumbnail and streaming endpoint. All this is required to properly initialize the media player and render the content.
The constructor initializes them to be default values of:
this.state = { movies: [], currMovie: { title: null, thumbnail: null, endpoint: null }, isPlaying: false };
The list of movies can be fetched with an API call to philo-media-service. With
GET /content, the JSON payload that is received is parsed and
then loaded into the
movies property in the state like so:
getContent() { const jsxElements = []; return fetch(`${PhiloMediaServiceEndpoint}/content`, { type: 'GET', }).then((response) => { return response.json(); }).then((json) => { let firstMovie = null; for(let currContainerKey in json) { const currElement = json[currContainerKey]; if(firstMovie === null) { firstMovie = currElement; } jsxElements.push( <div className='movie-item' onClick={this.playMovie.bind(this)} data-video-location={currElement.urls[2]} data-video-title={currElement.title} data-video-thumbnail={currElement.thumbnail} > <div className='movie-thumbnail'> <img src={currElement.thumbnail} /> <h4>{currElement.title}</h4> </div> </div> ); } if(jsxElements.length === 0) { // reset the state to empty values } else { // update the state with the new movies } }); }
The code is truncated due to the verbosity and JavaScript can be really hard to understand in large chunks, so I have only included the relevant pieces. Basically, we make a GET request. Our response is then expected to be a JSON. From here, we parse the JSON as a JavaScript object. The JSON object is an array of all the movie metadata data information.
As the routine iterates through the JSON array, JSX elements are created with the current element in the iteration. Basically the JSX element includes:
- The click handler which contains logic to update the media player with the new video of interest.
- The streaming URL of the movie as a
dataattribute value.
- The title of the movie as a
dataattribute value.
- The thumbnail file of the movie as a
dataattribute value.
renderDefaultView() { return ( <div> <div className='reel'> {this.state.movies} </div> <div className='theater-header'> <h1>philo theater</h1> <h3>{this.state.currMovie.title}</h3> </div> <div className={`video-container`}> <video className="azuremediaplayer amp-default-skin amp-big-play-centered" id='philo-movie' ref={(input) => { this.videoRef = input; }} /> </div> <div className='philo-theater_attribution'> (C) 2018 Roger Ngo, <a href="">rogerngo.com</a> </div> </div> ); }
That is pretty much it for the basics of what our theater should do. The rest of the functions such as updating the video list, updating the player to contain the current movie can all be referenced in the source code itself.
Telemetry
The player should also have the basic telemetry set up to gather useful data. A suggestion in some things we should send telemetry whenever:
- A user clicks on a new video to watch. Which are the most popular videos?
- If a user is currently playing a video, and has clicked on a new video, where did the previous video leave off at?
- A user pauses a video, when in the timespan did this occur?
- Whenever a video bitrate changes. This can gather pretty good data on the most frequent bitrate accessed.
I am purposely keeping the list small for the sake of reducing the scope of this project, but it is definitely an exercise worth exploring to think of other creative telemetry one can send from the front-end. One should also explore sending telemetry for performance and exception tracking.
The approach to tracking telemetry is to initialize the Application Insights SDK for JavaScript, and attach an event handler for specific Azure Media Player
events such as the
play event and send the telemetry. One can find the list of interesting events which can be handled here: Azure Media Player events.
For example, to send telemetry of the current movie title along with the streaming URL, we
can attach the event handler to the
play event.
this.videoPlayer.on('play', () => { appInsights.trackEvent("PhiloTheater.StartPlay", { title: this.state.currMovie.title, streamingUrl: this.state.currMovie.endpoint }); });
On Application Insights, the event can then be seen:
From here, it is really dependent on your creative juices to flow to make sense of the telemetry data. :) Application Insights provides a set of good reporting options to aggregate telemetry data and shape it to useful information that can aid in progressing design, development and the overall business direction.
There is a reason why I discussed event handling and telemetry before this last piece... allowing resuming of videos at a later times! Knowing the information in that
we can get various events such as
play,
pause, and
start, we can call to the
currentTime method made available and
retrieve the curren timespan of the video. With the information we have stored within the current playing video, we can cache this information either at the service level,
or at the client with the following example message:
{ currTitle: 'The Current Title', streamUrl: '', time: 'videoPlayer.currentTime() call', ... other useful data. }
After sending this information, it all becomes a basic exercise of mapping the video back to the client and programmatically seeking the video to the appropriate timespan upon load.
Architecture Map
Finally, we have implemented everything we need to create an end-to-end experience. Here is the architecture map for review:
The main entry points for the actors, in this case the users are colored in green. This is
philo-admin, and
philo-theater.
All Azure services are colored blue, while services implemented to leverage Azure services are gray for the
philo-media-encoder related services and yellow for the
philo-media-service related services.
Demo and Performance
I believe the best way to demo is actually perform some show-and-tell. :) Here is a video of the end-to-end flow on what philo can do.
A few important aspects related to performance and throughput of the encoding process:
- It is important to remember that the philo-media-encoder service does not do the encoding job itself, it is actually the Azure Media Services encoder which performs all the hard work.
- To leverage this, it was intentional to keep philo-encoder and philo-media-encoder-consumer separate as the consumer service is decoupled and can spawn as many encoder tasks as needed.
- philo-media-encoder can then make as many calls as needed to Azure Media Services to encode many videos at once. It is not only limited to 1 job, but multiple as the offering of Azure Media Services permits.
- The deliberate attempt to ensure that all potentially long-running operations are kept asynchronous as possible. The .NET
async/awaitkeywords helped a lot along with the service bus used to have the produce/consumer communicate with each other.
- I leveraged
philo-media-servicea lot. Keeping each API method call as small as possible was the best thing to do. The fact that I've left this implementation as a point-to-point call also made this a potential performance bottleneck in the overall system.
- The above might not be as bad as it seems through. Should performance due to load become an issue, we can create more instances for the database and service itself. We can also practice database optimization techniques such as adding an in-memory cache such as
memcachedand database indexes.
A/B Testing
This section is intentionally short due myself wanting to keep this article to a reasonable length. If you want to read up more on experimentation and how to achieve it at a technical level, check out my other post on A/B Client Testing with Chatbots.
The advantages of having an easy deployment strategy for your services enables A/B testing to be quite pleasant. Armed with small services, and a good strategy for recording telemetry events, we can code our application to be fronted with a gateway service for routing requests to experimental instances.
Remember the hard-coded thumbnail image we had? Well, an easy way to convey the example of A/B testing is if we had another instance of
philo-media-service in which we have deployed to display a different
thumbnail for a particular video. We could choose a client and have our gateway service inject a special header value within a request to signify that the request should be experimental, and thus display a different
thumbnail back to the user.
Having a good framework for sending telemetry helps here as data can be passed back and forth to gather events and metrics to determine how your experiment is running.
When the experiment is over, the service which held that experimental code can easily be killed, and all requests can be routed back to the stable service.
Cost Discussion
I can imagine some of you might be asking after reading and going through all this is, "Dude, how much did this all cost? Your Microsoft Azure bill must have been insane!"
I can't lie and tell you it it wasn't that bad. I'll tell you the truth. It was bad.
It was quite expensive to play around with all these services when all said and done. During my first month, I was mostly trying to learn how the services worked by making API calls, and testing out the encoding services locally on my machine. I also did not care too much for cost as I just wanted to get the project implemented as quickly as possible during its early stages. Thus, when it came to making sure my instances were shut down and my streaming endpoints were off when I needed them to be, I didn't care.
Unfortunately, after seeing the bill for the first month, it came out to be a little over $619.
At this point, for the sake of science, I wondered what would happen if I just left things the way they were, and just kept developing philo without being too concerned for cost? How much more would the bill be, and would it be practical for any sane person to make a streaming service on their own as a hobby project just for fun?
I let it be.
So for the second month, which has not ended yet, the estimate is going to be a little over $1,000.
YIKES!
The most expensive part of the bill through cost analysis has simply been running Azure Media Services through encoding and streaming the media itself. I was doing a lot of dev and test on with these services, and honestly, I didn't need to run them as often as I needed to. In total, I kicked off 82 encoding jobs. Each of these jobs had varying service levelsa of S1 and S3 encoding resources. It was entirely dependent on how fast I wanted my media encoded at that time and testing and proving a lot of concepts.
Fun thing I found out which I really appreciate... although the S3 service was costly, it was extremely fast to encode a Full-HD 1080p video. A 23 minute video only took about 4 minutes to encode!
The service overall is AWESOME, and very intuitive to use... however, the practicality only exists if you are serious about starting some sort of video delivery service yourself... whether it be a live-streaming service, or on-demand. It really is nice to know that one can literally create the next YouTube, or Netflix with just an ancient 2014 MacBook Pro with the power of the cloud. (Yes, I know I just said that.)
This project overall was very expensive to develop, but the amount of knowledge I gained from learning offsets any of the financial costs. All I lost was a few video games, nice meals, and overdue haircuts wearing the same t-shirts and jeans once in a while. My significant other also freaked out about my constant spending on these services, but she was quite understanding in that it was all for education. ^_^
Would I do something like this again? Probably not for a while. It did release a lot of curiosities out of system, and it was very relaxing and pleasurable to solve some of the problems I had encountered while developing this application. I also become more "zen" with the cloud. All of it was worth it.
So, how would I make this cheaper to run? Surely, there must be a way to do just that, right? Well, yes!
A few things I thought about while working on figuring out what I should do shave down the costs:
- Allow the services instances to shutdown after a period in being idle. In Azure, you can do this with Web Apps with the "Always On" toggle in the configuration settings.
- I had intentionally left some of my instances "always-on" for experimental purposes.
- Choose a lower offering for application instances, and configure autoscaling to scale horizontally.
- Hit the datastores less and use in-memory cache to reduce the number of query operations.
- The
philo-media-encodercode will blindly encode all jobs. This means that if you submit duplicate videos to process, each video will be considered a unique job.
- Save some money! Have the consumer code detect whether or not a re-encode is actually needed!
- Detect whether or not your streaming endpoint is idle or not. Shut it off when it is and turn it back on in an on-demand fashion!
- Cache things as much as possible!
Conclusion.
Phew, well that was quite the long post! I know there are a lot of unanswered questions regarding the functionality, and work needed to create a stable and resilient architecture. I can do everything, and perform all the "best practices" in creating an application based off of microservices, however that will take much more time and resources which quite frankly, most of us do not have. So, I encourage YOU, yes, YOU! If you have time and are interested in building off of this project even further, here are a few things that would be nice to implement as practice, a learning experience, or get rid of that irk in the code that I have done wrong:
- Implement circuit-breaker technology along with fallback mechanisms for any remote API calls. This is pretty much any call to any other service -- whether it be philo, or Azure related.
- Implement best practices for security in each service. For example, no other instance should make contact to
philo-media-serviceaside from the
philo-media-encoder-consumerand
philo-theaterservices themselves.
- Implement a gateway service, or a reverse proxy to handle policies, security, canary testing, etc. Have it be a single point of entry for most API calls.
- Encrypt all configuration data that is returned by phill-config-service, and ingested through properties settings.
- Implement a better logging system. Configure your ELK stack, or any other log-indexing service to handle the logs for all these services.
- Actually use all the telemetry data that is sent. How can we use it to not only detect service health and readiness, but also log metrics related to business-performance?
- Implement a CI/CD pipeline for all this!
- Disclaimer: I have never personally done this myself, but I have used Jenkins and Travis CI is pretty good. If you prefer something like Microsoft, try Visual Studio Online. It has gotten pretty good over the months.
- Save some money! Make the consumer code smarter by detecting whether or not the video has already been processed once before! Exit early and don't kick off a job when there is already a streaming asset. | http://rogerngo.com/article/20180730_philo/ | CC-MAIN-2020-24 | refinedweb | 13,672 | 53.71 |
#include <qrtlcodec.h>
Inherits QTextCodec.
Hebrew as a semitic language is written from right to left. Because older computer systems couldn't handle reordering a string so that the first letter appears on the right, many older documents were encoded in visual order, so that the first letter of a line is the rightmost one in the string.
In contrast to this, Unicode defines characters to be in logical order (the order you would read the string). This codec tries to convert visually ordered Hebrew (8859-8) to Unicode. This might not always work perfectly, because reversing the bidi (bi-directional) algorithm that transforms from logical to visual order is non-trivial.
Transformation from Unicode to visual Hebrew (8859-8) is done using the bidi algorithm in Qt, and will produce correct results, so long as the codec is given the text a whole paragraph at a time. Places where newlines are supposed to go can be indicated by a newline character ('\n'). Note that these newline characters change the reordering behaviour of the algorithm, since the bidi reordering only takes place within one line of text, whereas line breaks are determined in visual order.
Visually ordered Hebrew is still used quite often in some places, mainly in email communication (since most email programs still don't understand logically ordered Hebrew) and on web pages. The use on web pages is rapidly decreasing, due to the availability of browsers that correctly support logically ordered Hebrew.
This codec has the name "iso8859-8". If you don't want any bidi reordering to happen during conversion, use the "iso8859-8-i" codec, which assumes logical order for the 8-bit string.
See also Internationalization with Qt.
The algorithm is designed to work on whole paragraphs of text, so processing a line at a time may produce incorrect results. This approach is taken because the reordering of the contents of a particular line in a paragraph may depend on the previous line in the same paragraph.
Some encodings (for example Japanese or UTF-8) are multibyte (so one input character is mapped to two output characters). The lenInOut argument specifies the number of QChars that should be converted and is set to the number of characters returned.
Reimplemented from QTextCodec.
Reimplemented from QTextCodec. | http://man.linuxmanpages.com/man3/qhebrewcodec.3qt.php | crawl-003 | refinedweb | 380 | 52.8 |
stable 2.6 release remains 2.6.29.1; there have been no
stable 2.6 updates since April 2.
For the fans of extreme stability, though, 2.4.37.1 was released on
April 19. "Most of these fixes concern minor
security issues which have been backported from 2.6 (mostly local DoSes).
In my opinion, only people with local users might consider upgrading, if
those people still exist!"
Kernel development news
It all started innocently enough; Linus was engaging in a routine patch flaming when he encountered
one of the "Impact:" tags that some developers (especially those working
with Ingo Molnar's trees) have adopted in recent months:
Impact: clarify and extend confusing API
Suffice to say that he was not much impressed with it:
From there, the extended conversation focused on two related topics: the
value of "impact" tags and how to write better changelogs in general. On
the former, the primary (but not only) proponent of these tags is Ingo
Molnar, who cites several benefits from
their use. Using these tags, he claims, forces developers to write smaller
patches which can be adequately described in a single line. They give
subsystem maintainers an easy way to assess the changes made by a set of
patches and their associated risk; they also make it easier to review a
patch against its declared "impact." These tags are also said to force a
certain clarity of thought, making developers think through the
consequences of a change.
Most of these arguments leave "Impact:" detractors unmoved, though. Rather
than add yet another tag to a patch, they would prefer to see developers
just write better changelogs from the outset. In a properly-documented
patch, the new tag is just irrelevant. Andrew
Morton said:
Ingo disputed that claim at length,
needless to say. But he takes things further by stating that, while better
changelogs would certainly be desirable, they are not a practical goal.
According to Ingo, most
developers are simply not capable of writing good changelogs. Language
barriers and such often are part of this problem, but it goes deeper: most
developers simply lack the writing skills needed to write clear and concise
changelogs. This fact of life, as Ingo sees it, cannot really be changed,
but most developers can, at least, be trained to write a reasonable impact
tag.
It is probably fair to say that most developers do not see themselves as
being disabled in this way. That said, it is also fair to say that a lot
of patches go into the mainline with unhelpful changelogs. That can
probably be changed - to an extent at least - through pressure from
maintainers and a better understanding of what makes a good changelog.
In an attempt to help, your editor has proposed a brief addition to
Documentation/development-process:.
Other possible additions have been proposed by Ted Ts'o and Paul
Gortmaker. Of course, all of these patches are based on the optimistic
notion that developers will actually read the documentation.
One could argue that the kernel community is rather late in getting around
to this kind of discussion. That could be said to be par for the course;
in the pre-BitKeeper era (i.e. up to February, 2002), there was almost no
tracking of individual changes into the kernel at all. That the fine
points of changelogging are being discussed a mere seven years later
suggests things are going in the right direction. The level of
professionalism in the kernel community has been on the rise for a long
time; this process is likely to continue. Whether or not some variant on
the impact tag is used in the future, one can assume that the quality of
changelogs will, as a whole, be better.
Slow work is a thread pool implementation - yet another thread pool, one
might say. The kernel already has workqueues and the asynchronous function call
infrastructure; the distributed storage (DST) module added to the -staging
tree for 2.6.30 also
has a thread pool hidden within it. Each of these pools is aimed at a
different set of uses. Workqueues provide per-CPU threads dedicated to
specific subsystems, while asynchronous function calls are optimized for
specific ordering of tasks. Slow work, instead, looks like a true "batch
job" facility which can be used by kernel subsystems to run tasks which are
expected to take a fair amount of time in their execution.
A kernel subsystem which wants to run slow work jobs must first declare its
intention to the slow work code:
#include <linux/slow-work.h>
int slow_work_register_user(void);
The call to slow_work_register_user() ensures that the thread pool is set
up and ready for work - no threads are created before the first user is
registered. The return value will be either zero (on success) or the usual
negative error code.
Actual slow work jobs require the creation of two structures:
struct slow_work;
struct slow_work_ops {
int (*get_ref)(struct slow_work *work);
void (*put_ref)(struct slow_work *work);
void (*execute)(struct slow_work *work);
};
The slow_work structure is created by the caller, but is otherwise
opaque. The slow_work_ops structure, created separately, is where
the real work gets done. The execute() function will be called by
the slow work code to get the actual job done. But first,
get_ref() will be called to obtain a reference to the
slow_work structure. Once the work is done, put_ref()
will be called to return that reference. Slow work items can hang around
for some time after they have been submitted, so reference counting is
needed to ensure that they are freed at the right time. The
implementation of get_ref() and put_ref() functions is
not optional.
In practice, kernel code using slow work will create its own structure
which contains the slow_work structure and some sort of
reference-counting primitive. The slow_work structure must be
initialized with one of:
void slow_work_init(struct slow_work *work, const struct slow_work_ops *ops);
void vslow_work_init(struct slow_work *work, const struct slow_work_ops *ops);
The difference between the two is that vslow_work_init()
identifies the job as "very slow work" which can be expected to run (or
sleep) for a significant period of time. The documentation suggests that
writing to a file might be "slow work," while "very slow work" might be a
sequence of file lookup, creation, and mkdir() operations. The
slow work code actually prioritizes "very slow work" items over the merely
slow ones, but only up to the point where they use 50% (by default) of the
available threads. Once the maximum number of very slow jobs is running,
only "slow work" tasks will be executed.
Actually getting a slow work task running is done with:
int slow_work_enqueue(struct slow_work *work);
This function queues the task for running. It will succeed unless the
associated get_ref() function fails, in which case
-EAGAIN will be returned.
Slow work tasks can be enqueued multiple times, but no count is kept, so a
task enqueued several times before it begins to execute will only run
once. A task which is enqueued while it is running is indeed put
back on the queue for a second execution later on.
The same task is guaranteed to not run on multiple CPUs
simultaneously.
There is no way to remove tasks which have been queued for execution, and
there is no way (built into the slow work mechanism) to wait for those
tasks to complete. A "wait for completion" functionality can certainly be
created by the caller if need be. The general assumption, though, seems to
be that slow work items can be outstanding for an indefinite period of
time. As long as tasks with a non-zero reference count exist, any
resources they depend on need to remain available.
There are three parameters for controlling slow work which appear under
/proc/sys/kernel/slow-work: min-threads (the minimum size
of the thread pool), max-threads (the maximum size), and
vslow-percentage (the maximum percentage of the available threads
which can be used for "very slow" tasks). The defaults allow for between
two and four threads, 50% of which can run "very slow" tasks.
The only user of slow work in the 2.6.30 kernel is the FS-Cache file
caching subsystem. There is a clear need for thread pool functionality,
though, so it would not be surprising to see other users show up in future
releases. What might be more surprising (though desirable) would be a
consolidation of thread pool implementations in a future development cycle.
April 22, 2009
This article was contributed by Goldwyn Rodrigues
The Distributed Replicated Block Device (DRBD) patch, developed by Linbit,
introduces duplicated block storage over the network with synchronous data
replication. If one of the storage nodes in the replicated
environment fails, the system has another block device to rely on, and
can safely failover. In short, it can be considered as an implementation of
RAID1 mirroring using a combination of a local disk and one on a remote node,
but with better integration with cluster software
such as heartbeat and efficient resynchronization with the ability to
exchange dirty bitmaps and data generation identifiers. DRBD currently
works only on 2-node clusters, though you could use a hybrid version to
expand this limit. When both nodes of the cluster are up, writes are
replicated and sent to both the local disk and the other node. For efficiency
reasons, reads are fetched from the local disk.
The level of data coupling used depends on the protocol chosen:
DRBD classifies the cluster nodes as either "primary" or "secondary."
Primary nodes can initiate modifications or writes whereas secondary
nodes cannot. This means that a secondary DRBD node does not
provide any access and cannot be mounted. Even read-only access is
disallowed for cache coherency reasons. The secondary node is present
mainly to act as the failover device in case of an error. The secondary
node may become primary depending on the network configuration.
Role assignment and designation is performed by the cluster
management software.
There are different ways in which a node may be
designated as primary:
DRBD requires a small reserve area for metadata, to handle post
failure operations (such as synchronization) efficiently.
This area can be configured either on a separate device
(external metadata), or within the DRBD block device (internal
metadata). It holds the metadata with respect to the disk including
the activity log and the dirty bitmap (described below).
If a secondary node dies, it does not affect the system as a whole because writes
are not initiated by the secondary node. If the failed node is primary,
the data yet to be written to disk, but for which completions are not
received, may get lost. To avoid this, DRBD maintains an "activity log,"
a reserved area on the local disk which contains
information about write operations which have not completed. The data is stored
in extents and is maintained in a least recently used (LRU) list.
Each change of the activity log causes a meta data update (single
sector write). The size of the activity log is configured by the user;
it is a tradeoff between minimizing updates to the meta data and the
resynchronization time after the crash of a primary node.
DRBD maintains a "dirty bitmap" in case it has to run without a peer node or
without a local disk. It describes the pages which have been dirtied by the
local node. Writes to the on-disk dirty bitmap are minimized by the
activity log. Each time an extent is evicted from the activity log, the part of
the bitmap associated with it which is no longer covered by the activity log
is written to disk. The dirty bitmaps are sent over the network to
communicate which pages are dirty should a resynchronization become
necessary. Bitmaps are
compressed (using run-length encoding) before sending on the network to reduce network
overhead. Since most of the of the bitmaps are sparse, it proves to be
pretty effective.
DRBD synchronizes data once the crashed node comes back up, or in response
to data inconsistencies caused by an interruption in the link.
Synchronization is performed in a linear order, by disk offset, in
the same disk layout as the consistent node. The rate of
synchronization can be configured by the rate parameter in the
DRBD configuration file.
In case of local disk errors, the system may choose to deal with it
in one of the following ways, depending on the configuration:
In the dual-primary case, both nodes may write to the same disk sector,
making the data inconsistent. For writes at different offset, there is
no synchronization required. To avoid inconsistency issues, data
packets over the network are numbered sequentially to identify the
order of writes. However, there are still some corner-case
inconsistency problems the system can suffer from:
DRBD is not the only distributed storage implementation under development.
The implementation of Distributed Storage (DST) contributed by Evgeniy Polyakov
and accepted in staging tree takes a different approach.
DRBD is limited to 2-node active clusters, while DST can have
larger numbers of nodes. DST works on client-server model, where
the storage is at the server end, whereas DRBD is peer-to-peer based,
and designed for high-availability as compared to distributing
storage. DST, on the other hand, is designed for accumulative storage,
with storage nodes which can be added as needed. DST has a pluggable
module which accepts different algorithms for mapping the storage
nodes into a cumulative storage. The algorithm chosen can be mirroring
which would serve the same basic capability of replicated storage as
DRBD.
DRBD code is maintained in the git repository at
git://git.drbd.org/linux-2.6-drbd.git, under the "drbd" branch. It
contains the minor review comments posted on LKML
incorporated after the patchset was released by Philipp Reisner.
For further information, see the several PDF documents mention in the DRBD patch posting. | http://lwn.net/Articles/328761/ | CC-MAIN-2013-20 | refinedweb | 2,321 | 59.94 |
I am trying to create a program that automatically installs a network shortcut onto my desktop and downloads a driver (it is a print server for my work), but in order to access the shortcut after it is installed I need to enter my work credentials under the printer network's domain. I tried using the keyring library for Python but that was unsuccessful, I also tried to use win32wnet.WNETADDCONNECTION2() which I have seen posted on several forums but it was also unsuccessful for me.
Here is the code currently
import os, winshell, keyring, win32wnet
from win32com.client import Dispatch
#Add Windows Credentials
#**************************
url = r'\\LINKTOTHENETWORK'
win32wnet.WNetAddConnection2(0, None, url, None, USERNAME, PASSWORD)
keyring.set_password(url, USERNAME, PASSWORD)
keyring.get_password(url, USERNAME)
#**************************
# This is where I am having troubles.
# Create the shortcut
desktop = winshell.desktop()
path = os.path.join(desktop, "MYLINK.lnk")
target = url
# Set path and save
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.save()
# Open the shortcut
os.startfile(target)
I'm pretty sure you can achieve this by creating a .bat file and executing it in your program.
For Ex.
def bat_create_with_creds(id, pwd): """create Batch file to init printer domain creds with variables""" auth_print= open("auth_print.bat", "w") auth_print.write("NET USE \\printserverip /USER:%"+id+"% %"+pwd+"%") auth_print.close()
I haven't done this for your particular use case, but it works perfectly well for init. rdp sessions using windows mstsc for example. | https://codedump.io/share/16crtYgLDITL/1/how-can-i-add-windows-credentials-using-python | CC-MAIN-2017-34 | refinedweb | 243 | 52.87 |
Originally posted by Lionel Badiou: Hi George, You can easily use conditionnal compilation with Java. Here's a sample :
final boolean DEBUG = true;
if(DEBUG)
System.out.println("Printed only in Debug mode");
Once your code is correct, set DEBUG constant to false. You may check your .class files to verify that no code relative to a "if (DEBUG)" clause is included. Regards,
Originally posted by Paul Sturrock: Another alternative is to use a logging framework. Have a look at log4j or Java's own logging stuff in java.util.logging.*.
Originally posted by Lionel Badiou: Hi again I totally agree with Paul, you might consider using assertions or logging framework for professionnal projects. Nevertheless, you should be aware that the only mean to remove (not just to ignore) debug code from .class file is the conditionnal compilation trick I have described. Best regards to each of you,
Originally posted by Jeroen Wenting: Which isn't conditional compilation at all as it require a sourcecode change to take effect! It also depends on compiler implementation (another compiler may well decide not to inline the constant and may thus not even notice it can skip the code for example) which makes matters worse. Another reason you're not going to want to remove debug information at all is that problems usually pop up only after you start deploying the application to customers at which point having the debugging logs available can be a big help. Being able to enable and disable logging by simply changing a setting in a configuration file or a commandline option can save you a LOT of time. [ January 17, 2005: Message edited by: Jeroen Wenting ]
Originally posted by George Java: I am very interested in the assertions technology you mentioned. Can you provide more resources on this topic? I am still very interested in the conditional compilation trick you have described, and it is highly appreciate if you could provide more detailed descriptions.
Originally posted by George Java: ...Your reply is very helpful. I am wondering why .class files do not include code relative to a "if (DEBUG)" clause if I set DEBUG to false. I think if and only if Java compiler can make sure that the value of variable DEBUG does not change, it can exlude code relative to a "if (DEBUG)" clause when compiling. Am I correct? Can you provide more detailed information? regards, George
Originally posted by Joel McNary: [QB]
public class Test{
public static final boolean DEBUG = true;
public static void main(String argv[]){
if(DEBUG){
System.out.println("Testing...");
}
System.out.println("Hello, World!");
}
}
If you compare the compiled version of that to a compiled version where DEBUG = false, you would see that the entire if{DEBUG} block has been removed from the class -- not just the runtime logic.
Originally posted by Joel McNary: BTW, welcome to JavaRanch, George Java! I hope we've been helpful. I would like to point out, however, that your display name violates our Naming Policy (We are looking for names that are not obviously fake...) You can change your diplay name here
Originally posted by Layne Lund: Basically, that is correct. If the compiler is smart enough to see that the if statement will never be true, then it can remove it from the compiled .class file altogether. This is probably the primary reason that the "final" keyword is used when declaring the DEBUG variable. "final" tells the compiler that its value will never change. Layne | http://www.coderanch.com/t/398266/java/java/remove-debug-information | CC-MAIN-2014-10 | refinedweb | 582 | 54.73 |
updating open cv to version 3
Hi all,
I have opencv version 2.3 installed on my raspberry pi running raspbian. I looked at
the tutorial talks about opencv 3.0.0. Is this still under development? If not, how do I upgrade to it? Please see below for installed version details
pi@piprime ~ $ dpkg -l | grep libopencv
ii libopencv-calib3d2.3 2.3.1-11 armhf
computer vision Camera Calibration library
ii libopencv-core2.3 2.3.1-11 armhf
computer vision core library
ii libopencv-features2d2.3 2.3.1-11 armhf
computer vision Feature Detection and Descriptor Extraction library
ii libopencv-flann2.3 2.3.1-11 armhf
computer vision Clustering and Search in Multi-Dimensional spaces library
ii libopencv-highgui2.3 2.3.1-11 armhf
computer vision High-level GUI and Media I/O library
ii libopencv-imgproc2.3 2.3.1-11 armhf
computer vision Image Processing library
ii libopencv-legacy2.3 2.3.1-11 armhf
computer vision legacy library
ii libopencv-ml2.3 2.3.1-11 armhf
computer vision Machine Learning library
ii libopencv-objdetect2.3 2.3.1-11 armhf
computer vision Object Detection library
ii libopencv-video2.3 2.3.1-11 armhf
computer vision Video analysis library
pi@piprime ~ $
I want to upgrade because I want to run feature detection code. Please see the below python program as an example of what I want to run. Note: This program may have errors because I have been unable to test it.
import cv2 import time #test program for monocular obstacle detection vc = cv2.VideoCapture(-1) if vc.isOpened(): # try to get the first frame print 'fetching first frame' rval, frame = vc.read() else: rval = False print 'unable to fetch frame' while rval: rval, frame = vc.read() time.sleep(100) frame=vc.read() print 'images read.' #we now have two images one second apart orb = cv2.ORB() kp1, des1 = orb.detectAndCompute(rval,None) kp2, des2 = orb.detectAndCompute(frame,None) print 'detection done' bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches = bf.match(des1,des2) print 'matches done.' matches = sorted(matches, key = lambda x:x.distance) print matches[0].distance print 'end.' | https://answers.opencv.org/question/26611/updating-open-cv-to-version-3/ | CC-MAIN-2020-10 | refinedweb | 361 | 54.29 |
EAP 6.1.1 http session replication problemdanpeter Nov 14, 2013 5:13 AM
I am trying to get session replication working on EAP 6.1.1 with apache mod_cluster 1.2.6.Final.
Apache and 2 instances are all running on the same machine.
I start the instances with :
standalone.bat -c standalone-ha.xml -Djboss.node.name=nodeA
standalone.bat -c standalone-ha.xml -Djboss.socket.binding.port-offset=100 -Djboss.node.name=nodeB
I have not made any changes in standalone-ha.xml
The attached server log from nodeA looks good to me.
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""
xmlns:xsi=""
xsi:
<distributable/>
</web-app>
I have a facelet page witha a sessionscoped cdi bean:
@Named
@SessionScoped
public class MemberController implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(MemberController.class);
private String name;
@PostConstruct
public void init() {
LOGGER.info("MemberController constructed");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
When I go to the page I enter my name and it is displayed properly on the page.
When i ctrl-c nodeA and refresh the page the value is gone and I can see in the log "MemberController constructed" on nodeB.
What am I missing?
- server.log.zip 4.0 KB
1. Re: EAP 6.1.1 http session replication problemdanpeter Nov 20, 2013 7:12 AM (in response to danpeter)
Is this related to this bug?
Seems strange that this is not working ...
I also tried with clusterbench cdi test with the same negatie result
2. Re: EAP 6.1.1 http session replication problemWolf-Dieter Fink Nov 20, 2013 10:23 AM (in response to danpeter)
Could you check whether the example AS7 Cluster Howto work in your environment?
3. Re: EAP 6.1.1 http session replication problemdanpeter Nov 20, 2013 10:47 AM (in response to Wolf-Dieter Fink)
I used my standalone setup and deployed your cluster-demo.war and the replication works. Could the problem be related to CDI SessionScope?
I saw this issue but I have not configured <replication-trigger>SET</replication-trigger>
4. Re: EAP 6.1.1 http session replication problemRadoslav Husar Nov 26, 2013 10:05 AM (in response to danpeter)
So you have tried clusterbench/clusterbench · GitHub and it doesn't work?
What doesn't work?
How are you testing?
Maybe a test issue, are you sure you are sending the same cookies? Make sure you are accessing the load balancer URL, not AS directly via 8080.
5. Re: EAP 6.1.1 http session replication problemRadoslav Husar Nov 26, 2013 10:09 AM (in response to Radoslav Husar)
Are you using exploded deployments?
There is a known issue:
6. Re: EAP 6.1.1 http session replication problemdanpeter Nov 26, 2013 10:21 AM (in response to Radoslav Husar)
I just cloned clusterbench and built clusterbench-ee6.ear. I deploy it unexploded in the deploy folder of both servers.
I open in apache, I can refresh the page to increment the number. I Ctrl-c the command window which runs the instance handling the sticky session. I make a new request and the counter is back to 0.
Interesting thing is if I start the instance again and close down the running one the seesion is restored to the previous number.
There are no exceptions in the log.
7. Re: EAP 6.1.1 http session replication problemdanpeter Nov 26, 2013 10:42 AM (in response to Radoslav Husar)
Radoslav Husar skrev:
Are you using exploded deployments?
There is a known issue:
The problem is that it associates the session with the full path of the deployment? Altough im not using exploded deployment both instances are in the same machine so the paths are different.
C:\cluster-demo\jboss1\jboss-eap-6.1\standalone\deployments
C:\cluster-demo\jboss2\jboss-eap-6.1\standalone\deployments | https://developer.jboss.org/thread/234498 | CC-MAIN-2018-17 | refinedweb | 653 | 59.5 |
ndctl-write-labels - write data to the label area on a dimm
ndctl write-labels <nmem> [-i <filename>]
The namespace label area is a small persistent partition of capacity available on some NVDIMM devices. The label area is used to resolve aliasing between pmem and blk capacity by delineating namespace boundaries. Read data from the input filename, or stdin, and write it to the given <nmem> device. Note that the device must not be active in any region, otherwise the kernel will not allow write access to the device’s label data area.
).
-i; --input
input file
UEFI NVDIMM Label Protocol | http://pmem.io/ndctl/ndctl-write-labels.html | CC-MAIN-2018-51 | refinedweb | 101 | 51.78 |
There are the same risks with this as there are with any client-side code:
it can be manipulated. You should regard anything done on the client as
insecure, and verify on the server that you have what you should have.
The relevant line in the error is probably
08-31 17:04:08.470: I/GooglePlusPlatform(528):
{"code":401,"errors":[{"message":"Unauthorized","domain":"global","reason":"unauthorized"}]}
Indicating that there is an authorization error. Since it looks like you
are asking for the valid scope, as well as the visible activity you need,
the problem probably lies elsewhere. Did you enable the Google+ API in the
code console? Have you successfully authenticated as this user and
authorized actions under this scope?
You need to have a look at the ASP.NET Webforms page lifecycle in order to
understand what happens when.
Here is some docs regarding that:
The problem you have at the moment is that the Button click event happens
after the Page_Load event, so when you click the button you probably
experience that Label1.Text is one click "behind".
Look at the docs and place the Label1.Text assignment in PreRender for
example.
Like @ArabicProgrammer is answering, it is better yet to actually make use
of the Culture support that is available in the .NET Framework. If you use
that method instead, you can display the language using something like
this.
<%= System.Threading.Thread.CurrentThread.CurrentCulture.DisplayName %
Try putting this in your <head>
<meta http-
Also, try changing the de-DE in the <html> tag to
<html lang="de" prefix="og:">
let me know if that works
try this:
in your anchor do this:
<a href="javascript:void(0)" id="kontakt">Go to Kontakt</a>
and modify your ajax script to this:
$('a').click(function (e) {
var data = { 'id': $(this).attr("id") };
var dataVal = JSON.stringify(data);
$.ajax({
type: "POST",
url: "Default.aspx/loadNewPage",
contentType: "application/json; charset=utf-8",
data: dataVal,
dataType: "json",
success: function (id) {
}
});
});
You could use a module which allows to run custom code in it. There are
several solutions to this in the JED:.
You can use tag to show HTML entities You need to encode all
Your HTML entities like < => < like way.
Also you can show a text area in which all those HTML code need to echo, it
will not execute your code simply it will print it.
A hacky approach would be to:
Attach an event handler to the 'onclick' event of the button.
Then, once the event is triggered, use the Microsoft Internet Controls
(SHDocVw) type library in order to get the last URL opened in IE.
Lastly, navigate to the URL and once the document is loaded, get the source
of the document from the webBrowser1.DocumentText property.
In your project, add a reference to the Microsoft Internet Controls type
library (you'll find it in the COM tab). Add at the top of your file:
using SHDocVw;
The code:
webBrowser1.Navigate(url);
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
// assign the button to a variable
var button = webBrowser1.Document.GetElementById("downloadButton");
// attach an event handler for
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
WebClient wc = new WebClient();
var sourceCode =
wc.DownloadString("");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(sourceCode);
var node = doc.DocumentNode;
var nodes = node.SelectNodes("//a");
List<string> links = new List<string>();
foreach (var item in nodes)
{
var link = item.Attributes["href"].Value;
links.Add(link.Contains("h
As Filippo Toso said, you may include the HTML file in your code.php.
Perhaps, if you don't want to have two files, you may make only one file
and set the form to act like that:
<form id="createNewGallery" name="newgallery" method="GET"
action="./"><p><strong>please choose the number of pictures
you want to upload:
</strong>
<select name="numOfPictures" id="numOfPictures">
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select></p>
<input name="submitNumOfPictures" type="submit" />
<
You need to set the HTTP Accept header to tell the server that you want it
to give you JSON:
Accept: application/json
(assuming that the remote server is correctly implemented to read the
header)
The Content-Type request header indicates the type of the payload that you
are POSTing.
In your case, it does not apply, since you're sending a GET request.
The same origin policy predates IE7. Any browser that does not support
CORS will simply not allow you to make cross-domain ajax requests. The
same origin policy is enforced in IE7. Perhaps JSONP is an option for you.
Hard to say without more knowledge of your situation. If JSONP is not an
option for you, the request must be proxied from a server on the same
origin when using IE7.
In asp.net each request runs in its own independent context and hence the
header access as you have shown in your code make sense.
This does not hold good for angular or in fact any client side framework.
You can always get the headers for any request or response made using
angular $http but the question is which request? During the lifetime of the
app you would make many such requests.
Let's say you want to get the current userid, you can create a service that
returns the logged in user. There are two ways to implement such a sevice
create a method on server to return this data. Invoke this method from
service and cache results
on the client side assuming there is a login request made through angular,
implement a success callback method which can update the service with the
logged use
If your template has got 3 files header.php, content.php and footer.php,
you have to put them in "template" directory. Also, in the root dir you can
create some files which include the template form otterresti dir.
It's an example.
The API documentation will probably tell you that.
Yes, parse the data. If the data is coming down as XML, then you can parse
it with an XMLReader, or you can load it into an XMLDocument. It looks like
you're asking for JSON, though. If so, you'll want a JSON parser. Check out
Json.Net.
Again, check out the API documentation.
Their documentation page is suspiciously sparse. You'll probably get better
response on their Google group or one of the other sources listed on their
support page.
The /api/me.json route only accepts GET requests:
s = client.get('')
There is no POST route for that endpoint, so you'll get a 404 for that.
Also, if you need to pass modhash to the server, do so in the data passed
in the POST request; setting client.modhash does not then pass that
parameter to the server. You retrieve the modhash from your me.json GET
response:
r = client.get('')
modhash = r.json()['modhash']
Note how the response from requests has a .json() method, there is no need
to use the json module yourself.
You then use the modhash in POST request data:
client.post('', {'modhash': modhash,
'about_url': '...', ...})
private void requestPublishPermissions(Session session) {
List<String> PERMISSIONS = Arrays.asList("publish_actions",
"publish_stream");
if (session != null) {
pendingAnnounce = true;
Session.NewPermissionsRequest newPermissionsRequest = new
Session.NewPermissionsRequest(this, PERMISSIONS);
newPermissionsRequest.setRequestCode(REAUTH_ACTIVITY_CODE);
Session mSession = Session.openActiveSessionFromCache(this);
mSession.addCallback(callback);
mSession.requestNewPublishPermissions(newPermissionsRequest);
}
}
You should not use RestKit for this. RestKit is meant to be used for
mapping objects from JSON / XML / ... It is not meant for receiving image
data. Instead, use AFNetworking which is included with RestKit (used
internally for all comms) and can much better handle a simple post and
image response.
If you need to do some object serialisation to create the JSON to do your
post then look at using RKSerialization and RKMapperOperation.
You need to turn on the browser leverage caching using .htaccess files.
In order to make the files cached by the browser, say for example the
images, stylesheets, JavaScript etc, you need to turn on the Leverage
Caching using a .htaccess file, by which you can specifically inform the
browser that specific content won't be changing for a specified period - a
week/month/year. As the browser will not repeatedly request that content it
will drastically improve your page loading speed for future visits from the
same browser.
In your .htaccess file, you can add the following (for files that won't
change)
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/png "access plus 1
For one, I would recommend using a wrapper for the API. You're asking a lot
of questions on here that could be simplified by finding a wrapper whose
API you appreciate. There's a list of wrappers written in Python here.
As for your actually answering your question, the GitHub documentation is
fairly clear that you need to send the Authorization header. Your call
would actually look like this:
self.headers = {'Authorization': 'token %s' % self.api_token}
r = requests.post(url, headers=self.headers)
Since it seems like you're using requests and a class, might I be so bold
as to make a recommendation? Let's say you're doing something like making a
client for the API. You might have a class like so:
class GitHub(object):
def __init__(self, **config_options):
self.__dict__.upda
A route's activate hook is only called when the route is first transitioned
to. It is not called again if the route's model changes. So when you
transition into App.DatasetRoute either by entering the url directly or by
clicking link on index page, the activate hook runs and your dataset is
reloaded. When you switch from #/1 to #/2, the route remains active and no
hook is called.
If I am understanding your question correctly, you want to reload the
dataset whenever a user visits its url. In that case instead of the route's
activate hook what you probably want to do is observe changes to the
dataset controller's content. Something like this should work:
App.DatasetController = Ember.ObjectController.extend({
refreshOnChange: function() {
var dataset = this.get('content');
if (da
Just temporarily while debugging, you'll need to expand the code a little
to explain it:
<?php
mysql_connect("54.249.251.55","MYID","MYPASS"); //connect database
echo mysql_error();
mysql_select_db("aubook");//select name of the database
echo mysql_error();
$cmd = "select * from book limit 0,20";
$sql=mysql_query($cmd);
echo mysql_error();
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
if (count($output) == 0)
echo "The database contained no records.";
print(json_encode($output));
mysql_close();
?>
BrowserStack provides a feature of Local Testing via Command Line Tunnel.
To check if tunnel is connected or not, their JavaScript(JS) tries to talk
to a http server which runs on port 45691 inside BrowserStackTunnel.jar.
When you don't have this Command Line Tunnel set, then the JS gets these
errors, which turns to 200 OK response as soon as tunnel gets connected.
will not display the page - will not let me see the page
Your problems is most likely that TinyMCE escapes all HTML tags. To allow
code to be embedded without adding the security risk of allowing other HTML
tags to be inserted, I think this is what you want:
In order to have a better understanding of what is going in, perhaps you
could execute the commands related to assets in verbose mode (from your
project root directory when using a standard Symfony2 edition) ?
php app/console assets:install --symlink -v
php app/console assetic:dump -v
Solution is to place index.html file inside of public folder.
Now, it can be loaded and manipulated locally with ajax ( like a template
). Also hash in the url will work ( no request to server ) - that was my
main issue.
From Organizer it is not going to work, until you don't have .p12
certificate for your system. Make a .p12 certificate for your distribution
profile where it is set by admin and then you can check with provisioning
profiles.
Try attaching a listener to the facebook login event / statuschange:
$facebookProvider.Event.subscribe('auth.authResponseChange', function
(response) {
console.log(response);
})
And look at the response element to see if you have an error or not
I suppose you are using a HttpServletRequest and from the
ServletRequest#getParameter() documentation:
If the parameter data was sent in the request body, such as occurs with an
HTTP POST request, then reading the body directly via getInputStream() or
getReader() can interfere with the execution of this method.
Are you using either getInputStream() or getReader() prior to your
getParameter() ?
A related answer here might help you solve your problem:
Plain old C arrays don't have members. So it has no size or erase. If you
did want it to have members though, C++11 offers a class called
std::array<T,N> which can be used in your case by simply doing
std::array<int, 6> games = { ... }. Note however that std::array does
not have an erase member function, but it has a size member function. | http://www.w3hello.com/questions/-Requesting-a-web-page-from-asp-net-code- | CC-MAIN-2018-17 | refinedweb | 2,214 | 56.66 |
Introduction
After my latest published article about satellite image analysis “Image Analysis and Mapping in Earth Engine Using NDVI“, now it is another article about image analysis again. Unlike the previous article, this article discusses general image analysis, not satellite image analysis. The goal of this discussion is to detect whether two products are the same or not. Each of the two products has image and text names. If the pair of products have similar or the same images or text names, that means that the two products are the same. The data comes from a competition held in Kaggle.
There are 4 basic packages used in this script: NumPy, pandas, matplotlib, and seaborn. There are also other specific packages. “Image” loads and shows image data. “imagehash” computes the similarity of two images. “fuzzywuzzy” detects the similarity of two texts. The package “metric” computes the accuracy score of the true label and predicted label.
# import packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from PIL import Image import imagehash from fuzzywuzzy import fuzz from sklearn.tree import DecisionTreeClassifier from sklearn import metrics
Image Similarity
The similarity of the two images is detected using the package “imagehash”. If two images are identical or almost identical, the imagehash difference will be 0. Two images are more similar if the imagehash difference is closer to 0.
Comparing the similarity of two images using imagehash consists of 5 steps. (1) The images are converted into greyscale. (2) The image sizes are reduced to be smaller, for example, into 8×8 pixels by default. (3) The average value of the 64 pixels is computed. (4)The 64 pixels are checked whether they are bigger than the average value. Now, each of the 64 pixels has a boolean value of true or false. (5) Imagehash difference is the number of different values between the two images. Please observe the below illustration.
Image_1 (average: 71.96875)
Image_2 (average: 78.4375)
The imagehash difference of the two images/matrices above is 3. It means that there are 3 pixels with different boolean values. The two images are relatively similar.
For more clarity, let’s examine imagehash applied to the following 3 pairs of images. The first pair consists of two same images and the imagehash difference is 0. The second pair compares two similar images. The second image (image_b) is actually an edited version of the first image (image_a). The imagehash difference is 6. The last pair shows the comparison of two totally different images. The imagehash difference is 30, which is the farthest from 0.
# First pair hash1 = imagehash.average_hash(Image.open('D: /image_a.jpg')) hash2 = imagehash.average_hash(Image.open('D:/ image_a.jpg')) diff = hash1 - hash2 print(diff) # 0
# Second pair hash1 = imagehash.average_hash(Image.open('D: /image_a.jpg')) hash2 = imagehash.average_hash(Image.open('D:/ image_b.jpg')) diff = hash1 - hash2 print(diff) # 6
# Third pair hash1 = imagehash.average_hash(Image.open('D: /image_a.jpg')) hash2 = imagehash.average_hash(Image.open('D:/ image_c.jpg')) diff = hash1 - hash2 print(diff) # 30
Here is how the average imagehash looks like
>imagehash.average_hash(Image.open('D:/image_a.jpg')) array([[ True, True, True, True, True, True, True, True], [ True, True, True, True, True, True, True, True], [ True, True, True, True, True, True, True, True], [False, True, False, False, False, False, False, False], [ True, True, False, False, False, False, False, False], [False, False, False, True, False, False, False, False], [False, False, False, True, False, False, False, False], [False, False, False, False, False, False, False, False]])
>imagehash.average_hash(Image.open('D:/image_b.jpg')) array([[ True, True, True, True, True, True, True, True], [ True, True, True, True, True, True, True, True], [False, True, True, True, True, False, False, False], [ True, True, True, False, False, False, False, False], [ True, True, False, False, False, False, False, False], [False, False, False, True, False, False, False, False], [False, False, False, True, False, False, False, False], [False, False, False, False, False, False, False, False]])
>imagehash.average_hash(Image.open('D:/image_c.png')) array([[False, False, False, False, False, False, False, False], [ True, True, True, True, True, True, True, True], [ True, True, True, True, True, True, True, True], [ True, True, True, True, True, True, True, True], [ True, True, True, True, True, True, True, True], [ True, True, True, True, True, True, True, True], [False, False, False, False, True, False, False, False], [False, False, False, False, False, False, False, False]])
Text Similarity
Text similarity can be assessed using Natural Language Processing (NLP). There are 4 ways to compare the similarity of a pair of texts provided by “fuzzywuzzy” package. The function of this package returns an integer value from 0 to 100. The higher value means the higher similarity.
1. fuzz.ratio – is the most simple comparison of the texts. The fuzz.ratio value of “blue shirt” and “blue shirt.” is 95. It means that the two texts are similar or almost the same, but the dot makes them a bit different
from fuzzywuzzy import fuzz fuzz.ratio('blue shirt','blue shirt.') #95
The measurement is based on the Levenshtein distance (named after Vladimir Levenshtein). Levenshtein distance measures how similar two texts are. It measures the number of minimum edits, such as inserting, deleting, or substituting, a text into another text. The text “Blue shirt” requires only 1 editing away to be “blue shirt.”. It only needs a single dot to be the same. Hence, the Levenshtein distance is “1”. The fuzz.ratio is calculated with this equation (len(a) + len(b) – lev)/( (len(a) + len(b), where len(a) and len(b) are the lengths of the first and second text, and lev is the Levenshtein distance. The ratio is (10 + 11 – 1)/(10 + 11) = 0.95 or 95%.
2. fuzz.partial_ratio – can detect if a text is a part of another text. But, it cannot detect if the text is in a different order. The example below shows that “blue shirt” is a part of “clean blue shirt” so that the fuzz.partial_ratio is 100. The fuzz.ratio returns the value 74 because it only detects that there is much difference between the two texts.
print(fuzz.ratio('blue shirt','clean blue shirt.')) #74 print(fuzz.partial_ratio('blue shirt','clean blue shirt.')) #100
3. Token_Sort_Ratio – can detect if a text is a part of another text although they are in a different order. Fuzz.token_sort_ratio returns 100 for the text “clean hat and blue shirt” and “blue shirt and clean hat” because they actually mean the same thing, but are in reverse order.
print(fuzz.ratio('clean hat and blue shirt','blue shirt and clean hat')) #42 print(fuzz.partial_ratio('clean hat and blue shirt','blue shirt and clean hat')) #42 print(fuzz.token_sort_ratio('clean hat and blue shirt','blue shirt and clean hat')) #100
4. Token_Set_Ratio – can detect the text-similarity accounting for the partial text, text order, and different text lengths. It can detect that the text “clean hat” and “blue shirt” is part of the text “People want to wear a blue shirt and clean hat” in a different order. In this study, we only use “Token_Set_Ratio” as it is the most suitable.
print(fuzz.ratio('clean hat and blue shirt','People want to wear blue shirt and clean hat')) #53 print(fuzz.partial_ratio('clean hat and blue shirt','People want to wear blue shirt and clean hat')) #62 print(fuzz.token_sort_ratio('clean hat and blue shirt','People want to wear blue shirt and clean hat')) #71 print(fuzz.token_set_ratio('clean hat and blue shirt','People want to wear blue shirt and clean hat')) #100
The following cell will load the training dataset and add features of hash as well as token set ratio.
# load training set trainingSet = pd.read_csv('D:/new_training_set.csv', index_col=0).reset_index() # Compute imagehash difference hashDiff = [] for i in trainingSet.index: hash1 = imagehash.average_hash(Image.open(path_img + trainingSet.iloc[i,2])) hash2 = imagehash.average_hash(Image.open(path_img + trainingSet.iloc[i,4])) diff = hash1 - hash2 hashDiff.append(diff) trainingSet = trainingSet.iloc[:-1,:] trainingSet['hash'] = hashDiff # Compute token_set_ratio Token_tes = [] for i in trainingSet.index: TokenSet = fuzz.token_set_ratio(trainingSet.iloc[i,1], trainingSet.iloc[i,3]) TokenSet = (i, TokenSet) Token_tes.append(TokenSet) dfToken = pd.DataFrame(Token_tes) trainingSet['Token'] = dfToken
Below is the illustration of the training dataset. It is actually not the original dataset because the original dataset is not in the English language. I create another data in English for understanding. Each row has two products. The columns “text_1” and “image_1” belong to the first product. The columns “text_2” and “image_2” belong to the second product. “Label” defines whether the pairing products are the same (1) or not (0). Notice that there are other two columns: “hash” and “tokenSet”. These two columns are generated, not from the original dataset, but from the above code.
Applying Machine Learning
Now, we know that lower Imagehash difference and higher Token_Set_Ratio indicates that a pair of products are more likely to be the same. The lowest value of imagehash is 0 and the highest value of Token_Set_Ratio is 100. But, the question is how much the thresholds are. To set the thresholds, we can use the Decision Tree Classifier.
A Machine Learning of Decision Tree model is created using the training dataset. The Machine Learning algorithm will find the pattern of imagehash difference and the token set ratio of identical and different products. The Decision Tree is visualized for the cover image of this article. The code below builds a Decision Tree model with Python. (But, the visualization for the cover image is the Decision Tree generated using R because, in my opinion, R visualizes Decision Tree more nicely). Then, it will predict the training dataset again. Finally, we can get the accuracy.
# Create decision tree classifier: hash and token set Dtc = DecisionTreeClassifier(max_depth=4) Dtc = Dtc.fit(trainingSet.loc[:,['hash', 'tokenSet']], trainingSet.loc[:,'Label']) Prediction2 = Dtc.predict(trainingSet.loc[:,['hash', 'tokenSet']]) metrics.accuracy_score(trainingSet.loc[:,'Label'], Prediction2)
The Decision Tree is used to predict the classification of the training dataset again. The accuracy is 0.728. In other words, 72.8% of the training dataset is predicted correctly.
From the Decision Tree, we can extract the information that if the Imagehash difference is smaller than 12, the pair of products are categorized to be identical. If the Imagehash difference is bigger than or equal to 12, we need to check the Token_Set_Ratio value. The Token_Set_Ratio lower than 97 confirms that the pair of products are different. If else, check whether the Imagehash difference value again. If the imagehash difference is bigger than or equal to 22, then the products are identical. Otherwise, the products are different.
Apply to test dataset
Now, we will load the test dataset, generate the Imagehash difference and Token_Set_Ratio, and finally predict whether each product pair matches.
# path to image path_img = 'D:/test_img/' # load test set test = pd.read_csv('D:/new_test_set.csv', index_col=0).reset_index() # hashDiff list hashDiff = [] # Compute image difference for i in test.index[:100]: hash1 = imagehash.average_hash(Image.open(path_img + test.iloc[i,2])) hash2 = imagehash.average_hash(Image.open(path_img + test.iloc[i,4])) diff = hash1 - hash2 hashDiff.append(diff) test['hash'] = hashDiff # Token_set list Token_set = [] # Compute text difference using token set for i in test.index: TokenSet = fuzz.token_set_ratio(test.iloc[i,1], test.iloc[i,3]) Token_set.append(TokenSet) test['token'] = Token_set
After computing the Imagehash difference and Token_Set_ratio, the next thing to do is to apply the Decision Tree for the product match detection.
# Detecting product match test['labelPredict'] = np.where(test['hash']<12, 1, np.where(test['token']<97, 0, np.where(test['hash']>=22, 0, 1))) # or test['labelPredict'] = Dtc.predict(test[['hash','token']])
The above table is the illustration of the final result. The focus of this article is to demonstrate how to predict whether two images and two texts are similar or the same. You may find out that the Machine Learning model used is quite simple and there is no hyperparameter-tuning or training and test data splitting. Applying other Machine Learning, such as tree-based ensemble methods, can increase the accuracy. But it is not our discussion focus here. If you are interested to learn other tree-based Machine Learning more accurate than Decision Tree, please find an article here.
About Author
Connect with me here
The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.
| https://www.analyticsvidhya.com/blog/2021/05/beginners-guide-to-image-and-text-similarity/ | CC-MAIN-2021-25 | refinedweb | 2,070 | 58.69 |
Represents the result of an inner solve. More...
#include <BelosInnerSolveResult.hpp>
Represents the result of an inner solve.
An "inner solve" is an invocation of an iterative method, itself used as the operator or preconditioner for another iterative method. Inner solves may converge or not converge; they take some number of iterations to do either, and that number is less than or equal to some maximum number of iterations. The inner solve result may represent the result of solving for a single right-hand side, or it may aggregate the results of solving for multiple right-hand side(s).
Definition at line 66 of file BelosInnerSolveResult.hpp.
Constructor.
Definition at line 47 of file BelosInnerSolveResult.cpp.
Constructor, with no "extra data" input argument.
Definition at line 58 of file BelosInnerSolveResult.cpp.
Did the inner solve converge?
The ReturnType enum currently only has two values: Converged and Unconverged. This may or may not change in the future, which is why we express convergence using ReturnType rather than a Boolean value.
Definition at line 101 of file BelosInnerSolveResult.hpp.
Total number of iterations completed over all restarts.
This is the sum of all iterations over all restarts.
Definition at line 108 of file BelosInnerSolveResult.hpp.
Total number of restart cycles.
Definition at line 113 of file BelosInnerSolveResult.hpp.
"Extra" data from the inner solve.
The inner solve may choose to expose more data to the outside world than just the data above. The data are stored as a map from the string label, to a double-precision floating-point value.
Definition at line 123 of file BelosInnerSolveResult.hpp. | http://trilinos.sandia.gov/packages/docs/r10.12/packages/belos/doc/html/classBelos_1_1InnerSolveResult.html | CC-MAIN-2014-10 | refinedweb | 266 | 51.34 |
Reporting Bugs
If you've found something that angr isn't able to solve and appears to be a bug, please let us know!
- Create a fork off of angr/binaries and angr/angr
- Give us a pull request with angr/binaries, with the binaries in question
- Give us a pull request for angr/angr, with testcases that trigger the binaries in
angr/tests/broken_x.py,
angr/tests/broken_y.py, etc
Please try to follow the testcase format that we have (so the code is in a test_blah function), that way we can very easily merge that and make the scripts run.
An example is:
def test_some_broken_feature(): p = angr.Project("some_binary") result = p.analyses.SomethingThatDoesNotWork() assert result == "what it should *actually* be if it worked" if __name__ == '__main__': test_some_broken_feature()
This will greatly help us recreate your bug and fix it faster.
The ideal situation is that, when the bug is fixed, your testcases passes (i.e., the assert at the end does not raise an AssertionError).
Then, we can just fix the bug and rename
broken_x.py to
test_x.py and the testcase will run in our internal CI at every push, ensuring that we do not break this feature again.
Developing angr
These are some guidelines so that we can keep the codebase in good shape!
Coding style
We try to get as close as the PEP8 code convention as is reasonable without being dumb. If you use Vim, the python-mode plugin does all you need. You can also manually configure vim to adopt this behavior.
Most importantly, please consider the following when writing code as part of angr:
Try to use attribute access (see the
@propertydecorator) instead of getters and setters wherever you can. This isn't Java, and attributes enable tab completion in iPython. That being said, be reasonable: attributes should be fast. A rule of thumb is that if something could require a constraint solve, it should not be an attribute.
Use our
.pylintrcfrom the angr-dev repo. It's fairly permissive, but our CI server will fail your builds if pylint complains under those settings.
DO NOT, under ANY circumstances,
raise Exceptionor
assert False. Use the right exception type. If there isn't a correct exception type, subclass the core exception of the module that you're working in (i.e.,
AngrErrorin angr,
SimErrorin SimuVEX, etc) and raise that. We catch, and properly handle, the right types of errors in the right places, but
AssertionErrorand
Exceptionare not handled anywhere and force-terminate analyses.
Avoid tabs; use space indentation instead. Even though it's wrong, the de facto standard is 4 spaces. It is a good idea to adopt this from the beginning, as merging code that mixes both tab and space indentation is awful.
Avoid super long lines. It's okay to have longer lines, but keep in mind that long lines are harder to read and should be avoided. Let's try to stick to 120 characters.
Avoid extremely long functions, it is often better to break them up into smaller functions.
Always use
_instead of
__for private members (so that we can access them when debugging). You might not think that anyone has a need to call a given function, but trust us, you're wrong.
Documentation
Document your code. Every class definition and public function definition should have some description of:
- What it does.
- What are the type and the meaning of the parameters.
- What it returns.
We use Sphinx to generate the API documentation. Sphinx supports special keywords to document function parameters, return values, return types etc.
Here is an example of function documentation. Ideally the parameter descriptions should be aligned vertically to make the docstrings as readable as possible.
def prune(self, filter_func=None, from_stash=None, to_stash=None): """ Prune unsatisfiable paths from a stash. :param filter_func: Only prune paths that match this filter. :param from_stash: Prune paths from this stash. (default: 'active') :param to_stash: Put pruned paths in this stash. (default: 'pruned') :returns: The resulting PathGroup. :rtype: PathGroup """
This format has the advantage that the function parameters are clearly identified in the generated documentation. However, it can make the documentation repetitive, in some cases a textual description can be more readable. Pick the format you feel is more appropriate for the functions or classes you are documenting.
def read_bytes(self, addr, n): """ Read `n` bytes at address `addr` in memory and return an array of bytes. """
Unit tests
If you're pushing a new feature and it is not accompanied by a test case it will be broken in very short order. Please write test cases for your stuff.
We have an internal CI server to run tests to check functionality and regression on each commit. In order to have our server run your tests, write your tests in a format acceptable to nosetests in a file matching
test_*.py in the
tests folder of the appropriate repository. A test file can contain any number of functions of the form
def test_*():. Each of them will be run as a test, and if they raise any exceptions or assertions, the test fails. Use the
nose.tools.assert_* functions for better error messages.
Look at the existing tests for examples. Many of them use an alternate format where the
test_* function is actually a generator that yields tuples of functions to call and their arguments, for easy parametrization of tests.
Finally, do not add docstrings to your test functions. | https://docs.angr.io/HACKING.html | CC-MAIN-2017-51 | refinedweb | 909 | 66.13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.