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 |
|---|---|---|---|---|---|
Indexing Hierarchical Data
One of the greatest advantages of a document database is that we have very few limits in how we structure our data. One very common such scenario is the usage of hierarchical data structures. The most trivial of them is the comment thread, such as the following document:
{ //posts/123 'Name': 'Hello Raven', 'Comments': [ { 'Author': 'Ayende', 'Text': '...', 'Comments': [ { 'Author': 'Rahien', 'Text': '...', "Comments": [] } ] } ] }
While it is very easy to work with such a document in all respect, it does bring up an interesting question, how can we index all comments in the post?
The answer to that is that Raven contains built-in support for indexing hierarchies, we can define an index using the following syntax:
public class SampleRecurseIndex : AbstractIndexCreationTask<Post> { public SampleRecurseIndex() { Map = posts => from post in posts from comment in Recurse(post, x => x.Comments) select new { Author = comment.Author, Text = comment.Text }; } }
then create it using:
new SampleRecurseIndex().Execute(store);
Alternative way is to use
PutIndex command:
store.DatabaseCommands.PutIndex("SampleRecurseIndex", new IndexDefinition { Map = @"from post in docs.Posts from comment in Recurse(post, (Func<dynamic, dynamic>)(x => x.Comments)) select new { Author = comment.Author, Text = comment.Text }" });
This will index all the comments in the thread, regardless of their location in the hierarchy. | https://ravendb.net/docs/article-page/2.0/csharp/client-api/querying/static-indexes/indexing-hierarchies | CC-MAIN-2017-30 | refinedweb | 209 | 50.12 |
Let us now build the score maker. This will display whatever is played on the piano in music notation. For the sake of program modularity, we will build the program in a separate file named score_maker.py.
We start by defining a class ScoreMaker. Since we will be showing just two octaves of notes, we will define a constant NOTES listing all the notes (7.06/score_maker.py):
class ScoreMaker:NOTES = ['C1','D1', 'E1', 'F1', 'G1','A1', 'B1', 'C2','D2', 'E2', 'F2', 'G2','A2', 'B2']
The __init__ method of this class takes the container as an argument. This is the container on which this class will draw the score (7.06/score_maker.py):
def __init__(self, container): self.canvas = Canvas(container, width=500, height = 110) ... | https://www.oreilly.com/library/view/tkinter-gui-application/9781788837460/ad47d79e-3f04-40a9-a682-42a85d60f0d6.xhtml | CC-MAIN-2019-26 | refinedweb | 125 | 67.65 |
What is a python module?
Till now we have seen all the code written in a single python file but real applications are made up of multiple python files.
Each python file is called a Module.
This module can be used in other python files of the same application or it can also be used in other applications provided it is available to them.
Writing an application using modules promotes reusability since same code can be used at multiple places.
Each module consists of one or more functions which can be called from other modules which have access to the owner module of those functions.
Practical use of Module
Suppose you have a file which contains some utility functions such as one which reads a text file and returns a list of lines, other which takes a format and returns current date, one which takes a directory path and returns a list of all files in it etc.
Now you need those functions in your code somewhere else, say in some other file.
One way is to copy the functions from that file into your file and then use them.
Another and a more better way is to import that module(or file) into your file and call its functions directly.
This way you can re-use the functions which are already written and save your effort and time.
It might be possible that the module you are importing has been written by some other person working with you.
It might also be possible that the imported module is written by someone you don’t know as it may have been downloaded from the Internet.
Module import
A module before being used needs to be imported. Once a module is imported into another module, its variables and functions can be accessed in the importing module.
A module(or file) is used in another module(or file) using
import statement.
import is followed by the name of the file that needs to be imported.
While importing, the .py extension of file is not used.
Import module example
Suppose you have a python file which contains a function that takes a file name, reads its contents and returns a list of lines as shown below
# filereader.py def read_file(filename): # define a function filehandle = open(filename) # open file # read lines and store them in list filecontents = filehandle.read().splitlines() filehandle.close() # close file return filecontents # return list
This function takes a file name as argument, reads its lines into a list and returns it.
Let the name of its file be filereader.py and can also be called a Module.
Now you want to develop a program which should read a file and print its contents.
Either you write the file reading code again or use the above module and save your effort.
Let’s name this file as filedisplay.py
# filedisplay.py import filereader file_contents = filereader.read_file("f:/fruits.txt") print(file_contents)
Above code imports filereader and uses its file reading function. Note that the function from the imported module is called using syntax <modulename>.functionname
Importing required functions only
Many times only a single function is required from a module.
Thus, it is not necessary to import an entire file(or module) into another file. In such cases, it is also possible to import only selected functions or variables from a file(or module).
To import selected functions from a module,
from keyword is used.
Syntax is
# filedisplay.py from filereader import read_file file_contents = read_file("f:/fruits.txt") print(file_contents)
Note that now we are importing only a function from the specified module.
Thus, it is not necessary to prefix module name and dot while calling the function, it can be called directly using its name.
If you want to call the function defined in imported module, then use <filename>.<functionname> syntax.
from importsyntax, only the functions imported will be available.
In order to import all the functions using this syntax, write it as
Importing Variables from Modules
Not only functions, but variables can also be imported from other modules. Example,
# utility.py CITY_NAMES = ['California', 'Sydney, 'New York', 'London'] # returns square of supplied number def square(number): return number * number;
Above file(utility.py) contains a list of cities and a function which calculates square of a number provided to it.
Now, let’s say, another module wants to use the list of cities, then it will get it as
# user.py from utility import CITY_NAMES cities = CITY_NAMES print(cities)
Using the above syntax,
square function will not be available to the importing file, it will have to separately import it.
Module path
In all the examples till now, we directly imported a file into another file.
But where should the files be places relative to each other?
For all the examples above to work, both the files should be placed adjacent to each other as shown below
|— user.py
|— utility.py
But what if the module(or python file) to be imported is placed in a folder and the module which requires it are not adjacent to each other but at different locations.
Example,
|— user.py
|— mod
|— utility.py
# user.py from mod.utility import CITY_NAMES cities = CITY_NAMES print(cities)
Note that it prefixes the folder name followed by a dot(.) before the module name.
In case, if the file utility.py is located in a hierarchy of folders such as A/B/C/utility.py, then it will be imported as | https://codippa.com/tutorials/python/modules/ | CC-MAIN-2021-04 | refinedweb | 913 | 64.3 |
Architecting an iPhone chat app
With an installed base of 40 million iPhones, you have to be crazy if you aren't interested in writing an iOS application. But where do you start? Most applications are going to be network connected. So what about a project that spans across both, such as a chat application. In this article I show you how to build a chat application with both server and client components. You can learn much from it about creating iOS applications that I guarantee you will want to write one by the end of this article.
Building the application starts with architecting the solution. Figure 1 shows the architecture of how the iOS device (the iPhone in this case) connects to the server through two PHP pages.
Figure 1. The Chat App client/server architecture
These two PHP pages, add.php and messages.php, both connect to the database to both post and retrieve the messages, respectively. In the code that I provide, the database is MySQL, but you can use DB2 or any other database that you like.
The protocol I use is XML. The add.php page returns an XML message that says whether the message post has been successful. And the messages.php page returns the latest messages posted to the server.
Before you start, I want to cover what you will learn here.
- Database access. I show you how to use PHP to add rows to the database and retrieve them.
- XML encoding. The server code demonstrates how to package up the messages into XML.
- Building an iOS interface. I go through building the user interface for the application.
- Querying the server. The Objective-C code makes GET requests to the messages.php page to get the latest chat messages.
- Parsing the XML. Using the XML parser available to iOS developers you can parse the XML returned from messages.php.
- Displaying the messages. The application uses a custom list item to display the chat messages; this approach can give you some insight into how to customize the look and feel of your iOS application.
- Posting a message. The application POSTs data to the server through add.php, which guides you through that process.
- Timers. A timer task is used to periodically poll messages.php to see when new chat items arrive.
That's a lot for one example and it should provide a decent set of tools for you to develop any type of client/server iOS application you want to build.
Building the server
You start by creating the database. I called mine "chat," but you can call yours whatever you like. You just need to make sure that you change the connection strings in the PHP to match the name of the database. The SQL script used to build the single table for the application is in Listing 1.
Listing 1. chat.sql
DROP TABLE IF EXISTS chatitems; CREATE TABLE chatitems ( id BIGINT NOT NULL PRIMARY KEY auto_increment, added TIMESTAMP NOT NULL, user VARCHAR(64) NOT NULL, message VARCHAR(255) NOT NULL );
This simple single-table database has just four fields:
- The id of the row, which is just an auto-incrementing integer
- The date the message was added
- The user that added the message
- The text of the message itself
You can change the sizes of these fields to accommodate your content.
In a production system, you likely want to also have a user table with names and passwords and have a login user interface, and so on. For this example, I wanted to keep the database simple, so there is only a single table.
The first thing you want to build is the add.php script in Listing 2.
Listing 2. add.php
<?php header( 'Content-type: text/xml' ); mysql_connect( 'localhost:/tmp/mysql.sock', 'root', '' ); mysql_select_db( 'chat' ); mysql_query( "INSERT INTO chatitems VALUES ( null, null, '". mysql_real_escape_string( $_REQUEST['user'] ). "', '". mysql_real_escape_string( $_REQUEST['message'] ). "')" ); ?> <success />
This script connects to the database and stores the message using the posted
user and
message fields. It's a simple INSERT statement where the two values are escaped to account for any errant characters such as single quotes that might disturb the SQL syntax.
To test the add script, you create a test.html page, shown in Listing 3, that simply posts fields to the add.php script.
Listing 3. test.html
<html> <head> <title>Chat Message Test Form</title> </head> <body> <form action="add.php" method="POST"> User: <input name="user" /><br /> Message: <input name="message" /><br /> <input type="submit" /> </form> </body> </html>
This simple page has only one form that points to add.php, with the two text fields for the user and the message. It then has the Submit button that executes the post.
With the test.html page installed, you can test the add.php script. Bringing up the test page in the browser looks something like Figure 2, with the value of '"jack" in the User field displays, the value of "This is a test" in the Message field, and the Submit Query button.
Figure 2. The message posting test page
From here, you add in some values and click the Submit Query button. If all works well you see something like Figure 3.
Figure 3. A successful message post
If not, you likely get a PHP stack trace, informing you that the database connection failed or the INSERT statement did not work.
With the message add script working, it's time to build the messages.php script, which returns the list of messages. This script is shown in Listing 4.
Listing 4. messages.php
<?php header( 'Content-type: text/xml' ); mysql_connect( 'localhost:/tmp/mysql.sock', 'root', '' ); mysql_select_db( 'chat' ); if ( $_REQUEST['past'] ) { $result = mysql_query('SELECT * FROM chatitems WHERE id > '. mysql_real_escape_string( $_REQUEST['past'] ). '>
This script is a little more complicated. The first thing it does is put together the query. There are two possibilities here:
- If a
pastparameter was provided, then the script returns only messages past the specified ID.
- If no
pastparameter is specified, then all of the messages are returned.
The reason for the
past parameter is that you want clients
to be smart. You want the client to remember what messages it's already seen and ask for only those messages past the ones it already has. The client logic is easy enough, it just keeps the highest value ID that it finds and sends that as the
past parameter. In the beginning it can send 0 as the value, which is the same as specifying nothing at all.
The second half of the script does the retrieval of the records from the query result set and encodes them into XML. If this part of the script works, then you see something similar to Figure 4 when you go to the page in your browser of choice.
Figure 4. The chat message list
That's everything you need for the server. Of course, you can add whatever logic you want, extra channels, user validation and login, and so on. For the purposes of this experimental chat app, this script works nicely. Now you can build the iOS application that will use this server.
Building the client
The iOS IDE is called XCode. If you don't have it, you need to download it from the Apple Developer Site (see Resources). The most recent production version is XCode 3, and that's what I use for the screen captures here. There is a newer version called XCode 4, which integrates the User Interface editor into the IDE, but that version is still in preview mode at this point.
With XCode installed, it's time to build the application using the New Project wizard as in Figure 5.
Figure 5. Building a view-based iPhone app
The easiest type of application to start with is a view-based application. This kind of app allows you to place controls wherever you choose and leaves most of the UI design to you. After you select the controls, select either iPhone or iPad. This choice is concerned with the device you want to simulate on. You can write the code so that it works on iPhone or iPad, or any other i-device Apple comes up with next.
After you click Choose, you are asked to name the application. I called mine "iOSChatClient," but you can name it whatever you like. After you give it a name, the XCode IDE builds the core application files. From here, compile it once and start it up just to make sure that everything looks right.
Creating the user interface
After the application is created, you can develop the interface. The place to start is with the view controller XIB file, which is located in the Resources folder. By double-clicking on that folder, you bring up the Interface Builder which is the UI toolkit.
Figure 6. The interface layout
Figure 6 shows how I laid out the three controls. At the top is a text box for entering the message you want to send. To the right of that text box is the Send button. And below that is a UITableView object that shows all the chat items.
I could go into detail about how to set all this up in Interface Builder, but I recommend that you download the project code and play with it yourself. Feel free to use the project as a template for your own app.
Creating the view controller
That's really it for the user interface. The next task is to go back to the XCode IDE and add some member variables, properties, and methods to the view controller class definition as in Listing 5.
Listing 5. iOSChatClientViewController.h
#import <UIKit/UIKit.h> @interface iOSChatClientViewController : UIViewController <UITableViewDataSource,UITableViewDelegate> { IBOutlet UITextField *messageText; IBOutlet UIButton *sendButton; IBOutlet UITableView *messageList; NSMutableData *receivedData; NSMutableArray *messages; int lastId; NSTimer *timer; NSXMLParser *chatParser; NSString *msgAdded; NSMutableString *msgUser; NSMutableString *msgText; int msgId; Boolean inText; Boolean inUser; } @property (nonatomic,retain) UITextField *messageText; @property (nonatomic,retain) UIButton *sendButton; @property (nonatomic,retain) UITableView *messageList; - (IBAction)sendClicked:(id)sender; @end
From the top, I added UITableViewDataSource and UITableViewDelegate to the class definition. This code is used to drive the message display. There are methods in the class that get called back to feed both data and layout information to the table view.
The instance variables are broken into five groups. At the top are the object references to the various UI elements, the text field for the message to send, the send button, and the message list.
Below that is the buffer to hold the returned XML, the list of messages, and the last
ID seen. That lastID starts out at zero but gets set to the maximum ID value that you
see for any messages. It's then sent back to the server as the value of the
past parameter.
The timer is what fires every couple of seconds to look for new messages from the server. And the last section includes all the member variables needed to parse the XML. There are a lot of them because the XML parser is a callback-based parser, which means that it holds a lot of state in the class.
Below the member variables are the properties and the click handler. These are used by the Interface Builder to hook up the interface elements to this controller class. In fact, with all this in the view controller, it would be a good time to go back to the Interface Builder and use the connector controls to connect the message text, send button, and message list to their corresponding properties, and to connect the
Touch Inside event to the
sendClicked method.
Building the view controller code
With the view controller header out of the way, you're ready to dig into the meat of the project and to implement the view controller. I break this up across several listings even though it's just in one file so that I can explain each section a little more easily.
The first section, Listing 6, covers the application startup and the initialization of the view controller.
Listing 6. iOSChatClientViewController.m – Starting up
#import "iOSChatClientViewController.h" @implementation iOSChatClientViewController @synthesize messageText, sendButton, messageList; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { lastId = 0; chatParser = NULL; } return self; } - (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { return YES; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (void)viewDidUnload { } - (void)dealloc { [super dealloc]; }
This is pretty standard iOS code. There are some callbacks for variable system events such as memory warnings and the de-allocation. In a production app, you want to handle all of these items gracefully, but for the purposes of this example application I didn't want to overcomplicate matters.
The first real task comes in making the
GET request to the
messages.php script. Listing 7 shows the code for this.
Listing 7. iOSChatClientViewController.m – Getting the messages
- (void)getNewMessages { NSString *url = [NSString stringWithFormat: @"", lastId, time(0) ]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:url]]; [request setHTTPMethod:@"GET"]; NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self]; if (conn) { receivedData = [[NSMutableData data] retain]; } else { } } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { if (chatParser) [chatParser release]; if ( messages == nil ) messages = [[NSMutableArray alloc] init]; chatParser = [[NSXMLParser alloc] initWithData:receivedData]; [chatParser setDelegate:self]; [chatParser parse]; [receivedData release]; [messageList reloadData]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: [self methodSignatureForSelector: @selector(timerCallback)]]; [invocation setTarget:self]; [invocation setSelector:@selector(timerCallback)]; timer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:NO]; } - (void)timerCallback { [timer release]; [self getNewMessages]; }
The code starts with the
getNewMessages method. This method creates the request and starts it by building an
NSURLConnection. It also creates the data buffer that holds the response data. The three event handlers,
didReceieveResponse,
didReceiveData, and
connectionDidFinishLoading, all handle the various phases of loading the data.
The
connectionDidFinishLoading method is the most important because it starts the XML parser that reads through the data and picks out the messages.
The final method here,
timerCallback, is used by the timer to start the request of the new message. When the timer goes off, the
getNewMessages method is called, which starts the process again, culminating with creating a new timer that when it times out starts the message retrieval process again, and so on.
The next section, Listing 8, deals with the parsing of the XML.
Listing 8. iOSChatClientViewController.m – Parsing the messages
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ( [elementName isEqualToString:@"message"] ) { msgAdded = [[attributeDict objectForKey:@"added"] retain]; msgId = [[attributeDict objectForKey:@"id"] intValue]; msgUser = [[NSMutableString alloc] init]; msgText = [[NSMutableString alloc] init]; inUser = NO; inText = NO; } if ( [elementName isEqualToString:@"user"] ) { inUser = YES; } if ( [elementName isEqualToString:@"text"] ) { inText = YES; } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if ( inUser ) { [msgUser appendString:string]; } if ( inText ) { [msgText appendString:string]; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ( [elementName isEqualToString:@"message"] ) { [messages addObject:[NSDictionary dictionaryWithObjectsAndKeys:msgAdded, @"added",msgUser,@"user",msgText,@"text",nil]]; lastId = msgId; [msgAdded release]; [msgUser release]; [msgText release]; } if ( [elementName isEqualToString:@"user"] ) { inUser = NO; } if ( [elementName isEqualToString:@"text"] ) { inText = NO; } }
This XML parser should be familiar to anyone who knows SAX parsing. You give it some XML, and it calls you back when tags are opened, or closed, when text is found, and so on. It's an event-based parser rather than a DOM-based parser. Event parsers have the advantage that they have a light memory footprint. But the disadvantage is that they are a bit harder to use because all of the state needs to be stored in the host object during parsing.
The process starts with all of the member variables such as
msgAdded,
msgUser,
inUser, and
inText initialized to an empty string or false. Then as each of the tags is started in the
didStartElement method, the code looks at the tag name and sets the appropriate
inUser or
inText Boolean. From there, the
foundCharacters method handles adding the text data to the appropriate string. The
didEndElement method then handles the close of the tag by adding the parsed message to the message list when the end of the
<message> tag is found.
Now you need some code to display the messages. This is shown in Listing 9.
Listing 9. iOSChatClientViewController.m – Displaying the messages
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)myTableView numberOfRowsInSection: (NSInteger)section { return ( messages == nil ) ? 0 : [messages count]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath { return 75; } - (UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = (UITableViewCell *)[self.messageList dequeueReusableCellWithIdentifier:@"ChatListItem"]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChatListItem" owner:self options:nil]; cell = (UITableViewCell *)[nib objectAtIndex:0]; } NSDictionary *itemAtIndex = (NSDictionary *)[messages objectAtIndex:indexPath.row]; UILabel *textLabel = (UILabel *)[cell viewWithTag:1]; textLabel.text = [itemAtIndex objectForKey:@"text"]; UILabel *userLabel = (UILabel *)[cell viewWithTag:2]; userLabel.text = [itemAtIndex objectForKey:@"user"]; return cell; }
These are all of the methods defined by the
UITableViewDataSource and
UITableViewDelegate interfaces. The most important one is the
cellForRowAtIndexPath method, which creates a custom UI for the list item and sets its text fields to the appropriate text for that message.
This custom list item is defined in a new
ChatListItem.xib
file that you need to create in the Resources folder. In that file, you create a new
UITableViewCell item that has two labels in it, tagged 1
and 2. This file, along with all the other code, is available in the downloadable
project (see Download).
The code in the
cellForRowAtIndexPath method allocates one of these
ChatListItem cells, then sets the text field for the labels to the text and user values that we found for that message.
I know it's a lot to take in, but you are almost at the end. You already have the code to start up the view, get the message XML, parse it, and display the messages. The only thing that remains is to write the code that sends the message.
The first part of building that code is to create a setting for the user name. iOS applications can define custom settings that go in the Settings control panel. To create a setting you need to use the New File wizard to create a settings bundle in the Resources folder. Then you delete it down to just a single setting using the settings editor in Figure 7.
Figure 7. Setting up the settings
Then you define that you want the setting to be titled
User
and have the key
user_preference. From there, you can use this preference to get the user name for the message sending code in Listing 10.
Listing 10. iOSChatClientViewController.m – Sending the message
- (IBAction)sendClicked:(id)sender { [messageText resignFirstResponder]; if ( [messageText.text length] > 0 ) { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSString *url = [NSString stringWithFormat: @""]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:url]]; [request setHTTPMethod:@"POST"]; NSMutableData *body = [NSMutableData data]; [body appendData:[[NSString stringWithFormat:@"user=%@&message=%@", [defaults stringForKey:@"user_preference"], messageText.text] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:body]; NSHTTPURLResponse *response = nil; NSError *error = [[[NSError alloc] init] autorelease]; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; [self getNewMessages]; } messageText.text = @""; } - (void)viewDidLoad { [super viewDidLoad]; messageList.dataSource = self; messageList.delegate = self; [self getNewMessages]; } @end
This is the click handler code for the Send Message button. It creates a
NSMutableURLRequest that has the URL for the
add.php script. It then sets the body of the message to a string that has the user and message data encoded in POST format. It then uses an
NSURLConnection to synchronously send the message data to the server and starts a message retrieval using
getNewMessages.
The
viewDidLoad method at the bottom of this file is what is called when the view loads. It starts the message retrieval process and connects the message list with this object so that the message list knows where to get its data.
With all of this coded, it's time to test the application. That starts with setting the user name in the Settings page in Figure 8.
Figure 8. The Settings page
From here, you click the iOSChatClient application, and the settings page in Figure 9 displays.
Figure 9. Setting the user name
Then you return to the application just as you would on the phone and type a message using the keyboard as in Figure 10.
Figure 10. Typing a new message
Then pressing the send button we see that the message went to the server, was posted,
and then returned from
messages.php as you can see in Figure 11.
Figure 11. The completed chat application
You'll note from the code that there is no direct connection between the send button and the message list. So the only way for the message to make it into the list is through the server successfully inserting the data into the database. Then the
message.php code successfully returns the message for display in the message list.
Conclusions
It's certainly a lot to take in, but you learned a lot from this article. You did some database work with XML on the backend. You built an iOS application with a custom user interface that sends and retrieves data from the server. You used the XML parser to chew up the response XML from the server. And you built a custom list UI to make the messages look pretty.
Where you go next with this is up to you. Apple has given you the tools to implement whatever vision you want on the iPhone or the iPad. And this article has given you a roadmap to building your own network enabled app. I encourage you to jump in and give it a try. If you do build something cool please let me know and I'll be sure to check it out on the App Store.
Download
Resources
Learn
- The iOS Reference Library: Visit this great online resource for learning all about the iOS tool chest available to you.
- The PHP site: Explore the best reference for PHP that's available.
- The W3C: Visit a great site for standards, in particular the XML standard is relevant to this article.
- Apple documentation on the Objective-C language: Brush up on the unique syntax of the Objective-C language.
- Apple Developer Portal: Get the IDE, provision your test devices and upload finished apps to the. | http://www.ibm.com/developerworks/opensource/library/x-ioschat/index.html | CC-MAIN-2014-35 | refinedweb | 3,721 | 54.02 |
Applicable to us? Needs review.
Bill
-------- Original Message --------
Subject: readdir_r considered harmful
Date: Tue, 1 Nov 2005 03:57:03 +0000
From: Ben Hutchings <ben@decadentplace.org.uk>
To: bugtraq@securityfocus.com, full-disclosure@lists.grok.org.uk
readdir_r considered harmful
============================
Issued by Ben Hutchings <ben@decadentplace.org.uk>, 2005-11-01.
Background
----------
The POSIX readdir_r function is a thread-safe version of the readdir
function used to read directory entries. Whereas readdir returns a
pointer to a system-allocated buffer and may use global state without
mutual exclusion, readdir_r uses a user-supplied buffer and is
guaranteed to be reentrant. Its use is therefore preferable or even
essential in portable multithreaded programs.
Problem Description
-------------------
The length of the user-supplied buffer passed to readdir_r is
implicit; it is assumed to be long enough to hold any directory entry
read from the given directory stream. The length of a directory entry
obviously depends on the length of the name, and the maximum name
length may vary between filesystems. The standard means to determine
the maximum name length within a directory is to call
pathconf(dir_name, _PC_NAME_MAX). This method unfortunately results
in a race condition between the opendir and pathconf calls, which
could in some cases be exploited to cause a buffer overflow. For
example, suppose a setuid program "rd" includes code like this:
#include <dirent.h>
#include <unistd.h>
int main(int argc, char ** argv)
{
DIR * dir;
long name_max;
struct dirent * buf, * de;
if ((dir = opendir(argv[1]))
&& (name_max = pathconf(argv[1], _PC_NAME_MAX)) > 0
&& (buf = (struct dirent *)malloc(
offsetof(struct dirent, d_name) + name_max + 1))
{
while (readdir_r(dir, buf, &de) == 0 && de)
{
/* process entry */
}
}
}
Then an attacker could run:
ln -sf exploit link && (rd link &; ln -sf /fat link)
where the "exploit" directory is on a filesystem that allows a maximum of
255 bytes in a name whereas the "/fat" directory is the root of a FAT
filesystem that allows a maximum of 12 byes.
Depending on the timing of operations, "rd" may open the "exploit" directory
but allocate a buffer only long enough for names in the "/fat" directory.
Then names of entries in the "exploit" directory may overflow the allocated
buffer by up to 243 bytes. Depending on the heap allocation behaviour of
the target program, it may be possible to construct a name that will
overwrite sensitive data following the buffer. If the target program uses
alloca or a variable length array to create the buffer, a classic stack
overflow exploit is possible.
A similar attack could be mounted on a daemon that reads user-
controllable directories, for example a web server.
Attacks are easier where a program assumes that all directories will
have the same or smaller maximum name length than, for instance, its
initial current directory.
Impact
------
This depends greatly on how an application uses readdir_r and on the
configuration of the host system. At the worst, a user with limited
access to the local filesystem could cause a privileged process to
execute arbitrary code. However there are no known exploits.
Mitigation
----------
Many systems don't have any variation in maximum name lengths among
mounted and user-mountable filesystems.
Directory entry buffers for readdir_r are usually allocated on the
heap, and it is relatively hard to inject code into a process through
a heap buffer overflow, though denial-of-service may be more easily
achievable.
Many programmers that use readdir_r erroneously calculate the buffer
size as sizeof(struct dirent) + pathconf(dir_name, _PC_NAME_MAX) + 1
or similarly. On Linux (with glibc) and most versions of Unix, struct
dirent is large enough to hold maximum-length names from most
filesystems, so this is safe (though wasteful). This is not true of
Solaris and BeOS, where the d_name member is an array of length 1.
Affected software
-----------------
The following software appears to be exploitable when compiled for a
system that defines struct dirent with a short d_name array, such as
Solaris or BeOS:
- gcj (all versions to date)
The run-time library functions java.io.File.list and
java.io.File.listFiles call a private function written in C++ that
calls readdir_r using a stack buffer and has a race condition as
described above.
- KDE (versions 3.3.0 to 3.3.2 inclusive; not present in version 3.4.0)
The library function KURLCompletion::listDirectories, used for
interactive URL completion, may start a thread that calls readdir_r
using a stack buffer of type struct dirent (no extra bytes). This
behaviour can be disabled by defining the environment variable
KURLCOMPLETION_LOCAL_KIO.
- libwww (at least versions 3.1 to 5.3.2 inclusive; not yet fixed)
The library functions HTMulti, HTBrowseDirectory (version 3.1) and
HTLoadFile (version 4.0 onwards, when called for a directory)
indirectly call readdir_r using a stack buffer of type struct dirent
(no extra bytes). These functions are used in the process of
- Rudiments library (versions 0.27 to 0.28.2 inclusive; not yet fixed)
The library function directory::getChildName calls readdir_r using
a stack buffer of type struct dirent (no extra bytes).
- teTeX (versions 1.0 to 2.0 inclusive; not present in version 3.0)
The xdvi program included in these versions of teTeX use libwww to
read resources specified by URLs.
- xmail (at least versions 1.0 to 1.21 inclusive; fixed in version 1.22)
Uses readdir_r with variously allocated buffers of type struct dirent
(no extra bytes) when listing mail directories.
The following software may also be exploitable:
- bfbtester (versions 2.0 and 2.0.1; not fixed)
Uses readdir_r with a stack buffer of size struct dirent (no extra
bytes) to list the contents of /tmp (or a specified temporary
directory) and directories in $PATH. (Oh, the irony.)
- insight
Uses Tcl.
- ncftp (at least versions 3.1.8 and 3.1.9, but not version 2.4.3;
not fixed)
Uses readdir_r with a heap buffer with
min(pathconf(gLogfileName, _PC_NAME_MAX), 512) + 8 extra bytes
(where gLogFileName is the path to the log file).
- netwib (versions 5.1.0 to 5.30.0 inclusive; fixed in version 5.3.1.0)
Uses readdir_r with a heap buffer with extra bytes: if pathconf is
available, pathconf("/", _PC_NAME_MAX)+1; otherwise, if NAME_MAX is
available, NAME_MAX+1; otherwise 256.
- OpenOffice.org (at least version 1.1.3)
The code that enumerates fonts and plugins in the appropriate
directories uses a stack buffer of type
long[sizeof(struct dirent) + _PC_NAME_MAX + 1]. I can only assume
this is the result of a programmer cutting his crack with aluminium
filings.
- Pike (versions 0.4pl8 to 7.4.327, 7.6.0 to 7.6.35, 7.7.0 to 7.7.21,
all inclusive; fixed in versions 7.4.328, 7.6.36 and 7.7.22)
Uses readdir_r with a heap buffer with
max(pathconf(path, _PC_NAME_MAX), 1024) + 1 or NAME_MAX + 1025, or 2049
extra bytes, depending on which of these functions and macros are
available. In addition to the race condition described above, there
is a second race condition in the evaluation of the greater of
pathconf(...) or 1024.
- reprepro
Uses readdir_r with a stack buffer of type struct dirent (no extra
bytes). (Also misuses errno following the call.)
- Roxen (versions 1.1.1a2 to 4.0.402 inclusive; fixed in version 4.0.403)
Uses Pike.
- saods9
Uses Tcl.
- Tcl (versions 8.4.2 to 8.5a2 inclusive; fixed in version 8.5a3)
Uses readdir_r with a thread-specific heap buffer padded to a size of
at least MAXNAMLEN+1 bytes. This can be a few bytes too short, though
the heap manager may pad the allocation sufficiently to make up for
this.
- xgsmlib
Uses stack buffer with no extra bytes when listing device directories.
Some proprietary software may also be vulnerable, but I have no way of
testing this. I provided a draft of this advisory to Sun Security
earlier this year on the basis that applications running on Solaris
are most likely to be exploitable, but I have not received any
substantive response. A brief search through the OpenSolaris source
code suggests that it may include exploitable applications, but
apparently no-one at Sun could spare the time to investigate this.
Recommendations
---------------
Many POSIX systems implement the dirfd function from BSD, which
returns the file descriptor used by a directory stream. This allows
pathconf(dir_name, _PC_NAME_MAX) to be replaced by
fpathconf(dirfd(dir), _PC_NAME_MAX), eliminating the race condition.
Some systems, including Solaris, implement the fdopendir function
which creates a directory stream from a given file descriptor. This
allows the opendir,pathconf sequence to be replaced by
open,fpathconf,fdopendir. However this function is much less widely
available than dirfd..
Suggested code for calculating the required buffer size for readdir_r
follows.
#include <sys/types.h>
#include <dirent.h>
#include <limits.h>
#include <stddef.h>
#include <unistd.h>
/* Calculate the required buffer size (in bytes) for directory *
* entries read from the given directory handle. Return -1 if this *
* this cannot be done. *
* *
* If you use autoconf, include fpathconf and dirfd in your *
* AC_CHECK_FUNCS list. Otherwise use some other method to detect *
* and use them where available. */
size_t dirent_buf_size(DIR * dirp)
{
long name_max;
# if defined(HAVE_FPATHCONF) && defined(HAVE_DIRFD) \
&& defined(_PC_NAME_MAX)
name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX);
if (name_max == -1)
# if defined(NAME_MAX)
name_max = NAME_MAX;
# else
return (size_t)(-1);
# endif
# else
# if defined(NAME_MAX)
name_max = NAME_MAX;
# else
# error "buffer size for readdir_r cannot be determined"
# endif
# endif
return (size_t)offsetof(struct dirent, d_name) + name_max + 1;
}
An example of how to use the above function:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv)
{
DIR * dirp;
size_t size;
struct dirent * buf, * ent;
int error;
if (argc != 2)
{
fprintf(stderr, "Usage: %s path\n", argv[0]);
return 2;
}
dirp = opendir(argv[1]);
if (dirp == NULL)
{
perror("opendir");
return 1;
}
size = dirent_buf_size(dirp);
printf("size = %lu\n" "sizeof(struct dirent) = %lu\n",
(unsigned long)size, (unsigned long)sizeof(struct dirent));
if (size == -1)
{
perror("dirent_buf_size");
return 1;
}
buf = (struct dirent *)malloc(size);
if (buf == NULL)
{
perror("malloc");
return 1;
}
while ((error = readdir_r(dirp, buf, &ent)) == 0 && ent != NULL)
puts(ent->d_name);
if (error)
{
errno = error;
perror("readdir_r");
return 1;
}
return 0;
}
The Austin Group should amend POSIX and the SUS in one or more of the
following ways:
1. Standardise the dirfd function from BSD and recommend its use in
determining the buffer size for readdir_r.
2. Specify a new variant of readdir in which the buffer size is explicit
and the function returns an error code if the buffer is too small.
3. Specify that NAME_MAX must be defined as the length of the longest
name that can be used on any filesystem. (This seems to be what many
or most implementations attempt to do at present, although POSIX
currently specifies otherwise.) | http://mail-archives.apache.org/mod_mbox/apr-dev/200511.mbox/%3C436E3592.6070004@rowe-clan.net%3E | CC-MAIN-2014-52 | refinedweb | 1,789 | 57.37 |
.
The task
I’m a member of many groups on Meetup. It’s often useful for me to get information using the official Meetup API rather than go around clicking on a Web site on or a mobile app. Why do by hand what I can do much more efficiently and correctly with code?
Here’s a very simplified example of something I might want to do with Meetup. I’ve been active in the Pittsburgh Code and Supply community, which has a Meetup site with a packed calendar of events (it’s on hiatus now in December for the holidays, but is otherwise very active). Maybe I want to find out what upcoming events they are, and search for events of interest according to some criteria. For our toy example here, let’s say I want to find the ten upcoming events and get their names and venue names, and make sure there’s at least one event that has a name and venue name already set up (sometimes, an event is proposed but no venue has been found yet).
A test
Yesterday, day 3 of this article series, I mentioned liking using HSpec, so let’s use HSpec.
{-# LANGUAGE OverloadedStrings #-} import WreqExample (GroupId, eventName, venueName, getMeetupEventInfos) import Test.Hspec ( Spec, hspec, describe, it , shouldSatisfy, shouldNotSatisfy ) import qualified Data.Text as Text
We are using the
text
packed Unicode string type, because that’s what
wreq
uses.
OverloadedStrings is a convenient GHC extension that allows
string literals in code to be treated as
Text values rather than
String. Ollie discusses this extension in his 2014 Days of GHC Extensions.
Also, since I’m operating in test-driven development style, I wrote
this test first, before writing the
WreqExample module: I only wrote
the imports for what I need for the test.
spec :: Spec spec = describe "wreq" $ do it "there are named, located Pittsburgh Code and Supply events coming up" $ do -- Warning! This is a stateful test going out to the Web. events <- getMeetupEventInfos pittsburghCodeAndSupplyId events `shouldNotSatisfy` null events `shouldSatisfy` any (\event -> (not . Text.null . eventName) event && (not . Text.null . venueName) event) pittsburghCodeAndSupplyId :: GroupId pittsburghCodeAndSupplyId = "13452572"
Module signatures
If Haskell had module signatures, like Standard ML and OCaml do, I would write an explicit module signature for the module I intend to implement that will conform to that signature, but Haskell doesn’t, so the best we can do is operate in “duck typing” manner at the module level, relying implicitly on compilation to fail on import of a conforming module implementation rather than on matching against an explicit signature without the need for an implementation.
Here are the types we need (in a pseudo-syntax as though Haskell had module signatures):
type GroupId -- abstract type EventInfo -- abstract -- abstract type accessors eventName :: EventInfo -> Text venueName :: EventInfo -> Text getMeetupEventInfos :: GroupId -> IO [EventInfo]
Implementation
Imports
import Network.Wreq (Options, defaults, param, getWith, asValue, responseBody) import Data.Text (Text) import Data.Aeson (Value) import Control.Lens (view, set, toListOf) import Data.Aeson.Lens (key, _Array, _String)
Types
-- | Information that we care about from a Meetup event. data EventInfo = EventInfo { eventName :: Text , venueName :: Text } deriving (Show) -- | A valid Meetup group ID. type GroupId = Text
The Web client part
Since we’re only making one request, and are not doing any error
handling, but letting
wreq throw exceptions instead, the Web client
part is very brief. The Meetup API allows returning information as
JSON.
meetupEventsUrl :: String meetupEventsUrl = ""
We perform a
GET with query parameters.
wreq uses lens as its
domain-specific language for creating options for
GET, so let’s
create a
wreq
Options value, by setting the parameters one after
another using a builder pattern starting with the
wreq
defaults:
eventsOptions :: GroupId -> Options eventsOptions groupId = set (param "page") ["10"] ( set (param "order") ["time"] ( set (param "status") ["upcoming"] ( set (param "group_id") [groupId] ( set (param "format") ["json"] defaults))))
We begin by going out to the Web to get back a response, which is a
lazy
ByteString:
getMeetupEventInfos :: GroupId -> IO [EventInfo] getMeetupEventInfos groupId = do response <- getWith (eventsOptions groupId) meetupEventsUrl
The JSON part
Then we parse the lazy
ByteString response, including the headers
and the body, into an untyped JSON object, an
aeson
Value:
jsonResponse <- asValue response
More precisely,
Value is unityped:
type Object = HashMap Text Value type Array = Vector Value data Value = Object !Object | Array !Array | String !Text | Number !Scientific | Bool !Bool | Null
The lens part
It was annoying figuring out from the official Meetup API site what fields I needed from the response and what their types were supposed to be. In practice I just saved off JSON from a representative query and looked at some events to see what I wanted. I was told where to find the automatically generated documentation of all the API methods but it was not ideal. A later Day of Hackage will discuss what I did about this problem.
We extract the list of events, using a traversal to get the whole
list, which is encoded as a JSON array in the top level JSON object’s
results field:
let events = toListOf (responseBody . key "results" . _Array . traverse ) jsonResponse
Here we use
toListOf from lens with a traversal and a JSON object to
pull out everything from that traversal.
Finally, since we only want, for each event, its name and its venue’s name (the venue’s name is actually a field in a venue object):
return (map jsonToEventInfo events)
We again use lens, at the level of an individual event object, to extract what we want from it:
-- | Extract our typed data model from an untyped JSON object. jsonToEventInfo :: Value -> EventInfo jsonToEventInfo json = EventInfo { eventName = view (key "name" . _String) json , venueName = view (key "venue" . key "name" . _String) json }
Here we use the
view function of
lens, to apply a lens to the JSON
object to pull a field out of it.
And we’re done! We’ve written a script that looks pretty much like what you’d write in Perl or Python. It will also “fail” in similar ways, because we’re basically not using any types at all; even the final result just has strings, which may or may not be empty, whatever that’s supposed to mean. For example, if you try to find a field by a string key that doesn’t exist, the particular code here will just silently give back an empty string. Can we do better? Yes, there are various ways to do better. Stay tuned for a later Day of Hackage.
Lens operator syntax
If you’ve already used
wreq or
lens, you may have noticed
something strange above: I didn’t use any
lens operator syntax. This
was deliberate. Although the
wreq tutorial gives a
little bit of background on
lens,
the reality is that when some friends who were not experienced lensers
or Haskellers asked me how I do Web client programming in Haskell, and
I pointed to
wreq as being pretty cool, they got immediately stuck
on the lens stuff. Looking back at the tutorial, I do see that it
jumps straight into operator soup. This is unfortunate. You can
immediately use libraries like
wreq without having the lens
operators memorized already. You have to understand some facts (such
as the use of the function composition operator to compose lenses) and
have an idea of how the types work out, but one thing you don’t need
is the funny operators. I think it’s best to understand how to do
things without operators before starting to use them as a convenient
shortcut.
For example, an idiomatic way to set the options object, as presented
in the “whirlwind tour” section of the
wreq tutorial, is:
import Control.Lens ((&), (.~)) eventsOptions :: GroupId -> Options eventsOptions groupId = defaults & param "format" .~ ["json"] & param "group_id" .~ [groupId] & param "status" .~ ["upcoming"] & param "order" .~ ["time"] & param "page" .~ ["10"]
I don’t like the idea of newcomers to this library just copying and pasting stuff without understanding what it does, or getting the impression that these operators are somehow built into the Haskell language or required for using the library. People really do get these impressions.
I happen to like the reverse function operator
& a lot, although
it’s not as suggestive as the exact same reverse function operator in
many other languages (such as F#, OCaml, Elm, Elixir) in the form of a pipe
instead
|>,
so I feel OK about using it.
But the
.~ is I think not very suggestive to newcomers to
lens. Is
set lens newValue object so much worse to write or read than
object & lens .~ newValue?
(Update of 2014-12-12) Thinking compositionally
One thing that is unfortunately lost if you use pipeline application
operators such as
& is the compositionality that underlies the
power of lenses. So here is a refactoring of
eventsOptions that
shows how to best think of what we are doing, which is creating a
“builder” and applying it:
eventsOptionsRefactored :: GroupId -> Options eventsOptionsRefactored groupId = builder defaults where builder = eventsOptionsBuilder groupId -- | Recall: type is sugar for GroupId -> (Options -> Options) eventsOptionsBuilder :: GroupId -> Options -> Options eventsOptionsBuilder groupId = set (param "page") ["10"] . set (param "order") ["time"] . set (param "status") ["upcoming"] . set (param "group_id") [groupId] . set (param "format") ["json"]
Note the separation of concerns here: instead of thinking of building
an
Options object as
- starting with a default
- successively applying an extra setting to it
we think of
- creating an options builder through composition
- applying the builder to the default
Partial application in functional programming is used here to
implement the builder pattern:
eventsOptionsBuilder takes one
argument, and returns an
Options transformer of type
Options ->
Options.
Code golf?
To illustrate both the up sides and down sides of using operators (but in this case mostly down sides, I think), here is a code golf version of the entire code:
import Network.Wreq (Options, defaults, param, getWith, asValue, responseBody) import Data.Text (Text) import Control.Lens ((&), (.~), (^.), (^..)) import Data.Aeson.Lens (key, _Array, _String) import Control.Arrow ((>>>), (&&&)) meetupEventsUrl :: String meetupEventsUrl = "" -- | A valid Meetup group ID. type GroupId = Text -- | For searching for events in a Meetup group. eventsOptions :: GroupId -> Options eventsOptions groupId = defaults & param "format" .~ ["json"] & param "group_id" .~ [groupId] & param "status" .~ ["upcoming"] & param "order" .~ ["time"] & param "page" .~ ["10"] -- | Code golf version. Don't do this? getMeetupNameAndVenues :: GroupId -> IO [(Text, Text)] getMeetupNameAndVenues groupId = getWith (eventsOptions groupId) meetupEventsUrl >>= asValue >>= ((^.. responseBody . key "results" . _Array . traverse) >>> map ((^. key "name" . _String) &&& (^. key "venue" . key "name" . _String) ) >>> return )
In a way, this looks cool because the piping left to right reads well and naturally, if you know all the operators and are happy with operator sectioning syntax and point-free combinators. But when I showed this to friends who are not so fluent in Haskell, they didn’t like this. Also, note that I made concessions in order to arrange this pipeline. I lost the comments, the intermediate named sub-computations (very useful for finer-grained testing), and even my custom result type (resorting to just tupling). I feel something has been lost by writing in this style even though part of me secretly likes it.
An interview with Bryan O’Sullivan
Recently (September 2015), The Haskell Cast interviewed Bryan
O’Sullivan. I highly recommend listening to the whole thing. He
had stories to tell about how he got into Haskell, how he ended up
writing all these libraries, and how he goes about designing them and
what his goals are when implementing them. Note that
aeson and
text, which everyone uses, are his creations. Thank you, Bryan, for
all you’ve done for the Haskell community!
Lens resources
Gabriel Gonzalez wrote a lens tutorial that is useful. Thank you, Gabriel, for writing tutorials not only on your own libraries, but for others as well!
Conclusion
For day 4, I presented a tiny example of use of
wreq with
aeson
and
lens to perform a simple task of getting information from the
Web, and tried to make
wreq more accessible by not requiring use of
lens operators up front.
All the code
All my code for my article series are at this GitHub repo. | https://conscientiousprogrammer.com/blog/2015/12/04/24-days-of-hackage-2015-day-4-wreq-web-client-programming-with-notes-on-lens-and-operator-syntax/ | CC-MAIN-2022-33 | refinedweb | 1,999 | 60.24 |
A.
Correcting stuck or hot pixels in images
Hot or stuck pixels in a camera are annoying and other than replacing the ccd chip, nothing can be done about it with regard to the hardware. More on this in this illuminating article. Sometimes the camera can map out bad pixels but that won't fix old images, so the plan is to create a small program that does this on existing images.
PIL, the Python Imaging Library. There is even a version for Python 3 made available by Christoph Gohlke, although you will have to replace all relative import statements with absolute one if you want that to work. (Simply run the the installer, open allPIL, the Python Imaging Library. There is even a version for Python 3 made available by Christoph Gohlke, although you will have to replace all relative import statements with absolute one if you want that to work. (Simply run the the installer, open all
*.pyfiles in site-packages/PIL and replace all occurrences of
from . importwith a simple
import. A decent editor like notepad++ or ultraedit can manage that in one go).
The program will take the name of an image file and the x,y position of the pixel to fix as its arguments, e.g.
python correctpixel.py myimage.jpg 1500,1271 and will produce a corrected image with the same name but with a
c_ prefix added, in our example
c_myimage.jpg. It will use a weighted average of the eight neighboring pixels as depicted in this image (the diagonally adjacent pixels have a weight of
1/sqrt.
The program itself is rather straightforward and is shown in its entirety below:
import sys import Image def correct(im,xy,matrix): pim = im.load() x,y = xy maxx,maxy = im.size n = 0 sumr,sumg,sumb = 0,0,0 for dx,dy,w in matrix: px,py = x+dx,y+dy if px<0 or py<0 or px >= maxx or py >= maxy: break n += w r,g,b = pim[px,py] sumr,sumg,sumb = sumr+r*w,sumg+g*w,sumb+b*w pim[x,y]=(int(sumr/n),int(sumg/n),int(sumb/n)) w=1/(2**0.5) matrixd=((0,1,1),(0,-1,1),(1,0,1),(-1,0,1),(-1,-1,w),(-1,1,w),(1,1,w),(1,-1,w)) im = Image.open(sys.argv[1]) xy = tuple(map(int,sys.argv[2].split(','))) correct(im,xy,matrixd) im.save('c_'+sys.argv[1],quality=97)Given an opened image the function
correct()will load the data and the loop of the list of pixels offsets and weights given in its
matrixargument.).
The final lines take care of opening the image (line 22), and converting the pixel position argument to a tuple of integers before calling the
correct() function. The image is saved again with a name prefixed with
c_. The
quality parameter is set to a very high value to more or less save the image with the same jpeg quality a the original image.. | http://michelanders.blogspot.com/2011/08/correcting-stuck-or-hot-pixels-in-nikon.html | CC-MAIN-2017-22 | refinedweb | 509 | 62.78 |
I have a user on Windows 7 that is trying to access a local server with a DNS name of windows.cs. We have two internal DNS servers. The DHCP server assigns users the two internal DNS servers as primary and secondary and then our ISPs DNS as a tertiary DNS server.
Every now and then, the user can't access the website at windows.cs. If I ping it, it says it can't resolve the host name. I flush the DNS cache, and then when I display the dns cache it has the following:
windows.cs - Name does not exist
Yet if I use nslookup, which by default queries the primary DNS server (our internal one) and I query windows.cs, it returns the correct IP address.
So why can't Windows resolve the hostname using ping, but it can when using the nslookup tool? And how do I fix this? won't go to the ISP DNS server again.
The reason ping can't resolve the hostname but nslookup can is because nslookup a low-level tool that bypasses the Windows DNS client. It uses whatever DNS server you tell it to (the first one by default), and does the query on the fly. You can change the DNS server it queries by typing server <host> from the nslookup prompt, where host is the IP or FQDN.
server <host>
The Windows DNS client however will only do queries for entries that are not in its cache (or have expired). Otherwise it returns the cached result.
It's not immediately apparent why the Windows client is using the ISP DNS server. Perhaps it could not resolve the local server recently (due perhaps to being on another network), perhaps the local server was returning errors. Or, perhaps it is not ordered correctly under Advanced TCP/IP settings > DNS.
Personally I prefer to only use local DNS server addresses on workstations (propagated by DHCP), to simplify configuration and avoid issues like this. I'd be curious to know the rationale behind setting the ISPs DNS server on desktops. I can't imagine there being any valid performance reasons, and as far as redundancy goes two is enough on most networks (if not add a third).
The results of nslookup differ from that of ping because of nslookup idiosyncracies and bugs. They are not really relevant to your main problem, however, which is that you've violated the rule that your fallback proxy DNS servers must provide the same view of the DNS namespace as your principal one. Your ISP's proxy DNS server doesn't provide the same view of the DNS namespace as your own proxy DNS servers on your LAN.
nslookup
ping
It would seem that yet another system administrator has fallen foul of the My ISP provides and documents it, so I must use it. fallacy. ☺
By posting your answer, you agree to the privacy policy and terms of service.
asked
4 years ago
viewed
11226 times
active
1 year ago | http://serverfault.com/questions/282755/dns-cant-resolve-hostname-nslookup-can/282995 | CC-MAIN-2015-48 | refinedweb | 504 | 70.73 |
Last?
I’m Looking For:
- Best Practices.
- Applying Modularity
- Prototyping vs. Closures.
- Mixing And Matching With Different JavaScript Libraries (Namespaces).
- Familiar with Dojo (if you’re new to Dojo and coming from jQuery, we recommend our previous blog post “From jQuery to Large Applications”).
- Using the Dojo Build Tool to optimize performance (or would like to use it).
- Your application is single-page, or has sufficiently complex pages.
- Using Dojo 1.6.x.
The SitePen Approach to building web apps is pragmatic and we use the following guidelines and best practices.
Boilerplate File Structure
Every project should start with an organized file structure. To avoid a lot of thrashing and the interruptions that arise from reorganizing mid-development, start with a solid boilerplate. Depicted below is how we like to start our projects. You can create an empty file tree structure to match. Feel free to vary any of the ingredients to suit your specific application requirements, as each application is different.
Why this structure?
As developers, we like having cleanly structured code that’s easy to manage and maintain, but performance constrains us. For example, it’s ideal to have each logical segment of code be stored in a separate file, but delivering hundreds or even thousands of files to the web browser over HTTP will lead to significant performance problems.
The Dojo Build Tool allows you to work with and maintain a logical source code tree, yet deliver a fully-optimized application to your users. You’ll integrate the Dojo Build Tool into your staging and release process to manage this, and the boilerplate helps manage this by providing a source directory tree (
/src/static/dojo , etc.), and a release directory tree (
/release/ ) that are kept separate. When it comes time to build, the Dojo Build Tool will output an optimized and compressed copy of your code in the
/release/ directory. You only need to run the build when you’re ready to deploy your code and need an optimized release suitable for delivering on the web.
Adding Dojo to your Boilerplate
When building large applications you need complete access to all of the Dojo development tools and utilities. When setting up your boilerplate, you can either download a full release and decompress it into your boilerplate source tree, or you can include a checkout from our subversion source code repository.
We generally recommend a Dojo subversion checkout, using svn:externals because it has the added benefit allowing you to more easily move your application to a different branch or tagged version. If you don’t wish to go this route you can grab the full SDK version of the Dojo release and place it in your boilerplate. In either case your copy of the Dojo SDK should be placed in
src/static. For example, you would place
dijit/ in
src/static/dijit/.
Notes: Although you could use the pre-built CDN releases hosted by Google and AOL, our experience is that sooner or later you’ll want to have those files available locally – for your custom build, or troubleshooting and checking the source, even if you rely on the CDN to host parts of your application.
Rebecca Murphey’s Dojo Scaffold is a similar effort to the boilerplate mentioned here. The structure is a little different, but also provides a valuable starting point.
Application Controller
Now that we have our source code tree in place, the next step is determining how to best setup and configure our application, and we do this with an application controller. When we build applications at SitePen, we typically start with an application control pattern that has been refined over the years from our experience building web apps.
You can think of this pattern as the glue that cleanly binds all the various pieces of our applications. It operates on the page level, to implement configuration and an explicit lifecycle over a loosely-coupled architecture for assembling single-page-applications of many moving parts. We find great benefit in application controllers for generally having more explicit control of each application, even for Dojo Mobile applications!
This topic alone is substantial, so we’ve created an entire tutorial on Dojo application controllers and defer to that resource to help you effectively manage the modularity of your application!
Modularity and Namespaces
Application controllers provide extra control over functionality and modules within Dojo. JavaScript has no native module or namespace system, but never fear, Dojo has provided a solution to this problem for years!
An explicit
dojo.provide statement at the top of each file, allows you to load it as just another dependency using
dojo.require:
// contents of /src/static/yourns/Foo.js dojo.provide("yourns.Foo"); // ... contents of module
// contents of /src/static/yourns/Bar.js dojo.provide("yourns.Bar"); dojo.require("yourns.Foo"); // ... contents of module
Overall, Dojo works well with other toolkits. We’ve been careful not to break the work of others. But what happens when another toolkit does not play nicely with others?
One solution we’re involved with is helping define the CommonJS Asynchronous Module Definition (AMD) implementation that’s now beginning to be used in Dojo 1.6. It provides extreme flexibility for defining your modules, their dependencies, and more. Dojo 1.7 and beyond fully adopt the CommonJS AMD approach which will provide a lot more power and flexibility when released.
Prototyping vs. Closures
We typically define our modules as one class or object per file, making them easy to separate with the Dojo Build Tools. JavaScript is a very dynamic language and provides many constructs with different benefits and side effects for how modules are defined.
We use both prototypes and closures as the syntax for writing modules in Dojo. Closures provide ease of creating private methods and an easier to follow syntax, whereas prototypes are commonly used for modules where many instances are expected to be declared. For example,
dijit.form.Button uses the prototype model because there may be many buttons in a page and you’ll possibly have shared fields, whereas some of the encryption libraries in DojoX were deliberately created with closures (or self-executing functions) to prevent access to private variables.
Our blog post on Creating and Enhancing Dojo Classes the right way provides additional insight on this topic.
Summary
You now have a solid starting point for your Dojo application with a boilerplate, the Dojo SDK, an application controller, a module system, and an introduction to prototypes and closures.
In addition to using a Dojo build and optimizing your application for performance, another point of interest is the API documentation viewer. When using the full Dojo source tree, it’s possible to setup the API docs scripts from the outset, so you can see your API documentation as you comment your source code! This allows you to have an API viewer for your application code that works just like Dojo’s API Viewer. Documenting your code and using the API viewer will save you a lot of time in the future as your app begins to grow.
Lastly, you should always make sure you have tests for your modules! Dojo provides tests with every module and you can browse these tests in the Dojo SDK (look for the
test folders in each module directory). Starting with a stubbed out test suite for your application, a sample test or two makes it much easier to work testing into your development process. In practice you might have subdirectories which have their own tests directories, but its much easier to modify and copy existing files that are demonstrated to work.
Next Question Please!
Have a Dojo question you’re just dying to ask? Get your free support here! Or sign-up for the Best JavaScript and Dojo Support available to get all of your questions answered all the time!
Pingback: okeowoaderemi.com | Dojo Guides and Tutorials()
Pingback: DOJO - Build And Optimize Your DOJO Project() | https://www.sitepen.com/blog/2011/05/04/what-is-the-best-way-to-start-a-dojo-project/ | CC-MAIN-2015-40 | refinedweb | 1,322 | 52.9 |
Lettuce uses python’s builtin exception AssertionError to mark tests as failed.
Although in order to describe the assertion with a custom string you would need to do something like:
from lettuce import step @step('some step with "(.*)"'): def some_step(step, from): assert from == 'expectation', \ "Ooops, '%s' should be equal 'expectation', but isn't" % from
nose is a python module that provides a set of assert functions that already have a nice description, and fortunately it still uses AssertionError, which makes nose totally compliant with lettuce.
The example below shows how the step above could be written taking advantage of nose:
from lettuce import step from nose.tools import assert_equals @step('some step with "(.*)"'): def some_step(step, from): assert_equals(from, 'expectation')
It rocks, huh?! | http://lettuce.it/recipes/nose.html | CC-MAIN-2019-13 | refinedweb | 124 | 51.89 |
Sim. In general, e might not be explicitly defined in /any/ of the directly-imported modules, so you must recursively check their imports/re-exports. > If this is hard for the compiler, it's hard for the user too. Someone > understanding your source code has a lot of places to look to find the > target of an import. I think it is rather easy for the compiler actually. Agreed that it provides a slight extra burden on the human reader. But I don't think it is significantly larger than the current burden of knowing the definition site of a function. >! Indeed, the whole motivation was that we _don't_ want a global module namespace, because that would require all modules in all packages to have unique names. >). With explicit namespaces, nothing changes there (except that namespaces must also be recorded in the interface files). Regards, Malcolm | http://www.haskell.org/pipermail/libraries/2006-July/005490.html | CC-MAIN-2014-41 | refinedweb | 147 | 62.07 |
How to Fill Out The Free Application for Federal Student Aid (FAFSA) and Receive Money For College
Ranked #868 in How-To, #8,503 overall | Donates to Children's Defense Fund
There is over $30 Billion Available from the U.S. Federal Govt. For College
Take 5% off an order of $150 or more with coupon code REJULY at ResumeEdge.com (ends 7/18/08)
College Essay Downloads Unlimited Access To 40,000 Essays. New Essays Added Daily. Start Now!
How To Complete the FAFSA For Your State!
HEY, the FAFSA is a federal program. This means that there is no state application form to fill out.
There is only one form to complete.
There is no Texas, Ohio, California and on-and-on form to complete.
There is only one form to complete and all the links you need are right here in front of you on this page. So take advantage of the work we have done and read this page completely and thoroughly.
Download the StudentGuide.pdf to get started!
After you have completed the online form, the college you have been accepted by and plan to attend will receive a copy of the completed FAFSA and that college or university will administer the federal aid and tailor your financial aid package based upon what you can qualify for in the form of student loans, grants and work-study.
Get Your Fafsa Pin ID Number Before You Start To Fill Out Your Financial Aid Form
What You Need To Get Started On Your FAFSA
After You Have Completely Read The FAFSA Student Guide, You Need To Get Your FAFSA PIN Here:
To Complete The FAFSA You Need All This!
Social Security Number. (Be sure it is correct because that's how you get paid at the college you attend.)
Driver's License (if any)
2007 W-2 Forms and other records of money earned
You (and your spouse´s, if you are married) 2007
Parents´ 2007 Federal Income Tax return (if you are a dependent student)
2007 untaxed income records
* Social Security
* Temporary Assistance for Needy Families
* Welfare
* Veterans benefits records
All Current bank statements
Your or Parents current business and investment mortgage information, business and farm records, stock, bond and other investment records
Your alien registration or permanent resident card (if you are not a U.S. citizen
Then, You Can Complete Your FAFSA WorkSheet Here:
Unlocking The $Billions Available For College
What You Need to Know About the FAFSA
We've created a video on filling out the FAFSA at But, before you jump into the video, there are some key pieces of information about the FAFSA you should know before you try to fill it out. This article summarizes many questions and answers you may have about the FAFSA.
The FAFSA is the key to unlocking federal financial aid dollars - over $30 billion in new federal aid in 2005-2006 alone. The FAFSA program is managed by the United States Department of Education, or the Dept. of Ed. The FAFSA is used by the Dept of Ed to determine whether a student, based on the family's income, is eligible for federal grants or federal loans. In addition to being used by the Federal government, most states and many institutions also use the data collected on the FAFSA to determine eligibility for their own grant, loan, and scholarship programs as well.
The FAFSA is a long document that is now completed, almost entirely online at. While paper copies are still available, the online FAFSA is your best option for several reasons. First of all, the online FAFSA allows for the fastest and easiest processing of your information. When you complete the FAFSA online you'll have many opportunities to review your work to make sure it is accurate. If you use the paper document, you have to make sure it's right, mail it in to the Dept of Ed, someone hand enters it into a computer, and then you have to wait until your Student Air Report, or SAR, is returned to check for any errors. With the online FAFSA you receive the SAR electronically within one to five days - about half the time it takes with the mailed FAFSA. And if you complete online and find an error in the SAR, you can quickly and easily correct it online as well. (You can find the complete article at CollegeForKatie.com/articles.html)
Yale To Increase Endowment Spending On Financial Aid - A Boon For Students!
January 7, 2008
Yale University, flush with cash from strong investment returns, said on Monday it would spend roughly 37 percent more of its own money on financial aid for students and scientific research in 2008-2009.
The Ivy League school said it plans to pay out $1.15 billion of its $22.5 billion endowment in the next fiscal year after the endowment grew 28 percent in the fiscal year that ended on June 30. New Haven, Connecticut-based Yale expects to spend $843 million from its endowment in the current fiscal year.
The school also said it will "increase dramatically" the financial aid it awards to undergraduate students, but declined to give details before an announcement it plans to make later this month.
Monday's news comes at a time U.S. lawmakers are urging wealthy universities to make tuition more affordable and roughly one month after Harvard University said it would spend an additional $22 million of its $35 billion endowment to cut tuition costs for middle and upper middle class families.
Harvard and Yale are America's two richest universities and their investment returns have long beaten the Standard & Poor's 500 index returns. Yale earned 28 percent and Harvard 24 percent in the last fiscal year 2006-07. The S&P 500 returned 18 percent in fiscal 2006.
Congress Votes 273 - 149 To Increase Education Spending!
College Cost Reduction Act of 2007, H.R. 2669
Student Loans Are Being Eliminated By Major Universities!
Here are the excerpts if you wish to learn more:
UPenn to eliminate student loans by 2009
Posted Monday, December 17, 2007 at 11:38 am
PHILADELPHIA Officials at the University of Pennsylvania say they'll begin giving loan-free financial aid packages to eligible undergraduates starting in the fall of 2009.
Penn will phase in the changes next fall by eliminating loans for students with family incomes under $100,000.
At the same time, the Ivy League school will reduce need-based loans by 10 percent for students whose families make more than $100,000.
Penn costs about $46,000 a year for tuition and room and board.
Monday's announcement continues a trend among elite private colleges to replace loans with grants in financial aid packages. Harvard University and Swarthmore College announced similar policies this month.
======================================================================
Published in the Columbia Spectator ()
Following Princeton, Schools Switch to Grants
By Keren Daskin
Created 11/26/2007
Since Princeton's 2001 debut as the first private university to eliminate loans in favor of grants, many institutions have followed suit.
Although no other Ivy university has replicated Princeton's move to completely eliminate loans in place of grants, in 2006, Columbia replaced loans with grants for families earning under $50,000 per year. Similar policies were enacted in 2005 by Dartmouth and University of Pennsylvania, which eliminated loans for families whose household income was less than $30,000 and $50,000, respectively.
With a current trend in independent colleges and universities transitioning from loans to grants for students whose annual household income is below $50,000, Wesleyan University is the most recent institution to jump on the financial aid bandwagon.
Source URL:
=====================================================================
Buy 4 weeks of food, get one FREE! Use code PROMO at checkout
Duke University Joins Aid Boost Rush
By JUSTIN POPE - Dec 8, 2007
DURHAM, N.C. (AP) - Duke University on Saturday became the latest elite college to announce a major boost in financial aid. But like even some of its wealthiest peers, it isn't going so far as to guarantee all its students will graduate debt-free.
Instead, Duke - which has a list price of more than $45,000 per year - said it would stop requiring any parental contributions from families earning under $60,000. Students from families earning less than $40,000 will get a full ride, without being asked to take out any loans.
But while better-off students won't have to borrow as much as before, Duke will still ask them to take out some loans. That differs from new policies announced by a handful of prominent colleges recently, including Princeton, Davidson, Amherst and Williams - all of which have replaced loans entirely with grants that don't have to be repaid.
Duke says even with a $5.9 billion endowment, it doesn't have as much to spend per student on financial aid as the schools that have eliminated loans. But even some schools with much bigger endowments than Duke, including Harvard, Yale and Stanford, still ask students to borrow. They argue a degree from an elite school is worth so much over a graduate's lifetime that a small loan is a reasonable investment to require.
At Yale and Stanford, parents earning under $45,000 pay nothing, while at Harvard the threshold is $60,000.
About 40 percent of undergraduates receive aid at Duke, which said total aid spending would rise 17 percent next year to $86 million.
CollegeForKatie.com FAFSA Guestbook
Like this lens? Want to share your feedback, or just give a thumbs up? Be the first to submit a blurb!
You Can Save Even More On Laptops Here
Here!
New YouTube vids
Great Stuff on CafePress
Kiddie Tee's Kids Sweatshirt
Tee Shirts For the Whole Family To Enjoy!
Kiddie Tee's Mousepad
Tee Shirts For the Whole Family To Enjoy!
Periodic Table Calendar Print
Periodic Table T-Shirts, Hats and Mugs! Great for teens in highschool or just entering college.!
Periodic Table Fitted T-Shirt
Periodic Table T-Shirts, Hats and Mugs! Great for teens in highschool or just entering college.!
Create Your Own T-Shirts at Cafe Press
New Amazon Plexo
Mortgage Relief - Stop Foreclosure
Connect with Loan Modification specialists that wi more...1 point
Connect with Loan Modification specialists that will work with you to negotiate with your lender.1 point
Recommended Reading Tips!
New Links Plexo
Welcome To Our College For Katie Project Site
Our website has been developed for parents and you more...1 point
Our website has been developed for parents and young students who want to get a head start on finding money for college.1 point
FAFSA Free Financial Aid Application Form Online Guide
FAFSA Free Financial Aid Application Form Online g more...1 point
FAFSA Free Financial Aid Application Form Online gives you FASFA secrets and how to apply for federal financial aid!1 point
College Costs On The Rise Again For 2007 -2008 School Year on Squidoo
There Seems To Be No End In Sight For The Rising C more...1 point
There Seems To Be No End In Sight For The Rising Costs Of A College Education! To view the full chart, you may visit: point
CollegeForKatie
1 point
Teddi's Corner ~ College & Financial * Fundraising * Affiliates Programs * Your Place to find Great Resources!
Financial aid for college sources. Also- be sure t more...1 point
Financial aid for college sources. Also- be sure to check out the link to "fundraising" & "affiliate programs" area of the site too.1 point
Government Grants Report
Help choosing online government grant programs and more...1 point
Help choosing online government grant programs and how to avoid the bad ones.1 point
MySpace Profile - Preston, 34 years old, Male, ADD more...0 points
MySpace Profile - Preston, 34 years old, Male, ADDISON, Texas, US, MYSpace - CollegeforKatie.com.0 points
Financial Aid, College Scholarships and Student Loans
A comprehensive guide to all things financial aid, more...0 points
A comprehensive guide to all things financial aid, including college scholarships, federal and private student loans.0
Student Loans
Student Loans0 points
Get Deals On Toshiba Notebooks!
Have You Tried Ebay?
Wii is by far the absolute "hottest" game in town right now!
Articles By Preston Hill
by CollegeForKatie
Related Topics
CollegeForKatie Recommends...
- How To Dig Yourself Out Of Massive Debt & Bad Credit
- How To Make Chocolate Fudge That Will Have Your Family and Friends Begging For More! | http://www.squidoo.com/FAFSA | crawl-002 | refinedweb | 2,071 | 60.95 |
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ar.h> #include <arextern.h> int main() { ARControlStruct ctrl; ARNameType schema; ARStatusList status; ARFieldValueList fields; ARFieldValueStruct *field; AREntryIdType entryID; int errorCode; ctrl.cacheId = 0; ctrl.sessionId = 0; strcpy(ctrl.user, "username"); strcpy(ctrl.password, "password"); strcpy(ctrl.authString, ""); strcpy(ctrl.server, "servername"); strcpy(schema, "schemaname"); if(ARInitialization(&ctrl, &status) >= AR_RETURN_ERROR) { printf(status.statusList[0].messageText); printf("\n"); exit(1); } FreeARStatusList(&status, FALSE); fields.numItems = 30; fields.fieldValueList = malloc(30*sizeof(ARFieldValueStruct)); field = fields.fieldValueList; /* this marks the beginning of the items */ /* fieldID and charVal are the values I need to pull from a text file */ field[0].fieldId = 700000000; field[0].value.dataType = AR_DATA_TYPE_CHAR; field[0].value.u.charVal = "Tivoli Event ID"; /* repeat about 30 times ... snip */ if(ARCreateEntry(&ctrl, schema, &fields, entryID, &status) >= AR_RETURN_ ERROR) { printf(status.statusList[0].messageText); printf("\n"); exit(2); } printf(entryID); printf("\n"); ARTermination(&ctrl, most part, unless you call malloc (alloc, realloc, etc.) you don't have dynamic memory so there can't be a memory leak.
Of course, any function that the program calls can assign dynamic memory. If the function returns a pointer to a structure, you need to know if the buffer is static, or if the calling function (your program) needs to free the memory when it's done with the structure.
Your code looks pretty good. Nothing there leaps out and screams "Memory Leak".
Also, no matter how much memory you allocate, when the program ends, it ALL goes back to the operating system. This program doesn't loop so there's no chance of a serious memory leak.
Good Luck,
Kent
>>> I would only get "the return code is" for the value. How do I grab the rest of the information behind the delimiter?
This is a little tricky. You'll need to check to make sure the = isn't in the middle of a pair of ", if it is you know you are in the middle of a value. To do this check from the last strtok result to the current, looking for an odd number of ". If you have an odd number you must be in the middle of a string (unless the string can also have escaped " (\"), in which case you will also need to allow for that). There is no short cut to this really, unless you specify that = is not allowed in a value! Welcome to the wonderful world of lexical parsing :)
fields.fieldValueList = malloc(30*sizeof(ARFieldVa
so before exiting, remember to call free(fields.fieldValueList
Another point - you have a hard-coded number of fields, i.e. 30. It is usual to use a manifest constant to make this easier to maintain.
Putting this all together, your code should have something like this:
Open in new window.
Since they all will be of the format :
field=value
you just have to find the first =. Everything before it is the field, everything after it is the value. In other words, you have to call strtok only once for each line.
ID = strtok(buffer, "=");
TXT = ID + strlen(ID) + 1;
This will work since strtok puts a NULL into the buffer instead of the delimiter, and you simply point after the first delimiter. This will work even with something like:
MySillyValue=six equals = "======"
where ID will be 'MySillyValue', and TXT will be 'six equals = "======"'
I am implementing some of your suggestions. Currently, the number 30 will NOT be a hard coded value(it's hard coded now). The reason for this is that if we want to add/remove fields later, we would be able to edit the text file(or the script(s) that create it), and not have to recompile the entire program. Still figuring out where and how to to pull that data, but that's another topic.
Oh and this works fine:
printf(entryID);
It's actually a char valued defined in one of the headers:
typedef char AREntryIdType[AR_MAX_ENTRY
Open in new window
fieldValue = *(fieldID + strlen(fieldID) + 1);
I assumed it was a stream of fields rather than one value one field, but good point :)
Input file is this:
7000000001="msg=test"
7000000002="classname"
output is this:
user@xubuntu:~/bin$ ./test
7000000001 = "7000000001
7000000002 = "7000000002
Open in new window
Open in new window
Have fun :) | https://www.experts-exchange.com/questions/23117076/C-newbie-Needs-help-and-pointers-no-pun-intended.html | CC-MAIN-2018-34 | refinedweb | 717 | 66.54 |
This is the mail archive of the cygwin mailing list for the Cygwin project.
On Wed, Apr 04, 2012 at 10:02:24AM -0400, Ryan Johnson wrote: >> On 04/04/2012 9:32 AM, Denis Excoffier wrote: >> >Hello, >> > >> >It could be that snprintf() is not properly declared in<stdio.h>. >> According to [1], it's not officially part of c++98 (???). Try >> gnu++98 instead. As for why it's not in c++0x, there's a problem >> with the macros being defined [2] that AFAIK remains unresolved; >> again the workaround is gnu++0x. >> >> [1] >> [2] >> Oh, i should have found these, at least the first one... For c++0x, couldn't this be addressed now? As a start, i can (humbly) propose: --- stdio.h 2012-04-04 14:50:32.000000000 +0159 +++ stdio.h++ 2012-04-04 16:38:21.049273700 +0159 @@ -237,7 +237,7 @@ off_t _EXFUN(ftello, ( FILE *)); #endif #endif -#if !defined(__STRICT_ANSI__) || (__STDC_VERSION__ >= 199901L) +#if !defined(__STRICT_ANSI__) || (__STDC_VERSION__ >= 199901L) || (__cplusplus >= 201103L) #ifndef _REENT_ONLY int _EXFUN(asiprintf, (char **, const char *, ...) _ATTRIBUTE ((__format__ (__printf__, 2, 3)))); Regards, Denis Excoffier. -- Problem reports: FAQ: Documentation: Unsubscribe info: | http://cygwin.com/ml/cygwin/2012-04/msg00152.html | CC-MAIN-2019-26 | refinedweb | 187 | 70.19 |
Fri, 20 Sep 2002, Bryan L. Fordham wrote:
>.
I'm looking more for a narrative, but it should be succinct. Think of a
Cliff's Notes version of "Remailers for Dummies", and you've got an idea
of what I want. We already have a list of functions -- it's called mix.1.
> Would you want client or remailer functions done first?
Client functions are more important in the short term.
> I apologize for my absence from this
No problem -- and thanks for volunteering.
look at me, 3 posts in a few minutes 8)
What's the best way to get mix to work with client software? I played
around (many moons ago) with the mix stuff on windows when reliable was
first released. I seem to remember it being fairly easy to use it in C
programs. Is that still the case? basically, I'd love to be able to
produce (for instance) python bindings for creating and sending mix
messages.
Also, say you wanted to create a java client for mix? Is that even
possible to accomplish in a sane fashion?
--B
as far as testing goes, what clients should we be worried about? I can
think of a few:
pidaho (is it still used?)
qs
what else? I know there are several scripts out there, do we worry
about those? What about mutt and other MUAs?
I assume that we should test if these clients can read the keys from
mix, and successfully send messages to it. What other specifics?
Also, what about testing the remailers themselves?
I'm not sure about how to do this with windows clients, but I'm a huge
fan of automated testing. I've actually been spending a lot of time
doing just that at work recently, so I'm just sort of in that mode, I guess.
--B.
Would you want client or remailer functions done first?
I apologize for my absence from this
--B
Update of /cvsroot/mixmaster/Mix/Src
In directory usw-pr-cvs1:/tmp/cvs-serv25245/Mix/Src
Modified Files:
main.c mix.c mix3.h mixlib.def
Log Message:
add commandline option --config=file
this allows to use alternate configuration file
(for example on encrypted partition)
also make pool directory configurable
Index: main.c
===================================================================
RCS file: /cvsroot/mixmaster/Mix/Src/main.c,v
retrieving revision 1.21
retrieving revision 1.22
diff -u -d -r1.21 -r1.22
--- main.c 18 Sep 2002 23:26:16 -0000 1.21
+++ main.c 20 Sep 2002 19:01:33 -0000 1.22
@@ -155,6 +155,10 @@
#endif /* USE_PGP */
else if ((q = largopt(p, "copies", argv[0], &error)) != NULL) {
sscanf(q, "%d", &numcopies);
+ } else if ((q = largopt(p, "config", argv[0], &error)) != NULL) {
+ strncpy(MIXCONF, q, PATHMAX);
+ MIXCONF[PATHMAX-1] = 0;
+ mix_config(); /* configuration file changed - reread it */
} else if (error == 0 && mix_configline(p) == 0) {
fprintf(stderr, "%s: Invalid option %s\n", argv[0], argv[i]);
error = 1;
@@ -367,7 +371,8 @@
#endif /* USE_SOCK */
"-P, --pop-mail force getting messages from POP3 servers\n\
-G, --generate-key generate a new remailer key\n\
--K, --update-keys generate remailer keys if necessary\n"
+-K, --update-keys generate remailer keys if necessary\n\
+ --config=file use alternate configuration file\n"
#ifdef WIN32SERVICE
"\n\
WinNT service:\n\
Index: mix.c
===================================================================
RCS file: /cvsroot/mixmaster/Mix/Src/mix.c,v
retrieving revision 1.28
retrieving revision 1.29
diff -u -d -r1.28 -r1.29
--- mix.c 18 Sep 2002 23:26:16 -0000 1.28
+++ mix.c 20 Sep 2002 19:01:33 -0000 1.29
@@ -36,7 +36,7 @@
int buf_vappendf(BUFFER *b, char *fmt, va_list args);
/** filenames ************************************************************/
-char MIXCONF[PATHMAX];
+char MIXCONF[PATHMAX] = DEFAULT_MIXCONF;
char DISCLAIMFILE[PATHMAX];
char FROMDSCLFILE[PATHMAX];
char MSGFOOTERFILE[PATHMAX];
@@ -350,11 +350,10 @@
return (0);
}
-void mix_setdefaults()
+static void mix_setdefaults()
{
#define strnncpy(a,b) strncpy(a, b, sizeof(a)); a[sizeof(a)-1] = '\0'
- strnncpy(MIXCONF , DEFAULT_MIXCONF);
strnncpy(DISCLAIMFILE , DEFAULT_DISCLAIMFILE);
strnncpy(FROMDSCLFILE , DEFAULT_FROMDSCLFILE);
strnncpy(MSGFOOTERFILE, DEFAULT_MSGFOOTERFILE);
@@ -562,7 +561,7 @@
read_conf(NYMDB) || read_conf(PIDFILE) );
}
-static int mix_config(void)
+int mix_config(void)
{
char *d;
FILE *f;
@@ -622,18 +621,6 @@
mixdir(MIXDIR, 0);
}
- mixfile(POOLDIR, POOL);
-def GLOBALMIXCONF
f = mix_openfile(GLOBALMIXCONF, "r");
if (f != NULL) {
@@ -650,6 +637,19 @@
mix_configline(line);
fclose(f);
}
+
+ mixfile(POOLDIR, POOL); /* set POOLDIR after reading POOL from cfg file */
+ (IDEXP > 0 && IDEXP < 5 * SECONDSPERDAY)
IDEXP = 5 * SECONDSPERDAY;
if (MAXRANDHOPS > 20)
Index: mix3.h
===================================================================
RCS file: /cvsroot/mixmaster/Mix/Src/mix3.h,v
retrieving revision 1.16
retrieving revision 1.17
diff -u -d -r1.16 -r1.17
--- mix3.h 18 Sep 2002 23:26:16 -0000 1.16
+++ mix3.h 20 Sep 2002 19:01:34 -0000 1.17
@@ -237,6 +237,7 @@
/* configuration, general remailer functions */
int mix_configline(char *line);
+int mix_config(void);
int mix_initialized(void);
int mix_daily(void);
Index: mixlib.def
===================================================================
RCS file: /cvsroot/mixmaster/Mix/Src/mixlib.def,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -d -r1.7 -r1.8
--- mixlib.def 28 Aug 2002 16:29:28 -0000 1.7
+++ mixlib.def 20 Sep 2002 19:01:34 -0000 1.8
@@ -111,3 +111,4 @@
pgpdb_getkey @106
ENTEREDPASSPHRASE @107
PASSPHRASE @108
+ mix_config @109
Update of /cvsroot/mixmaster/Mix/Src
In directory usw-pr-cvs1:/tmp/cvs-serv6694/Mix/Src
Modified Files:
pgpcreat.c
Log Message:
close the comment
Index: pgpcreat.c
===================================================================
RCS file: /cvsroot/mixmaster/Mix/Src/pgpcreat.c,v
retrieving revision 1.10
retrieving revision 1.11
diff -u -d -r1.10 -r1.11
--- pgpcreat.c 18 Sep 2002 23:26:16 -0000 1.10
+++ pgpcreat.c 20 Sep 2002 17:59:25 -0000 1.11
@@ -52,7 +52,7 @@
}
#ifndef MIMIC
else if (in->length < 65536)
-#else /* end of not MIMIC
+#else /* end of not MIMIC */
else if ((type == PGP_PUBKEY || type == PGP_SECKEY || type == PGP_SIG
|| type == PGP_SESKEY || type == PGP_PUBSUBKEY ||
type == PGP_SECSUBKEY) && in->length < 65536)
--->[Quoting Peter Palfrader <peter@...>:]
> > If you find my idea useful, and you can code it in C, I can
> > prepare description of XML file format.
>
> I'm not sure it would be usefull - it would not get adapted widely
> enough.
Could you please use any arguments? Why do not use XML instead
of simple ASCII if this could help with analyzing?
cheers - Sergiusz
--
private: company:
______________________________________________________________
on wallpaper: tldp.org, gnu.org, pld-linux.org, hyperreal.info
On Fri, 20 Sep 2002, Sergiusz Pawlowicz wrote:
> I have an idea to make an option which allow to receive stats
> for mixmaster remailer as XML file.
>=20
> I've started to write analyzer of remailer-stats messagess,
> but it looks that there are difference between output of
> several remailers,
There is Reliable, which is totally broken, then Mixmaster 2.0 which I
don't know the format right now and then Mixmaster 2.9*.
So there should not be more than three formats. You'll also probably
never get Mix2 users to adapt your scheme - If they installed newer
versions they'ld use Mix3. And Reliable hasn't seen updates for even
known bugs in yars.
> and there are problems with timezones,
> because not every remailer have good definitions of them.
Dates and Times in stats are always in UTC. At least with the 2.9
versions of mixmaster. I think it's the same for 2.0*.
> If you find my idea useful, and you can code it in C, I can
> prepare description of XML file format.
I'm not sure it would be usefull - it would not get adapted widely
enough.
yours,
peter
--=20
PGP signed and encrypted | .''`. ** Debian GNU/Linux **
messages preferred. | : :' : The universal
| `. `' Operating System | `-
I have an idea to make an option which allow to receive stats
for mixmaster remailer as XML file.
I've started to write analyzer of remailer-stats messagess,
but it looks that there are difference between output of
several remailers, and there are problems with timezones,
because not every remailer have good definitions of them.
If you find my idea useful, and you can code it in C, I can
prepare description of XML file format.
cheers - Sergiusz
--
private: company:
______________________________________________________________
on wallpaper: tldp.org, gnu.org, pld-linux.org, hyperreal.info
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/mixmaster/mailman/mixmaster-devel/?viewmonth=200209&viewday=20 | CC-MAIN-2017-09 | refinedweb | 1,394 | 58.99 |
cf-ui (not maintained)
This repository is no longer maintained. We decided to merge cf-ui into our internal monorepo and we will keep the future development there. We do not accept pull requests here. However, we plan to synchronize our internal changes with this repository.
Cloudflare UI Framework
cf-ui is a set of over 50 packages used to build UIs at Cloudflare using projects such as React, Fela, Lerna and more.
- Read the introductory blog post →
- Interested in more of our technical decisions? See
cf-ui/discussions→
Usage
Whilst cf-ui is used extensively within Cloudflare, it is also an evolving set of components and therefore can be unstable. We recommend only using this toolset to build interfaces for Cloudflare-internal products. However, feel free to follow along and contribute as we continue to grow this library.
cf-ui meets CSS in JS
We are currently migrating cf-ui to CSS in JS powered by Fela. That means that our components include styles written in JavaScript and you can use them out of the box! However, you need to start using Fela in your project. Follow our migration here.
Getting Started
To view all of the available components and packages, see the
packages/ directory. Do you want to see examples? Check out our documentation.
CSS in JS setup
cf-ui components expect that there is Fela Renderer in the context of your React app. It's the way how to render styles that come with our components into the
<style></style> node. You have to use Fela in your project if you want to use cf-ui. Here's the code example how:
import React from 'react'; import ReactDOM from 'react-dom'; import { StyleProvider } from 'cf-style-provider'; import { Button } from 'cf-component-button'; ReactDOM.render( <StyleProvider> <Button type="primary" onClick={() => console.log('clicked')}> Primary Button </Button> </StyleProvider>, document.getElementById('react-app') );
Do you want to try for yourself?
git clone [email protected]:cloudflare/cf-ui.git cd cf-ui/packages/example npm install npm run build open index.html
Contributing
To get started contributing please see CONTRIBUTING.md
License
cf-ui is BSD Licensed | https://nicedoc.io/cloudflare/cf-ui | CC-MAIN-2019-35 | refinedweb | 357 | 59.4 |
Oxygene and Windows Phone 8 tutorials – Article Index
What is XAML?
XAML stands for Extended Application Markup Language. It is a declarative Markup language which is generally used to create the user interface.
The XAML can be defined directly in the Visual Studio/Expression Blend XAML Editor or the designer.
Let’s take the MainPage.XAML file that is created when creating a new Windows Phone project as example. The MainPage.XAML file looks something like shown below.
Inside the MainPage.xaml, you will notice the series of attributes xmlns followed by colon followed by the name and = symbol and the path to the assembly.
For example,
xmlns: shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
This is the namespace “shell” which represents the Microsoft.Phone.Shell namespace from the Microsoft. Phone assembly. The namespaces are generally created automatically when the controls are created in the designer by dragging and dropping them from the toolbox. You can also manually add them as well.
To Create a Button, one can use the XAML tag with the attributes as shown below
<Button Name="btn1" Content="Click"></Button>
If you want to add the complex property, you can do that as well. For example, assume that you need to set the background color of the button to Blue.
You can do this by setting the Background property of the button as shown below
<Button Name="btn1" Background="Blue"> </Button>
The developers can also use the Nested / Complex attributes as shown below to set the background color.
<Button Name="btn1"> <Button.Background> <SolidColorBrush Color="Blue" /> </Button.Background> </Button>
Few attributes takes special kind of values surrounded by the curly brackets in XAML. For example , in the below screenshot , the style attribute takes the value Static Resource surrounded by curly braces. These kind of values are generally used to bind the data, static resources, style etc. | http://developerpublish.com/oxygene-wp8-xaml-overview/ | CC-MAIN-2017-22 | refinedweb | 312 | 58.18 |
Since blue corner are the Kellyites. Worshipping at the feet of John Kelly and Ed Thorpe they have only one commandment in their holy book: Thou shalt maximise the expectation of log utility of wealth.
This post is sort of about that battle, but more generally it's about two different forms of uncertainty for which humans have varying degrees of stomach for, and how they should be accounted for when deciding how much volatility your trading or investment portfolio should have: "Risk" (which we can think of as known unknowns, or at least the amount of volatility expected from a risk & return model which is calibrated on past data) and "Uncertainty" (which we can think of as unknown unknowns, or to be more precise the unknowability of our risk & return model).
The Kellyites deny the existence of "risk appetite" (or at least they deny it's importance), whereas the Utilatarians embrace it. More seriously both camps seriously underestimate the importance of uncertainty; which will be more the focus of this post.
This might seem somewhat esoteric but in laymans term this post is about answering an extremely critical question, which can be phrased in several equivalent ways:
- What risk target should I have?
- How much leverage should I use?
- How much of my capital should I bet on a given position?
This post was inspired by a twitter thread on this subject and I am very grateful to Rob Hillman of Neuron Advisors for pointing me towards this. I've blogged about this battle before, here (where I essentially address one interesting criticism of Kelly) and I've also talked about Kelly generally here.
If you're unfamiliar with arithmetic and geometric returns it's probably worth rereading the first part of this post here, otherwise you can ignore these other posts (for now!).
Classic Utilitarian portfolio optimisation
To make live easier I'm going to consider portfolios of a single asset. The main difference I want to highlight here is the level of leverage / risk that comes out of the two alternatives, rather than the composition of the portfolio.:
Of course we could also use a different utility function, like one which cares about higher moments, but that will probably make the maths harder and definitely mean we have to somehow define further coefficients establishing an investors pain tolerance for skew and kurtosis.
Subject to: portfolio risk = function of weights and E(asset covariance)<= maximum risk
Which for one asset, with no risk free rate is::
Maximise f.E(r) - b*[f.E(s)]^2
Where f is the leverage factor (f=1 incidentally means fully invested, f=2 means 100% leverage, and so on), r is the expected return, E is the expectation operator, risk s is measured as the standard deviation of returns on the unleveraged asset, b is the coefficient of risk aversion (you'll often see 1/2 here, but like, whatever). This is a quadratic utility function. In this model risk tolerance is an input, here defined as a coefficient of aversion.
Of course we could also use a different utility function, like one which cares about higher moments, but that will probably make the maths harder and definitely mean we have to somehow define further coefficients establishing an investors pain tolerance for skew and kurtosis.
This specification isn't so much in fashion in industry; it's hard enough getting your investors to tell you what their risk appetite is (few people intuitively understand what 150% standard deviation a year feels like, unless they're crypto investors or have money with Mr C. Odey). Imagine trying to get them to tell you what their coefficient of risk aversion is. Easier to say "our fund targets 15% a year volatility" which most people will at least pretend to understand. So we use this version instead:
Maximise portfolio returns = weights.E(asset returns)
Which for one asset, with no risk free rate is:
Maximise f.E(r)
Subject to f.E(s)<=s_max
Where s_max is some exogenous maximum risk tolerance specified by the investor
Importantly (a) maximum risk depends on the individual investors utility function (which is assumed to be monotonically increasing in returns up to some maximum risk at which point it drops to zero - yeah I know, weird) and (b) the return here is arithmetic return (c) we only care about the first two moments since risk is measured using the standard deviation. Again risk is an input into this model (as a tolerance limit this time, rather than coefficient), and the optimal leverage comes out.
Kelly
Under Kelly we choose to find the portfolio which maximises the expectation of the log of final wealth. For Gaussian returns (so again, not caring about the 3rd or higher moments which I won't do throughout this post) it can be shown that the optimal leverage factor f* is:
f* = (r - r_f) / s^2
(If you aren't in i.i.d. world then you can mess around with variations that account for higher moments, or just do what I do - bootstrap)
s* = f*. s = (r - r_f) / s
Notice that this thing on the right is now the Expected Sharpe Ratio. This is my favourite financial formula of all time: optimal Kelly risk target = Expected Sharpe Ratio. It has the purity of E=mc^2. But I digress. Let's take out the risk free rate for consistency:
f* = r / s.
f* = r / s^2
s* = r /.
The battleLet's recap:
Kelly: f* = r / s^2 s* = r / s
Utilitarian: f* = s_max / s s* = s_max
Importantly the two formula don't usually give the same answers (unless r /s = s_max; i.e. the Sharpe Ratio is equal to the risk tolerance), and the relative answer depends on the Sharpe Ratio you're using versus typical risk appetite.
CASE ONE: Kelly leverage< Utilitarian leverage
If you're investing in a long only asset allocation portfolio then a conservative forward looking estimate of Sharpe Ratio (like those in my second book) would be about 0.20. If we assume expected return 2% and standard deviation 10% then the optimal Kelly risk target will be 20%, implying a leverage factor of 2. But that only gives 4% return! If the utilitarian investor is rather gung ho and has a risk appetite of 30% then the optimal leverage for them would be 3.
CASE TWO: Kelly leverage > Utilitarian leverage
If you're running a sophisticated quant fund with a lot of diversification and a relatively short holding period then a Sharpe Ratio of 1.0 may seem reasonable. For example if a stat-arb equity neutral portfolio has expected return 5% and standard deviation 5% (assuming risk free of zero) then the optimal Kelly risk target will be 100%, which implies a leverage factor of 20 (!). But a utilitarian investor may only have a risk appetite of 15%, in which case the optimal leverage will be 3. And indeed most equity neutral funds do run at leverage of about 3.
Case two is a little more complicated, and the solution quoted in a thousand websites and papers is "Most investors find the risk of full Kelly to be too high - we recommend they use half Kelly instead". Frankly this is a bit of a cop-out by the Kelly people, which admits to the existence of risk appetite.
The compromise
I personally believe in risk appetite. I believe that people don't like lumpy returns, and some are more scared of them than others. Nobody has the self discipline to invest for 40 years and completely ignore their portfolio value changes in the interim.
But I also believe that using more than full Kelly is dangerous, insane, and wrong.
So this means the solution is easy. Your risk target should be:
s* = Minimum(r / s , s_max)
Where the first term is of course the Kelly optimum without the risk free, and the second is the risk tolerance beloved of utilitarian investors. And your leverage should be:
f* = Minimum(r / s^2, s_max / s)
What we know, and what we don't know
In case you haven't noticed I find this battle a little tiresome (hence my pretty superficial attempt at 'solving' it), and mainly because it completely ignores something incredibly important. We have two guys in the corner of a room arguing about whether Margin Call or The Big Short is the best film about the 2008 financial crisis (a pointless argument, because both v. good films), whilst a giant elephant is in the corner of the room. Running towards them, about to flatten them. Because they haven't seen it. They're too busy arguing. Have I made the point sufficiently, do you think?
What is the elephant in this particular metaphorical room. It's this. We don't know r. Or s. Of the Sharpe Ratio, r/s (ignoring risk free of course). And without knowing these figures, we don't have a hope in hell of finding the right leverage factor.
We have to come up with a model for them, based on historical data, because that's what quant finance people do. Which means there is the risk that:
- It's the wrong model (non Gaussian returns, jumps, autocorrelation...)
- The parameters of the model aren't stable
- The parameters of the model can't be accurately measured
Parameter uncertainty (and the other issues) isn't such an issue for standard deviation; we are relatively good in finance at predicting risk using past data (R^2 of regressions of monthly standard deviation on the previous month is around 0.6, compared to about 0.01 for means and Sharpe Ratios). So let's pretend that we know the standard deviation.
However the Sharpe Ratio is the key factor in working out the optimal leverage and risk target for Kelly (which even for Utilitarians should act as a ceiling on your aspirations). The sampling distribution of Sharpe Ratio is highly uncertain.
The effect of parameter uncertainty on Sharpe Ratio estimates
There is an easy closed form formula for the variance of the Sharpe Ratio estimate under i.i.d returns given N returns:
w = (1+ 0.5SR^2)/N
(If you aren't in i.i.d. world then you can mess around with formulas that account for higher moments, or just do what I do - bootstrap)
We need an example. Let's just pick an annual Sharpe Ratio out of the air: 0.5. And assume the standard deviation is 10%. And 10 years of monthly data. But if you don't like these figures feel free to play with the example here in google docs land (don't ask for edit access - make your own copy).
Here is the distribution of our Sharpe Ratio estimate:
The concept of "Uncertainty appetite"
Now let's take the distribution of Sharpe Ratio estimate, and map it to the appropriate Kelly risk target:
Yeah, of course it's the same plot, since s* = r/s = SR. You should however mentally block off the negative part of the x-axis, since we wouldn't bother running the strategy here and negative standard deviation is meaningless. And here is the plot for optimal leverage (r/s^2):
So to summarise the mean (and median, as these things are Gaussian regardless of the underlying return series) optimal risk target is 50% and the mean optimal leverage is 5. Negative leverage sort of makes sense in this plot, since if an asset was expected to lose money we'd short it.
At this point the Kellyites would say "So use leverage of 5 or if you're some kind of wuss use half Kelly which is 2.5" and the Utilitarians might sniff and say "But my maximum risk appetite is 15% so I'm going to use leverage of 1.5". Since the optimal standard deviation of 50% is relatively high it's very likely that we'd get a conflict between the two approaches here.
But we're going to go beyond that, and note that there is actually a lot of uncertainty about what the optimal leverage and risk target should be. To address this let's introduce the concept of uncertainty appetite. This is how comfortable investors are with not knowing exactly what their optimal leverage should be. It is analogous to the more well known risk appetite, which is how comfortable investors are with lumpy returns.
Someone who is uncertainty blind would happily use the median points from the above distributions- they'd use full Kelly, assuming of course that their risk appetite wasn't constraining them to a lower figure. And someone weird who is uncertainty loving might gamble and assume that the true SR lies somewhere to the right of the median, and use a higher leverage and risk target than full Kelly.
But most people will have a coefficient of uncertainty aversion (see what I did there?). They'll be uncomfortable with full Kelly, knowing that there is a 50% chance that they will actually be over gearing. We have to specify a confidence interval that we'd use to derive the optimal leverage, with uncertainty aversion factored in.
So for example suppose you want to be 75% sure that you're not over-geared. Then you'd take the 25th percentile point off the above distributions: which gives you an expected Sharpe Ratio of about 0.29, a risk target of 29% and optimal leverage of 2.9.
Here are a few more figures for varying degrees of uncertainty:
Confidence interval Optimal risk Optimal leverage
<5.8% Don't invest anything
10.0% 9.2% 0.93
15.0% 17.1% 1.71
20.0% 23.2% 2.32
30.0% 33.3% 3.33
40.0% 41.9% 4.1950.0% 50.0% 5.00
Incidentally the famous half Kelly (a leverage of 2.5) corresponds to a confidence interval of about 22%. However this isn't a universal truth, and the result will be different for other Sharpe Ratios.
What this means in practice is that if you're particularly averse to uncertainty then you'll end up with a pretty low optimal Kelly risk target. How does this now interact with risk appetite, and the Utilitarian idea of maximum risk tolerance? Well the higher someones aversion to uncertainty, the lower their optimal risk target will be, and the less likely that an exogenous maximum risk appetite will come into play.
Now someone who is averse to uncertainty will probably also be averse to the classical risk of lumpy returns. You can imagine people who are uncertainty averse but not risk averse (indeed I am such a person), and others who are risk averse but not uncertainty averse, but generally the two probably go together. Which also raises an interesting philosophical point about the difference between them, as we'd rarely be able to distinguish between the two kinds of uncertainty except in specific experiments or unusual corner cases.
Summary
Both the Kellyites and the Utilitarians have good points to make - you should never bet more than full Kelly no matter how gung ho you are, and risk appetite is actually a thing even if few investors really know have quadratic utility functions..
Hi Rob, ever since reading your first book I meant to ask how exactly "implies" works in this sentence from it: “Kelly criterion implies the optimal risk percentage for a sharpe ratio 0.5 system is 50%”.
It's like when a university math\physics professor makes a swift transition on a blackboard from one gargantuan formula to another with a phrase "..and so we can easily see how this leads to that..", when in fact the "easily" part leaves most of the audience bewildered :).
So thanks for finally clarifying it here.
You're welcome!
Hi there,
I don´t understand how you can define a risk appetite for a given standard deviation for example on yearly 20% - disregarding if the sharp ratio is 0.2 or 2. There is a big difference in risk appetite on those two strategies, regardless if they are run on the same vol. Any comments on that?
Hi there,
I don´t see how you can evaluate risk, with out taking into account the expected returns - I.e, use Sharp ratio. The risk for two portfolios with the same vol, but different returns - seems to me to be very different over time. (Offcourse all assuming that we have realiable estimates of true Sharp ratios).
Curious to your comments on this?
Kind Regards from a kelly fan :-)
Okay it's true that if your Sharpe is 1.0 rather than 0.0 then after many years the risk of having less money than you started with is much lower. But the main point about this post is deciding how much leverage you should have. Leverage is something that kills you in the short term, no matter how good you think the long term will be. If you lose all your margin money it's no use calling your broker and telling him you expect to have a 99% chance of being up after 10 years :-)
And in the short term risk is pretty much invariant to Sharpe Ratio. So for example with a SR of 0.0 there is a 50% chance I'll lose money today. With an annualised SR of 1.0 there is still a 47.5% chance I'll lose money today. | https://qoppac.blogspot.com/2018/06/kelly-versus-classical-portfolio-theory.html | CC-MAIN-2019-22 | refinedweb | 2,925 | 59.64 |
Guest Post by Willis Eschenbach
Although it sounds like the title of an adventure movie like the “Bourne Identity”, the Bern Model is actually a model of the sequestration (removal from the atmosphere) of carbon by natural processes. It allegedly measures how fast CO2 is removed from the atmosphere. The Bern Model is used by the IPCC in their “scenarios” of future CO2 levels. I got to thinking about the Bern Model again after the recent publication of a paper called “Carbon sequestration in wetland dominated coastal systems — a global sink of rapidly diminishing magnitude” (paywalled here ).
Figure 1. Tidal wetlands. Image Source
In the paper they claim that a) wetlands are a large and significant sink for carbon, and b) they are “rapidly diminishing”.
So what does the Bern model say about that?
Y’know, it’s hard to figure out what the Bern model says about anything. This is because, as far as I can see, the Bern model proposes an impossibility. It says that the CO2 in the air is somehow partitioned, and that the different partitions are sequestered at different rates. The details of the model are given here.
For example, in the IPCC Second Assessment Report (SAR), the atmospheric CO2 was divided into six partitions, containing respectively 14%, 13%, 19%, 25%, 21%, and 8% of the atmospheric CO2.
Each of these partitions is said to decay at different rates given by a characteristic time constant “tau” in years. (See Appendix for definitions). The first partition is said to be sequestered immediately. For the SAR, the “tau” time constant values for the five other partitions were taken to be 371.6 years, 55.7 years, 17.01 years, 4.16 years, and 1.33 years respectively.
Now let me stop here to discuss, not the numbers, but the underlying concept. The part of the Bern model that I’ve never understood is, what is the physical mechanism that is partitioning the CO2 so that some of it is sequestered quickly, and some is sequestered slowly?
I don’t get how that is supposed to work. The reference given above says:
CO2 concentration approximation
The CO2 concentration is approximated by a sum of exponentially decaying functions, one for each fraction of the additional concentrations, which should reflect the time scales of different sinks.
So theoretically, the different time constants (ranging from 371.6 years down to 1.33 years) are supposed to represent the different sinks. Here’s a graphic showing those sinks, along with approximations of the storage in each of the sinks as well as the fluxes in and out of the sinks:
Now, I understand that some of those sinks will operate quite quickly, and some will operate much more slowly.
But the Bern model reminds me of the old joke about the thermos bottle (Dewar flask), that poses this question:
The thermos bottle keeps cold things cold, and hot things hot … but how does it know the difference?
So my question is, how do the sinks know the difference? Why don’t the fast-acting sinks just soak up the excess CO2, leaving nothing for the long-term, slow-acting sinks? I mean, if some 13% of the CO2 excess is supposed to hang around in the atmosphere for 371.3 years … how do the fast-acting sinks know to not just absorb it before the slow sinks get to it?
Anyhow, that’s my problem with the Bern model—I can’t figure out how it is supposed to work physically.
Finally, note that there is no experimental evidence that will allow us to distinguish between plain old exponential decay (which is what I would expect) and the complexities of the Bern model. We simply don’t have enough years of accurate data to distinguish between the two.
Nor do we have any kind of evidence to distinguish between the various sets of parameters used in the Bern Model. As I mentioned above, in the IPCC SAR they used five time constants ranging from 1.33 years to 371.6 years (gotta love the accuracy, to six-tenths of a year).
But in the IPCC Third Assessment Report (TAR), they used only three constants, and those ranged from 2.57 years to 171 years.
However, there is nothing that I know of that allows us to establish any of those numbers. Once again, it seems to me that the authors are just picking parameters.
So … does anyone understand how 13% of the atmospheric CO2 is supposed to hang around for 371.6 years without being sequestered by the faster sinks?
All ideas welcome, I have no answers at all for this one. I’ll return to the observational evidence regarding the question of whether the global CO2 sinks are “rapidly diminishing”, and how I calculate the e-folding time of CO2 in a future post.
Best to all,
w.
APPENDIX: Many people confuse two ideas, the residence time of CO2, and the “e-folding time” of a pulse of CO2 emitted to the atmosphere.
The residence time is how long a typical CO2 molecule stays in the atmosphere. We can get an approximate answer from Figure 2. If the atmosphere contains 750 gigatonnes of carbon (GtC), and about 220 GtC are added each year (and removed each year), then the average residence time of a molecule of carbon is something on the order of four years. Of course those numbers are only approximations, but that’s the order of magnitude.
The “e-folding time” of a pulse, on the other hand, which they call “tau” or the time constant, is how long it would take for the atmospheric CO2 levels to drop to 1/e (37%) of the atmospheric CO2 level after the addition of a pulse of CO2. It’s like the “half-life”, the time it takes for something radioactive to decay to half its original value. The e-folding time is what the Bern Model is supposed to calculate. The IPCC, using the Bern Model, says that the e-folding time ranges from 50 to 200 years.
On the other hand, assuming normal exponential decay, I calculate the e-folding time to be about 35 years or so based on the evolution of the atmospheric concentration given the known rates of emission of CO2. Again, this is perforce an approximation because few of the numbers involved in the calculation are known to high accuracy. However, my calculations are generally confirmed by those of Mark Jacobson as published here in the Journal of Geophysical Research.
251 thoughts on “The Bern Model Puzzle”
There’s a massive CO2 sink that resides over Siberia during winter, it is rapidly ‘taken up’ by foliage during Spring and Summer.
We affect the partition in many different ways, on what we plant and harvest and what we do with the harvest. Numerous other biological systems do as well and none are fully understood.
excellent thought post Willis……..
I still can’t figure out how CO2 levels rose to the thousands ppm….
….and crashed to limiting levels
Without man’s help……….
The categories are fixed so that you can see net effects.
Their graph is made in a manner which would make readers not realize how much biomass growth occurs from human CO2 emissions.
Human emissions averaged around 27 billion tons a year of CO2 during the decade of 1999-2009 (on average 7 billion tons annually of carbon), which amounted to about 270 billion tons of CO2 added to the atmosphere. Meanwhile there was a measured increase in atmospheric CO2 levels of 19.4 ppm by volume, 155 billion tons by mass, an amount about 57% of the preceding but only 57% of it.
If one looks at where the other 115 billion tons went, it was a mix of uptake by the oceans and it going into increased growth of biomass (carbon fertilization from higher CO2 levels) / soil.
Approximately 18% (49 billion tons CO2, 13 billion tons carbon) went into accelerated growth of biomass / soil, and about 25% went into the oceans.
To quote TsuBiMo: a biosphere model of the CO2-fertilization effect:
“The observed increase in the CO2 concentration in the atmosphere is lower than the difference between CO2 emission and CO2 dissolution in the ocean. This imbalance, earlier named the ‘missing sink’, comprises up to 1.1 Pg C yr–1, after taking land-use changes into account.” “The simplest explanation for the ‘missing sink’ is CO2 fertilization.”
In fact, global net primary productivity as measured by satellites increased by 5% over the past three decades. And, for example, estimated carbon in global vegetation increased from approximately 740 billion tons in 1910 to 780 billion tons in 1990:
Other observations include those discussed at
The categories are fixed so that one can import a sense of order and predictability to a collection of processes that lack both. I can just as easily categorize the residence time of foodstuffs in my refrigerator as beverage, pre-packaged, and leftovers. That doesn’t mean I can predict whether the salsa will become empty within three months or stick around to generate new life forms. It presumes a level of understanding of the “carbon budget” that doesn’t exist. But with such a model I can calculate how much milk will be in my fridge in 2050. Regardless of that result, the dried clump of strawberry jam on the third shelf won’t be inconsistent with my projection.
Turtles, indeed.
Ah! A warmist recently told me that the residence time of CO2 is 2 to 500 years. I replied that that is quite the error bar. He probably had looked up that Bern model and got his information from there. But it really doesn’t make any sense and I would file it under make-work schemes or epicycles. A product of the Warmist Works Progress Administration.
“what is the physical mechanism that is partitioning the CO2 so that some of it is sequestered quickly, and some is sequestered slowly?”
“PV=nRT” basically dashes such a fantastic model on the rocks. A classic example of the modeller’s propensity to assume something corny in order to make the model do their bidding. One school assumes “well mixed” while its class clown decides to countermand the principles behind partial pressures. Hocus-pocus, tiddly-okus, next it’ll be a plague of locusts.
“Calculating” to 4.16 or 1.33 years indicates a remarkable of “accuracy” 3.65 days residence time for “some” CO2. The oceans do NOT absorb CO2 from the atmosphere. The oceans have “vast pools of liquid CO2 on the ocean floors” which keep constant supply of dissolved CO2 and other elemental gases in the water column ready to disperse. See Timothy Casey’s excellent “Volcanic CO2” posted at While there visit the “Tyndall 1861” actual experiment with Casey’s endnotes and the original translation of Fourier on greenhouse effect. Reality is different than the forced orthodoxy.
The average time molecules remain in the atmophere as a gas is probably a matter of hours. Think how fast a power plant plume vanishes to a global background level. Think about how clouds absorb and transport CO2. It is the different lengths of reservoir changing cycles that is changing the amount of gaseous CO2 we measure in the atmosphere. I have evidence that most of anthropogenic emissions cycle through the environment in about ten years and, at present, contribute less than 10% to atmospheric levels. Click on my name for details.
I’m way out of my depth here, but The Hockey Schtick wrote about The Bern Model with advice from “Dr Tom V. Segalstad, PhD, Associate Professor of Resource and Environmental Geology, The University of Oslo, Norway, who is a world expert on this matter.”
Imagine you have three tanks full of water: A, B, and C. A and B are connected with a large pipe. A and C are connected with a narrow pipe. The water levels start off equal.
We dump a load of water into tank A. Quite quickly, the levels in tanks A and B equalise, A falling and B rising. But the level in tank C rises only very slowly. Tank A drops quickly to match B, but then continues to drop far more slowly until it matches C.
Dumping an extra load in A while this is going on would again lead to another fast drop while it matched B again. It ‘knows’ which is which because of the amount in tank B.
I gather the BERN model is more complicated, and the parameters listed are an ansatz obtained by curve-fitting a sum of exponentials to the results of simulation. But I think the choice of a sum of exponentials to represent it is based on the intuition of multiple buffers, like the tanks.
John Daly wrote some stuff about this – I haven’t worked my way through it, so I can’t comment on validity, but I thought you might be interested.
“Partitioning” is trivial
The simple case of a single exponent corresponds to a first-order linear equiation, but this does not describe the complex nature.
CO2 evolves according to a higher-order linear equation (or a system of first-order linear equations that is the same). Very reasonable. That is where the “partitioning” comes,
You write down these quations and look for eigenmodes. These are the exponents. IPCC effectively claims, there are 6 first order equations or a single 6th order linear equation. OK, no objection, although there can be even more eigenmodes, but let us assume these are the major 6.
Now, the general solution is a sum of these exponents with ARBITRARY pre-factors at each exponent. How to define these pre-factors?
The pre-factors are defined by the initial conditions: the particular CO2-level and 5 (6-1) derivatives (!). IPCC claims, these are 14%, 13%, 19%, 25%, 21%, and 8%. What does it mean?
Effectively IPCC claims to know the 5th derivative of CO2 population down to 1% accuracy level!!!
Sorry, as a physicist I cannot buy such accuracy in derivatives of an experimental value.
Two words… Occam’s Razor
CO2 is determined by climatic factors. Temperature-independent CO2 fluxes into/out of the atmosphere (especially minor ones like the human input) are compensated by the system (oceans).
If we could magically remove 100 ppm of the CO2 from the atmosphere in one day, what would be the transient system response (after 10 days, 1 month, a year…)?
Forgot smth to add.
IPCC claims to Bern model to find out these “prefactors” in simulations with a “CO2-impulse”.
The point is, the linear exponential solutions are valid only in the vicinity of an equilibrium. This means, IPCC must use an infinitesimal CO2-impulse to define the system response.
What does IPCC instead?
They assume the “CO2-impulse” being an instantaneous combustion of ALL POSSIBLE FOSSILE FUELS.
The response is in no way linear then and the results are just crap.
They even introduce some model for “temperature increase” due to higher CO2. The higher temperature means there is less absorption of CO2 by oceans etc…
This is not a science, but a clear misuse of it.
The idea CO2 is partitioned in any way sounds like complete bull to me – CO2 is quickly well mixed in the atmosphere. But its possible some CO2 sinks could be diminishing, that might help explain some of the increase in atmospheric concentration (plus as others have pointed out higher temperatures mean less absorption by the oceans).
I don’t think any discussion of the carbon cycle should be without mention of Salby’s work, if you haven’t seen it:
[REPLY: It was discussed here on April 19. -REP]
The basic assumption of this model seems to be that there is some “perfect” amount of CO2 that the earth tries to return to. Otherwise, if adding CO2 causes it to slowly go away, we should have no CO2 now, right? Thus, they must believe that it does down to this “perfect” amount and just stays there. Why does it stop diminishing? What mechanism could cause it to do so? For that matter, what mechanism would cause it to try and return to some “perfect” amount?
If CO2 goes down to this “perfect” amount and just stays there, CO2 over time should mostly be at that level all throughout history, is it? In fact, it goes up and down all the time, why is that? In fact, even in recent history it has gone up and down, that being the case, how can we even vaguely estimate how fast it will do so, much to the accuracy they claim here. In fact, since we know that CO2 goes up and down, if it does go down over time, we should be able to tell over a long enough time period how fast it goes down on average.Since we do have records of CO2 in the past, we should be able to compare this idea to the real world, and if what they are saying is true, that it goes down steadily over time (despite the actual records that say it does not), should we not be able to check this real world record against this model? Has it been checked? If it has not been checked, is this science? If it has not been checked, this model is fiction.
Also, their idea is that if CO2 increases, it then decreases, well, where does it go? The only place it can go is into the ground as oil, coal, natural gas, etc. This if we burn these, we are merely returning to the atmosphere what came from the atmosphere. This should return to the atmosphere what they claim here is being steadily removed. We need to keep doing this, otherwise we will run completely out of CO2, right? If this is not true, they need to demonstrate that CO2 will go down to this mythical “perfect” amount and just stays there.
Also, if CO2 is decreasing all the time, as they claim, yet it goes up and down over time (and note that the world does not end when it does), then something must be adding it, what, and is it enough to keep us from running out completely? Since we know that in the distant past there was far more CO2 (yet life flourished, go figure), yet now it is near to the level where all life on earth will die, we cannot rely on whatever natural processes add CO2 to bring it back up, since it obviously is not working, CO2 is dangerously low. We need to invent a way to return the CO2 back to the atmosphere. Occording to the IPCC, we have, now they are trying to stop us from doing what this model claims we must do to survive.
Once you understand the logical underlying assumption of this, that there must be a “perfect” level of CO2 that the earth tries to return to, the actual logic is:
The history of the earth shows that there is no perfect amount of CO2 that the earth tries to return to.
We the IPCC however, say that there is.
We say that because we wish it to be so.
We wish it to be so because if it is true, we can tax you and regulate you if it is not perfect.
We are the only authority on when it is perfect.
Ignore that real world behind the curtain!
Peter Huber used to make the controversial claim that North America is a carbon sink, based on a 1998 article in Science. This was based on prevailing winds blowing from West to East, with higher concentrtions of CO2 found on the West coast than the East. Later papers doing carbon inventories have disputed this. Huber responded that there was plenty of ways to miss inventory. Whoever is right, Huber makes a good case that the US does a better job than the rest of the world of replacing farmland with trees.
Isn’t just like a bunch of resistors in parallel? 1/R =1/r1+1/r2+1/r3…..
FTA: “Anyhow, that’s my problem with the Bern model—I can’t figure out how it is supposed to work physically.”.
This gives rise to a so-called “fat-tail” response. Such a fat-tail response can be approximated as a sum of exponential responses with discrete time constants.
I am not, of course, advocating the Bern model parameters. The modeling process is reasonable and justifiable, but the parameterization is basically pulled out of a hat..
Interesting Willis. The problem reminds me of pharmacokinetics where the fate of drugs/toxins in the body are studied; wish I knew enough about pk to be more specific unfortunately it was only ancillary to my field of study. Any toxicologists around?
Thanks. I thought I was the only one that didn’t believe this fallacy.
The fast processes will finish with it’s CO2 then go after the next batch !
The alarmists just want an excuse to say CO2 remains in the atmosphere for 100 years which is can’t possibly do.
The different timings are only relevent for the first 376.1 years of the model after that they are totally irrelevant as all sinks will be working. In fact in the real world they will be totally irelevant as all the sinks will be working all of the time. It just padding for the report to make it look more technical.
CO2 works like resistors in parallel.
1/RT=1/R1 + 1/R2+1/R3
So the total resistance can’t be more than the smallest resistor.
for CO2 the 1/2 life of the total can’t be greater than the 1/2 life which is shortest.
The Bern Model needs to introduced to the Law of Entropy (diffusion of any element or compound within a gas or liquid to equal distribution densities). And it should also be introduced to osmosis and other biological mechanisms for absorbing elements and compounds across membranes.
In fact, it seems to need a serious dose of reality
Bart says:
May 6, 2012 at 11:51 am
I want to repeat this part of my post, because people may miss it in with the other stuff, and I think it is important..
Bart says:
May 6, 2012 at 11:51 am
Thanks, Bart. That all sounds reasonable, but I still don’t understand the physics of it. What you have described is the normal process of exponential decay, where the amount of the decay is proportional to the amount of the imbalance.
What I don’t get is what causes the fast sequestration processes to stop sequestering, and to not sequester anything for the majority of the 371.6 years … and your explanation doesn’t explain that.
w.
Surely they don’t serious use the sum of five or six exponentials, Willis. Nobody could be that dumb. The correct ordinary differential equation for CO_2 concentration
, one that assumes no sources and that the sinks are simple linear sinks that will continue to scavenge CO_2 until it is all gone (so that the “equilibrium concentration” in the absence of sources is zero (neither is true, but it is pretty easy to write a better ODE) is:
Interpretation: Since CO_2 doesn’t come with a label, EACH process of removal is independent and stochastic and depends only on the net atmospheric CO_2 concentration. Suppose
is the rate at which the ocean takes up CO_2. Left to its own devices and with only an oceanic sink, we would have:
where
is the constant of integration. I mean, this is first year calculus. I do this in my sleep. The inverse of $R_1$ is the exponential decay constant, the time required for the original CO_2 level to decay to
of its original value (for any original value
). If there are two processes running in parallel, the rate for each is independent — if (say) trees remove CO_2 at rate $R_2$, that process doesn’t know anything about the existence of oceans and vice versa, and both remove CO_2 at a rate proportional to the concentration in the actual atmosphere that runs over the sea surface or leaf surface respectively. The same diffusion that causes CO_2 to have the same concentration from the top of the atmosphere to the bottom causes it to have the same concentration over the oceans or over the forests, certainly to within a hair. So both running together result in:
If (say) trees and the ocean both remove CO_2 at the same independent rate, the two together remove it at twice the rate of either alone, so that the exponential time constant is 1/2 what it would have been for either alone. If there are five such independent sinks (where by independent I mean independent chemical processes), all with equal rate constants
, the exponential time constant is 1/5 of what it would be for one of them alone. This is not rocket science.
This is completely, horribly different from what you describe above. To put it bluntly:
Compare this when
,
:
(correct) versus
(incorrect). The latter has exactly twice the correct decay time, and makes no physical sense whatsoever given a global pool of CO_2 without a label. The person that put together such a model for CO_2 — if your description is correct — is a complete and total idiot.
Note that this would not be the case if one were looking at two different processes that operated on two different molecular species. If one had one process that removed CO_2 and one that removed O_3, then the rate at which one lowered the “total concentration of CO_2 + O_3” would be a sum of independent exponentials, because each would act only on the partial pressure/concentration of the one species. However, using a sum of exponentials for independent chemical pathways depleting a shared common resource is simply wrong. Wrong in a way that makes me very seriously doubt the mathematical competence of whoever wrote it. Really, really wrong. Failing introductory calculus wrong. Wrong, wrong, wrong.
(Dear Anthony or moderator — I PRAY that I got all of the latex above right, but it is impossible to change if I didn’t. Please try to fix it for me if it looks bizarre.)
rgb
Nullius in Verba says:
May 6, 2012 at 11:19 am (Edit)
My thanks for your explanation. That was my first thought too, Nullius. But for it to work that way, we have to assume that the sinks become “full”, just like your tank “B” gets full, and thus everything must go to tank “C”.
However, since the various CO2 sinks have continued to operate year after year, and they show no sign of becoming saturated, that’s clearly not the case.
So what we have is more like a tank “A” full of water. It has two pipes coming out the bottom, a large pipe and a narrow pipe.
Now, the flow out of the pipe is a function of the depth of water in the tank, so we get exponential decay, just as with CO2.
But what they are claiming is that not all of the water runs out of the big pipe, only a certain percentage. And after that percentage has run out, the remaining percentage only drains out of the small pipe, over a very long time … and that is the part that seems physically impossible to me.
I’ve searched high and low for the answer to this question, and have found nothing.
w.
What about rain water, which, in its passage through the air dissolves many of the soluble gases e.g. CO2 present in the atmosphere, and which as part of ‘river waters’ eventually makes its way into the oceans?
River and Rain Chemistry
Book: “Biogeochemistry of Inland Waters” – Dissolved Gases
.
“The IPCC, using the Bern Model, says that the e-folding time ranges from 50 to 200 years.”
**********************
Strikes me as a pretty wide ranging estimate. More like a ‘WAG’.
I file this Bern Model under “more BAF (Bovine Academic Flatulence)”.
The physiology of scuba diving divides body tissues into different categories, with different “half-lives”, or nitrogen abosrption rates. Some tissues absorb, and release Nitrogen rapidly, others more slowly; they are given different diffusion coefficients.
Nitrogen absorbed in your tissues in diving is the cause of the bends.
Maybe the Bern Conspiracy is thinking that some absorption mechanisms operate at different rates others. How fast do forests absorb CO2 compared to oceans? etc. Perhaps that is what they are thinking.
mfo says:
May 6, 2012 at 11:19 am
mfo, take a re-read of my appendix above. The author of the hockeyschtick article is conflating the residence time and the e-folding time. As a result, he sees one person saying four years or so for residence time, and another person saying 50 to 200 years for e-folding time, and thinks that there is a contradiction. In fact, they are talking about two totally separate and distinct measurements, residence time and e-folding time.
w.
Willis Eschenbach says:
May 6, 2012 at 12:07 pm
“What I don’t get is what causes the fast sequestration processes to stop sequestering, and to not sequester anything for the majority of the 371.6 years … and your explanation doesn’t explain that.”
The best I can tell you is what I stated:.” The link I gave explains it from a mathematical viewpoint.
rgbatduke says:
May 6, 2012 at 12:12 pm
“The correct ordinary differential equation…”
It’s a PDE, not an ODE. See comment at May 6, 2012 at 11:51 am.
About 1/2 of the annual human emission are absorbed each year. If they weren’t the growth in CO2 as a % of total would be growing, which it isn’t.
Assuming an exponential rate of uptake, we have a series something like this:
1/2 = 1/4 + 1/8 + /16 + 1/32 ….
With each year absorbing 1/2 of the residual of the previous, to match the rate of the total.
ie: R = R^2 + R^3 + R^4 … R^n , where 0 < R infinity.
What this means is that tau is 2 years. 1/4 + 1/8 = 0.25 + 0.125.= 0.375 = approx 1/e
The mathematical and physical ability of climate scientists appears to be very poor.
The worst case is the assumption by Houghton in 1986 that a gas in Local Thermodynamic Equilibrium is a black body. This in turn implies that the Earth’s surface, in radiative equilibrium, is also a black body, hence the 2009 Trenberth et. al. energy budget claiming 396 W/m^2 IR radiation from the earth when the reality is presumably 63 of which 23 is absorbed by the atmosphere.
The source of this humongous mistake is here:
Here is the [good] Wiki write-up:.’
So, the IR absorption in the atmosphere has been exaggerated by 15.5 times. The carbon sequestration part is no surprise; these people are totally out of their depth so haven’t fixed the 4 major scientific errors in the models.
And then they argue that because they measure ‘back radiation’ by pyrgeometers, it’s real They have even cocked this up: a radiometer has a shield behind the detector to stop radiation from the other direction hitting the sensor assembly. So, assuming zero temperature gradient, the signal they measure is an artefact of the instrument because in real life it’s zero. What is measures is temperature convolved with emissivity, and so long as the radiometer points down the temperature gradient, that imaginary radiation cannot do thermodynamic work!
This subject is really the limit of cooperative failure to do science properly. Even the Nobel prize winner has made a Big Mistake!
I’m not sure of the significance of the e-folding time. I presume it must be related to the rate at which a particular sink absorbs CO2, in which case why not use the absorption time? As for the partitions, I just don’t get it. Surely there must be a logical explanation in the text for the various percentages listed.
ferd berple says:
May 6, 2012 at 12:25 pm
“About 1/2 of the annual human emission are absorbed each year.”
In the IPCC framework, that 1/2 dissolves rapidly into the oceans. So, if you include both the oceans and the atmosphere in your modeling, there is no rapid net sequestration.
I agree with the IPCC on the former. But, I do not agree with them that the collective oceans and atmosphere take a long time to send the CO2 to at least semi-permanent sinks.
Bart says:
May 6, 2012 at 12:21 pm
No, the link you gave explains simple exponential decay from a mathematical viewpoint, which tells us nothing about the Bern model.
w.
Willis said: What I don’t get is what causes the fast sequestration processes to stop sequestering, and to not sequester anything for the majority of the 371.6 years … and your explanation doesn’t explain that.
================================
Either there are five different types of CO2…..or CO2 is not well mixed at all……or each “tau” has a low threshold cut off point
The only things that can have a low threshold cutoff point are biology
Cos the other sinks are fully saturated, or already absorbing all they can, so they leave the rest behind for the other longer sinks – then they can claim the natural sinks are saturated and we are evil despite it making no sense. Its all based on the assumption that before 1850 co2 levels were constant and everything lived in a perfect state of equilibirum just on the very the systems absorbtion capacity. Ahhh the world of climate science!
I must step away, so apologies if anyone has a question or challenge to anything I have written. Will check the thread later.
All I’ve got time for today is: Here we go again …
Welcome to the ‘troop’ which denies the measurable EM-nature of bipolar gaseous molecules, e.g. is studied in the field of IR Spectroscopy.
.
The rate of each individual sink is meaningless. What is important is that the total increase each year remains approximately 1/2 of annual emissions. Everything else is simply the good looking girls the magician uses to distract the audience from the sleight of hand.
As Willis points out, the thermos cannot know if the contents are hot or cold. Similarly, the sinks cannot know how long the CO2 has been in the atmosphere, so you cannot have differential rates depending on the age of the CO2 in the atmosphere.
1/2 the increased CO2 is absorbed each year. therefore 1/2 the residue must also be absorbed year to year. The sinks cannot tell if it is new CO2 or old CO2.
What are the mechanisms for removing CO2 from the atmosphere?
1. Asorbsion at the surface of seas and lakes
2, Absorbsion by plants through their leaves
3, Washed out by rain.
Any others?
What is the split in magnitude between these methods because I’d expect some sort of equilibrium for each of 1 & 2 whereas 3 seems to be one way.
Every year this lady named Mother Nature adds a whole lot of CO2 to the atmosphere, and every year she takes out a whole lot. The amount she adds in a given year is only loosely correlated with the amount she takes out, if at all. Year after year we add a little more CO2 to the atmosphere, still only around 4% of the average amount MN does. There is no basis for contending that the amount we add is responsible for what may or may not be an increased concentration with respect to recent history. All we know is that CO2 frozen in ice averages around 280 ppm, but this is definitely an average value as the ice can take hundreds of years to seal off. The only numbers in this entire discussion that have a basis in fact are 220 gT in and out, and an average four year residence time. All else is speculation/conjecture/WAG.
Occam’s Razor rules as always.
Bart says:
May 6, 2012 at 12:32 pm
In the IPCC framework, that 1/2 dissolves rapidly into the oceans.
Nonsense. The oceans cannot tell if that 1/2 comes from this year or last year. If the oceans rapidly absorb 1/2 of the CO2 produced this year, then they must also rapidly absorb 1/2 the remaining CO2 from last year in this year. And so on and so on, for each of the past years.
The ocean cannot tell when the CO2 was produced, so it cannot have a different rate for this years CO2 as compared to CO2 remaining from any other year.
rgbatduke says:
May 6, 2012 at 12:12 pm
Thanks, Robert, your contributions are always welcome. Unfortunately, that is exactly what they do, with the additional (and to my mind completely non-physical) restriction that each of the exponential decays only applies to a certain percentage of the atmospheric CO2. Take a look at the link I gave above, it lays out the math.
Your derivation above is the same one that I use for the normal addition of exponential decays. I collapse them all into the equivalent single decay with the appropriate time constant tau.
But they say that’s not happening. They say each decay operates only and solely on a given percentage of the CO2 … that’s the part that I can’t understand, the part that seems physically impossible.
w.
_Jim says:
May 6, 2012 at 12:35 pm
_Jim and Mydogs, please, this thread is about CO2 sequestration and the Bern Model. Please take the blackbody discussion to some other more appropriate thread.
Thanks,
w.
ferd berple says:
Your comment is awaiting moderation.
May 6, 2012 at 12:39 pm
Bart says:
May 6, 2012 at 12:32 pm
In the IPCC framework, that 1/2 dissolves rapidly into the oceans.
ps: when I said “nonsense” I was referring only to the IPCC framework or any other mechanism that suggests different absorption rates based on the age of the CO2 in the atmosphere.
Willis Eschenbach says:
May 6, 2012 at 12:33 pm
“No, the link you gave explains simple exponential decay from a mathematical viewpoint, which tells us nothing about the Bern model.”
No, that’s not what it explains at all. It is a statistical model in which the probability distribution is exponential, to be used in finding a solution of the Fokker-Planck equation. The “decay” he shows is actually 1/(1+a*sqrt(t)), the reciprocal of 1 plus a constant time the square root of time.
Sorry I cannot explain it better right now. Must go.
son of mulder asks:
“Any others?”
There is overwhelming evidence that the biosphere is expanding due to the increase in CO2. There is no doubt about that. Therefore, it is not in ‘equilibrium’. As ferd berple points out, more of the increase is absorbed every year.
In addition, the oceans contain an enormous quantity of calcium, which is utilized by biological processes to form protective shells for organisms. Those organisms require CO2. With more CO2 available, those organisms rapidly proliferate. When they die, they sink to the ocean floor, thus permanently removing CO2 from the atmosphere.
The planet is greening due to the added CO2, which is completely harmless at current and future concentrations. If CO2 increases from 0.00039 of the atmosphere to 0.00056 of the atmosphere, it is still a very minor trace gas. At such low concentrations plants are the only thing that will notice the change. And any incidental warming will be minor, and welcome.
I am particularly intrigued by the 17.01 year figure, I had no idea climate science was so precise.
son of mulder says:
May 6, 2012 at 12:36 pm
Any others?
================
bacteria…..the entire planet is one big biological filter
They are the most abundant…………..or we wouldn’t be here
Willis Eschenbach – “However, there is nothing that I know of that allows us to establish any of those numbers. Once again, it seems to me that the authors are just picking parameters.”
I would point out a very important part of the link you referenced ():
“All IRFs are obtained by running the Bern model (HILDA and 4-box biosphere) as used in SAR or the Bern CC model (HILDA and LPJ-DGVM) as used in the TAR.” – (IRF’s -> impulse response functions, time factors, and final percentages)
The percentages you quoted are the resulting partial absorptions of various climate compartments resulting from running the Bern model, which is described in Siegenthaler and Joos 1992 (). In short, those percentages are results, not the inputs, of running the Bern model – presented by Joos et al for use by other investigators if they wish to apply the Bern model to their calculations.
Also note the statement that “Parties are free to use a more elaborate carbon cycle model if they choose.” Again – the results of the Bern model were offered as an available computational tool for further work.
I hate to say this, but you give the impression you did not fully read the UN reference (with percentages) that you opened the discussion with…
“My thanks for your explanation. That was my first thought too, Nullius. But for it to work that way, we have to assume that the sinks become “full”, just like your tank “B” gets full, and thus everything must go to tank “C”.”
That’s where I was going with the following paragraph. The buffer ‘tank B’ doesn’t stop absorbing because it’s full, it stops absorbing because the levels equalise. If you keep pouring water into tank A continuously, the water level keeps going up in B continuously. The tanks have infinite capacity, but the ratios of their capacities are much smaller.
The partitioning is the equivalent of the ratio of surface areas in each tank. If A and B are of equal size, then half the water in A flows into B and half stays where it is. If B is a lot bigger than A, then the level in A drops more and the level in B only rises a tiny amount heightwise, although the changes in volume are the same. The atmospheric analogy to surface area is the derivative of buffer content with respect to concentration.
I just went through that post with Salby video (didn’t have time before). Amazing that people still misunderstand the natural CO2-rise argument (like by Salby). Again:
The rise in the atmospheric CO2 is caused by warming climatic factors. The source is anthropogenic CO2, because it’s available in the atmosphere, but the cause is the warmth. Without anthropogenic CO2, oceans would have to release the necessary CO2 to achieve the climatically driven atmospheric CO2.
rgbatduke says:
May 6, 2012 at 12:12 pm
Robert, if I understand you correctly, I can’t tell you how happy I am to see you write this. That was my first response when I read the linked description of the Bern Model, it made my head explode. Unfortunately, I didn’t (and don’t) have your familiarity with the underlying math, so I had to set up some separate sample exponential decay streams in Excel, combine them, and then calculate iteratively the joint time constant … all of which very clumsily lead me to the conclusion that you established with a few lines of math …
Since I did that, which was maybe five years ago, I’ve questioned it and people have given vague handwaving explanations for something that I, like you, consider to be “wrong, wrong, wrong” and without any physical justification.
w.
Willis, with all due respect, that is ALL I had (and have) time for; I have to ‘be somewhere’ shortly. Thanks. I ‘capeesh’/capisce/’savvy’ the expressed desire to stick-to-the-issue-presently-being-debated, too. Good luck with your present efforts, and with that I gotta run … 73’s
.
CO2 started increasing about 1750. Human emissions of CO2 more-or-less started at that time as well. Here is a chart of Human Emissions in CO2 ppm versus the amount of CO2 that actually stayed in the air each year (the airborne fraction – about 50%) since 1750.
Global CO2 levels only increased 1.94 ppm last year (to 390.45 ppm – a little lower than expected) while human emissions continued increasing to about 9.8 billion tonnes Carbon (about 4.6 percentage points of CO2).
The natural sinks of CO2 have been increasing gradually over time so that they are now over 224 billion tons Carbon versus 220 billion tons in 1750. (the actual natural sinks and sources level might be closer to 260 billion tons going by some recent estimates of plant take-up but none-the-less).
The amount that the natural sinks absorb each year seems to be directly related to the concentration in the atmosphere. There is an equilibrium level of CO2 at about 275 ppm in non-ice-age conditions (this is the level it has been at for the past 24 million years).
So the natural sinks and sources are in equilbrium (give or take) when the CO2 level is 275 ppm or the Carbon level in the atmosphere is 569 billion tonnes.
The rise of the natural sinks over the past 250 years indicate the sinks will absorb down or sequester about 1.0% per year of the excess over this 569 billion tons or 275 ppm.
The last 65 years have been very close to the 1.0% level. It doesn’t matter how much we add each year. The plants and oceans and soils will respond to how much is in the air, not how much we add. And it is about 1.0% of the excess Carbon in the amtosphere each year – Bern model or no.
It will take about 150 years to draw down CO2 to the equilibrium of 275 ppm if we stop adding to the atmosphere each year. Alternatively, we can stabilize the level just by cutting our emissions by 50%.
To attempt to clarify what I wrote in my previous post ():
The exponentials, percentages, and time factors in the link Willis Eschenbach provided are approximations that reproduce the results of running the Bern model – much as 3.7 W/m^2 direct forcing per doubling of CO2 is the approximation of running radiative code such as MODTRAN, allowing quick calculations without having to run the model over and over again. I.e., the percentages and time factors are shorthand for the model.
As Joos stated in that link (), the Bern model approximations were offered as a tool for use by others, and “Parties are free to use a more elaborate carbon cycle model if they choose.”
OK, I’ve looked at the model details via the provided link. They are frigging insane. I mean seriously, one should just take the article’s provided advice and ‘use a more complex model’ if we like. I like. Here is a very simple linear model. Still too simple, but at least I can justify its structure:
Interpretation: We make CO_2 at some rate,
, that is completely independent of the concentration
. Because the atmosphere is vast, the percentage of CO_2 in the atmosphere can be considered to be the amount of CO_2 added divided into the total where the latter basically does not vary, hence I don’t need to work harder and write an ODE that saturates at 100% CO_2 — we are in the linear growth regime of a saturating exponential and I can assume assume that the concentration increases linearly at a constant rate independent of how much is already there (true until a significant fraction of the atmosphere is CO_2, utterly true when 400 ppm is CO_2).
However, CO_2 is removed from the atmosphere by processes that literally have a probability of removing a CO_2 molecule per unit time, given the presence of a molecule to remove. They are all proportional to the concentration. If I double the concentration, I present twice as many molecules per second to the e.g. surface of the sea as candidates for adsorption or to the stoma of a leaf as candidates for respiration and conversion into cellulose or sugar or whatever. They are all independent; if some particular wave removes a molecule of CO_2 at 11:37 today, a leaf on a tree in my back yard doesn’t know about it. The removed CO_2 has no label, and the jostling of molecules in the well-mixed warm air guarantees that one cannot even meaningfully deplete the local concentration of CO_2 by this sort of process, so both remain proportional to the same total concentration
.
and
are themselves directly proportional to (or more generally dependent on) other sensible quantities — we might expect the former to be proportional to the total surface area of the ocean for example, or to be related to some function of its area, its local temperature, and the concentration of CO_2 in the water already (which MIGHT vary appreciably geographically, as seawater is not well-mixed and it has its own sources and sinks). We might expect the latter to be dependent on the total surface area of CO_2 scavenging tree leaves, or more simply to total acreage of trees, again leaving open a more complex model that couples in the further modulation by water availability, hours of sunlight, and so on. Still, averaging over these latter probably makes this simple model already pretty reasonable.
The nice thing about this is that it is a well-known linear first order inhomogeneous ordinary differential equation, and can be directly integrated just as simply as the previous one. The result is (non-calculus people can take my word for it):
where
and where
is the steady state concentration one arrives at eventually from any starting concentration, as long as
(see linearization requirement above).
is a constant of integration used to set the initial conditions. If you started from no CO_2 in the air at all, you would make
so that
. We don't start from zero, so we have to choose it such that
comes out right. At the steady state concentration, the sinks remove CO_2 at the rate
, balancing the sources.
This simple linear response model shows precisely how one expects the eventual atmospheric concentration of CO_2 to saturate as long as saturation is achieved at low net concentrations of the total atmosphere such that the total relative fractions of N_2 and O_2 were the same and are still much larger than CO_2 taken together. And it is a well known and easily understood one. Equilibrium is
and one approaches it exponentially with time constant
— you can’t get much simpler than that. In fact, if you know
and can measure
one can is done, no need for complex integrals over sums of exponential sinks times a source rate (what the hell does that even MEAN).
Now as models go this one sucks — it is arguably TOO simple, but it is easy to fix. For example, the ODE is the same if one has a source rate that isn’t constant but is itself a function of time —
for example, describing source production that is increasing linearly in time, or
, a model that assumes source production is itself increasing towards an eventual peak at some rate with exponential time constant
. The former suffers from the flaw that it increases without bound. The latter is probably not terrible, but I’m guessing CO_2 sources are bursty and that this equation is a pretty crude approximation of the industrial revolution and eventual saturation of production/sources. Both suffer from the fact that CO_2 production might depend on the concentration
— although these production mechanisms can probably be handled with negative
.
A bigger problem is that for the ocean
depends on the temperature! A warming ocean can be a CO_2 source (or a heavily reduced sink as its uptake is reduced). A cooling ocean can sequester more CO_2, faster. But even this is too simple because part of the eventual sequestration involves chemistry and biology that depend on temperature, sunlight, animals activity, ocean currents and nutrients… so it is with all of the rates. They themselves might be — indeed, almost certainly are — functions of time!
However, even if we put far more complex differential forms into this ODE, it remains pretty easy to solve without making any sort of formal approximation or decomposition. Matlab lets one program it in and solve it in a matter of minutes, and graph or otherwise present the results at the same time. Writing a parametric form and then fitting the parameters to past data in hope of predicting the future is also possible, although it is a bit dicey as soon as you have a handful of nonlinear parameters because then one is trying to optimize a possibly non-monotonic function on a multidimensional manifold, which is the literal definition of “complex systems” in the Santa Fe institute sense.
Unless you know what you are doing — and few people do — you are likely to start the optimization process out with some set of assumptions and optimize with e.g. a gradient search to find an optimum that “confirms” those assumptions, ignoring the fact that a far better fit is available but is nowhere particularly near your initial guess. In a rough landscape, there might always be local maxima near at hand to get trapped on, and even finding the right neighborhood of the optimal fit can be challenging. Imagine an ant searching for the highest point on the surface of the earth by going up from wherever you drop them. Nearly every point they get dropped on will take them to the top of a grain of sand or a small hill. Only a teensy fraction of the Earth’s surface is mountains, a smaller one big mountains, a handful of mountains the highest peaks in a range, and one range the right range, one mountain the right mountain, one small area of slopes the right SLOPE, ones, that go straight on up to the top without being trapped.
There may be some way to formally justify the Bern model. Offhand I can’t see it — integrating E(t) is fine, but integrating it while multiplying it by that bizarre sum of exponential terms? It doesn’t even look like it has the right asymptotic form, implicit saturation. In other words, although it uses time constants, the time constants aren’t the time constants of a presumed exponential sequestration process that removes CO_2 at a rate proportional to its concentration, they are more like “relaxation times”. The expression looks like an unbounded integral growth in concentration modulated by temporal relaxation times that have nothing to do with concentration but rather describe something else entirely.
Just what is an interesting question, but this is not a sensible sequestration model, which is necessarily at least proportional to concentration. At higher concentrations, plants take up more of it and grow faster. The ocean absorbs more of it (at constant temperature) because more molecules hit the surface per unit time. More of the CO_2 that makes it into the ocean is taken up by algae and bound up, eventually to rain down onto the sea floor, removed from the game for a few hundred million years.
I cannot believe that there isn’t anybody out there in climate-ville that hasn’t worked all this out in a believable model of some sort, something that is a perturbation of the first order linear model I wrote out above. If not, shame on them.
rgb
In relation to sources and sinks, can Willis, or anyone else explain this image of global CO2 concentrations ?
Why don’t warm tropical oceans give high CO2 ?
Why is there a band of high CO2 around the 35S ?
How is the distribution over Africa and S America explained ?
Why does Antarctic ice appear to be such a strong absorber in parts and why such strong striation?
Seems this is a mental image issue – like putting the cart in front of the mule. It isn’t the carbon dioxide in the atmosphere that controls the timing. You can buy paints, some are fast-drying. Some dry slowly. Eventually, they all dry. CO2 sinks (hundreds, not 6 or 3) do their thing in their own way, so other things equal (constant CO2 levels), a very slow process might take 371.3 years to sequester a unit of gas, a very fast process might take 1.33 years to do the same. Thus, the numbers (wherever they came from) might have meaning – just not that described. So, one should really call it the Bourne Model insofar as the identity of the processes is a mystery and no one is sure just what is going on.
Well, whatever the Bern model does, it must be correct. After all, once you match the results of 9 GCM models (except one outlier), you have matched them all. CO2 sensitivity was assumed to be 2.5 K to 4.5 K in the models.
” After 80 years, the increase in global average surface temperature is 1.6 K and 2.4 K, respectively. This compares well with the results of nine A/OGCMs (excluding one outlier) which are in the range of 1.5 to 2.7 K”
KR says:
May 6, 2012 at 12:58 pm
Say what?
Look, KR, they used the box model to calculate the IRFs. The part you seem to be missing is that once they have used the box model to calculate the IRFs, then
claiming that the IRFs represent actual physical processes.
Next, you say the IRFs are the “resulting partial absorptions of various climate compartments”. This is similar to what the citation says, that they “reflect the time scales of different sinks”. Both of you are claiming that the IRFs have reflect real-world processes… so could you explain just how it is that the atmosphere is divided into “various climate compartments”, some of which decay quickly and some slowly?.
Perhaps you could explain to us how that works, that certain CO2 molecules are sequestered but some are immune to sequestration for hundreds of years.
I also note that there are no less than four different (and in fact very different) IFTs that have been used by the UN … hardly what one would expect if they actually are the “resulting partial absorptions of various climate compartments”. How are we supposed to pick one of them?
The SAR used five IRFs reflecting, according to you, five “climate compartments”, while the TAR used only three. What happened to two of the “climate compartments” between the SAR and the TAR … the IRFs just disappeared, what happened to the “climate compartments” that you claim they represent? Did they go out of business?
More to the point, why should we believe the model at all? The conclusion of your citation says:
The model calculates CFC-II well, but it misses on CO2. In other words, the model doesn’t work very well, and even the authors don’t understand why their model doesn’t work … not encouraging.
w.
Fascinating stuff, cheers Willis. So instead of trying to capture CO2 underground why not just dump into a high speed sink?
KR says:
May 6, 2012 at 1:19 pm
Both you and the citation I gave have said that the IRFs represent actual physical processes. You said the IRFs represent the “ resulting partial absorptions of various climate compartments”. My citation says that the IRFs “ reflect the time scales of different sinks”
Now you want to claim that this is just a way to approximate the model. Come back when you make up your mind and can explain why the citation is wrong.
w.
PS—See also Robert Brown’s comments above (rgbatduke) …
So … does anyone understand how 13% of the atmospheric CO2 is supposed to hang around for 371.6 years without being sequestered by the faster sinks?
Perhaps you need to look at this the other way around. We have often heard about the 800 year time lag between high temperatures and CO2 concentrations. Is it a coincidence that 371.6 is about half of 800? Is it possible that if the CO2 concentration were to suddenly drop, then various processes would act to raise the CO2? And that the part of the CO2 that is in the deep oceans may take 371.6 years to reach the atmosphere and add 13% to the overall increase in CO2 concentration?
RGB at duke says:
May 6, 2012 at 1:21 pm
…Please try to fix it for me if it looks bizarre.
Here is something bizarre that no one can do much about, let alone fix it.
Dr Burns says:
May 6, 2012 at 1:30 pm
Why does Antarctic ice appear to be such a strong absorber…
Antarctic is simply bizarre, see the link above
They may be discussing on-rate constants only. The concept might be equilibrium and saturation in different reservoirs. The on-rate for a given reservoir is the atmospheric concentration times the rate constant. The off rate is the reservoir concentration times the off-rate constant. If the on-rate equals the off-rate, then the reservoir is at equilibrium. No net uptake would occur.
rate(on) = k(on) * [conc(air)]
rate(of) = k(off) * [conc(res)]
No net uptake occurs when rate(on) = rate(off), that’s equilibrium.
In the real case, you also have a loss rate for CO2 via other routes, e.g. diatom skeletons in the ocean, and leaves or grasses on land. Which means the reservoirs don’t necessarily saturate, and they can continue to take up more CO2. In some cases, the on-rate may depend on the rate of dropout loss in that reservoir since near equilibrium limits the net uptake.
d(CO2 air)/dt = k(off) * [CO2(res)] – k(on) * [CO2(air)]
d(CO2 res)/dt = k(on) * [CO2(air)] – k(off) * [CO2(res)] – k(dropout) * [CO2(res)]
If the reservoir is in dynamic equilibrium, and to a reasonable approximation the reservoir concentration doesn’t change. Then
-k(on) * [CO2(air)] – k(off) * [CO2(res)] = k(dropout) * [CO2(res)] ,
which means both sides of the equation are constant, since CO2(res) doesn’t change.
Since the dropout material doesn’t readily cycle back to the air via the reservoir, it only makes sense when the dropout material can be returned to the atmosphere via another route, e.g. biological digestion, fire, volcanoes, or burning fossil fuel (coal). Returning the dropout material to the atmosphere creates the Carbon cycle we think about.
Partitions in the atmosphere itself make no sense, unless you are silly enough to count flying birds (%P) <- that's an emoticon.
From 1976 to 1997, atmospheric 14CO2 was measured. The levels spiked after due to atmospheric testing of nuclear weapons that ended in the 1960s. These data show the 14CO2 half-life is about 11 years (see raw data here:). In the first approximation, uptake mechanisms won't know the difference between carbon isotopes. It is quite safe to say half of the CO2 in the atmosphere is turned over in about 11.4 years. Five half-lives is about 57 years. That means only about 3% of the CO2 present in the atmosphere 57 years ago is still in the air.
It seems we have an idea of what the dropout rate for CO2 must be, and thus what the replenishment rate must be to keep the atmosphere in roughly steady state. In this simple model, a sudden change in atmospheric CO2 concentration could shift the equilibrium concentration in the reservoirs, and then establish a new constant uptake rate somewhat higher than the old one. If you think about it, perhaps that does make some sense in some cases, such as faster plant growth, or more alkalinty in the ocean (sorry catastrophists, biological action converts carbonic acid to bicarbonate, e.g. by nitrogen fixation).
Yes, models can be misused. It's up to you to decide when they are appropriate.
That’s July, two months after annual peak.
Why don’t warm tropical oceans give high CO2 ?
Maybe they do, but you can’t evaluate “vertical” fluxes only on the basis of concentrations in a month (average). The horizontal transport of CO2 in the atmosphere is spatialy and temporarily very dynamic (sesonal). It could also be rain (CO2 scrubbing) in the tropics…
Why is there a band of high CO2 around the 35S ?
High sommer in NH?
How is the distribution over Africa and S America explained ?
Why does Antarctic ice appear to be such a strong absorber in parts and why such strong striation?
Others should speculate. Seasons, moisture, snow, sst, surface altitude, energy budget, mass budget…
Since you like differential equations…
Start with three variables A, B, and C. The volume of flow from A to B is k_AB (A-B), and the volume of flow from A to C is k_AC (A-C).
So
dA/dt = k_AB (B-A) + k_AC (C-A) + E
dB/dt = k_AB (A-B)
dC/dt = k_AC (A-C)
where E is the rate of emission.
Treat L = (A, B, C) as a vector, ignore E for the moment to get dL/dt = ML where M is a matrix of constants. Diagonalise the matrix to get two independent differential equations (the rows of M are not linearly independent), each giving a separate exponential decay with a different time constant. Transforming back to the original variables gives a sum of exponentials.
(I think the two time constants are -k_AB-k_AC +/- Sqrt(k_AB^2-k_AB k_AC +k_AC^2) but I did it quickly.)
Hi _Jim: I did not state that there is no absorption of IR by GHGs. What l add though is that the present IR physics which claims 100% direct thermalisation is wrong and thermalisation is probably indirect at heterogeneous interfaces.
The reason for this is kinetic. Climate Science imagines that the extra quantum of vibrational resonance energy in an excited GHG molecule will decay by dribs and drabs to O2 and N2 over ~1000 collisions so it isn’t re-emitted. This cannot happen: exchange is to another GHG molecule and the principle of Indistinguishability takes over. [See ‘Gibbs’ Paradox’]
This is yet more scientific delusion in that all it needs is the near simultaneous emission of the same energy photon from a an already thermally excited molecule thus restoring LTE. This happens throughout the atmosphere at the speed of light so the GHGs are an energy transfer medium. The conversion to heat probably takes place mainly at clouds.
Frankly I am annoyed because this is the second tome through ignorance you have called me out this way. It’s because i have 40 years’ post PhD experience in applied physics I can show how climate science has been run by amateurs who have completely cocked the subject up. Nothing is right. The modellers are fine though because Manabe and Wetherald were OK, but once Hansen, Trenberth an Houghton took control, the big mistakes happened. it looks deliberate.
Following on from an earlier poster’s comments, the science of decompression diving uses a similar approach to that of the Bern model, to understand the movement of nitrogen into and out of a divers’ body tissues. The approach was pioneered by JS Haldane in 1907. He came up with the idea of using tissue compartments which exchanged nitrogen at different rates. Tissues like blood and nerves were fast, and were able to quickly equilibrate with any changes in the partial pressure of nitrogen. Tissues like muscle and fat were of intermediate speed, while bone was extremely slow. What Haldane did was to come up with a crude multi-compartment (tissue) model, and then carry out very extensive tests to tweak the model so that divers (goats in his initial experiments) did not get decompression sickness (gas bubbles forming in tissue). Over a hundred years on, Haldane-type tissue models are used in most divers’ decompression computers, and they work extremely well.
Some important points about diving science: 1. Haldane, and those who followed, constantly tested and refined their models against experimental data – a process which continues today – over a hundred years on. 2. The models are a crude approximation of a complex system (the human body), but at least the physics is reasonably well understood e.g. the local temperature and pressure gradients and the kinetics of the physical processes – solubility, perfusion and diffusion. 3. In decompression models, only one of the tissue compartments usually controls the behaviour of the model (rate of ascent/decompression stop timing). Therefore, small errors or uncertainties in each compartment are not a major problem.
The application of this approach to climate science is, in my view, highly problematic because: 1. There simply has not been enough time/effort to refine these models against experimental data – a process which can take many decades. 2. The models are a profoundly crude approximation of a bewilderingly complex system (global carbon cycle), about which most of physics/biology/geology/chemistry/vulcanology etc, etc are not well understood. 3 In climate models all of the compartments contribute to the behaviour of the model (CO2 sequestration rate) and so errors and uncertainties in each compartment are cumulative.
Bill Illis says:
May 6, 2012 at 1:16 pm
So the natural sinks and sources are in equilbrium (give or take) when the CO2 level is 275 ppm or the Carbon level in the atmosphere is 569 billion tonnes
====================================
Bill, this is biology…..what you’re calling equilibrium is exactly what happens when a nutrient becomes limiting……..
Bill Illis says:
May 6, 2012 at 1:16 pm
Very interesting charts as always, Bill. Thanks.
[note: the 3rd one has the wrong starting year].
Willis Eschenbach – .”
Then, Willis, I suggest you read the original papers on the Bern model, such as Siegenthaler and Joos 1992.
The percentages you listed are the results of running the Bern model, and as such are a convenient shorthand. The actual physical processes include mixed layer oceanic absorption, eddy currents and thermohaline circulation, etc. The very link you provided states that:
(emphasis added)
Your claim that these are percentages and time constants are the direct processes is a strawman argument – Joos certainly did not make that claim, he stated that these were a useful approximation.
I have to say I find your claims otherwise, and in fact your original post, to be quite disingenuous.
I have been wondering, if there is any reason to expect the rate of carbon exchange between the athmosphere and the ocean ( and other sinks) to be diffrent for diffrent isotopes of C ( CO2 for that matter ) . In other word might it be possible to infere something about the uptake rate of the sinks from the data (its accessible at the CDIAC website ) for the athmospheric dC14 content and the spike caused in it by open air nuclear bomb testing in the last century. I belive the i have somwhere seen a statment claming the “athmospheric half life” calculated from this “experiment” is 5.5 – 6 for the c14 isotope.
It is called a box model. Box models were discarded in the late 70’s, early 80’s, because they cannot describe complex systems.
There is an input into the system, the release of carbon from geologic sources (Vulcanism) and fossil fuels; the influx of carbon into the biosphere.
There is an output from the system, mineralization of carbon into muds, which will become rock; the efflux from the system.
At steady state, influx = efflux. In the previous 800,000 years of pre-industrial times CO2 is between 180-330 ppm. So either we were VERY lucky that influx=efflux due to chance; or the rate of efflux is coupled to the rate of influx. Thus, when CO2 is high, marine animals do well, the ocean biotica grows, more particulate organic matter sinks to the bottom of the ocean, more carbon trapped in mud, more mineralization.
Basic control mechanisms in fact..
Dearest Bart,
Piffle. I am talking about the integral in the document Willis linked, which is an integral over time only. If you set all of the
, effectively making the entire sum under the integral zero — this is what you would get if you made carbon dioxide sequestration in these imagined modes instantaneous — then the remainder of the function under the integral is
. This will cause CO_2 concentration to grow without bound as long as we are emitting CO_2 at all. Nor will it ever diminish, even if
. Worse, all of the terms in the integral I forced to zero by making their time constants absurdly small are themselves non-negative. None of them cause a reduction of
. They only make CO_2 concentration grow faster as one makes their time constants longer as long as
.
Now, as to your actual assertion that the rate that CO_2 molecules are “snatched from the air” is proportional to the concentration of molecules in the air — absolutely. However, for each mode of removal it is proportional to the total concentration in the air, not the “first fraction, second fraction, third fraction”. The CO_2 molecules don’t come with labels, so that some of them hang out anomalously long because they are “tree removal” molecules instead of “ocean removal” molecules. The ocean and the trees remove molecules at independent rates proportional to the total number of molecules. That is precisely the point of the simple linear response model(s) I wrote down. They actually “do the right thing” and remove CO_2 faster when there is more of it in total, not broken up into fractions that are somehow removed at different rates, as if some CO_2 is “fast decay” CO__2 and comes prelabelled that way and is removed in 2.57 years, but once that fraction is removed none of the rest of the CO_2 can use that fast removal process.
Except that the integral equation for the concentration is absurd — it doesn’t even do that. There is no open hole through which CO_2 can ever drain in this formula — it can do nothing but cause CO_2 to inexorably and monotonicall increase, for any value of the parameters, and CO_2 can never equilibrate unless you set
to zero.
As I said, piffle. I do teach this sort of thing, and would be happy to expound in much greater depth, but note well that all of this is true before one considers any sort of PDE or multivariate dependence. Those things all modulate the time constants themselves, or make the time deriviative a nonlinear function of the concentration. In general, one can easily handle those things these days by integrating a set of coupled ODEs with a simple e.g. runge-kutta ODE solver in a package like the Gnu Scientific Library or matlab or octave. I tend to use octave or matlab for quick and dirty solutions and the GSL routines (some of which are very slick and very fast) if I need to control error more tightly or solve a “big” problem that needs the speed more than the convenience of programming and plotting.
But one thing one learns when actually working with meaningful equations over a few decades is how to read them and infer meaning or estimate their asymptotics. The “simple carbon cycle model” Willis linked, wherever it came from, is a travesty that quite literally never permits CO_2 concentration to diminish and that purports to break a well-mixed atmosphere into sub-concentrations with different decay rates, which is absurd at the outset because it violates precisely the principle you stated at the top of this response, where removal/sequestration by any reasonable process is proportional to the concentration, not the sub-concentration of “red” versus “blue”, “ocean” vs “tree” CO_2.
rgb. Precipitation and weathering rates will also modulate those rate limiting nutrients. CO2 is the dependent variable, not the driving one…
The “Bern Model” is broken if it does not address that.
@ Latitude, May 6, 2012 at 10:38 am
“I still can’t figure out how CO2 levels rose to the thousands ppm….
….and crashed to limiting levels
Without man’s help……….”
Perhaps it is because your ( and your teacher’s ) view of the subject is incorrect.
The real question is: “Why is there any CO2 in the atmosphere at all?”
Answer that question and you will have the puzzle solved. CO2 is constantly and irreversibly being sequestered into the formation of insoluble carbonates (organically e.g. Foraminifera and chemically e.g. Calcium carbonate) over millennia.
One possible answer is the concept of a Hydritic Earth. With never ending up dwelling methane being oxidized to CO2.
Dan Kurt
Since you like differential equations…
I do, and if you tell me what A, B and C are, and what the equations represent, I'll tell you whether or not I believe the coupled system of equations or the final solution.
But neither one has anything to do with the equation Willis linked. It is an integral equation that has the asymptotic property of monotonic growth of CO_2 concentration completely independent of the parameter values on the domain given. The exponentials aren't the result of solving an ODE even — they are under an integral sign.
That particular integral equation looks like a non-Markovian multi-timescale relaxation equation with a monotonic driver, but whatever it is, it is absurdly wrong before you even begin because it gives utterly nonphysical predictions in some very simple limits. In particular, it never permits CO_2 concentration to decrease, and it never even saturates. If
,
increases, period.
rgb
[Moderator’s request: it wasn’t just a dollar sign, I guess. Please send the formula again and I will paste it in. -REP]
[Fixed (I think). -w.]
And by the way “The Bern Model” triggered a memory in my head about having read an article by Jarl Ahlbeck some years ago on the John Daly website, where he among other things maintains that the future athmospheric carbon dioxide concentrations the bern model predicts are just a simple minded parabolic fit to to some unrealistic assumptions (not data). I never could really make up my mind if he was right or wrong in that, but for what it is worth the link to the paper is on the line below:
SNIP: Twice is enough. This is starting to be thread bombing. WUWT also does not encourage tampering with polls. If it has been adjusted to allow only Australians, then foreigners casting votes are simply cheating. -REP
Final comment and then time to do some actual “work”. I do, actually respect the notion that CO_2 concentration should be modelled by a set of coupled ODEs. I also am perfectly happy to believe that some of the absorption mechanisms — e.g. the ocean — are both sources and sinks, or rather are net one or the other but which they are at any given time may well depend on some very complicated, nonlinear, non-Markovian dynamics indeed. In this case trying to write a single trivial integral equation solution for CO_2 concentration (one with a visibly absurd asymptotic behavior) is counterindicated, is it not? In fact, in this case on has to just plain “do the math”.
The point is that one may, actually, be able to write an integrodifferential equation that represents the CO_2 concentration as a function of time. It appears to be the kind of problem for which a master equation can be derived (somebody mentioned Fokker-Planck, although I prefer Langevin, but whatever, a semideterministic set of coupled ODEs with stochastic noise). That is not what the equation given in the link Willis posted is. That equation is just a mistake — all gain terms and no loss terms. Perhaps there is a simple sign error in it, but as it stands it is impossible.
rgb?
E.M.Smith says:
May 6, 2012 at 2:38 pm.
=========================
Saharan/African dust……….
“I do, and if you tell me what A, B and C are, and what the equations represent, I’ll tell you whether or not I believe the coupled system of equations or the final solution.”
See my previous comments above.
I should perhaps clarify – I don’t consider the BERN model ansatz to be more than a simplistic approximation, and make no comment on its validity or physical significance. I’m just explaining the intuition behind it.
If you have several linked buffers with different rate constants for transfer between them, the system of differential equations generally has a sum-of-exponentials solution. (Or sinusoidal oscillations if some of the eigenvalues are imaginary.) That’s why they used that model to fit the simulation output. It sounds vaguely plausible as a first approximation, but beyond that I make no comment on whether they’re right to do so.
I’m not sure which equation Willis linked you mean.
Dan Kurt says:
May 6, 2012 at 2:48 pm
CO2 is constantly and irreversibly being sequestered into the formation of insoluble carbonates
==================
Gosh Dan, you just explained how denitrification is possible without carbon………….
Nullius,
Thanks for that very effective toy model, and the follow up bit on the effect of the different tank sizes. I’m sure it needs many add ons and caveats, but as a quick and accessable mental model to use as a starting point, for someone who thinks visually, it is a beauty.
Willis,
I have not yet plowed through all the comments so if this is redundant please forgive me. What you have described as the Bern model sounds a lot like a multi-compartment first-order elimination model similar to that of some drugs. A simple one-compartment, first-order elimination model is concentration dependent. That is, you put Drug X into the body and it will be eliminated primarily through one route (usually the kidneys). You have t1/2 elimination constant and about five half-lives later the body has essentially cleared the drug. Some drugs like aminoglycoside antimicrobials have a simple and rather restricted distribution in the human body. Their apparent volume of distribution (a purely theoretical metric derived for the purposes of calculation) is roughly that of the blood volume. Other drugs have very unusual volumes of distribution. An ancient (but good) example is that of digoxin. You can give a few daily doses of 250 µg of digoxin and end up with an observed serum concentration in the ng range much lower than one might anticipate. That drug has gone somewhere else other than the apparent blood volume.
This is where we get into multi-compartment models. A single drug may occupy the blood volume, the serum proteins, adipose tissue, muscle tissue, lung tissue, kidney tissue, lung tissue and brain tissue. Each tissue “compartment” is associated with its own in-and-out elimination constants so a steady state, single elimination constant is virtually impossible to quantify.
I know nothing about the the Bern Model so I can only surmise that maybe this is an elaborate model built on multi-compartment, first-order elimination kinetics. Then again, you have to consider the possibility of zero-order (non-concentration dependent) kinetics. Drugs like ethanol follow this model. If one keep ingesting alcohol at a certain point the liver’s capacity to metabolize alcohol is overwhelmed. We see a real-life “tipping point.” Once those metabolic pathways in the liver become saturated, every additional gram of alcohol ingestion produces a geometrically higher EtOH serum concentration (i.e. blackouts).
I have no idea if any of this is relevant. But what you described bore an amazing resemblance to multi-compartment, first-order kinetics. Still…on a personal level I think it’s BS. Different drugs behave differently in the human body. I have a hard time believing CO2 (a “single drug”) behaves differently in the atmosphere as a whole.
Willis:
I am pleased that you notice some problems with the Bern Model because the IPCC uses only that model of the carbon cycle.
I am especially pleased that you observe the problem of partitioning. In reality, the dynamics of seasonal sequestration indicate that the system can easily absorb ALL the anthropogenic CO2 emission of each year. But CO2 is increasing in the atmosphere.
Importantly, as your question highlights, nobody has a detailed understanding of the carbon cycle and, therefore, it is not possible to define a physical explanation of “partitioning” (as is used in all ‘plumbing’ models such as the Bern Model). Hence, any model that provides a better fit to the empirical data is a superior model to the Bern Model.
I remind that one of our 2005 papers proves any of several models provide better representation of atmospheric CO2 increase than the Bern Model.
(ref. Rorsch A, Courtney RS & Thoenes D, ‘The Interaction of Climate Change and the Carbon Dioxide Cycle’ E&E v16no2 (2005)) Bern Model requires for it to match the data. The six modelseach match the empirical data for each year.
However, the six models each provide very different ‘projections’ of future atmospheric carbon dioxide concentration for the same assumed future anthropogenic emission. And other models are.
Assertions that isotope ratio changes do not concur with these conclusions are false.
Richard
Oddly enough I read your post whilst in a “Tidal wetland” that I had visited to observe the spring *super moon” tides. Been doing this for more years than I care to remember but the tide was no higher than I’ve seen before (nowhere near), the estuary just as vibrant as ever but the first time I have ever seen a bird surface before me with a wriggling fish in its beak and gobble it down.
KR says:
May 6, 2012 at 2:08 pm
Disingenouus? So you are calling me a liar and a deliberate deceiver, except you are doing it politely?
KR, you can apologize for calling me a liar and we can continue the discussion. Or not.
Your choice.
w.
[Note: logic fixed, the way I wrote it made no sense. Teach me to write when my blood is angrified. -w.]
Wet lands are usually replaced by pasture. Another sink.
Secondly, every previous run up of CO2 has been followed by significant drop. So obviously some other factor9s) may come into play.
Brad says:
May 6, 2012 at 3:14 pm
Haven’t a clue who the “you” is that you are talking about. Me? rgbatduke? KR? Someone else?
Also, rather than saying “you do understand” X, Y, or Z, it would be much more useful if you quote exactly the words you disagree with, and then tell us why you think they are wrong.
Next, please note how what I wrote differs from if I were to have simply asked “You do understand how to respond to a blog post, right?”
Asking that, just like you asking the questions in your post, goes nowhere. You need to point out what you think is wrong, and point out where it is wrong, and tell us how to do it right.
Finally, “where is your degree from?” is a very unpleasant ad hominem. It doesn’t matter where anyone’s degree is from. What matters is, are they right or wrong.
w.
the first thing I noticed is “tau” time calculated to 3 (three!!!) significant figures. A good sign that those involved have NO clue what they are doing. Now let me finish reading…..
“rgbatduke says:
Now, as to your actual assertion that the rate that CO2 molecules are “snatched from the air” is proportional to the concentration of molecules in the air — absolutely. However, for each mode of removal it is proportional to the total concentration in the air, not the “first fraction, second fraction, third fraction”. The CO2 molecules don’t come with labels, so that some of them hang out anomalously long because they are “tree removal” molecules instead of “ocean removal” molecules. ”
This is indeed true, but it presents a problem to the modelers. They know that any saturatable process does not have first order kinetics as it approaches saturation; but if they allow all the first order processes to ‘see’ the whole atmospheric [CO2], then they end up with a rate constant that is the sum of all the rates. They have to artificially add in saturation limits, supported by lots of arm waving, to make their box models spit out the result they want; a saturatable sink.
Take a look at the marine biotica. Total mass 3GtC, annual fixation of carbon, 50GtC. A good fraction of the 50GtC is converted in ‘poop’ and falls to the bottom. If there is oxygen present some is converted to CO2, A lot is encased in mud. The figure of 150 GtC in the sediments is bollocks; that is only the carbon in the surface of the sediment. There is 20,000,000 GtC of Kerogen at the bottom of the oceans; this has been removed from the Wiki figures over the past year. The Kerogen is the true sink of the Carbon Cycle and it can only have come from the biosphere,
The ultimate test of the Bern Box Model is to measure the relative ratios of 14C in the ocean depths. After nuclear testing a large series of 14C were generated and this disappeared from the atmosphere with a t1/2 of about a decade. According to the Bern model, the vast majority of this 14C should be in the upper surface of the ocean, and lower amounts in the ‘saturatable’ sinks.
Look at figure 4
14C is higher at depths less than 2000m than at 2000m; this means the flux of particulate 14C to the bottom is high, then the organic material is partly gasified, CO2/CH4, and rises.
The 14C numbers of the H-bomb tests are not well modeled by the Bern Box models, but they get around it by having a difference in the equilibrium time between surface water and air of CO2, depending on if the isotope is 12C or 14C. Arguing that 12CO2:12CO2 were at equilibrium and 14CO2:14CO2 were not.
right or wrong in that, but for what it is worth the link to the paper is on the line below:
Good paper. Agree or disagree, he is very clear about what he models and the assumptions in it and how he sets his parameters.?
I’m not rigid in my thought process at all. I am looking at the equation Willis linked! Are you? Is there something in that equation that makes you think that it it could possibly be correct? The point I’ve been making is that even if you remove the exponential decaying parts from the kernel entirely, you are left with an integral of
from
to the present. I can do this integral in my head for any non-compact function
— it is infinite. Ignoring the
and integrating from “a long time ago but not infinity” in such a way that you get the right baseline behavior is obviously wrong in so many ways, if that is what they do.
would remain constant for eternity.
This is clearly absurd, as I’ve tried to say so many times now.
We could then go on and address the rest of the kernel, the part that actually might make physical sense, depending on how it is derived. But it is then difficult, actually, to have it make a LOT of sense because the result would almost certainly have a completely incorrect form if $latexE(t)$ were suddenly set to zero. I could be convinced otherwise, but it would certainly take some effort, because then those “buckets” that are basically fairly arbitrary terms in an approximation to a very odd decay function, one that describes a very highly nonexponential process, not a sum of mixed differential processes.
In physics mixed exponential processes are far from unknown. For example, if one activates silver with slow neutrons, two radioactive isotopes are produced with different half-lives. If you try to determine the half lives from the raw count rate, you find that one of the two isotopes decays much more quickly than the other, so that after a suitable time the observed rate is almost all the slow process. One can fit that, then subtract the back-projected result and fit the faster time constant. Or nowadays, of couse, you could use a nonlinear least squares routine to fit the two at the same time and maybe even be able to get the result from a much shorter observation time if you have enough signal.
But note well, two different isotopes. I’m having a very hard time visualizing how, if CO_2 sources all turned off tomorrow, 1/e of 32% of it would have disappeared from the atmosphere within 2.56 years via one channel, but 28% of it will have only gone down by a factor of
, while 25% of the rest will have diminished by
and 15% of it will not have changed at all. It might even be correct, but what does this mean? All of the CO_2 molecules in the atmosphere are identical. What one is really describing is some sort of saturation (as you might have noted) of some process that can never take up more than 32% of the atmospheric CO_2, no matter how long you wait, with absolutely no sources at all.
At that point I have to say that I become very dubious indeed. First of all, this implies a complete lack of coupling across the “buckets”, which is itself impossible. By the time the fast process has removed 32% of the atmospheric CO_2 — call it ten or fifteen years, depending on how many powers of 1/e you want to call zero, the concentration exposed to the intermediate process has had its baseline concentration dropped by a third or more. This, in turn, destroys the assumptions made in writing out sums of exponentials in the first place, and so its time constant is now meaningless because the CO_2, unlike the silver atoms, has no label! It is quite possible that whatever process was involved in the 18 year exponential decay constant removal has switched sign and become a CO_2 source, because the reason given for not just summing the exponential decay rates of the independent processes is that they are not independent.
Finally, one then has to question the uniqueness of the decomposition of the decay kernel. Why three terms (plus the impossible fourth term)? How “linearized” were the assumptions that went into constructing it, and how far does
have to change before the assumptions break down? This is a pretty complex model — wouldn’t simpler models work just as well, or even better? Why write the solution as an integral equation at all instead of as a set of coupled ODEs?
The latter is the big question. If
were constant or slowly varying or there was some kernel of meaning to be extracted from converting the ODEs into an integral equation, there might be some point. But when one looks at the leading constant term, presumably added because without it the model is just wrong, it leads to instantly incorrect asymptotic behavior. Surely that is a signal that the rest of the terms cannot be trusted!. The evidence is straightforward — there are times in the past when CO_2 concentration has been much higher. Obviously the monotonic term is fudged over the real historical record or CO_2 now would not be less. But nothing in this equation predicts the asymptotic equilibrium CO_2 concentration if
is zero. In fact, it creates a completely artificial baseline CO_2 that the decay kernel parts will regress to, one that varies with time to be ever higher now in spite of the fact that one simply didn’t do the integral over all past times and in fact imposed an arbitrary cut-off or something so that it didn’t diverge.
Am I somehow mistaken in this analysis? Is there some way that the baseline CO_2 concentration produced by this model is not strictly increasing from an absolutely arbitrary amount that is whatever value you choose to assign the integral before you really start to do it, say 1710 years in the past (ten of the slowest decay times)?
I’ve done my share of fitting nonlinear multiple exponentials, and you can get all kinds of interesting things if you have three of them and a constant to play with, but there is no good reason to think that the resulting fit is meaningful or extensible.
rgb
P.S. My degree in physics is from Duke. And I’ve published papers on Langevin models in quantum electrodynamics, and spent a decade doing Monte Carlo and finite size scaling analysis that involved fitting exponentially divergent quantities (and made my share of mistakes, and could easily be mistaken here — this is the first few hours I have looked at the equation, after all). But still, wrong/completely nonphysical asymptotic form is not a good sign when looking at a model, as I point out just as emphatically when it is CAGW doubters (like Nikolov and Zeller who propose a model for explaining atmospheric heating that contains utterly nonphysical dimensioned parameters) that come up with it.
And yeah, it disturbs me a lot to talk about “buckets” in a three term exponential decomposition of an integral equation kernel supposed to describe a systems of great underlying complexity with many feedback channels and mechanisms. It’s too many, or too few. Too few to be a good approximation to a laplace transform of the actual integral kernel. Too many to be physically meaningful in a simple linearized model. If you want to write
I’m all for it, but be aware that the
you end up with from an empirical fit are, well, shall we say open to debate in any discussion of physical relevance or meaning, especially one where the mechanisms they supposedly represent can themselves have nontrivial functional dependences.
And in the end, if you have a believable model, why not just integrate the coupled ODEs? That’s what I’d do, every time. If nothing else it can reveal places where your linearization hypotheses are terrible, as you add or tweak detail and the model predictions diverge.
Do you disagree?
[Formatting fixed … I think … -w.]
IMO…until someone can produce evidence that some atmospheric CO2 changes into SUPER CO2 that is time resistant to sequesters…………….
CO2 sequesters are blind to the object [ CO2 ].
The only evidence we have is the variability of the sequester – some do it faster.
rgbatduke: I often read the thread backwards (for various reasons), and I’ve learned to distinguish your comments well before I scroll all the way up to your name. They really stand out. Thanks for participating.
This model doesn’t seem to jive with the idea that the atmosphere is well mixed. It would seem to me that the model would be better characterized by using diffusion models similar to those used in electrochemical systems in soluton.
Freeman Dyson proposed “growing” topsoil (Biomass) as a means to fighting climate change – which he is sceptical of – as this would be more cost effective than reducing emissions and have a positive benefit for agriculture whilst resolving excess CO2.
Why haven’t the greens supported this innovative idea ?
I think it clearly shows the “climate change” debate is about political powerand not much else !
It reads like a weighted average that has not yet been averaged – and perhaps shouldn’t be. If so, then the 1.33 year sink never does fill up, and indeed does keep sequestering, however the size of the “pipe” is only 8% so can not do the whole job in 1.33 years (it would take about 17 years). Meanwhile, while the 1.33 is busy running, so are the slower sinks. So the combined rate would be something less than 17. To go back to the tank of water example, it is like having a single tank with lots of pipes to drain it, let’s say 100. 8 of those pipes are of a size that would empty the tank in 1.33 years if there were 100 of that size. The other 92 pipes on our tank are sized to correspond to the sequestration (drainage) rate of the other partitions. To try a different analogy, it’s like having 100 people drinking from a pitcher of beer the size of a swimming pool. Some are using garden hoses, some are using straws, and others are using fibre optics. The pool eventually empties, everyone gets some beer, just some get a lot more than others.
Willis Eschenbach
You asked: “what is the physical mechanism that is partitioning the CO2 so that some of it is sequestered quickly, and some is sequestered slowly?”
Perhaps the writeup you linked to was just not clear enough, or you interpreted the approximations presented as the model itself – if so, my sincere apologies. It seems quite clear to me what the page () presented: approximations of the Bern model () results for how much and how fast CO2 ends up in different partitions, based upon that model of the carbon cycle, as those percentages. Not parameters, not the model itself, but an approximation of the model results. Results presented so that other researchers could use that approximation in their own work, with the stated caveat that “Parties are free to use a more elaborate carbon cycle model if they choose.”
I’m therefore finding quite difficult to see how you arrived at the interpretation you posed when writing the original post – that there is somehow an initial “partitioning”. That’s neither a correct description of the Bern model results nor of the UN page you linked to…
@Latitude says:May 6, 2012 at 3:26 pm
“Gosh Dan, you just explained how denitrification is possible without carbon………….”
So you are a bean farmer!
Dan Kurt
jimboW,
Thanks. It’s appreciated.
rgbatduke,
“However, for each mode of removal it is proportional to the total concentration in the air, not the “first fraction, second fraction, third fraction”. The CO_2 molecules don’t come with labels,”
As I mentioned above, the fractions are not a separation of the atmosphere into labelled portions, but a consequence of the relative sizes of the reservoirs. If water flows from tank A to tank B until levels equalise, and the tanks have equal surface area, they converge on the midpoint and half the water added to tank A stays there. If you add another bucketload to A, they equalise again and half the new bucket goes to B. It’s not some magic form of CO2 that hangs around for longer, it’s just the effect of the level increasing in the destination reservoir.
\rho_{CO_2} would remain constant for eternity.”
Ah, right. I’ve figured out what you’re talking about, now.
Yes, that is what the equations says, because it doesn’t include the very long term geological sequestration processes that take place on the order of thousands of years. Those components would have no significant effect – they’d look effectively constant – over the time intervals they ran the simulations for. The first fraction represents all those time constants too big to measure.
CO2 is conserved. If you chuck it into a system with no exits, it will stay there forever..
Hello Willis,
I don’t know anything about this model but I can tell you that there are different physical models which would have similar behaviour.
Consider a thermal model where you have multiple heatsinks with different thermal resistances and heat storage capacity connected to a source of heat via interfaces with different thermal resistances.
A small heatsink connected to your heat source via a low thermal resistance will absorb heat quickly but its temperature will quickly reach equilibrium with the source so it will stop absorbing heat after a short period. At the same time, a large heatsink connected to the heat source via a high thermal resistance will only absorb a small amount of heat but it will take a lot longer to reach equilibrium so it will continue to do so for a long time.
You could come up with a similar electronic model where you have multiple capacitors with different capacities and leakages connected to a node via different value resistors.
I can see how nature could exhibit similar characteristics.
Having said that, their model seems like a clumsy approximation. I don’t know why they don’t use free electronics modeling tools like SPICE which are perfect for examining the response of systems with multiple time constants to perturbations. SPICE has been around for a while and is pretty much perfect for this sort of task. You just have to convert your model into capacitors, resistors and inductors which isn’t very hard. It’s done all the time with thermal modeling.
All modelers are looking towards the next funding round and sensationalism wins the day every time. “Nature”, despite its unwarranted kudos, is not a scientific journal, it is a magazine.
I dont know too much about carbon cycle in the diagram, but I’m very suspicious about the figures concerning the sediments and the sea. As usual, they have forgotten about volcanoes.
The oceans contain mid ocean ridges and other undersea volcanoes that exchange vast amounts of c02 and other elements and minerals with seawater; none of this is represented in the diagram. The mid ocean ridges themselves strech for tens of thousands of kilometres. I know from personal experience that sediments adjacent to underwater voclanoes are enriched in carbonate, as I have drilled though thousands of metres of them. This carbonate exists in a complex arrangement with the heat and c02 sourced from the volanoes, as well as the carbonate in seawater, and I also suspect these undersea volcanoes buffer the acidity of the oceans as a whole-ie if the aicidity of the ocean oes up-more volcanic carbonate is deposited in the sediments-if the ocean acidity goes down-more carbonate is dissolved.
Volcanism has never really been very popular amongst the greens, because they arent very ‘green’ to begin with.
Let’s back away from the problem just a bit and look at some data on carbon. Carbon in the world is located in the following locations/situations:
The question is then how does carbon dioxide convert -get into- the various forms of carbon storage or sinks? The times for each sink are obviously highly variable with the water bodies being the shortest, vegetation being second and the sedimentary rocks probably being the longest. With data perhaps one could develop relative time intervals. To me, using different times is acceptable for a model, I just don’t like the times and percentages used by the authors. They have made it too simple and precise of a problem.
One has to be careful of pinch points when dealing with something that is only .1% of the whole. In human time frames only water bodies and vegetation are of probable interest. Winds and currents are of the most interest with clearing and replanting of forests and jungles being of important interest as well.
With the CO2 in/out ratio being so constant, I am suspicious of oxidation of limestones and dolomites being undercounted in any material balance calculations. Ninety Nine point nine percent doesn’t have to change very much to sway the other times considerably.
The CO2 uptake can be fitted to give a reasonable match in a number of different ways. My guess is that the Bern model is very wrong because it ignores a dominant process: thermohaline circulation, which leads to absorption of lots of CO2 at high latitudes in cold ocean regions with deep convection. Some of the sinks in the Bern model are real, but almost certainly the model is not an accurate predictor of future CO2 absorption; it suggests far too short a time to “saturate” the system with CO2. Consider a simpler simpler fit to the data: Just as good a fit, and more physically reasonable.
The future absorption of CO2 with rising CO2 in the atmosphere will be much higher than the Bern model suggests, and for a very long time (at least several hundred years).
Nicholas says:
May 6, 2012 at 5:42 pm
Thanks, Nicholas. The problem with your model is where you say the sink “will stop absorbing heat”.
The reason it’s a problem is that we know that the sinks have not stopped absorbing CO2. If they were saturated, the airborne fraction (the amount that remains airborne of the amount emitted annually) would be rising. This is just as in your thermal model, when the heatsinks stop absorbing heat, the temperature will rise.
But the airborne fraction has not been rising, which means that the CO2 sinks are not saturating, and so your model fails.
Regarding SPICE, you are right that it would be a good model to use, but to mangle Shakespeare, “The fault, dear Brutus, is not in our models but in ourselves” … a model is only as good as the theory underneath it.
w.
JFD says:
May 6, 2012 at 6:03 pm
I fear you miss the point. The different sinks absorb at different rates, but that doesn’t mean that somehow 13% of the CO2 is immune to sequestration by any but the slowest processes. The faster processes will continue to remove CO2.
w.
To electrical engineers, the impulse response model (the equation) in the link is quite unremarkable – just an ordinary linear system. On our benches, it would look like a bunch of R-C low-pass circuits in parallel (six of them I guess). The partitions (gain constants) and time constants are parameters of the model, and could be derived from rho(t) by deconvolution, if we knew E(t). This assumes the system really is linear (the one on the bench is), and is exactly the sum of six real poles. The theory is straightforward and manipulations such as “Prony’s method” and “Kautz function analysis” are long-established (and quite beautiful ).
That noted, attempting to apply this mathematical procedure to a true CO2 concentration curve is of course, utter nonsense. Likely the CO2 situation is not even linear in the first place, and the measured curves are subject to large systematic and random errors. For a circuit on the bench, we could at least cheat and peek at some of the component values. But for the atmosphere, there are no actual partitions, or separable processes with-defined characteristic times. There are NO discrete components – let alone ones we could identify and measure! It’s just a silly over-beefy model.
For CO2, It is doubtful there would be any usable physical reality to even a single pole model. It’s very very far from being a circuit on a bench.
KR says:
May 6, 2012 at 5:15 pm
No, I asked for an apology before I’d continue the discussion. Or not. Your choice.
In other words, you are saying that IF I was not trying to be deceptive, you apologize …
In other words, no apology at all.
You have accused me, without a shred of evidence, of trying to deceive people. When you are called on it, you say well, if you weren’t trying to deceive people I apologize …
Look, KR, I’m an honest man, and damn proud of it. It seems you may not have had much interaction with my particular breed. I tell the truth as best I know it. I’m sometimes wrong, sure, more often that I’d like to admit … but I admit it nonetheless.
The part you seem to be missing is that to accuse me of trying to deceive people is a nasty, underhanded, slimy tactic.
That’s what you need to apologize for, and it doesn’t depend in the slightest on whether “the writeup I linked to was not clear enough”. Your false allegation is scurrilous, sleazy, untrue, and insulting, whether or not the writeup was clear … and your apology is a joke.
w.
Willis, you are one of the great ones. I very much appreciate your keen mind and the quickness and width of your knowledge and interests. I read your treatises first, always.
I just see that it doesn’t take much exposure to the air of near surface carbonates, arising from landslides, floods, hurricanes, earthquakes; you name it, to introduce enough additional CO2 to the atmosphere to offset the removal by the other sinks. Thus, in human time, there will always be CO2 in the atmosphere no matter what the faster processes do in removing CO2.
I have 99.9% versus .1% in my favor, grin.
JFD
JFD says:.
No carbon in volcanoes, mid ocean ridge systems? Ever heard of carbonitite volcanoes?
Bill Illis says:
May 6, 2012 at 1:16 pm
“It will take about 150 years to draw down CO2 to the equilibrium of 275 ppm if we stop adding to the atmosphere each year. Alternatively, we can stabilize the level just by cutting our emissions by 50%”
——————————————–
Why would we want to do that?
People upthread have said that I misunderstand the situation. They say he equations that I linked to, with the partitions and the various time constants. are not the model. The actual model, they say, is the computer box-model that generated those partitions and time constants.
I have understood that from the start. What those folks fail to consider is the first line of the linked file, which says:
Parties are free to use a more elaborate carbon cycle model if they choose.
However, a number of the IPCC participants use the simple model given in the linked file. And for those folks, THAT IS THE MODEL THEY ARE USING. They are not using the underlying computer box-model. They are using the simple model given in the linked file.
My point is, as far as I know, that simple model is physically impossible. It doesn’t matter where they get the values for the various parameters (and in fact they use various values).
The problem is, the world simply doesn’t work that way. There is no factual basis for the simple model.
In addition, Robert Brown above shows that not only is the simple model physically impossible, it leads to ludicrous boundary conditions. That’s another, and separate, strike against the model.
In any case, yes, I know that’s not the more complex model. It says that in the first line of the linked file. I do read, you know.
But for the folks using the simple model, that’s the only model they are using. They’re not using the box model, or any even more complex model. They are using the simple model, and that’s the model I’m objecting to.
w.
Sure, I’ve heard of carbonitite volcanoes. They have a high percentage of limestone and dolomite (calcium/magnesium carbonates) in them. They are in the 99.9% of carbon listed first in my post.
_Jim says:
May 6, 2012 at 1:12 pm
73’s back atcha …
H44WE
There was an extensive set of meaurement published in several peer reveiwed papers by by teams of scientists working at Princeton University at the beginning of the 21Century.
Unlike the bovine pasture patties “precise” half-entry, non-debit only, “bookeeping accounting” produced by the EPA, these scientyists measured the CO2 content on the Air blowing in from the Pacific prevailing winds, into North America and they measured what happened to it as it traversed over the continent, and then measured CO2 as it exited on the prevailing winds blowing out over the Atlantic. They discovered it rose over the industrialized Coasts, and the again in industrial midwest, but decreased as it traversed the forests, ranchlands of the West, the breadbaskets of the grasslands and the eastern and southern forests. They also reported the North America continent absorbs much more than it emits by both Man and Nature. The Air blowing out over the Atlantic has much less CO2 the air entering the continent, despite all that the most industrialized country adds.
North America is the biggest Carbon Sink on the Planet and proves there is absolutely no need for America to have any concerns about CO2, even if you concede that CO2 is of any concern at all except to a botanist. If Eurasia produces net CO2, let them remove it. We have already done all we need to do and much more.
“A Large Terrestrial Carbon Sink in North America Implied by Atmospheric and Oceanic Carbon Dioxide Data and Models
S. Fan, M. Gloor, J. Mahlman, S. Pacala, J. Sarmiento, T. Takahashi and P. Tans” Science 16 October 1998:
Vol. 282 no. 5388 pp. 442-446
DOI: 10.1126/science.282.5388.442
, is just typically one of many such papers, that the CAGW Eco-Druids, managed to suppress and/or ignore.
Meanwhile the EPA eco-druids total the reports which estimate the kilo pounds that human industries report emiting; and in their half-assed accounting haven’t found a way to intimidate the mighty Oak and Pine to fill out their bureaucratic forms and to report how many megatons they and their saplings absorb, so don’t bother to include any considerations of that.
ferd berple says:
May 6, 2012 at 12:39 pm
“Nonsense. The oceans cannot tell if that 1/2 comes from this year or last year.”
rgbatduke says:
May 6, 2012 at 2:35 pm
“Dearest Bart, Piffle.”
Guys… if you jump to conclusions and assume your opponents are completely witless without even bothering to understand their reasoning, you are never going to be effective. To get an idea of what they are thinking, consider a simple atmosphere/ocean coupled model of the form
dA/dt = a*O – b*A + H
dO/dt = b*A – a*O – k*(1+a/b)*O
A = atmospheric CO2 concentration
O = oceanic CO2 concentration
H = anthropogenic inputs
a,b,k = coupling constants
The “a” and “b” constants control how quickly CO2 from the atmosphere dissolves into the oceans. The “k” constant determines how quickly the oceans permanently (or, at least, semi-permanently, i.e., sufficiently long as to be of little consequence) sequester CO2.
If you are familiar with Laplace transforms, you can easily show that the transfer function from H to A is
A(s)/H(s)= (s + a + k*(1+(a/b)) / (s^2 + (a + b + k*(1+a/b))*s + k*(a+b) )
Under the assumption that “a” and “b” are much greater than k, this becomes approximately
A(s)/H(s) := (a / (a + b) ) / (s + k)
This approximate transfer function describes a system of the form
dA/dt := -k*A + (a / (a + b) )*H
A similar calculation for O will yield
dO/dt = -k*O + (b / (a+b) )*H
Thus, the fraction a/(a+b) of H accumulates in the atmosphere, and b/(a+b) accumulates in the oceans. The total a/(a+b) + b/(a+b) = 1, so all of it either ends up in the land or in the oceans.
The IPCC effectively says a is approximately equal to b, hence roughly 1/2 ends up in each reservoir in the short term. If this seems unreasonable to you, well, we aren’t done yet, so keep your powder dry. In actual fact, the processes involved are much more complicated than this. Obviously, for one thing, we haven’t included the dynamics of the land reservoir.
And, because the dynamics are governed by diffusion equations, partial differential equations (PDE) which can be cast as an infinite expansion of ordinary differential equations (ODE) (this is a key result of functional analysis), the scalar equations can be expanded into infinite dimensional vector equations, with the components of the vectors summing up to the total. Each component has its own gain and time constant associated with it, and can thereby be considered a partition of the total CO2. It is a mathematical construct, not a physical one, which approximates the physical reality only when it is all summed together.
That is how the Bern model is constructed. I am not saying it is constructed correctly, I am just telling you it is on firm theoretical grounds, and you guys are attacking the castle wall at its most fortified location, instead of just walking around to where they haven’t even laid the first stones.
I’ll acknowledge a personal lack of mathematical virtuosity, but there seem to be two ways of applying mathematics to physical phenomena.
The first is to come up with some ‘cocktail-shaker’ combination of numbers and functions that somehow fits observations and accurately models the past, thus inspiring confidence that it may be useful for predictions. This is essentially ‘hit-and-miss’ with little genuine understanding required, but can be useful for complex, analysis-defying systems.
The second is to accurately quantify and incorporate ALL relevant factors with their correct relationships. This requires a high degree of understanding and becomes progressively more difficult as system complexity increases. Indeed, with something like the weather or CAGW I have to wonder at the claimed reliability of ANY model.
I like to think that mathematicians are gainfully employed but, surely, some phenomena are not readily amenable to mathematical modelling. Will a significant increase in CO2 lead to evolution of more CO2-hungry organisms? Exactly how big a role does the sun play and how do we know what it’s going to do next? What about cosmic rays? I’ve barely scratched the surface here and we’re arguing about the application of high mathematics to poorly-understood phenomena. What’s the weather going to be like next month?
Frankly, I believe that the study of crystal orbs or chicken entrails is just as likely to deliver an understanding of climate as the Bern Model or its rivals.
Surely, fans of this website have noticed that it is a lot easier to poke holes in the asinine pronouncements of the doomsayers than it is to come up with a robust alternative. Think about the reasons for this.
(Wet blanket now hung out to dry.)
I look at the CO2 anual variations of the Hawaii observations due to just the seasonal temperature variations and it is 300% of the annual increase. The ocean’s breath is 3 times the annual increase of the supposed human footpring.
I think David Archer is describing the “Bern” model clearly here.
I think they’re arguing that CO2 quickly reaches a balance with sea surface and plants, but is slow to reach balance with the ocean depths. Forr a simple example, if the CO2 ratios in
the oceans’ top layer, in plants,,in the atmosphere, and ocean depths was 2, 1, 1, and 48,
and an additional unit of CO2 was dumped into the system, the balance would quickly reach
2.5, 1.5, and 1.5, but the 48 ocean depth is acting a lot slower, on a scale of about 800 years.
I think the drop in C14 since the nuclear testing spike in the early 1960s is a counter example to the Bern- David Archer model.
Seems to me plants will grab as much CO2 as they can get their grubby leaves on.
Since the CAGW claim is CO2 is “Well Mixed” then the reduction of CO2 in the atmosphere by plants should be governed only by how fast new CO2 can be transported via diffusion or wind into contact with the leaves.
Hydroponic Shop
Given the evidence from the wheat field (C3 plants) that plants will use all the CO2 in their vicinity, coupled with absorption of CO2 by water (rain is a weak acid due to dissolved CO2) I find the residence times over a couple of years very tough to swallow.
As Ian W says:
And of course as the CO2 is brought back to the surface the plants on land and in the ocean gobble it up.
I find myself agreeing with Bart here. And with Nullius, who I think is expressing the right idea, and also with the electrical circuit analogies.
To rephrase Bart (I think) you have a Laplace Transform representation, and you approximate the integrand by a set of poles. Or, if you want to think of it in the real domain, you have the idea that your response can be represented as a weighted average of a whole lot of exponentials (that’s just math), and then you choose a few to be representative.
But you can also see it in electrical terms with resistance-capacitance circuits. Each R-C pair has a time constant, reflecting the timescales in the Bern Model.
And yes, it’s also a multi-box model, and they have difficulties.
I’m glad to see Willis’ appendix – the two different time constants are indeed poorly understood.
The only thing that makes sense to me is the model they are using is assuming saturation of the various processes and assigning a % to that sink. That is, once the fastest sink saturates they assign a value to it, then they look at the 2nd fastest sink and so on. What’s eventually left goes into the slowest sink.
I didn’t read the link but I can’t think of any other way they could generate those percentages.
“CO2 evolves according to a higher-order linear equation (or a system of first-order linear equations that is the same). Very reasonable. That is where the “partitioning” comes,”
NO, NO, NO, NO, NO.
CO2 does not do anything “according to” any equation.
We humans use equations as fair, simlar MODELS of reality. A molecule of ANYTHING never checks some equation to see how to behave. Never.
That is our human imagination that a falling object’s speed “follows” some formula, etc.
This may not seem like a big point, but it makes all the difference in the world. The natural world does not behave according to formulas, with us discovering the formula. The natural world behaves. We develop models that APPROXIIMATE this behavior. If we are lucky.
There seems to be confusion about the integral equation in the link. It is simply a “convolution integral” which says that the output is the input
convolved with the impulse response – very standard stuff. The impulse response, the term in [ ], does (in their formulation) contain a step, but IT is not inside the integral BY ITSELF. It is inside multiplied by E. E in turn can be thought of as a single impulse (or usually as many, possibly an infinite number) of impulses. Thus we may integrate TO a step. This simply means there will be a scaled version of the input in the output. A non-decaying exponential in the impulse response. Overall this corresponds to an exact (actual) circuit configuration.
It seems to me – we should think of CO2 here just like charge on a capacitor. In the circuit, individual (isolated) charges are restricted to their own capacitor (drained by an individual resistor). This is NOT what happens in the atmosphere – obviously. It’s all one capacitor and all the individual sinks are one resistor. Wrong model, and probably a faulty physical understanding.
First thing is, the expression is not the Bern model, it is approximation (regression) of the Bern model. You can understand individual factors as regression coeficients which usually have very limited connection to reality.
Second thing, the categorization of CO2 sinks in SAR has probably nothing to do with categorization of CO2 sinks in TAR – SAR works with five “main sinks”, TAR works with three completely different “main sinks”. In each case real considered CO2 sinks are assigned to five or three groups for simplicity in a way so that differences in each group more or less cancel out to provide consistent behavior of the group.
In order to visualise the expression, divide earth surface to six (SAR) or four (TAR) parts, proportional to coefficients a(0) to a(n). a(0) is part of earth surface which does not act as carbon sink, the rest are carbon sinks with “sinking” effectivity given as tau(n). Also understand that proportion of Earth surface also corresponds to proportion of atmospheric volume above that surface.
The coefficients tau(n) specify effectivity of individual sinks – if tau(1) is 171 and tau(2) is 18 it only means that sink 1 would do with the atmosphere in 171 years what sink 2 would do with it in 18 years, if there was only sink 1, respective sink 2 all over the world.
In the paper they claim that a) wetlands are a large and significant sink for carbon, and b) they are “rapidly diminishing”.
They’re also a large and significant source of methane. As for the “rapidly diminishing” part, I can only assume they believe that any (cue scary music) sea level rise (cut scary music) will cover existing wetlands (aka, “tidal swamps”) without creating new ones…
Bart says:
May 6, 2012 at 7:47 pm
Thanks, Bart. So … where in your derivation do we find the part about the division of the atmosphere into partitions, each of which has a different time constant? That’s the part that seems problematic to me, and I didn’t see anything about that in your math, although I could have overlooked it. What am I missing?
w.
JFD says:
“Sure, I’ve heard of carbonitite volcanoes. They have a high percentage of limestone and dolomite (calcium/magnesium carbonates) in them. They are in the 99.9% of carbon listed first in my post.”
You only mentioned sedimentary rocks, volcanic source rocks are not sedimentary rocks, they source material from the mantle. (as well as recycling material from the crust and from the ocean at plate boundaries). But until there is a mantle cycle ( eg mid ocean ridges) and a subduction cycle (eg largely at plate boundaries) in the carbon cycle diagram, the carbon cycle diagram as shown, is astonishingly incomplete. As I said before, carbonate and volcanoes in the oceans are involved in large scale exchanges, especially along mid ocean ridge systems, and in island arcs. These are not accounted for in the carbon cycle diagram of the IPCC. Carbonitites are another example, contianing >50% carbonate, although the origin of this carbonate is disputed.
As I also mentioned, this is important because I suspect the mid ocean ridges and other volcanoes play a role in e.g. buffering ocean acidity. This is not accounted for by marine biologists, of course.
Bart says:
May 6, 2012 at 7:47 pm
Bart, a question. Why is the rate at which the ocean sequesters CO2 a function of 1 + a/b ? Isn’t it a totally different physical process? Why should it depend on the rate of air/sea exchange?
w.
Nick Stokes says:
May 6, 2012 at 8:22 pm
“But you can also see it in electrical terms with resistance-capacitance circuits. Each R-C pair has a time constant, reflecting the timescales in the Bern Model.”
The characteristics of transmission lines fit this description, and transmission line models are often used to characterize so-called pink noise.
Willis Eschenbach says:
May 6, 2012 at 10:16 pm
“…where in your derivation do we find the part about the division of the atmosphere into partitions, each of which has a different time constant?”
At the part where I said: ” partial differential equations… can be cast as an infinite expansion of ordinary differential equations… Each component has its own gain and time constant… It is a mathematical construct, not a physical one, which approximates the physical reality only when it is all summed together.”
Bart says:
May 6, 2012 at 11:43 pm
Thanks, Bart, but I still don’t see where you get the partitioning. My understanding (which of course may be wrong) is that in an infinite expansion, each term applies to the entire thing, not e.g. 13% of the total for one term and 26% of the total for the second term and the like.
For example, the expansion of Cos(x)/x = 1/x – x/2 + x3/24 – x5/720 + …
But nowhere in there do I find x broken into “13% x / 720 +26% x / 720 …”
Also, normally an infinite expansion has alternating positive and negative terms which decrease in size. This is not true of their expression, where all terms are positive and are of different sizes …
Thanks for your patience in the explanations. As I said at the start, that’s what I’m looking for.
w.
Bart says:
May 6, 2012 at 7:47 pm
Erratum – This sentence should read: “The total a/(a+b) + b/(a+b) = 1, so all of it either ends up in the atmosphere or in the oceans.” The model I demonstrated did not include the land dynamics. Its main purpose was to show how roughly 1/2 of the CO2 could end up rapidly transported from the atmosphere into the oceans without becoming permanently sequestered from the overall system.
As I stated above, I believe this description is moot. That it is mathematically possible is not confirmation that it is the governing process, and the rather strong correlation between CO2 and temperature which I have pointed out indicates that to me that it is an unimportant question. Temperatures are driving CO2 concentration, and not the reverse.
Bart, let me try to explain it a different way. If I understand you, you are saying that the equation that they give in the linked file is an infinite expansion of a transfer function based on the underlying box model.
But if that were the case, why would there be a variety of numbers of terms, along with different coefficients for the terms? If it is an infinite expansion, wouldn’t it have defined coefficients with defined corresponding time constants? They use two forms, for example, one with six terms and the other with four terms. The terms have different coefficients, and apply to different fractions of the whole … how is it possible that that is “an infinite expansion of ordinary differential equations” as you say?”
Willis Eschenbach says:
May 7, 2012 at 12:06 am
‘For example, the expansion of Cos(x)/x = 1/x – x/2 + x3/24 – x5/720 + …
But nowhere in there do I find x broken into “13% x / 720 +26% x / 720 …”’
I assume you mean, if “y = Cos(x)/x”, nowhere do you find y broken into “13% x / 720 +26% x / 720 …”’
But, nothing is stopping you from doing so.
“Also, normally an infinite expansion has alternating positive and negative terms which decrease in size. This is not true of their expression, where all terms are positive and are of different sizes …”
Not generally. For example, exp(x) = 1 + x + x^2/2 + x^3/6 + … The coefficients have to decrease in size or the expansion will not converge. But, the decrease does not have to be monotonic. For example, (1 + x^2)*exp(x) = 1 + x + 1.5*x^2 + 7/6*x^3 + …
Of course, exp(x) is unbounded as a function of x. But, the polynomial base functions are, themselves, unbounded. In the Bern model, the basis functions are decaying exponentials, so this is not a concern. For example, I can expand
(1 + exp(-x)^2)*exp(exp(-x)) = 1 + exp(-x) + 1.5*exp(-2*x) + 7/6*exp(-3*x) + …
Willis Eschenbach says:
May 7, 2012 at 12:16 am
“If it is an infinite expansion, wouldn’t it have defined coefficients with defined corresponding time constants?”
The function is not known a priori, so the coefficients have to be estimated based on observables (my beef being that the observables are not enough to provide a complete description, and not very certain, either). Different estimation techniques and assumptions tend to yield different results.
In addition, practically speaking, you have to truncate the expansion at some point – there generally is not enough information rich data to estimate all the coefficients, and the more coefficients you try to estimate, the more uncertain each estimate becomes. Always, there is a tradeoff between bias and variance. The only question is whether the bias and variance can be small enough for the estimate to be useful.
So, to wrap it up for now, theoretically, the procedure is sound. But, practically speaking, there are plenty of good reasons to be wary, even skeptical (or, downright disbelieving, as I am), of the parameterization.
Dr Burns says:
May 6, 2012 at 1:30 pm
In relation to sources and sinks, can Willis, or anyone else explain this image of global CO2 concentrations ?
Why does Antarctic ice appear to be such a strong absorber in parts and why such strong striation?
I think the striations are due to mid-troposphere southward flows of air with relatively high CO2 feeding surface northward katabatic winds.
But I was unable to find a study that supports this, so just a guess on my part.
Haven’t read all the replies, so this point might have been made.
Exponentials are not orthogonal functions like sine waves, and cannot be picked out of a mixture with any accuracy. Noisy data simply exacerbates the problem. Declaring exponential constants to four significant figures is a triumph of optimism.
Mike
“Thanks, Bart. So … where in your derivation do we find the part about the division of the atmosphere into partitions, each of which has a different time constant? That’s the part that seems problematic to me”
Where he says:
“Thus, the fraction a/(a+b) of H accumulates in the atmosphere, and b/(a+b) accumulates in the oceans. The total a/(a+b) + b/(a+b) = 1, so all of it either ends up in the land or in the oceans.”
If a fraction a/(a+b) stays in the air, the time constant for the transfer only applies to the CO2 transferred, which is a proportion b/(a+b) of the total atmosphere..
And the difference between the atmosphere and one sink may be different to the difference between the atmosphere and another sink.
The other thing being assumed is that the CO2 transferred has no effect on the level of CO2 in the sink, that it acts like an infinite void, or an idealised thermodynamic cold sink that can absorb any amount of heat without changing temperature. While there’s no doubt the ocean is a lot bigger than the atmosphere, it’s not infinitely bigger, and to start with only the top layer of the ocean is affected. The level in the sink increases as it absorbs CO2, and the rate of flow is proportional to the difference in levels. So the flow pushes the source to decrease and the sink to rise until they converge on an intermediate level, when flow stops. It’s not because the reservoir is full, or saturated. It’s simply because the levels are equal. If you add more CO2, it will go up again. If you keep adding CO2 it will go up continuously. Stop and the flow will slow and stop, but it decays away exponentially to the intermediate level, not the original level. (A fraction a/(a+b) stays in the air.) This is at some fraction of the difference between them, and that’s where the apparent partitioning comes from.
I’ll try the tanks example with some numbers, in case that helps. Tanks A and B have 1 square metre horizontal cross sections, but are very tall. Tank C has a 98 square metre cross section, and is again tall. The level of water in all three tanks is 3 metres. We now dump a pulse of 3 cubic metres into tank A. Instantaneously the level in that tank doubles to 6 metres. Very quickly, because of the wide pipe connecting them, A drops to 4.5 metres and B rises to 4.5 metres as 1.5 cubic metres of water flows between them. Note that the 3 cubic metres added has been partitioned – half of it has transferred and half stayed. Only 1.5 metres is affected by the rapid exponential decay. Then over a far longer period, the 4.5 metres in A and B equalises with the 3 metres in C. 3 cubic metres (2x(4.5-3)) is spread evenly over 100 square metres, for an equilibrium depth of 3 centimetres. Tanks A and B slowly drop to 3.03 metres, and C even more slowly rises to 3.03 metres. There is 3 cm of permanent rise.
None of the tanks are full. If you dump another three cubic metres into tank A, half of it will still drain into tank B just as rapidly as before. The sink is not saturated, its capacity for absorption not reduced. You could dump 300 cubic metres into it and half would still transfer to B with the same rapid rate constant. But only half.
Willis and others:.
I again point to our 2005 paper which I referenced in my above post at May 6, 2012 at 3:58 pm. As I said in that post, agreement of output of the Bern Model requires 5-year smoothing of the empirical data for output of the Bern Model to match the observed rise in atmospheric CO2 concentration.
The need for 5-year smoothing demonstrates beyond doubt that the Bern Model is plain wrong: the model’s basic assumption is that observed rise of atmospheric CO2 concentration is a direct result of accumulation in the air of the anthropogenic emission of CO2, and the needed smoothing shows that assumption cannot be correct.
(Please note that – as I explain below – the fact that the Bern Model is based on the false assumption does NOT mean the anthropogenic emission cannot be the cause of the observed rise of atmospheric CO2 concentration.)
I explain this as follows.
For each year the annual rise in atmospheric CO2 concentration is the residual of the seasonal variation in atmospheric CO2 concentration. If the observed rise in the concentration is accumulation of the anthropogenic emission then the rise should relate to the emission for each year. However, in some years almost all the anthropogenic CO2 emission seems to be sequestered and in other years almost none. And this mismatch of the hypothesis of anthropogenic accumulation with observations can be overcome by smoothing the data.
2-year smoothing is reasonable because different countries may use different start-dates for their annual accounting periods.
And 3-year smoothing is reasonable because delays in accounting some emissions may result in those emissions being ‘lost’ from a year and ‘added’ to the next year.
But there is no rational reason to smooth the data over more than 3-years.
The IPCC uses 5-year smoothing to obtain agreement between observations and the output of the Bern Model because less smoothing than this fails to obtain the agreement. Simply, the assumption of “accumulation” is disproved by observations.
Furthermore, as I also said in my above post, the observed dynamics of seasonal sequestration indicate that the system can easily absorb ALL the CO2 emission (n.b. both natural and anthropogenic) of each year. But CO2 is increasing in the atmosphere. These observations are explicable as being a result of the entire system of the carbon cycle adjusting to changed conditions (such as increased temperature, and/or addition of the anthropogenic emission, and/or etc.).
The short-term sequestration processes can easily absorb all the emission of each year, but some processes of the system have rate constants of years and decades. Hence, the entire system takes decades to adjust to any change.
And, as our paper shows, the assumption of a slowly adjusting carbon cycle enables the system to be modelled in a variety of ways that each provides a match of model output to observations without any need for any smoothing. This indicates the ‘adjusting carbon cycle’ assumption is plausible but, of course, it does not show it is ‘true’.
In contrast, the need for smoothing of data to get the Bern Model to match ‘model output to observations’ falsifies that model’s basic assumption that observed rise of atmospheric CO2 concentration is a direct result of accumulation in the air of the anthropogenic emission of CO2.
Richard
Willis and others:
I write this as an addendum to my post at May 7, 2012 at 2:09 am.
As several people have noted, the Bern Model is one example of a ‘plumbing model’ of the carbon cycle (personally, I think Engelbeen’s is the ‘best’ of these models).
Adjustment of the carbon cycle is akin to all the tanks and all the pipes varying in size at different and unknown rates. Hence, no ‘plumbing model’ can emulate such adjustment.
And the adjustment will continue until a new equilibrium is attained by the system. But, of course, by then other changes are likely to have happened so more adjustment will occur.
Richard
Bart,
Not sure about the infinite expansion.
I think the number of decaying exponentials is the number of reservoirs minus one.
It’s a system of coupled first-order linear differential equations. If we put the levels in all the n reservoirs into an n dimensional vector L, the homogeneous part is dL/dt = ML for some matrix of constants M. This can be diagonalised dL/dt = (U^-1 D U) L so we can change variables d(UL)/dt = D(UL) and the coupled equations are separated into independent differential equations each in one variable. Once we’ve solved for the variables UL, we can transform back to the original variables.
The matrix is of rank n-1, since we lose one degree of freedom from the conservation of mass. We therefore ought to get n-1 decaying exponentials for n reservoirs.
So if we stop all fossil fuel CO2 the level of CO2 in the atmosphere would drop. There would be a modest fall in global temperature. At what level would the amount of CO2 in the atmosphere stabilise? And as the natural processes of the carbon cycle continue then
1) What is the source of CO2 to maintain stability as the natural sequestering processes would continue as sediments fall below the earth’s surface? Is it essentially just volcanoes?
2) Based on this stable level of atmospheric CO2 what reduction in biogrowth would we expect vs current levels of CO2?
3) What limits would such a fall put on potential global agricultural production vs projected growth in world population?
4) Should we be capturing carbon now so that when carbon fuels run out we can inject CO2 into the atmosphere to maintain agricultural production levels?
Its not clear to me whether the various carbon sinks are acting in series or parallel.
Let’s say the ocean is a fast carbon sink and plankton photosynthesis is a slow carbon sink. The ocean takes up CO2 and then plankton remove it from the water and it sinks to the deep. An initial pulse of CO2 would be reduced quickly, but the ocean would become saturated, then there would be a long tail as the plankton removed it at the same rate as there was further uptake by the ocean.
Is this going in the right direction? Don’t know enough myself.
Thanks Willis for responding to my comment, which was based on a misunderstanding of the link I gave. But what an interesting post, question and comments. I learn something new here every day.
The question, ” what is the physical mechanism that is partitioning the CO2 so that some of it is sequestered quickly, and some is sequestered slowly?” seems to be unanswerable, which perhaps makes the Bern Model wrong and therefore its use by the IPCC wrong.
Particularly as “there is no experimental evidence that will allow us to distinguish between plain old exponential decay (which is what I would expect) and the complexities of the Bern model”.
The Svensmark paper mentioned carbon dioxide being scarce when supernovas were high based on the idea that plants dislike carbon dioxide molecules containing carbon-13, which were then absorbed by the ocean. But this doesn’t seem relevant so apologies if I’m talking through my proverbial.
I look forward to your further posts on sinks and the e-folding time. You have that rare knack for getting straight to the heart of a theory.
son of mulder:
At May 7, 2012 at 2:49 am you ask;
“So if we stop all fossil fuel CO2 the level of CO2 in the atmosphere would drop. There would be a modest fall in global temperature. At what level would the amount of CO2 in the atmosphere stabilise?” etc.
I answer;
Please read my above post at May 6, 2012 at 3:58 pm because it explains why it is not possible for anybody to provide an answer to any of your questions (although some people claim they can).
Richard
Published in January 2008 at
Excerpt:
The four parameters ST (surface temperature), LT (lower tropospheric temperature), dCO2/dt (the rate of change of atmsopheric CO2 with time) cannot cause the past.
Faux Science Slayer says
The oceans do NOT absorb CO2 from the atmosphere
——–
The measurements says otherwise..
You might find it useful to plot a graph of the correlation coefficient between temperature and lagged CO2 as a function of the lag. That’s the usual way to make lagged relationships clear.
A long time ago I worked on developing an inverse technique for deducing isotope concentrations based on the results of degassing experiments on minerals. It turned out to be mathematically equivalent to a constrained numerical inversion of the Laplace transform. Unfortunately, this is known to be an incredibly ill-conditioned problem.. I would be quite skeptical of anyone who purported to do both.
I notice that the little cartoon diagram fails to include the sequestration as concrete sets.
Bill Tuttle says:
May 6, 2012 at 10:15 pm
….They’re also a large and significant source of methane. As for the “rapidly diminishing” part, I can only assume they believe that any (cue scary music) sea level rise (cut scary music) will cover existing wetlands (aka, “tidal swamps”) without creating new ones…
________________________________
The “rapidly diminishing” part also sticks in my craw. In the USA swamps are busy forming as the !@#&* beaver dam up streams and creeks. My pretty little creek is now a large multi-acre swamp despite the power company having a guy trap over two hundred beaver in one year. The nearest city, with a drinking water inlet just down stream from the outlet of my creek, now has a Giardia/Beaver Fever problem according to the county Inspections Department guy I asked.
I should also note that the beaver dam raised the water table so high that along with the beaver pond there is now an additional 40 acres that is too soggy to support the lob lolly pine that had been growing and the field beyond the pines is also too wet to plow. That is just on my land. It does not include the addition hundred or so acres belonging to my neighbor.
I should also add about this to the “rapidly diminishing” part.
Running water performs three closely interrelated forms of geologic work:
1. Erosion
2. Transportation
3. Deposition
As rivers erode the river bed the angle of incline becomes lower. In “old age” or where a river/stream dumps into a lake, pond or ocean you get flood plains with low relief across which the water flows meander causing braided channels, deltas and marshes. As the eroded sediment is dumped into lakes and ponds they fill and the later stages are swamps and marshes.
Mankind using dredging can to some extent modify this geologic progression but with “wetlands protection” in many advanced western countries “rapidly diminishing” stopped thirty years ago and has more likely changed to “rapidly advancing” ever since.
In 1971, the international Convention on Wetlands was adopted…The Ramsar List of Wetlands of International Importance includes nearly 2,000 sites, covering all regions of the planet.
In other words this is a recycling of the old “Boogy Man” from the 1960’s for a new generation of ignorant bleeding hearts who are unfamiliar with the complex tangle of international treaties, conventions and accords.
(BTW bleeding hearts is not a derogatory term, it is the con-men using people’s compassion that I have the problem with. Civilization requires EDUCATED bleeding hearts to keep the predators in check. Most people on WUWT fit the category of educated bleeding hearts, or we would not give a darn what happens to future generations.).
No, it doesn’t. I understand perfectly well what this model does. If we feed it:
as input — your “emissions pulse” (which we’ll have to assume is uniformly applied, since I imagine that it takes times commensurate with the shortest decay time to mix a bolus through the entire atmosphere) — then it states that — given an initial concentration at
of
which we’ll assume was established in the distant past so that it is constant, the concentration will be the following:
and we are right back where we started, asking why the bolus of CO_2 that was added at time $t_0$ came with four labels and is removed by a sum of exponential processes acting on labelled partial fractions of the whole.
There are two things immediately apparent about this. First, no matter how long you wait, the asymptotic behavior of this is:
It does not decay. This is a monotonically growing model and if it were true we would see CO_2 inexorably increase over the ages because even the 171 year time scale is absurd — it really says that we keep 40% of every delta function “blip”, every breath, the foam from every beer, in the atmosphere, indefinitely. It says that almost 30% of the gasp of breath Albert Einstein exhaled when he first realized that Planck’s quantum hypothesis could explain the photoelectric effect is still with us, not just 30% of the molecules but 30% of the additional concentration that it represented. There is no rate of addition of CO_2 that can lead to equilibrium with this solution but zero.
If this doesn’t strike you as being a blatently political but well-concealed scientific lie, well, you are very forgiving of a certain class of error.
Error, you say? Yes, error. Obvious error. If you will check back to my first post — and Bart’s remarks, if he will take the time to go back and check them, and K.R.’s remarks as he accuses Willis of being less than sincere — it appears that we all agree that there is no way in hell atmospheric CO_2 concentration will decay as a sum of exponentials because this is a horrendous abuse of every principle that leads one to write down exponential functions in the first place. CO_2 does not come with a label, and decay processes act on the total concentration to reduce it until equilibrium is reached. The only conceivable correct local behavior is the product of competing exponentials, never the sum.
Now, it was asserted (by K.R. and perhaps Bart, hard to recall) that the integral presented wasn’t really the sum of exponentials but something way complicated that does in fact arise from unlabelled CO_2 in some math juju magic way. By presenting you with the actual integral of a delta function bolus of CO_2, I refute you. Perhaps K.R. can apologize for his use of “disingenuous” to describe Willis’ stubborn and correct assertion that it did. I have never known Willis to be anything but sincere…;-)
Now, it would be disingenuous to continue without an actual explanation of two things:
a) Why anyone should take seriously a model that cannot — note well cannot — ever produce an equilibrium given a non-zero input function
. That is an absurdity on the face of it — surely there is a natural rate
that would maintain an equilibrium CO_2 concentration, within noise, on all time scales, and equally certainly it won’t take the Earth thousands of years or even hundreds to find that equilibrium. Indeed, I’ve written a very simple linear model for — at least in a linear response model in which exponentials are themselves appropriate — how the equilibrium concentration must depend on the input and total decay rate. My model, gentlemen, will reach follow equilibrium wherever the input might take it. The Bern model, my friends, has no equilibrium —
increases without bound for any input at all, and not particularly slowly at that.
b) Far up above, I thought that we all agreed that a model that consists of a weighted sum of exponentials acting on partial fractions of the partial pressure was absurd and non-physical, because CO_2 does not come with a label and each process, being stochastic and proportional to the probability of a CO_2 molecule being presented to it, proceeds at a rate proportional to the total CO_2 concentration, not the “tree fraction” of it. I have now conclusively proven that hiding that behavior in a convolution does not eliminate it from the model. What, as they say, is up with that?
The onus is therefore upon any individuals who wish to continue to support the model to start by justifying equation (1) above for a presumed delta function bolus. A derivation would be nice. I want to see precisely how you arrive at a sum of exponential functions each acting on a partial fraction of the additional CO_2, with a “permanent” residual.
rgb
[Formatting fixed … I think. w.].
Yes, but in order for the model to be correct, none of the reservoirs can be in contact with absolute zero, and if the model doesn’t permit the attainment of equilibrium on a reasonable time scale and in a reasonable way, it is just wrong. So why, exactly, will the biosphere adjust its equilibrium upwards? Why won’t the ocean follow the temperature instead of some imagined “fractional difference” leading it to an every higher base equilibrium concentration? Noting well that the total atmospheric CO_2 is just a perturbation of oceanic CO_2 so that for all practical purposes it is an infinite reservoir.
rgb
rgbatduke,
Thanks for the extensive reply. I’ll try to take each of your points systematically. Let me know if I miss anything important.
Your equation (1) contains a number of negative exponentials, which decrease in value over time. That’s what I meant by “decay”.
I already explained why it came with four ‘labels’. Because there are effectively five reservoirs, and five coupled linear ODEs.
Yes, the asymptotic behaviour is that $0.15 E_0$ remains. That’s partly because I think some very slow decay terms are being approximated, and partly because mass is conserved, and if you add CO2 to a system then the total amount of CO2 in the system must increase.
This doesn’t include Einstein’s last breath, though, because that’s part of the exchanges being modelled. The exchange with the biosphere reservoir includes both plants growing and animals eating them. $E_0$ is CO2 added from outside the modelled system.
If you pour water into a container with no exits, the water level increases forever. There is no equilibrium in which the level tails off to a constant, even though you’re still adding more water. Why do you assume there *has* to be an equilibrium?
I try not to assume motive without evidence.
I went through the business about labelling and whether decay is proportional to total concentration or the difference in concentrations previously. If decay is proportional to total concentration, you could only reach equilibrium when total concentration was zero.
I don’t consider anyone here to be disingenuous. Willis asked a sensible question, the answer to which I agree is not at all obvious. And I can quite see where you’re coming from with this.
a) You say “surely there is a natural rate E(t) > 0 that would maintain an equilibrium CO_2 concentration”. Why?
b) I agree CO2 doesn’t come with a label. But I’ve already explained that the partition is a mathematical artefact of the ratio of reservoir sizes, and that a portion does not get transferred because the level rises somewhat in the sink as a result of the transfer.?
The probability of a CO2 molecule moving from A to B is proportional to the total CO2 concentration in A, but the probability of a molecule moving from B to A is proportional to the total concentration in B. The net flow from one to the other is proportional to the difference in concentrations.
“A derivation would be nice. I want to see precisely how you arrive at a sum of exponential functions each acting on a partial fraction of the additional CO_2, with a “permanent” residual.”
See my comments above regarding the equation dL/dt = ML and diagonalisation. The algebra is messy, but straightforward.
MikeG says:
May 7, 2012 at 1:31 am
“Declaring exponential constants to four significant figures is a triumph of optimism.”
Or, something. Agree completely.
richardscourtney says:
May 7, 2012 at 2:09 am
“This indicates the ‘adjusting carbon cycle’ assumption is plausible but, of course, it does not show it is ‘true’.”
Absolutely. The system is underdetermined and not fully observable. Thus, to get an answer, the analysts have to insert their own biases. The likelihood that they would hit on a faithful model, out of all the possibilities, is vanishingly small.
Nullius in Verba says:
May 7, 2012 at 2:45 am
“The matrix is of rank n-1, since we lose one degree of freedom from the conservation of mass. We therefore ought to get n-1 decaying exponentials for n reservoirs.”
The reservoirs themselves are a continuum. For example, what is the land reservoir? It is trees, grasslands, soil bacteria, rock and sediment formation, mammals, reptiles, amphibians, insects, etc… And, the dynamics of the atmosphere are diffusive. Areas of high and low concentration appear randomly, and the divergence increases near the surface sink. The eigevalues of the Laplacian operator are limitless. So, basically, you are correct, but n tends to infinity.
Gail Combs says:
May 7, 2012 at 6:06 am
My pretty little creek is now a large multi-acre swamp despite the power company having a guy trap over two hundred beaver in one year.
If you had dammed the creek to create a small pond for migrating waterfowl, the EPA would have forced you to tear down your dam (they have the backing of the DoJ) and fined you several thousand dollars for interfering with a watercourse and creating a potential health hazard. Because beavers built the dam, any action you might take (like accidentally dropping a stick of dynamite in the center of the dam) to assist the creek to return to it’s previous state would render you subject to horrendous fines for destroying a Giardia-filled wetland.
Just one more reason to gut the EPA…
[Formatting fixed. -w.]
rgbatduke says:
May 7, 2012 at 8:06 am
“There is no rate of addition of CO_2 that can lead to equilibrium with this solution but zero.”
Yes. As I have been saying, the model is mathematically, theoretically sound. But, they have parameterized it in such a way that it gives the answer they wanted, vastly underestimating the power of the sinks to draw out a substantial fraction of the atmospheric constituents in the near term. There is no data available to establish that the model is correct.
In fact, we know it is incorrect, for the very simple reason that temperature is driving the rate of CO2, and not the other way around. It is obvious in this plot that anthropogenic inputs have, at best, a minor role in establishing the overall concentration. Temperature variation accounts for almost all of it.
Nullius in Verba:
At May 7, 2012 at 9:16 am in relation to a ‘plumbing model’ you ask;
?”
I answer:
It goes into a change in the volume(s) of the reservoirs.
In other words, the model is misconceived. Please see my above post at May 7, 2012 at 2:09 am and especially its addendum at May 7, 2012 at 2:44 am.
Richard
My Occamized Hypothesis is:
Geology and geogenesis put a sh**-load of CO2 into the early atmosphere. Eventually, life forms (flora) arose able to build themselves and proliferate by using photons to combine H2O and CO2. Shortly, eaters (fauna) evolved to munch on said flora. The flora expanded with little restraint and consumed CO2 until it began to run short. They then evolved to survive on less, but kept going. They are now approaching a lower limit, variously guesstimated to be in the region of 130-260 ppm — famine time. Fauna mass and volume and numbers track this, more or less.
So the “ideal number” is the lower limit, as that’s what the dominant life forms (flora) keep trying to achieve. Warmies are mental vegetables, so they also want to flirt forever with suicide by famine.
Simples!
So.
richardscourtney says:
May 7, 2012 at 2:09 am
Richard, your paper is paywalled, so I fear I won’t be able to comment. That may be the reason your claims have gotten little traction, because you are referring to an unavailable citation.
All the best,
w.
I could be mistaken, but it seems to me that this Bern Model has appropriated a perfectly good concept of “impulse response” and other ideas of Laplace transform theory encountered by electrical engineers in “Linear Systems Theory.” The theory is of course correct in its EE version. The climate application is highly flawed: first in its inappropriate misapplication, and then in its poor implementation (at least a failure to do it with orthogonal basis functions).
So we are left with comments here pointing out the failings in the climate application. Quite so. But this does not reflect back and invalidate the theory as used in EE. Perhaps you do need to sketch the corresponding circuit (it involves R-C low-pass sections with a common input E (setting time constants), buffered, weighted, and summed (the partitioning lacking in the atmosphere). The equation in the link is correct. The convolution integral does not blow up. Think about electrons on discrete capacitors, not CO2 in the one atmosphere.
Given enough parameters (recall von Neumann’s delicious joke about an elephant modeled with 5 parameters), most mathematical constructions can be made to work locally. A polynomial can model a sinewave locally – but soon runs rapidly to infinity! Wrong choice. Only a fool would try to bake a cake in a refrigerator. But after that failure, should we decide it was not suitable for cooling lemonade?
It does no good to attempt to find fault with established linear systems theory. What seems to be wrong is the inappropriate application attempt, or at least considering it anything more than a local model (no physical meaning).
“a2videodude says:.”
Absolutely correct. In a chemical reaction the measured first order rate constant IS the sum of all the first order rate constants, which are individual collisions of molecules of differing energy and colliding on different vectors.
I normally cringe from citing Wikipedia, but there is an interesting plot of carbon-14 concentration since 1945 at en.wikipedia.org/wiki/Carbon-14 that shows an exponential decay (removal of C-14 excess over background levels) consistent with an e-folding time on the order of a decade. The reason for the excess? Atmospheric nuclear testing. A never-to-be-repeated experiment.
Willis:
Thankyou for your comment to me that says;
“Richard, your paper is paywalled, so I fear I won’t be able to comment. That may be the reason your claims have gotten little traction, because you are referring to an unavailable citation.”
OK, I understand that, and I am not arguing that it get “traction”. In this thread I have been pointing out what the paper says so those points can be considered in the context of arguments about the Bern Model.
Also, I have a personal difficulty in that the paper was published in E&E and I am now on the Editorial Board of E&E so I cannot give the paper away. That said, I presented a version of it at the first Heartland Climate Conference and that version is almost completely a ‘cut and paste’ from the paper so I could send you a copy of that if you are interested to read it.
Regards
Richard
Willis Eschenbach
I spent some time re-reading the thread, and you are completely correct. It was entirely inappropriate for me to ascribe ill intent, and I would like to sincerely apologize for doing so in what should be a discussion of the science. Mea culpa, I was wrong. Please – call me on such things if I cross that line again.
—
With respect to the science: I thought it was quite clear that the exponentials and constants in the link you provided () are not the Bern model itself, which is described in Siegenthaler and Joos 1992 (). That is a multi-box model involving eddys, surface uptake, and the physics of mid-term CO2 absorption, with transport parameters calibrated against carbon-14 distribution measurements – complexities not in that page of exponentials.
Rather, they are approximate exponentials and fractions fitted to the results of running the Bern model, providing other investigators with some tools to estimate mid-term CO2 effects. Along with the caveat that “Parties are free to use a more elaborate carbon cycle model if they choose”. For example, the Bern model does not include CaCO3 chemistry or silicate weathering, long term carbon sinks.
So, as a starting point of discussion on the science:
– Is it clear that those exponentials are not the Bern model?
I am just amazed that nobody has commented on the relationship I have pointed out numerous times, which clearly shows that temperature has been driving CO2 concentration. It is obvious here that there simply is no need to consider human emissions to any significant level. This very simple observation kicks the very foundation out from under the Climate Change imbroglio.
KR says:
May 7, 2012 at 4:47 pm
KR, my thanks to you. It is the mark of an honest man and a gentleman to acknowledge when he has gone over the line. You have my sincere acknowledgement and appreciation.
I thought I had been clear above when I said:
My point is that whether you are using the Bern Model itself, or the simpler model described in the paper that I linked, it needs to be physically plausible and lead to physically plausible results. The problem is that the simple model that I linked to, which emulates the Bern Model, does neither.
My best to you, and again my thanks for your honesty,
w.
Willis Eschenbach – “”…as far as I can see, the Bern model proposes an impossibility. It says that the CO2 in the air is somehow partitioned, and that the different partitions are sequestered at different rates”
I really don’t understand this statement. There are multiple parallel and serial processes occurring in the fairly simple Bern model, and the approximations (constants for weighting and time factor) are just approximations for the various and multiple (parallel and serial) inter-compartment transfer rates. The percentages allow considering different CO2 pulses, and the time factors show how the Bern model inter-compartment movements show up.
There certainly is no initial partitioning of a CO2 input in the Bern model. The complexities of the model, its behavior, are just curve-fitted. Much in the way nuclear reactor fuel decay can be fit with a decaying exponential, regardless of the internal physics – a behavioral description. The exponentials are purely descriptive, behavioral analogs to the Bern model, which was (if I interpret that initial page correctly) provided as one potential resource. The issues raised with compartmentalization are really irrelevant.
I (IMO) don’t believe it’s appropriate to criticize the Bern (or any other model) from that standpoint – two steps back, arguing about the curve-fit to the model behavior. Rather, if you wish to truly critique a model, you need to show where the model itself breaks down. And since there is as far as I can see no discussion here of the assumptions, parameters (fit to among other things the carbon-14 data), and compartmentalization of that model, what is being discussed really isn’t the model at all.
That is not to say that the Bern model is a thing of perfection. It’s 20 years old, does not include long term sequestration such as CaCO3 or rock weathering, a simplistic biosphere compartment, and (as Joos et al note in their paper) has some latitude dependent inaccuracies with replicating C-14 measurements. But to quote George Box, “Essentially, all models are wrong, but some are useful”. A critique of this model needs to show how the model fails to meet observations – something that simply hasn’t been done on this thread.
There has been no demonstration that the model itself isn’t useful – that requires an evaluation against the data. If it fits the data, it’s useful. If it doesn’t, it’s not. I have seen no discussion of the model behavior against observations.
KR says:
May 7, 2012 at 7:53 pm
“A critique of this model needs to show how the model fails to meet observations – something that simply hasn’t been done on this thread.”
Ahem..
Bart
The Bern model is a carbon cycle model, not a temperature model, and the observations used to calibrate the Bern model are carbon-14 distributions in the oceans, also checked against (IIRC) CFC-11 distributions. In regards to the mid-term carbon cycle, the model being discussed is reasonably accurate – it matches those observations.
It would be an error to assume that CO2 is the only forcing WRT temperature, however – methane, CFC’s, aerosols, solar, and the ENSO variations are also in play. All of those affect climate forcings (and hence temperatures) as well. And all of those need to be (and are, in the literature) considered when looking at forcings and climate responses – issues beyond the realm of the carbon-cycle model discussed in this thread.
I am going to repeat what I see as a couple key points, and then add one new thought that may help in pulling them together:
1) As mentioned, the 4 exponential equation is a fit to a more complex model. The fit is statistical, not physical. The underlying model, however, is physical, with diffusive oceans and ecosystems. The first web page I found when googling Bern carbon cycle model has a bit of a description:. Note that even the Bern model is simple compared to the models used by carbon cycle researchers.
2) Nullius’ description of 3 compartments is a decent one for getting the key concept, which is that you have 2 compartments which reach equilibrium with a pulse of emissions (or added water) on one time scale, and a 3rd which reaches equilibrium with the first two on a longer time scale, and some percentage of the added water remains in the original compartment forever.
3) My key additional point, then, is that the Bern cycle approximation is meant to apply to one specific scenario, which is a pulse of carbon emissions in a system which starts at equilibrium. This is why it doesn’t match intuition applied to phenomena like constant airborne fractions, and is only a rough guide to the effect of a stream of emissions over a number of years. Though, as a side note, a constant airborne fraction is a number that depends on the rate of emissions increase, and therefore isn’t a reliable source of information about sink saturation: if next year, human emissions were to drop by a factor of 10, based on my understanding I would predict a reduction in CO2 concentrations (because emissions would be smaller than the sink), so airborne fraction would become negative too. Or if emissions grew by a factor of 10, the airborne fraction would probably grow pretty large, because the sink would not grow nearly as fast. My intuition on sinks is based on the assumption that while there is probably pretty fast equilibration between the very surface ocean and some parts of the ecosystem, the year-to-year changes in sink size will be interactions with the slower moving parts of the system which are driven by the difference between the concentration in the fast-mixing layer and the medium mixing layer.
4) While there is a “permanent” part of the Bern cycle approximation, it isn’t really permanent – carbonate formation does eventually take carbon out of the cycle and back into deep ocean and thence to sedimentary rock (on a greater than ten thousand year timescale), where it will eventually be subsumed, and in millions of years may eventually end up being outgassed by a volcano.
-MMM
KR says:
May 7, 2012 at 8:26 pm
“It would be an error to assume that CO2 is the only forcing WRT temperature…”
Indeed it would. CO2 is not forcing temperature. Temperature is forcing CO2. The fact that the derivative of CO2 is highly correlated with temperature anomaly establishes it. As I related above, the forcing cannot be the other way around without producing absurd consequences.
“In regards to the mid-term carbon cycle, the model being discussed is reasonably accurate – it matches those observations. “
A subjective exercise in curve fitting which cannot gainsay the above.
MMM says:
May 7, 2012 at 8:30 pm
“Note that even the Bern model is simple compared to the models used by carbon cycle researchers.” answer: they did not have the observations – the strong correlation has only recently become evident. CO2 has only been reliably sampled since 1958, and a real kink in the rate of change has only come about with the last decade’s lull in temperature rise.
I can only surmise that others who have taken the time to pay attention to what I have put forward here are similarly taken aback, and do not yet know how to respond. Can the solution to the riddle actually be so easy?
Yes, it can.
For those who have not been following along, the way in which CO2 concentration can be insensitive to human inputs while its derivative is effectively proportional to delta-temperature is explained here.
Bart,
Atmospheric concentrations of CO2 are slightly sensitive to anthropogenic emissions; at present, making up less than 10%..
Willis — A multiple exponential equation is typically the solution to a system of linear differential equations.
To take a simple example, reduce Fig. 2 to three reservoirs — Atmosphere A, Surface Ocean S, and Deep Ocean D. Assume their equilibrium capacities are proportional to the given values, 750, 1020, and 38,100 GtC. If this is an equlibrium, the flows in and out must be equal, so let’s take the averages and say that S to A and back is 91 GtC/yr in and S to D and back is 96 GtC/yr., that these are the instantaneous rates of flow, and that if any reservoir were to change, its outflow(s) would change proportionately.
Then
d/dt A = -(91/750)A + (91/1020)S,
d/dt S = +(91/750)A – (91/1020)S – (96/1020)S + (96/38100)D ,
d/dt D = +(96/1020)S – (96/3810)D.
Setting x equal to the column vector (A, S, D)’, this has the form
d/dt x = B x, where
B = (-91/750 91/1020 0;
91/750 -187/1020 96/38100;
0 96/1020 -96/38100)
The general solution of this system has the form
x = Sum{ c_j exp(d_j t) v_j},
where the column vectors v_j are the right eigenvectors of B and d_j the corresponding eigenvalues.
For this B, the eigenvalues are -.2615, -.0457, 0. Since I assumed for simplicity that all the C is in one of the 3 reservoirs, the changes sum to 0, B is singular, and there is one zero eigenvalue. (If I had included a permanent sink like sediments or biomass, all eigenvalues would be negative and the system would be stationary, but the math works either way.)
The corresponding matrix V of eigenvectors is approximately V =
(-.51 -.44 .02;
.81 -.36 .03;
-.29 .82 .1.00)
The column vector c of weights is determined by the initial condition x_0 = V c, so that
c = V^-1 x_0. For simplicity we may take all variables as deviations from the initial equilibrium. If x_0 = (1, 0, 0)’, so that we are adding 1 GtC to the initial value of A, c will be
c = (-.69, -1.42, .96)’. Over time, A will then be
A = c_1 v_1,1 exp(d_1 t) + c_2 v_1,2 exp(d_2 t) + c_3 v_1,3 exp(d_3 t)
= .35 exp(-.26 t)+ .63 exp(-.05 t) + .02.
The three e-fold times are 3.8, 22, and inf years. The initial unit injection is “partitiioned” into three portions of size .35, .63, .02 with different decay rates, but there in fact is no difference between the gas in the three portions. The sum simply evolves according to this equation.
The same approach can be used to solve more complicated systems, stationary or nonstationary. Does this help?
[Formatting fixed. -w.]
Thanks, Willis!
Bart says: May 7, 2012 at 9:00 pm
“I came upon this remarkable relationship between the derivative of CO2 concentration and temperature by accident just last week.”
Hi Bart – I discovered this dCo2/dt vs T relationship in late December 2007, emailed to a few friends including Roy Spencer, and published in Jan 2008 at
Please see my post above at May 7, 2012 at 3:51 am
____________________________
Nullius in Verba says: May 7, 2012 at 4:50 am
.”
Nullius, I don’t think I’ve ever said it’s just about solubility – it’s clearly not. There is a solubility component, and also a huge biological component, and others…. I did say the following in the above 2008 paper:
.”
See Murry Salby’s more recent work where (I recall) he included both “temperature” AND “soil moisture” as drivers of CO2 and got a somewhat better correlation coefficient. I have not reviewed his work in any detail.
I further think the science is substantially more complicated, with several temperature cycle lengths, each with its associated CO2 lag time.
So – is the current increase in atmospheric CO2 largely natural or manmade?
Please see this 15fps AIRS data animation of global CO2 at
[video src="" /]
It is difficult to see the impact of humanity in this impressive display of nature’s power.
All I can see is the bountiful impact of Spring, dominated by the Northern Hemisphere with its larger land mass, and some possible ocean sources and sinks.
I’m pretty sure all the data is there to figure this out, and I suspect some already have – perhaps Jan Veizer and colleagues.
Allan MacRae says:
May 7, 2012 at 10:31 pm
Well, Allan, count me an enthusiastic supporter of your position. When you view things the right way, the relationship just comes screaming out at you. Kudos for your writeup.
I knew CO2 and temperatures exhibited seasonal fluctuations which I assumed were correlated in some way, but I never realized there was such a pronounced long term correlation with the derivative and the temperatures. The alleged driving influence of human emissions can now be summed up in the famous words of Laplace: I have no need of that hypothesis.
Bart:
At May 7, 2012 at 9:00 pm you say and ask:
relationship is a demonstration of Nigel Calder’s “CO2 Thermometer” which he first proposed in the 1990s. He describes it with honest appraisal of its limitations at
And never forget the power of confirmation bias powered by research funding.
In 2005 I gave the final presentation on the on the first day of at a conference in Stockholm. It explained how atmospheric CO2 concentration could be modelled in a variety of ways that were each superior to the Bern Model, and each gave a different development of future atmospheric CO2 concentration for the same input of CO2 to the air.
I then explained what I have repeatedly stated in many places including on WUWT; i.e.
The evidence suggests that the cause of the recent rise in atmospheric CO2 is most probably natural, but it is possible that the cause may have been the anthropogenic emission. Imortantly, the data shows the rise is not accumulation of the anthropogenic emission in the air (as is assumed by e.g. the Bern Model).
A representative of KNMI gave the first presentation of the following morning. He made no reference to my presentation and he said KNMI intended to incorporate the Bern Model into their climate model projections.
So, I conclude that what is knowable is less important than what is useful for climate model development.
Richard
PS Apologies if this is a repost
Thank you Bart for your kind words,
While the dCO2/dt vs Temperature relationship is new information, I suspect that the lag of CO2 after temperature at different time scales (~800 year lag in ice core data, ~9 month in the modern instrument data record) has been long known, and only recently “swept under the rug” by global warming mania. Here are two papers from 1990 and 1995 on the multi-month CO2-after–temperature delay, first brought to my attention as I recall by Richard S Courtney:
Keeling et al (1995)
Nature 375, 666 – 670 (22 June 1995); doi:10.1038/375666a0
Interannual extremes in the rate of rise of atmospheric carbon dioxide since 1980
C. D. Keeling*, T. P. Whorf*, M. Wahlen* & J. van der Plichtt†
*Scripps Institution of Oceanography, La Jolla, California 92093-0220, USA
†Center for Isotopic Research, University of Groningen, 9747 AG Groningen, The Netherlands
________.
________
Kuo et al (1990)
Nature 343, 709 – 714 (22 February 1990); doi:10.1038/343709a0.
________
As you can see, Keeling believed that humankind was also causing an increased in atmospheric CO2. I’m not convinced, since human emissions of CO2 are still small compared with natural seasonal flux. I think human CO2 emissions are lost in the noise and are not a significant driver. More likely, the current increase in CO2 is primarily natural. I’ve heard ~all the counter-arguments by now, including the C13/C12 one, and don’t think they hold up.
It is possible that the current increase in atmospheric CO2 is primarily driven by the Medieval Warm Period, ~~800 years ago. The “numerical counter-arguments” rely upon the absolute accuracy of the CO2 data from ice cores. While I think the trends in the ice core data are generally correct, the values of the CO2 concentrations are quite possibly not absolutely accurate, and then the “numerical counter-arguments” fall apart..
Regards, Allan
Hu McCulloch, that would be a reasonable description of the system: including the magic words ‘Assume their equilibrium’. However, the system is not at equilibrium, indeed it is far from equilibrium. There are two zones of high biotic density, the first few meters of the top and the first few centimeters of the bottom. CO2 is a biotic gas and is denuded from the surface layer, as photosynthetic organisms devour it, generating oxygen. CO2 flux from the atmosphere and the lower depths to this area is high. Particulate organic matter rains down from the surface, enriched with14C. Some is intercepted and converted to CO2/CH4, but a reasonable amount reaches the bottom. Look at the numbers once again, slice the ocean into a layer cake of 1m thick layers. The bottom layer has a huge amount of carbon, and also has a higher 14C12C ratio than the bottom 3 kilometers of water. There is a very rapid, y-1, transport of organic matter directly to the bottom of the oceans.
If one wishes to defend the Bern CO2 model, do this experiment. a prior, calculate the equilibrium concentration of molecular oxygen with ocean depth. This should be trivial as 23% atmospheric oxygen gives about 250 micro molar aqueous O2 at the surface.. If the O2 concentration does not follow the physical model of oxygen partition with respect to temperature/pressure, then one must ask why CO2 should.
fhhaynie says:
Thank you for the link.
I would like to see that cross posted to WUWT BTW.
In the article it says
If the atmosphere is “accumulating the lighter CO2 faster” and “the lighter is more from organic origin” would this not indicate the increase in CO2 is more organic in origin and not from burning fossil fuels (inorganic)? (I haven’t had my morning tea yet and may be a bit blurry mentally)
On the other hand I consider coal complete with fossil ferns as “organic”
Gail,
Fossil fuels are of organic origin and have 13CO2 indexes between around -23 and -30.
“It says that the CO2 in the air is somehow partitioned, and that the different partitions are sequestered at different rates. ”
My understanding is that they simulated their “box model” to get its impulse response. They then fitted three or four exponentials, plus a constant, to the resulting impulse response.
As I said I am a bit blurry still. Dr Spencer addressed the “natural” vs “man-made” argument about the C12 – C13 ratio here:
Atmospheric CO2 Increases: Could the Ocean, Rather Than Mankind, Be the Reason?
Spencer Part2: More CO2 Peculiarities – The C13/C12 Isotope Ratio
The fact that these carbon isotope ratios are taken at Mauna Loa, the site of an active volcano that between eruptions, emits variable amounts of carbon dioxide on one hand and a CO2 “active” ocean affected by ENSO on the other does not give me much confidence in the carbon isotope ratio, C13/C12 as the purported signature of anthropogenic CO2.
That is a really small change in signal they are talking about especially given the mythical nature of CO2 as a gas well mixed in the atmosphere.
Further to Bart:
I am still pondering my conclusions in my 2002 paper – as some critics have noted, there are two drivers of CO2 – the humanmade component and the natural component, and both can be having a significant effect – critics suggest the humanmade component is dominant. I suggest the natural component is dominant.
Following my email to him, Roy Spencer also wrote on this subject at
One more reference on this subject is by climate statistician William Briggs, at
Prior work, which I became aware of after writing my 2008 paper, includes:
Pieter Tans (Dec 2007)
Tans noted the [dCO2/dt : Temperature] relationship but did not comment on the ~9 month lag of CO2.
Correction to above
I am still pondering my conclusions in my 2008 paper
Willis, I stumbled over this while looking for something else and thought it had a bit of relevance to your discussion. It is from CO2 Acquittal by Jeffrey A Glassman PhD. He discusses the politics behind partitioning CO2 in one of his responses to a comment.
a) You say “surely there is a natural rate E(t) > 0 that would maintain an equilibrium CO_2 concentration”. Why?
Because we agree that there is one, you’ve just hidden it. You yourself are using as a baseline “natural emissions”, which presumably maintain an equilibrium, one that is somehow not participatory in this general process because you’ve chopped all of its dynamics out and labelled it
. Furthermore, this equilibrium has a signficant natural variability and probably nonlinear feedback mechanisms — more carbon dioxide in the atmosphere may well increase the rate at which carbon dioxide is removed by the biosphere, for example. There is some evidence that this is already happening, and a well-understood and studied explanation for it (greenhouse studies with CO_2 used to force growth). Trees and plants and algae grow faster and photosynthesize more with more CO_2, not just more proportional to the concentration — that’s per plant — but nonlinearly more, because as the plants grow faster there is more plant. I would argue as well that the ocean is more than just a saturable buffer (although it is a hell of a buffer). In particular, small shifts in the temperature of the ocean can mean big shifts in atmospheric CO_2 concentration, either way.
But here is why I doubt this model. Seriously, you cannot exclude the CO_2 produced by the biosphere and volcanic activity and crust outgassing and thermal fluctuations in the ocean in a rate equation, especially one with lots of nonlinear coupling of multiple gain and loss channels. That’s just crazy talk. The question of how the system responds to fluctuations has to include fluctuations from all sources not just “anthropogenic” sources because as I am getting a bit tired of reciting, CO_2 doesn’t come with a label and a volcanic eruption produces a bolus that is indistinguishable at a molecular level from a forest fire or the CO_2 produced by my highly unnatural beer.
Without a natural equilibrium and with your “15% is forever” rule, every burp and belch of natural CO_2 hangs out forever (where forever is a “very long time”. You can’t ascribe gain to just one channel, or argue that you can ignore gain in one channel of a coupled channel system so that it only occurs in the others. That is wrong from the beginning.
I do understand what you are trying to say about adding net carbon to the carbon cycle — one way or another, when one burns lots of carbon that was buried underground, it isn’t buried underground anymore and then participates in the entire carbon cycle. I agree that it will ramp up the equilibrium concentration in the atmosphere. Where we disagree is that I don’t think that we can meaningfully compute how effectively it is buffered and how fast it will decay because of nonlinear feedbacks in the system and because it is a coupled channel system — all it takes is for ONE channel to be bigger than your model thinks it is, for ONE rate to experience nonlinear gain (so that decay isn’t exponential but is faster than exponential) and the model predictions are completely incorrect.
The Earth is for the most part a stable climate system, or at least it was five million years ago. Then something changed, and it gradually cooled until some two and a half million years ago the Pliestocene became bistable with an emerging dominant cold mode. One possible explanation for this — there are several, and the cause could be multifactorial or completely different — is that it could be that CO_2 concentration is pretty much the only thing that sets the Earth’s thermostat, with many (e.g. biological) negative feedbacks that generally prevent overheating but are not so tolerant of cold excursion, which sadly has a positive feedback to CO_2 removal. The carbon content of the crust might well rotate through on hundred million year timescales — “something” releases new CO_2 into the atmosphere at a variable rate (hundred million year episodes of excess volcanism? I still have a hard time buying this, but perhaps). Somehow this surplus CO_2 enters at a rate that is so slightly elevated that the “15% is forever” rule doesn’t cause runaway CO_2 concentration exploding to infinity and beyond — I leave it to your imagination how this could possibly work over several billion years without kicking the Earth into Venus mode if there were any feedback pathway to Venus mode, given an ocean with close to two orders of magnitude more CO_2 dissolved in it than is present in the atmosphere and a very simple relationship between its mean temperature and the dissolved fraction (which I think utterly confounds the simple model above).
In this scenario, the Earth suddenly became less active and the biosphere sink got out in front of the crustal CO_2 sources. At some point glaciation began, the oceans cooled, and as the oceans cooled their CO_2 uptake dramatically increased, sucking the Earth down into a cold phase/ice age where during the worst parts of the glaciation eras, CO_2 levels drop to less than half their current concentration, barely sufficient partial pressure to sustain land based plant growth. Periodically the Earth’s orbit hits just the right conditions to warm the oceans a bit, when they warm they release CO_2, and the released CO_2 feeds back to warm the Earth back up CLOSE to warm phase for a bit before the orbital conditions change enough to permit oceanic cooling that takes up the CO_2 once again.
I disbelieve this scenario for two reasons. The first is that it requires a balance between bursty CO_2 production and CO_2 uptake that is too perfectly tuned to be likely — the system has to be a lot more stable than that which is why your manifestly unstable model is just plain implausible. I respectfully suggest that your model needs to include CO_2 from all sources in
if its coupled channel dynamics is to be believable, and the long term stability of the solution under various scenarios demonstrated. If you send me or direct me at the actual coupled channel ODEs this integral equation badly represents — the actual ODEs for the channels, mind you — I would be happy to pop them into matlab and crank out some pretty pictures of the results, given some numbers. It isn’t necessary or desireable to write out the solution as an integral equation, especially an integral equation for the “anthropogenic” CO_2 surplus only, when one can simply solve the ODEs linear or not. It isn’t like this is 1960, after all — my laptop is a “supercomputer” by pre-2000 standards. We’re talking a few seconds of computation, a day’s work to generate whole galleries of pictures of solutions for various hypothesized inputs.
The second is that the data directly refutes it. Disturbed by the fact that studies of e.g. ice core data fairly clearly showed global warming preceded CO_2 increase at the leading edge of the last four or five interglacials, a recent study tried hard to manufacture a picture where CO_2 led temperature at the start of the Holocene. The data are difficult to differentiate, however.
There is no doubt, however, that the CO_2 levels trailed the fall in temperature at the end of the last few interglacials. And thus it is refuted. The whole thing. If high CO_2 levels were responsible for interglacial warming and climate sensitivity is high, it is simply inconceivable that the Earth could slip back into a cooling phase with the high CO_2 levels trailing the temperature not by decades but by centuries. A point that seems to have been missed in the entire CO_2 is the only thermostat discussion, by the way. Obviously whatever it is that makes the Earth cool back down to glacial conditions is perfectly happy to make this happen in spite of supposedly stable high CO_2 levels, and those levels remain high long after the temperature has dropped out beneath them.
Before you argue that this suggests that there ARE long time constants in the carbon cycle, permit me to agree — the data support this. Looking at the CO_2 data, it looks like a time constant of a century or perhaps two might be about right, but of course this relies on a lot of knowledge we don’t have to set correctly.
There are many other puzzles in the CO_2 uptake process. For example, there is a recent paper here:
that suggests that the ocean alone has taken up 50% of all of the anthropogenic carbon dioxide released since 1800. Curiously, this is with a (presumably)generally warming ocean over this period, and equally interesting, the non-anthropogenic biosphere contributed 20% of the surplus CO_2 to the atmosphere over the same period. So much for a steady state
contribution from the biosphere that is ignorable in the rate equation, right?
One of many reasons I don’t like the integral equation we are discussing that I find it very difficult to identify what goes where in it and connect it with papers like this. For example, what that means is that a big chunk of all three exponential terms belong to the ocean, since the ocean alone absorbed more than any of these terms can explain. How can that possibly work? I might buy the ocean as a saturable sink with a variable equilibrium and time constant of 171 years, but not one with a 0.253 fraction. In fact, turning to my trusty calculator, I find that the correct fraction would be 0.58. I see no plausible way for the time constant for the ocean to be somehow “split”. We’re talking simple surface chemistry here, it is the one thing that really does need to be a single aggregate rate because all that ultimately matters is the movement of CO_2 molecules over the air-water interface. Also, even if it were somehow split — perhaps by bands of water at different latitude, which would of course make the entire thing NON-exponential — how in the world could its array of time constants somehow end up being the same as those for soil uptake or land plant uptake?
To be blunt, the evidence from real millennial blasts of CO_2 — the interglacials themselves — suggests a longest exponential damping time on the order of a century. There is absolutely no sign of very long time scale retention. It is very likely that the ocean itself acts as the primary CO_2 reservoir, one that is entirely capable of buffering all of the anthropogenic CO_2 released to date over the course of a few hundred years. If the surplus CO_2 we have released by the end of the 21st century were sufficient to stave off the coming ice age, or even to end the Pliestocene entirely, that would actually be fabulous. If you want climate catastrophe, it is difficult to imagine anything more catastrophic than an average drop in global temperature of 6C, and yet the evidence is overwhelming that this is exactly what the Earth would experience “any century now”, and sadly, the trailing CO_2 evidence from the last several interglacials suggests that whatever mechanism is responsible for the start of fed-back glaciation and a return to cold phase, it laughs at CO_2 and drags it down, probably by cooling the ocean.
In other words, the evidence suggests that it is the temperature of the ocean that sets the equilibrium CO_2 concentration of the atmosphere, not the equilibrium CO_2 concentration of the atmosphere that sets the temperature of the ocean, and that while there is no doubt coupling and feedback between the CO_2 and temperature, it is a secondary modulator compared to some other primary modulator, one that we do not yet understand, that was responsible for the Pliestocene itself.
rgb
The evidence suggests that the cause of the recent rise in atmospheric CO2 is most probably natural, but it is possible that the cause may have been the anthropogenic emission. Importantly, the data shows the rise is not accumulation of the anthropogenic emission in the air (as is assumed by e.g. the Bern Model).
I would agree, especially (as noted above) with the criticism of the Bern Model per se. It is utterly impossible to justify writing down an integral equation that ignores the non-anthropogenic channels (which fluctuate significantly with controls such as temperature and wind and other human activity e.g. changes in land use). It is impossible to justify describing those channels as sinks in the first place — the ocean is both source and sink. So is the soil. So is the biosphere. Whether the ocean is net absorbing or net contributing CO_2 to the atmosphere today involves solving a rather difficult problem, and understanding that difficult problem rather well is necessary before one can couple it with a whole raft of assumptions into a model that pretends that its source/sink fluctuations don’t even exist and that it is, on average a shifting sink only for anthropogenic CO_2.
I’m struck by the metaphor of electrical circuit design when those designs have feedback and noise. You can’t pretend that one part of your amplifier circuit is driven by a feedback current loop to a stable steady state (especially not when there is historical evidence that the fed back current is very noisy) when trying to compute the effect of an additional current added to that fed back current from only one of several external sources. Yet that is precisely what the Bern model does. The same components of the circuit act to damp or amplify the current fluctuations without any regard for whether the fluctuations come from and of the outside sources or the feedback itself.
rgb
I am trying to find references to a major misalignment between the ice core CO2 record and modern atmospheric records of CO2, one that was allegedly “solved” by shifting the ice core record until it matched the modern record.
Can anyone help please?
d/dt A = -(91/750)A + (91/1020)S,
d/dt S = +(91/750)A – (91/1020)S – (96/1020)S + (96/38100)D ,
d/dt D = +(96/1020)S – (96/3810)D.
Finally, some actual differential equations! A model! Now we can play. Now let’s see, A is atmosphere and atmosphere gains and loses CO_2 to the surface from simple surface chemistry. Bravo. S is the surface ocean. D is the deep ocean.
Now, let’s just imagine that I replace this with a model where what you call the deep ocean is the meso ocean M, and where we let D stand for the deep ocean floor. The surface layer S exchanges CO_2 with A and with M, to be sure, but biota in the surface layer S take in CO_2 and photosynthesize it, releasing oxygen and binding up the CO_2 as organic hydrocarbons and sugars, then die, raining down to the bottom. Some fraction of the carbon is released along the way, the rest builds up indefinitely on the sea floor, gradually being subducted at plate boundaries and presumably being recycled, after long enough, as oil, coal, and natural gas reservoirs where “long enough” is a few tens or hundreds of millions of years. As a consequence, CO_2 in this layer is constantly being depleted since the presence of CO_2 is probably the rate limiting factor (perhaps along with the wild card of nutrient circulation cycles and surface temperatures, ignored throughout) on the otherwise unbounded growth potential of the biosphere here.
Carbon is constantly leaving the system from S, in other words, being replaced by crustal carbon cycled in from many channels to A and carbon from M, the vast oceanic sink of dissolved carbon. There is actually very likely a one-way channel of some sort between M and D — carbon dioxide and methane are constantly being bound up there at the ocean floor in situ, forming e.g. clathrates. I very much doubt that this process ever saturates or is in equilibrium. But because I doubt we have even a guesstimate available for this chemistry or the rates involved at 4K and at a few zillion atmospheres of pressure, nor do we have a really clear picture of sea bottom ecology that might contribute, we’ll leave this out. Then we might get:
d/dt A = -(91/750)A + (91/1020)S,
d/dt S = +(91/750)A – (91/1020)S – (96/1020)S + (96/38100)M – R_b S ,
d/dt M = +(96/38100) S – (96/38100) M
d/dt D = + R_b S
Hmm, things are getting a bit complicated, but look what I did! I proposed an absolutely trivial mechanism that punches a hole out of your detailed balance equation. Furthermore, it is an actual mechanism known to exist. It takes place in a volume of at least 100 meters times the surface area of the entire illuminated ocean. Every plant, every animal that dies in this zone sooner or later contributes a significant fraction of its carbon to the bottom, where it stays.
This is just the ocean and we’ve already found a hole, so to speak, for carbon. Note well that it doesn’t even have to be a big hole — if you bump A you transiently bump S, but S is now damped — it can contribute or pick up CO_2 from M, but all of the while it is removing carbon from the system altogether. Now let’s imagine the other 30% of the earth. In this subsystem we could model it like:
d/dt A = E(t) – (91/750)A + (91/1020)S,
d/dt S = +(91/750)A – (91/1020)S – (96/1020)S + (96/38100)M – R_b S ,
d/dt M = +(96/38100) S – (96/38100) M
d/dt D = + R_b S
where E(t) is now the sum of all source rates contributing to A that aren’t S. Note well that for this to work, we can’t pretend that there are no contributions from the ground G or the crust (including volcanoes) C as well as humans H and land plants L. Some of these are sources that are not described by detailed balance — they are true sources or sinks. Others have similar (although unknown) chemistry and some sort of equilibrium. At the very least we need to write something like:
d/dt A = H(t) + C(t) – (91/750)A + (91/1020)S – R_{AL} A*L(t) – R_{GA} A + R_{GA} G
d/dt G = +R_{GA} A – R_{AG} G
d/dt S = +(91/750)A – (91/1020)S – (96/1020)S + (96/38100)M – R_b S ,
d/dt M = +(96/38100) S – (96/38100) M
d/dt D = + R_b S
which says that the ground has an equilibrium capacity not unlike the sea surface that takes up and releases CO_2 with some comparative reservoir capacities and exchange rate, humans only contribute at rate H(t), the crust contributes to the atmosphere at some (small) rate C(t) (and contributes to the ocean at some completely unknown rate as well, where I don’t even know where or how to insert the term — possibly a gain term in M — but still, probably small), where land plants net remove CO_2 at some rate that is proportional to both CO_2 concentration and to how many plants there are, which is a function of time whose primary driver at this point is probably human activity.
Are we done? Not at all! We’ve blithely written rate constants into this (that were probably empirically fit since I don’t see how they could possibly be actually measured). Now all of their values will, of course, be entirely wrong. Worse, the rates themselves aren’t constants — they are multivariate functions! They are minimally functional on the temperature — this is chemistry, after all — and as noted are more complicated functions of other stuff as well — rainfall, cloudiness, windiness, past history, state of oceanic currents, state of the earth’s crust. So when solving this, we might want to make all of the rates at the very least functions of time written as constants plus a phenomenological stochastic noise term and investigate entire families of solutions to determine just how sensitive our solutions are to variability in the rates that reasonably matches observed past variability. That’s close to what I did by putting an L(t) term in, but suppose I put a term L into the system instead as representing the carbon bound up in the land plants, and allow for a return (since there no doubt is one, I just buried it in L(t))? Then we have nonlinear cross terms in the system and formally solving it just became a lot more difficult.
Not that it isn’t already pretty difficult. One could, I suppose, still work through the diagonalization process and try to express this as some sort of non-Markovian integral, but it is a lot simpler and more physically meaningful to simply assign A, G, S, M, D initial values, write down guestimates of H(t), L(t), C(t), and give the whole mess to an ODE solver. That way there is no muss, no fuss, no bother, and above all, no bins or buckets. We no longer care about ideas like “fractional lifetime” in some diagonalized linearized solution that ignores a whole ecosystem of underlying natural complexity and chemical and biological activity influenced by large scale macroscopic drivers like ocean currents, decadal oscillations, solar state, weather state — algae growth rates depend on things like thunderstorm rates as lightning binds up nitrogen in a form that can eventually be used by plants — and more, so R_b itself is probably not even approximately a constant and could be better described by whole system of ODEs all by itself, with many channels that dump to D.
The primary advantage of my system compared to the one at the top is that the one at the top does have nowhere for carbon to go. Dump any in via E(t) and A will monotonically increase. Mine depletes to zero if not constantly replenished, because that’s the way it really is! The coal and oil and natural gas we are burning are all carbon that was depleted from the system described above over billions of years. Carbon is constantly being added to the system via C(t) (and possibly other terms we do not know how to describe). A lot of it has ultimately ended up in M. A huge amount of it is in M. There is more in M than anywhere else except maybe C itself (where we aren’t even trying to describe C as a consequence). And the equilibrium carbon content of M is a very delicate function of temperature — delicate only because there is so very much of it that a single degree temperature difference would have an enormous impact on, say, A, where the variations in temperature in S have a relatively small impact.”. Optimizing highly nonlinear multivariate models is my game. It is a difficult game, easy to play badly and get some sort of result, difficult to win. It is also an easy game to skew, to use to lie to yourself with, and I say this as somebody that has done it! It’s not as bad as “hermeneutics” or “exegesis”, but it’s close. If there is some model that you believe badly enough, there is usually some way of making it work, at least if you squint hard enough to blur your eyes to the burn on the toast looks like Jesus.
rgb
To rgbatduke,
To add another complication to your summation of natural cycles. Because of their size and density, decaying phytoplankton will remain near the surface and contribute to the ocean’s out gassing on a relatively short cycle. How long does it take to move from the Arctic to the equator? Another complication is the periodic upwelling off Peru of cold, carbonate saturated bottom water that will outgass as it warms crossing the Pacific near the surface. The inorganic cycle is the major long term player. How long does it take for the ocean’s conveyor belt to make a lap?
Help, Mr. Moderator! Change to before “buckets”.
rgb
[OK, Well, at least seeing the (hidden-by-html-brackets) letters makes the edit make sense … 8<) Robt]
richardscourtney says:
May 8, 2012 at 1:29 am
“He describes it with honest appraisal of its limitations at…”
Thanks, Richard. I think the root of Calder’s angst is that he is trying to satisfy requirements which may be irreconcilable. The CO2 records from ice cores and stomata disagree. Which is right? Perhaps neither. Certainly, if this relationship between temperature and the rate of change of CO2 has held in the past, the former are wrong. But, that does not mean the latter are right.
I am always very wary of claims made of measurements which cannot be directly verified. I have spent enough time in labs testing designs to know that you never really know how things will work in the real world until you have actually put them to the test in a closed loop fashion, with the results used to make corrections until it all works. And that is with components and systems which are designed based on well established principles, and using precision hardware to implement. Nature, as we say, is pernicious. Murphy, of course, proclaimed anything which can go wrong, will. And then, there is Gell-Mann’s variation describing physics: anything which is not forbidden is compulsory. And, Herbert: “Tis many a slip, twixt cup and lip.”
Everyone knows ice cores act as low pass filters with time varying bandwidth, smoothing out the rouch edges increasingly with time. I am not at all convinced, indeed am deeply suspicious, that the degree of smoothing and complexity of the transfer function is underappreciated.
The reliable data we do have, since 1958, says the data is behaving this way over the current timeline, with the derivative of CO2 concentration tracking the temperature. Over a longer timeframe, the relationship likely would change, if temperatures maintained their rise, with CO2 concentration becoming a low pass filtered time series proportional to the temperature anomaly. But, in any case, it is clear that right now, the rate of change in CO2 is governed by temperature.
Allan MacRae says:
May 8, 2012 at 2:48 am
I think the C13/C12 argument is an attempt to construct a simple narrative of a very complex process. An analogy which has come up in various threads is the case of a bucket of water with a hole in the bottom fed by clear mountain spring water. The height of water in the bucket has reached an equilibrium. Then, someone starts injecting 3% extra inflow with blue dyed water. The height of water in the bucket re-stabilizes 3% higher than before, but due to the delay of the color diffusion process, most of the blue dye lingers near the top of the bucket. Even when the spring ice melts, and the clear water inflow increases, adding say 30% more height, the upper levels are bluer than the lower. So, a naive researcher looks at the blue upper waters, and concludes that the dyed water input is responsible for the rise.
fhhaynie says:
May 8, 2012 at 5:19 am
Fred – I have enjoyed your presentations over the years. Not having the time to replicate your research, I have kept it in the bin marked “maybe”. That is why I hoped making the temperature to CO2 rate of change relationship readily accessible to everyone to replicate through this link might help sway people who otherwise would stay on the fence.
Gail Combs –
You may also want to consider Glassman’s post and the Q & A that follows “On why CO2 is known not to have accumulated in the atmosphere & what is happening with CO2 in the modern era.” Very thorough discussion.
rgbatduke says:
May 8, 2012 at 9:54 am
Yes, it is substantially guesswork. The value of such equations, IMHO, is substantially qualitative – they can illustrate what kind of dynamics are possible.
It is generally helpful to reduce the order of the model, as I demonstrated above. Model order reduction is a key element of modern control synthesis, e.g., as discussed here.
And, I then showed how we can get a system which will quickly absorb the anthropogenic inputs, yet have CO2 derivative appear to track the temperature anomaly (with respect to a particular baseline) here.
rgbatduke:
Thankyou very much indeed for your comment at May 8, 2012 at 9:54 am and especially for this one of its statements:
”.”
Yes! Oh, yes! I wish I had thought of your phrasing, and I thank you for it.
As I have repeatedly stated above, we proved by demonstration that several very different models each emulates the observed recent rise in atmospheric CO2 concentration better than the Bern Model although each of our models assumes a different mechanism dominates the carbon cycle.
Simply, nobody knows the cause of the observed recent rise in atmospheric CO2 concentration and there is insufficient understanding and quantification of the carbon cycle to enable modelling to indicate the cause.
Richard
richardscourtney says:
May 8, 2012 at 11:12 am
This is the question of observability. For an unobservable system, there exists a non-empty subspace of the possible states which does not affect the output. Thus, you can replicate the output with any observable portion of the state space plus any portion of the unobservable subspace. As the unobservable subspace is typically dense, there are generally an infinite number of possible states which can reproduce the observables.
For observability of stochastic systems, you have the added feature that even theoretically observable states are effectively unobservable because of low S/N.
It is analogous to a system of N equations in which you have greater than N unknowns to solve for. In such an instance, you must constrain your solution space by some means in order to find a unique solution. In the case of climate science, the selection of constraints provides an avenue for confirmation bias.
Bart:
Of course you are right in all you say at May 8, 2012 at 12:03 pm, but I put it to you that the paragraph from rgbatduke (which I quoted in my post at May 8, 2012 at 11:12 am) says the same in words that non-mathematicians can understand.
Also, our point was that it is one thing to know something is theoretically true and it is another to demonstrate it. We demonstrated it; i.e.
the observed rise in atmospheric CO2 can be modelled to have any one or more of several different causes and there is no way to determine which if any of the modeled causes is the right one.
Richard
richardscourtney says:
May 8, 2012 at 1:40 pm
“We demonstrated it; i.e. the observed rise in atmospheric CO2 can be modelled to have any one or more of several different causes and there is no way to determine which if any of the modeled causes is the right one.”
Did your models attempt to reproduce the affine dependence of the derivative of CO2 concentration on temperature? I would expect that to be a discriminator.
In the case of climate science, the selection of constraints provides an avenue for confirmation bias.
I couldn’t have said it better myself. We disagree, I think, about numerics vs analytics, but then, I’m a lazy numerical programmer and diagonalizing ODEs to find modes gives me a headache (common as it is in quantum mechanics). The beauty of numerically solving non-stiff ODEs (like this) is that, well, it just works. Really well. Really fast. It’s not like you don’t have to work pretty hard and numerically to evaluate the Bern integral equation anyway, unless you use a particularly simple E(t), and then you have the added complication of just what you’re going to do with that pesky
bit. It’s so much simpler to basically solve a Markovian IVP problem than a non-Markovian problem with a multimode decay kernel and an indeterminate initial condition.
But as to the rest of it, I think we agree pretty well. It’s a hard problem, and the Bern equation is one, not necessarily particularly plausible, solution proposed that can fit at least some part of the historical data. Is it “right”? Can it extrapolate into the future? Only time, and a fairly considerable AMOUNT of time at that, can tell.
In the meantime, the selection of the model itself is a kind of confirmation bias. 15% of the integral of any positive function you put in for E(t) simply monotonically causes CO_2 to increase. Another 25% decays very slowly on a decadal scale, easy to overwhelm with the integral. It’s carefully selected for maximum scariness, much like the insanely large climate sensitivities.
Or not selected. Scientists who care understand that it is only a model, one of many possible models that might fit the data, can look at it skeptically and decide what to believe, disbelieve, and can actually intelligently compare alternative explanations or debate things like what I put in my previous post that suggest that it would be pretty easy to fit the model and maybe even fit the susceptibility of the model (if that’s what you are claiming that you accomplished) with alternatives that have very different asymptotics and interpretations, or (as Richard has pointed out) with models where anthropogenic CO_2 isn’t even the dominant factor.
What I object to is this being presented to a lay public as the basis for politically and economically expensive policy decisions that direct the entire course of human affairs to the tune of a few trillion dollars over the next couple of decades. If only we could attack things like world hunger, world disease, or world peace with the same fervor (and even a fraction of the same resources). As it is, I think of the billions California is spending to avert a disaster that will quite possibly never occur because it is literally non-physical and impossible, and think of the starving children those billions would feed, or the people who lost their jobs in California when it went bankrupt that that money would employ.
And there is no need to panic. Global temperatures are remarkably stable at the moment. An absolutely trivial model computation suggests that the Earth should be in the process of cooling in the face of CO_2 by as much as 2C at the moment (7% increase in dayside bond albedo over the last 15 years). The cooling won’t happen all at once because the ocean is an enormous buffer of heat as well as CO_2, but it is quite plausible that we will soon see global temperatures actually start to retreat — indeed, it would be surprising if they don’t, given the direct effect of increasing the albedo by that factor.
And in a couple of decades we will (IMO, others on list disagree) on the downhill side of the era when the human race burns carbon to obtain energy anyway, with or without subsidy. There are cheaper ways to get energy that don’t require constant prospecting and tearing up the landscape to get at them. Well, they will be cheaper by then — right now they are marginally less cheap. Human technology marches on, and will solve this problem long before any sort of disaster occurs.
rgb
Yes! Oh, yes! I wish I had thought of your phrasing, and I thank you for it.
Oh, my phrasing isn’t so good — there is far better out there in the annals of other really smart people. Check out this quote from none other that Freeman Dyson, referring to an encounter of his with the even more venerable Enrico Fermi:
The punch line:
.”
Yeah, John von Neumann was a pretty sharp tool to keep in your shed as well. The Bern model has five free parameters, so it isn’t terribly surprising that it can even make the elephant wiggle his trunk. (Thanks to Willis for pointing this delightful story out on another thread where we were both intent on demolishing an entirely nonphysical theory/multiparameter model of GHG-free warming.)
I feel a lot better about a model when there is some experimental and theoretical grounding that cuts down on the free parameters. “None” is just perfect. One or two is barely tolerable, more so if it isn’t asserted as being “the truth” but is rather being presented as a model calculation for purposes of comparison or insight. Get over two and you’re out there in curve-fitting territory, and by five — well why not just fit meaning-free Legendre polynomials or the like to the function and be done with it?
rgb
Oops, I miscounted. The Bern model has eight free parameters — I forgot the weights of the exponential terms. So wiggle his trunk while whistling Dixie, balanced on a ball. Although perhaps someone might argue that they aren’t really free, I doubt that they are set from theory or measurement.
rgb
Yes the five-parameter elephant.
Above several times I have noted that the integral equation that is at times causing so much worry in these comments is a very basic convolution equation of linear systems theory. Solving it is usually a matter of transforming it into the Laplace transform domain where convolution becomes a multiply operation.
More directly, “by inspection” the impulse response given there (the parallel decaying exponentials) corresponds to a particular configuration of passive R-C circuits. Without further analysis, we recognize exactly what it is and what it can (and can’t) do. It seems quite unlikely it could correspond to CO2 sourcing and sinking to four partitions (electrons to four capacitors in the circuit).
It could only be a “model” in the sense that it can be MADE to fit, given the free parameters. Hence the aptness of von Neumann’s elephant joke – which I also noted above.
Bart:
At May 8, 2012 at 5:03 pm you ask me:
“Did your models attempt to reproduce the affine dependence of the derivative of CO2 concentration on temperature? I would expect that to be a discriminator.”
I answer:
No, that was not their purpose.
Our paper explains;
“It is often suggested that the anthropogenic emission of CO2 is the cause of the rise in atmospheric CO2 concentration that has happened in the recent past (i.e. since 1958 when measurements began), that is happening at present and, therefore, that will happen in the future (1,2,3). But Section 2 of this presentation explained that this suggestion may not be correct and that a likely cause of the rise in atmospheric CO2 concentration that has happened in the recent past is the increased mean temperature that preceded it. A quantitative model of the carbon cycle might resolve this issue but Section 2 also explained that the lack of knowledge of the rate constants of mechanisms operating in the carbon cycle prevents construction of such a model. However, this lack of knowledge does not prevent models from providing useful insights into ways the carbon cycle may be behaving. ‘Attribution studies’ are a possible method to discern mechanisms that are not capable of being the cause of the observed rise of atmospheric CO2 concentration during the twentieth century..”
Richard
Allan MacRae:
I apologise that I overlooked your question at May 8, 2012 at 7:45 am and have only now noticed it.
It asks;
“I am trying to find references to a major misalignment between the ice core CO2 record and modern atmospheric records of CO2, one that was allegedly “solved” by shifting the ice core record until it matched the modern record.
Can anyone help please?”
Hu McCulloch says:
May 7, 2012 at 9:19 pm
Many thanks, Hu, following your explanation I finally see how it could work. The key is that to have it work, we have to have all of the CO2 pass from the atmosphere to one reservoir (the upper ocean in your example), which then passes all the CO2 to a second reservoir (deep ocean) at a different rate. In that way, part of it is absorbed quickly, and the remainder more slowly.
My problem is that to have the five different partitions they describe, you have to have the CO2 absorbed from the atmosphere by one single reservoir, which then transfers it to a second reservoir at a different rate, which then transfers that to a third reservoir at a third rate, which then transfers that to a fourth reservoir at a fourth rate, which then transfers that to a fifth reservoir at a fifth rate.
It also means that there can’t be any other sequestration mechanisms operating, because if there are other sinks, they will continue to absorb the CO2, and will sequester it long before the 371.6 years are up …
So I’m back to my same old problem … I still don’t understand where in the physical world we find such a system. It assumes the one and only sink is the ocean, which is partitioned into 5 sequential sub-sinks … I’m not seeing it.
w.
PS—I am sure that others explained this to me but I didn’t get it until Hu explained it … no telling how the mind works. In any case, my thanks to everyone who tried to explain it, and my apologies for not getting it.
Now I just need to find the five-chambered sequential CO2 sequestering system that corresponds with their math … oh, and also solve the separate and distinct problems pointed out by Robert Brown ….
Willis Eschenbach:
Your post at May 9, 2012 at 1:38 am concludes by saying;
“So I’m back to my same old problem … I still don’t understand where in the physical world we find such a system. It assumes the one and only sink is the ocean, which is partitioned into 5 sequential sub-sinks … I’m not seeing it.”
I am pleased that you have grasped the point that the Bern Model does not represent behaviour of the real-world carbon cycle. Perhaps now you can understand my post (above) at May 7, 2012 at 2:09 am which began by saying;
.” etc.
Please note that I am NOT now writing to say, “I told you so” (I am fully aware that one is often forgiven for being wrong but rarely forgiven for being right). I am writing this to make a point which I am certain has great importance but is often missed; viz.
THE CAUSE OF THE RECENT OBSERVED RISE IN ATMOSPHERIC CO2 CONCENTRATION IS NOT KNOWN AND – WITH THE PRESENT STATE OF KNOWLEDGE – IT CANNOT BE KNOWN.
We few who have persistently tried to raise awareness of this point have been subjected to every kind of ridicule and abuse by those who claim to “know” the recent rise in atmospheric CO2 concentration is caused by accumulation of anthropogenic emissions in the air. But whether or not the cause is anthropogenic or natural, that cause is certainly not accumulation of anthropogenic emissions in the air.
And the point is directly pertinent to the AGW-hypothesis which says;
(a) Anthropogenic emissions of GHGs are inducing an increase to atmospheric CO2 concentration;
(b) an increase to atmospheric CO2 concentration raises global temperature
(c) rising global temperature would be net harmful.
At present nobody can know if (a) is true or not, but the existing evidence indicates that if it is true then it is not a direct result of accumulation of anthropogenic emissions in the air. And if (a) is not true then (b) and (c) become irrelevant.
Richard
“My problem is that to have the five different partitions they describe, you have to have the CO2 absorbed from the atmosphere by one single reservoir, which then transfers it to a second reservoir at a different rate, which then…”
It will still work even if all the reservoirs connected, but I’m afraid I can’t think of any clearer explanation as to why than the tanks argument. Sometimes analogies and explanations just don’t catch – there’s some unrealised assumption or preconception that blocks the intuition. The mind’s workings are indeed strange.
It’s sometimes worth persisting with different analogies, but without understanding the reason for the block, it’s a bit hit and miss. Perhaps you can ask again another time, in a few months maybe.
Willis wrote:
.”
Actually, it’s a parallel, not a series system, which is evident from the summation sign rather than a product. You don’t need SPICE because it’s so simple. Not that either would have a physical correspondence to what goes on with CO2 in the atmosphere.
Nullius in Verba:
At May 9, 2012 at 11:25 am you say;
“It will still work even if all the reservoirs connected, but I’m afraid I can’t think of any clearer explanation as to why than the tanks argument.”
Hmmm. That depends on what you mean by “work”.
The model can be made to fit the rise in atmospheric CO2 concentration as observed at Mauna Loa since 1958 if the model’s output is given 5-year smoothing. But so what? Many other models which behave very differently can also provide that fit and do not require any smoothing to do it.
If you mean the Bern Model emulates the behaviour of the real carbon cycle then it does not: nothing in that cycle (except possibly the deep ocean) acts like a reservoir with a fixed volume.
Richard
Quinn the Eskimo says:
May 8, 2012 at 10:43 am
Gail Combs –
You may also want to consider Glassman’s post and the Q & A that follows “On why CO2 is known not to have accumulated in the atmosphere & what is happening with CO2 in the modern era.” Very thorough discussion.
____________________________________
OH wonderful!
It is so nice to see someone has done a really good rebuttal on the well mixed conjecture. That is a really big nail in the coffin of CO2 warming hype.
BernieH says:
May 9, 2012 at 3:31 pm
Thanks, Bernie. If all of the R/C pairs are in parallel, then your circuit looks like this:
If it’s like that, the quickest path to ground is what rules. Since the claim in the Bern model is that the exponential decay is partitioned, it has to be a series circuit.
w.
Gail Combs says:
May 9, 2012 at 4:18 pm (Edit)
No, Gail and Quinn, it’s not wonderful at all. It’s wildly incorrect. The author of the article is conflating residence time with e-folding time (or half-life). He doesn’t know the difference between the two. As a result, his conclusions are totally incorrect. Re-read my Appendix above.
Finally, is CO2 well-mixed? Well, I suppose it depends on what you call “well-mixed”.
Note that everywhere but the south pole the range is from about 375 – 382 ppmv, or ± 1% … in my book, that’s well mixed. Include the south pole and the range goes to about 368 – 382 ppmv … that’s ± 2%. Again, I call that well-mixed.
In other words, the citation is not a nail in the coffin of anyone but the author.
w.
No, I would use it to begin looking at the change in CO2 concentration with respect to average wind speed and direction with respect to changes in
1. Surface temperature (Cold Japanese current, hotter far west deserts and great basin, slightly cooler eastern US), hotter Gulf Stream off of east coast, colder currents off of Europe, then the central Asian barren highlands and back over the (colder and warmer) Pacific currents.
2. surface mass of growing plants: Great basin across Great plains to farmed Midwest to very tree-covered east coast), then barren areas in central Asia to the very overgrown Indian Peninsula …
3. Lower levels over the Amazon – that extend out over the Atlantic Ocean. But these conflict with the barren Saudi peninsula and Afghanistan and Mongolia that don’t match vegetation, and don’t match human activity to the immediate west. Odd.
4. Amount of human released CO2.
5. Actual direction and speeds of the “average” wind WHEN the measurements of the CO2 were taken.
Highest areas don’t “seem” to track with industrial activity (great basin, mountainous west, but then a high spot over the Atlantic Ocean. If you “translate human activity east” (assuming some west-to-east wind pattern), then where did Europe’s CO2 go? Where did Saudi Arabia and Afghanistan’s CO2 come from? Why is the CO2 high over the entire mountain area out west? There’s nobody west of there other than islands of people at LA and SFO. And nobody west of them for thousands of miles.
Applause, Thank you all for a very interesting discussion !
Hi Willis
What I am doing is less ambitious than what you and others here seem to be attempting.
I am (in the back of my mind) thinking about how CO2 in the atmosphere moves in, out, and about, but I am only working with the
mathematics in the link as what it is – a simple RC network. The integral equation given there is a fundamental convolution relationship between an input signal and the impulse response of a system. Just sophomore-level Laplace transform system theory – no big deal to an EE.
The equation describes the relationship between E (the input) and rho (the concentration). It seems to me that E is an extensive variable (an “amount” or quantity) while rho is an intensive variable (a property, a characteristic number, a concentration, in the same units as C) so we don’t seem to be talking about transfer of anything (such as electrons or CO2 molecules) but only a numerical ratio. So my RC network is a computational device only – it does not represent physical reality.
This “computer” happens to be composed of resistors, capacitors, buffer/multipliers, and a summer. I don’t know how to put a picture in comments here, so I have posted the schematic diagram at:
Aside from scaling factors (which I would probably get wrong!), the diagram there is the one and only RC network that corresponds to the impulse response in the [ ]. The input is an “inventory” number of all CO2 going in, and rho is a number some “master controller” of all sinks is instructed to maintain. The sinks are NOT a physical analog of the electrons flows in the network – as least as their mathematics shows it.
Much as you and others here have problems with the partitions, so do I. I am not, but if I were considering a true electrical analog (electrons = CO2 molecules and capacitors represent storage of CO2) there is only one atmosphere (one capacitor) and one grand summed source (E) and one net sink. That would be one net resistor – if it’s even linear.
I think they were facing the problem that there does not seem to be a simple (one) exponential decay. Parallel RC’s is one way of handling this (Kautz functions are better). But the parallel RC suggests the partitioning. That’s a problem. Perhaps it was just intended as a computer, not as a physical model.
richardscourtney says: May 9, 2012 at 1:34 am
Allan MacRae asks;
“I am trying to find references to a major misalignment between the ice core CO2 record and modern atmospheric records of CO2, one that was allegedly “solved” by shifting the ice core record until it matched the modern record. Can anyone help please?”
Richard:
*********
Thank you very much Richard – I hope you are well. Yes, that is exactly what I was seeking.
Note to Richard, Bart, Willis and others:
This shifting of ice core data to align with Mauna Loa data is just one of several examples of confirmation bias in the current hypothesis that CO2 MUST drive temperature, and the related hypothesis that the primary source of increasing atmospheric CO2 MUST BE humankind.
When one starts to examine this complex subject, similar contradictions become apparent, not the least of which is that atmospheric CO2 lags temperature at all measured time scales (and dCO2/dt changes ~contemporaneously with temperature).
The counterarguments for the observed ~9 month lag of CO2 after temperature are:
A. It is a “feedback effect”.
B. It is clear evidence that time machines really do exist.
Both counterarguments A and B are supported by equally compelling evidence. :-)
To me, one must start with the evidence, and work back to a logical hypothesis. The CO2-drives-temperature hypothesis and related man-drives-CO2 hypothesis both start with the hypo, and then try (unsuccessfully, imo) to fit the evidence to the hypo. When the evidence fails to fit, the data is “adjusted” and yet another illogical hypo (move-the-air–up-the-ice-firn) is invented, and so on, and so on. The alleged physical system becomes increasingly Byzantine, and increasingly improbable. That, I submit, is the current highly improbable state of “settled” climate science.
I would prefer to start with the evidence, as stated above, and then try to respect fundamental logical concepts such as the Uniformitarian Principle and Occam’s Razor.
Here are some thoughts: temperature-time cycle..
I have suggested that there could be one or more intermediate cycles where CO2 lags temperature (between 9 months and 800 years).
There should be ample evidence in existing data to develop a much more credible and simpler hypothesis that does not rely for support on data-shifting, “feedback effects” and many other improbable hypotheses.
Regards, Allan
Summary – Multiple Cycles in which CO2 Lags Temperature:
For a mechanism, see Veizer (2005).
I think there are perhaps four cycles in which CO2 lags T:
1. A cycle of thousands of years, in which CO2 lags T by ~~800 years (Vostok ice cores, etc.)
2. A cycle of ~70-90 years (Gleissberg, PDO or similar), in which CO2 lags T by ~5-10 years. This “Beck hypo” is highly contentious – the late Ernst Beck’s direct-measurement CO2 data allegedly supports this possibility, and there is the important question of how much humanmade CO2 affects this and subsequent cycles. Ernst Beck was widely disrespected and his work dismissed by both sides of the CAGW debate – I think this was most unfortunate, and probably was an intellectual and ethical error – there is possibly some merit, particularly in Beck’s data collection work, and many were too quick to dismiss it.
3. The cycle I described in my 2008 icecap possible Cycle 2 we may have inadequate data.
– Allan MacRae, circa 2008
Friends:.
The magnitude of the problem is obvious when the processes of the carbon cycle (i.e. the ‘tanks’ or ‘electrical resistors’ and their connections) are considered.
In our paper that I reference above, conservatively about” in the air.
And there are people who think they can make a meaningful simple model of that when nobody knows the rate constants of any of the processes!
Richard
Hi Willis,
I have to say that I don’t like your RC circuit diagram — you need to put the “atmosphere” in parallel, not in series, and it isn’t really a parallel circuit anyway. Also, you don’t need two resistors in the circuit on either side of the capacitors — one will do since resistors in series add anyway.
I have no way to add a jpg graphic (that I know of) to this — I’ll try doing it in raw html pointing to images I just put onto my own web space, but if Mr. Moderator or anyone with cool super powers can download them and put them inline I would appreciate it.
This is what you were trying to construct, I think. It shows the atmosphere as a capacitor
. A current
is charging it. As it charges, the charge is shared with three other capacitors, labelled
through resistors that limit the current. a is atmosphere, s is sea surface layer, m is the middle ocean beneath that and d is the deep ocean bottom (only), but of course one could add soil, leaf water, and so on. Note well that equilibrium depends on the sizes of the capacitances (relative to
) and the resistances.
However, this model is not correct. The atmosphere doesn’t share CO_2 (“charge”) with the deep ocean or middle ocean directly and the rates from surface to middle depend on the differences in “voltage” across the surface capacitor relative to middle, not atmosphere to middle. The first metaphor might work to find equilibrium, when there is no current flowing and the potentials across all the capacitors must be the same, but it won’t work to describe the APPROACH to equilibrium correctly.
I offer a slightly alternative model:
A current
dumps e.g. a bolus of charge on
. It bleeds through the surface resistance
to try to equilibrate the potential differences across
and
, but as it does so some of the charge is similarly bled off
through resistance
onto
.
At this point there is no path to ground. All the charge you put in via
remains in the system, shared between $C_a, C_s, C_m$. How much remains in $C_a$ depends on the relative magnitudes of the other two — in particular, if
, then less than 1.7 % of the total surplus charge will end up on
because the ratio of
must be the same for all three capacitors.
Suppose, however, that
is “infinite” in size. It is then formally equivalent to ground — indeed the Earth itself IS an enormous capacitor that acts as a ground. If indeed what I label the deep ocean is ground, capable of “permanently” sequestering CO_2 for periods of tens to hundreds of millions of years, requiring an actual turnover of the crust to return it back to the atmosphere, or if it is simply a vast reservoir compared to even
that can hold almost as much carbon as you drop into it without significantly altering the CO_2/charge in
, we can just put a resistor between any reservoir that can directly dump carbon there in our circuit above.
I drew such a resistive pathway
in the figure above with a switch, so one can mentally understand what happens when the switch is closed. Without the pathway (switch open), CO_2/charge builds up indefinitely as there is a nonzero current
into the atmosphere
with nowhere to ultimately go to ground. With the switch closed, things are very different indeed. Now charge constantly bleeds off of all three capacitors to ground. The only way to sustain the CO_2 levels in all three is via a nonzero current
.
I do not suggest that this is an accurate model for the atmosphere, but it is one that at least roughly corresponds to the three processes outlined in the set of coupled ODEs above. Personally, I found the “rocket science journal” discussion of the surface equilibrium exchange a lot more reasonable — it doesn’t try to pretend that
can remain in equilibrium with a nonzero non-anthropogenic current so that only anthropogenic current counts as “charge” in
. There are many known non-anthropogenic currents (sources of CO_2) and without a path to either “ground” or a very large reservoir any nonzero current will monotonically boost the charge/CO_2 content of
.
Even
is already more than capable of “grounding”
as far as the current discussion is concerned — the ocean contains many, many times more CO_2 in chemical equilibrium than the atmosphere contains, and the “fraction” of any addition that should be permanent in the atmosphere is strictly less than the ratio of their capacitances, all things being equal. So the 0.15 factor in the Bern equation makes little sense to me on strictly physical grounds. If the equilibrium atmosphere contained 15% of all of the carbon in the carbon cycle, that would be the right number. It doesn’t, and it isn’t.
rgb
Figures ADDED by Anthony at the request of RGB:.
Agreed..
I’m reading my way through “The Black Swan”. It should (IMO) be required reading for all scientists. It graphically and precisely illustrates the risk of naive mathematical models, especially those that we have “reduced” to have only a few parameters (usually because that’s all our Platonic little minds can wrap themselves around). It also thoroughly explores the human tendency towards confirmation bias, because we stubbornly continue to try to confirm a theory (which is impossible, usually) instead of disprove it (which is easy, when it works). Feynman says much the same thing — the sad thing about modern science is that we don’t publish null results, and our brains get dopamine-driven satisfaction from “being right”. It is very difficult to say “I don’t know”, or “my favorite hypothesis, when compared to the data, doesn’t quite work right”.
rgb
Any chance (Mr. Moderator) of inserting the figures?
Here they are:
for those that are wondering why my post above refers to figures and there aren’t any figures.
rgb
REPLY: Done, Anthony
rgbatduke:
At May 10, 2012 at 8:43 am you say to me;
.”
Yes, I knew you were “only correcting Willis’ effort”, and I write to confirm that your understanding of my point is exactly right.
I take this opportunity to thank you for your excellent contributions to the above discussion. I value them.
Richard
richardscourtney says:
May 10, 2012 at 10:19 am
Yeah, as usual Robert Brown has it right … teach me to post late at night without thinking …
w.
richardscourtney says:
May 10, 2012 at 4:32 am
“The carbon cycle cannot be represented by a ‘plumbing’ or ‘electrical’ circuit because all the ‘tanks’ or ‘resistors’ change with time and their magnitudes, variations and connections are almost completely unknown .”
Yes. Which is why I have been saying the value of these models, IMHO, is substantially qualitative.
It is easy to get wrapped around the axle looking at ever more intricate models but, at some point, you gain more insight by stepping back and viewing the forest rather than the trees.
In the model I proffered here, I subsumed all the complexity by allowing the time constant and gains to be operator theoretic. Bounding behavior of the system can be obtained by making these operators constant equal to infinity normed values. It is then apparent that the fundamental properties of the real world system are 1) relatively rapid sequestration of inputs (large norm of the inverse time constant) and 2) temperature sensitivity of sufficient magnitude such that temperature is driving the output.
Aside: Regarding electrical circuit analogies, the case of transmission lines is instructive. These are modeled using parameters such as conductance and capacitance per unit length. Under appropriate circumstances, a distributed element model of discrete components can be used to approximate the behavior. How well the model approximates the true behavior depends on the length of the line, the bandwidth of the signals to which the line will be subjected, and the source and load impedances (boundary conditions). A precise model would be inifinite dimensional, but the number of lumped parameters can be truncated in order to achieve a given degree of fidelity. You generally can get these types of models when you deal with continuum systems which are governed by partial differential equations.
Bart:
Thankyou for your post at May 10, 2012 at 10:39 am.
Before saying why I am responding to your post, I remind of my position which I have stated in many places including WUWT; viz.
I don’t know what has caused the recent rise in atmospheric CO2 concentration, but I want to know.
So, being aware of my stated position, you will surely understand my two responses to your post that I am replying.
Firstly, I thank you for reminding of the simple empirical model which you provided at May 7, 2012 at 10:50 am above. My problem with it is that it fits to a short time series (i.e. 1958 to present) and I fail to see the value of that because – in the absence of a physical basis – extrapolating any such fit is a ‘risky’ thing to do. However, I agree with its assessment that (in the existing data) temperature change is the observable dominant effect on atmospheric CO2; indeed, I have said that in this thread, too.
Secondly, and more importantly, I am very interested in your suggestion that a distributed element model may be helpful to understanding the system. Please note that my background is in materials science so I am very familiar with systems analyses, but I have no knowledge of electrical engineering and, therefore, I am ignorant of distributed element models (i.e. I don’t know what they are, what they do, what they can’t do, and what insights they may provide).
Hence, I write to request an expansion of your suggestion that a distributed element model may be helpful to understanding the system of the carbon cycle. And I ask you to remember my ignorance of electrical engineering so I need an explanation which I can understand (if that is possible).
Richard
Hi RGB –.
Try walking into your local Radio Shack and asking for a “current source”. They have only batteries – voltage sources. For anyone this bothers, a good idea of a current source would be a battery with an absurdly large series resistance (say a 1.5 volt battery and 1000 megohms series, which delivers 1.5 na to any ordinary load).
Now, there is of course no switch, so let’s assume our current source is attached, and that it is a constant current Io. Ca begins to charge, and in turn, Cs and Cm, with Rd beginning to draw off current. As you point out, Ca no longer ramps without limit.
I make it that the voltage on Ca becomes Va = Io(Rs+Rd). That is, Io eventually spills through the Rs and Rd series. So Cs becomes charged to Vs=VaRd/(Rs+Rd). And Cm has a voltage Vm = Vs, since no current flows through Rm. This would make Cs and Cm all one “sea” which makes sense.
It would probably be worth looking at the impulse response and/or the decay from constant current charge. What do you think?.
I’m assuming it to play precisely the same role as “E(t)” in the Bern equation:
Note the eight parameters:
. Lots of trunk wiggling room.
The point of the metaphor is that
— the charge on a capacitor — is the moral equivalent of
(or more correctly, its volume integral, the total CO_2 in the atmosphere). E(t) in the Bern equation is the “anthropogenic CO_2 current” that is charging up the atmospheric capacitance, which then “drains” at exponential rates $R = 1/\tau$ into reservoirs 1, 2 and 3.
This doesn’t make complete sense to me. It is claimed that the reason for the three terms is (ultimately) detailed balance between three reservoirs and the atmospheric reservoir, perturbing a pre-existing equilibrium with the additional CO_2. In a word, as with the first capacitive model above, any additional CO_2 “charge” delivered to the atmosphere is shared across all connected reservoirs until they all have balanced rates of exchange.
However, it is perfectly obvious that when that is true, the different reservoirs will share the CO_2 in — certainly to first order — the same proportion that they already share it in equilibrium. That is, one would expect roughly 50 parts of any surplus to end up in the ocean (which contains roughly 50 times as much carbon as the air). In the end, that means
, not
as it is given in the Bern formula. This does depend on the time constants of the various reservoirs, of course.
But all of this is highly idealized. As Richard Courtney and Bart have pointed out, things are a lot more complicated and unknown than this. For example, every one of the capacitors in the simplified model have variable capacitance and time constants. They vary with respect to many coupled parameters. For example, thinking only of the surface (euphotic zone), things that affect absorption rates include: temperature, wind speed over the surface, frothiness of the surface (related to wind speed), local carbon dioxide content, local nutrient content (oceanic phytoplankton are often growth limited by other nutrients than CO_2), carbon dioxide content above the surface in the atmosphere, presence/absence of sunlight, and details of the thermohaline circulation. Many of these factors are thus themselves functions of both location and past history! — average functions of location, as waters up in Nova Scotia are always a lot colder than they are around Puerto Rico and very likely experience quite different average sustained wind speeds and have different nutrient content and biology. Past history is more complicated — thermohaline circulation operates on a dazzling array of timescales, the longest of which (for complete turnover) are around 1000 years.
That means that the carbon dioxide content of deep oceanic water welling up to the surface — which in part determines how much that water is happy absorbing or releasing once it gets there — was laid down as long as 1000 years ago. It also means that there is a possibility of resonant amplification and positive feedback on an (order of) thousand year loop or any of several shorter loop times in between as thermohaline circulation is chaotic and complex and not just a single coherent flow. Global decadal atmospheric oscillations no doubt play a role as well.
In the end, this means (as Bart suggests, I think) that atmospheric CO_2 content is regulated far more strongly by variations in the capacitance of the soils and the sea than it is by the human “current”.
rgb
[Latex fixed, although you should check it, it seems to be missing a close parenthesis. For the large braces, you need to use \begin{Bmatrix} and \end{Bmatrix}. For large brackets, use \begin{bmatrix} and \end{bmatrix} … w.]
Damn, and I checked it. Likely the wordpress latex doesn’t like \left{ \right} pairs or the like. Sigh. Help Mr. Moderator? I’m really sorry…
rgb
Think rgb meant this:
( Dr. Brown, your were just missing the final “\right}” )
Mods, I’m sorry too. The correct Latex is here. rgb is correct, it was the \left{ or \right} though Latex editors accept it fine. We learn.
[Wayne, see my note above regarding the use of “\begin{Bmatrix}” and “\end{Bmatrix}. w.].
richardscourtney says:
May 10, 2012 at 11:39 am
“My problem with it is that it fits to a short time series (i.e. 1958 to present) and I fail to see the value of that because…”
It’s 54 years. And, it’s the only reliable data we have.
“Hence, I write to request an expansion of your suggestion that a distributed element model may be helpful to understanding the system of the carbon cycle. “
It was merely an attempt on my part to point out that lumped parameter models, such as in rgbatduke @ May 10, 2012 at 8:32 am, are generally approximations to a continuum model with is defined by partial differential equations.
Again, my main point is that we do not need to wade so deeply into models which cannot be authenticated with present data. It is clear that the broad general outline of the system is that, here and now, and for the past several decades, sinks are more active than supposed so that the sequestration feedback is strong, which attenuates the anthropogenic input markedly, and sensitivity to temperature is high. These conclusions fly directly in the face of the assumption that atmospheric CO2 concentration is being driven by humans.
rgbatduke says:
May 11, 2012 at 3:26 am
‘In the end, this means (as Bart suggests, I think) that atmospheric CO_2 content is regulated far more strongly by variations in the capacitance of the soils and the sea than it is by the human “current”.’
Indeed, he does. More than suggests. Asserts with evidence, that being that the atmospheric CO2 concentration has tracked the integrated temperature anomaly with respect to a particular baseline for the past 54 years, and assuredly into the next several at the very least.
“…for the past 54 years, and assuredly into the next several at the very least.”
I meant my statement to be more forceful than that. I had it in my head that I had described the interval as “decades”. The relationship will almost assuredly hold for the next several decades at the very least. | https://wattsupwiththat.com/2012/05/06/the-bern-model-puzzle/ | CC-MAIN-2016-40 | refinedweb | 44,283 | 59.53 |
Why have AppName at the start of fully qualified class paths?
(prompted by a late reply on a bug already marked as fixed - custom folder structure)
The reply was about adopting some first letter uppercase vs lowercase convention to differentiate namespace (alias?) from package path in a class path.
I assume what is meant is having 'MyPath.MyClass' as a shorthand reference to 'MyApp.path.to.MyClass', while having used setAlias('MyApp.path.to', 'MyPath')?
The truth is that most languages that rely on packages don't have the AppName as first item in the path. You would use 'path.to.MyClass' and it would be assumed that it matches the folder structure starting from the source or the app folder. The avoidance of a mention of the AppName in the package path makes the code more portable (easier to re-use the same code across projects).
If you use these other languages as inspiration, 'MyApp.path.to.MyClass' could be instead expressed as package: path.to.MyClass and, optional, a second parameter that let you define a baseFolder (or namespace) 'MyApp'. I think you already have some aspect of that baseFolder functionality in, through the 'alias' property. [Wondering, could you have more than one application loaded from an index.html? If not, the appName is completely predictable and therefore of no value as information.]
This would solve the problem without requiring a mix of conventions within a single item. With editors like Sublime Text allowing to refer to folders outside of your project, it is possible to think of building a library of components re-used across applications.
There seems to be an interest from Sencha to attract people from an entreprise background (e.g., Flex). However, small deviations from the usual conventions, like the addition of MyApp at the start of the path easily create major headaches for code structure and re-use in larger applications.
Another aspect of these reverse url conventions for namespaces is how easy or difficult you can make it to re-use community contributed components.
With Sencha, it looks like the practice is to release official plugins and name them something like Ext.layout.AccordionLayout or Ext.ux.touch.Rating. Implicit to this naming convention is the expectation that there can ever be one trustworthy accordion layout or rating component.
To better support fully qualified namespaces (without AppName at the start of the path) could more explicitly encourage average Joe's contributions, with com.average-joe.Rating happily co-existing in the ecosystem with Ext.ux.touch.Rating.
The reverse url is widely adopted in communities that show a very strong ecosystem, with many quality libraries and components contributed on github and google code.
The problem then is to balance out the benefits and costs of this approach. Custom paths give more freedom but make the code more bloated and more difficult to read if you have to write fully qualified class names everywhere. Javascript doesn't really offer any opportunity for an import statement that would let you define the fully qualified class reference first and then access it via the className only later. Alias could help with this but only to some extend. Aliases appear to be global when the import statement defines a reference that is active only in the current class.
- Join Date
- Mar 2007
- Location
- Gainesville, FL
- 38,580
- Vote Rating
- 1136
Sorry it has taken me this long to jump on this thread... forgot about it but I promised I would jump on it so I am
We have used the naming convention Ext.grid.Panel where the root (Ext) and the actual name (Panel) are UpperCamelCase and the inner namespaces (grid) are all lowercase. We have been using this naming convention since all of this was started in 2006.
That being said, you are not force to. If you name your classes something like com.users.list then you actually can. The only thing we do force is that the file structure matches your class name and is case sensitive. We recommend you use the UpperCamelCase but it's really not required.
Now the plugins that aren't actually part of the framework are up to the author of those classes. For instance I used to use the Ext.ux (kind of an unspoken namespace for 3rd party extensions) but have now started to use the Ux namespace instead of Ext.
So to sum it up... we have naming conventions and recommendations but not really really appreciate if you could provide a working example. I have been looking on github and googlecode and couldn't find any example using custom path structure.
If I try to deviate from the app>[controller/view/model] recommended structure, then I end up with a lot of weird outcomes (v2pr3).
(using AppName at the start of the class path)
I can only get the code to work if the controller that is defined in app.js (main script, declared in the index.html file) is in a folder app/controller. If I do something as simple as renaming app/controller to app/controllers (making all necessary changes), the app stops working. The culprit is an attempt to load a view dynamically from a controller, using Ext.ClassManager.get('AppName.AppView').create(); (using AppName.view.AppView makes no difference). I grant you, not an orthodox approach, but the issue is that as soon as you deviate a tiny bit from the app/[controller/view/model] basic structure, other, seemingly unrelated, part of the sencha code starts to break in odd ways.
(not using AppName at the start of the class path, using fully qualified names of the type com.domain.project)
If I use views : [ 'com.domain.project.AppView' ], sencha tries and load the file from app/view/com/domain/project/AppView.js, not com/domain/project/AppView.js.
If you name your classes something like com.users.list then you actually can.
The second aspect of the discussion was how the recommendation of using Ext.ux (or ux) for user contributed content could hinder the development of an ecosystem around Sencha.
If I go to codeCanyon, I get 750 matches for jQuery, One for ext (but nothing to do with ext-js). One match for sencha.
Is the lack of availability of components outside of those provided by the official routes something that you perceive as a problem or not? Yes, you can find some (touch-datepicker, touch-calendar) but they seem to be few, or at the least, difficult to find.
I've updated how this works as of the next release. There's no longer any guesswork based on the case of the package - instead Application will just interrogate Ext.Loader to resolve dependencies. This means that for any external dependencies (things from outside your app) you'll just have to specify the path above your Ext.application.
Hopefully this gives a good balance of flexibility and convenience. The docs are also updated for the next release to show the changes.Ext JS Senior Software Architect
Personal Blog:
Twitter:
Github:
Thanks for that. Patiently waiting for next release, then.
B3 is now live at - hope the updated dependency management better meets your needsExt JS Senior Software Architect
Personal Blog:
Twitter:
Github:
Thanks Ed. I will check it out.
What I am trying to do is figure out a good way to write re-usable widgets. A widget could capture an editable event calendar such as this one:
(ignore the glitches, tested on safari)
And ideally, it should be possible to organize the javascript code in a way similar to this:
A mvc separation is applied, but it is done in each folder, agenda (catalogue of events) and calendar (day views), with class names that are closer to the ones I am used to (Flex conventions) than the ones in Sencha.
Some components used by the widget have the potential to be reused across projects. The ui/MoreOverflow.js class could be used in a todo list application or other list contexts. As such, there are better kept outside of the calendar folder and in a more neutral ui one.
It should be possible to add variations without modifying any file in the original author's namespace. The original Frontier calendar provided a typical monthly view. I was after a week by week one. A day view could be contributed by another user later on, without a need for me to update my own plugin. That other user should be able to link to my library and extend it, by adding and editing files in a separate namespace.
I will give a shot a turning that jQuery plugin into a Sencha one. I will keep track of the problems I come across.
Still getting the same errors. Code that was working with touch 2 pr 3 doesn't run with any of the beta versions, including beta 3.
If, in the main app controller, I specify
Code:
views : [ 'AppName.AppView', ]
Two problems. (1) I don't have a folder app. I renamed it to app1 for the purpose of testing custom path support. (2) AppView is at "app1/AppView.js", not "app/view/AppView/AppView.js" (3) AppView shows up twice in the path ('../AppView/AppView.js') though this happens inconsistently, most of the time, I get 'Failed loading 'app/view/AppName/AppView.js''? | https://www.sencha.com/forum/showthread.php?179316-Why-have-AppName-at-the-start-of-fully-qualified-class-paths | CC-MAIN-2015-35 | refinedweb | 1,565 | 65.12 |
. License:
Boost License 1.0. Authors:
Andrei Alexandrescu.
- void getopt(T...)(ref string[] args, T opts);
- Parse and remove command line options from an string array. Synopsis:
import std.getopt; string data = "file.dat"; int length = 24; bool verbose; enum Color { no, yes }; Color color; void main(string[] args) { getopt( args, "length", &length, // numeric "file", &data, // string "verbose", &verbose, // flag "color", &color); // enum ... and an unrecognized command-line argument is found, a GetOptException is thrown. Depending on the type of the pointer being bound, getopt recognizes the following kinds of options:
- Boolean options. A lone argument sets the option to true. Additionally true or false.) Options with multiple names Sometimes option synonyms are desirable, e.g. "--verbose", "--loquacious", and "--garrulous" should have the same effect. Such alternate option names can be included in the option specification, using "|" as a separator:
- : stderr.writeln("Dunno how verbose you want me to be by saying ", value); exit(1); } } getopt(args, "verbosity", &myHandler); } accepts.
- enum config: int;
- Configuration options for getopt. You can pass them to getopt in any position, except in between an option string and its bound pointer.
- caseSensitive
- Turns case sensitivity on
- caseInsensitive
- Turns case sensitivity off
- bundling
- Turns bundling on
- noBundling
- Turns bundling off
- passThrough
- Pass unrecognized arguments through
- noPassThrough
- Signal unrecognized arguments as errors
- stopOnFirstNonOption
- Stop at first argument that does not look like an option
-Options effectively. | https://docarchives.dlang.io/v2.066.0/phobos/std_getopt.html | CC-MAIN-2019-04 | refinedweb | 229 | 50.02 |
My Blog
Fan's Blog
Albums
Children
Wedding
Friends
Hobbies
Firefox
Java
Psion
Toto/4D
Palm Pilot
Wap
Html
Perl
Chinese
Web Tools
Emacs/Cygwin
The Gnu Emacs and Cygwin tty problem has been haunting me since
I have started using them the first day. I did not understand
the cause of the problem at that time. After sufficient researches,
I think I have now understood the cause of it, but I have no solution to it.
Hopefully someone brilliant can solve the problem for me.
For Gnu Emacs running in Windows, if a shell is invoked
(regardless of cmd.exe shell, emacs eshell or cygwin bash shell),
the shell is not run under a tty terminal.
This can be verified by invoking the tty.exe command distributed with
cygwin. The output from the tty.exe command simply says "not a tty".
(For Gnu Emacs running in Unix, tty command says "/dev/ttyN".)
If an application is not invoked within a tty terminal, usually the
application assumes that its output is redirected to a file. The application
will buffer the output. This means the output will not be flushed until
a sufficient amount of output has accumulated.
Considered the following simple buffer.c program.
#include <stdio.h>
int main(int argc, char** argv)
{
char buf[1000];
if( _isatty( _fileno( stdout ) ) )
printf( "stdout has not been redirected to a file\n" );
else
printf( "stdout has been redirected to a file\n");
printf("Hello World\n");
scanf("%s",buf);
return(0);
}
stdout has not been redirected to a file
Hello World
xxxxx
xxxxx
stdout has been redirected to a file
Hello World
It is fortunate that the tty problem does not happen in Cygwin Bash shell
running in a Windows DOS prompt console. If a tty.exe command is invoked, it
says "/dev/conin".
However, if the Cygwin Bash shell is run in a Cygwin rxvt
terminal, the problem appears (assuming the buffer.c program is compiled
using Microsoft Visual C compiler or using Cygwin gcc with -mno-cygwin option).
If a tty.exe command is invoked, it
says "/dev/ttyN". This suggests that /dev/ttyN used by Cygwin is not recognized as
tty by Windows.
If the same buffer.c program is compiled using Cygwin gcc complier against
the cygwin.dll (gcc buffer.c), then the problem goes away.
This means Cygwin applications recognize /dev/ttyN as a valid terminal.
In short, all Cygwin applications work well in a rxvt terminal. All Windows
applications that do not involve user inputs work in a rxvt terminal as well.
The problem is with all Windows applications that require user inputs.
More information about this problem
I do not know the solution. The workaround is to run Windows applications that
require user inputs in a Cygwin Bash shell in a Windows DOS Prompt console.
Let me know if you have found a solution. | http://www.khngai.com/emacs/tty.php | crawl-002 | refinedweb | 479 | 66.54 |
Related
Tutorial
Building a Landing Page in React Native Using Flex.
Styling a React Native app can be quite painful if you aren’t familiar with its styling powerhouse: the Flexbox layout module. While we can style with JavaScript, understanding and implementing Flexbox layout is an absolute essential for UI development with React Native. In this walkthrough, we’re going to build a landing page using Flexbox.
Spoiler alert, we won’t implement Flexbox until the end!
About Flexbox
You’re probably already familiar with flexbox layout with CSS, and React Native’s implementation of Flexbox is almost the same. Flexbox is a powerful and efficient styling tool optimized for building user interfaces, especially for mobile interfaces. By using the
flex property in a component’s style, we can enlarge and shrink dynamically based on the space available.
The
flex property in React Native is a little bit different than with CSS, and instead works a little more like the fr unit in CSS, where the number value provided represents a proportion of the space taken. So in React Native
flex expects just a simple number value.
Aside from the
flex property being different than with the CSS
flex shorthand property, the other difference between React Native’s implementation of flexbox and the CSS implementation is that the
flex-direction defaults to a value of column in React Native.
Let’s Do It
In our example project we’re going to build a landing page for AlligatorChef 🐊, the number one fictional source for cajun bacon recipes since 1987.
Here’s how our project should look when we’re finished:
🐥 If you’re new to React Native, our tutorial Getting Started with React Native and Expo is a stellar way to prepare for this tutorial.
🚀 React Native Quickstart
In your terminal run the following commands to create a new React Native project, change into the new directory, initiate the project and then enter
i for iOS.
$ create-react-native-app AlligatorChef $ cd AlligatorChef $ npm start $ i
What Do We Have Here?
We can already see an example of Flexbox being used in the initial code obtained with Create React Native App with the use of the
flex poperty in the call to
StyleSheet.create. Take a look at the
App.js file. Seems like they might be giving us a hint that Flexbox is key to styling in React Native:
const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, });
This is telling us that the container should stretch to fit the entire screen.
Next steps
Now that we have our default project, let’s make a few modifications.
Let’s first add two
Text elements for our headers.
Replace:
<Text>Open up App.js to start working on your app!</Text> <Text>Changes you make will automatically reload.</Text> <Text>Shake your phone to open the developer menu.</Text>
With:
<Text style={styles.h1}>AlligatorChef</Text> <Text style={styles.h2}>Providing cajun bacon recipes since 1987.</Text>
Not much to look at, right? Let’s add some styles in the
StyleSheet to spice it up. In one big swoop, replace everything you have with the following styles, including the default container. Your
StyleSheet should now look exactly like this:
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'space-between', backgroundColor: '#000', alignItems: 'center', width: '100%', }, h1: { color: '#008F68', fontSize: 40, }, h2: { color: '#FAE042', fontSize: 18, marginTop: 8, }, });
Let’s talk a little bit about what we just changed. You probably noticed the colors and fonts, but there’s one sparkling example that will explain why your app is looking a little spacey.
We changed justifyContent from
center to
space-between. If we change it back to
center, everything will look happy and centered again, but we have much more to add. When using
justifyContent: 'space-between' we’re getting each item spaced evenly between the top and the bottom of the screen. This is why our
h1 is glued to the top and
h2 to the bottom.
Images and Buttons
Rather than remedy this immediately, we’d prefer to create a little more chaos. Let’s go ahead and add an
Image and a
Button.
Replace your current code with the code below, while keeping the
styles declaration:
import React from 'react'; import { StyleSheet, Text, View, Button, Image } from 'react-native'; import Logo from './assets/chef.png'; export default class App extends React.Component { render() { return ( <View style={styles.container}> <Text style={styles.h1}>AlligatorChef</Text> <Text style={styles.h2}>Providing cajun bacon recipes since 1987.</Text> <Image source={Logo} style={styles.image} /> <Button title="LET'S START" style={styles.button} onPress={() => this.onPress()} </View> ); } } // ...
Next, in the
root folder, create a folder called
assets. Generally we like to keep images in an
assets folder to be easily accessible to all components in our project. Add the image file you’d like to use as your AlligatorChef 🐊 logo to this folder.
React Native is a bit fickle with images and might give you some issues. For this use case, make sure you’re using a png image.
Oof. Not quite what we were wanting, right? 🌵
Styling
Now that we have all of our elements, they look a little sad. Let’s fix that.
Images in React Native need a size
As a best practice in React Native, we always need to give our images a size. If you’re ever having an issue with an image not showing up, ensure that you’re assigning it a size. As you can see, we already gave the image a class in its
style prop so let’s give that class some attributes. In your
StyleSheet add the lines below to tame that big ole’ gator.
image: { width: 300, height: 260, justifyContent: 'center', },
He looks much more manageable now!
My button doesn’t look like a button!
React Native buttons are quite picky as well. Rather than having an opening and closing
<Button> with text between, React Native requires a title prop. If you look at the supplied code above, you’ll notice we included that to avoid some errors.
React Native requires us to send-in props to the
Button, but it also requires us to create a style for the
View that contains the button. Let’s go ahead and add a container and a class to our
StyleSheet.
First add a
View with the class of
buttonContainer to your code:
<View style={styles.buttonContainer}> <Button title="LET'S START" style={styles.button} onPress={() => this.onPress()} </View>
Next, add the following to your stylesheet:
buttonContainer: { backgroundColor: '#008F68', borderRadius: 5, padding: 8, margin: 8, },
That looks a lot more like a button!
Are You Ready for Some Flexbox?!
Okay, let’s get the rest of this page under control by using the magical Flexbox. Ya’ll ready for this? 🏀
We’re going to start by adding three
containers within our original container. If you replace your initial code with the following, you’ll notice a few new classes,
topContainer,
middleContainer, and
bottomContainer.
import React from "react"; import { StyleSheet, Text, View, Button, Image, ProgressViewIOS } from "react-native"; import Logo from "./assets/chef.png"; export default class App extends React.Component { render() { return ( <View style={styles.container}> <View style={styles.topContainer}> <Text style={styles.h1}>AlligatorChef</Text> <Text style={styles.h2}> Providing cajun bacon recipes since 1987. </Text> </View> <View style={styles.middleContainer}> <Image source={Logo} style={styles.image} /> </View> <ProgressViewIOS number={1} /> <View style={styles.bottomContainer}> <View style={styles.buttonContainer}> <Button title="LET'S START" style={styles.button} onPress={() => this.onPress()} </View> </View> </View> ); } }
Let’s add these classes to our current
StyleSheet to see some magic.
topContainer: { flex: 2, justifyContent: 'center', alignItems: 'center', }, middleContainer: { flex: 3, justifyContent: 'flex-start', alignItems: 'center', }, bottomContainer: { justifyContent: 'flex-end', width: '90%', margin: 20, padding: 10, },
✨MAGIC!✨
Let’s discuss how Flexbox saved the day
We assigned
flex: 2 to
topContainer, giving it a flex-grow value of 2, so that it takes 2/5ths of the original
container. We also told it to align and justify everything in the center. Take a look at the screenshot below for a visual demo.
We assigned
flex: 3 to
middleContainer to take the remaining 3/5ths of the original
container. Rather than using
justifyContent: 'center', we instead used
justifyContent: 'flex-start'. This is why our AlligatorChef 🐊 image is aligned to the top of
middleContainer.
Lastly since we aren’t concerned with how much of the page the
Button takes up, we do not need to specify a flexBasis. We only need the button to be at the bottom of the page, so we assign
bottomContainer
justifyContent: 'flex-end'.
That’s it 🐿
Though this is just a general introduction, the Flexbox layout module has a ton to offer for not only React Native but general web development.
👉 Always remember to look for easter eggs. 🤓 | https://www.digitalocean.com/community/tutorials/react-react-native-flexbox | CC-MAIN-2020-34 | refinedweb | 1,477 | 66.54 |
Welp, no one else on the Mac web seems to care that today is the 10-year anniversary of Steve Jobs' return to Apple, but this week also signifies another 10-year anniversary: the 10-year anniversary of the formation of the Macintosh Business Unit (Mac BU) at Microsoft! Incidentally, this anniversary (February 6, 1997) falls just one day before the Jobs return (February 7, 1997).
What did the Mac BU do to celebrate? Well, they nerded it the hell up, it seems. One ambitious employee, Joe LeBlanc, and two cohorts, Jessica Lambert and Matt Elggren, arrived at the office at 6am yesterday to set up giant, pixelated designs in the windows, made entirely out of sticky notes.
The display was "designed" in Excel, oddly enough, and made use of exactly 1,336 different-colored sticky notes.
(Photos from Microsoft's Mac Mojo)
Read the entire transcript of Mac BU's David Weiss interviewing Joe LeBlanc about how and, importantly, why the team did this. If you ever wanted to learn how to make monolithic, pixelated representations of your favorite OS X icons in Excel to be implemented in sticky notes, now's your chance.
So, happy anniversary, Mac BU! The Mac world, while harsh at times, wouldn't be the same without you guys.
You must login or create an account to comment. | https://arstechnica.com/apple/2007/02/6943/ | CC-MAIN-2017-30 | refinedweb | 224 | 60.14 |
In the following example, we will create a new custom table using the New custom table wizard. It will be a simple table for storing information about people. Each data record in the table will contain a person's first name, last name and date of birth.
1. Go to Site Manager -> Development -> Custom tables and click the New custom table (
) link.
2. The New custom table wizard starts. In the first step, you are asked to fill in the custom table's display name (used in Kentico CMS user interface) and code name (used in website code). The code name is always preceded by a namespace, which allows you to have different tables of the same name used in different contexts. Enter the following details:
and click Next to continue.
3. In the second step, you are asked to fill in the database table name, i.e. the actual name of the table in the system database. A name in the <namespace>_<code name> format is pre-filled automatically. The primary key name can not be changed by default. Using the check-boxes below, you can determine which of the default fields should be included in the table:
For the purposes of this example, leave default values for all options and click Next to continue.
4. In the third step, the field editor is displayed. It lets you define which columns will be included in the database table. Create three fields with the following attributes:
When you are finished, click Next to proceed to the following step.
5. In Step 4, you only have to select in which sites will the custom table be available. Click Add sites and choose Corporate Site in the pop-up dialog. Finally click Next to proceed to the following step.
6. Step 5 offers you to configure indexing of data in the custom table by the Smart Search module. The four drop-downs at the top determine which fields of the table will be displayed in search results. Change the values to the following:
Leave the rest of the settings at default values and click Next. For more information about settings in this step, please refer to Modules -> Smart search -> Object settings.
7. The fifth step gives you an overview of what has been done automatically by the wizard. To finish the wizard, click Finish. You will be redirected back to the list of custom tables in Site Manager -> Development -> Custom tables.
Page url: | http://devnet.kentico.com/docs/5_5r2/devguide/creating_custom_tables.htm | CC-MAIN-2019-47 | refinedweb | 412 | 72.66 |
Traditionally, web pages have been split up into markup (HTML), styling (CSS), and logic (JavaScript). Thanks to React and similar approaches, we've begun to question this split. We still may want to separate our concerns somehow. But the split can be on different axes.
This change in the mindset has lead to new ways to think about styling. With React, we're still figuring out the best practices. Some early patterns have begun to emerge, however. As a result it is difficult to provide any definite recommendations at the moment. Instead, I will go through various approaches so you can make up your mind based on your exact needs.
The old school approach to styling is to sprinkle some ids and classes around, set up CSS rules, and hope for the best. In CSS everything is global by default. Nesting definitions(e.g.,
.main .sidebar .button) creates implicit logic to your styling. Both features lead to a lot of complexity as your project grows. This approach can be acceptable when starting out, but as you develop, you most likely want to migrate away from it.
What happens when your application starts to expand and new concepts get added? Broad CSS selectors are like globals. The problem gets even worse if you have to deal with loading order. If selectors end up in a tie, the last declaration wins, unless there's
!important somewhere. It gets complex very fast.
We could battle this problem by making the selectors more specific, using some naming rules, and so on. That just delays the inevitable. As people have battled with this problem for a while, various methodologies have emerged.
Particularly, OOCSS (Object-Oriented CSS), SMACSS (Scalable and Modular Approach for CSS), and BEM (Block Element Modifier) are well known. Each of them solves problems of vanilla CSS in their own way.
BEM originates from Yandex. The goal of BEM is to allow reusable components and code sharing. Sites, such as Get BEM help you to understand the methodology in more detail.
Maintaining long class names which BEM requires can be arduous. Thus various libraries have appeared to make this easier. For React, examples of these are react-bem-helper, react-bem-render, and bem-react.
Note that postcss-bem-linter allows you to lint your CSS for BEM conformance.
Just like BEM, both OOCSS and SMACSS come with their own conventions and methodologies. As of this writing, no React specific helper libraries exist for OOCSS and SMACSS.
The primary benefit of adopting a methodology is that it brings structure to your project. Rather than writing ad hoc rules and hoping everything works, you will have something stronger to fall back onto. The methodologies overcome some of the basic issues and help you develop good software over the long term. The conventions they bring to a project help with maintenance and are less prone to lead to a mess.
On the downside, once you adopt one, you are pretty much stuck with that and it's going to be difficult to migrate. But if you are willing to commit, there are benefits to gain.
The methodologies also bring their own quirks (e.g., complex naming schemes). This may make certain things more complicated than they have to be. They don't necessarily solve any of the bigger underlying issues. They rather provide patches around them.
There are various approaches that go deeper and solve some of these fundamental problems. That said, it's not an either-or proposition. You may adopt a methodology even if you use some CSS processor.
Vanilla CSS is missing some functionality that would make maintenance work easier. Consider something basic like variables, nesting, mixins, math or color functions. It would also be nice to be able to forget about browser specific prefixes. These are small things that add up quite fast and make it annoying to write vanilla CSS.
Sometimes, you may see terms preprocessor or postprocessor. Stefan Baumgartner calls these tools simply CSS processors. The image above adapted based on Stefan's work gets to the point. The tooling operates both on authoring and optimization level. By authoring we mean features that make it easier to write CSS. Optimization features operate based on vanilla CSS and convert it into something more optimal for browsers to consume.
The interesting thing is that you may actually want to use multiple CSS processors. Stefan's image illustrates how you can author your code using Sass and still benefit from processing done through PostCSS. For example, it can autoprefix your CSS code so that you don't have to worry about prefixing per browser anymore.
You can use common processors, such as Less, Sass, Stylus, or PostCSS with React.
cssnext is a PostCSS plugin that allows us to experience the future now. There are some restrictions, but it may be worth a go. The advantage of PostCSS and cssnext is that you will literally be coding in the future. As browsers get better and adopt the standards, you don't have to worry about porting.
Compared to vanilla CSS, processors bring a lot to the table. They deal with certain annoyances (e.g., autoprefixing) while improving your productivity. PostCSS is more granular by definition and allows you to use just the features you want. Processors, such as Less or Sass, are more involved. These approaches can be used together, though, so you could, for instance, author your styling in Sass and then apply some PostCSS plugins to it as you see necessary.
In our project, we could benefit from cssnext even if we didn't make any changes to our CSS. Thanks to autoprefixing, rounded corners of our lanes would look good even in legacy browsers. In addition, we could parameterize styling thanks to variables.
With React we have some additional alternatives. What if the way we've been thinking about styling has been misguided? CSS is powerful, but it can become an unmaintainable mess without some discipline. Where do we draw the line between CSS and JavaScript?
There are various approaches for React that allow us to push styling to the component level. It may sound heretical. React, being an iconoclast, may lead the way here.
Ironically, the way solutions based on React solve this is through inline styles. Getting rid of inline styles was one of the main reasons for using separate CSS files in the first place. Now we are back there. This means that instead of something like this:
render(props, context) { const notes = this.props.notes; return <ul className='notes'>{notes.map(this.renderNote)}</ul>; }
and accompanying CSS, we'll do something like this:
render(props, context) { const notes = this.props.notes; const style = { margin: '0.5em', paddingLeft: 0, listStyle: 'none' }; return <ul style={style}>{notes.map(this.renderNote)}</ul>; }
Like with HTML attribute names, we are using the same camelcase convention for CSS properties.
Now that we have styling at the component level, we can implement logic that also alters the styles easily. One classic way to do this has been to alter class names based on the outlook we want. Now we can adjust the properties we want directly.
We have lost something in process, though. Now all of our styling is tied to our JavaScript code. It is going to be difficult to perform large, sweeping changes to our codebase as we need to tweak a lot of components to achieve that.
We can try to work against this by injecting a part of styling through props. A component could patch its style based on a provided one. This can be improved further by coming up with conventions that allow parts of style configuration to be mapped to some specific part. We just reinvented selectors on a small scale.
How about things like media queries? This naïve approach won't quite cut it. Fortunately, people have come up with libraries to solve these tough problems for us.
According to Michele Bertoli basic features of these libraries are
border,
animation,
flex.
:hover,
:active.
@media (max-width: 200px).
I will cover some of the available libraries to give you a better idea how they work. See Michele's list for a more a comprehensive outlook of the situation.
Radium has certain valuable ideas that are worth highlighting. Most importantly it provides abstractions required to deal with media queries and pseudo classes (e.g.,
:hover). It expands the basic syntax as follows:
const styles = { button: { padding: '1em', ':hover': { border: '1px solid black' }, '@media (max-width: 200px)': { width: '100%', ':hover': { background: 'white', } } }, primary: { background: 'green' }, warning: { background: 'yellow' }, }; ... <button style={[styles.button, styles.primary]}>Confirm</button>
For
style prop to work, you'll need to annotate your classes using
@Radium decorator.
React Style uses the same syntax as React Native StyleSheet. It expands the basic definition by introducing additional keys for fragments.
import StyleSheet from 'react-style'; const styles = StyleSheet.create({ primary: { background: 'green' }, warning: { background: 'yellow' }, button: { padding: '1em' }, // media queries '@media (max-width: 200px)': { button: { width: '100%' } } }); ... <button styles={[styles.button, styles.primary]}>Confirm</button>
As you can see, we can use individual fragments to get the same effect as Radium modifiers. Also media queries are supported. React Style expects that you manipulate browser states (e.g.,
:hover) through JavaScript. Also CSS animations won't work. Instead, it's preferred to use some other solution for that.
React Style plugin for Webpack can extract CSS declarations into a separate bundle. Now we are closer to the world we're used to, but without cascades. We also have our style declarations on the component level.
JSS is a JSON to StyleSheet compiler. It can be convenient to represent styling using JSON structures as this gives us easy namespacing. Furthermore it is possible to perform transformations over the JSON to gain features, such as autoprefixing. JSS provides a plugin interface just for this.
JSS can be used with React through react-jss. You can use JSS through react-jss like this:
... import classnames from 'classnames'; import useSheet from 'react-jss'; const styles = { button: { padding: '1em' }, 'media (max-width: 200px)': { button: { width: '100%' } }, primary: { background: 'green' }, warning: { background: 'yellow' } }; @useSheet(styles) export default class ConfirmButton extends React.Component { render() { const {classes} = this.props.sheet; return <button className={classnames(classes.button, classes.primary)}> Confirm </button>; } }
The approach supports pseudoselectors, i.e., you could define a selector within, such as
&:hover, within a definition and it would just work.
There's a jss-loader for Webpack.
React Inline is an interesting twist on StyleSheet. It generates CSS based on
className prop of elements where it is used. The example above could be adapted to React Inline like this:
import cx from 'classnames'; ... class ConfirmButton extends React.Component { render() { const {className} = this.props; const classes = cx(styles.button, styles.primary, className); return <button className={classes}>Confirm</button>; } }
Unlike React Style, the approach supports browser states (e.g.,
:hover). Unfortunately, it relies on its own custom tooling to generate React code and CSS which it needs to work.
Pete Hunt's jsxstyle aims to mitigate some problems of React Style's approach. As you saw in previous examples, we still have style definitions separate from the component markup. jsxstyle merges these two concepts. Consider the following example:
// PrimaryButton component <button padding='1em' background='green' >Confirm</button>
The approach is still in its early days. For instance, support for media queries is missing. Instead of defining modifiers as above, you'll end up defining more components to support your use cases.
Just like React Style, jsxstyle comes with a Webpack loader that can extract CSS into a separate file.
As if there weren't enough styling options for React, there's one more that's worth mentioning. CSS Modules starts from the premise that CSS rules should be local by default. Globals should be treated as a special case. Mark Dalgleish's post The End of Global CSS goes into more detail about this.
In short, if you make it difficult to use globals, you manage to solve the biggest problem of CSS. The approach still allows us to develop CSS as we've been used to. This time we're operating in a safer, local context by default.
This itself solves a large amount of problems libraries above try to solve in their own ways. If we need global styles, we can still get them. We still might want to have some around for some higher level styling after all. This time we're being explicit about it.
To give you a better idea, consider the example below:
style.css
.primary { background: 'green'; } .warning { background: 'yellow'; } .button { padding: 1em; } .primaryButton { composes: primary button; } @media (max-width: 200px) { .primaryButton { composes: primary button; width: 100%; } }
button.jsx
import styles from './style.css'; ... <button className=`${styles.primaryButton}`>Confirm</button>
As you can see, this approach provides a balance between what people are familiar with and what React specific libraries do. It would not surprise me a lot if this approach gained popularity even though it's still in its early days. See CSS Modules Webpack Demo for more examples.
You can use other processors, such as Sass, in front of CSS Modules, in case you want more functionality.
gajus/react-css-modules makes it even more convenient to use CSS Modules with React. Using it, you don't need to refer to the
stylesobject anymore, and you are not forced to use camelCase for naming.
Glen Maddern discusses the topic in greater detail in his article named CSS Modules - Welcome to the Future.
It is simple to try out various styling approaches with React. You can do it all, ranging from vanilla CSS to more complex setups. React specific tooling even comes with loaders of their own. This makes it easy to try out different alternatives.
React based styling approaches allow us to push styles to the component level. This provides an interesting contrast to conventional approaches where CSS is kept separate. Dealing with component specific logic becomes easier. You will lose some power provided by CSS. In return you gain something that is simpler to understand. It is also harder to break.
CSS Modules strike a balance between a conventional approach and React specific approaches. Even though it's a newcomer, it shows a lot of promise. The biggest benefit seems to be that it doesn't lose too much in the process. It's a nice step forward from what has been commonly used.
There are no best practices yet, and we are still figuring out the best ways to do this in React. You will likely have to do some experimentation of your own to figure out what ways fit your use case the best.
This book is available through Leanpub. By purchasing the book you support the development of further content. | https://survivejs.com/react/advanced-techniques/styling-react/index.html | CC-MAIN-2018-51 | refinedweb | 2,469 | 67.65 |
Mobile App Performance and Size Optimization
iOS vs Android
Smartface is supporting iOS and Android development. Both working with Native API access. For more information how this works please check Smartface Native Framework Architecture document.
iOS and Android are very different platforms. They have different architectures. Smartface is bringing layers for single code base app development. Some differences are managed on the Native side, some of them are managed in the sf-core side. Even though Smartface is managing those differences, but still it is bound to the limitations of the platform which it is running on.
For that reason, while developing apps, developers will notice performance differences between iOS and Android.
Here is a comparison of some fundamental performance differences between iOS and Android:
The features mentioned above should be used with care. The developer needs to reduce the usages of those features excessively. This will not just benefit Android, iOS will benefit too.
File Operations
There are several calls that result in file operation:
- File Read & Write
- Creating an image from file
- require
- Data & Database
General tips
- Try to reduce the number of calls
- Define them on top of the file as much as possible as long it suits
- require uses caching by (absolute) paths. When a resolved path is a match, it reuses the cached module export. Resolving the path is a CPU operation if not a file (for cached results). Using require on top of the file at least reduces the CPU calls.
- Define images on top of the file, as much as possible.
- Cache values as much as possible. For Page instance-related values, using of WeakMap and WeakSet is advised.
- Use global variables or modules to share data across the files, do not use the Data or Database modules. Data & Database to be used only with persistent data.
Blob
Android parses blob (Binary Large Object Block) slower than iOS. This resulting in converting binary data to other formats.
- Try to cache the converted values (such as images)
- Try to use small amounts of HTTP data while parsing responses. Make sure APIs responds only relevant data.
- If an image needs to be downloaded from the internet and to be showed on an ImageView and caching is not required, using of ImageView.loadFromUrl is advised.
If possible using async task will also speed-up the process.
Pages
Pages are the core of the application. They form whole screen UI and also used with navigator & SwipeView.
Creation of a page has a cost. The cost is considerable for both iOS & Android. To reduce the number creation of pages, defining them as a singleton for Router and Navigator is important. As a side effect, this approach is making the state management of pages mandatory, such as the need to reset as they are shown in some cases. Anyway resetting the data & display costs definitely less than the creation of whole new UI page and children.
SwipeView
SwipeView pages are created partially when assigned. Setting the pages property causes recreating of all pages as it is assigned.
If data on the SwipeView pages to be changed, but not the number of pages, then this SwipeView.pages property should not be re-assigned, instead data should be modified on the instances of the pages. How to access to the SwipeView instances is explained in SwipeView Guide.
UI Thread
JavaScript is a single-threaded environment. setTimeout and setInterval creates a timer call back to the same main JavaScript thread.
In Smartface JavaScript thread is performing UI operations. In order to access UI objects from JS, JS main thread and the UI thread are the same. So everything that causes to wait on the JS side can cause hanging and freeze on the UI.
In order to avoid such behavior, and perform partial UI updates, dividing the big tasks into smaller tasks by using timers (setTimeout, setInterval) is advised.
There is no doubt that mobile device performance increases day by day. Still, mobile apps should be considered as thin clients of the system. The heavy burden of calculation should be performed on the servers as much as possible.
Even such an architectural design needs some performance tuning: UI operations. Heavy cost UI operations on the app will make the app run slower. In order to fine-tune those operations following things can be done:
Splash
Splash is shown until the first page appears the screen, caused by Router.go. If there are some heavy operations that need to be completed, those operations can be triggered before showing the first page. This approach is extending the splash duration (app start) and reduces the UI freeze, it is a trade-off actually.
BottomTabBar
BottomTabBar is creating pages and uses navigator. This is causing creating bulk of pages when it is initiated, some of its pages are created on demand. This is considered a heavy UI operation. If needed, this operation can be moved to the app start.
Setting data during onShow
Page.onShow event is fired after the page is even partially shown. This event is giving enough time for developers to bind data. If the showing of the page is slow (due to the big constructor and onLoad operations) some of the tasks can be moved to onShow. This causing a faster appearance of the page, but still, the total loading time will be the same.
Using state management and subscribing to changes
When using a state management library like Redux or Flux to handle your own states, make sure that the subscribes you define on the page is unsubscribed on the page removal. You can use onHide for such cases, removing the risks of unexpected UI rendering on a page which doesn't exist anymore.
Async Task
Smartface introduces a new feature called AsyncTask. The task function is running on a separate thread, should not access (will result in a crash) to UI components and no UI operation should be performed on this task. It is useful to load some heavy libraries, which do not depend on the UI (such as google-libphonenumber).
This async task is not fully compatible with any library. Some libraries might cause a problem depending on each System (iOS or Android) and might result in hang or crash. This is determined by trial and error.
Util lib offers a promise based solution.
Property assignment
In Smartface, with sf-core assignments directly affecting the UI object.
this.textBox1.text = "Smartface"; //assignment
When the assignment occurs, it goes to the next line after UI operation is complete.\ This can cause an overhead if the original value before the assignment is the same with the value to be assigned after.
import Color from "@smartface/native/ui/color";
this.flexLayout.backgroundColor = Color.RED;
const myRed = Color.create("#FF0000");
this.flexLayout.backgroundColor = myRed;
The example above is triggering the UI rendering twice for the same outcome, wasting a precious time of execution.\ It will be better to assign a property if the value is different what it originally had. For that solution, Smartface Contx is very handy. Contx is a base style state management tool shipped with Smartface. Contx is keeping track of changes on the object, is called state. As long as all the changes are done via Contx, the state will not be broken. Before making an assignment with Contx, it is comparing the value to be assigned with the original values, only the different ones are assigned.
- Contx Assignment
- myFlexLayout Class
this.flexLayout.dispatch({
type: "pushClassNames",
classNames: ".myFlexLayout",
}); //this makes the background color as red
this.dispatch({
type: "updateUserStyle",
userStyle: {
backgroundColor: "#FF0000",
},
}); //original color is already red, no UI update
{
".myFlexLayout":
{
"backgroundColor": "#FF0000"
}
}
If the code is written out of the state, Contx will not be aware of the changes. Below is a bad example, and do not write such code as much as possible.
- Bad State Management
- myFlexLayout
this.flexLayout.dispatch({
type: "pushClassNames",
classNames: ".myFlexLayout",
}); //this makes the background color as red
this.flexLayout.backgroundColor = Color.BLUE;
// Contx still thinks the background color is red
this.dispatch({
type: "updateUserStyle",
userStyle: {
backgroundColor: "#FF0000",
},
}); //original color supposed to be red, so Contx state does not see any change, so it does not perform a UI update
{
".myFlexLayout":
{
"backgroundColor": "#FF0000"
}
}
MapView
MapView is not a light view. In order to interact with the map, it is advised to use the onCreate Event.
If a page has a MapView, postpone the following actions after the event is called:
- Service call, which is going to populate the map pins
- Add pins
- Add map events (such as move)
- Add additional views/controls to interact with the map to the page (or dialog)
Using this will have minimal impact on iOS, will have an impact on Android.
As a UI guidance, showing an activity indicator is advised.
MapView does not keep a flag that it is created or not. Also, in some cases, onCreate might be triggered before Page.onShow event. Best practice to handle that event is to use a code like this:
function pageConstructor() {
setupMapReadiness(page);
}
function onShow() {
tickMapReady();
this.mapReady(()=> {
//perform the service call
});
}
functon onMapViewCreate() {
tickMapReady();
}
function buttonPress() {
this.mapReady(() => {
//do any action for intreacting the map
});
}
function setupMapReadiness(page) {
let tick = 0;
let readyList = [];
this.tickMapReady = function tickMapReady() {
tick++;
if(tick >= 2 && readyList.length > 0) {
readyList.forEach(fn => fn.call(page));
readyList.length = 0;
}
};
this.mapReady = function mapReady(fn) {
if(tick >= 2) { //shown & created
readyList.push(fn); //adds them
} else {
fn.call(page); //map is ready, call it as requested
}
}
}
BottomTabBar
BottomTabBar (btb as short) is managing pages like a router does. It is responsible for showing pages. Pages are created and shown as btb instructs.
In the normal behavior of btb, pages are created on demand, as the user changes the tabs. According to that flow:
- The tab is about to change
- The target page is created, constructor called
- The page is loaded, onLoad event called
- Tab changed
- The page is shown, onShow event is called
Using heavy operations, too much controls & views may slow down the changing of the tab. A case looking fine on iOS might work too slow for Android. Performing the following actions might speed up the btb performance:
- Creating pages as they are being added to btb
- Adding UI components/views on-demand
- Performing actions after onShow
- Map related actions
Adding UI components/views on-demand
If the page components are to be shown after some asynchronous call, it is advised to not to add those components beforehand to the page. Create those views using library and add them to the page on demand. This will greatly improve the performance of tab switching.
Performing actions after onShow
Some pages containing lots of UI components/views, including static ones. Using those pages in btb might slow down the changing of the tab. It is advised to show an ActivityIndicator and add those components after the page is shown. (not changing the visibility; adding)
Map related actions
Using MapView in btb can have an impact on switching the tabs. If the guideline above is followed the impact will be minimum.
Life-cycle
If a page is shown once, only the page.onShow event is fired:
- The tab is about to change
- Tab changed
- The page is shown, onShow event is called
If the guidelines above are followed, make sure that the post-onShow UI operations may occur once only.
Avoid ScrollView
ScrollView, ListView, GridView can be used to show vertical scrolling content. In ScrollView all of the child components are created at the beginning while ListView and GridView are only creating the items which are visible only and they are creating rest of the items on-demand as user scrolls.
It is advised to avoid ScrollView as much as possible if a ListView or GridView can be used even with non-uniform items. This approach will also increase the performance of BottomTabBar, because items can be rendered during onShow.
Caching
With JavaScript tricks, caching mechanisms can also help performance. We have a scenario to give an example of caching.
- Assume there is a ListView
- Each ListViewItem has a touch interaction defined in onRowSelected method
- When a row is selected, a Menu is shown.
listView.onRowSelected = function (listViewItem, index) {
showMenu(data);
};
function showMenu(data) {
const menu = new Menu();
const menuItemCopy = new MenuItem({
title: "Copy",
});
menu.items = [menuItemCopy];
menu.headerTitle = data;
menuItemCopy.onSelected = function () {
alert(data);
};
menu.show(page);
}
listView.onRowSelected = function (listViewItem, index) {
showMenu(data);
};
const showMenu = (function () {
// This block runs only once and variables are cached
const menu = new Menu();
const menuItemCopy = new MenuItem({
title: "Copy",
});
menu.items = [menuItemCopy];
// End of block
// Main logic, this block runs every time when showMenu is called
return function (data) {
menu.headerTitle = data;
menuItemCopy.onSelected = function () {
alert(data);
};
menu.show(page);
};
})();
In the latter code sample:
- Menu and MenuItem instances are created only once
- Events and properties are set when showMenu is called, same instances are used
Using console.log statements
These statements can cause a big bottleneck in the JavaScript UI thread. These statements are unnecessary when running a published app. So make sure to remove them before publishing.
Other
- When performing lazy loading on ListView, use onRowBind method.
- onLoad method of a SwipeView's page is triggered when swipe occurs on Android. On iOS, onLoad method of all pages is triggered at the beginning. Please consider this while working with a SwipeView object.
Application Size
Users are usually reluctant to download an application that is too large. This section explains how to reduce the size of the application.
App resources can take up 70%-75% of the application. Resources can be a custom fonts, multimedia content or images. You can compress jpeg and png files without affecting the visible image quality using tools like pngcrush. It is also recommended to delete the unused resources.
In Android, you don't need to support all available densities based on the user base. Android densities are
mdpi,
hdpi,
xhdpi,
xxhdpi and
xxxhdpi. If you have a data that only a small percentage of your users have devices with specific densities, consider whether you need to bundle those densities into your app or not. For more information screen densities, see Screen Sizes and Densities | https://docs.smartface.io/7.0.1/smartface-native-framework/tips-and-tricks/mobile-app-performance-and-size-optimization/ | CC-MAIN-2022-40 | refinedweb | 2,362 | 65.32 |
8560/how-make-transactions-without-creating-assets-multichain
To transfer your Mycoins, you can make use of the send command as follows:
send address amount
where address is the address of the receiver.
To Know more about this, check out
In a private ethereum network you have ...READ MORE
you can use
const Socket = require('blockchain.info/Socket');
const mySocket ...READ MORE
you can use proof of Authority consensus ...READ MORE
You can change the speed by the ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
You can do this by developing a ...READ MORE
It could be because of the script ...READ MORE
OR | https://www.edureka.co/community/8560/how-make-transactions-without-creating-assets-multichain?show=8561 | CC-MAIN-2019-35 | refinedweb | 133 | 70.7 |
#include <euc.h> int csetlen(int codeset);
int csetcol(int codeset);
int csetno(unsigned char c);
#include <widec.h> int wcsetno(wchar_t pc);
Both csetlen() and csetcol() take a code set number codeset, which must be 0, 1, 2, or 3. The csetlen() function returns the number of bytes needed to represent a character of the given Extended Unix Code (EUC) code set, excluding the single-shift characters SS2 and SS3 for codesets 2 and 3. The csetcol() function returns the number of columns a character in the given EUC code set would take on the display.
The csetno() function is implemented as a macro that returns a codeset number (0, 1, 2, or 3) for the EUC character whose first byte is c. For example,
#include<euc.h> . . . x+=csetcol(csetno(c));
increments a counter “x” (such as the cursor position) by the width of the character whose first byte is c.
The wcsetno() function is implemented as a macro that returns a codeset number (0, 1, 2, or 3) for the given process code character pc. For example,
#include<euc.h> #include<widec.h> . . . x+=csetcol(wcsetno(pc));
increments a counter “x” (such as the cursor position) by the width of the Process Code character pc.
These functions work only for the EUC locales.
The cset(), csetlen(), csetcol(), csetno(), and wcsetno() functions can be used safely in multithreaded applications, as long as setlocale(3C) is not being called to change the locale.
See attributes(5) for descriptions of the following attributes:
setlocale(3C) euclen(3C), attributes(5) | http://docs.oracle.com/cd/E36784_01/html/E36874/csetcol-3c.html | CC-MAIN-2014-42 | refinedweb | 259 | 61.56 |
mcpi alternatives and similar packages
Based on the "Network" category.
Alternatively, view mcpi alternatives based on common mentions on social networks and blogs.
haskoin9.9 4.5 mcpi VS haskoinHaskoin Core is a Bitcoin and Bitcoin Cash library
tls9.8 6.8 mcpi VS tlsTLS/SSL implementation in haskell
gogol9.8 9.9 mcpi VS gogolA comprehensive Google Services SDK for Haskell.
prometheus-client9.2 2.6 mcpi VS prometheus-clientHaskell client library for exposing prometheus.io metrics.
curl9.2 0.0 mcpi VS curlA Haskell binding to the curl library
connection9.1 0.0 mcpi VS connectionsimple client connection library in haskell with builtin features: SSL/TLS, SOCKS, session management.
network-hans8.9 0.0 mcpi VS network-hansHaNS <-> Network Shims for easier porting to HaNS and the HaLVM
riak8.8 0.0 mcpi VS riakA fast Haskell client library for the Riak decentralized data store
libssh28.7 4.3 mcpi VS libssh2LibSSH2 FFI bindings for Haskell
json-rpc8.1 2.0 mcpi VS json-rpcFully-featured JSON-RPC 2.0 library for Haskell programs
pcap8.0 0.0 mcpi VS pcapHaskell bindings for the pcap library, which provides a low level interface to packet capture systems.
glue7.8 0.0 mcpi VS glueBuilding Better Services And Clients
api-builder7.6 0.0 mcpi VS api-builderlibrary for building JSON API wrappers in haskell
pusher-http-haskell7.4 5.9 mcpi VS pusher-http-haskellPusher Channels Haskell HTTP Library
helics6.9 0.0 mcpi VS helicsNew Relic® agent SDK wrapper for Haskell
pagerduty6.5 0.0 mcpi VS pagerdutyHaskell PagerDuty API Client
tcp-streams5.9 0.0 mcpi VS tcp-streamsOne stop solution for tcp client and server with tls support.
download5.9 0.0 L2 mcpi VS downloadHigh level download interface for Haskell
udbus5.3 0.0 mcpi VS udbusSmall Haskell DBus implementation
Dust-tools5.0 0.0 mcpi VS Dust-toolsA set of tools for exploring network filtering
memcache-conduit5.0 0.0 mcpi VS memcache-conduitConduit library for memcache procotol
fluent-logger4.8 0.0 mcpi VS fluent-loggerA structured logger for Fluentd (Haskell)
hs-twitterarchiver4.6 0.0 mcpi VS hs-twitterarchiverCommandline Twitter feed archiver
peyotls4.4 0.0 mcpi VS peyotlsPretty Easy YOshikuni-made TLS library
linode-v43.6 0.0 mcpi VS linode-v4Haskell wrapper for the Linode v4 API
kafka-client2.9 0.0 mcpi VS kafka-clientLow-level Haskell client library for Apache Kafka 0.7.
hsdns-cache2.1 0.0 mcpi VS hsdns-cacheCaching asynchronous DNS resolver
Clean code begins in your IDE with SonarLint
* Code Quality Rankings and insights are calculated and provided by Lumnify.
They vary from L1 to L5 with "L5" being the highest.
Do you think we are missing an alternative of mcpi or a related project?
Popular Comparisons
README
mcpi
All code is placed in the Public Domain.
Author
Doug Burke, [email protected]
Description
This is a basic interface to the MineCraft-Pi API. The intention is to build higher-level commands (and add support for missing commands), but you can say
{-# LANGUAGE RecordWildCards #-} module Main where import Control.Monad (when) import Data.MineCraft.Pi.Block import Data.MineCraft.Pi.Player import Data.MineCraft.Pi.Types import Network.MineCraft.Pi.Client -- | Returns @[email protected] if the player is standing on gold ore. isOnGold :: IO Bool isOnGold = runMCPI $ do Pos {..} <- getPlayerTile bType <- getBlock $ Pos _x _y (_z-1) return (bType == goldOre) main :: IO () main = do flag <- isOnGold when flag $ putStrLn "Look down!"
Building
Install ghc and the Haskell platform
sudo apt-get install ghc haskell-platform
Download the package
cabal unpack mcpi
which will create the directory
mcpi-<version>. If you instead
say
cabal install mcpi
then the package will be built and installed into the system; by
using
unpack you just build a local copy.
Build the package
cd mcpi-<version> cabal configure cabal build
You may need to install the
pipes package before the above
will run:
cabal install pipes
Run one of the examples
./dist/build/isongold/isongold
Examples
Several examples are included in the
examples/
directory. They are built, and installed, by default. To avoid
building them tun off the
build-examples flag at configure time by
saying
cabal configure -f-build-examples | https://haskell.libhunt.com/hmcpi-alternatives | CC-MAIN-2022-33 | refinedweb | 701 | 59.09 |
Debugging Python’s Memory Usage with Dowser
The Performance Zone is brought to you in partnership with New Relic. New Relic APM provides constant monitoring of your apps so you don't have to.
As I mentioned in my previous post, I had to hunt down a leak (which was intentional considering the functionality) somewhere in a batch import task in my Pyramid app. I’ve never played around with any memory profilers in python before, so this was a proper opportunity to see what the different options were. StackOverflow to the rescue as usual, with a handful of suggestions for Python memory profilers.
After trying a few, I ended up with Dowser. Dowser fit my use case neatly, as my application was a long running process, was console based (since it uses cherrypy to launch its own HTTP Server, it was a good thing that it didn’t conflict with any existing server) and I could pause it at a proper location before it consumed too much memory (a time.sleep(largevaluehere) worked nicely, thank you).
Installing Dowser was relatively pain free (a few of the other options I tried either needed custom patches, or required the process to run all the way through before giving me the information I needed).
I needed to dependencies installed:
pip install pil
... which Dowser uses to generate sparkline diagrams, and cherrypy itself:
easy_install cherrypy
... and last, checking out the latest version of Dowser from SVN:
svn co dowser
I modified the example from the Stack Overflow question above a bit, and ended up with a small helper function in the application’s helper library:
def launch_memory_usage_server(port = 8080): import cherrypy import dowser cherrypy.tree.mount(dowser.Root()) cherrypy.config.update({ 'environment': 'embedded', 'server.socket_port': port }) cherrypy.engine.start()
Then doing
launch_memory_usage_server() somewhere early in my code launched the HTTP interface () to see memory usage while the import process was running. This helped me narrow down where the issue showed up (as we were leaking MySQLdb cursors at an alarming rate), and digging deeper into the structure hinted to the underlying cause.
The Performance Zone is brought to you in partnership with New Relic. New Relic’s SaaS-based Application Performance Monitoring helps you build, deploy, and maintain great web software.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/debugging-python%e2%80%99s-memory?mz=110215-high-perf | CC-MAIN-2015-48 | refinedweb | 390 | 50.97 |
On Thursday 12 December 2002 03:12, Joe Thornber wrote:> On Wed, Dec 11, 2002 at 04:15:42PM -0800, Wil Reichert wrote:> > Ok, 2.5.51 plus dm patches result in the following:> >> > Initializing LVM: device-mapper: device> > /dev/ide/host2/bus1/target0/lun0/disc too small for target> > device-mapper: internal error adding target to table> > device-mapper: destroying table> > device-mapper ioctl cmd 2 failed: Invalid argument> > Couldn't load device 'cheese_vg-blah'.> > 0 logical volume(s) in volume group "cheese_vg" now active> > lvm2.> >> > Was fine (minus of course the entire bio thing) in 50, did something> > break in 51 or is it just my box?>> I've had a couple of reports of this problem. The offending patch is:>>>0005.patch>> back it out if necc.>> All it does is:>> --- diff/drivers/md/dm-table.c 2002-12-11 11:59:51.000000000 +0000> +++ source/drivers/md/dm-table.c 2002-12-11 12:00:00.000000000 +0000> @@ -388,7 +388,7 @@> static int check_device_area(struct dm_dev *dd, sector_t start, sector_t> len) {> sector_t dev_size;> - dev_size = dd->bdev->bd_inode->i_size;> + dev_size = dd->bdev->bd_inode->i_size >> SECTOR_SHIFT;> return ((start < dev_size) && (len <= (dev_size - start)));> }Actually, this 00005.patch *is* necessary. dd->bdev->bd_inode->i_size *is* in bytes, and does need to be shifted to do the above comparison.I believe we have tracked the problem down to the call to dm_get_device() in dm-linear.c. It is passing in an incorrect value, which winds up being the "start" parameter to the check_device_area() function. I've included a patch at the end of this email which I believe should fix the problem. I have also checked dm-stripe.c, and it appears to make the call to dm_get_device() correctly, so no worries there.-- Kevin Corrycorryk@us.ibm.com--- linux-2.5.51a/drivers/md/dm-linear.c 2002/11/20 20:09:22 1.1+++ linux-2.5.51b/drivers/md/dm-linear.c 2002/12/12 21:38:32@@ -43,7 +43,7 @@ goto bad; } - if (dm_get_device(ti, argv[0], ti->begin, ti->len,+ if (dm_get_device(ti, argv[0], lc->start, ti->len, dm_table_get_mode(ti->table), &lc->dev)) { ti->error = "dm-linear: Device lookup failed"; goto bad;-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2002/12/12/173 | CC-MAIN-2016-44 | refinedweb | 396 | 58.18 |
Following on from this post, I wanted to see what would happen if I opened my solution in Expression Blend 2.5 June Preview and tried to style my control a little.
So, I opened it in Blend.
I got a bit stuck straight away because when I tried to display my page.xaml Blend threw up an error;
From the stack trace, this looked suspiciously like some of my code running to load images when it really shouldn't be inside of a design time environment like Blend.
So, I added a little member function to my control;
private bool IsInDesignMode
{
get
{
return (DesignerProperties.GetIsInDesignMode(this));
}
}
and called it from a few places to stop the control trying to load images and so on if it's in design mode rather than run-time mode and Blend sprung into life;
Now...to try and set about styling the control. First off, I created an empty template for my control;
Then I took the Grid that's given to me;
and replaced it with a StackPanel, some Buttons, an Image and a couple of other bits and pieces to create my UI. I made sure to name this things in accordance with the naming expected by my control. I managed to get as far as this;
Which gives me this delightful look and feel ;-)
With a sort of "border path" that I "drew" in Expression Design but then I got stuck in that I get exceptions from Blend if I try and change the template on those buttons that I've got. That is, just picking one of those buttons and doing "Edit Empty Template" gives me;
I wasn't entirely sure what to do about that but I found that if I went into the XAML and just set up a Template for the buttons manually and then just put something basic into that template then once I revisited that in Blend it would now edit that template.
So, I managed to get a fairly ugly looking thing :-) but at least it looks different from where I started;
And, with that, I'm giving up for a while :-)
If you want the project, then I shared the whole thing here for download. It includes the web project, the images, everything so you should be able to just press F5. Most of the size of the ZIP file is the 5 images which are taken from Windows. | http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2008/07/21/10617.aspx | crawl-002 | refinedweb | 407 | 70.16 |
Greetings! "Mike Thomas" <address@hidden> writes: > Hi Camm. > > 1. While trawling through the ANSI tester output a few days ago I noticed > that call-arguments-limit (set to 64) conflicts with the test in "eval.c" > based on the C macro MAX_ARGS (63) defined in "h/funlink.h". > > I played it safe and set call-arguments-limit to MAX_ARGS (in "eval.c") > which I left at 63. This fixed the failure of SUBTRACT.3 in the ANSI tests: > > (LET ((ARGS NIL)) > (LOOP > FOR > I > FROM > 1 > TO > (MIN 256 (1- CALL-ARGUMENTS-LIMIT)) > DO > (PUSH 1 ARGS) > ALWAYS > (EQL (APPLY #'- 1000 ARGS) (- 1000 I)))) > > but is not necessarily a high quality design decision. I also set > LAMBDA-PARAMETERS-LIMIT to MAX_ARGS. > Thanks for your changes here, discussed separately, which all look fine. > Now in CVS. > > > 2. Also now in CVS is stack size configuration for Windows. I still need to > link it to the test for C stack origin by passing a switch to the linker for > that test. It is possible that other platforms may be affected accidentally > by these changes - hopefully not. > Small error here breaking the Linux build. Committed a fix. Please object if necessary. :-) > 3. I am proposing a patch to GCL along the general lines set out below to > remove compiler warnings about the unknown optimizer quality "debug" as > frequently seen in the ANSI test output. These changes (*debug* and > appropriate checks in "cmpnew/gcl_cmpmain.lsp") are sufficient to remove > those warnings but I've hesitated about an appropriate compiler response to > the debug quality in light of the CLHS discussion: > > > I certainly agree, at least personally, with the paragraph at the bottom here. These compilation parameters are confusing. That said, we could do some creative things here given that we mostly build atop gcc. *debug* should strip out -fomit-frame-pointer, turn on *c-debug* aka. -g, turn on *default-c-file* and *keep-gaz*, and push the file load address to the function symbol plist (as its lambda list is done now) with the debug property, so that we might facilitate running atop gdb and loading the symbol tables dynamically at runtime. Not that it would do much, but *space* should throw -Os. This does conflict with *speed*, as does *debug* via the conflict with -fomit-frame-pointer. Other than this, debugging and speed are mostly orthogonal with gcc. To my very limited understanding, *safety* is effectively a binary toggle, turning on type checking (alone) in the compiled code. > I imagine that the right thing would be for that quality to put debug > switches in the C compiler command line via *c-debug* , leaving manipulation > of C optimizer switches to the other optimizer qualities (it might be > beneficial, on occasion, to have maximum optimization with debug symbols). > > The negative side to this patch is that I renamed "si::debug" to > "si::debugger" to avoid a namespace clash with the compiler debug quality > symbol. > > Not yet in CVS > I've seen your patch, and it looks good. I don't see the name clash. *debug*!=debug, no? Currently, the symbol represents both a function and denotes an element in a symbol's plist. It would not appear that this would have to be changed. If it does need changing, we should change the C vars sSdebug and fSdebug accordingly. I'd like to work a bit on this too time permitting. > After these changes 1164 of the ANSI tests fail on Windows. > Great! Most of this stuff, for me at least, is pretty printing. Haven't yet heard from anyone regarding the advisability of inhaling XP as compared with rolling our own. Take care, > Cheers > > Mike Thomas. > > > > > -- Camm Maguire address@hidden ========================================================================== "The earth is but one country, and mankind its citizens." -- Baha'u'llah | http://lists.gnu.org/archive/html/gcl-devel/2004-11/msg00012.html | CC-MAIN-2015-06 | refinedweb | 630 | 64.91 |
INTRO(5) File Formats Manual INTRO(5)
NAME
intro - introduction to the Plan 9 File Protocol, 9P
SYNOPSIS
#include <<fcall.h>>
DESCRIPTION
A Plan 9, per-
haps servers: system calls
operating on files are translated into requests and responses transmit-
ted. The first byte is the
message type, one of the constants in the enumeration in the include
file <<fcall.h>>. The remaining bytes are parameters. Each parameter
consists of a fixed number of bytes (except the data fields of write
requests or read replies); in the message descriptions below, the num-
ber of bytes in a field is given in brackets after the field name. The
two-, four-, and eight-byte fields may hold unsigned integers repre-
sented in little-endian order (least significant byte first). Fields
that contain names are 28-byte strings (including a terminal NUL (zero)
byte). Other than the NUL terminator, all characters are legal in file
names. (Systems may choose to reduce the set of legal characters to
reduce syntactic problems, for example to remove slashes from name com-
ponents, but the protocol has no such restriction. Plan 9 names may
contain any printable character (that is, any character outside hexa-
decimal 00-1F and 80-9F) except slash and blank.) Messages are trans-
ported in byte form to allow for machine independence; fcall(2)
describes routines that convert to and from this form into a machine-
dependent C structure.
MESSAGES
Tnop tag[2]
Rnop tag[2]
Tsession tag[2] chal[8]
Rsession tag[2] chal[8] authid[28] authdom[48]
Rerror tag[2] ename[64]
Tflush tag[2] oldtag[2]
Rflush tag[2]
Tattach tag[2] fid[2] uid[28] aname[28] ticket[72] auth[13]
Rattach tag[2] fid[2] qid[8] rauth[13]
Tclone tag[2] fid[2] newfid[2]
Rclone tag[2] fid[2]
Tclwalk tag[2] fid[2] newfid[2] name[28]
Rclwalk tag[2] fid[2] qid[8]
Twalk tag[2] fid[2] name[28]
Rwalk tag[2] fid[2] qid[8]
Topen tag[2] fid[2] mode[1]
Ropen tag[2] fid[2] qid[8]
Tcreate tag[2] fid[2] name[28] perm[4] mode[1]
Rcreate tag[2] fid[2] qid[8]
Tread tag[2] fid[2] offset[8] count[2]
Rread tag[2] fid[2] count[2] pad[1] data[count]
Twrite tag[2] fid[2] offset[8] count[2] pad[1] data[count]
Rwrite tag[2] fid[2] count[2]
Tclunk tag[2] fid[2]
Rclunk tag[2] fid[2]
Tremove tag[2] fid[2]
Rremove tag[2] fid[2]
Tstat tag[2] fid[2]
Rstat tag[2] fid[2] stat[116]
Twstat tag[2] fid[2] stat[116]
Rwstat tag[2] fid[2]
Each T-message has a tag field, chosen and used by the client to iden-
tify the message. The reply to the message will have the same tag.
Clients must arrange that no two outstanding messages on the same con-
nection have the same tag. An exception is the tag 0xFFFF, meaning `no
tag': the client can use it, when establishing a connection, to over-
ride tag matching in nop and session messages.
The type of an R-message will either be one greater than the type of
the corresponding T-message or Rerror, indicating that the request
failed. In the latter case, the ename field contains a string describ-
ing the reason for failure.
The nop message request has no obvious effect. Its main purpose is in
debugging the connection between a client and a server. It is never
necessary. A session request initializes a connection and aborts all
outstanding I/O on the connection. The set of messages between session
requests is called a session.
Most T-messages contain a fid, a 16 manipu-
lated by the operating system -- are identified by fids. Fids are cho-
sen by the client. All requests on a connection share the same fid
space; when several clients share a connection, the agent managing the
sharing must arrange that no two clients choose the same fid.
The first fid supplied (in an attach message) will be taken by the
server to refer to the root of the served file tree. The attach iden-
tifies the user to the server and may specify a particular file tree
served by the server (for those that supply more than one). A walk
message causes the server to change the current file associated with a
fid to be a file in the directory that is the old current file. Usu-
ally, a client maintains a fid for the root, and navigates by walks on
a fid cloned from the root fid.
A client can send multiple T-messages without waiting for the corre-
sponding R-messages, but all outstanding T-messages must specify dif-
ferent tags. The server may delay the response to a request on one fid
and respond to later requests on other fids; this is sometimes neces-
sary, for example when the client reads from a file that the server
synthesizes from external events such as keyboard characters.
Replies (R-messages) to eight-byte qid fields rep-
resent two four-byte unsigned integers: first the qid path, then the
qid version. The path is an integer unique among all files in the
hierarchy. If a file is deleted and recreated with the same name in
the same directory, the old and new path components of the qids should
be different. Directories always have the CHDIR bit (0x80000000) set
in their qid path. The version is a version number for a file; typi-
cally, it is incremented every time the file is modified.
An existing file can be opened, or a new file may be created in the
current (directory) file. I/O of a given number of bytes (limited to
8192) 28-byte names. The wstat transaction
allows some of a file's properties to be changed.
A request can be aborted with a Tflush request. When a server receives
a Tflush, it should not reply to the message with tag oldtag (unless it
has already replied), and it should immediately send an Rflush. The
client should ignore replies with tag oldtag until it gets the Rflush,
at which point oldtag may be reused.
Most programs do not see the 9P protocol directly; instead calls to
library routines that access files are translated by the mount driver,
mnt(3), into 9P messages.
DIRECTORIES
Directories are created by create with CHDIR set in the permissions
argument (see stat(5)). The members of a directory can be found with
read(5). All directories must support walks to the directory .. (dot-
dot) meaning parent directory, although by convention directories con-
tain per-
missions: read-
ing permis-
sions. If bit 31 is set, the file is a directory; if bit 30 is set,
the file is append-only (offset is ignored in writes); if bit 29 is
set, the file is exclusive-use (only one client may have it open at a
time).
INTRO(5) | http://modman.unixdev.net/?sektion=5&page=0intro&manpath=plan9 | CC-MAIN-2017-17 | refinedweb | 1,167 | 66.27 |
Debuggers. Maybe you don’t always need them, but when you do, you need one that can give you comprehensive insight into your code, and make it easy to quickly track down problems.
In this post, we’ll take a look at some of the most popular Python debuggers to see how they measure up against each other, and to give you a chance to decide which debugger is right for your Python projects.
Let’s start with the basics: Python’s built-in pdb.
Pdb: The Native Python Debugger
Python’s default debugger, pdb, is a no-frills module with a strictly command-line interface. You can use it to perform basic debugging tasks such as stepping through code, post-mortem debugging, displaying the values of specified code elements, and stack frame inspection. You can set hard breakpoints using the in-line command
import pdb; pdb.set_trace() (which starts the debugger at the location where it’s placed), or use the
break or
tbreak commands to set persistent or temporary breakpoints from the debugger prompt.
pdb can also be set to skip specified code elements, to execute statements, and to evaluate specified functions. You can move through the stack trace, manage breakpoints, jump to arbitrary locations in the code, and combine commands into aliases. Commands (including aliases) can be placed in a file named
.pdbrc, which will be loaded automatically if it is present when you run pdb, providing a considerable degree of scriptability.
pdb is certainly a step above no-debugger debugging, but it is definitely a classic example of the bare-bones, CLI-only school of debuggers.
Pros:
- Convenient for smaller projects with relatively simple debugging requirements since it has minimal overhead.
Cons:
- For a project of any size or complexity, pdb’s CLI-only approach can prove frustrating.
- Evaluates individual variables and expressions only when specifically commanded to do so (rather than providing a list of those that are currently in use), and it does not allow you to edit those values.
Visual/Graphic Debugger Comparison
CLI-only debuggers are largely a thing of the past. Modern debuggers are GUI-based, and typically either part of an Integrated Development Environment (IDE), or an editing system with IDE capabilities. These include:
- PyCharm, which is a Python-Specific IDE developed by JetBrains.
- Visual Studio, which is developed by Microsoft and comes in two basic flavors:
- Visual Studio 2019, a full-featured, multi-language IDE that runs on Windows and macOS, and
- Visual Studio Code (vscode), a lightweight, multi-language IDE/editor that runs on Windows, macOS and Linux.
- Komodo, which is a full-featured, multi-language IDE developed by ActiveState. It runs on Windows, macOS, and Linux, and is designed for mixed-language environments.
Before we look at the differences between these debugging environments, here’s a quick rundown of the basic features that they have in common:
Debugger Commonalities: General Operation
- They all work with a range of common Python interpreters.
- They all include built-in code editors and an extensive set of tools for managing development projects.
- While they are all designed to work with full development projects, they will run and debug individual code files not associated with a project.
- They all support a variety of plug-ins and extensions for adding functionality, and customizing the user interface.
- They all include professional and free community versions.
Debugger Commonalities: Debugging
- They all feature debugging commands (including those found in pdb, or the equivalent) are available through the GUI.
- They all display information about execution, output, and debugging in multiple windows, making it easier to find and identify specific types of debugger output.
- They all provide debugger output at breakpoints that include an extensive list of variables with data types and values.
- They all allow variable values to be manually set during pauses in execution/debugging.
- They all allow individual variables to be added to a watch list, with watch output in a separate window.
Debugger Showdown
While PyCharm, Visual Studio, vscode and Komodo all share a number of features, they also have a number of key differences. Where do they shine, and where are they not so shiny?
Debugger Showdown: Basic Debugging
We’ll start with some basic ease-of-use issues. Let’s say we just want to open a Python file and debug it. First, how do we open the file?
Running on Windows, both Komodo and vscode use the standard Windows Open File interface. PyCharm uses a nonstandard interface which, while it is hardly difficult to use, does take a bit of getting used to. Visual Studio 2019, on the other hand, starts out with a repository/project/folder-oriented Getting Started screen. After you make a selection, however, it shifts to the standard Windows Open File interface.
After you select a file, each of the IDEs opens it in the editor window without any additional prompts. What do you have to do to debug it?
All four IDEs have Debug menus with a reasonably good range of options (in PyCharm, the Debug menu is named “Run”). After you select the Debug option (“Go/Continue” in Komodo), both versions of Visual Studio simply run the debugger, while Komodo and PyCharm prompt you with dialog boxes asking you to set debugging options.
if you select the defaults in Komodo, the debugger runs without any further prompts. PyCharm, on the other hand, requires you to select an interpreter for the project (if one is not already set as part of the project environment) using the Edit menu’s Settings dialog box in a process that is far from intuitive. (See below for more on interpreter selection.)
Debugger Showdown: Setting a Breakpoint
Setting a breakpoint is simple in Komodo – you click on the line number (or just to the left of it), and the standard red breakpoint symbol appears. You can manage the breakpoint and set options for it using the right-click context menu’s Debug submenu.
In PyCharm and both flavors of Visual Studio, the process is similar, but with some ease-of-use and functional differences. For example, PyCharm and vscode are both rather picky about just where you should click (next to the line number, but not on it), and both flavors of Visual Studio have rather awkward interfaces (and somewhat limited options) for editing breakpoints.
Debugger Showdown: Language Detection and Interpreter Selection
You can’t debug even the simplest line of code unless you know what language it’s written in, and which interpreter or compiler it requires. The IDE/debuggers that we’re looking at today represent very different approaches to the closely-related processes of language detection and interpreter selection.
With PyCharm, the problem of language selection is more or less trivial, since it’s a Python-only IDE. As we indicated above, however, it does not automatically look for or accept a system default for the Python interpreter. Rather, you need to manually set the interpreter on a project-by-project basis.
Both versions of Visual Studio, on the other hand, follow the standard Microsoft practice of identifying file types (and in this case, their associated programming languages) by extension. They accept default interpreters based on the system’s environment and path settings. You can change interpreters, but for both versions of Visual Studio the commands for doing this are not easy to find, and the process is somewhat less than self-explanatory.
Komodo takes a more sophisticated (and more flexible) approach to language detection. It uses both extensions and analysis of file content to determine language, and is capable of detecting multiple languages in a single file. In addition, you can manually assign a language to each file individually using a menu on the top bar of the editor window. For Python, there are separate options for Python 2 (“Python”) and Python 3 (“Python3”).
Like Visual Studio, Komodo assigns interpreters (separately for “Python” and “Python3”) based on the system’s environment settings. Unlike Visual Studio, however, manually assigning interpreters (under “Languages” in the Edit menu’s Preferences dialog box) turns out to be a simple and reasonably intuitive task.
Debugger Showdown: Mixed-Language Development
Many, if not most contemporary large software development projects are not single-language. Unlike typical development projects of the past (including the DOS and Windows desktop eras), they are much less likely to be constrained by the need to fit within the scope of a single operating system or compiler. The choice of language can depend on the task (database access, manipulating large text files, graphic display, etc.), the operating environment (i.e., a browser window, virtualized backend Linux, or a Windows desktop), compatibility with existing code, or a variety of other factors.
As stated previously, PyCharm isn’t designed to address multi-language issues. Visual Studio 2019 and vscode are equipped to handle multiple languages, but their relatively basic and inflexible methods of identifying languages reflect the built-in limitations of their desktop-era legacy.
Komodo, on the other hand, is designed specifically for today’s large, multi-language projects. It is designed to handle projects that include frequent inline language changes within individual files, and that require distinctions between different versions of the same language.
Python Debugger: Which Is Best?
Komodo, both as an overall multi-language IDE as well as a Python development and debugging environment, is built on the belief that in a world where infrastructure itself is virtualized and can be tailored to the application’s requirements (rather than the other way around), you should not be constrained by the development environment.
For real-world Python development in today’s multi-language, multi-platform environment, Komodo is not just the best choice in terms of overall design and features, it’s simply the most practical choice. | https://sweetcode.io/python-debugger-showdown/ | CC-MAIN-2021-21 | refinedweb | 1,628 | 50.97 |
Why build a Home Truck Simulator?
Because we can (thanks to Vos Truck Parts Hedel NL)!
Feel free to ask "anything"!
The Scrapyard and Arduino make a great combination!
To make the experience fit your profile, pick a username and tell us what interests you.
We found and based on your interests.
Why build a Home Truck Simulator?
Because we can (thanks to Vos Truck Parts Hedel NL)!
Feel free to ask "anything"!
Use this code to connect a Toggle Flip Switch to an Arduin Pro Micro or Leonardo.
The pin to connect is Digital PIN 8 and GND
ON will output "a"
OFF will output "b"
Change if you like!
#include <Keyboard.h> const byte switchPin = 8; byte oldSwitchState = HIGH; // assume switch open because of pull-up resistor const unsigned long debounceTime = 10; // milliseconds void setup () { Serial.begin (9600); pinMode (8, INPUT_PULLUP); } // end of setup void loop () { Keyboard.begin(); // see if switch is open or closed byte switchState = digitalRead (switchPin); // has it changed since last time? if (switchState != oldSwitchState) { oldSwitchState = switchState; // remember for next time delay (debounceTime); // debounce if (switchState == LOW) { Serial.println ("Switch closed."); Keyboard.press('a'); delay(100); Keyboard.releaseAll(); } // end if switchState is LOW else { Serial.println ("Switch opened."); Keyboard.press('b'); delay(100); Keyboard.releaseAll(); } // end if switchState is HIGH } // end of state change // other code here ... } // end of loop
Hi folks!
Today I show you my Scania 4-Series Opticruise working in ETS2. In fact, it will work on any Simulator due to the use of an Arduino Leonardo which Windows will recognize as a HID device (keyboard). I programmed Shift up to "Right Shift" and shift down to "Right CTRL" which are the ETS2 default keys for shifting gear!
Have fun!
Arduino Leonardo Code:
#include "Keyboard.h" #define SHIFTUP_PIN 2 #define SHIFTDOWN_PIN 3 // Works on the Leonardo board // Build by Jeroen van der Velden // static void ShiftUp(void) { Keyboard.press(KEY_RIGHT_SHIFT); } static void ShiftDown(void) { Keyboard.press(KEY_RIGHT_CTRL); } void setup(void) { Keyboard.begin(); // Set pin to input pinMode(SHIFTUP_PIN, INPUT); // Enable pullup resistor digitalWrite(SHIFTUP_PIN, HIGH); // Set pin to input pinMode(SHIFTDOWN_PIN, INPUT); // Enable pullup resistor digitalWrite(SHIFTDOWN_PIN, HIGH); } void loop(void) { static uint8_t shiftUpStateLast = 0; static uint8_t shiftDownStateLast = 0; uint8_t shiftState; shiftState = digitalRead(SHIFTUP_PIN); if (shiftState != shiftUpStateLast) { shiftUpStateLast = shiftState; if (shiftState == 0) { ShiftUp(); delay(100); Keyboard.releaseAll(); } } shiftState = digitalRead(SHIFTDOWN_PIN); if (shiftState != shiftDownStateLast) { shiftDownStateLast = shiftState; if (shiftState == 0) { ShiftDown(); delay(100); Keyboard.releaseAll(); } } delay(50); }
My very first test with our new PCB for original 4-Series Clusters.
This film shows how the board below works:
Below is the final result of the PCB on top of the Nucleo. If you are interested in the PCB, please contact me. I do have some spare boards.
Credits for Arcannae who developed the Nucleo integration and code. Check his YouTube for more info:
Hi all,
We got the Gerber files for our PCB and a first sample has been made:
We are going to use a "Nucleo F446RE" board along with this print to get our cluster up and running.
Keep following!
We have a Cluster! Keep following!!
Hi folks!
Now Mr. Blom has made some beautiful pieces for our Scania Steering Wheel we have started working on the Steering Again.
If you have read my old Steer Part 1 you have noticed that we started all over. We warn`t satisfied with our results so I have spoken to our new sponsor and he made me a disc that fits over our Logitech Drivingforce Pro wheel.
This is the result:
The Steering Shaft in the picture is a BMW Steering Shaft, very lightweight and cheap on Ebay and perfect for our simulator. The disc is quite heavy weight but its perfectly tune-able for our sim and if it causes trouble we will cut some slices pizza out of it.
Mr. Blom is now working on the top part of the steering shaft and a bracket to hold it all into place. Keep following for more updates!
Hi folks,
After a long summer-stop we are back in business and this time we are proud to announce our new sponsor "Blom Eethen". Mr. Blom is helping us with some of the metal parts required to get the steering wheel connected to our USB Racing Wheel. Mr. Blom is very skilled and he has over 45 years of experience and just about all the right tools for any kind of metalwork job !!
If you need some "Custom" metal work for you DIY simulator, he`s the person you should talk to!
Mr. Blom Eethen and his tool shop (pictures and video below):
Feel free to have a look at his website for more information:
Progress with our Pedals!
think they do sell
But eBay SCANIA 4-series parts should work.
Bonjour, Je suis le propriétaire original de "votre" travail concernant la mise en application du tableau de bord avec une carte nucleo. j'aimerai vous dire que déjà la moindres des choses lorsque on utilise le travail de quelqu’un d'autre, on site la source ou la personne qui en est le propriétaire... ça fait toujours plaisir et ça évite certains malentendu...
Ensuite je vois également que vous vendez un travail qui ne vous appartient pas. sachez que je pourrais engager des poursuites judiciaire et demander un dédommagement pour atteinte au droits de propriété intellectuelle. MON travail est a disposition GRATUITE sur ma chaine YouTube et en aucun cas il est autorisé a être utilisée a des fins de revente par tierce personne. Vous voila prévenu.
Cordialement,
Arcannae
Sorry Arcannae, I’m not selling your code. I did sell a few of my PCB’s at cost but no profit was ever made or intended. Anyway I’m no longer selling. Sorry if I disappoint you and thank you for your great work.
Great work! I've been working on a Kenworth Simulator Cockpit, myself for American Truck Simulator, since February, 2016. I've always liked Scanias, too though!
nice!
Very cool simulator, any plans to make one for a regular or may be a sport car? :)
Thanks Roman! Who knows what may be next! Nobody did a Truck and I have seen cars so for now I stick with Trucks ;0
Awesome project
How much did it cost you ? Are all the codes available in your post ? can you make a tutorial on wiring and programming it ? I am thinking of making something similar to your project . I will be starting with Arduino and I am having no idea about its coding please help me with it ?
check my logs! It's all there my friend! Both Instructions and code. If you need specific help, send me a note and I will share my knowledge with you.
thank you very much I will be starting it by end of this March.
is Arduio UNO Rev3 the Arduino UNO R3??
Yes Arduino UNO R3 or UNO Rev3 (its the same). The UNO is only used for the VW Polo Cluster Instrument Panel. I used Arduino Pro Micro and Leonardo R3 for all the Scania parts.
Really good looking project! Keep going!
Is there any way to contact some of developers? I`ve trying to create by myself, but have some problems :)
I love simulator builds, and this one is quite nice!
Thanks Greg!
Become a member to follow this project and never miss any updates
About Us Contact Hackaday.io Give Feedback Terms of Use Privacy Policy Hackaday API
Over here in America, we do not have access to a "Vos Truck Parts." Is there any alternative that we can use? Is there any other way to get the Scania dashboard? Or will this work with any other truck dash? | https://hackaday.io/project/8448-real-scania-truck-home-simulator | CC-MAIN-2020-50 | refinedweb | 1,287 | 74.49 |
guides-page_object
Contents
- Page Object Pattern
- Introducing the Page Object Pattern
- 1. The public methods represent the services that the page offers.
- 2. Try not to expose the internals of the page.
- 3. Methods return other PageObjects
- 4. Assertions should exist only in tests
- 5. Need not represent an entire page
- 6. Actions which produce multiple results should have a test for each result
Introducing the Page Object Pattern
Automated testing of an application through the Graphical User Interface (GUI) is inherently fragile. These tests require regular review and attention during the development cycle. This is known as Interface Sensitivity (“even minor changes to the interface can cause tests to fail”). Utilizing the page-object pattern, alleviates some of the problems stemming from this fragility, allowing us to do automated user acceptance testing (UAT) in a sustainable manner.
The Page Object Pattern comes from the Selenium community and is the best way to turn a flaky and unmaintainable user acceptance test into a stable and useful part of your release process. A page is what’s visible on the screen at a single moment. A user story consists of a user jumping from page to page until they achieve their goal. Thus pages are modeled as objects following these guidelines:
- The public methods represent the services that the page offers.
- Try not to expose the internals of the page.
- Methods return other PageObjects.
- Assertions should exist only in tests
- Objects need not represent the entire page.
- Actions which produce multiple results should have a test for each result
Lets take the page objects of the Ubuntu Clock App as an example, with some simplifications. This application is written in QML and Javascript using the Ubuntu SDK.
1. The public methods represent the services that the page offers.
This application has a stopwatch page that lets users measure elapsed time. It offers services to start, stop and reset the watch, so we start by defining the stop watch page object as follows:
class Stopwatch(object): def start(self): raise NotImplementedError() def stop(self): raise NotImplementedError() def reset(self): raise NotImplementedError()
2. Try not to expose the internals of the page.
The internals of the page are more likely to change than the services it offers. A stopwatch will keep the same three services we defined above even if the whole design changes. In this case, we reset the stop watch by clicking a button on the bottom-left of the window, but we hide that as an implementation detail behind the public methods. In Python, we can indicate that a method is for internal use only by adding a single leading underscore to its name. So, lets implement the reset_stopwatch method:
def reset(self): self._click_reset_button() def _click_reset_button(self): reset_button = self.wait_select_single( 'ImageButton', objectName='resetButton') self.pointing_device.click_object(reset_button)
Now if the designers go crazy and decide that it’s better to reset the stop watch in a different way, we will have to make the change only in one place to keep all the tests working. Remember that this type of tests has Interface Sensitivity, that’s unavoidable; but we can reduce the impact of interface changes with proper encapsulation and turn these tests into a useful way to verify that a change in the GUI didn’t introduce any regressions.
3. Methods return other PageObjects
An UAT checks a user story. It will involve the journey of the user through the system, so he will move from one page to another. Lets take a look at how a journey to reset the stop watch will look like:
stopwatch = clock_page.open_stopwatch() stopwatch.start() stopwatch.reset()
In our sample application, the first page that the user will encounter is the Clock. One of the things the user can do from this page is to open the stopwatch page, so we model that as a service that the Clock page provides. Then return the new page object that will be visible to the user after completing that step.
class Clock(object): ... def open_stopwatch(self): self._switch_to_tab('StopwatchTab') return self.wait_select_single(Stopwatch)
Now the return value of open_stopwatch will make available to the caller all the available services that the stopwatch exposes to the user. Thus it can be chained as a user journey from one page to the other.
4. Assertions should exist only in tests
A well written UAT consists of a sequence of steps or user actions and ends with one single assertion that verifies that the user achieved its goal. The page objects are the helpers for the user actions part of the test, so it’s better to leave the check for success out of them. With that in mind, a test for the reset of the stopwatch would look like this:
5. Need not represent an entire page
The objects we are modeling here can just represent a part of the page. Then we build the entire page that the user is seeing by composition of page parts. This way we can reuse test code for parts of the GUI that are reused in the application or between different applications. As an example, take the _switch_to_tab(‘StopwatchTab’) method that we are using to open the stopwatch page. The Clock application is using the Header component provided by the Ubuntu SDK, as all the other Ubuntu applications are doing too. So, the Ubuntu SDK also provides helpers to make it easier the user acceptance testing of the applications, and you will find an object like this:
class Header(object): def switch_to_tab(tab_object_name): """Open a tab. :parameter tab_object_name: The QML objectName property of the tab. :return: The newly opened tab. :raise ToolkitException: If there is no tab with that object name. """ ...
This object just represents the header of the page, and inside the object we define the services that the header provides to the users. If you dig into the full implementation of the Clock test class you will find that in order to open the stopwatch page we end up calling Header methods.
6. Actions which produce multiple results should have a test for each result
According to the guideline 3. Methods return other PageObjects, we are returning page objects every time that a user action opens the option for new actions to execute. Sometimes the same action has different results depending on the context or the values used for the action. For example, the Clock app has an Alarm page. In this page you can add new alarms, but if you try to add an alarm for sometime in the past, it will result in an error. So, we will have two different tests that will look something like this:.')
Take a look at the methods add_alarm and add_alarm_with_error. The first one returns the Alarm page again, where the user can continue his journey or finish the test checking the result. The second one returns the error dialog that’s expected when you try to add an alarm with the wrong values. | https://docs.ubuntu.com/phone/en/apps/api-autopilot-development/guides-page_object.html | CC-MAIN-2018-47 | refinedweb | 1,165 | 62.27 |
Hey, all. In this article, we will be focusing on the scanf() function in C in detail.
Table of Contents
Working of the scanf() function in C
Be it any programming language, we always need user input, in order to make it work with a dynamic set of values.
This is where the
scanf() function in C comes into picture.
The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.
Having understood the working of scanf() function, let us now focus on the structure of the same.
Syntax of scanf() function
Let us have a look at the below syntax:
scanf("%format-specifier", &variable)
format_specifier: It decides the type of value to be taken as input from the standard input device. Example: “%d” for integer, “%c” for character values, etc.
variable: The value taken as input from the user gets stored at the location pointed by the variable.
The scanf() function accepts the value of the specified type through the help of the format specifiers and stores the value at the location pointed by the variable passed as a parameter to it.
Let us now implement the scanf() function through the below examples.
Examples of scanf() function
In the below example, we have accepted the integer value as input and have displayed the value.
#include <stdio.h> int main() { int x; scanf("%d", &x); printf("The value of x is: %d", x); return 0; }
Output:
20 The value of x is: 20
Now, we have accepted the string values as input and displayed the same.
#include <stdio.h> int main () { char city[20]; printf("Enter name of the city: "); scanf("%s", city); printf("The city value is: %s", city); return(0); }
Output:
Enter name of the city: Pune The city value is: Pune
Conclusion
By this, we have come to the end of this topic. The scanf() function can be used to accept values of different data types, thus making it a user-friendly function.
Feel free to comment below in case, you come across any question.
For more such posts related to C programming, do visit C programming with us.
Till then, Happy Learning!! | https://www.journaldev.com/43350/scanf-function-c | CC-MAIN-2021-04 | refinedweb | 376 | 59.43 |
PRCTL(2) Linux Programmer's Manual PRCTL(2)
prctl - operations on a process or thread
#include <sys/prctl.h> int prctl(int option, unsigned long arg2, unsigned long arg3, unsigned long arg4, unsigned long arg5);
pr_SYSCALL_USER_DISPATCH (since Linux 5.11, x86 only) Configure the Syscall User Dispatch mechanism for the calling thread. This mechanism allows an application to selectively intercept system calls so that they can be handled within the application itself. Interception takes the form of a thread-directed SIGSYS signal that is delivered to the thread when it makes a system call. If intercepted, the system call is not executed by the kernel. To enable this mechanism, arg2 should be set to PR_SYS_DISPATCH_ON. Once enabled, further system calls will be selectively intercepted, depending on a control variable provided by user space. In this case, arg3 and arg4 respectively identify the offset and length of a single contiguous memory region in the process address space from where system calls are always allowed to be executed, regardless of the control variable. (Typically, this area would include the area of memory containing the C library.) arg5 points to a char-sized variable that is a fast switch to allow/block system call execution without the overhead of doing another system call to re-configure Syscall User Dispatch. This control variable can either be set to SYSCALL_DISPATCH_FILTER_BLOCK to block system calls from executing or to SYSCALL_DISPATCH_FILTER_ALLOW to temporarily allow them to be executed. This value is checked by the kernel on every system call entry, and any unexpected value will raise an uncatchable SIGSYS at that time, killing the application. When a system call is intercepted, the kernel sends a thread-directed SIGSYS signal to the triggering thread. Various fields will be set in the siginfo_t structure (see sigaction(2)) associated with the signal: * si_signo will contain SIGSYS. * si_call_addr will show the address of the system call instruction. * si_syscall and si_arch will indicate which system call was attempted. * si_code will contain SYS_USER_DISPATCH. * si_errno will be set to 0. The program counter will be as though the system call happened (i.e., the program counter will not point to the system call instruction). When the signal handler returns to the kernel, the system call completes immediately and returns to the calling thread, without actually being executed. If necessary (i.e., when emulating the system call on user space.), the signal handler should set the system call return value to a sane value, by modifying the register context stored in the ucontext argument of the signal handler. See sigaction(2), sigreturn(2), and getcontext(3) for more information. If arg2 is set to PR_SYS_DISPATCH_OFF, Syscall User Dispatch is disabled for that thread. the remaining arguments must be set to 0. The setting is not preserved across fork(2), clone(2), or execve(2). For more information, see the kernel source file Documentation/admin-guide/syscall-user-dispatch.rst: • brk(2), mmap(2), shmat(2), shmdt(2), and the new_address argument of mremap(2). (Prior to Linux 5.6 these accepted tagged addresses, but the behaviour may not be what you expect. Don't rely on it.) • to indicate the error.FAULT option is PR_SET_SYSCALL_USER_DISPATCH and arg5 has an invalid address. EINVAL The value of option is not recognized,_SYSCALL_USER_DISPATCH and one of the following is true: * arg2 is PR_SYS_DISPATCH_OFF and the remaining arguments are not 0; * arg2 is PR_SYS_DISPATCH_ON and the memory range specified is outside the address space of the process. * arg2 is invalid...
signal(2), core(5)
This page is part of release 5.11 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2021-03-22 PRCTL(2)
Pages that refer to this page: capsh(1), setpriv(1), systemd-nspawn), credentials(7), environ(7), pid_namespaces(7), time(7), mount.fuse3(8) | https://man7.org/linux/man-pages/man2/prctl.2.html | CC-MAIN-2021-17 | refinedweb | 648 | 57.06 |
Let's talk about... architecture?
I'm going to cover an important, but potentially misunderstood topic: The architecture that you use for your web app, and specifically, how your architectural decisions come into play when you're building a progressive web app.
"Architecture" can sound vague, and it may not be immediately clear why this matters. Well, one way to think about architecture is to ask yourself the following questions: When a user visits a page on my site, what HTML is loaded? And then, what's loaded when they visit another page?
The answers to those questions are not always straightforward, and once you start thinking about progressive web apps, they can get even more complicated. So my goal is to walk you through one possible architecture that I found effective. Throughout this article, I'll label the decisions that I made as being "my approach" to building a progressive web app.
You're free to use my approach when building your own PWA, but at the same time, there are always other valid alternatives. My hope is that seeing how all the pieces fit together will inspire you, and that you will feel empowered to customize this to suit your needs.
Stack Overflow PWA
To accompany this article I built a Stack Overflow PWA. I spend a lot of time reading and contributing to Stack Overflow, and I wanted to build a web app that would make it easy to browse frequently asked questions for a given topic. It's built on top of the public Stack Exchange API. It's open source, and you can learn more by visiting the GitHub project.
Multi-page Apps (MPAs)
Before I get into specifics, let's define some terms and explain pieces of underlying technology. First, I'm going to be covering what I like to call "Multi Page Apps", or "MPAs".
MPA is a fancy name for the traditional architecture used since this beginning of the web. Each time a user navigates to a new URL, the browser progressively renders HTML specific to that page. There's no attempt to preserve the page's state or the content in between navigations. Each time you visit a new page, you're starting fresh.
This is in contrast to the single-page app (SPA) model for building web apps, in which the browser runs JavaScript code to update the existing page when the user visits a new section. Both SPAs and MPAs are equally valid models to use, but for this post, I wanted to explore PWA concepts within the context of a multi-page app.
Reliably fast
You've heard me (and countless others) use the phrase "progressive web app", or PWA. You might already be familiar with some of the background material, elsewhere on this site.
You can think of a PWA as a web app that provides a first-class user experience, and that truly earns a place on the user's home screen. The acronym "FIRE", standing for Fast, Integrated, Reliable, and Engaging, sums up all the attributes to think about when building a PWA.
In this article, I'm going to focus on a subset of those attributes: Fast and Reliable.
Fast: While "fast" means different things in different contexts, I'm going to cover the speed benefits of loading as little as possible from the network.
Reliable: But raw speed isn't enough. In order to feel like a PWA, your web app should be reliable. It needs to be resilient enough to always load something, even if it's just a customized error page, regardless of the state of the network.
Reliably fast: And finally, I'm going to rephrase the PWA definition slightly and look at what it means to build something that's reliably fast. It's not good enough to be fast and reliable only when you're on a low-latency network. Being reliably fast means that your web app's speed is consistent, regardless of the underlying network conditions.
Enabling Technologies: Service Workers + Cache Storage API
PWAs introduce a high bar for speed and resilience. Fortunately, the web platform offers some building blocks to make that type of performance a reality. I'm referring to service workers and the Cache Storage API.
You can build a service worker that listens for incoming requests, passing some on to the network, and storing a copy of the response for future use, via the Cache Storage API.
![ A service worker using the Cache Storage API to save a copy of a
network response.]()
The next time the web app makes the same request, its service worker can check its caches and just return the previously cached response.
![ A service worker using the Cache Storage API to respond, bypassing
the network.]()
Avoiding the network whenever possible is a crucial part of offering reliably fast performance.
"Isomorphic" JavaScript
One more concept that I want to cover is what's sometimes referred to as "isomorphic", or "universal" JavaScript. Simply put, it's the idea that the same JavaScript code can be shared between different runtime environments. When I built my PWA, I wanted to share JavaScript code between my back-end server, and the service worker.
There are lots of valid approaches to sharing code in this way, but my
approach was to use ES
modules as
the definitive source code. I then transpiled and bundled those modules for the
server and the service worker using a combination of
Babel and Rollup. In my project,
files with an
.mjs file extension is code that lives in an ES module.
The server
Keeping those concepts and terminology in mind, let's dive into how I actually built my Stack Overflow PWA. I'm going to start by covering our backend server, and explain how that fits into the overall architecture.
I was looking for a combination of a dynamic backend along with static hosting, and my approach was to use the Firebase platform.
Firebase Cloud Functions will automatically spin up a Node-based environment when there's an incoming request, and integrate with the popular Express HTTP framework, which I was already familiar with. It also offers out-of-the-box hosting for all of my site's static resources. Let's take a look at how the server handles requests.
When a browser makes a navigation request against our server, it goes through the following flow:
The server routes the request based on the URL, and uses templating logic to create a complete HTML document. I use a combination of data from the Stack Exchange API, as well as partial HTML fragments that the server stores locally. Once our service worker knows how to respond, it can start streaming HTML back to our web app.
There are two pieces of this picture worth exploring in more detail: routing, and templating.
Routing
When it comes to routing, my approach was to use the Express framework's native routing syntax. It's flexible enough to match simple URL prefixes, as well as URLs that include parameters as part of the path. Here, I create a mapping between route names the underlying Express pattern to match against.
const routes = new Map([ ['about', '/about'], ['questions', '/questions/:questionId'], ['index', '/'], ]); export default routes;
I can then reference this mapping directly from the server's code. When there's a match for a given Express pattern, the appropriate handler responds with templating logic specific to the matching route.
import routes from './lib/routes.mjs'; app.get(routes.get('index'), async (req, res) => { // Templating logic. });
Server-side templating
And what does that templating logic look like? Well, I went with an approach that pieced together partial HTML fragments in sequence, one after another. This model lends itself well to streaming.
The server sends back some initial HTML boilerplate immediately, and the browser is able to render that partial page right away. As the server pieces together the rest of the data sources, it streams them to the browser until the document is complete.
To see what I mean, take a look at the Express code for one of our routes:
app.get(routes.get('index'), async (req, res) => { res.write(headPartial + navbarPartial); const tag = req.query.tag || DEFAULT_TAG; const data = await requestData(...); res.write(templates.index(tag, data.items)); res.write(footPartial); res.end(); });
By using the
response object's
write()
method,
and referencing locally stored partial templates, I'm able to start the
response stream immediately,
without blocking any external data source. The browser takes this initial
HTML and renders a meaningful interface and loading message right away.
The next portion of our page uses data from the Stack Exchange API. Getting that data means that our server needs to make a network request. The web app can't render anything else until it gets a response back and process it, but at least users aren't staring at a blank screen while they wait.
Once the web app's received the response from the Stack Exchange API, it calls a custom templating function to translate the data from the API into its corresponding HTML.
Templating language
Templating can be a surprisingly contentious topic, and what I went with is just one approach among many. You'll want to substitute your own solution, especially if you have legacy ties to an existing templating framework.
What made sense for my use case was to just rely on JavaScript's template literals, with some logic broken out into helper functions. One of the nice things about building an MPA is that you don't have to keep track of state updates and re-render your HTML, so a basic approach that produced static HTML worked for me.
So here's an example of how I'm templating the dynamic HTML portion of my web app's index. As with my routes, the templating logic is stored in an ES module that can be imported into both the server and the service worker.
export function index(tag, items) { const title = `<h3>Top "${escape(tag)}" Questions</h3>`; const form = `<form method="GET">...</form>`; const questionCards = items.map((item) => questionCard({ id: item.question_id, title: item.title, })).join(''); const questions = `<div id="questions">${questionCards}</div>`; return title + form + questions; }
These template functions are pure JavaScript, and it's useful to break out the logic into smaller, helper functions when appropriate. Here, I pass each of the items returned in the API response into one such function, which creates a standard HTML element with all of the appropriate attributes set.
function questionCard({id, title}) { return `<a class="card" href="/questions/${id}" data-${title}</a>`; }
Of particular note is a data
attribute
that I add to each link,
data-cache-url, set to the Stack Exchange API URL
that I need in order to display the corresponding question. Keep that in
mind. I'll revisit it later.
Jumping back to my route handler, once templating is complete, I stream the final portion of my page's HTML to the browser, and end the stream. This is the cue to the browser that the progressive rendering is complete.
app.get(routes.get('index'), async (req, res) => { res.write(headPartial + navbarPartial); const tag = req.query.tag || DEFAULT_TAG; const data = await requestData(...); res.write(templates.index(tag, data.items)); res.write(footPartial); res.end(); });
So that's a brief tour of my server setup. Users who visit my web app for the first time will always get a response from the server, but when a visitor returns to my web app, my service worker will start responding. Let's dive in there.
The service worker
![ An overview of generating a navigation response, in the service
worker.]()
This diagram should look familiar—many of the same pieces I've previously covered are here in a slightly different arrangement. Let's walk through the request flow, taking the service worker into account.
Our service worker handles an incoming navigation request for a given URL, and just like my server did, it uses a combination of routing and templating logic to figure out how to respond.
The approach is the same as before, but with different low-level primitives,
like
fetch() and the Cache
Storage API. I use
those data sources to construct the HTML response, which the service worker
passes back to the web app.
Workbox
Rather than starting from scratch with low-level primitives, I'm going to build my service worker on top of a set of high-level libraries called Workbox. It provides a solid foundation for any service worker's caching, routing, and response generation logic.
Routing
Just as with my server-side code, my service worker needs to know how to match an incoming request with the appropriate response logic.
My approach was to
translate
each Express route into a corresponding regular
expression,
making use of a helpful library called
regexparam. Once that translation is
performed, I can take advantage of Workbox's built-in support for regular
expression
routing.
After importing the module that has the regular expressions, I register each regular expression with Workbox's router. Inside each route I'm able to provide custom templating logic to generate a response. Templating in the service worker is a bit more involved than it was in my backend server, but Workbox helps with a lot of the heavy lifting.
import regExpRoutes from './regexp-routes.mjs'; workbox.routing.registerRoute(regExpRoutes.get('index'), // Templating logic. );
Static asset caching
One key part of the templating story is making sure that my partial HTML templates are locally available via the Cache Storage API, and are kept up to date when I deploy changes to the web app. Cache maintenance can be error prone when done by hand, so I turn to Workbox to handle precaching as part of my build process.
I tell Workbox which URLs to precache using a configuration file, pointing to the directory that contains all of my local assets along with a set of patterns to match. This file is automatically read by the Workbox's CLI, which is run each time I rebuild the site.
module.exports = { globDirectory: 'build', globPatterns: ['**/*.{html,js,svg}'], // Other options... };
Workbox takes a snapshot of each file's contents, and automatically injects that
list of URLs and revisions into my final service worker file. Workbox now has
everything it needs to make the precached files always available, and kept up to
date. The result is a
service-worker.js
file that contains something
similar to the following:
workbox.precaching.precacheAndRoute([ { url: 'partials/about.html', revision: '518747aad9d7e' }, { url: 'partials/foot.html', revision: '69bf746a9ecc6' }, // etc. ]);
For folks who use a more complex build process, Workbox has both a
webpack
plugin and a generic node
module, in addition to its command
line interface.
Streaming
Next, I want the service worker to stream that precached partial HTML back to the web app immediately. This is a crucial part of being "reliably fast"—I always get something meaningful on the screen right away. Fortunately, using the Streams API within our service worker makes that possible.
Now, you might have heard about the Streams API before. My colleague Jake Archibald has been singing its praises for years. He made the bold prediction that 2016 would be the year of web streams. And the Streams API is just as awesome today as it was two years ago, but with a crucial difference.
While only Chrome supported Streams back then, the Streams API is more widely supported now. The overall story is positive, and with appropriate fallback code, there's nothing stopping you from using streams in your service worker today.
Well... there might be one thing stopping you, and that's wrapping your head around how the Streams API actually works. It exposes a very powerful set of primitives, and developers who are comfortable using it can create complex data flows, like the following:
const stream = new ReadableStream({ pull(controller) { return sources[0].then((r) => r.read()) .then((result) => { if (result.done) { sources.shift(); if (sources.length === 0) return controller.close(); return this.pull(controller); } else { controller.enqueue(result.value); } }) } });
But understanding the full implications of this code might not be for everyone. Rather than parse through this logic, let's talk about my approach to service worker streaming.
I'm using a brand new, high-level wrapper,
workbox-streams.
With it, I can pass it in a mix of streaming sources, both from caches and
runtime data that might come from the network. Workbox takes care of
coordinating the individual sources and stitching them together into a single,
streaming response.
Additionally, Workbox automatically detects whether the Streams API is supported, and when it's not, it creates an equivalent, non-streaming response. This means that you don't have to worry about writing fallbacks, as streams inch closer to 100% browser support.
Runtime caching
Let's check out how my service worker deals with runtime data, from the Stack Exchange API. I'm making use of Workbox's built-in support for a stale-while-revalidate caching strategy, along with expiration to ensure that the web app's storage doesn't grow unbounded.
I set up two strategies in Workbox to handle the different sources that will make up the streaming response. In a few function calls and configuration, Workbox lets us do what would otherwise take hundreds of lines of handwritten code.
const cacheStrategy = workbox.strategies.cacheFirst({ cacheName: workbox.core.cacheNames.precache, }); const apiStrategy = workbox.strategies.staleWhileRevalidate({ cacheName: API_CACHE_NAME, plugins: [ new workbox.expiration.Plugin({maxEntries: 50}), ], });
The first strategy reads data that's been precached, like our partial HTML templates.
The other strategy implements the stale-while-revalidate caching logic, along with least-recently-used cache expiration once we reach 50 entries.
Now that I have those strategies in place, all that's left is to tell Workbox how to use them to construct a complete, streaming response. I pass in an array of sources as functions, and each of those functions will be executed immediately. Workbox takes the result from each source and streams it to the web app, in sequence, only delaying if the next function in the array hasn't completed yet.
workbox.streams.strategy([ () => cacheStrategy.makeRequest({request: '/head.html'}), () => cacheStrategy.makeRequest({request: '/navbar.html'}), async ({event, url}) => { const tag = url.searchParams.get('tag') || DEFAULT_TAG; const listResponse = await apiStrategy.makeRequest(...); const data = await listResponse.json(); return templates.index(tag, data.items); }, () => cacheStrategy.makeRequest({request: '/foot.html'}), ]);
The first two sources are precached partial templates read directly from the Cache Storage API, so they'll always be available immediately. This ensures that our service worker implementation will be reliably fast in responding to requests, just like my server-side code.
Our next source function fetches data from the Stack Exchange API, and processes the response into the HTML that the web app expects.
The stale-while-revalidate strategy means that if I have a previously cached response for this API call, I'll be able to stream it to the page immediately, while updating the cache entry "in the background" for the next time it's requested.
Finally, I stream a cached copy of my footer and close the final HTML tags, to complete the response.
Sharing code keeps things in sync
You'll notice that certain bits of the service worker code look familiar. The partial HTML and templating logic used by my service worker is identical to what my server-side handler uses. This code sharing ensures that users get a consistent experience, whether they're visiting my web app for the first time or returning to a page rendered by the service worker. That's the beauty of isomorphic JavaScript.
Dynamic, progressive enhancements
I've walked through both the server and service worker for my PWA, but there's one last bit of logic to cover: there's a small amount of JavaScript that runs on each of my pages, after they're fully streamed in.
This code progressively enhances the user experience, but isn't crucial—the web app will still work if it's not run.
Page metadata
My app uses client-side JavaScipt for to update a page's metadata based on the API response. Because I use the same initial bit of cached HTML for each page, the web app ends up with generic tags in my document's head. But through coordination between my templating and client-side code, I can update the window's title using page-specific metadata.
As part of the templating code, my approach is to include a script tag containing the properly escaped string.
const metadataScript = `<script> self._title = '${escape(item.title)}'; </script>`;
Then, once my page has loaded, I read that string and update the document title.
if (self._title) { document.title = unescape(self._title); }
If there are other pieces of page-specific metadata you want to update in your own web app, you can follow the same approach.
Offline UX
The other progressive enhancement I've added is used to bring attention to our offline capabilities. I've built a reliable PWA, and I want users to know that when they're offline, they can still load previously visited pages.
First, I use the Cache Storage API to get a list of all the previously cached API requests, and I translate that into a list of URLs.
Remember those special data attributes I talked about, each containing the URL for the API request needed to display a question? I can cross-reference those data attributes against the list of cached URLs, and create an array of all the question links that don't match.
When the browser enters an offline state, I loop through the list of uncached links, and dim out the ones that won't work. Keep in mind that this is just a visual hint to the user about what they should expect from those pages—I'm not actually disabling the links, or preventing the user from navigating.
const apiCache = await caches.open(API_CACHE_NAME); const cachedRequests = await apiCache.keys(); const cachedUrls = cachedRequests.map((request) => request.url); const cards = document.querySelectorAll('.card'); const uncachedCards = [...cards].filter((card) => { return !cachedUrls.includes(card.dataset.cacheUrl); }); const offlineHandler = () => { for (const uncachedCard of uncachedCards) { uncachedCard.style.opacity = '0.3'; } }; const onlineHandler = () => { for (const uncachedCard of uncachedCards) { uncachedCard.style.opacity = '1.0'; } }; window.addEventListener('online', onlineHandler); window.addEventListener('offline', offlineHandler);
Common pitfalls
I've now gone through a tour of my approach to building a multi-page PWA. There are many factors that you'll have to consider when coming up with your own approach, and you may end up making different choices than I did. That flexibility is one of the great things about building for the web.
There are a few common pitfalls that you may encounter when making your own architectural decisions, and I want to save you some pain.
Don't cache full HTML
I recommend against storing complete HTML documents in your cache. For one thing, it's a waste of space. If your web app uses the same basic HTML structure for each of its pages, you'll end up storing copies of the same markup again and again.
More importantly, if you deploy a change to your site's shared HTML structure, every one of those previously cached pages is still stuck with your old layout. Imagine the frustration of a returning visitor seeing a mix of old and new pages.
Server / service worker drift
The other pitfall to avoid involves your server and service worker getting out of sync. My approach* was to use isomorphic JavaScript, so that the same code was run in both places. Depending on your existing server architecture, that's not always possible.
Whatever architectural decisions you make, you should have some strategy for running the equivalent routing and templating code in your server and your service worker.
Worst case scenarios
Inconsistent layout / design
What happens when you ignore those pitfalls? Well, all sorts of failures are possible, but the worst case scenario is that a returning user visits a cached page with a very stale layout—perhaps one with out of date header text, or that uses CSS class names that are no longer valid.
Worst case scenario: Broken routing
Alternatively, a user might come across a URL that's handled by your server, but not your service worker. An site full of zombie layouts and dead ends is not a reliable PWA.
Tips for success
But you're not in this alone! The following tips can help you avoid those pitfalls:
Use templating and routing libraries that have multi-language implementations
Try to use templating and routing libraries that have JavaScript implementations. Now, I know that not every developer out there has the luxury of migrating off your current web server and templating language.
But a number of popular templating and routing frameworks have implementations in multiple languages. If you can find one that works with JavaScript as well as your current server's language, you're one step closer to keeping your service worker and server in sync.
Prefer sequential, rather than nested, templates
Next, I recommend using a series of sequential templates that can be streamed in one after another. It's okay if later portions of your page use more complicated templating logic, as long as you can stream in the initial part of your HTML as quickly as possible.
Cache both static and dynamic content in your service worker
For best performance, you should precache all of your site's critical static resources. You should also set up runtime caching logic to handle dynamic content, like API requests. Using Workbox means that you can build on top of well-tested, production-ready strategies instead of implementing it all from scratch.
Only block on the network when absolutely necessary
And related to that, you should only block on the network when it's not possible to stream a response from the cache. Displaying a cached API response immediately can often lead to a better user experience than waiting for fresh data.
Resources
RSS or Atom feed and get the latest updates in your favorite feed reader!Subscribe to our | https://developers.google.cn/web/updates/2018/05/beyond-spa?hl=id | CC-MAIN-2020-34 | refinedweb | 4,373 | 62.68 |
Episode #77: You Don't Have To Be a Workaholic To Win
Published Sat, May 12, 2018, recorded Sat, May 12, 2018.
Sponsored by Datadog: pythonbytes.fm/datadog
Brian #1: Why Senior Devs Write Dumb Code
- “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” - Kent Beck
- Code that is clean, straightforward, obvious, and easy to read actually takes practice to achieve.
- Follow principles like YAGNI, Singe Responsibility, DRY, etc.
- Avoid clever one-liners, weird abstractions.
- Esoteric language features.
- Code needs to be readable and easily understood while under time and stress pressure.
Michael #2: GeoAlchemy 2
- GeoAlchemy 2 provides extensions to SQLAlchemy for working with spatial databases.
- GeoAlchemy 2 focuses on PostGIS. Aims to be simpler than its predecessor, GeoAlchemy.
- Using it:
- Connect (e.g. Postgres)
- Declare a Mapping
class Lake(Base): __tablename__ = 'lake' id = Column(Integer, primary_key=True) name = Column(String) geom = Column(Geometry('POLYGON'))
- Create a table (via the engine)
- Create an Instance of the Mapped Class
- Inserts like standard SQLAlchmey
- Spatial Query
from sqlalchemy import func query = session.query(Lake).filter( func.ST_Contains(Lake.geom, 'POINT(4 1)')) query = session.query(Lake.name, Lake.geom.ST_Buffer(2).ST_Area().label('bufferarea'))
Brian #3: QtPyConvert
- An automatic Python Qt binding transpiler to the Qt.py abstraction layer.
- QtPyConvert supports the following bindings out of the box:
- Conversions leave code comments in place, with the help of RedBaron
- Converts to Qt.py
- Minimal Python 2 & 3 shim around all Qt bindings - PySide, PySide2, PyQt4 and PyQt5
Michael #4: You Don't Have To Be a Workaholic To Win: 13 Alternative Ways To Stand Out
- Do we have to kill ourselves to get ahead?
- Don’t busy-brag
- Max Q analogy
- The tips
- Creativity
- Stubbornness
- Curiosity
- Kindness
- Planning
- Improvisation
- Enthusiasm
- Communication
- Presence
- Collaboration
- Willingness
- Patience
- Institutional Knowledge
- RedBaron is a python library to make the process of writing code that modify source code as easy and as simple as possible.
- writing custom refactoring, generic refactoring, tools,
- Used by QtPyConvert to achieve the conversion while leaving code comments in place
- Uses the full syntax tree, FST. Like an AST, but keeps all information, including comments and formatting.
- possible uses:
-
Michael #6: Project Beeware AppStore
- Project BeeWare has just released its first iPhone app made in Python using its Briefcase tool.
- Simple travel app for currency and tip calculations
- Briefcase: A distutils extension to assist in packaging Python projects as standalone applications. Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:
- Mac
- Windows
- Linux
- iPhone/iPad
- Android
- AppleTV
- tvOS
- While there are other Python GUI toolkits aiming to enable Python developers to build and deploy iOS apps, like for instance the very nice Pythonista app, the BeeWare project is a bit different because it aims at cross-platform compatibility and native widgets with a set of different tools, like Briefcase and Toga.
Extras:
- Michael: Extra ssh breach Did you see that?
- PyCon videos already up at | https://pythonbytes.fm/episodes/show/77/you-don-t-have-to-be-a-workaholic-to-win | CC-MAIN-2018-30 | refinedweb | 503 | 54.42 |
> Google > for "per-type function namespaces", which was an idea I sent to the > list a few months ago, for something which I think better solves the > naming issue. Quite a lot of people disagreed with it, but I still > think it's a good idea. (FWIW, I nearly managed to implement this with > Template Haskell, but I couldn't work around the restriction that you > couldn't splice in a TH function declared in the same module.) Andrei, I just skimmed through the "per-type namespace" thread. I'd say besides the ability to do overloading with type classes, I do like what they called ad-hoc polymorphism. And that is by no means the type classes can support. By "ad-hoc", we mean we don't know who the heck will create a function with the same name with whatever parameters and in whatever modules, classes. If you create a type class to mean "well, this name may be used by different module for god-knows different things", that feels awkward. And theoretically, any name can be duplicated. Do we create a class for every function names we create? And there's naming problems for type class operations too. When you create classes, how do you name operations? If you name your operation happily as "get", how are you sure that somebody else will not want to use this name for his own functions or class operations? Actually, to me, it is the naming clash for class operations that bothers me the most. For the alternatives people present so far, I don't see any of them satisfactory. 1. Use small modules. Yes. I can use small modules. But I will somewhere need to use more than one modules. And it is very possible that two names from two modules that I import clash. Also, even not able to use the same name within one module is sometimes annoying too. Split this module into 2 sub modules? I suppose modules are designed for seperating natural modules, not for seperating duplicate names. Creating a module just to get some synonym out sounds quite ad-hoc design. OO languages, on the other hand, even within the same class/interface, we have overloadings, we can create nested classes that brings its own namespace. Very rarely do I need to worry about name clashes. I can name functions as nicely as I can come up with. 2. Use qualified name. Well. that is a systematic solution. But, if I know I'll have to almost always write MySomeModule.add, I probably would want to name it "addMSM" to make it short, as what FiniteMap is doing. I like the code example that Oleg presented in your thread, and I love the Haskell type system that can even support overloading by returns, very powerful indeed. However, they are parametric polymorphism, even though they can to some extent simulate ad-hoc polymorphism, I just don't see they are the right tool to support ad-hoc polymorphism. In summary, names may seem a cosmetic issue. What is the fundamental semantics and functionality differnce between "add" and "MyModule.add" anyway? Just a few keystrokes, right? However, IMHO, naming is the very fundamental cosmetic issue, as in most programming languages. Not being able to name things freely is a big problem in my eyes.. | http://www.haskell.org/pipermail/haskell/2004-June/014180.html | CC-MAIN-2014-10 | refinedweb | 558 | 73.68 |
Windows Communication Foundation From the Inside
The last cipher I'm going to talk about is the Advanced Encryption Standard (AES). With this, we'll have covered about half of the important algorithms needed for a transport security implementation, such as SSL. AES started out as a contest to replace DES for use by the US government. Several submissions were made, including one called Rijndael by Joan Daemen and Vincent Rijmen. Rijndael won the contest and became AES.
AES is a 128-bit block cipher with a variable length key from 128 to 256 bits. Encryption keys of 128 bits are the current minimum standard for encrypting information that has an expected lifetime of several years. The implementation of AES is significantly more complicated than for DES. AES has a key expansion stage and rounds that consist of four operations on a matrix of state bytes. The matrix operations mix in bytes from the key, modify the elements of the matrix, permute the entries in the rows of the matrix, and transform the matrix columns. These rounds are repeated 10 to 14 times depending on the size of the encryption key. The final round concludes by mixing in additional key bytes.
Rather than writing your own implementation of AES or any of the algorithms that I've been talking about, you should get a standard and well-tested implementation. Most of these algorithms are available in the System.Security.Cryptography namespace.
The only significant attacks on AES are known as side-channel attacks. A side-channel attack uses observations of coincidental information, such as power usage, cache hits, and execution times, to extract information about the internal state of the algorithm. If AES is run on a general-purpose processor and another process can force you to encrypt text with your secret key, then that process can extract the encryption key in a surprisingly short amount of time. When there is a lot of activity on the system, these attacks are still possible but may require averaging of many more measurements to obtain the answer. Most algorithms are vulnerable to side-channel attacks if you give attackers enough access to the device.
Next time: Introducing MessageState | http://blogs.msdn.com/drnick/archive/2006/08/01/685012.aspx | crawl-002 | refinedweb | 366 | 53.41 |
Articles Index
Currently there is no standard way to add validity constraints to Java classes. This is in contrast to other languages like XML in which (using XML Schema) relatively rich constraints may be specified. With the advent of annotations (JSR 175) in the Java 2 Platform, Standard Edition (J2SE) 5.0 a convenient mechanism now exists to allow such constraints to be specified in the Java meta model. This article explores how annotations might be used for this purpose and discusses why this may be an important capability.
This article is made up of 3 parts:
In this section we'll take a look at what Java has to offer in terms of support for constraints and compare this with other technologies that a Java 2 Platform, Enterprise Edition (J2EE) developer would typically encounter. First, lets start with some definitions to make sure we are all on the same page.
What we mean by the term constraint (for the purposes of this article) is simple field level constraints on data. For example, to store a person's age we may define an integer field called age. In plain English, a constraint on this field would be something like "the age must be greater than or equal to 0".
When we define an entity, such as a person, in a language like Java then we do so in the meta model of that language. In the case of Java, the meta model that we use is for this is a Class. So if we define an age field as "private int age;" then we are specifying three pieces of meta information: the visibility; the type and the name. The meta model for Java is defined in the Java Language Specification.
In most computer systems, the integrity of the data is paramount. For example, the data may represent a bank account or patient record. The usefulness of that information, to the organization that maintains it, is typically related to the accuracy and integrity of that information. For example, if a bank account does not have a valid account number then it is difficult for the bank to make proper use of that account.
In an n-tier system, the business tier exposes services that provide an access point to parts of a business process that is being automated. One of the key responsibilities of these business services is to ensure that the integrity of the business data is maintained. They do this by enforcing certain business rules on that data during the life cycle of that data. Additionally, databases are normally designed with a certain degree of integrity checking built in.
Unfortunately, if no integrity checking is performed on the data prior to it reaching these business services, then the user experience may suffer because of the time it takes between the user submitting the information and the user being informed of errors in the data. Additionally, increased load is placed on the system as it needs to cope with a higher amount of messages to the business services for each business transaction.
To alleviate these problems, it is common to do some integrity checks on the data closer to the end user. Some checks may be done in the browser using the facilities in HTML forms or by using JavaScript. Checks are also typically done in the presentation tier which is the front door to the server side processing. These checks are a subset of the overall business rules as it is typically impractical to attempt to validate the data completely. A typical example would be for a credit card number. You might check that the card number adheres to the correct format in the browser or presentation tier, but ensuring that it is a valid credit card number and has sufficient credit will typically be left to the business tier.
In trying to solve this problem, however, new problems are often introduced. One problem is that the business rules are duplicated. For example if you have a rule specifying the constraints on a credit card number and you hand code this check in the browser, presentation tier and business tier, then you have duplicated that rule three times. If the rule changes then you need to change this in each place. This is clearly a maintenance issue.
Another problem is missing rules in the business tier, as a result of adding those rules in the browser or presentation tiers. This may occur deliberately to avoid maintenance problems associated with duplication, or accidentally because the data reaching the business services no longer has these integrity issues.
At first this may not seem like a problem. However, it means that the business services are no longer in charge of maintaining the integrity of that data, but are instead trusting their clients to look after some aspects of that integrity. The moment a business service is reused, then the new clients must know that they need to do the same validity checks or you now risk the integrity of your businesses data.
In an SOA world, where we want to increase the reuse of business services, we cannot afford to have the business services not taking complete responsibility for the validity of the data. This is particularly important for business services that are used between separate organizations such as business partners. Clearly, you can't rely on your business partner to ensure the validity of your businesses data.
One approach to solving this issue (at least partially), is to declaratively define a set of constraints on the data, that can be shared by various producers and consumers of that data. This approach is adopted by the Web Services standards which use XML Schema to define data exchanged in these services.
This is also the approach adopted within this article, where we introduce a mechanism to define constraints using the new Annotation facility in J2SE 5.0. But first, we dig a little deeper into constraints.
Consider Figure 1 below. It shows a simple application which captures address information from the user in a web browser, transfers it to a J2EE application server which in turn both stores the address in a local database as well as passes the address to a partner's web service. In addition, there is a simple business rule (constraint) associated with the address specifying that the street field cannot be greater than 20 characters in length.
At each node in the application, the address data is captured in a different format and governed by a different meta model. Taking the street field, we can see that in the browser it is in the form of an HTML text input field; in the application server it is in the form of a String property of an Address Java class; in the database it is a VARCHAR column of an ADDRESS table; and in the partner's web service it is a string element within an address element of an XML document.
Lets take a closer look at the meta model that applies to the address data at each of these nodes.
In The Browser
Here we represent the street field as an input text field. In HTML 4.0 the meta model of an input field allows for some constraints to be placed on the data to be captured. In particular it allows us to specify a maxlength attribute (as shown in the diagram) which will cause browsers to prevent the users from typing more than that many characters into the field. The meta model allows for the definition of this constraint and the browser will enforce the constraint.
Beyond maxlength there are some other constraints, such as option lists, which restrict the user to choose one of a fixed set of options, but on the whole the list of constraints is fairly limited. As a result, web developers typically resort to the use of JavaScript to enforce other constraints in the browser.
The next generation of forms known as XForms leverages the XML Schema meta model and contains a far richer set of constraints.
In The Database
In the database we represent the street field as a VARCHAR column of an ADDRESS table. The relational database meta model allows us to specify a maximum length constraint on VARCHAR columns as is shown in the diagram. So once again, the meta model allows for the definition of the constraint and the RDBMS will enforce the constraint.
The constraint mechanisms of modern DB's are pretty rich these days.
In The Web Service
Web Services leverage XML Schema as the meta model for the input and output data of WSDL operations. XML schema allows a relatively rich set of constraints to be specified. For example, our business rule of a maximum of 20 characters on the street field is no problem in XML schema.
The list of XML Schema constraints (known as simple type facets) are: length, minLength, maxLength, pattern, enumeration, whiteSpace, maxInclusive, maxExclusive, minInclusive, minExclusive, totalDigits and fractionDigits.
length
minLength
maxLength
pattern
enumeration
whiteSpace
maxInclusive
maxExclusive
minInclusive
minExclusive
totalDigits
fractionDigits
In The Application Server
In the application server the street field is represented as a String property of a Java class. The Java meta model does not have a standard mechanism to specify any constraints on a String field. So we cannot directly capture the business rule that restricts the street field to 20 characters, as part of the definition of the street field. Typically such constraints end up being enforced in code.
Others have discussed this issue before and proposed some potential solutions. We will cover some of these later in the article.
As you can see there is a fair difference in these four meta models when it comes to defining constraints. In the next section we discuss why we think that being able to specify constraints declaratively is a useful thing.
The problem is not that you can't enforce such constraints in the Java programming language. Clearly you can do so programatically as the following example shows.
public class Address {
...
public void setStreet(String newStreet) throws ConstraintViolationException {
if ((newStreet != null) && (newStreet.length() > 20))
throw new ConstraintViolationException();
street = newStreet;
}
...
}
But how does this differ from, say, the XML example (reproduced below) where the constraint was captured (declaratively) in the meta model?
<complexType name="Address">
...
<element name="street">
...
<restriction base="string">
<maxLength value="20"/>
...
</complexType>
First thing you might notice is that the enforcement is quite ad hoc. We could have written the Java code in different ways. In fact, it would be quite easy to have forgotten to do a null check first. The second thing is that (ignoring the verbosity of XML Schema) there is more code required to procedurally capture the constraint.
Another difference is that there is no separation of the definition of the constraint, from the enforcement of it. In fact, the Java version does not really define the constraint at all, except possibly informally in the JavaDoc. The XML version, in contrast, does not contain any enforcement code. The enforcement would be done in some other language like Java. However, a very important difference is that this code is likely to be part of a framework, rather than an application. Very little, if any, application code would be required for enforcement.
And the last difference is that there is no way to programatically determine what constraints are present on the street field. For example, we can't introspect on the field and find the constraints.
By separating the definition from the enforcement, and by providing a way to introspect these constraints, we gain much more flexibility in the enforcement. This is particularly useful when integrating with other frameworks and also for sharing with other meta models (which we will cover in the next section). It also allows us to potentially employ different enforcement strategies over time or in different circumstances.
Not only would it be nice to have a standard mechanism for specifying and enforcing constraints within the Java programming language, it would also be useful to be able to share constraints between Java and other meta models.
In Figure 1, we showed an example where the Address data moved between 4 different meta models. The diagram showed how the maximum length constraint on the street field could be defined in the various meta models (except Java).
Ideally we would like to define this constraint only once and then share it between each of these meta models. For example we would like to be able to do the following sorts of things.
<->
To be able to do all of the above, we need to be able to programatically access to the constraints.
Most applications today do constraint checking in a fairly informal and ad hoc manner. It is not uncommon to see constraint checking coded manually in the HTML forms, web applications, or EJB's, with little or no attempt to avoid code duplication. It is also not uncommon to find constraint checking missing from some of these places or indeed be inconsistent between them. There are likely many cases where the business rules changed but not all the checking code was changed, leading to unexpected behaviour.
Others have discussed this issue before and presented some solutions. The following is a summary of the different approaches we have come across. The resources section contains links to articles that discuss these approaches. Note these articles are worth reading in their own right.
public class AddressBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor streetDesc =
new PropertyDescriptor("street", Address.class, "getStreet", "setStreet");
streetDesc.setValue("MAX LENGTH CONSTRAINT", new Integer(20));
return new PropertyDescriptor[] { streetDesc };
} catch(IntrospectionException ex) {
return null;
}
}
}
public class Address {
public static Constraint STREET_CONSTRAINT = new MaxLengthConstraint(20);
private String street;
public void setStreet(String street) throws ConstraintViolationException {
STREET_CONSTRAINT.validate(street);
this.street = street;
}
}
public class Address {
public static Constraint STREET_CONSTRAINT;
static {
CompositeConstraint cc = new CompositeConstraint();
cc.add(new MaxLengthConstraint(20)).add(new MinLengthConstraint(10));
STREET_CONSTRAINT = cc;
}
}
CompositeConstraint
MaxLengthConstraint
MinLengthConstraint
PropertyDescriptor
'street'
'STREET_CONSTRAINT'
This is by no means an exhaustive list of possible approaches to solving this problem. Many other approaches are possible including having separate classes for each constrained property (having a Street class for the street property instead of String). What we have covered are some of the more popular and successful approaches that we are aware of.
We have provided an overview of some of the existing approaches and pointed out where we believe there is room for improvement. In wrapping up the first part of this article, let us outline what we see as some of the more important features of an ideal solution. We believe an ideal solution would have the following properties.
In the remainder of this article we will discuss the use of J2SE 5.0 annotations for defining constraints. We believe this fulfils the first four goals and that it would be a good basis for a standard. The remaining goals are beyond the scope of this article.
Let's explore a possible way to add constraints by using annotations. If you are not familiar with annotations, then we recommend you read some other articles before you continue.
The code below shows a snippet of an Address class with a @MaxLength(20) annotation added to the street field. The intended meaning of this annotation is that the street field has a constraint associated with it specifying that the length cannot be greater than 20 characters.
@MaxLength(20)
public class Address {
@MaxLength(20)
public String street;
....
}
You may have noticed that the street field is declared public. I will deal with this later in the article, but let's ignore this for now.
We can define the MaxLength annotation as follows.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MaxLength {
int value();
}
Note the annotation is defined by the use of the @interface keyword. The @Retention and @Target bits are annotations (or more formally meta-annotations) that apply to the MaxLength annotation (meta data of meta data). Here the @Retention annotation is set to RUNTIME which means the annotations can be introspected at runtime. The @Target annotation is used to say that the MaxLength annotation can only be applied to fields.
@interface
@Retention
@Target
MaxLength
RUNTIME
The following code snippet shows how you can use reflection to get the MaxLength constraint for the street field.
// introspect to get a list of annotations on the street field.
Field f = Address.class.getField("street");
Annotation[] annotations = f.getAnnotations();
// iterate over the annotations to locate the MaxLength constraint if it exists
for (Annotation a : annotations) {
if (a instanceof MaxLength) {
MaxLength ml = (MaxLength)a; // here it is !!!
}
}
Now that you have the constraint you can validate values against it. The following code illustrates this.
MaxLength ml = ... // from above
String value = "101 first st";
if (value.length() > ml.value()) {
// The constraint is violated
}
It's straightforward to add constraints to fields and validate them by using annotations and the runtime reflection capabilities associated with them. However, this example relied on the field being public, or else the introspection would have failed. This short coming will be addressed next.
So let's adapt this approach to a JavaBeans model, and while we are at it, get a bit more sophisticated in the processing. In this case the field will be private and there will be associated public getters and setters. As mentioned, annotating the field is not useful as we can't sensibly introspect it when it's private.
Fortunately there are other places we can put the annotations where we can introspect them. The choices are as follows:
Any of these are possible, and in fact all could be allowed, but we will concentrate on the setter method itself. To be easy for frameworks to identify constraints, it would be useful to have something to mark them out from other annotations. There is no inheritance for annotations, but luckily there is another mechanism -- annotations for annotations. Below is a simple marker meta-annotation that will be applied to our constraint annotations (like MaxLength).
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Constraint {}
The @Target(ElementType.ANNOTATION_TYPE) indicates that the Constraint annotation will be applied to other annotations (that it is a meta-annotation). Now let's use this to define a new constraint - MinLength.
@Target(ElementType.ANNOTATION_TYPE)
Constraint
MinLength
@Constraint
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
public @interface MinLength {
int value();
}
Note the @Constraint marker annotation is now included and the @Target specifies that the annotation is allowed on fields, methods and method parameters.
@Constraint
Now we are ready to define a JavaBeans version of Address with an additional MinLength constraint. This is shown below.
public class Address {
private String street;
public String getStreet() {
return street;
}
@MinLength(10)
@MaxLength(20)
public void setStreet(String street) {
this.street = street;
}
}
Let's now start to put together some code to get at these property-based constraints. First, we write a simple method to determine if a given annotation is a constraint.
/**
* Returns true if the annotation is a Constraint. I.e. Contains the Constraint marker.
*/
public static boolean isConstraint(Annotation annotation) {
if (annotation == null)
throw new IllegalArgumentException("null is not a legal value for annotation");
return annotation.annotationType().isAnnotationPresent(Constraint.class);
}
Next we build on that to go through an array of annotations and return from that a set of constraints (Annotations that pass the isConstraint test above). This method will be used later.
isConstraint
/**
* Returns the set of constraints that are contained within the array of annotations.
* If no constraints found then the set will be empty.
*/
private Set<Annotation> getConstraints(Annotation[] annotations) {
Set<Annotation> constraints = new HashSet<Annotation>();
for (Annotation a : annotations) {
if (isConstraint(a))
constraints.add(a);
}
return constraints;
}
Finally we write a method to give us the set of constraints associated with a given property of a given class. Exception handling has been omitted for clarity.
public Set<Annotation> getConstraints(Class<?> theClass, String propName) {
/*
* Find the descriptor for the property name given and return the
* constraints from the write method.
*/
PropertyDescriptor[] descs =
Introspector.getBeanInfo(theClass).getPropertyDescriptors();
for (PropertyDescriptor desc : descs) {
if (propName.equals(desc.getName()) {
Method write = desc.getWriteMethod();
// get the constraints off the write method. This calls the previous
// method passing the array of annotations from the write method.
if (write != null)
return getConstraints(write.getAnnotations());
}
}
// if we get here then we didn't find the property or its write method - exception
...
}
So we now have a simple way to annotate properties on JavaBeans and a simple method to get at them later.
To be perfectly honest, we've taken a few liberties with the above code in order to make it simpler to follow. In reality, you wouldn't want to create a new set of constraints from scratch each time. You'd really want to do it once and cache it. Also, the above assumes that the setter methods are not being overridden. In the real world, you'd want to cater for the setter method being inherited from a parent class and also having the setter method being overridden, one or more times, in the inheritance hierarchy. What we want, is the union of all the constraints on the setter method, such that all the constraints on the property, regardless of where they are defined, must be satisfied. This means walking up the inheritance hierarchy, looking for all the definitions of the setter method and collecting the corresponding constraints. You can download the complete code from the resources section.
Clearly minimum and maximum lengths are just two examples of constraints that could be added using Annotations. We could define annotations for many of the XML Schema constraints like @Pattern("(\\d{4}\\-){3}\\d{4}"), @MaxInclusive(56) etc. While there is no need to limit the possible constraints that could be defined, it would be valuable to have a standard set of constraints that you could always rely on to be there. We believe a good starting point is probably the simple type facets from XML Schema. Additionally, for collections, we could adopt the minOccurs and maxOccurs that are applied to elements in XML Schema. Click here to see examples of some more potential constraints.
@Pattern("(\\d{4}\\-){3}\\d{4}")
@MaxInclusive(56)
minOccurs
maxOccurs
Now we have an extensible mechanism for defining constraints on JavaBeans properties and a straightforward way to get at them at runtime. What we need next is a validation framework that allows us to check whether a given value is valid for a given property of a given class. The following code snippet gives you the general idea.
public ValidationResult validate(Class theClass, String propertyName, Object value) {
Set<Annotation> constraints = getConstraints(theClass, propertyName);
for (Annotation c : constraints) {
// check for violations against the constraints
}
// return the result.
}
Note that this simple validation method is usable in several different ways. For example, you could call this inside the setter method if you wanted to prevent invalid values being set as shown in the following code snippet. The Validator is some instance of a class that implements the validate method shown above.
public void setStreet(String street) throw ValidationException {
ValidatonResult result = theValidator.validate(getClass(), "street", street);
if (// result shows street value not valid)
throw new ValidationException(result);
this.street = street;
}
Or if you prefer you could allow the value to be set and then validate the field afterwards.
String street = "123 highway 1 ....";
address.setStreet(street); // note setStreet() no longer throws exceptions
...
ValidatonResult result = theValidator.validate(address.getClass(), "street", address.getStreet());
if (// result shows street value not valid)
// do something
Still another option is to validate a value externally from the bean and only call the setter if it is valid. The last option may be useful when integrating with a presentation framework like JSF.
String street = "123 highway 1 ....";
ValidatonResult result = theValidator.validate(Address.class, "street", street);
if (// result shows street value not valid)
// do something
else
address.setStreet(street);
We won't go into more details on validation for now. Hopefully we've shown enough to demonstrate that you could implement a sophisticated validation framework around these constraints and that you could even integrate it in to some existing validation framework. In this way, you could get a seamless framework that handled simple field constraints, as well as more complex cross field validations and so on.
A validation framework is included with the downloadable source.
One of the advantages of using annotations is that J2SE 5.0 aware IDEs may provide auto-completion for annotations. This makes it very easy for developers to see the list of constraints that can be applied. The following screenshot shows this feature in NetBeans 4.
It's also worth pointing out that this works best when we have each annotation applying a single constraint and the name of that annotation being fairly self explanatory. For example, it wouldn't be hard to figure out what adding a MaxLength annotation might do, once you were familiar with applying constraints this way. Aligning these annotation names with the names used for corresponding constraints in XML Schema, further simplifies things for developers familiar with XML Schema.
The end result is a strong development story around applying property constraints, without the need for custom IDE support (i.e. it's out of the box).
In this section we discuss some other possibilities as well as some limitations of this implementation.
We have covered the use of annotations for constraints in isolation from other annotations. The reality is that as developers move to J2SE 5.0, annotations will be created for many things. One area that seems likely, is a set of annotations for JavaBeans properties as a whole. In this case the property-based constraint annotations, as discussed in this article, would need to work together with these annotations or may even be folded into this set. As a simplistic illustration, you might have something like this.
public class Address {
@Property @MinLength(10) @MaxLength(20) String street;
....
}
Note the @Property annotation is a slightly different type of annotation from constraint annotations, as it would need to be processed at build time in order to generate the getter and setter methods.
We based our approach on the use of the runtime support for annotations, because we wanted the constraints to become part of the class's meta data, in a similar way that constraints within XML Schema are part of the meta data for XML based data. Annotations, however, may also be accessed at build time.
Included with the J2SE 5.0 release is a tool known as the Annotation Processing Tool (APT), which is designed to support build time processing of annotations. It allows us to generate additional code, such as additional classes, based on annotations within existing classes.
This may be particularly useful, if you want to ensure that property validation is always done in the setter method. To illustrate this, let's revisit our Address class, which is reproduced below.
public class Address {
private String street;
public String getStreet() {
return street;
}
@MinLength(10)
@MaxLength(20)
public void setStreet(String street) {
this.street = street;
}
}
Using APT we could generate a decorator class (applying the GOF decorator pattern) to enforce validation in the setter method as shown below.
public class AddressValidationDecorator extends Address {
...
public AddressValidationDecorator(Address address) {
this.address = address;
}
...
public void setStreet(String street) {
ensurePropertyValid("street", street); // throws exception if invalid
address.setStreet(street);
}
...
}
Having validation in the setter method is simply a matter of constructing and using the decorator as shown below.
Address a; // from somewhere
Address a2 = new AddressValidationDecorator(a);
a2.setStreet("123 better make it valid lane"); // would get an exception if street invalid
The approach we have outlined mirrors the approach taken by XML Schema, in that we have explicitly defined a set of constraint objects that can be applied to a property. For example, to constrain the street property to a maximum length of twenty characters, we declaratively add a MaxLength constraint object to the street property's meta data. Enforcing this constraint, is logically equivalent to enforcing the following boolean expression:
street.length() <= 20
When there is more than one constraint applied to a property, all those constraints must be adhered to for the property to be valid. In other words, there is an implicit AND operation between the constraints. For example, if we define a minimum length constraint and a maximum length constraint on the street property as follows:
@MinLength(10) @MaxLength(20) public void setStreet(String street)
then enforcement of these two constraints is logically equivalent to enforcement of the following boolean expression:
(10 <= street.length()) AND (street.length() <= 20)
Note, XML Schema also has an implicit ANDing of constraints, as do frameworks like JSF. There is no support for the use of an OR operator between constraints, nor the use of a NOT operator, nor grouping operators to control operator precedence. In other words, there is only partial support for boolean expression.
We consider alignment with XML Schema more important than more complete boolean expression support. We also feel, as the designers of XML Schema and JSF presumably do, that this approach results in a good compromise between power and complexity. The end result is that, while it may not cover every situation, it is easy to use and covers many common cases.
An alternative approach is to have a single annotation to which we pass a boolean expression. For example, the setStreet method could be written as:
setStreet
@Constraint("(10 <= street.length()) && (street.length() <= 20)")
public void setStreet(String street)
As we showed in the previous section, this boolean expression is logically equivalent to adding both a MaxLength and a MinLength constraint to the street property. The following are some of the pros and cons of this approach:
PROS
CONS
Incidentally, if we go down this path and add full boolean expression support, we are getting pretty close to what Design By Contract (DBC) implementations like iContract offer. The goal of the constraint mechanism is not to create another DBC solution, but instead to add a simple mechanism for declaratively adding some constraints to properties, which is aligned with important standards like XML Schema and JSF. This is intended to be complimentary to the J2SE 1.4 assertion facility, which provides support for some of the DBC concepts.
So while there are some limitations to the approach we have presented in this article, we believe that it provides a pragmatic and useful solution to an important problem.
In this article we have discussed the value of having a mechanism in the Java programming language to be able to declaratively add constraints to properties, and covered some of the existing approaches to solving this problem. Additionally, we have listed what we see as some of the more important features of an ideal solution, and presented a new approach, that leverages the power of J2SE 5.0 annotations to, in our opinion, take us a step closer to that ideal. | http://java.sun.com/developer/technicalArticles/J2SE/constraints/annotations.html | crawl-001 | refinedweb | 5,154 | 53.51 |
Unity Function Performance Followup!
Today’s contenders are:
- Non-Virtual Instance Functions
- Virtual Instance Functions
- Static Functions
- Lambdas (i.e.
() => {})
- Delegates (i.e.
delegate(){})
- GameObject.SendMessage
Here’s the script that runs the test:
using System; using System.Diagnostics; using UnityEngine; public class TestScript : MonoBehaviour { private const int reps = 100000000; private string report; void Start() { var stopwatch = new Stopwatch(); var staticFunctionTime = RunTest( stopwatch, () => { for (var i = 0; i < reps; ++i) { StaticFunction(); } } ); var instanceFunctionTime = RunTest( stopwatch, () => { for (var i = 0; i < reps; ++i) { InstanceFunction(); } } ); var virtualFunctionTime = RunTest( stopwatch, () => { for (var i = 0; i < reps; ++i) { VirtualFunction(); } } ); var lambdaTime = RunTest( stopwatch, () => { Action lambda = () => {}; for (var i = 0; i < reps; ++i) { lambda(); } } ); var delegateTime = RunTest( stopwatch, () => { Action del = delegate(){}; for (var i = 0; i < reps; ++i) { del(); } } ); var sendMessageTime = RunTest( stopwatch, () => { for (var i = 0; i < reps; ++i) { SendMessage("InstanceFunction"); } } ); report = "Test,Time\n" + "Static Function," + staticFunctionTime + "\n" + "Instance Function," + instanceFunctionTime + "\n" + "Virtual Function," + virtualFunctionTime + "\n" + "Lambda," + lambdaTime + "\n" + "Delegate," + delegateTime + "\n" + "SendMessage," + sendMessageTime; } private long RunTest(Stopwatch stopwatch, Action test) { stopwatch.Reset(); stopwatch.Start(); test(); return stopwatch.ElapsedMilliseconds; } void OnGUI() { GUI.TextArea(new Rect(0, 0, Screen.width, Screen.height), report); } public static void StaticFunction() {} public void InstanceFunction() {} public virtual void VirtualFunction() {} }
Notice that this is the same computer that the previous test was run on, aside from the software differences between Mac OS X and Unity.
Here are the results I got:
It turns out that
GameObject.SendMessage is ludicrously slow. It’s about 200x slower than the next-slowest type of function. That said, each function type was called 100 million times, so it’s not so slow that you should never use it. Each call was only 6/10,000 of a millisecond, so feel free to make a few of these calls without worrying that it’ll ruin your app’s performance.
Delegates and lambdas are essentially the same and perform essentially the same. They’re a bit slower than a virtual function call, but close enough that you can consider them about the same performance. As mentioned, all three types of functions are about 200x faster than
SendMessage.
Finally there are the “fast” functions: non-virtual instance and static functions. These are again an order of magnitude faster than the virtual functions, lambdas, and delegates. In the previous article the instance functions were a bit slower than the static functions, but that’s been reversed somewhere between Unity 5.0 and Unity 5.4. Regardless, these functions are in the same ballpark performance-wise and blisteringly fast compared to their “virtual” competitors and
SendMessage.
So go ahead and use non-virtual functions to your heart’s content, provided you’re not calling them in huge numbers such as one million per frame. The overhead is really tiny for almost all tasks. Virtual functions, lambdas, and delegates are probably also fine for most tasks. You can certainly make thousands of calls per frame without causing any issues. Just make sure to be careful with garbage creation when using lambdas. Finally there is
GameObject.SendMessage that you should use extremely sparingly. A few per frame is OK, but never use them heavily or you’ll quickly run into performance problems.
Do you ever use
SendMessage? Do you avoid virtual functions, lambdas, or delegates? Let me know how it’s worked out for you in the comments!
#1 by Andy Buchanan on October 13th, 2016 · | Quote
Have you tested IL2CPP vs Mono?
#2 by jackson on October 13th, 2016 · | Quote
This test was on Mac where there is no IL2CPP support yet. It’d certainly be nice to get IL2CPP stats for articles like this one and some readers have asked for it, so perhaps I’ll start testing both scripting backends in the future.
#3 by David Barlia on October 13th, 2016 · | Quote
I wonder how delegates would score if, instead of invoking 100,000,000 times, the call were added to the delegate 100,000,000 times and then (start the stopwatch now…) invoked once. While that may be an unfair comparison, given the removal of the overhead of the for loop, not *having* to iterate is one of the innate advantages of delegates.
#4 by jackson on October 13th, 2016 · | Quote
I changed the lambda part of the test to this:
Then ran it on the same computer as in the article. After five minutes or so I killed the test app and lowered
repsto 100,000. Again it took several minutes and I killed the test app.
Suffice to say it’s a bad idea to add tons of listeners to a delegate. For more on this, check out this article where I discuss C# event performance in depth. Since events are basically delegates, it makes sense that their non-linear time growth would apply here too.
#5 by David Barlia on October 14th, 2016 · | Quote
Wow! That was not what I was expecting at all. And thank you for the link to your other article– What a revelation!
…Well, now surely you’ve got to add UnityEvent to this speed test.
#6 by Justin Wasilenko on December 10th, 2018 · | Quote
David I just tried this benchmark and UnityEvents are much faster then SendMessage and C# even faster.
Performance running 100 million reps:
Mono, (Ticks)
C#Event, 178
UnityEvent, 1482
Messenger, 3820
Event System – Dispatcher, 4134
SendMessage, 42248
Tested on Windows Standalone 640×480, Fastest, Windowed, Unity 2018.3.0f1
#7 by Stephen Hodgson on October 27th, 2016 · | Quote
Jackson, you sir are a gentleman and a scholar!
Thanks for all this great information. | https://jacksondunstan.com/articles/3605 | CC-MAIN-2020-29 | refinedweb | 928 | 62.48 |
We needed a radio in the kitchen to replace our Bush DAB/FM portable which has put in good service, although DAB reception in our area has never been great.
As space is at a premium, I wanted the new radio to take up as little space as possible.
So I came up with the idea of building something that would fit under the eye-level kitchen cabinets, behind the decorative molding.
This is another wifi Raspberry Pi powered internet radio, similar in operation to two previously described designs (the Radio Caroline inspired radio & the Insomniacs Bedside Radio).
Basic operation
KitchenPi just has a push-button switch and a rotary volume control. When powered on via the wall (mains) switch, the Pi boots and after 20-30 seconds starts playing.
Each time the push button is pressed, the program selects the next program source, the text-to-speech program eSpeak announces the source (e.g. "Radio Caroline") and then the stream starts.
The current configuration includes 5 internet radio streams and a music player (i.e. randomised music files).
functional testing
That's about it. The radio is turned off via the mains switch (I know...brutal).
The electronics
The audio amplifier design is pretty much covered in an earlier post on the NJM2073D. The final circuit looks like this:-
The volume control has a logarithmic law because our hearing is not linear (i.e. we notice a doubling of sound level as being "a bit louder!").
As mentioned in the earlier post, this design is not optimal for use with the Pi as there is far more gain available than actually required.
And as a result of my tests on the Adafruit USB Audio adapter I decided there was no real benefit in using the Adafruit module, rather than the Pi jack socket.
The Pi audio output circuit (from the jack) includes basic filtering and looks like this:-
In the final circuit I decided to add a 1nF capacitor across the 10K volume control to improve audio and restrict bandwidth to about 16kHz. This seemed to sound better and it improved the shape of the output for the 8kHz sine wave test.
The sound quality is also improved as a result of "baffling" the speakers. The enclosure consists of a 5 sided acrylic box, where the 6th side is effectively closed when the unit is screwed to the base of a kitchen unit.
The enclosure sides were cut from an A3 sized sheet of 3mm thick blue acrylic and glued together with rigid plastic adhesive.
I cut large holes for the speakers using my largest tank cutter (58mm diameter). The speakers are protected from probing fingers by 100mm finger safety guards, the kind designed for cooling fans (less than £1 each via Amazon).
I'm using a 12V dc 1A supply (from Spiratronics) with a 5Volt switching regulator for the Raspberry Pi.
The switch logic is reversed from previous projects, only because this made the wiring and component placement slightly easier.
The 10uF capacitor is really just included as a physical connection point for the wires running to the LEDs and the wires running to the power/amp board. (i.e. the wires are soldered to the capacitor leads, and the capacitor leads are clamped by the terminal block connecting the incoming 12V supply).
I did try a couple of blue/UV LEDs initially, but the wavelengths of the blue LED and blue acrylic did not match, so much of the light was filtered out
The software
As in my previous internet radio projects I've used a fairly simple Python program:-
#kitchenPi.py
#---------------
#Plays random music player (Juke Box) or selected internet radio stream
#Pressing button (input 7) switches to next source from list
#SteveDee
#1/4/16
#==========================================================================
import os
import psutil
#Import the time library
import time
#Import the Raspberry Pi library which controls the GPIO
import RPi.GPIO as GPIO
PLAYER = "mplayer"
MUSIC = "/home/pi/Music"
MusicSource = 0
def SelectSource(mSource):
RADIO_CAROLINE = "" #128k
PLANET_ROCK = "" #112k
RADIO_TWO = "" #128k
RADIO_FOUR = "" #128k
WORLD_SERVICE = "" #48k mp3
JukeBox = 0
RadioCaroline = 1
PlanetRock = 2
RadioTwo = 3
RadioFour = 4
WorldService = 5
if mSource > 5:
mSource = JukeBox
if mSource == RadioCaroline:
#start radio
os.system('espeak -ven+f4 -s110 -k5 "Radio Caroline"')
#time.sleep(2)
os.system('mplayer -cache 64 -playlist ' + RADIO_CAROLINE + ' &')
elif mSource == PlanetRock:
#start radio
os.system('espeak -ven+m5 -s100 -k5 "Planet Rock"')
os.system('mplayer -cache 64 ' + PLANET_ROCK + ' &')
elif mSource == RadioTwo:
#start radio
os.system('espeak -ven+f1 -s100 -k5 "BBC Radio two"')
os.system('mplayer -cache 64 -playlist ' + RADIO_TWO + ' &')
elif mSource == RadioFour:
#start radio
os.system('espeak -ven+m1 -s100 -k5 "BBC Radio Four"')
os.system('mplayer -cache 64 -playlist ' + RADIO_FOUR + ' &')
elif mSource == WorldService:
#start radio
os.system('espeak -ven+m3 -s110 -k5 "The BBC world service"')
os.system('mplayer -cache 64 -playlist ' + WORLD_SERVICE + ' &')
else:
#start Juke-Box
os.system('espeak -ven+f2 -s90 -k9 "play that funky music White boy"')
os.system('mplayer -shuffle -playlist ' + MUSIC + '/playlist &')
return mSource
#Main
#Clear the current GPIO settings
GPIO.cleanup()
#Set mode to use Raspberry Pi pins numbers
GPIO.setmode(GPIO.BOARD)
#Set connector pin 7 to be an input
GPIO.setup(7,GPIO.IN)
#Set volume
os.system('amixer sset PCM,0 100%')
#update JukeBox playlist
os.system('find '+ MUSIC + ' -type f -iname \*.ogg -o -iname \*.wma -o -iname \*.mp3 > ' + MUSIC + '/playlist')
#get MusicSource from last time the program was run
file_source = open('/home/pi/LastSource','r')
MusicSource = int(file_source.read())
if MusicSource < 0:
MusicSource = 0 #default to JukeBox
MusicSource = SelectSource(MusicSource)
#Create a LOOP that runs & runs (...until you shutdown)
while True:)
#Reduce cpu load
time.sleep(0.2)
As before (see details) this program is run automatically by modifying /etc/local.rc.
You will also need to install python-psutil and espeak. From a command line in terminal, try this:-
sudo apt-get install python-psutil
sudo apt-get install espeak
more to do
If/when time permits I may work on the following.
Audio noise; As already mentioned, the audio amp has too much gain for this application. There is some low level random & intermittent background noise with the volume turned right down. The primary source of this noise appears to be the wifi dongle.
This noise is swamped by music, and compared to many conventional radios (FM as well as AM) is really not too bad. My family don't notice it.
But I know its there!
And the engineer inside my head says "...we can do better than this...". So once I have the additional components that I need, I will determine whether reducing the audio gain by applying negative feedback results in any improvement.
web interface; Using a simple push-button to change channels is fine as long as you don't need too many options. However, by creating a web interface I should be able to extend the range of stations (and maybe add podcasts, BBC iPlayer Radio & so on) by allowing the use of smart phone/iPad to select media.
Hygiene/cleaning
People in kitchens often have sticky fingers. My use of cheese-head screws and finger guards could make this radio difficult to keep clean.
My original plans were for a radio mounted high up, on top of the kitchen cabinets, with remote controls. But this would come with its own set of problems.
EDIT 26-May-2016
KitchenPi modifications
KitchenPi has been running about 6 weeks and giving great service. Here are a few more comments and recent modifications.
Station ID announcement
When switching stations, the station announcement (e.g. "Radio Caroline") was found to be a bit loud. In some cases, it seemed louder than much of the program content. So I've modified the code to lower the volume for espeak using the "-a" variable:-
os.system('espeak -ven+m5 -s100 -k5 -a 30 "Planet Rock"')
Setting a value around 20-30 seems about right. This is done for all espeak lines within the program.
Stream drop-out
Just once in a while, usually during breakfast, we lose a stream. Sometimes this coincides with the microwave being used. Unfortunately the microwave is located directly in-line between KitchenPi and our wifi router.
I was hoping to move up from 2.4GHz to 5GHz to see if this would provide a more reliable link. But as you will see from my post on 5GHz wifi there seems to be a problem playing BBC streams via mplayer on the Raspberry Pi.
I now suspect this is an mplayer problem, but don't have much to go on at the moment (e.g. it works fine with Radio Caroline and Planet Rock streams, and it works fine on 2.4GHz with all streams). So I'm sticking with 2.4GHz for now.
However, to recover from the very occasional loss of stream, I've modified the Python code to check every 60s whether mplayer is still running. Here are the code modifications highlighted in red text:-
MusicSource = SelectSource(MusicSource)
LoopCount = 0
PlayerHasStopped = False
#Create a LOOP that runs & runs (...until you shutdown)
while True:
LoopCount += 1)
#check whether player is still running
if LoopCount > 300:
LoopCount = 0
PlayerHasStopped = True
for proc in psutil.process_iter():
if proc.name() == PLAYER:
PlayerHasStopped = False
if PlayerHasStopped == True:
MusicSource = SelectSource(MusicSource)
#Reduce cpu load
time.sleep(0.2)
I've only been testing this for a couple of days...so far, so good.
Audio noise
I still have a small noise issue which I now know is due to the wifi dongle. As it scans for access points you can hear a background click which corresponds to the dongle blue light flashing.
The noise level is the same, irrespective of volume setting. In a way this makes it more difficult to deal with than it would be if the level went up and down with the volume.
As mentioned in the main text, its a problem to no-one but me. You can't hear it at all when music is playing. It is only noticeable in the gaps between speech and when the system is booting up.
I added ferrite beads to the left & right wires at the volume control input/Pi output (which probably hasn't made any difference) and two more to the pin 7 inputs to the NJM2073D amps (which I think has reduced the level a little).
Like most audio equipment, you also get noise when you hold a mobile phone close to kitchenPi, when the phone is actively communicating with the service.
But basically, KitchenPi is working great! | http://captainbodgit.blogspot.com/2016/04/kitchenpi-internet-radio-for-my-kitchen.html | CC-MAIN-2017-34 | refinedweb | 1,757 | 64.41 |
Stream and convert BCP format files
Project description
BCP Reader
A reader for BCP-format data files. BCP files are similar to CSV files but contain a multi-character line and field delimiters. The default delimiters used are:
- field delimiter:
@**@
- line delimiter:
*@@*
Python's csv module can only deal with single character delimiters, so this
module has a
reader function and
DictReader class which should be drop-in
replacements for python's
csv module equivalents.
Credits
The author of the main method is Gertjan van den Burg of the Alan Turing Institute. It was based on a method originally developed by David Kane at NCVO.
Installation
Install with
pip install bcp-reader
Usage
The module can be used by importing from the
bcp module in a python script:
import bcp with open('path_to_bcp_file.bcp') as f: bcpreader = bcp.reader(f) for row in bcpreader: print(row) # ["Value 1", "Value 2"] with open('path_to_bcp_file.bcp') as f: bcpreader = bcp.DictReader(f, fieldnames=["field 1", "field 2"]) for row in bcpreader: print(row) # {"field 1": "Value 1", "field 2": "Value 2"}
You can also use it via the command line to convert a BCP file to CSV:
bcp path_to_bcp_file.bcp > csv_output.csv
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/bcp-reader/ | CC-MAIN-2020-10 | refinedweb | 227 | 62.38 |
Index
Links to LINQ.
NOTE: The LINQ to SQL Designer is covered here.
When combined with partial classes, partial methods allow the developers of auto-generated code to reserve a name for a method that can be optionally implemented by the consumer of the class. This gives a developer a place where she can optionally add code that will never be overwritten if the code generation tool is re-run.
Listing 1: A simple example of a partial method
using System;
namespace PartialMethods
{
// Assume this class is autogenerated
public partial class MyPartialClass
{
partial void MyPartialMethod();
public void CallPartialMethod()
{
MyPartialMethod();
}
}
// Assume this class is written by hand
public partial class MyPartialClass
{
partial void MyPartialMethod()
{
Console.WriteLine("Second half");
}
}
class Program
{
static void Main(string[] args)
{
MyPartialClass p = new MyPartialClass();
p.CallPartialMethod();
}
}
}
Consider the code shown in Listing 1. Assume that the first instance of MyPartialClass was auto-generated by a visual designer that is part of Visual Studio. Notice that the class is declared as partial, as is MyPartialMethod. Notice that MyPartialMethod contains a header, but no implementation. You can consider this an invitation to the developer to implement this method if desired.
Assume that the developer took up the invitation and created by hand the second half of MyPartialClass. In this class she has written her implementation for MyPartialMethod, which will duly be called at runtime by the code in the first part of this partial class. If she had decided to decline the invitation, then the code to call MyPartialMethod would have been optimized out by the compiler, causing all traces of MyPartialMethod to be entirely eliminated at run time.
This system allows the developer to re-run the designer that created the first part of MyPartialClass without fear that this action would overwrite the code in her half of MyPartialClass. It also allows the developer to work with a relatively small implementation of MyPartialClass that contains only a few methods, without needing to wrestle with the potentially long and complex listings that are often found in auto-generated code.
The rules governing partial methods state that they:
Since they are primarily designed as a tool for use with auto-generated code, it is unlikely that most developers will ever design and write both halves of a partial method. However, the SQL Designer does make heavy use of partial methods, so many LINQ developers will want to understand this technology.
If you would like to receive an email when updates are made to this post, please register here
RSS
PingBack from
Good stuff .. very excited about partial methods :)
In my opinion, the power of them in C# is that when not implementing a body of a method, it will not be compiled into the output assembly.
If you look at the IL level, you'll see that the methods and method calls will be removed...
In an earlier post I showed how LINQ developers can connect to a database and write a simple query. This
I may be missing the point a bit (I hope so), but how does this differ significantly from abstract methods (other than not being compiled into the assembly when not required)?
Looking forward to partial methods being used in the SubSonic O/R generated code. Will save me a lot of headaches. This is a really useful feature unlike a few others which may be mildly termed as retrogressive - Lambda expressions for one comes to mind.
@Darren, this features comes in really handy when you want to modify code that has been generated for you - say when you are using code generated by an O/R mapper. When the db schema changes and you have to regenerate code, your changes are overwritten. Some code-generators use unsightly artifacts within comments to preserve user modified code. Goes without saying that the user must not go anywhere near those comment-markers. Partial methods offer a more robust and elegant solution.
Darren,
Whay Jay says above is true and very much to the point. Also, classes with abstract methods that have not been implemented cannot be instantiated, while those with partial methods can. Given these two classes:
public partial class MyPartialClass
{
partial void MyPartialMethod();
public void CallPartialMethod()
{
MyPartialMethod();
}
}
abstract class MyClass
public abstract void Foo();
It is legal to write this:
MyPartialClass m = new MyPartialClass();
But a compile time error is generated by this code:
MyClass m = new MyClass();
- CHarlie
Though you'd have to inherit, virtual methods would work just as well, right, and with fewer limitations?
Guess I miss the point, doesn't seem worth the effort to add this.
Are there plans to add high level, robust two-way template based code generation features to Visual Studio?
Charles: "Though you'd have to inherit, virtual methods would work just as well, right, and with fewer limitations?"
I implemented few years ago code-generation framework for ORM in C# 1.1 and using this virtual method approach. So instead of partial classes I used classes with virtual methods and derived other classes of those that implemented (by hand-coding) some of those methods. While this works, there was significant down-side to the present partial method possibility: Instead of *one class* (say "Person") that is defined in two *parts* I had to have TWO classes (say "Person_BASE" and "Person").
This becomes messy when the generated code has to create instances of classes: The generated code (Person_BASE) has to create then istances of Person creating ugly two-way dependencies between the classes. But it does work.
Is this available in VB, if not, any plans to add it? We generate code in both languages, this would solve a big problem for us if it was available in VB also.
This is standard GoF template pattern or strategy pattern. The way to use partial method to implement this is kind of strange. It can be easily implemented as abstract class, base class with override. Or simplely a class allow inheritance with capability to override - which has been well known in the industry.
Is there a way to control the order in which the partial methods get their code executed?
Hi,
Everything sounds nice, (you can modify generated code behaviour, blabla), but... ONLY when this generated code is so kind, that it bothers to call your partial method at all (e.g. there is no use for partial methods if code generator does not generate a call to the partial method). Am I right?
Looks quite messy and highly unpredictable to me, without knowing generated code inside out - e.g. when actually is partial method called (but then we are missing the point of generating it...)
I would still preffer a good design instead ;) (a base class with abstract/virtual methods, and partial classes for generated descendants. For me it is just lovely, and enough (as for my 15 years industry experience)).
But it may be very handy though, (e.g. when changing already bad design is not an option, but slight modification to custom code generator is).
cheers
I also do not see the value in this extra syntax. Seems to be too easy to misconstrue as well.
What if you had more than 2 partial classes with the same partial method, and what if both implementations were not empty?
Now, if partial methods worked like wrappers and the implementations stacked in some predictable order, then that would be useful. Otherwise, it's just a compiler-optimized override that the programmer should not have had to worry about in the first place.
bushi, the abstract/inherited strategy doesn't have any advantages over the partial strategy in the areas you're concerned about. There's no way to know (without, like you said, knowing the generated code intimately) when, or even if, the abstract method will be called. The fact that the generated code -has- a partial method is a pretty good indication that the method will be called, and the documentation (you do have documentation, right?) should describe when and how the method will be called. The exact same situation that you'd have with an abstract class, but much less complicated, and much more efficient.
I can see the value in this I suppose - you get the speed of being compiled into a single function ultimately (as opposed to a vtable virtual call) and have the choice of not implementing if desired.
It's very reminicent of the split between C++ headers and implementation files. You'd have the code generator spit out the header and one implementation file, with the partial methods declared as inline and implemented in a hand coded file.
I took a look at VS2008 and the intellisense does help with providing the (actual) implementation of the partial (latent) method. Like typing "override", which results in the list of virtual methods popping up, the list of partial methods popped up when you typed "partial". An implemented member disappears the next time you typed "partial".
Not having VS2008 would likely mean more work.
re: Ken: I'd guess the compiler wouldn't let you do that. I haven't tried it, but it'd be pretty silly. What if you provided two implementations of an overridden method in two halves of a partial class? Or two regular methods, for that matter?
re: Paul: The lack of intellisense wouldn't be any worse for the partial method than it would be for the abstract/virtual method, right?
At first I was surprised to see this option, since partially classes would be just fine in code-generation, in combination with abstracts. But if you look at the restrictions of usage, you can only use private voids. So it might be useful in cases where inheritance would be over-the-top.
This reminds me of the template method pattern which confused me at first. Now that I've thought about it I can see how this works. The template method pattern's goal is to define the steps of an algorithm while leaving the implementation of those steps to the inheriting class. It's a good method for leaving a system closed for modification but open for extension. With partial methods the goal isn't to leave the system open for extension but instead to make it easy to use auto generated code. The code generating tool will produce the code that defines the steps that make up an algorithm but it is up to the developer to provide the implementation of some/all of the steps. This can be done in a separate source file and written once without having to worry about it being overwritten. Also, in contrast to the template method pattern, an artificial inheritance hierarchy is not introduced into the model.
Partial methods? Whatever.
You know, sometimes terminology equals significant perspective shift such that it can count as innovation.
I am not sure this is it. In fact, it more resembles confusion.
There seems to be an aversion to OOA/M/D/P (Ojbect Oriented Modeling, Analysis, Design, Programming) techniques, although .Net itself is a good OOE (OO Environment) minus multiple inheritance, overuse of sealed, underuse of virtual, and underuse of Interfaces.
Ah well. Maybe there is a really good reason.
@mark: "the abstract/inherited strategy doesn't have any advantages over the partial strategy in the areas (...)". I think it has some important advantage:
When implementing virtual method YOU decide WHEN and IF you will call base method. So you have much greater controll on the actual code flow, and you DON'T necessary have to know anything about the base, since you can rewrite method completely, or prepare some object data before base class call, etc. This is what OOP is all about - descendants know better what's good for them, than base classes.
"The fact that the generated code -has- a partial method is a pretty good indication that the method will be called". I will answer the same: The fact that the method is declared virtual is a pretty good indication that the method will be called. Equally good, or equally bad indicator.
"and the documentation (...)" yeah, sure ;).
Still, I agree that this approach ("having something like virtuals without inheritance") may be sometimes usefull, but I still prefer OO techniques, as it enforces thoughtfull design.
I do see some limited value for this feature in certain areas, and obviously it was designed specifically with code generation in mind. But it seems to me that spending time adding a fairly complex feature to address a corner case was a waste, especially given all of the other features that developers have been begging for that are still missing. I wish the C# language team would spend more time addressing developer concerns and less time playing with pet features.
I think it a little similar with event delegation except the implementation of an event has to be in a program invoking the target class. right?
@Edward,
Not really, no. What you are describing is a kind of inversion of control. That is not what is happening here. Partial methods are simply a way of declaring that a method MIGHT exist without actually supplying the implementation for that method. The implementation, if any, must still be supplied within another partial declaration of the same class. If there is no implementation at the point when the class is compiled, the method simply disappears.
I think we need to understand the partial method's usefulness in context of partial classes. I think its a very useful feature for partial class development, specially classes that have complex logic specifically logic that involves series of steps. As each of these steps could be declared as partial methods and these partial methods are developed in separate partial classes. The original partial class doesn't have to wait for the other classes to complete before putting its logic together.
public partial class MyClass
{
partial void method1();
partial void method2();
public void MyMethod()
{
method1();
method2();
}
}
partial void method1()
{
//method1 implementation is now avaliable
}
partial void method2()
//method2 implementation is now avaliable
Maybe they should have just added the keyword 'protoype'.
What will be done if two developers give the implementation of partial method in their own partial classes? | http://blogs.msdn.com/charlie/archive/2007/11/11/partial-methods.aspx | crawl-002 | refinedweb | 2,370 | 61.06 |
nsg_get_pids - Return a list of a NUMA Scheduling Group's
process identifiers (libnuma library)
#include <numa.h>
int nsg_get_pids(
nsgid_t nsg,
pid_t *pidlist,
int numpids );
Specifies the NUMA Scheduling Group (NSG). Specifies an
array receiving the process identifiers of the specified
NSG. Specifies the maximum number of pid_t entries in
pidlist.
The nsg_get_pids() function returns a list of process IDs
of processes attached to the NSG in the buffer pointed to
by pidlist. The argument numpids specifies the number of
process IDs that can be accommodated in the buffer. The
list is terminated by a NULL entry. The required size of
the buffer can be obtained from the nsg_nattach member of
the nsgid_ds structure returned by the nsg_get() function.
As always, on a dynamically changing system, the number of
entries may be different by the time nsg_get_pids() is
called.
The effective user ID of the calling process must be equal
to the value of nsg_perm.cuid or nsg_perm.uid in the associated
nsgid_ds structure; or the calling process must
have read permissions to the NSG.
Success. However, if errno is set to E2BIG on a successful
return, more processes than numpids were available. Failure.
In this case, errno is set to indicate the error.
If the nsg_get_pids() function fails, it sets errno to one
of the following values for the specified condition: The
calling process does not have read permission. The
pidlist argument specifies an invalid address. The NSG
argument does not specify a valid NSG identifier.
Functions: nsg_attach_pid(3), nsg_get(3), nsg_get_nsgs(3),
numa_intro(3)
Files: numa_types(4)
nsg_get_pids(3) | https://nixdoc.net/man-pages/Tru64/man3/nsg_get_pids.3.html | CC-MAIN-2022-21 | refinedweb | 261 | 57.37 |
The
**This project is still in work. I hope the final version will be more beautiful.
Preparation:
Relay connection
- Connect relay to RPI 3. In my case i used GPIO12 pin for data , 5v for power and you can choose any GND.
You can test the relay with shell script, just create a simple sh script:
nano open.sh chmod +x open.sh sh open.sh
paste the code below and run it
Script code:
#!/bin/bash echo 12 > /sys/class/gpio/export echo out > /sys/class/gpio/gpio12/direction echo 0 > /sys/class/gpio/gpio12/value ping -c 1 localhost echo 12 > /sys/class/gpio/export echo out > /sys/class/gpio/gpio12/direction echo 1 > /sys/class/gpio/gpio12/value
Camera connection
- Connect camera module and enable it in raspi-config:
Open the raspi-config tool from the Terminal:
sudo raspi-config
Select Enable camera and hit Enter, then go to Finish and you'll be prompted to reboot.
To test that the system is installed and working, try the following command:
raspistill -v -o test.jpg
Led Connection
Connect your led to any gpio you want + GND. In my case i used GPIO16 for green led and GPIO26 for red. When you are done, test it:
Create 2 simple python scripts for green and red led with following content:
from gpiozero import LED from time import sleep led = LED(16) while True: led.on() sleep(3) led.off() led.cleanup()
from gpiozero import LED from time import sleep led = LED(26) while True: led.on() sleep(3) led.off() led.cleanup()
And then test it. If led's are glowing, then everything works good.
python led.py python led2.py
Face Recognition Script
Install this module from pypi using pip3(or pip2 for Python 2):
pip3 install face_recognition
Create directory "pic" and "unknown" in Documents for example and place there some face pics of people you know. My case it's ("/home/pi/Documents/pic/") and ("/home/pi/Documents/unknown/").
Create python script with following code
import face_recognition import picamera import numpy as np import os camera = picamera.PiCamera() camera.resolution = (320, 240) output = np.empty((240, 320, 3), dtype=np.uint8) print("Loading known face image(s)") ep_image = face_recognition.load_image_file("/home/pi/Documents/pic/ep.jpg") ep_face_encoding = face_recognition.face_encodings(ep_image)[0] vl_image = face_recognition.load_image_file("/home/pi/Documents/pic/vl.jpg") vl_face_encoding = face_recognition.face_encodings(vl_image)([ep_face_encoding,vl_face_encoding], face_encoding) name = "<Unknown Person>" os.system("python /home/pi/led2.py &") import time date_string = time.strftime("%Y-%m-%d-%H:%M:%S") camera.capture("/home/pi/Documents/unknown/image-" + date_string + ".jpg")
Test it
python facerec.py
RFIDConnection
Pins:
We need this to connect our RFID module to Raspberry pi 1.
- Preparation
$ sudo nano /etc/modprobe.d/raspi-blacklist.conf #blacklist spi-bcm2708 $ sudo apt-get install python-dev $ git clone $ cd SPI-Py $ sudo python setup.py install
- read.py When the script finds authorized card, it opens user picture on the remote RPI 3 (runs led scripts), then it opens the door.
import MFRC522 import signal import os continue_reading = True MIFAREReader = MFRC522.MFRC522()...Read more »
very impressive! I will set this up soon! | https://hackaday.io/project/25716-smart-intercom | CC-MAIN-2020-05 | refinedweb | 523 | 52.36 |
strcspn() prototype
size_t strcspn( const char *dest, const char *src );
If either src or dest does not point to a null terminated byte string, the behaviour of
strcspn() function is undefined.
It is defined in <cstring> header file.
strcspn() Parameters
dest: Pointer to a null terminated string to be searched.
src: Pointer to a null terminated string containing the characters to search for.
strcspn() Return value
The
strcspn() function returns number of characters in dest before the first occurrence of any characters present in src.
Example: How strcspn() function works
#include <cstring> #include <iostream> using namespace std; int main() { char num[] = "0123456789"; char code[] = "ceQasieoLPqa4xz10Iyq"; size_t result = strcspn(code, num); if (result < strlen(code)) cout << "First occurrence of number in " << code << " is at position " << result; else cout << code << " does not contain numbers"; return 0; }
When you run the program, the output will be:
First occurrence of number in ceQasieoLPqa4xz10Iyq is at position 12 | https://www.programiz.com/cpp-programming/library-function/cstring/strcspn | CC-MAIN-2020-16 | refinedweb | 153 | 54.36 |
Musings of a Client Platform Guy
If you want to see a contrasting online shopping experience to Otto, you could do worse than look at fnac.com. FNAC are in many ways the French equivalent of Best Buy, selling all things electronic: cameras, MP3 players, televisions, PCs. To coincide with the Windows Vista launch, they've produced a WPF-based next-generation shopping experience.
This application is nicely done. Rather than go with an XBAP, they've opted to use the ClickOnce capabilities of the .NET Framework to deliver a client experience that runs outside of the browser but is still a seamless, zero-footprint install that doesn't require administrator rights.
In many ways, this is an interesting contrast to Otto. Otto really uses the 3D capabilities of the platform to make the experience feel as close as possible to a real-world clothes shopping experience, with virtual models that act as digital mannequins for their clothes. fnac.com on the other hand have recognized the different way that consumers shop for electronic equipment, which is far less about what items "go" together, and much more about a feature-by-feature comparison that enables you to narrow down from an implausibly large selection of choices to a shortlist. If you're buying a laptop as a consumer, you're probably only going to buy one at a time: the optimization here is to ensure that you really feel as if you've been able to make the right decision based on the combination of features you're looking for at a price point.
The second screenshot (left) really demonstrates this well - by presenting the various choices using a metaphor of a fanned hand of playing cards, it's a dense information visualization that highlights the key information and allows you to use the buttons at the top to refine or narrow down the search. At the bottom of the screen, you'll see the total number of products in a little thumbnail-esque view that gives you a sense of how many of the items are being viewed at the current time. As you narrow down your selection (e.g. by searching only for PCs with Windows Vista pre-installed), the others fade out and a very neat animation brings the filtered view to the forefront. By clicking on any one item, you zoom into a different view that gives you a lot more feature information on the product, highlights applicable accessories and service plans, and ultimately allows you to compare two products side-by-side.
I really like this application: it's subtle and well thought through. There's nothing gratuitous about the way it uses animation or styles: everything is done to enhance the user experience, and that's of course the way it should be. With power comes responsibility, and all that...
You can run the application from the fnac.com site (the usual caveats apply about having .NET Framework 3.0 installed). One important warning - there's a minor glitch in the current release that prevents it executing successfully on machines that aren't set to the French locale. If you're affected, you'll see a message box with no text, just an OK button, which exits the application. To fix this on Windows Vista, go to the Control Panel and choose Regional and Language Options -> Change the date, time or number format; set the listbox here to French, and you'll be all set. (Don't forget to change it back again afterwards.) Fortunately, the use of ClickOnce means that it'll be a simple fix for the FNAC team to silently deploy.
Are you having fun yet? Six great WPF applications so far, with plenty of others in the pipeline...
Could you provide a direct link to the application ?
I can't figure out where to access it from the site (my french is very bad).
From the last link on the page, click on the button "Lancer l'installation". From there, I think it's fairly straightforward. When the application first loads, you'll want to click on the green button at the bottom right hand corner of the screen to synchronize the latest product data.
Arrest me if I'm wrong, but these applications are 90% bling, and 10% usefulness...
"Neat", but not smart...
As a developer of the OTTO Store App it is very interesting to finally see another WPF app for online shopping. Really good work. I heard roumours about it before but never actually saw it. It seem that we had in parts similar ideas (a product card with details is coming to the front). But the final app feels very different though. Much more different then the existing html shopping websites for fnac products (electronic stuff) or otto products (clothes) feel today. And this is the big chance of wpf shops - the experience part of the shopping. The shopping experience had a very high priority for us.
Lets face it: most customers who buy in current webshop have a lack of time and know exactely what they need. That is webshopping status quo. They come because it is practical and not because of the shopping experience. The OTTO Store was planed exactely the other way around with the approach to get closer to a real shopping experience. (i want to write more about "Experience matters" soon on my blog) It was planed WITHOUT ANY limits in mind. Just afterwards we matched it to what is possible in WPF. And this is what made us satisfied with WPF - we had to cut less ideas and experience of then with any other technology i know (with flash as the closest competetory - but very different thought). With WPF we were able to offer the experience that we had in mind. But yes we had to pay for that: At the moment we reach less people then a traditional webshop. Vista is just out a few days so only time will solve that problem.
Stephan
Winter has finally set in with single digit temps and minus degrees wind chills but still no snow. WPF/Avalon
I can't find the "Lancer l'installation" !
both with FireFox search and my eyes :)
I was planning to use it in my XAML presentation that I've made yesterday at work (We're one of the biggest ERP Software Companies in Turkey) to our whole Software Department. I must admit that they are all pretty impressed with both XAML and WPF. I hope that Delphi.Net would also be supported in the near future as a code behind language.
And thank you Tim Sneath for your Interview with Tom Relyea at Channel 9; I used your Q&A part and Tom Relyea's technical background parts :)
For the last part I must add that there's still a bit documentation problem in XAML. I got lot's of "the x tag doesn't exist in XAML namespace" errors while trying the examples from books, screencasts and even some from msdn Library.
I couldn't find the "Lancer l'installation" link in Firefox either, but it showed up in IE. From there I was able to get the installation to start, but a proxy authentication problem caused it to fail. | http://blogs.msdn.com/tims/archive/2007/02/02/great-wpf-applications-6-fnac-com.aspx | crawl-002 | refinedweb | 1,215 | 69.62 |
PSoC Creator 4.0: Import & modify components with customizers failuser_246598725 Mar 13, 2017 11:43 PM
Hi,
I just wanted to get in touch with the customizers, so I decided to make a new library and imported the demux component. After renaming the component and its files and also took care of the catalog placement, I build the project. Those steps seem to be the standard method when importing components, according to some (outdated) documents.
And voila... many error messages regarding not existing namespaces in actual context, etc. After digging a bit deeper into it, I figured out that the customizer assembly references have to be configured (this isn't mentioned anywhere!!!). So, I copied the references from the CyPrimitivesLibrary workspace, and most of the error messages went away. However, I don't want to search how to get rid of those errors. Instead, I want a clean documentation of customizers and how to create them. Cypress, you can't make statements like 'create your own customizers' and then a simple component import fails.
If there's a document describing that the assembly references also have to be configured, then it's my fault because I didn't found it. What about to make a tutorial on how to implement customizers in a clean and working way? Yes, there's a customizer API reference, but this doesn't really help without basic knowledge of how it has to be used.
Regards
Ralf
1. Re: PSoC Creator 4.0: Import & modify components with customizers failuser_342122993 Jan 24, 2017 3:59 AM (in response to user_246598725)My experience is that after importing and renaming a component with customizer, it is necessary to find and replace all occurrences of the previous component name in the entire project space. Customizer API files have a lot of them. I second your concern re lack of documentation on customizer creation process.
2. Re: PSoC Creator 4.0: Import & modify components with customizers failuser_246598725 Jan 24, 2017 4:55 AM (in response to user_246598725)
Hi odissey1,
it seems that the used demux component doesn't have any component names of the original component, so this seems not to be the issue.
There's also an error message after changing the assembly references when clicking the OK or APPLY button:
System.ApplicationException: Could not load exported type data for assembly 'CyFramework, Version=4.0.0.432, Culture=neutral, PublicKeyToken=null'. ---> System.TypeLoadException: Die Methode "DrawGlyph" im Typ "CyDesigner.Framework.CyLineIndicator" der Assembly "CyFramework, Version=4.0.0.432, Culture=neutral, PublicKeyToken=null"
Don't know if something's broken or if I'm doing something wrong. Anyway, importing and modifying components isn't as easy as Cypress states in some documents.
Regards
Ralf
3. Re: PSoC Creator 4.0: Import & modify components with customizers failuser_342122993 Jan 25, 2017 8:23 AM (in response to user_246598725)Ralf, I reproduced problem with demux component. I had recently contacted Cypress for support on same issue, when tried to make a customizer for nput pins to no avail. In this case it may be easier to write your own demux component with verilog.
4. Re: PSoC Creator 4.0: Import & modify components with customizers failuser_246598725 Jan 27, 2017 5:56 AM (in response to user_246598725)
Hi odissey,
did the support mention if this will be solved in the future?
Regards,
Ralf
5. Re: PSoC Creator 4.0: Import & modify components with customizers failuser_342122993 Jan 27, 2017 7:33 AM (in response to user_246598725)In short, they said that customizer design is too difficult to support. You may try to bug them also, try to elevate the case.
6. Re: PSoC Creator 4.0: Import & modify components with customizers failuser_246598725 Jan 29, 2017 11:29 PM (in response to user_246598725)
Then I don't know why they state that we can make our own customizers if the system is too complicated to support. I hope they'll find an easier system for the future, I like the concept.
Regards,
Ralf
7. Re: PSoC Creator 4.0: Import & modify components with customizers failanks Jan 30, 2017 9:56 PM (in response to user_246598725)1 of 1 people found this helpful
We don’t recommend customers to import primitive components . It’s also not recommended to import and modify complex components such as Capsense, BLE and USB
We have an enhanced default customizer in PSoC Creator 4.1 which allow more presentable customizers to be implemented without the extra overhead of C#.
We do not support making C# customizers . | https://community.cypress.com/thread/11316 | CC-MAIN-2018-43 | refinedweb | 754 | 56.35 |
We proudly want to participate in this week’s flurry of announcements around Apache Spark.
While we’re cooperating with Databricks in other areas like the implementation of openCypher on Spark and as an industry-partner of AMPLab, today I want to focus on the Neo4j Spark Connector.
Enabled by Neo4j 3.0
One of the important features of Neo4j 3.0 is Bolt, the new binary protocol with accompanying official drivers for Java, JavaScript, .NET and Python. That caused me to give implementing a connector to Apache Spark a try, and also to see how fast I can transfer data from Neo4j to Spark and back again.
The implementation was really straightforward. All the interaction with Neo4j is as simple as sending parameterized Cypher statements to the graph database to read, create and update nodes and relationships.
Features of the Spark Connector
So I started with implementing a Resilient Distributed Dataset (RDD) and then added the other Spark features, including GraphFrames, so that the connector now supports:
- RDD
- DataFrame
- GraphX
- GraphFrames
You can find more detailed information about it’s usage here; this is only a quick overview on how to get started.
Quickstart
I presume you already have Apache Spark installed. Then download, install and start Neo4j 3.0.
For a simple dataset of connected people, run the following two Cypher statements that create 1M people (with
:Person labels and
id,
name and
age attributes) and 1M
:KNOWS relationships, all in about a minute.
UNWIND range(1, 1000000) AS x CREATE (:Person {id: x, name: 'name' + x, age: x % 100}))
UNWIND range(1, 1000000) AS x MATCH (n) WHERE id(n) = x MATCH (m) WHERE id(m) = toInt(rand() * 1000000) CREATE (n)-[:KNOWS]->(m)
Spark Shell
Now we can start both spark-shell with our connector and GraphFrames as packages.
$SPARK_HOME/bin/spark-shell \ --conf spark.neo4j.bolt.password=
\ --packages neo4j-contrib:neo4j-spark-connector:1.0.0-RC1,\ graphframes:graphframes:0.1.0-spark1.6
And to start using it, we only do a quick RDD and GraphX demo and then look at GraphFrames.
RDD Demo
import org.neo4j.spark._ // statement to fetch nodes with id less than given value val query = "cypher runtime=compiled MATCH (n) where id(n) < {maxId} return id(n)" val params = Seq("maxId" -> 100000) Neo4jRowRDD(sc, query, params).count // res0: Long = 100000
GraphX Demo
import org.neo4j.spark._ val g = Neo4jGraph.loadGraph(sc, label1="Person", relTypes=Seq("KNOWS"), label2="Person") // g: org.apache.spark.graphx.Graph[Any,Int] = org.apache.spark.graphx.impl.GraphImpl@574985d // What's the size of the graph? g.vertices.count // res0: Long = 999937 g.edges.count // res1: Long = 999906 // let's run PageRank on this graph import org.apache.spark.graphx._ import org.apache.spark.graphx.lib._ val g2 = PageRank.run(g, numIter = 5) val v = g2.vertices.take(5) // v: Array[(org.apache.spark.graphx.VertexId, Double)] = // Array((185012,0.15), (612052,1.0153), (354796,0.15), (182316,0.15), (199516,0.385)) // save the PageRank data back to Neo4j, property-names are optional Neo4jGraph.saveGraph(sc, g2, nodeProp = "rank", relProp = null) // res2: (Long, Long) = (999937,0)
GraphFrames Demo
import org.neo4j.spark._ val labelPropertyPair = ("Person" -> "name") val relTypePropertyPair = ("KNOWS" -> null) val gdf = Neo4jGraphFrame(sqlContext, labelPropertyPair, relTypePropertyPair, labelPropertyPair) // gdf: org.graphframes.GraphFrame = GraphFrame(v:[id: bigint, prop: string], // e:[src: bigint, dst: bigint, prop: string]) gdf.edges.count // res2: Long = 999999 // pattern matching val results = gdf.find("(A)-[]->(B)").select("A","B").take(3) // results: Array[org.apache.spark.sql.Row] = Array([[159148,name159149],[31,name32]], // [[461182,name461183],[631,name632]], [[296686,name296687],[1031,name1032]])
Please Help
The connector, like our official drivers is licensed under the Apache License 2.0. The source code is available on GitHub and the connector and its releases are also listed on spark packages.
I would love to get some feedback of the things you liked (and didn’t) and that worked (or didn’t). That’s what the relase candidate versions are meant for, so please go ahead and raise GitHub Issues.
Ready to take a deeper dive into Neo4j? Click below to get your free copy of the Learning Neo4j ebook and catch up to speed with the world’s leading graph database. | https://neo4j.com/blog/neo4j-3-0-apache-spark-connector/ | CC-MAIN-2020-34 | refinedweb | 709 | 57.77 |
The Data Science Lab
Dr. James McCaffrey of Microsoft Research shows how to compute the Wasserstein distance and explains why it is often preferable to alternative distance functions, used to measure the distance between two probability distributions in machine learning projects.
A common task in machine learning is measuring the distance between two probability distributions. For example, suppose distribution P = (0.2, 0.5, 0.3) and distribution Q = (0.1, 0.8, 0.1). What is the distance between P and Q? The distance between two distributions can be used in several ways, including measuring the difference between two images, comparing a data sample to the population from which the sample was drawn, and measuring loss/error for distribution-based neural systems such as variational autoencoders (VAEs).
There are many different ways to measure the distance between two probability distributions. Some of the most commonly used distance functions are Kullback-Leibler divergence, symmetric Kullback-Leibler distance, Jensen-Shannon distance, and Hellinger distance. This article shows you how to compute the Wasserstein distance and explains why it is often preferable to alternative distance functions.
A good way to see where this article is headed is to take a look at the screenshot of a demo program in Figure 1. The demo program sets up a P distribution = (0.6, 0.1, 0.1, 0.1, 0.1) and a Q1 distribution = (0.1, 0.1, 0.6, 0.1, 0.1) and a Q2 distribution = (0.1, 0.1, 0.1, 0.1, 0.6). The graphs of the three distributions, and common sense, tell you that P is closer to Q1 than it is to Q2. The Wasserstein distance between (P, Q1) = 1.00 and Wasserstein(P, Q2) = 2.00 -- which is reasonable. However, the symmetric Kullback-Leibler distance between (P, Q1) and the distance between (P, Q2) are both 1.79 -- which doesn't make much sense.
This article assumes you have an intermediate or better familiarity with a C-family programming language. The demo program is implemented using Python. I also present a C# language version..
Understanding the Wasserstein DistanceThe Wasserstein distance (also known as Earth Mover Distance) is best explained by an example. Suppose P = (0.2, 0.1, 0.0, 0.0, 0.3, 0.4) and Q = (0.0, 0.5, 0.3, 0.0, 0.2, 0.0, 0.0). See Figure 2. If you think of distribution P as piles of dirt and distribution Q as holes, the Wasserstein distance is the minimum amount of work required to transfer all the dirt in P to the holes in Q.
The transfer can be accomplished in six steps.
In each transfer, the amount of work done is the flow (amount of dirt moved) times the distance. The Wasserstein distance is the total amount of work done. Put slightly differently, the Wasserstein distance between two distributions is the effort required to transform one distribution into the other.
The Kullback-Leibler DivergenceA common alternative distance function is the Kullback-Leibler (KL) divergence, and a slightly improved variation called symmetric Kullback-Leibler distance. Suppose distribution P = (0.2, 0.5, 0.3) and distribution Q = (0.1, 0.3, 0.7). The Kullback-Leibler divergence is computed as the sum of the p[i] times the log(p[i] / q[i]):
KL = (0.2 * log(0.2 / 0.1)) +
(0.5 * log(0.5 / 0.3)) +
(0.3 * log(0.3 / 0.7))
= (0.2 * 0.69) + (0.5 * 0.51) + (0.3 * -0.85)
= 0.14 + 0.25 - 0.25
= 0.14
Kullback-Leibler divergence can be implemented using Python like this:
import numpy as np
def kullback_leibler(p, q):
n = len(p)
sum = 0.0
for i in range(n):
sum += p[i] * np.log(p[i] / q[i])
return sum
Because of the division operation in the calculation, the Kullback-Leibler divergence is not symmetric, meaning KL(P, Q) != KL(Q, P) in general. The simplest solution to this problem is to define a symmetric Kullback-Leibler distance function as KLsym(P, Q) = KL(P, Q) + KL(Q, P). However, Kullback-Leibler still has the problem that if any of the values in the P or Q distributions are 0, you run into a division-by-zero problem. One way to deal with this is to add a tiny value, such as 1.0e-5, to all distribution values, but this has the feel of a hack. In short, the common Kullback-Leibler distance function has conceptual and engineering problems.
Implementing Wasserstein DistanceThere are many different variations of Wasserstein distance. There are versions for discrete distributions and for mathematically continuous distributions. There are versions where each data point is a single value such as 0.3 and there are versions where each data point is multi-valued, such as (0.4, 0.8). There are mathematical abstract generalizations called 2-Wasserstein, 3-Wasserstein, and so on. The version of Wasserstein distance presented in this article is for two discrete 1D probability distributions and is the 1-Wasserstein version.
The demo defines a my_wasserstein() function as:
Most of the algorithmic work is done by helper functions first_nonzero() and move_dirt(). In words, the function finds the first available dirt, then finds the first non-filled hole, then moves as much dirt as possible to the hole, and returns the amount of work done. The amount of work done on each transfer is accumulated.
Helper function first_nonzero() is simple:
def first_nonzero(vec):
dim = len(vec)
for i in range(dim):
if vec[i] > 0.0:
return i
return -1 # no empty cells found
Helper function move_dirt() is defined as:
def move_dirt(dirt, di, holes,
The condition dirt[di] <= holes[hi] means the amount of available dirt at [di] is not enough to fill the hole at [hi]. Therefore, all available dirt at [di] is moved. The condition dirt[di] > holes[hi] means the current dirt at [di] is more than there is room for in the holes at [hi] so only part of the dirt is used.
The Complete Demo ProgramThe complete Python version of the demo program is presented in Listing 1. The demo program defines separate helpers first_nonzero() and move_dirt(), and the calling my_wasserstein() function. An alternative structure is to wrap the three functions in a class. Another design alternative is to define first_nonzero() and move_dirt() as nested local functions inside the my_wasserstein() function.
Listing 1: Python Version of Wasserstein Distance
# wasserstein_demo.py
# Wasserstein distance from scratch
import numpy as np
def first_nonzero(vec):
dim = len(vec)
for i in range(dim):
if vec[i] > 0.0:
return i
return -1 # no empty cells found
def move_dirt(dirt, di, holes, hi):
# move as much dirt at [di] as possible to h
def kullback_leibler(p, q):
n = len(p)
sum = 0.0
for i in range(n):
sum += p[i] * np.log(p[i] / q[i])
return sum
def symmetric_kullback(p, q):
a = kullback_leibler(p, q)
b = kullback_leibler(q, p)
return a + b
def main():
print("\nBegin Wasserstein distance demo ")
P = np.array([0.6, 0.1, 0.1, 0.1, 0.1])
Q1 = np.array([0.1, 0.1, 0.6, 0.1, 0.1])
Q2 = np.array([0.1, 0.1, 0.1, 0.1, 0.6])
kl_p_q1 = symmetric_kullback(P, Q1)
kl_p_q2 = symmetric_kullback(P, Q2)
wass_p_q1 = my_wasserstein(P, Q1)
wass_p_q2 = my_wasserstein(P, Q2)
print("\nKullback-Leibler distances: ")
print("P to Q1 : %0.4f " % kl_p_q1)
print("P to Q2 : %0.4f " % kl_p_q2)
print("\nWasserstein distances: ")
print("P to Q1 : %0.4f " % wass_p_q1)
print("P to Q2 : %0.4f " % wass_p_q2)
print("\nEnd demo ")
if __name__ == "__main__":
main()
Because the Python language version of the demo program doesn't use any exotic libraries, it's easy to refactor the code to C# or any other c-family language. A C# version of the Wasserstein distance function is presented in Listing 2.
Listing 2: C# Version of Wasserstein Distance
using System;
namespace Wasserstein
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\nBegin demo \n");
double[] P = new double[]
{ 0.6, 0.1, 0.1, 0.1, 0.1 };
double[] Q1 = new double[]
{ 0.1, 0.1, 0.6, 0.1, 0.1 };
double[] Q2 = new double[]
{ 0.1, 0.1, 0.1, 0.1, 0.6 };
double wass_p_q1 = MyWasserstein(P, Q1);
double wass_p_q2 = MyWasserstein(P, Q2);
Console.WriteLine("Wasserstein(P, Q1) = " +
wass_p_q1.ToString("F4"));
Console.WriteLine("Wasserstein(P, Q2) = " +
wass_p_q2.ToString("F4"));
Console.WriteLine("\nEnd demo ");
Console.ReadLine();
} // Main
static int FirstNonZero(double[] vec)
{
int dim = vec.Length;
for (int i = 0; i < dim; ++i)
if (vec[i] > 0.0)
return i;
return -1;
}
static double MoveDirt(double[] dirt, int di,
double[] holes, int hi)
{
double flow = 0.0;
int dist = 0;
if (dirt[di] <= holes[hi])
{
flow = dirt[di];
dirt[di] = 0.0;
holes[hi] -= flow;
}
else if (dirt[di] > holes[hi])
{
flow = holes[hi];
dirt[di] -= flow;
holes[hi] = 0.0;
}
dist = Math.Abs(di - hi);
return flow * dist;
}
static double MyWasserstein(double[] p, double[] q)
{
double[] dirt = (double[])p.Clone();
double[] holes = (double[])q.Clone();
double totalWork = 0.0;
while (true)
{
int fromIdx = FirstNonZero(dirt);
int toIdx = FirstNonZero(holes);
if (fromIdx == -1 || toIdx == -1)
break;
double work = MoveDirt(dirt, fromIdx,
holes, toIdx);
totalWork += work;
}
return totalWork;
}
} // Program
} // ns
In a production environment you'd probably want to add error checking. For example, you should check that the P and Q distributions have the same length, the values in both sum to 1.0, and so on.
Wrapping UpIn informal usage, the term "metric" means any kind of numerical measurement. But in the context of measuring the distance between two distributions the term "metric" describes a distance function that has three nice mathematical characteristics:
The Wasserstein distance function satisfies all three conditions and so it is a formal distance metric. Many common distance functions do not meet one or more of these conditions. For example, Kullback-Leibler divergence meets only condition 1. Symmetric Kullback-Leibler distance meets conditions 1 and 2 but not 3.
Variations of the Wasserstein distance function are used in several machine learning scenarios. For example, standard generative adversarial networks (GANs) use Kullback-Leibler divergence as a loss/error function, but WGANs (Wasserstein GANs) use the more robust Wassersein distance.
About the Author
Dr. James McCaffrey works for Microsoft Research in Redmond, Wash. He has worked on several Microsoft products including Azure and Bing. James | https://visualstudiomagazine.com/articles/2021/08/16/wasserstein-distance.aspx | CC-MAIN-2022-21 | refinedweb | 1,734 | 65.62 |
hello,\nI am newbie in c++ and want to have good proggramer in it. I want\nto ask some question\n1)I downlaoded some .cpp files and found some have iostream.h while\nsome have only\n#include <iostream>\nusing namespace std;\nwhats difference between them?\n2) former include works in turbo C++ compiler but later not works why??\n3) which is most used good debugging facility provider compiler for\nWindows and Linux to do c++ programming?\n4) Also in world C++ programming mean its console based programming or\nvisual c++ programming?\n5) which is mostly used way to do c++ programming on console(Dos based)\nor on windows?\nThanks,\nrahul | https://www.thecodingforums.com/threads/newbie-to-c-programming.290405/ | CC-MAIN-2020-16 | refinedweb | 111 | 59.9 |
We have created a custom class, say
Person, and use it in a unit test.
void TestPerson::testEquality() { Person p1("Alice", 42); Person p2("Bob", 37); QCOMPARE(p1, p2); }
The unit test fails with this message.
FAIL! : TestPerson::testEquality() Compared values are not the same Loc: [../QComparePrint/TestPerson.cpp(8)]
This message does not tell us how the two
Person objects differ. We would like to see this message as we would see it for any type known to
QCOMPARE.
FAIL! : TestPerson::testEquality() Compared values are not the same Actual (p1): "Person(Alice, 42)" Expected (p2): "Person(Bob, 37)" Loc: [../QComparePrint/TestPerson.cpp(16)]
How do we achieve such a pretty-printed output for
QCOMPARE?
The solution turns out to be very simple. The QCOMPARE documentation gives the crucial hint.
For your own classes, you can use QTest::toString() to format values for outputting into the test log.
Unfortunately, the documentation links to the first overload of
QTest::toString(), which is irrelevant for our problem. If we don’t give up and scroll down to the last overload of
QTest::toString(), we will be rewarded. It suggests to overload
toString() in the namespace of our class
Person. Using the example from the documentation, we can quickly come up with our own overload of
toString().
char *toString(const Person &p) { return QTest::toString("Person(" + p.firstName() + ", " + QString::number(p.age()) + ")"); }
Our overload assembles a formatted string of a
Person object and passes this string to
QTest::toString(const QString &value).
If we use
QCOMPARE on
Person objects only in one test class, we add our new
toString() function to the source file of this test class. If we use it in several test classes, we put the function in a custom test library containing common test functionality.
You can find the example code on github. | http://www.embeddeduse.com/2017/10/07/pretty-printing-output-for-qcompare/ | CC-MAIN-2017-51 | refinedweb | 304 | 65.22 |
0
I have had an issue with getline(cin,string) in several of my programs. The program does not allow the user to input information after the cout statement preceding getline(cin,string). Below is an example code of the issue I am having(Btw I am using code::blocks with GNU compiler):
#include <iostream> #include <cstring> #include <cstdlib> using namespace std; int main() { int option; string name; cout<< "1. Yes"<<endl<< "2. No"<<endl; cout<< "would you like to see if there is an issue with this code: "; cin>>option; while(option == 1) { cout<< "Please enter your name: "<<endl; getline(cin,name); cout<<"Your name is: " << name<< endl; name.clear(); cout<< "1. Yes"<< endl<< "2. No"<<endl; cout<< "Would you like to enter another name? "<<endl; cin>>option; } return 0; } | https://www.daniweb.com/programming/software-development/threads/364623/getline-cin-string-issue | CC-MAIN-2016-50 | refinedweb | 131 | 73.78 |
C Program For Palindrome String – What is Palindrome? A palindrome is a sequence of characters which reads the same backward as forward. A palindrome could be a word, phrase, number, or other sequences of characters. such as madam or racecar.
Palindrome Word Examples:
Madam, Racecar, Radar, Etc.
C Program For Palindrome
If you are looking for a palindrome string in C program, this article will help you to learn how to write palindrome program in C language. Just go through this C program for palindrome to check whether a string is palindrome or not. After going through this C programming tutorial, you will be able to write a C palindrome program.
C Programming Tutorials
C Program For Palindrome Numbers
C Program To Reverse a String with Using Function
C Program To Reverse a String without Using Function
C Program To Reverse a String Using Recursion
C Program To Reverse a String Using Pointers
C Program For Palindrome String
Learn how to write a Palindrome program in C language. Writing a C program to check whether a string is a palindrome or not can be done using various techniques, but here in this program, we show how to write palindrome program in a proper way.
This is the eighth C programming example in the series, it helps newbies, students and B.Tech graduates in enhancing C programming and land on their dream job. All the best guys in learning c programming with coding compiler website. Happy Learning.
C Program For Palindrome Source Code
Copy paste the below source code or write your own logic into C compilers and run the program to see the result.
#include <stdio.h> #include <string.h> int main() { //Variables declaration char string1[20]; int i, length; int flag = 0; //Reading a string from user printf("Enter a string:"); scanf("%s", string1); length = strlen(string1); //checking whether a string is palindrome or not for(i=0;i < length ;i++) { if(string1[i] != string1[length-i-1]) { flag = 1; break; } } if (flag) { printf("%s is not a palindrome", string1); } else { printf("%s is a palindrome", string1); } return 0; }
C PROGRAM FOR PALINDROME OUTPUT
After you compile and run the above program, your C compiler asks you to enter a string to check whether entered string is palindrome or not. After you enter a string, the programming logic will check and show result like below expected output.
Example-1
Enter a string:
Radar
Radar is a palindrome
Example-2
Enter a string:
King
King is not a palindrome | https://codingcompiler.com/c-program-for-palindrome-string/ | CC-MAIN-2020-16 | refinedweb | 419 | 66.98 |
This is a sequel of previous post Sangria without case classes where I’m exploring shapeless in conjunction with the awesome Sangria lib. Mind this is total exploration and chances are (actually very likely) that it is possible to do simpler code to achieve the same effect.
In this post we will see shapeless
HMaps and again, use the sangria-akka-http-example as basis for our adventure.
A quick refresh of what is going on here. Sangria is a awesome GraphQL lib for scala. It uses case classes in the documentation and provide a set of macros to derive some stuff from them. What is great, but, I’m trying to expose dynamic content objects no known at compile time.
HMaps resembles C++ POCO Dynamic Var lib. I’m not comparing exactly, but this allows us to create dynamic type safe
structs at runtime. Of course the API is quite different and
ugly if compared to what shapeless did taking advantage of the scala type system.
For my scenario, I defined a parametrized class
class PersistentIS[K, V] and just three implicits to start. Let’s take a look:
// SchemaDefinition.scala // ... class PersistentIS[K, V] // Maps a String to a Int value implicit val stringToInt = new PersistentIS[String, Int] // Maps a String to a String value implicit val stringToString = new PersistentIS[String, String] // Maps a String to another full PersistentIS implicit def stringToNested = new PersistentIS[String, HMap[PersistentIS]] // sample instance of a HMap supporting the provided implicit mappings val author = HMap[PersistentIS]("name" → "Josh", "age" → 33)
Wow, looks like a bunch of empty classes. The first occurency of
HMap is in the implicit definition of the maping from
String to a
PersistentIS, that happens to be wrapped in a
HMap. In order to create a instance of our
PersistentIS[K, V], just do like in the last line of the sample code above.
Now it is time to define our GraphQL
ObjectType:
// SchemaDefinition.scala // ... lazy val AuthorType = ObjectType( "Author", "sample author", () ⇒ fields[CharacterRepo, HMap[PersistentIS]]( Field("name", StringType, Some("Author name"), resolve = defaultResolve[String] ), Field("age", IntType, Some("Author age"), resolve = ctx ⇒ ctx.value.get[String, Int]("age").get ) )) // Notice the resolve hard coded here. Could be a database returned map val Query = ObjectType( "Query", fields[CharacterRepo, Unit]( Field("author", AuthorType, resolve = ctx ⇒ HMap[PersistentIS]("name" → "Josh", "age" → 33)), Field("book", BookType, // ...
There is a trick here. The resolvers are different and I’ll show why and how in a minute. First take a look at the
age resolve function. It is a normal Sangria way to resolve a field from a
Val stored in the
Context here named
ctx . That is, the query resolver returns a Value of type
HMap[PersistentIS] and this resolve function extracts the needed field from it.
The point is that we need to know the type of the result value (a
Int for
age) but also the name of the field. I wanted to get rid of both and use just
defaultResolve but so far I couldn’t wipe them. But at least the field name I managed to get rid of. Not that the code that I’m showing below has the sole purpose to get rid of the field name while extracting it from the
HMap[PersistentIS]. The main goal here is a more dynamic configuration of GraphQL as well as its resolve functions.
Here we go! A lot of code at first but in summary what is involved is a type class that defines a get method, instances of this type class for
Int and
String. And as a extra step the definition of the
defaultResolve[Res]:
// SchemaDefinition.scala // ... // Here the type class that gets values V from HMap[PersistentIS] given a key value K trait PersistentGet[K, V] { def get(k: K, m: HMap[PersistentIS]): V } // Here the conventional way to add the summoner (apply) and a instance helper object PersistentGet { // This allows for implicit resolution via PersistentGet[String, Int], for example def apply[K, V](implicit getter: PersistentGet[K, V]) = getter // Helps instantiate a new PersistentGet[K, V], takes as parameter the function that does the actuall work // against the HMap[PersistentIS] def instance[K, V](f: ((K, HMap[PersistentIS]) ⇒ V)) = new PersistentGet[K, V] { override def get(k: K, m: HMap[PersistentIS]): V = { f(k, m) } } } // Finally the two implementations implicit val getString = PersistentGet.instance[String, String]((k, m) ⇒ m.get[String, String](k).get) implicit val getInt = PersistentGet.instance[String, Int]((k, m) ⇒ m.get[String, Int](k).get)
Ok I know, looks like lots of code, etc, etc. But to be fair when you start working with type classes and concepts you also find in Haskell and Cats, you have a thinking shift. It is like you start to see code in multiple dimensions instead of the usual linear roll from the top to the bottom of the file and you are ok to write, read and luckily understand code.
The code above is commented, so no extra info to add. Now the most confusing part - must confess - of the code. The
defaultResolve signature:
def defaultResolve[Res] (implicit getter: PersistentGet[String, Res]) : (Context[CharacterRepo, HMap[PersistentIS]] => Action[CharacterRepo, Res]) = ctx ⇒ getter.get(ctx.field.name, ctx.value)
Go back to the second snippet, you’ll quickly grasp that
defaultResolve[String] is actually returning a resolve function as required by Sangria. There is nothing special here actually. Just pay attention to the implicit getter that is resolved based on
[Res]. Using this getter we then extract the value from the context value, a
HMap[PersistentIS] and return it as
Res that happen to be
Int or
String.
I wanted to remove the type parameter from
defaultResolve[String] and use just
defaultResolve but maybe after abstracting the whole generation of the GrpahQL
ObjectType this will work.
Conclusion
HMaps is quite powerful and using it caused no impact in the GrpahQL exposed API, everything works normal. It results in a more dynamic behavior when compared to
Records that requires a macro to generate the appropriate labeled
HList.
I’m
in love with shapeless. This thing is simply mind blowing. I thought I would be using labeled
HLists some how. But not sure if possible due to the lack of information at compile time to get singleton types, etc. Well, need to investigate more and hope this investigation can result in another post.
Happy shapeless! | https://paulosuzart.github.io/blog/2017/07/29/sangria-without-case-classes-pt2/ | CC-MAIN-2021-21 | refinedweb | 1,066 | 53.1 |
NOTE: This article has been updated to use the new Sentry SDK
Prereqs:
- Sentry — Open-source error tracking that helps developers monitor and fix crashes in real time.
- @sentry/browser — Sentry SDK for JavaScript
- Webpack — Webpack is an open-source JavaScript module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.
If you’re like us at INTURN, you’ve found great value in having live error tracking integrated with your apps. Not only can you see if there are any issues in your production applications, but you can hook up error tracking to any environment and see when and where an error is thrown. After doing some research, we chose Sentry for our error tracking because of its ability to track in multiple environments, and across multiple releases.
When hooking this up to our front-end application, we used React’s Error Boundaries to manage our calls to Sentry with this bit of code:
import React from 'react';
import InternalErrorBoundary from 'react-error-boundary';
import * as Sentry from '@sentry/browser';const defaultOnErrorHandler = (error, stack) => {
console.error(error, stack); Sentry.captureException(error);
};const ErrorBoundary = props => (
<InternalErrorBoundary
onError={defaultOnErrorHandler}
{...props}
/>
);export default ErrorBoundary;
This way, whenever an Error Boundary is hit, we send a request to Sentry with the error and stack information. While we have a few other custom exceptions, the majority of the errors in our app are reported this way. At the end of the day, it was a simple way to get a ton of information about any errors our users see.
After some time using Sentry in our production app, we noticed a couple issues with how our errors were being reported. The first issue was that we had no context in terms of which version of our software was throwing this error. The second, and most important, was that we were getting minified code in our reports, which made it difficult to figure out where the actual issue was in our files. We decided to make these two improvements to our Sentry setup:
- Adding versions to our Sentry reporting by using git’s SHA-1 hash
- Adding source maps to our error traces
Adding versions to Sentry seemed like the low-hanging fruit, so we decided to tackle that first. In setting up Sentry, we had created a
sentry.js file that housed our configuration for Sentry (if you need help doing this, see the Sentry docs here). This config accepts a
release key, and since we already pass that into our build command as
process.env.GIT_SHA1, we added that to our Sentry config. And just like that, errors were attached to a specific git hash!
Now for adding source maps. The easiest solution was to build and bundle them with our application, but there are many obvious issues with doing this (security, bundle size, etc.). So we did some digging, and the first thing that we found was sentry-webpack-plugin, which we were excited about. Reading the docs, it seemed like a pretty simple setup to get source maps hooked up to Sentry.
Unfortunately, two days later, we still couldn’t figure out how to get it working. We re-read the docs and tried every configuration that might make sense, but still got nothing. We weren’t even seeing files attempting to be uploaded to Sentry (if you had success with this plugin, please let us know what you did!).
This is when frustration started to kick in.
After no success with the plugin, we decided to try using Sentry’s CLI tool, sentry-cli. The first step was to
yarn add -D @sentry/cli. Then, we needed to figure out how to use sentry-cli. After reading the docs here, we were able to access our projects with this command:
yarn sentry-cli --auth-token=${SENTRY_API_KEY} projects --org={SENTRY_ORG} list
NOTE: If you haven’t created an API Key for Sentry, you can do so by following this link (just make sure to enable the
project:write option or you won’t be able to upload your source maps).
Now that we were able to access the project, let’s try to create a release using the following command:
yarn sentry-cli --auth-token=${SENTRY_API_KEY} releases --org={SENTRY_ORG} --project={SENTRY_PROJECT_NAME} new test-release
This creates a new release in Sentry called
test-release , which you should be able to see in your Sentry web app.
NOTE: If you are using a git hash for your release name, the title of the release will be shown as a short version of that hash. However, actual release name is the full git hash. This threw us for quite some time, but hopefully our pain can save you some.
The next step is to upload some source maps to a release, but first, we need some generated source maps to upload.
During your build process, you want to make sure that you build source map files. For us, this meant turning the
sourceMap option on in
UglifyJsPlugin , and adding
SourceMapDevToolPlugin to our build with the following configuration (appending the
sourceMappingURL is required in Sentry’s docs):
new webpack.SourceMapDevToolPlugin({
filename: '[name].[hash].js.map',
exclude: ['vendor'],
append: '//# sourceMappingURL=[url]',
}),
Next, you need to upload these files to Sentry with the following command:
yarn sentry-cli --auth-token=${SENTRY_API_KEY} releases --org={SENTRY_ORG} --project={SENTRY_PROJECT_NAME} files ${GIT_SHA1} upload-sourcemaps "./dist/*.js.map" --url-prefix "~/dist/"
This assumes you’re using the git hash for your release name, but if you’re not, you just need to substitute the
GIT_SHA1 with whatever name or variable you decide to use for your release name. Just make sure it matches whatever is set in your app’s
sentry.js file.
Also, you’ll notice we added a
--url-prefix . This was the last big hurdle for us to jump over to get these source maps working. Essentially, Sentry’s source map paths must match the file names exactly. We noticed that since we’re using a
dist directory for our assets, we needed to prefix the url when we upload to Sentry. If you get stuck here, just check the names of the source maps in webpack’s output and compare it to the name of the uploaded files in your Sentry release.
One final step here is to delete the generated source maps before you put this app into production, so clients don’t see them. We do this in our builds by running
rm -rf ./dist/*.js.map after we upload.
And that’s it! You should see the source maps uploaded to your release in Sentry, and when you use a version of your app that has the same release name set in its
sentry.js file, the source maps will be applied in Sentry. | https://medium.com/inturn-eng/uploading-source-maps-to-sentry-with-webpack-ed29cc82b01d | CC-MAIN-2020-24 | refinedweb | 1,151 | 60.04 |
automatic line numbering help.
Hi I love notepad++ and use it for all my code editing. I’m hoping it can help with an issue I have with automation scripts for a program called “do it again”. This lightweight tool makes simple recordings of your actions and allows you to re-run them and loop them.
It saves them as text with an extension .dia. which can be opened and edited in any text editor. I usually use the find and replace function to reduce the delay time between each action which is great but sometimes I need to edit add or remove lines.
here is an example of the code…
MouseLDown 942 804 [3]
MouseLUp 942 804 [4]
Pause 40 [5]
MouseLDown 909 1003 [6]
MouseLUp 909 1003 [7]
Pause 40 [8]
MouseLDown 518 302 [9]
Pause 40 [10]
MouseLUp 518 302 [11]
Pause 40 [12]
I up till now for removal I just put a pause command in but if I want to add something I need to change the [number] at the end of the line for every following line so that it matches the line number.for example in notepad++ it looks like this…
3 MouseLDown 942 804 [3]
4 MouseLUp 942 804 [4]
5 Pause 40 [5]
6 MouseLDown 909 1003 [6]
7 MouseLUp 909 1003 [7]
8 Pause 40 [8]
9 MouseLDown 518 302 [9]
if I add a line
3 MouseLDown 942 804 [3]
4 MouseLUp 942 804 [4]
5 KeyDown 124 [ ]
6 Pause 40 [5]
7 MouseLDown 909 1003 [6]
8 MouseLUp 909 1003 [7]
9 Pause 40 [8]
10 MouseLDown 518 302 [9]
I would have to change it to
3 MouseLDown 942 804 [3]
4 MouseLUp 942 804 [4]
5 KeyDown 124 [ 5]
6 Pause 40 [6]
7 MouseLDown 909 1003 [7]
8 MouseLUp 909 1003 [8]
9 Pause 40 [9]
10 MouseLDown 518 302 [10]
to match the line number at the front. Simple to do with 10 lines of code but when you change line 3 of a 1000+ line script it is tiresome work.
is there some way of using find and replace or a macro so say
var x = 0
if line of text ends [?] {
if [?] != line number {
[?] == [line number]}
else {
x++}
}
else{
x++}
excuse my poor syntax.
now working smarter (though still a pain).
change extention to .csv
now using NP++ to replace " " with “,”
opening in excell
finding all rows with “pause” and deleting, this means all rows left contain 4 columns.
Column 4, which needs the row number, I am using the string ="[" &ROW()&"]" this fills the box as i need is [row number].
save as csv
return to NP++
replace"," with " "
save and change the extention back to .dia.
it is a long ass way of doing it but it is quicker than renumbering each line by hand.
anyone know how i can do this easier and all withing NP++??
Hello, james-robert-billington and All,
I supposed that each number beginning your code is, simply, the automatic line number feature and not a number, which does begin each line !
Well, the most simple way would be to use a Lua or Python script to achieve such a task ! In the meanwhile, I just propose you a semi-automatic way, which, first, writes an automatic numbering list and, secondly, use a regex search/replacement !
- First, place the cursor at column
1of the first line of the block of text which needs renumbering
So, for instance, assuming your text below, where a new line
KeyDown 124 [ ]has been added
MouseLDown 942 804 [3] MouseLUp 942 804 [4] KeyDown 124 [ ] Pause 40 [5] MouseLDown 909 1003 [6] MouseLUp 909 1003 [7] Pause 40 [8] MouseLDown 518 302 [9]
Now :
Place the cursor in line
1, at column
1, right before the word
MouseLDown( IMPORTANT )
Open the Column Editor… (
ALT + C)
Select the option
Number to Insert
Type
3, as Initial number :
Type
1as Increase by :
Type
1, as Repeat :
Set the
Leading zerosoption, although it’s not mandatory
Select the
Decdecimal format
Click on the
OKbutton
At once, any line downwards, will be updated with an automatic numbering, in column
1, till the last line of your file. Don’t panic ! With the following S/R, these numbers will disappear all at once !
03MouseLDown 942 804 [3] 04MouseLUp 942 804 [4] 05KeyDown 124 [ ] 06Pause 40 [5] 07MouseLDown 909 1003 [6] 08MouseLUp 909 1003 [7] 09Pause 40 [8] 10MouseLDown 518 302 [9] 11Some text 12Other text 13....
Finally, open the Replace dialog (
Ctrl + H)
SEARCH
(?-s)^0*(\d+)(.+[)(?:\d+|\x20+)]|^\d+
REPLACE
?2\2\1]
Select the
Regular expressionsearch mode
Set the
Wrap aroundoption
Click on the
Replace Allbutton
=> You should get the following text, with the correct renumbering of your code and the suppression of the leading numbers, located downwards :
MouseLDown 942 804 [3] MouseLUp 942 804 [4] KeyDown 124 [5] Pause 40 [6] MouseLDown 909 1003 [7] MouseLUp 909 1003 [8] Pause 40 [9] MouseLDown 518 302 [10] Some text Other text ...
Et voilà !
Note : Of course, this method also supposed that any line of code, located after the block of text to be modified, does not begin, itself, with some digits ! If it’s not the case, just tell me about it !
Best Regards,
guy038
P.S. :
You must be a fulfilled father, with your two adorable daughters !
All lines baring line 1, which does not have the [n] on it, begin with a word. this method is perfect. I will have to make a good old text file with the instructions, well at least the search and the replace strings, but still brilliant. thank you so much. And the girls are blessings even when annoying me :).
Hi , I would recommend you to install the Pythonscript plugin. So you can do all kind of document processing.
I had similar scripts for similar tasks - I’ve edited one so it will work for your case.
So once you have the plugin installed, this script will do the replacement in the whole active document
(assuming brackets are used only for numbers and do not appear in other context):
def cursorinfo(): # get caret info pos = editor.getCurrentPos() # current caret position LN = editor.lineFromPosition(pos) # current line number # LP = editor.positionFromLine(C) # buffer position at current line start return pos, LN # replace text in brackets with a number def replace_num(S, num): LC = S.find( "[" ) if LC >= 0 : RC = S.find( "]" ) number = str(num) S_new = S[0:LC + 1] + number + S[RC:] return S_new return S # process all text def process(): textL = [] for i in range (0, total): s = editor.getLine(i) # get text in line s = replace_num(s, i+1) textL.append(s) text = "".join(textL) return text pos, LN = cursorinfo() total = editor.getLineCount() # get lines total editor.setText( process() ) editor.gotoPos(pos) # restore caret position | https://community.notepad-plus-plus.org/topic/15933/automatic-line-numbering-help | CC-MAIN-2019-43 | refinedweb | 1,140 | 74.63 |
Tutorial: Create custom functions in Excel
Custom functions enable you to add new functions to Excel by defining those functions in JavaScript as part of an add-in. Users within Excel can access custom functions as they would any native function in Excel, such as
SUM(). You can create custom functions that perform simple tasks like calculations or more complex tasks such as streaming real-time data from the web into a worksheet.
In this tutorial, you will:
- Create a custom function add-in using the Yeoman generator for Office Add-ins.
- Use a prebuilt custom function to perform a simple calculation.
- Create a custom function that gets data from the web.
- Create a custom function that streams real-time data from the web.
Prerequisites
Node.js (the latest LTS version).
- Excel on Windows (version 1904 or later, connected to a Microsoft 365 subscription) or on the web
Create a custom functions project
To start, you'll create the code project to build your custom function add-in. The Yeoman generator for Office Add-ins will set up your project with some prebuilt custom functions that you can try out. If you have already run the custom functions quick start and generated a project, continue to use that project and skip to this step instead.
Run the following command to create an add-in project using the Yeoman generator:
yo office
Note
When you run the
yo officecommand,:
Excel Custom Functions Add-in project
- Choose a script type:
JavaScript
- What do you want to name your add-in?
starcount
The Yeoman generator will create the project files project.
cd starcount
Build the project.
npm run build
Note
Office Add-ins should use HTTPS, not HTTP, even when you are developing. If you are prompted to install a certificate after you run
npm run build, accept the prompt to install the certificate that the Yeoman generator provides.
Start the local web server, which runs in Node.js. You can try out the custom function add-in in Excel on the web or Windows.
To test your add-in in Excel on Windows or Mac, run the following command. When you run this command, the local web server will start and Excel will open with your add-in loaded.
npm run start:desktop
Try out a prebuilt custom function
The custom functions project that you created contains some prebuilt custom functions, defined within the ./src/functions/functions.js file. The ./manifest.xml file specifies that all custom functions belong to the
CONTOSO namespace. You'll use the CONTOSO namespace to access the custom functions in Excel.
Next you'll try out the
ADD custom function by completing the following steps:
In Excel, go to any cell and enter
=CONTOSO. Notice that the autocomplete menu shows the list of all functions in the
CONTOSOnamespace.
Run the
CONTOSO.ADDfunction, with numbers
10and
200as input parameters, by typing the value
=CONTOSO.ADD(10,200)in the cell and pressing enter.
The
ADD custom function computes the sum of the two numbers that you provided and returns the result of 210.
Create a custom function that requests data from the web
Integrating data from the Web is a great way to extend Excel through custom functions. Next you'll create a custom function named
getStarCount that shows how many stars a given Github repository possesses.
In the starcount project, find the file ./src/functions/functions.js and open it in your code editor.
In function.js, add the following code:
/** * Gets the star count for a given Github repository. * @customfunction * @param {string} userName string name of Github user or organization. * @param {string} repoName string name of the Github repository. * @return {number} number of stars given to a Github repository. */ async function getStarCount(userName, repoName) { try { //You can change this URL to any web request you want to work with. const url = "" + userName + "/" + repoName; const response = await fetch(url); //Expect that status code is in 200-299 range if (!response.ok) { throw new Error(response.statusText) } const jsonResponse = await response.json(); return jsonResponse.watchers_count; } catch (error) { return error; } } B1, type the text =CONTOSO.GETSTARCOUNT("OfficeDev", "Excel-Custom-Functions") and press enter. You should see that the result in cell B1 is the current number of stars given to the [Excel-Custom-Functions Github repository]().
Create a streaming asynchronous custom function
The
getStarCount function returns the number of stars a repository has at a specific moment in time. Custom functions can also return data that is continuously changing. These functions are called streaming functions. They must include an
invocation parameter which refers to the cell where the function was called from. The
invocation parameter is used to update the contents of the cell at any time.
In the following code sample, you'll notice that there are two functions,
currentTime and
clock. The
currentTime function is a static function that does not use streaming. It returns the date as a string. The
clock function uses the
currentTime function to provide the new time every second to a cell in Excel. It uses
invocation.setResult to deliver the time to the Excel cell and
invocation.onCanceled to handle what occurs when the function is canceled.
- In the starcount project, add the following code to ./src/functions/functions.js and save the file.
/** * Returns the current time * @returns {string} String with the current time formatted for the current locale. */ function currentTime() { return new Date().toLocaleTimeString(); } /** * Displays the current time once a second * @customfunction * @param {CustomFunctions.StreamingInvocation<string>} invocation Custom function invocation */ function clock(invocation) { const timer = setInterval(() => { const time = currentTime(); invocation.setResult(time); }, 1000); invocation.onCanceled = () => { clearInterval(timer); }; } C1, type the text =CONTOSO.CLOCK() and press enter. You should see the current date, which streams an update every second. While this clock is just a timer on a loop, you can use the same idea of setting a timer on more complex functions that make web requests for real-time data.
Next steps
Congratulations! You've created a new custom functions project, tried out a prebuilt function, created a custom function that requests data from the web, and created a custom function that streams data. Next, you can modify your project to use a shared runtime, making it easier for your function to interact with the task pane. Follow the steps in the following article: | https://docs.microsoft.com/en-us/office/dev/add-ins/tutorials/excel-tutorial-create-custom-functions | CC-MAIN-2020-45 | refinedweb | 1,055 | 57.47 |
Nov 18, 2013 04:20 PM|ojm37|LINK
I'm converting to using C# from VB and I have a question about the c# using directive as opposed to the VB includes directive.
I have a class in a namespace with a fairly long, descriptive name that I can shortcut in VB with the includes directive.
For example, in VB I have a class called "ThisLongClassName" in the Functions namespace with an enum defined something like:
Namespace Functions Public Class ThisLongClassName Public Sub New() 'Some code here End Sub Public Enum SOME_NAME VALUE0 = 0 VALUE1 = 1 VALUE2 = 2 ETC = 3 End Enum End Class End Namespace
In VB, I can just include Functions and then use it without specifying the namespace OR class name like this:
Dim SomeVal as Integer = SOME_NAME.Value0
When I try to do the same thing in C#, I get a compile error saying the SOME_NAME is not valid in the current context.
Is there a way to get C# to allow similar syntax ( int someVal = SOME_NAME.Value0 )? I've tried "using Functions.ThisLongClassName" without success.
TIA,
Contributor
4232 Points
Nov 18, 2013 05:05 PM|jsiahaan|LINK
Hi
You should use:
using Functions;
Open ThisLongClassName class and see what is the nameSpace in there, and then use that name space to use in "using" statement to reference.
Just a small help
Nov 18, 2013 05:19 PM|ojm37|LINK
Right. I know that, I want to shortcut the class name, not just the namespace name.
BTW, my "using Functions.ThisLongClassName" failed on compile. The compiler says "ThisLongClassName" is a type and not a namespace and that using can only be used on namespaces. So, maybe VB can use imports on BOTH namespaces AND types, but C# cannot?
TIA,
Star
9555 Points
Nov 18, 2013 07:42 PM|Paul Linton|LINK
I'm trying to understand how this works in VB to give you the C# method. I find it difficult to understand how the VB works as you say. What if the VB file is
Namespace Functions Public Class ThisLongClassName Public Sub New() End Sub Public Enum SOME_NAME VALUE0 = 0 End Enum End Class Public Class AnotherLongClassName Public Sub New() End Sub Public Enum SOME_NAME VALUE0 = 99 End Enum End Class End Namespace
You say that you just include Functions and don't have to make any reference to ThisLongClassName. How does VB know which SOME_NAME you are referring to?
In C# you can give an alias for a class.
using Fred=Functions.ThisLongClassName;
then you could refer to
Fred.SOME_NAME.VALUE0
I don't have easy access to VB to try to understand how the 'include' works but it doesn't make sense to me.
Contributor
4232 Points
Nov 19, 2013 10:15 AM|jsiahaan|LINK
Hi,
In C#, let say a class like this
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TunaTumureApi.Models { public class Person { public int Id { get; set; } public string Name { get; set; } } }
And then, in other function or class use "Person"
using System; using System.Collections.Generic; using System.Linq; using System.Web; using TunaTumureApi.Models; namespace TunaTumureApi.Controllers { public class UseClass { public Person Person { get; set; } public int MyNumber { get; set; } } }
NameSpace in "Person" class is "TunaTumureApi.Models" and then "using" in "UseClass" is "using TunaTumureApi.Models"
So nameSpace to be used in "using"
Please let me know if you need more explanation. Have fun
4 replies
Last post Nov 19, 2013 10:15 AM by jsiahaan | https://forums.asp.net/t/1951634.aspx?using+namespace+class | CC-MAIN-2017-43 | refinedweb | 585 | 63.8 |
When developing web applications with Vue.js, unless you're building a Single-Page Application (SPA), you'll want to connect multiple pages to a landing page to allow users to navigate through them. This is known as routing. Routing is the process by which a user is navigated to different pages on a website. Vue.js is a JavaScript framework used to create Single Page Apps, which means that this application is only loaded once from the server to the browser, and the browser does not need to reload when routing; instead, it simply requests these pages and they are loaded.
In this guide, we will learn how to do routing with Vue.js and take a deep dive into the various types of routing that can be done and how they can be done.
Routing in Vue.js is done with Vue Router, which works in tandem with the core Vue library to allow us to set up a routing system. We would like to use
vue-router in two scenarios in our project. We either want to use the router in an existing project or add it while creating a new project.
Integrating
vue-router into an existing project can be technical, and we will go over these details now. The first step would be to install the vue router package using the following command:
! npm install [email protected]
Once installed, navigate to the
src folder and create a folder called
router, followed by a file called
index.js in the
router folder, which will serve as our router configuration file. Our
src directory will now look like this:
In the
index.js file, let’s ensure that we paste the code below, which is the router configuration code:
import { createRouter, createWebHashHistory } from 'vue-router' import HomePage from '../views/HomePage.vue' const routes = [ { path: '/', name: 'home', component: HomePage }, ] const router = createRouter({ history: createWebHashHistory(), routes }) export default router
We have a
routes array that contains a single object, which could be multiple objects where each object represents a single route. For the time being, we only created the one that would redirect to the homepage component.
Each of these
routes objects is typically composed of the
path, which is the url path relative to the site's root, the
name, which serves as an identifier, and the
component, which we imported at the top of the page.
Aside from the route array, we set up the router instance at the bottom by creating a
createRouter() function and passing in the
history key values and the
routes array, and then we export the
router instance for use within our application.
To use this router configuration within our application, open the
main.js file in the
src folder,
import router from "./router", and then add
.use(router) between
createApp(App) and
.mount('#app') just as it is below:
import router from './router' createApp(App).use(router).mount('#app')
This
vue-router has been globally configured within our application, and the next step is to use it within our application. This is easily accomplished by including
<router-view /> within the
App.js template tag, which renders only the matched route:
<template> <router-view> </router-view></template> <script> export default { name: 'App', } </script>
Routes are usually created in the
router/index.js file's routes array, and these routes connect to components. It is a good practice to create a views folder where all page views will be stored. For example:
At this point we now know how to setup routes manually.
Note: All of this will be done for us if we use the
vue-clito install
vue-routerwhen creating our project.
<h4 id="installvuerouterwithvuecli">Install Vue Router With Vue CLI</h4>
If we are about to create a new project and believe that we'll make use of
vue-router, it is easier to do so while creating the project.
All we have to do is use Vue CLI to install the most recent version of
vue-router while manually selecting features in the process of creating our project:
Read and learn more about creating Vue.js project via our Guide to the Vue CLI!
As our application grows in size, the bundle size grows, causing our site to take longer to load. We can use
vue-router to implement lazy loading to avoid loading some specific routes until the user specifically requests them.
This is typically accomplished in the router configuration file by removing the
import statement at the top and replacing it with a dynamic import statement in the component option of our route:
import { createRouter, createWebHashHistory } from 'vue-router'; const routes = [ { path: '/', name: 'home', component: () => import(/* webpackChunkName: "home" */ '../views/HomePage.vue'), }, { path: '/about', name: 'about', component: () => import(/* webpackChunkName: "about" */ '../views/AboutPage.vue'), }, ]; const router = createRouter({ history: createWebHashHistory(), routes, }); export default router;
So far, we've been able to create routes, but how do we navigate within our application? We use the
<router-link> tag instead of the
<a> element in HTML to handle routing.
For example, if we want to create a navigation bar at the top of our application, we could do this in the
App.js file above the
<router-view/> tag so it shows on all routes:
<nav> <router-linkHome</router-link> | <router-linkAbout</router-link> </nav>
The router-link accepts the
to='path' attribute that takes the user to path of the component as have set when configuring route. This works like the
href='path``' attribute in HTML.
Using named routes allows us pass in the
name key that has access to the
name property which we set while configuring the routes instead of using the path by binding the data this way:
<router-link :About</router-link>
One advantage of using this method is in case we decide to change the route path for our large applications, we don’t need to start changing all links path which could be cumbersome.
Situations may arise that necessitate the use of dynamic routing to avoid unnecessary page repetition. For example, suppose we have a list of fruits and we want a which a user to be able to click on a specific fruit and only details about that fruit are displayed on a fruit-details page. In this case, we use dynamic routing.
We'd have two pages - one to showcase the fruits in a list and one to show the details of each fruit, which is a "blueprint" page to be populated with the fruit's details. We'll create the pages in the Vue folder and then add the routes to the
routes array:
import FruitsPage from '../views/FruitsPage.vue'; import FruitDetails from '../views/FruitDetails.vue'; const routes = [ { path: '/fruits', name: 'Fruits', component: FruitsPage, }, { path: '/fruits/:id', name: 'FruitDetails', component: FruitDetails, }, ];
We will notice that for the
FruitDetails page, we added a dynamic
id property so it gets the
id parameter and uses it to query the particular data that shows on that page using
$route.params in our template, thus making the route dynamic.
In the
FruitsPage, suppose we have an array of fruits which we loop into our application, we can wrap each fruit with a link alongside params this way:
<template> <h1>Fruits page</h1> <div : // dynamic linking by attaching the id as params <router-link : <h3>{{ fruit.name }}</h3> </router-link> </div> </template> <script> export default { data() { return { fruits: [ { id: 1, name: 'Apple', description: "Apples are an incredibly nutritious fruit.", }, { id: 2, name: 'Mango', description: 'A mango is an edible stone fruit produced by the tropical.', }, { id: 3, name: 'Banana', description: 'A banana is an elongated, edible fruit of the genus Musa.', }, ], }; }, }; </script>
At this point when a user clicks each fruit, it will take them to the
FruitDetails page where we can access the
id parameter and use it to identify which fruit's details should be shown in the
FruitDetails page.
So far we have seen how to pass down params to a particular page dynamically, let's now see how we can access that param in our
FruitDetails page. There are two ways we can access parameters in Vue - via
$route.params or making use of props:
The parameters are directly accessible via
$route.params:
<template> <h1>Fruit Details</h1> <p>This is fruit with the id of {{ $route.params.id }}</p> </template>
Or we can access it within our
data() method using
this:
<template> <h1>Fruit Details</h1> <p>This is fruit with the id of {{ id }}</p> </template> <script> export default { data() { return { id: this.$route.params.id, }; }, }; </script>
Another easy method to access data dynamically via routes is using props. We first have to set
props to
true in the routes configuration object:
{ path: '/fruits/:id', name: 'FruitDetails', component: FruitDetails, props: true, },
This way, all we have to do next is to add
props option to the
script tag and then make use of the props within our
template tag:
<template> <h1>Fruit Details</h1> <p>This is fruit with the id of {{ id }}</p> </template> <script> export default { props: ['id'], }; </script>
In the event that a user navigates to a non-existent route, Vue will load the page but without any components, producing an empty page. In this case, the best thing to do is display a 404 page with perhaps a button leading them to the homepage or wherever we believe they would like to go. This is easily handled by creating a component for our 404 page and then adding a 404 route to our router configuration file's routes array, but this time we will use a regular expression to catch all routes that have not been declared previously:
{ path: '/:catchAll(.*)', name: 'ErrorPage', component: ErrorPage, }
The
:catchAll is the dynamic segment which recieves a regular expression of
(.*) in which Vue Router uses to check if the route the user navigates to is defined in our router’s configuration file. If such routes do not exist, the user is directed to the component, which in our case is the
ErrorPage component:
<template> <h2>404 Page</h2> <p>This is a 404 page</p> <p>Visit home page <router-linkhere</router-link></p> </template>
In a situation where we want users to be redirected when they visit a specific route, for example, if we had a former route that we no longer use, we want users to be redirected to the new one when they visit that route. This is easily accomplished by adding a new object to our routes configuration array, with a
redirect field:
{ path: '/fruits', name: 'Fruits', component: FruitsPage, }, { path: '/all-frults', redirect: '/fruits', },
All the code above does is that if a user visits, the path
/all-fruits, it would redirect them to the
/fruits route.
So far, we've learned a lot about routing, but there's one more thing you'll want to know: how to perform programmatic navigation. We define programmatic navigation as a situation in which a user is redirected/directed based on a specific action that occurs on a route, such as a login or signup action, or by clicking a specific button, such as a "go back" button.
We can use the browser history to easily navigate backwards or forwards, depending on our preferences. If you recall, we have a
createRouter() function in the router configuration file where we set a
history value, allowing Vue router to keep track of our router history as we route through the web application.
This allows us to traverse the browser's history, based on a conditional such as a button click:
<template> <h1>Fruit Details</h1> <p>This is fruit with the id of {{ id }}</p> <button @Go Back</button> </template> <script> export default { props: ['id'], methods:{ goBack(){ this.$router.go(-1) } } }; </script>
We can also decide to go foward by using the
1 instead of
-1 and suppose we want to move by 2 steps we can use either
2 or
-2.
push() is typically used after an action has occurred and adds a new entry to the history stack. For example, if a user signs in successfully, we would like to be navigated to the dashboard page programmatically. This is accomplished by including the push method alongside the route's name:
this.$router.push({ name: 'Dashboard' });
Note: We must ensure that route is declared in our router configuration file, or else it will not work and will redirect us to the 404 page.
<h3 id="conclusion">Conclusion</h3>
Routing is one of the core functionalities of Vue. Unless you're building a Single-Page Application (SPA), you'll want to connect multiple pages to a landing page to allow users to navigate through them.
In this guide, we've taken a look at what routing is, how you can install the
vue-router in new and existing projects, how to perform lazy loading, navigate between routes, perform dynamic routing, access route parameters and peform programmatic navigation. | https://www.codevelop.art/guide-to-vue-router.html | CC-MAIN-2022-40 | refinedweb | 2,155 | 55.88 |
This how-to post will introduce you to building REST-based services using WCF. This series is split into three parts. Each part is built on the previous part.
WCF in .NET 3.5 has added features to its programming model to make it easy to build services which can be invoked using a REST-based approach. In this first part you will create a WCF endpoint using this new Web programming model. You will expose data through a URI-based REST mechanism returning XML-formatted data.
Select Start | All Programs | Microsoft Visual Studio 2008 | Microsoft Visual Studio 2008 to load the Visual Studio 2008 development environment.
Inside of Visual Studio 2008 select File | New | Web Site.
Select Empty Web Site as the template, and ensure that .NET Framework 3.5 is selected as the target framework version.
Select Location to be HTTP, then type the following as the URL:, select the Language to be Visual C#, and click OK.
Right-click on the project node in the Solution Explorer, select Add ASP.NET Folder from the context menu, and select App_Data from the submenu.
Repeat the last step, this time selecting App_Code as the ASP.NET Folder to add.
Right-click on the App_Data folder and select Add Existing Item. Browse to where you saved the Movie.mdf file and add the database file.
Right-click on the App_Code folder and select Add New Item. Select LINQ to SQL classes as the template, and MovieData.dbml as the Name. Press the Add button.
Open the Server Explorer (View | Server Explorer menu), expand Movie.mdf, expand the Tables node.
Drag and drop the director and movie tables onto the Object Relational Designer surface. This action generates classes you can use to work with data from the Music database.
Right-click on the App_Code folder and select Add New Item. Select Class as the template, and name the class DirectorService.cs. Click Add.
Open the file DirectorService.cs file.
After the using statements, add the following using statements:
using System.ServiceModel; using System.Runtime.Serialization; using System.Collections.Generic; using System.ServiceModel.Web; using System.ServiceModel.Activation;
Add a ServiceContract attribute to the top of the DirectorService class. Add an AspNetCompatibilityRequirements attribute, with a RequirementsMode property of AspNetCompatibilityRequirements.Allowed.
[ServiceContract()] [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)] public class DirectorService { public DirectorService() { // // TODO: Add constructor logic here // } }
After the closing brace of the DirectorService class, add a public class named DirectorResult. Add the DataContract attribute to this class, and set Name property to be "Movie" and the Namespace property to a blank string:
[DataContract(Namespace="", Name="Director")] public class DirectorResult { }
Add two public fields to DirectorResult class, both of type string, one named DirectorName and the other named Link. Add the DataMember attribute to both of these fields.
[DataContract(Namespace="", Name="Director")] public class DirectorResult { [DataMember] public string DirectorName;
[DataMember] public string Link; }
After the DirectorResult class, add another public class that derives from List<string>, this one named MovieList.
Add the CollectionDataContract attribute to the MovieLIst class. Set its ItemName property to "Movie", and the Namespace property to a blank string.
Add a default parameterless constructor to MovieList.
Add another constructor to MovieList, this one takes an IEnumerable<string> parameter, and calls the base class's constructor.
[CollectionDataContract(ItemName="Movie", Namespace="")] public class MovieList : List<string> { public MovieList() { } public MovieList(IEnumerable<string> movies) : base(movies) { } }
After the MovieList class, add another public class, this one named DirectorDetail. Add a DataContract attribute to the ArtistDetail class, and use "Director" as the value for the Name property and a blank string as the value of the Namespace property.
[DataContract(Namespace="", Name="Director")] public class DirectorDetail { [DataMember(Order=0)] public string DirectorName;
[DataMember(Order=1)] public MovieList Movies; }
Inside of the DirectorService class add a public method named GetAllDirectors that returns an array of DirectorResult. Add the OperationContract attribute to this method. Also add the WebGet attribute to this method and specify the UriTemplate property of the WebGet attribute to be "/".
[OperationContract] [WebGet(UriTemplate="/")] public DirectorResult[] GetAllDirectors() { }
Within the GetAllDirectors method, create an instance of the MovieDataDataContext class, named dc:
MovieDataDataContext dc = new MovieDataDataContext();
Get the URI of the incoming request and put it into a string variable. You can get this value from WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.
string currentUrl = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString();
Add a LINQ query to get all the directors from the data context, and select it into new instances of DirectorResults, selecting the name from the data and the link by creating a string from the directorname and the currentUri. Convert the result of the LINQ query to an array and return it. The contents of the GetAllDirectors procedure should look like the following:
MovieDataDataContext dc = new MovieDataDataContext();
string currentUrl = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString();
var result = from aDirector in dc.directors select new DirectorResult { DirectorName = aDirector .director_name, Link = String.Format("{0}{1}", currentUrl, aDirector .director_name) };
return result.ToArray();
Inside of the DirectorService class add a public method names GetDirector that returns an DirectorDetail class and takes a string parameter named director. Add the OperationContract attribute to this method. Also add the WebGet attribute to this method - and specify the UriTemplate property of the WebGet attribute to be "/{director}"
[OperationContract] [WebGet(UriTemplate="/{director}")] public DirectorDetail GetDirector(string director) { }
Inside of the GetDirector method, create an instance of the MovieDataDataContext object, named dc.
Use the MovieDataDataContext.directors with a LINQ query to find the particular director that is being queried. Create a DirectorDetail and use a subquery to fill in the MovieList property. Return the first item from the collection. The completed contents of the procedure should look like the following:
[OperationContract] [WebGet(UriTemplate="/{director}")] public DirectorDetail GetDirector(string director) { MovieDataDataContext dc = new MovieDataDataContext();
var result = from aDirector in dc.directors where aDirector.director_name == director select new DirectorDetail { DirectorName = aDirector.director_name, Movies = new MovieList( (from movie in aDirector.movies select movie.movie_name) ) };
return result.First(); }
Right-click on the project in the Solution Explorer and select Add New Item. Select Text File as the template, and specify the name as DirectorSerivce.svc. Click Add.
Inside of the DirectorService.svc file, add a ServiceHost declaration with the following attributes and properties:
<%@ ServiceHost Language="C#" Service="DirectorService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
Save all open files. Right-click on the MovieWeb project in the Solution Explorer and select Build Web Site.
Right-click on the DirectorService.svc file in the Solution Explorer and select View in Browser.
Your browser window should look similar to this (if you see an error message, refresh the content by pressing F5).
(Note - Now you have a REST service that returns XML that could be consumed by any REST client (typically that would not be a browser).
Click the menu next to the Tools menu item on the Internet Explorer toolbar and select Web Development Helper.
(Note - The Web Development Helper is a tracing tool which will allow you to see the requests going from the browser to the WCF Service).
Check the checkbox next to Enable Logging. Copy the value of the first Link element from the browser ( Clooney), put that link in the address bar of your browser and press enter. This should take you to the second method.
Double-click on the URL in the bottom pane of the Web Development Helper, then click on the Response Content tab in the bottom pane, so you can see what the response looks like.
Close the Http Log View dialog.
In this post we created a simple WCF REST-based Service. The service returned custom XML serialized data - and used the URIs to map client invocations to methods using WebGet and UriTemplate.
In the next part (Part 2) we will look at JSON. Until next time...
Happy Coding!
Summary: This how-to post will introduce you to building REST-based services using WCF. This series
Overview: This how-to post will introduce you to building REST-based services using WCF. This series
In the sample project, Movie.zip doesn't seem available any more for download. Is there an alternative link somewhere?
Besides, 'MusicWeb' as a project name should have been 'MovieWeb' instead, as read from the context.
Good work!
Humm, well I am not sure what is going on there. The files are on my skydrive account and the zip file is still there. It must be a permissions thing. I will look into it more.
Thanks! | http://blogs.msdn.com/b/bspann/archive/2008/04/04/building-rest-based-services-using-wcf-part-1.aspx | CC-MAIN-2014-41 | refinedweb | 1,403 | 50.43 |
A lightweight and easy to use logging API to include in your mobile iOS application.
DogSwift uses
os_log on devices with iOS 10.0+ installed and falls back to
NSLog for older iOS versions. DogSwift can print errors, messages and object descriptions to Xcode's debugging console. It's also possible to tag each logging statement with a category which will be utilized by Apple's
os_log implementation, like
UI,
Networking et cetera.
Add the environment variable
LOG_LEVEL along with the desired value:
error = 1
warn = 2
info = 3
debug = 4
// Log function name of current scope. Log.info(#function) // The message parameter can be of type `Any`. Log.debug(view.bounds, tag: .ui) // Log a warning. Log.warn("Current device is running iOS 9.0, which doesn't support os_log.", tag: .location) // Error logging. let exampleError = NSError(domain: "ch.dreipol", code: -9999, userInfo: [ NSLocalizedDescriptionKey: "Flying to the moon was not possible.", NSLocalizedFailureReasonErrorKey: "The operation timed out.", NSLocalizedRecoverySuggestionErrorKey: "Have you tried turning it off and on again?" ]) Log.error(exampleError, description: #function, tag: .system
Tags can help to group the logging output. Currently the folliwing tags are supported:
none
database
networking
system
ui
It's possible to define your own tags and pass them to DogSwift:
import DogSwift enum ExampleTag: String { case viewDidLoad } extension ExampleTag: TagProtocol { func makeString() -> String { return String(describing: self) } }
The new Tag can now be passed to DogSwift:
[...] override func viewDidLoad() { super.viewDidLoad() Log.debug(view.bounds, tag: ExampleTag.viewDidLoad) } [...]
Swift 5.0
DogSwift is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'DogSwift'
Add the following to your
Package.swift file:
dependencies: [ .package(url: "", .upToNextMajor(from: "1.1.2")) ]
To run the example project, open
DogSwiftExample.xcworkspace which resides inside the DogSwiftExample directory. The demo app contains some examples on how to use DogSwift for Logging errors as well as various information to Xcode's debugging console.
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | https://swiftpack.co/package/dreipol/DogSwift | CC-MAIN-2021-21 | refinedweb | 329 | 51.85 |
TkInter
The "standard" Python Gui Framework.
But many don't like it much.
Lion Kimbro helper tool
Oct'2014: Upgrading Python in the course of playing with TankWiki has killed my TkInter, which is needed to run some other script someone gave me. {{{
import Tkinter
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 39, in
This suggested getting Active Tcl from Active State. So I did. Installing it didn't make a difference.
Since I only have that 1 need, I figured out how to run that script from the Command Line, and ripped out the GUI code. Hack!
I'm a TkInter fan. Like the Python folks in general, I occasionaly look around to see if I should switch from Tk, and it's usually "not yet". I first started with Tk when it was Tcl-only. The things I like the most about Tk are how easy it is to build reusable windows, frames, or widgets in very few lines of code, the text and canvas widgets, and the ease of handling callbacks (Tk is callback based, not event based). Tk's "object model" (for lack of a better term, it's not OO in the traditional sense) and packing are what seem to make it so easy.
The one thing I haven't liked so much about Tk is that I wish it used Te X style layout rather than its current packing model. --KenMacLeod 15Apr02
Edited: | Tweet this! | http://webseitz.fluxent.com/wiki/TkInter | CC-MAIN-2018-22 | refinedweb | 250 | 81.43 |
I've recently started developing with Jython and I love the language. the combination of Python's dynamic features with Java is extremely powerful. If you are not familiar with Python or Jython, be sure to check the above links. As an Action Script veteran, I have to admit that Python makes me miss the early days of AS, when the language was dynamic and weakly typed.
The following is an example of a typical web client task, a conversion of a local file to a Byte array, such a conversion is common when sending a local file from the client to a Java server, using SOAP Web Services or other integration layer. Here is an example of a file to Byte array conversion in Jython, it's a Jython version of a simple java code I've found here:
from java.lang import Byte
from java.io import FileInputStream
from java.io import File
import jarray
def getByteArray(self,fileUrl):
file = File(fileUrl);
inputStream = FileInputStream(file)
length = file.length()
bytes = jarray.zeros(length, 'b')
#Read in the bytes
offset = 0
numRead = 0
while offset<length:
if numRead>= 0:
print numRead
numRead=inputStream.read(bytes, offset, length-offset)
offset = offset + numRead
return bytes
As you can see, I had to use the jarray Jython module in this code. Jarray provides a much needed API that is missing from Jython's core modules. It exposes two methods which allow you to construct Typed Arrays and\or determine the array length on creation. The following are the two jarray methods:
array(sequence, type): Creates an array of a specific type with values from the sequence; the array is the same size as the sequence
zeros(length, type): Creates an empty array the length of the length parameter
The follwoing line in my code:
bytes = jarray.zeros(length, 'b')
Is the jarray, Jython implementation of the following java code:
byte[] bytes = new byte[(int)length];
2 comments:
Jython is fun to work with!
I am glad I am not the only one who's enjoying its flexibility and extendability.
Go Lior!
thank you... you saved my day :) | http://www.flexonjava.net/2009/08/jython-convert-file-into-byte-array.html | CC-MAIN-2015-40 | refinedweb | 354 | 61.56 |
On Thu, 2006-07-13 at 12:14 -0600, Eric W. Biederman wrote:> Maybe. I really think the sane semantics are in a different uid namespace.> So you can't assumes uids are the same. Otherwise you can't handle open> file descriptors or files passed through unix domain sockets.Eric, could you explain this a little bit more? I'm not sure Iunderstand the details of why this is a problem?-- Dave-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2006/7/13/253 | CC-MAIN-2015-22 | refinedweb | 101 | 69.89 |
Using groovy script I have gathered all the ID one by one from response. I want to store these values into datasource, and pass them into next request, is it possible??
=========================================================
My script:
for ( j = 0 ; j < dresRows ; j++){
def response = context.expand( '${ABCD#Response#$['+j+'][\'href\']}' )
testRunner.testCase.testSteps["IdDataSource"].setPropertyValue("account_id", response)}
DataSouce is Grid :
ERROR:
I am getting ERROR java.lang.runtimeException: Trying to set read-only property [account_id)
===================================
How to store value from groovy script into DataSource
DataSource is basically used to read-only the data not to store any data. You can use DataSink and update the value there. Just add 1 step as DataSink and replace "IdDataSource" with DataSink in code.
Hope, this solves your problem.
Its kind of solved my problem. I want to loop the ID into my next REST request step.
Now I have to store my IDs into DataSink Excel and Load the data (IDs) into datasource in my next step
is there any other easy way to do it ??
As per my knowledge. you cannot write anything to DataSource but you can set the property value in DataSource like this:-
def response = context.expand(${Request#Response})
testRunner.testCase.testSteps["DataSource"].setPropertyValue("Response", response)
So, here if you are getting ID's at every loop, put this code there (Do some changes in code with respect to ID) inside for loop and store the ID's at DataSource property.
Does it sound good to you?
Hi @jeev,
Does @avidCoder's reply help you? If it does, please accept this post as a solution (a big green button). It will help other community members find the answer faster. Plus, avidCoder will get some points to his reputation! | https://community.smartbear.com/t5/SoapUI-Pro/How-to-store-value-from-groovy-script-into-DataSource/m-p/175816 | CC-MAIN-2019-47 | refinedweb | 286 | 66.64 |
from qiskit import * from qiskit.tools.visualization import plot_histogram %config InlineBackend.figure_format = 'svg' # Makes the images look nice import numpy as np
1
Show that the Hadamard gate can be written in the following two forms$$H = \frac{X+Z}{\sqrt{2}} \equiv \exp\left(i \frac{\pi}{2} \, \frac{X+Z}{\sqrt{2}}\right).$$
Here $\equiv$ is used to denote that the equality is valid up to a global phase, and hence that the resulting gates are physically equivalent.
Hint: it might even be easiest to prove that $e^{i\frac{\pi}{2} M} \equiv M$ for any matrix whose eigenvalues are all $\pm 1$, and that such matrices uniquely satisfy $M^2=I$.
2
The Hadamard can be constructed from
rx and
rz operations as
For some suitably chosen $\theta$. When implemented for finite $n$, the resulting gate will be an approximation to the Hadamard whose error decreases with $n$.
The following shows an example of this implemented with Qiskit with an incorrectly chosen value of $\theta$ (and with the global phase ignored).
Determine the correct value of $\theta$.
Show that the error (when using the correct value of $\theta$) decreases quadratically with $n$.
q = QuantumRegister(1) c = ClassicalRegister(1) error = {} for n in range(1,11): # Create a blank circuit qc = QuantumCircuit(q,c) # Implement an approximate Hadamard theta = np.pi # here we incorrectly choose theta=pi for j in range(n): qc.rx(theta/n,q[0]) qc.rz(theta/n,q[0]) # We need to measure how good the above approximation is. Here's a simple way to do this. # Step 1: Use a real hadamard to cancel the above approximation. # For a good approximation, the qubit will return to state 0. For a bad one, it will end up as some superposition. qc.h(q[0]) # Step 2: Run the circuit, and see how many times we get the outcome 1. # Since it should return 0 with certainty, the fraction of 1s is a measure of the error. qc.measure(q,c) shots = 20000 job = execute(qc, Aer.get_backend('qasm_simulator'),shots=shots) try: error[n] = (job.result().get_counts()['1']/shots) except: pass plot_histogram(error)'} | https://qiskit.org/textbook/ch-ex/ex2.html | CC-MAIN-2020-50 | refinedweb | 360 | 57.67 |
Reading CSV files into Dask DataFrames with read_csv
• February 9, 2022
This blog post explains how to read one or multiple CSV files into a Dask DataFrame with read_csv. It’ll discuss the different options for reading CSV files and what code design patterns will give you the best performance.
Here’s how this post is organized:
- Reading a single small CSV file
- Reading a large CSV file
- Reading multiple CSV files
- Reading files from in remote data stores like S3
- Limitations of CSV files
- Alternative file formats that often perform better than CSV
Lots of datasets are stored with the CSV file format, so it’s important for you to understand the Dask
read_csv API in detail.
Dask read_csv: single small file
Dask makes it easy to read a small file into a Dask DataFrame. Suppose you have a
dogs.csv file with the following contents:
first_name,age fido,3 lucky,4 gus,8
Here’s how to read the CSV file into a Dask DataFrame.
import dask.dataframe as dd ddf = dd.read_csv("dogs.csv")
You can inspect the content of the Dask DataFrame with the
compute() method.
ddf.compute()
This is quite similar to the syntax for reading CSV files into pandas DataFrames.
import pandas as pd df = pd.read_csv("dogs.csv")
The Dask DataFrame API was intentionally designed to look and feel just like the pandas API.
For a single small file, Dask may be overkill and you can probably just use pandas. Dask starts to gain a competitive advantage when dealing with large CSV files. Rule-of-thumb for working with pandas is to have at least 5x the size of your dataset as available RAM. Use Dask whenever you exceed this limit. For example, when working on a 16GB RAM machine, consider switching over to Dask when your dataset exceeds 3GB in size.
Dask read_csv: single large file
Dask DataFrames are composed of multiple partitions, each of which is a pandas DataFrame. Dask intentionally splits up the data into multiple pandas DataFrames so operations can be performed on multiple slices of the data in parallel.
Let’s read in a 5.19 GB file (5,190 MB) into a Dask DataFrame. This file is hosted in a public S3 bucket at
s3://coiled-datasets/h2o/G1_1e8_1e2_0_0/csv/G1_1e8_1e2_0_0.csv if you’d like to download it yourself. See the coiled-datasets repo for more information about accessing sample datasets.
ddf = dd.read_csv("data/G1_1e8_1e2_0_0.csv")
We can run
ddf.partitions to see how many partitions the data is divided into.
ddf.partitions # 82
You can customize the number of partitions that the DataFrame will contain by setting the
blocksize parameter when invoking
read_csv.
Dask read_csv: blocksize
The number of partitions depends on the value of the blocksize argument. If you don’t supply a value to the blocksize keyword, it is set to “default” and the blocksize is computed based on the available memory and number of cores on the machine, up to a max blocksize of 64 MB. In the example above, Dask automatically splits up the 5,190 MB data file into ~64 MB chunks when run on a Macbook Air with 8 GB of RAM and 4 cores.
We can also manually set the blocksize parameter when reading CSV files to make the partitions larger or smaller.
Let’s read this data file with a blocksize of 16 MB.
ddf = dd.read_csv("data/G1_1e8_1e2_0_0.csv", blocksize="16MB") ddf.npartitions # 325
The Dask DataFrame consists of 325 partitions when the blocksize is 16 MB. The number of partitions goes up when the blocksize decreases.
Let’s read in this data file with a blocksize of 128 MB.
ddf = dd.read_csv("data/G1_1e8_1e2_0_0.csv", blocksize="128MB") ddf.npartitions # 41
The Dask DataFrame has 41 partitions when the blocksize is set to 128 MB. There are fewer partitions when the blocksize increases.
Let’s take a look at how Dask infers the data types of each column when a CSV file is read.
The rule of thumb when working with Dask DataFrames is to keep your partitions under 100MB in size.
Dask read_csv: inferring dtypes
CSV is a text-based file format and does not contain metadata information about the data types or columns. When reading a CSV file, Dask needs to infer the column data types if they’re not explicitly set by the user.
Let’s look at the dtypes that Dask has inferred for our DataFrame.
ddf.dtypes id1 object id2 object id3 object id4 int64 id5 int64 id6 int64 v1 int64 v2 int64 v3 float64 dtype: object
Dask infers dtypes based on a sample of the data. It doesn’t look at every row in the dataset to infer dtypes because that would be prohibitively slow for large datasets.
You can increase the number of rows that are sampled by setting the sample_rows parameter.
ddf = dd.read_csv("data/G1_1e8_1e2_0_0.csv", sample_rows=5000)
For this dataset, increasing the number of rows that are sampled does not change the inferred dtypes.
ddf.dtypes id1 object id2 object id3 object id4 int64 id5 int64 id6 int64 v1 int64 v2 int64 v3 float64 dtype: object
Inferring data types based on a sample of the rows is error-prone. Dask may incorrectly infer dtypes based on a sample of the rows which will cause downstream computations to error out. You can avoid dtype inference by explicitly specifying dtypes when reading CSV files.
Dask read_csv: manually specifying dtypes
Let’s manually set the id1, id2, and id3 columns to be strings, which are more efficient than object type columns, as described in this video.
ddf = dd.read_csv( "data/G1_1e8_1e2_0_0.csv", dtype={ "id1": "string[pyarrow]", "id2": "string[pyarrow]", "id3": "string[pyarrow]", }, ) ddf.dtypes id1 string id2 string id3 string id4 int64 id5 int64 id6 int64 v1 int64 v2 int64 v3 float64 dtype: object
Dask will infer the types for the columns that you don’t manually specify.
See this blog post to learn more about Dask dtypes.
If you specify the dtypes for all the columns, then Dask won’t do any dtype inference and you will avoid potential errors or performance slowdowns
Dask read_csv: multiple files
Dask can read data from a single file, but it’s even faster for Dask to read multiple files in parallel.
Let’s write out the large 5.19 GB CSV file from earlier examples as multiple CSV files so we can see how to read multiple CSV files into a Dask DataFrame. Start by writing out the single CSV file as multiple CSV files.
ddf = dd.read_csv("data/G1_1e8_1e2_0_0.csv") ddf.npartitions # 82 ddf.to_csv("data/csvs")
This will write out 82 files, one for each partition. The files will be outputted as follows.
data/csvs/ 000.part 001.part 002.part
Let’s read these 82 CSV files into a Dask DataFrame.
ddf = dd.read_csv("data/csvs/*.part")
Reading multiple files into a pandas DataFrame must be done sequentially and requires more code as described in this blog post. Here’s the pandas syntax:
import glob import pandas as pd all_files = glob.glob("./data/csvs/*.part") df = pd.concat((pd.read_csv(f) for f in all_files))
Parallel I/O is a huge strength of Dask compared to pandas. pandas is designed for read / write operations with single files. pandas does not scale well with multiple files. Dask is designed to perform I/O in parallel and is more performant than pandas for operations with multiple files.
The same blocksize and dtype arguments we discussed earlier for reading a single file also apply when reading multiple files.
Dask readers also make it easy to read data that’s stored in remote object data stores, like AWS S3.
Dask read_csv: analyzing remote files with localhost compute
You can easily read a CSV file that’s stored in S3 to your local machine. Here’s how to read a public S3 file.
ddf = dd.read_csv("s3://coiled-datasets/timeseries/20-years/csv/0000.part") ddf.head()
You normally should not analyze remote data on your localhost machine because it’s slow to download the data locally. It’s more natural to process cloud data with cloud compute power. Files stored in the AWS S3 cloud should be processed with AWS ec2 cloud provisioned compute instances.
Let’s look at a S3 folder with a lot of data. The
coiled-datasets/timeseries/20-years/csv/ S3 folder has 1,095 files and requires 100 GB of memory when loaded into a DataFrame. Let’s try to run a computation on the entire dataset and see if it works.
ddf = dd.read_csv("s3://coiled-datasets/timeseries/20-years/csv/*.part") ddf.describe().compute()
I let this computation run for 30 minutes before canceling the query. Running this locally is way too slow.
Let’s see how to read in this large dataset of CSVs to a Dask cluster that contains multiple compute nodes, so we can execute this query faster.
Dask read_csv: read remote files in cluster environment
Let’s spin up a 5 node cluster with Coiled and try to run the same computation with more computing power.
import coiled import dask.distributed cluster = coiled.Cluster(name="powers", n_workers=5) client = dask.distributed.Client(cluster) ddf = dd.read_csv("s3://coiled-datasets/timeseries/20-years/csv/*.part") ddf.describe().compute()
This computation runs in 5 minutes and 10 seconds. Running this computation on a cluster is certainly faster than running on localhost. It would have taken a very long time for the query to finish on localhost.
Storing the data in a different file format could make the query run even faster.
Limitations of CSV file format
CSV files are commonly used because they’re human readable, but they are usually not the best file format for a data analysis.
I gave a talk at PyData Global on 5 reasons Parquet is better than CSV for data analyses.
Here are the five reasons:
- Parquet files don’t require schema inference / manual schema specification
- Parquet files are easier to compress
- Columnar nature of Parquet files allows for column pruning, which often yields big query performance gains
- Row group metadata in Parquet files allows for predicate pushdown filtering
- Parquet files are immutable
See this blog post on the advantages of Parquet files for more details.
In addition, CSV files let you save messy data in files, unlike other file formats. CSV lets you save string data in an integer column, whereas Parquet will error out if you try to store string data in an integer column.
Conclusion
Lots of data is stored in CSV files and you’ll often want to read that data into Dask DataFrames to perform analytical queries.
This blog has shown you that it’s easy to load one CSV or multiple CSV files into a Dask DataFrame. You’ve also learned how to set dtypes and customize the number of partitions in the DataFrame by setting the blocksize parameter.
CSV files aren’t usually as performant as a binary, columnar file format like Parquet. Whenever possible, consider converting the CSV files to Parquet, as described in this blog post. Most analytical queries run faster on Parquet lakes. | https://coiled.io/blog/dask-read-csv-to-dataframe/ | CC-MAIN-2022-21 | refinedweb | 1,867 | 63.09 |
How to: Create and Execute a Simple PLINQ Query
The following example shows how to create a simple Parallel LINQ query by using the AsParallel extension method on the source sequence, and executing the query by using the ForAll method.
Note
This documentation uses lambda expressions to define delegates in PLINQ. If you are not familiar with lambda expressions in C# or Visual Basic, see Lambda Expressions in PLINQ and TPL.
Example
using System; using System.Linq; public class Example { public static void Main() {); Console.WriteLine("\nPress any key to exit..."); Console.ReadLine(); } static void DoSomething(int i) { } }
Imports System.Linq Module Example Public Sub Main() Dim source = Enumerable.Range(100, 20000) ' Result sequence might be out of order. Dim parallelQuery = From num In source.AsParallel() Where num Mod 10 = 0 Select num ' Process result sequence in parallel parallelQuery.ForAll(Sub(e) DoSomething(e) End Sub) ' Or use For Each to merge results first ' as in this example, Where results must ' be serialized sequentially through static Console method. For Each n In parallelQuery Console.Write("{0} ", n) Next ' You can also use ToArray, ToList, etc, as with LINQ to Objects. Dim parallelQuery2 = (From num In source.AsParallel() Where num Mod 10 = 0 Select num).ToArray() ' Method syntax is also supported Dim parallelQuery3 = source.AsParallel().Where(Function(n) Return (n Mod 10) = 0 End Function).Select(Function(n) Return n End Function) For Each i As Integer In parallelQuery3 Console.Write("{0} ", i) Next Console.WriteLine() Console.WriteLine("Press any key to exit...") Console.ReadLine() End Sub ' A toy function to demonstrate syntax. Typically you need a more ' computationally expensive method to see speedup over sequential queries. Sub DoSomething(ByVal i As Integer) Console.Write("{0:###.## }", Math.Sqrt(i)) End Sub End Module
This example demonstrates the basic pattern for creating and executing any Parallel LINQ query when the ordering of the result sequence is not important; unordered queries are generally faster than ordered queries. The query partitions the source into tasks that are executed asynchronously on multiple threads. The order in which each task completes depends not only on the amount of work involved to process the elements in the partition, but also on external factors such as how the operating system schedules each thread. This example is intended to demonstrate usage, and might not run faster than the equivalent sequential LINQ to Objects query. For more information about speedup, see Understanding Speedup in PLINQ. For more information about how to preserve the ordering of elements in a query, see How to: Control Ordering in a PLINQ Query.
See also
Feedback | https://docs.microsoft.com/en-au/dotnet/standard/parallel-programming/how-to-create-and-execute-a-simple-plinq-query | CC-MAIN-2019-39 | refinedweb | 431 | 50.02 |
ichael Raduga
INear-Death Meditation for BeginnersFirst Edition Translated by Peter Orange
The practice of phase states of the mind is the hottest and most promising pursuit of the modern age. Unlike in the past the notions of !out"of"body e#perience$ !near"death meditation$ !lucid dreaming$ and !astral pro%ection$ ha&e already lost their mystical halo and their real basis has been studied in minute detail from the most non"nonsense approach. 'o( this phenomenon is accessible to e&eryone regardless of their (orld&ie(. )t is no( kno(n ho( to easily master it and apply it effecti&ely. This te#tbook gi&es each and e&ery person something that pre&iously could only be dreamt about " a parallel reality and the possibility of e#isting in t(o (orlds. This book is for pragmatic people (ho are not used to taking anything on faith or reading about empty theories. The book only deals (ith (hat (orks in practice and nothing else. Proposals regarding translating and publishing this book and other (orks of M. Raduga may be sent to aing*aing.ru
Table of ,ontentsPart I Entering the Out-of-Body State Chapter 1 General Ba !ground The Essence of the Phase Phenomenon .hy Enter the Phase/ The 0ifestyle of a Practitioner 1lgorithm for Mastering the Phase Types of Techni2ues ,ontraindications Recommendations for Using the 3uidebook E#ercises for ,hapter 1 Chapter " Indire t #e hni$ues The ,oncept of )ndirect Techni2ues Primary )ndirect Techni2ues 4econdary )ndirect Techni2ues 4electing the Right Techni2ues 4eparation Techni2ues The 5est Time to Practice ,onscious 1(akening 1(akening (ithout Mo&ing ,ycles of )ndirect Techni2ues 6ints from the Mind 1ggression and Passi&ity 4trategy for 1ction Typical Mistakes (ith )ndirect Techni2ues E#ercises for ,hapter + Chapter % Dire t #e hni$ues The ,oncept of 7irect Techni2ues The 5est Time to Practice )ntensity of 1ttempts 5ody Position 8
7uration of an 1ttempt Rela#ation 9ariations of Using 7irect Techni2ues The Free"floating 4tate of Mind 1u#iliary Factors 4trategy for 1ction Typical Mistakes (ith 7irect Techni2ues E#ercises for ,hapter 8 Chapter & Be o'ing Cons ious (hile Drea'ing The ,oncept of Techni2ues )n&ol&ing 5ecoming ,onscious (hile 7reaming Techni2ues for 5ecoming ,onscious in a 7ream 1ctions to be 7one (hen 5ecoming ,onscious (hile 7reaming 4trategy for 1ction Typical Mistakes (hen Practicing 5ecoming ,onscious (hile 7reaming E#ercises for ,hapter : Chapter ) Non-autono'ous Methods The Essence of 'on"autonomous Methods for Entering the Phase ,ueing Technologies .orking in Pairs Technologies for )nducing the Phase 6ypnosis and 4uggestion Physiological 4ignals ,hemical 4ubstances The Future of 'on"autonomous Methods for Entering the Phase Typical Mistakes (ith 'on"autonomous Techni2ues E#ercises for ,hapter ; Part II Managing the Out-of-Body E*perien e :
Chapter + Deepening The ,oncept of 7eepening Primary 7eepening Techni2ues 7eepening through 4ensory 1mplification 4econdary 7eepening Techni2ues 3eneral 1cti&ity Typical Mistakes 7uring 7eepening E#ercises for ,hapter < Chapter , Maintaining The 3eneral ,oncept of Maintaining Techni2ues and Rules against Returning to the 5ody Techni2ues and Rules for Resisting Falling 1sleep Techni2ues against an Unrecogni=ed Phase 3eneral Rules for Maintaining Typical Mistakes (ith Maintaining E#ercises for ,hapter > Chapter - Pri'ary S!ills The Essence of Primary 4kills 7iscerning the Phase Emergency Return. Paralysis Fighting Fear ,reation of 9ision ,ontact (ith 0i&ing Ob%ects Reading 9ibrations Techni2ues for Translocating through Ob%ects Flight 4uper"abilities The )mportance of ,onfidence ,ontrolling Pain Moral 4tandards in the Phase 4tudying Possibilities and 4ensations Typical Mistakes (ith Primary 4kills ;
E#ercises for ,hapter ? Chapter . #ranslo ation and /inding O01e ts The Essence of Translocation and Finding Ob%ects 5asic Property of the Phase 4pace Techni2ues for Translocation Ob%ect Finding Techni2ues Typical Mistakes (ith Translocation and Finding Ob%ects E#ercises for ,hapter @ Chapter 12 3ppli ation The Essence of 1pplications for Phase 4tates 1pplications 5ased on 4imulation 1pplications 5ased on ,ontact (ith the 4ubconscious Mind 1pplication 5ased on )nfluencing Physiology Unpro&en Effects Use of the Phase by the 7isabled Typical Mistakes (hen Using 1pplications E#ercises for ,hapter 1A Part III 3u*iliary Infor'ation Chapter 11 4seful #ips 1 Pragmatic 1pproach )ndependent 1nalysis 1pproach to 0iterature Practice En&ironment Talking (ith 0ike"minded People The Right .ay to Beep a Cournal Chapter 1" Pra titioners5 E*perien es The 4ignificance of Other PeopleDs E#periences 1nalysis of 4elected PractitionersE E#periences E#ercises for ,hapter 1+ <
Chapter 1% Putting a /a e on the Pheno'enon 4tephen 0aberge ,arlos ,astaneda Robert 1. Monroe Patricia 3arfield 4yl&an Muldoon ,harles 0eadbeater Robert 5ruce Richard .ebster ,harles Tart Chapter 1& /inal #est 3ppendi* 1ssessment of PractitionersD E#periences Fchapter 1+G 1ns(ers to the Final Test Fchapter 1:G 1 4implified 7escription of the Easiest Method for Entering the Phase using )ndirect Techni2ues Take Part in Research The ,ell Phone Techni2ue 1ttentionH The 4chool of Out"of"5ody Tra&el 5rief 3lossary of Terms and 7efinitions
>
/ore6ord This guidebook is the result of ten years of e#tremely acti&e personal practice and study of the out"of"body phenomenonF the phaseG coupled (ith ha&ing successfully taught it to thousands of people. ) kno( all of the obstacles and problems that are usually run into (hen getting to kno( this phenomenon and ha&e tried to protect future practitioners from them in this book. This guidebook (as not created for those (ho prefer light empty reading. )t is for those (ho (ould like to learn something. )t contains no speculations or stories only dry hard facts and techni2ues in combination (ith a completely pragmatic approach and clear procedures for action. They ha&e all been successfully &erified by a &ast number of practitioners that often had no prior e#perience. )n order to achie&e the same result it is only necessary to read through each section thoroughly and complete the assignments. The book is beneficial not only for beginners but also for those (ho already kno( (hat it feels like to ha&e an out"of"body encounter and ha&e a certain amount of e#perience as this guidebook is de&oted not only to entering the state but also e2ually dedicated to controlling it. ,ontrary to popular opinion there is nothing difficult about this phenomenon if one tries to attain it (ith regular and right effort. On a&erage results are reached in less than a (eek if attempts are made e&ery day. More often than not the techni2ues (ork in literally a couple of attempts. Michael Raduga Founder of the School of Out-of-Body Travel January 11, 2 !
)n essence the phase is an une#plored state of mind (here one is unable to control and feel his physical body. )nstead his space perception is filled (ith realistic phantom e#periences. Interesting Fact! Sensations in the phase state can "e so realistic that practitioners &ho unintentionally enter phase often "elieve they are still in the physical "ody, that the e#perience is occurring in the &a+ing state( These types of unintended e#cursions $ost often occur at night or early in the $orning( )t is belie&ed that up to one 2uarter of the human population has encountered this phenomenon. 6o(e&er if &ariations and different degrees of intensity of the state are taken into consideration it may be safely assumed that e&eryone has encountered the phase. 4ince the phase is a rare sub%ect of study many (ho inad&ertently enter it do not reali=e (hat has taken place once they return to (akefulness. Many do not assign any significance to the occurrence of a phase en&ironment that is not fully formed because shallo( phases donDt lea&e the same %olting impression as deep states. Elusi&e as the phase may seem this is an e#tremely common phenomenon accessible to 1A
anyone (illing to consciously learn and apply the correct methods of achie&ing and maintaining the phase. (78 EN#E9 #7E P73SE: 4uch a 2uestion can only arise from not fully understanding the properties of the phenomenon and its nature. .hen one suddenly understands at a certain moment that he is %ust as real as he normally is and is standing some(here that is not in the physical (orld (ith his same hands and body and can touch e&erything around him and discern fine details such much emotion stirs up inside him that no 2uestions arise at all. This is the $ost a$a*ing e#perience that a person can attain, The initial phase encounter is al(ays %olting and sometimes frightening. 7epending on the indi&idual fear e#perienced during initial encounters (ith the phase occurs in about one"third of all cases. E&en &eteran practitioners encounter fear (hich speaks to the profound nature of the phase state. .ith time as rapture ebbs and emotions (ane thoughts turn from the fact of the phenomenon itself to(ards ho( to someho( use it. 1nd here a fantastically di&erse field of practical application opens up before the practitioner. These applications I (hich this book communicates I are not to be associated (ith the many unpro&en and dubious methods often described in sundry esoteric literature. The information presented herein is &erifiable practical and attainable. .hate&er the nature of the phase " a state of mind or perhaps an e#ternal e#perience " this is the sole opportunity to- &isit any part of the (orld or uni&erseJ see people (ho are out"of"reach in real life including relati&es the deceased celebrities and &arious creaturesJ communicate (ith the enormous resources of the subconscious mind and obtain information from itJ reali=e desires that are unattainable in real lifeJ model artistic productionsJ influence physiology and more. These are not dull e#periences. They are eminently personal and real. #7E ;I/ES#8;E O/ 3 P93C#I#IONE9 11
)t must be said that &arious diets e#ercises rituals and so forth do not produce noticeable supplementary effects to proper practice of the phase. 'aturally e#istent psychological and physiological comfort is of the utmost importance. Thus methods recommending o&ereating under"eating or tormenting oneself (ith &arious diets and strange e#ercises are useless and ultimately detrimental to a practitionerDs (ellness and balance in&ariably producing a negati&e impact to the effecti&eness of techni2ues taught in this guidebook. 1dditionally no meaningful association has been found bet(een practice of the phase and (hat may be construed as !bad habits$. Regardless of a lifestyleDs null effect on phase achie&ement a healthy acti&e lifestyle (ill al(ays be recommended to en%oy a good 2uality of li&ing. Interesting Fact! -f one "elieves that it is necessary to position one.s "ed &ith the head"oard facing the /orth&est or so$e other direction in order to have $ore effective out-of-"ody e#periences, then doing so &ill invaria"ly have a positive effect on results( 0o&ever, the issue at hand is not the positioning of the "ody, "ut a "elief that is a+in to an intention, &hich in turn is enor$ously i$portant( )t has been obser&ed that a regular and orderly lifestyle increases the fre2uency of genuine lasting phase e#periences. 4leeping normally and soundly is the most basic e#ample of a lifestyle choice that produces direct positi&e impact on results especially (hen a practitioner commits to a full nightEs rest se&eral times a (eek. 3;GO9I#7M /O9 M3S#E9ING #7E P73SE 1 no&ice practitioner must understand the procedure for learning and mastering phase entry. This procedure consists of se&eral primary steps each of (hich is a uni2ue science unto itself. 1+
1. The first and most important step addresses the techni2ues used to enter the phase state. )t is not necessary to master e&ery type of entrance techni2ue Fdirect indirect dream consciousnessG. 0earning and applying the easiest techni2ues pro&ides the necessary prere2uisites to more ad&anced methods. )f so desired it is possible to try more difficult entrance techni2ues in parallel (ith the mo&ing on to the subse2uent steps for mastering the phase. +. ,ontrary to popular opinion the need for conscious techni2ues does not cease upon phase entrance. )t is absolutely necessary to learn and apply methods for deepening the phase to achie&e a consistently hyper"realistic en&ironment. Failing to apply deepening techni2ues almost guarantees that e#periences (ill be dull uninteresting and subse2uent practice short"li&ed. Practitioners should immediately learn and apply deepening techni2ues after mastering any one entrance method. 8. The third step in&ol&es mastering techni2ues for maintaining the phase as (ithout them the a&erage person (ould ha&e phase e#periences of much shorter duration than is possible. .hen in the phase the 2uestion of ho( to lea&e it almost ne&er occurs. On the contrary one is normally thrust from it in the course of se&eral seconds if one simply does nothing. :. 1fter learning all the necessary techni2ues for mastering the phase state it is time to learn and apply methods of control (hich encompass the ability to translocate find and interact (ith ob%ects influence surroundings and so forth. ;. Once the pre&iously noted steps ha&e been accomplished a practitioner may proceed to apply phase e#periences to enhance e&eryday life. O&er the course of this guidebook (e (ill e#amine do=ens of these &aluable applications in great detail.
18
.ith basic skills mastered remember that practicing the phase is (orth(hile and effecti&e only (hen the results are consistent. )f a practitioner enters the phase only once a month the e#perience (ill be too emotional to allo( the obser&ation of important principles and methodologies. The phase should be encountered at least once a (eek. .orking to(ard a le&el higher than a (eekly phase entry is ambitious e&en beneficial. Realistically t(o to four phase e#periences per (eek might be considered the le&el of a grandmaster but this is far from the up(ard boundary. 1s a rule no&ice practitioners achie&e the phase less often than is desired. 6o(e&er (ith regular attempts success occurs more and more fre2uently (hich should help alle&iate any frustration resulting from failed attempts. #8PES O/ #EC7NI<4ES There are three primary types of techni2ues that make it possible to enter the phase- direct indirect and drea$ consciousness. These methods are performed (hile lying do(n or reclining eyes closed the body in a state of total rela#ation. Interesting Fact! Often, people have an out-of-"ody e#perience &ithout prior +no&ledge or 1:
"elief in the pheno$enon( -t 1ust happens, and a large "ody of evidence has "een gathered to support this fact( 2ven $ore interesting is that spontaneous e#periences often occur after a "rief study of $aterial a"out the topic, li+e this guide"oo+((( 3irect techni4ues are perfor$ed &ithout any noticea"le lapse in consciousness( 5hile practicing direct techni4ues, a lapse into sleep for less than 6 $inutes is not considered a "reach of the techni4ue( 5y definition direct techni2ues encompass the performance of specific actions for a pre"defined inter&al of time. 4uccessfully applied direct methods result in a phase entrance (ithout passing through any intermediary states. For @AK of the population these techni2ues are the most difficult because the mind naturally e#ists in an e#cessi&ely acti&e state. )t has been clearly pro&en (ithin the 4choolDs student body that no&ice practitioners do not benefit from beginning a training regimen (ith direct techni2ues. This is because direct techni2ues re2uire a thorough understanding and masterful application of indirect techni2ues in order to be effecti&e. The incorrect notion that the phase state is e#tremely difficult to enter is due to the fact that people are more often dra(n to the more difficult direct techni2ues. )t is al(ays better to approach direct techni2ues only after becoming e#pert in the use of indirect techni2ues. -ndirect techni4ues are techni4ues that are put into practice upon a&a+ening fro$ sleep( The effecti&eness of indirect techni2ues is not dependent on the length of the prere2uisite sleep cycle. )ndirect techni2ues can be used (hile e#iting a full nightDs sleep after a daytime catnap or follo(ing se&eral hours of deep sleep. The most important thing is that there is a lapse of consciousness into sleep before implementing the techni2ues. )ndirect techni2ues are the easiest techni2ues to practice (hich is (hy many practitioners use them to enter the phase. 4leep naturally pro&ides the mind (ith deep rela#ation (hich is often difficult to 1;
ac2uire by other methods. 4ince sleep is re2uired to perform indirect techni2ues it is a con&enient oft"occurring means to conduct e#periments (ith the phase. 'o&ice practitioners benefit greatly from the use of indirect techni2ues and learn firsthand the possibility of phase entrance. 3rea$ consciousness is ac4uired "y techni4ues that allo& entrance to the phase through &hat is co$$only referred to as lucid drea$ing( )n this case the phase begins (hen the a(areness that a dream is occurring happens (ithin the dream itself. 1fter becoming conscious (hile dreaming se&eral types of actions can be performed including returning to the body and rolling out (hich (ill be described later. .hen deepening techni2ues are applied in the conte#t of a conscious dream the sensory perceptions of the phase surpass those of normal (akefulness. Techni2ues that facilitate dream consciousness are usually categori=ed separately from methods used to perform out"of"body tra&elJ in practice ho(e&er it is apparent that the characteristics of dream consciousness and out"of"body tra&el are identical (hich places both phenomena directly in the phase. These practices are difficult because unlike other techni2ues they do not in&ol&e specific actions that produce instantaneous results. 1 large measure of preparatory steps must be obser&ed that re2uire time and effort (ithout any guarantee of results. 6o(e&er dream consciousness techni2ues are not as difficult as direct techni2ues. Moreo&er the ma%ority of practitioners (hether using indirect or direct techni2ues e#perience spontaneous a(areness (hile dreaming (ithout ha&ing to apply techni2ues aimed at dream consciousness. )n addition to the techni2ues described abo&e there are also non" autonomous means and tools- &arious de&ices programs e#ternal influences and so forth (hich can be used to enter the phase. )t is necessary to mention that these are only useful to practitioners (ho are able to enter the phase (ithout supplementary assistance. 1<
9arious chemical substances and herbal supplements ha&e been recommended to assist phase entrance though using them is unlikely to do any good and use of these has ne&er yielded the effect that can be achie&ed through unadulterated practice. 1s such the use of a chemical crutch is regarded here as completely unacceptable. CON#93INDIC3#IONS E#act scientific proof that entering the phase is dangerous I or e&en safe " does not e#istJ there has ne&er been an e#hausti&e controlled study to pro&e either supposition. 6o(e&er since the phase e#ists at the fringes of naturally"occurring states of mind it can hardly be assumed dangerous. 'otably the phase is accompanied by rapid eye mo&ement FREMG (hich e&ery human e#periences for up to + hours each night and this begins to e#plain the phase e#perience as entirely safe and natural. 1lready confirmed are the psychological influences of the phase on the physical mind and bodyJ namely the emotional effects that can occur during the onset of the phase state. Phase entry is a &ery profound incredible e#perience that may induce fear (hich is in&oked by a natural instinct for self" preser&ation. The phase can create stress. This is especially true for no&ices and those poorly ac2uainted (ith the nature of the phenomenon and techni2ues used to control it. .ithout kno(ledge and proper practice a fear"induced reaction can escalate into full" blo(n terror. 1fter all (hile in the phase fantasy 2uickly becomes reality and reticent fears can take on hyper"realistic 2ualities. .hen this occurs itDs not the phase en&ironment but the fear that is treacherous. )t goes (ithout saying that fear is a to#ic influence especially to sensiti&e souls the elderly and people (ith physical ailments like certain cardio&ascular conditions. This does not mean that persons in these groups should abstain from practicing the phase. The solution is to learn about and a&oid common stressors associated (ith the practice kno( the mechanics of controlling ob%ects and understand the principles of making an emergency e#it. 1>
3i&en the possibility of negati&e phase e#periences it could be ad&ised that practitioners limit the time in phase to fifteen minutes though it is 2uite e#ceptional to maintain the phase for such duration. Proposed time limits are entirely theoretical and moti&ated by the fact that natural REM does not normally last longer than fifteen minutes and at the risk of side effects due to the alteration of natural cycles e#periments directed at unnaturally prolonging REM are not recommended. 9ECOMMEND3#IONS /O9 4SING #7E G4IDEBOO= 7uring classroom instruction at the 4chool of Out"of"5ody Tra&el se&eral key factors are kno(n to produce positi&e and negati&e effects to(ard the likelihood of success during indi&idual practicePositi>e Effe t on Pra ti e 1ttenti&e thorough study of the course material ,onsistent (ork (ith practical elements. 7iligent completion of technical elements. 1 rela#ed approach to the sub%ect matter. Beeping a %ournal of all initial attempts follo(ed by recording successful phase entrances. 1dhering to the recommended number of daily entrance attempts. Regular attempts and practice. 1? Negati>e Effe t on Pra ti e 6asty and inattenti&e study of course materials. )nconsistent application of techni2ues. 1ppro#imating the techni2ues outside of recommended guidelines. 1 hysterical approach to the matter !idLe fi#e$. 1 lack of personal analysis (hen problems or a lack of success are encountered. E#cessi&e number of attempts per day. 4poradic practice regimen.
!) also kno( e&erything ) need to and (ill do as ) (antM. This attitude is good only for those (ho ha&e a great amount of real practical e#perience. Reading a lot on the sub%ect or simply ha&ing kno(ledge of it is not e#perience.
1@
#as!s 1. +. 8. Try to remember if you ha&e e#perienced phase encounters in the past. )f you ha&e encountered the phase (hat type of techni2ue gained entranceJ direct indirect or conscious dreaming/ )f possible ask some friends and ac2uaintances about the sub%ect of out"of"body tra&el or conscious dreaming. 7o any of them remember a similar e#perience/ .hat (as it like/
Interesting Fact! Many e#perienced practitioners prefer to "ypass the effort associated &ith direct techni4ues and hone their s+ills through the sole use of indirect techni4ues( )n order to ensure that oneDs efforts are most fruitful and producti&e (e are going to indi&idually e#amine each step and principle behind the actions in great detail. 0et us start from a description of the techni2ues themsel&es (hich (ill actually apply practically %ust as much to direct techni2ues as to indirect techni2uesJ as they only differ in character and length of application. There are plenty of techni2ues so after practicing all of the indirect techni2ues presented in this chapter a practitioner should be able to choose three or four of the most straightfor(ard indi&idually effecti&e methods. 4eparation techni2ues (ill be e#amined later. They are completely different from usual techni2ues (hich only bring one into the phase but do not necessarily themsel&es lead to separation from the body. )t is often also necessary to kno( ho( to stop percei&ing oneDs physical body after employing these techni2ues. )t is necessary to understand (hen to employ these techni2ues and the importance of (aking from sleep (ithout opening the eyes or mo&ing the body. 1ttempting to enter the phase immediately upon a(akening must be learned and practiced to mastery since it constitutes the main barrier to successful practice. 1fter e#amining the peripheral information surrounding indirect techni2ues the cycles of indirect techni2ues (ill be e#amined including (hat there are ho( they (ork and ho( they are best used. 4uccessful phase entrance is the direct result of performing these cycles. 6o(e&er there are e#ceptions and it is not completely necessary to proceed (ith these cycles if oneEs o(n mind someho( hints (hat e#actly one should start from (hich (e (ill also e#amine separately.
P9IM398 INDI9EC# #EC7NI<4ES /ota Bene, The techni2ues described belo( are the simple components of indirect techni2ue cycles. )mplementing each techni2ueDs description is far from effecti&e. Of the list gi&en belo( it behoo&es the indi&idual practitioner to choose the most comprehensible and interesting techni2ues then acti&ely study and apply the instructions for use. OBSE9?ING IM3GES #esting Indi>idual Effe ti>eness )mmediately after (aking from sleep remain motionless eyes closed. Obser&e the blank space behind the eyes for 8 to ; seconds and try to locate recogni=able pictures images or symbols. )f nothing appears during this e#ercise the techni2ue should be substituted. )f something appears continue to passi&ely obser&e the images. Mean(hile the images (ill become increasingly realistic literally en&eloping the practitioner. 7o not aggressi&ely e#amine the details
of the image or it (ill &anish or change. The image should be e#perienced as a panorama taking e&erything in. Obser&e the images as long as the 2uality and realism increases. 7oing so yields t(o possible results- the practitioner becomes part of the surroundings and has achie&ed the phase or the image becomes borderline or absolutely realistic and separation from the physical body is possible. #raining To train the use of this techni2ue lie do(n in the dark eyes closed and obser&e the blackness for se&eral minutes identifying any specific images that may arise from simple spots or floaters and then gradually transition to (hole pictures scenes or scenarios. .ith practice this techni2ue is &ery easy and straightfor(ard. 1 common mistake made during practice of this techni2ue is (hen the practitioner aggressi&ely attempts to con%ure images &ersus passi&ely obser&ing (hat is naturally presented. P73N#OM (IGG;ING @MO?EMEN#A #esting Indi>idual Effe ti>eness )mmediately after (aking from sleep remain motionless eyes closed. Try to (iggle a part of the body for 8 to ; seconds but (ithout using any muscles. )f nothing mo&es during the attempt try a different techni2ue. )f a sensation of (iggling occurs e&en in the slightest continue to employ the techni2ue stri&ing to increase the range of mo&ement as much as possible. This techni2ue should be performed &ery aggressi&ely not passi&ely. 1s soon as the range of mo&ement nears or e#ceeds four inches " (hich may take %ust se&eral seconds " the follo(ing situations may arise- one momentarily finds oneself someho( in the phase or the (iggled part of the body begins to mo&e freely. The occurrence of mo&ement during practice of this techni2ue allo(s the practitioner to transition to a separation techni2ue and attempt to lea&e the body. .hile practicing phantom (iggling strong &ibrations may occur amid (hich separation may be attempted. 4ounds also often arise
allo(ing the opportunity to practice listening in (hich can lead to phase entrance. The phantom (iggling techni2ue is not meant to produce an imagined mo&ement by a phantom body. The point of the techni2ue is to attempt the mo&ement of a physical body part (ithout using muscular action. That is the focus should rest upon an internal intention of mo&ement (ithout physical action. .hen the sensation occurs it differs little from its real counterpart and is often accompanied by hea&iness and resistance. 3enerally there is &ery little range of mo&ement at first but (ith concentrated effort the range of mo&ement noticeably increases. )t does not matter (hich part of the body is used to e#ercise phantom mo&ement. )t may be the (hole body or %ust one finger. 'either is the speed of the mo&ement important. )ncreased range of percei&ed mo&ement is the aim of the techni2ue. #raining To train the techni2ue of phantom (iggling rela# a hand for se&eral minutes (hile lying do(n eyes closed. Then aggressi&ely en&ision the follo(ing hand mo&ements (ithout mo&ing any muscles for t(o to three minutes each- rotating up"do(n left"right e#tending the fingers and dra(ing the fingers together clenching and unclenching a fist. 'o sensations (ill occur at first. 3radually the sensation of muscular action (ill become so apparent that the percei&ed mo&ement (ill be indistinguishable from real mo&ement. 7uring the first training attempts practitioners are often tempted to open their eyes to see if actual mo&ement is occurring I thatDs ho( real the sensation feels. ;IS#ENING IN #esting Indi>idual Effe ti>eness )mmediately after (aking from sleep remain motionless eyes closed. Try to listen to noise in your head. 7o this for 8 to ; seconds (ithout mo&ing and (ithout opening the eyes. )f nothing happens
during this period of time s(itch to another techni2ue. )f any sounds like bu==ing humming ra&ing hissing (histling tinkling or melodies occur listen attenti&ely. .ith results the sound (ill increase in &olume. 0isten in as long as there is some dynamism in the &olume of the sound. .hen the sound stops or the noise becomes loud enough a separation techni2ue may be attempted. 4ometimes the noise itself thro(s one into the phase (hile listening. 1t a certain stage sounds may be e#tremely loud and ha&e e&en been described as comparable to the roar of a %et"engine. The action of listening in consists of acti&ely and attenti&ely e#ploring a sound the (hole of its tonality and range and ho( it reacts to the listener. There is an optional techni2ue kno(n as for ed listening in (here it is simply necessary to strongly (ant to hear noise and mean(hile make intuiti&e internal efforts (hich as a rule are correct. Performed correctly forced sounds (ill intensify the same (ay as those percei&ed (ith the standard listening in techni2ue. #raining )n order to practice listening in lie do(n in a silent place eyes closed and listen for sounds originating in the head. These attempts are usually cro(ned (ith success (ithin se&eral minutes of trying and one starts to hear that noise that absolutely e&eryone has (ithin. One simply has to kno( ho( to tune in to it. 9O#3#ION #esting Indi>idual Effe ti>eness )mmediately after (aking from sleep remain motionless eyes closed. )magine the physical body is rotating along an a#is for ; to 1A seconds. )f no unusual sensations occur try another techni2ue. )f &ibrations occur during rotation or the mo&ement suddenly feels realistic then continue the rotation techni2ue as long as there is progress in the sensationDs de&elopment. There are se&eral possible outcomes (hen rotation is practiced. The imagined rotation is replaced by a &ery real sensation of rotating along an imagined a#is.
.hen this occurs a practitioner may easily lea&e the body. The other outcome is the sudden presence of strong &ibrations or loud sounds amid (hich separation from the body is possible. 7uring rotation separation has been kno(n to spontaneously occur and the practitioner enters the phase. #raining To practice rotation imagine re&ol&ing around the head"to"foot a#is for se&eral minutes (hile lying do(n eyes closed. )t is not necessary to focus on the &isual effects of rotation or minute sensations in the body. The key factor is the &estibular sensation that arises from internal rotation. 1s a rule many practitioners e#perience difficulty performing full rotation. One person may be limited to @A degrees of mo&ement (here another e#periences 1?A degrees. .ith consistent correct practice full 8<A degree rotation (ill occur. /O9CED /3;;ING 3S;EEP #esting Indi>idual Effe ti>eness )mmediately after (aking from sleep remain motionless eyes closed. Picture a s(ift compulsory fall into sleep for ; to 1A seconds and then return to (akefulness follo(ed by an aggressi&e attempt at separating from the physical body. 3enerally after performing this techni2ue the practitionerDs state of mind 2uickly transitions bet(een different states of brain. 4trong &ibrations often occur (hen emerging from this !pseudo"sleep$ (here the likelihood of separation from the body is increased accompanied the opportunity to practice other techni2ues. Resist actually falling asleep during this e#ercise. )n essence forced falling asleep is a trick on the mind designed to take ad&antage of the brainDs refle#i&e responses to actions that immediately induce semi"conscious states that allo( easy entrance into the phase. Employing it is especially effecti&e upon an e#tremely alert a(akening or after a mo&ement is unintentionally made upon a(akening. Forced sleep is 2uite simple. )t re2uires a cessation of internal dialogue shifting mental focus a(ay from e#ternal stimuli and a
strong desire for a 2uick reentrance to the sleeping state follo(ed by rene(ed (akefulness after se&eral seconds. )n order to understand ho( this is done it is sufficient to recall ho( one had urgently made oneself fall asleep before or ho( one had fallen asleep after ha&ing been e#hausted or after a long period of sleep depri&ation. 1 common mistake in practice occurs (hen people fall asleep after attempting the techni2ue forgetting the necessary desire to 2uickly return to consciousness. SECOND398 INDI9EC# #EC7NI<4ES S#93INING #7E B93IN #esting Indi>idual Effe ti>eness )mmediately after (aking from sleep remain motionless eyes closed. Make + to 8 s2uee=es straining the brain. This is kno(n as straining the brain. )f nothing happens try another techni2ue. )f &ibrations occur during this e#ercise try to mo&e the &ibrations around the body and amplify them by continuing to strain the brain. The stronger the &ibrations the higher the probability that a separation techni2ue may be applied. 4pontaneous separation may occur. .hile straining the brain a practitioner may e#perience the sounds necessary for transitioning to a listening in techni2ue. The &ibrations that arise from straining the brain are &ery striking. )f there is any doubt as to (hether the &ibrations happened then most likely a practitioner did not e#perience them. The &ibrations may be described as an intense painless electrical current mo&ing through or gripping the body. 1t times the sensation of a total numbing of the body is e#perienced. #raining To practice straining the brain lie do(n eyes closed and attempt to strain the brain. 7o not think about the fact that actually s2uee=ing the brain is impossible. The imagined straining should be spasmodic rhythmic. Practitioners may strain the entire brain or specific parts of it. 7uring the process a sensation of pressure or e&en real strain
arises in the brain. .ith @;K of practitioners this strain usually occurs (ithin the first fe( minutes of e#ercise. This techni2ue should be committed to memory (hen training so that it may be instantly recalled and practiced upon a(akening from sleep. Practitioners often make the mistake of unintentionally straining their facial and neck muscles instead of straining the interior of their heads. This error should be a&oided at all costs lest it become a habit that frustrates genuine practice. S#93INING #7E BOD8 (I#7O4# 4SING M4SC;ES #esting Indi>idual Effe ti>eness This techni2ue in&ol&es straining the (hole body and differs little from straining the brain. .hen a(akening from sleep make one to three attempts at straining the (hole body refraining from actually fle#ing any physical muscle. )f nothing happens try another techni2ue. 9ibrations may occur as a result and amplifying these by straining the body (ithout using muscles can induce a spontaneous separation from the body. .hen the &ibrations become strong enough attempt a separation techni2ue. 4ounds often arise during the &ibration (hich allo( for listening in and a subse2uent entrance to the phase. #raining To practice- (hile lying do(n eyes closed try to strain the entire body (ithout using physical muscles for se&eral minutes. Tingling internal pressure and a strain on the brain often occur during this e#ercise. Remember to a&oid straining any real muscles. )f physical strain occurs results may be forfeited in the critical moment of fruition. ?IS43;IB3#ION )mmediately after (aking from sleep remain motionless eyes closed. For three to fi&e seconds con%ure an intense desire to see and literally create a specific ob%ect. The ob%ect should be en&isioned at
rest about four to eight inches from the practitioner. 0imit the &isuali=ation to simple familiar ob%ects like an apple flo(er sphere or hand. 4ometimes it is useful to imagine an ob%ect floating %ust abo&e the eyebro(s instead of directly in front. )f nothing appears during this period of time a different techni2ue should be used. )f an ob%ect appears one should keep looking hard at it and at a certain moment one (ill reali=e that one is already standing ne#t to it some(here in the (orld of the phase. .hen the ob%ect becomes realistic one can also try to separate from oneDs body on oneDs o(n. SENSO98-MO#O9 ?IS43;IB3#ION )mmediately after (aking from sleep remain motionless eyes closed. )magine acti&e physical mo&ement for 1A to 1; seconds (hile touching an actual ob%ect and simultaneously e#amining the imagined details of the room. )f nothing appears during this period of time a different techni2ue should be used. )f real and imagined sensations become mi#ed then continue the practice until the imagined sensations o&ercome the primary senses. IM3GINED MO?EMEN# )mmediately after (aking from sleep remain motionless eyes closed. For ; to 1A seconds concentrate on &isuali=ing any of the follo(ing actions- (iggling (alking running somersaulting pulling a rope or s(imming. Try to imagine the mo&ement as a realistic and acti&e e&ent during the practice period. )f nothing happens a different techni2ue should be employed. )f results occur in the form of the sensation of mobility the imagined mo&ement should be continued until it becomes the dominant sensation. .hen the mo&ement achie&es primacy it is accompanied by translocation to the phase. )f such a translocation does not automatically occur a separation techni2ue is recommended. IM3GINED SENS3#IONS
)mmediately after (aking from sleep remain motionless eyes closed. For three to fi&e seconds en&ision that a specific ob%ect is being held in the hand. )f nothing happens a different techni2ue should be practiced. )f the impression of shape and (eight become apparent concentrate harder on the sensation trying to compound the e#perience. Once the ob%ectDs presence in the hand achie&es a realistic 2uality separation is possible. 6o(e&er it is preferable to continue handling the ob%ect. 1 practitioner is free to imagine any type of ob%ect that fits in the hand. E#amples include a telephone a drinking glass a remote control a ball a pen or a bo#. IM3GINED SO4NDS Upon a(akening (ithout mo&ing or opening oneDs eyes one should acti&ely try to hear a specific sound or (ord e.g. someoneDs name or a melody. )f nothing happens the techni2ue should be changed for another one. )f sound arises one should try to listen in to it. .hen it peaks in &olume one may try to separate. E8E MO?EMEN# )mmediately after (aking from sleep remain motionless eyes closed. Perform t(o to fi&e sharp left"right or up"do(n eye mo&ements. )f nothing happens the techni2ue should be e#changed for another. )f &ibrations occur separation may be attempted after efforts to intensify the &ibrations. DO# ON #7E /O9E7E3D )mmediately after (aking from sleep remain motionless eyes closed. For three to fi&e seconds &isuali=e a point in the middle of the forehead. )f nothing happens a different techni2ue should be used. )f &ibrations occur they may be intensified by using this techni2ue or by straining the brain facilitating separation from the body. 1lso sounds may arise that allo( the practice of listening in.
/E39 ME#7OD )mmediately after (aking from sleep remain motionless eyes closed. For three to fi&e seconds imagine something horrific and gra&eyard"related staying nearby something graphic macabre out of the (orst nightmare imaginable. )f nothing happens a different techni2ue should be employed. 6o(e&er acute fear may occur most likely forcing the practitioner into the phase (here a separation techni2ue may be applied. 1lternati&ely &ibrations or noise may arise and allo( the use of other indirect techni2ues. 1 common problem (ith the use of this techni2ue is that fear often makes the practitioner so uncomfortable in the phase that he desires nothing else than to return to (akefulness. 9EC3;;ING #7E P73SE S#3#E )mmediately after (aking from sleep remain motionless eyes closed. For three to fi&e seconds recall the sensations that accompanied a pre&ious phase e#perience. FThis only (orks if the practitioner has achie&ed phase entrance in the past.G Either nothing (ill happen and a different techni2ue should be used or these sensations (ill be recalled and separating from the body may be tried " if it doesnDt occur spontaneously. 9ibrations or noise may also arise during this techni2ue in (hich case listening in or straining the brain may be practiced. B9E3#7ING CONCEN#93#ION )mmediately after (aking from sleep remain motionless eyes closed. For three to fi&e seconds focus on breathingJ the rise and fall of the rib cage the inflation and deflation of the lungs the intake and escape of air. )f no results occur a different techni2ue should be used. )f &ibrations noise or spontaneous separation occur the practice of this techni2ue should be intensified and used to its full ad&antage.
SE;EC#ING #7E 9IG7# #EC7NI<4ES The ne#t step to mastering indirect techni2ues is choosing the right techni2ues that suit indi&idual predispositions. There is no point in going for one techni2ue or another only because they look interesting and because someone (rote a lot or spoke a lot about them. The choice should be based strictly upon (hat suits an indi&idual practitioner. Out of all of the enumerated primary indirect techni2ues practically only straining the brain (orks easily and 2uickly for @;K of practitioners. 1ll other techni2ues (ork immediately for only about +;K to ;AK of practitioners during initial training. 6o(e&er after se&eral training sessions each techni2ue yields results for >;K of engaged practitioners. One (ay or another e&ery practitioner should identify a certain set of techni2ues that (orks best. 1 set should consist of no less than three techni2uesJ four or fi&e is e&en better to allo( more options and practical combinations. 'on"(orking techni2ues should not be discarded (holesale by the indi&idual because they afford an opportunity to achie&e success through ne( pre&iously unresponsi&e e#periences. To ensure the correct selection of techni2ues each should be separately practiced o&er a period of at least three days. To this end one should e#periment (ith each of the primary techni2ues for + to 1A minutes before falling asleep or e&en during the day. )t is good to choose at least one secondary techni2ue practice. This regimen allo(s a precise determination of the techni2ues that (ill yield the best results for the practitioner. 7uring the process of selecting personali=ed techni2ues a practitioner learns and retains the techni2ues in an intimate personal (ay (hich positi&ely affects ho( techni2ues are used during critical moments. )t is (orth noting that the final selection of techni2ues should be &aried. For e#ample choosing both straining the brain and straining the body (ithout using muscles is pointless because they are practically one and the same. More often than not they (ill both either (ork or not (ork. This is (hy techni2ues should in&ol&e
&arious types of sensory perception- &isual audio kinesthetic &estibular imaginary sense perception and internal strain. Remember that priorities and goals change (ith time and that a techni2ue that fell flat during initial attempts may une#pectedly pro&e &aluable later on. 5e fle#ible. 'o set of techni2ues should be car&ed in stone. )n fact the set may change se&eral times o&er the first fe( (eeks as the practitioner disco&ers (hat produces the best indi&idual results. To close this section a list has been pro&ided detailing the most effecti&e indirect techni2ues. This list (as compiled (ith classroom data from the 4chool of Out"of"5ody Tra&el and may pro&e helpful in determining an effecti&e set of indirect techni2ues. #he Most Effe ti>e Indire t #e hni$ues at S hool of Out-ofBody #ra>el Se'inars Obser&ing )mages 1;K Phantom .iggling 1;K 0istening in 1;K Rotation 1AK 4training the 5rain ;K 4training the 5ody .ithout Using Muscles ;K Forced Falling 1sleep ;K Mi#ture of Techni2ues 1AK Other Techni2ues +AK SEP393#ION #EC7NI<4ES 0et us begin (ith a totally shocking fact- during one"third of successful indirect entries into the phase it is not necessary to perform any specific phase entry techni2ues as separation techni2ues are immediately successfulN This has been statistically pro&en at 4chool of Out"of"5ody Tra&el seminars and in the analyses of other sources. ,on&ersely an incorrect understanding of separation techni2ues may lead to undesirable conse2uences. )t is possible for a practitioner to enter the phase state and be unable to separate from the
body. Therefore it is &ery important to understand ho( separation techni2ues (ork since they are often a key to success. Interesting Fact! Relatively often, a practitioner &ill try to e$ploy separation techni4ues to no effect, ho&ever, he &ill later une#pectedly understand that he had "een lying in a different position than he sensed that he &as in, and in fact, it had only "een necessary for hi$ to stand up( This happens $ostly a$ong "eginners and is indicative of an incorrect understanding of separation techni4ues( 1t times a practitioner may only need to think about separation and it happens. This is a rarity (hich e#plains the e#istence of a (hole series of au#iliary techni2ues. The most important separation techni2ues are rolling out getting up climbing out and le&itation. 9O;;ING O4# .hile a(akening attempt to roll o&er to the edge of the bed or the (all (ithout using any muscles. 7onDt (orry about falling out of bed hitting the (all or be concerned (ith the details of ho( this techni2ue should feel. Cust roll. GE##ING 4P Upon a(akening attempt to get out of bed (ithout physical e#ertion. This should be performed in a (ay that is most comfortable for the practitioner. C;IMBING O4# .hile a(akening try to climb out of the body (ithout using any muscles. This techni2ue generally comes to mind (hen a partial
separation has been achie&ed through the use of other techni2ues or one part of the body has completely separated. ;E?I#3#ION Upon a(akening attempt to le&itate up(ard parallel to the bed. .hile attempting to le&itate do not (onder ho( it should be accomplishedJ e&eryone intuiti&ely kno(s ho( to le&itate from their e#periences in dreams. /3;;ING O4# Practically the same as le&itation- upon a(akening try to sink do(n through the bed. P4;;ING O4# 6ere upon a(akening try to e#it the body through the head as if escaping from a lidded cocoon. B3C=(39DS 9O;; 1fter a(akening try to perform a back(ards somersault o&er the head (ithout using any physical muscles. B4;GE #7E E8ESC Upon a(akening bulge out or (iden the eyes (ithout opening them. Frontal mo&ement to(ard separation may result. 4eparation techni2ues are united by a singular idea- nothing should be imagined mo&ement should be attempted (ithout the use of physical muscles. The techni2ues produce the same sensations of mo&ement felt in real life. )f nothing happens immediately after trying then the techni2ue is not going to (ork though it may deli&er results at a later time. 1 practitioner (ill instantly be able to
recogni=e if the techni2ue has (orked. 6o(e&er people are often unprepared for the realness of the sensations and think that they are making a physical mo&ement instead of reali=ing that a part or all of the body has separated. 1fter this unfortunate failure careful analysis helps to understand (hat happened and plan for a successful retry. )f separation (as incomplete or took place (ith some difficulty this is a signal that the techni2ue is being performed correctly. 4trength and aggressi&e effort are re2uired from this point to achie&e complete separation. For e#ample if some mo&ement began and then stopped after ha&ing made some progress then one should go back and mo&e e&en harder once again in the same direction. )n order to practice separation techni2ues lie do(n (ith the eyes closed and attempt all of them o&er the course of se&eral minutes. 4eparation has likely been accomplished if no muscles t(itch or strain and a sensation of mo&ement occurs. There (ill be a strong almost physically palpable internal effort to perform a mo&ement. 'aturally no physical mo&ement actually occurs and the practitioner remains prone and immobileJ ho(e&er at the right moment these actions (ill lead to an easy entrance into the phase. Interesting Fact! %ppro#i$ately 17 to 87 of the ti$e that the phase is practiced, one reali*es i$$ediately upon a&a+ening that one has already separated( This $eans that one $ay already go so$e&here and stand, lie do&n, sit do&n, etc( This is not ho&ever "eco$ing conscious in a drea$, "ut an actually a&a+ening( #7E BES# #IME #O P93C#ICE The key to practice is the 2uantity and 2uality of attempts made that hone a practitionerDs skills. There are se&eral (indo(s of time best suited for employing indirect techni2ues. To begin it should be stated that sleep follo(s a cyclical pattern. .e a(aken e&ery hour"and"a"half and then 2uickly fall asleep again
(hich gi&es rise to sleep cycles. Furthermore (e e#perience t(o primary stages of sleep- rapid eye mo&ement FREMG sleep and non" rapid eye mo&ement F'REMG sleep. 'REM sleep includes many internal stages. The more (e sleep the less the body needs deep 'REM sleep and the more time (e spend in REM sleep. Phase entrance is most likely to occur during REM sleep.
The best (ay to implement indirect techni2ues is by the deferred $ethod. The aim of the method is to interrupt a sleep cycle during its final stage and then disrupt it again after falling back to sleep (hich makes sleep light during the rest of the sleep cycle. 4leep accompanied by fre2uent interruptions can be put to producti&e uses. For e#ample if a practitioner FletDs call him CackG goes to sleep at midnight then Cack should set an alarm for < oDclock in the morning. Upon a(akening Cack should engage in some sort of physical acti&ity like going to the bathroom getting a drink of (ater or reading a fe( pages of this book. 1fter(ard Cack should go back to bed thinking about ho( (ithin the ne#t t(o to four hours he (ill (ake up multiple times and make an attempt to enter the phase during each a(akening. )f Cack goes to bed earlier then his alarm clock should be set back by that amount of time since si# hours of initial sleep is the optimal length of time. )f Cack sleeps less than si# hours then the second half of his nightDs sleep (ill be too deep. )f Cack sleeps longer than si#
hours then there (ill be little time remaining for attempts or Cack may not e&en be able to fall asleep. )f a practitioner naturally (akes up in a forceful manner it (ill be difficult to regain sleep. Thus it (ill not be necessary for the practitioner to get out of bed (ith the aid of an alarm. The practitioner should attempt to go right back to sleep. 'aturally the deferred method is most applicable in cases (here it is possible to sleep as long as a practitioner desires (ithout ha&ing to (ake up early. 'ot e&eryone en%oys such lu#ury on a daily basis but nearly e&eryone has days off (hen time may be set aside to practice the deferred method. -t is in large $easure due to the deferred $ethod that classroo$ courses at the School of Out-of-Body Travel allo& up to 298 of class participants to enter the phase in the course of a single &ee+end, The second most effecti&e (indo( of time for entering the phase is ordinary $orning a&a+ening( This generally occurs during light slumber follo(ing a full nightDs sleep. 1nother effecti&e time to practice indirect techni2ues is after a(akening from a daytime nap. Once again this type of sleep (ill be light and short (hich pro&ides the body needed rest (hile allo(ing memory and intention to be kept intact through the moment of a(akening. 1gain not e&eryone has the lu#ury of taking daytime naps but if such a chance arises then it (ould be &ery beneficial to take ad&antage of the opportunity. /ightti$e a&a+enings are the least effecti&e times for phase e#perimentation because the brain still re2uires a lot of deep sleep at this time. 1(akening at night the mind is 2uite (eak and hardly capable of any effort. E&en if some results are obser&ed a(akening often ends (ith 2uickly falling back asleep. This is not to say that normal practice of the phase cannot occur at nightJ it %ust (onDt be as effecti&e as at other times. The nighttime option is best for those (ho lack an opportunity to use other (indo(s of time for practicing the phase. Understand that (e a(aken at night e&ery @A minutes (hich is (hy a minimum of four a(akenings is almost guaranteed (hen sleeping e&en for %ust si# hours. .hen the practitioner kno(s about
this and stri&es to sei=e those moments (ith time he (ill actually sei=e them and take ad&antage of them. CONSCIO4S 3(3=ENING :onscious a&a+ening is (aking up (ith a particular thought in mindJ ideally a thought about indirect techni2ues. )n order to start using indirect techni2ues upon a(akening it is not sufficient to ha&e a cursory kno(ledge of the techni2ues to be used (hen (aking. 7ue to the peculiarities of the human mind and its habits it is not al(ays easy (hen (aking to recall any particular moti&e or idea. The goal of conscious a(akening is to practice instant action (ithout being idle after (aking up. Interesting Fact! There e#ists a "elief that the pheno$enon of outof-"ody travel is practically unattaina"le, and is accessi"le only to an elect fe& through practices that re4uire secret +no&ledge( 0o&ever, the greatest difficulty &hen trying to e#perience out-of"ody travel in a short period of ti$e lies only in i$$ediately re$e$"ering a"out the techni4ues upon a&a+ening &ithout $oving( This is all si$ple and straightfor&ard( But it is precisely this trifle that is the largest stu$"ling "loc+ &hen trying to e#perience such an unco$$on pheno$enon( This is not difficult at all for appro#imately +;K of the population. 6o(e&er for the other three"2uarters of the population this is an difficult barrier to entry that can e&en seem insurmountable. )f such thoughts arise one should simply understand that this cannot be so and that persistent attempts and training are the key solution. The reasons (hy people are unable to remember practicing the phase upon a(akening are- not being in the habit of immediately doing anything upon a(akening a desire to sleep longer a desire to
go to the bathroom being thirsty a desire to suddenly start sol&ing day"to"day problems and so on. ,onscious a(akening (ith the intent of attempting an indirect techni2ue should be a practitionerDs primary goal (hich should be pursued at e&ery cost. The speed at (hich the phase is learned and e#perienced depends on this. There are se&eral effecti&e tricks to learning conscious a(akening-ntention upon falling asleep' This is the &ery important to successfully achie&ing conscious a(akening. 1 &ery clear scientific fact has been pro&en by somnologists Fscientists (ho study sleepGupon a(akening people usually think about (hat they had been thinking about before falling asleep. This phenomenon is easy to obser&e if the sleeper is e#perience a serious life problemJ they fall asleep (ith the problem and (ake (ith it. 4o in a case like this if difficulties at the front of the mind are replaced (ith a desire to practice the phase this (ill produce the desired effect. )t is not necessary to think solely about conscious a(akening (hile falling asleep. )t is sufficient to simply affirm the intention clearly and distinctly e&en state the intention out loud. Practicing these types of conscious actions (hile entering sleep (ill do much to promote the success of indirect techni2ues upon a(akening. ;eneral intent' The more clearly a practitioner concentrates on the importance and necessity of (aking up and immediately remembering to practice the techni2ues the more solid the intent (ill become and the more likely the process (ill fulfill its role and actually lead to results. %ffir$ing desires' 4ometimes an internal intention is simply not enough for some people or they are unable to properly affirm one by &irtue of indi&idual characteristics. )n this case an affirmation of desires should be introduced at the physical le&el. This could be in the form of a note (ith a description of a goal placed ne#t to the bed under oneDs pillo( or hung on the (all. )t could be a con&ersation (ith friends or family about the particular desire or by repeatedly &ocali=ing the actions that need to be performed upon a(akening. )t could e&en be an entry in a diary blog or te#ting on a mobile phone.
%naly*ing unsuccessful a&a+enings( 1naly=ing unsuccessful attempts at conscious a(akening is e#tremely important. .hen remembering the failed attempt after se&eral minutes se&eral hours or e&en later in the day focus on it and resol&e to succeed during the ne#t attempt. 7eep e#ploration of the failure is highly effecti&e and practical since the practitioner is learning (hat (orks (hat doesnDt (ork and making healthy resolutions to(ard success. :reating $otivation' The greater the desire to enter into the phase to accomplish a goal there the 2uicker successful conscious a(akening is achie&ed. Moti&ation is be created by a great desire to do or e#perience something in the phase. )n general pre&ious &isits to the phase are great moti&ation but an uninitiated person does not kno( it and (ill need something to (hich they can relate. For some this could be a childhood dream of flying to Mars for others it could be the opportunity to see a lo&ed one (ho has passed a(ay for another it could be the chance to obtain specific information or influence the course of a physical illness and so forth. 1side from natural methods to achie&e conscious a(aking there are &arious de&ices and tools that facilitate a measure of success. These (ill be co&ered in ,hapter ; in the section describing non" autonomous (ays of entering the phase. The "est $o$ent for conscious a&a+ening is &hile e#iting a drea$( This is the $ost effective and productive ti$e to atte$pt separation or perfor$ing the techni4ues( 1t this moment physical a(areness of the body is at a minimum. 1(areness at the &ery end of a dream often occurs after nightmares painful e#periences in the dream falling dreams I any dream that causes a sudden a(akening. .ith time one should de&elop a refle# that enables one to perform planned actions at the moment of a(akening but (hen consciousness itself has not yet had time to return. This type of refle# is highly beneficial to sei=ing the most fruitful of opportunities to enter the phase. 7ue to &arious psychological and physiological factors it is not possible for e&ery person to achie&e conscious a(akening after e&ery sleep cycle. Thus there is no point in becoming upset if conscious a(akening does not occur e&ery time. E#periencing only + to 8
a(akenings per day is normalJ this is sufficient enough to attempt phase entrance + to ; times per (eek (hen practiced daily. )t is not (orth getting carried a(ay (ith an e#cessi&e number of attempts. 7uring the 4choolDs courses it has been noted that doing 1A conscious a(akenings or more Fsome students try +A or e&en 8AG o&er the course of one night and morning rarely yields results. This is due to the fact that if one sets oneself a goal that is desired so much that its reali=ation breaks the natural rhythms of the body one depri&es oneself of the intermediate transitional states that make the phase effecti&e. 1 practitioner may also 2uickly become emotionally e#hausted from the large number of attempts and be unable to push limits in the right direction. The upside is that one (ill simply tire out. )f that starts to happen it is better to calm do(n and try to approach the matter in a more rela#ed manner e&enly and gradually. 3(3=ENING (I#7O4# MO?ING 1longside remembering the phase immediately upon (aking another important re2uirement is a(akening (ithout mo&ing (hich is difficult since many people (ake up and mo&e. Upon a(akening scratching stretching opening the eyes and listening to real sounds should be a&oided. 1ny real mo&ement or perception (ill &ery 2uickly disintegrate the intermediate state and introduce reality the acti&ation of the mind and its connection to the sensory organs. 1t first a(akening (ithout mo&ing seems difficult or e&en impossible. 6o(e&er it has been pro&en that this is remedied for through acti&e attempts and the desire to achie&e set goals. People often claim that they cannot a(aken (ithout mo&ing that itDs an impossible e#perience. 6o(e&er after se&eral attempts it (ill happen and it (ill occur more and more fre2uently (ith practice. Thus if there is difficulty in a(akening (ithout mo&ement do not despair %ust keep trying. 4ooner or later the body (ill yield to the practice and e&erything (ill happen smoothly. 1(akening (ithout mo&ing is &ery important because for the ma%ority of people e#periments (ith the phase are not possible e#cept in the first (aking moments (here (aking (ithout mo&ing
sets the stage for successful indirect techni2ue cycles. Often a practitioner (ill make 1A unsuccessful attempts and mo&e (hile a(akening. Once the practitioner learns to consistently (ake calmly and gradually success 2uickly follo(s. 6o(e&er if an a(akening is conscious but (ith mo&ement that does not mean that the practitioner cannot immediately make an attempt to fall into the phase. 4uch attempts although they (ill be about ; times less effecti&e than usual should ne&ertheless be made 1ny opportunity to practice (hile (aking should not be (asted. )t must only be kept in mind that one must first neutrali=e the effects of the mo&ement in order to once again fall into an intermediate state. )n the case of mo&ement it is e#tremely helpful to begin practice (ith forced falling asleep. 0istening in also (orks (ell as does obser&ing images and phantom (iggling each performed passi&ely for ;"1; seconds instead of the standard duration of 8 to ; seconds. 1fter performing these cycling may begin. 1(akening (ithout mo&ement despite all its importance is not a goal in and of itself and also not (orth suffering o&er. .hen a(akening if there is great discomfort something itches a need to s(allo( arises or any manner of natural refle# it is better to deal (ith it and then act according to practices recommended (hen mo&ement upon a(akening happens. 'ot all mo&ements upon a(akening are real and if only for this reason alone (hen mo&ement occurs indirect techni2ues should follo(. Interesting Fact! <p to 2 7 of sensations and actions that happen upon a&a+ening are not real as they see$, "ut are phanto$( False sensations occur in (idely di&erse (ays. People often do not understand (hat is going on (ith them (ithout ha&ing e#perienced the phase. For e#ample a person may think they are scratching their ear (ith their physical hand (hen they are really using a phantom hand. 1 person may hear pseudo"sounds in the room on the street or
at the neighborDs (ithout noting anything unusual. Or a person may look around the room (ithout kno(ing that their eyes are actually closed. )f a practitioner recogni=es such moments for (hat they are they may immediately try to separate from the body. C8C;ES O/ INDI9EC# #EC7NI<4ES Thus far indirect techni2ues used for phase entrance and techni2ues for separation in the phase ha&e been co&ered. ,onscious a(akening and the best times to practice it ha&e also been e#amined. 'o( a specific algorithm of action for indirect techni2ues (ill be presented. Follo(ing this algorithm promises 2uick and practical results. 1lgorithm of 1ction upon 1(akening-
1D #esting Separation #e hni$ues 6ithin ) Se onds 0ike the pre&ious obser&ation of separation techni2ues a third of successful attempts (ith indirect techni2ues yield immediate success upon the attempt of a separation techni2ue due to the fact that the first seconds after (aking up are the most useful for entering the phase. The less time that has elapsed after a(akening the better.
,on&ersely if one lies do(n e#pecting something to happen chances 2uickly dissipate. Thus upon a(akening preferably (ithout first mo&ing a practitioner should immediately try &arious separation techni2ues like rolling out getting up or le&itation. )f a techni2ue suddenly started to yield results for appro#imately for ; seconds then separation from the body should be attempted. 4ometimes inertia difficulty or a barrier (ill arise during a separation attempt. 'o attention should be gi&en to these problems. )nstead resol&e to separate " decidedly and aggressi&ely climb out of the body. Beep in mind that trying to immediately separate upon a(akening is a skill of the utmost importanceJ one that is (orth honing from the &ery beginning ne&er forgotten. "D #he Cy le of Indire t #e hni$ues to 4se if One is 4na0le to Separate )f separation does not occur after se&eral seconds it most likely means that separation (ill not occur regardless of elapsed time in effort. This is (here the practitioner must resort to other techni2ues. The practitioner should already ha&e chosen a minimum of three primary or secondary techni2ues that suit a practical repertoire. 6ere is (here the techni2ues are put into action. /ota Bene, -n order to give a specific e#a$ple, &e &ill e#a$ine the use of three specific techni4ues, &hich should "e replaced &ith a tested and chosen set of techni4ues( The follo(ing operational techni2ues ha&e been used as e#amples- obser&ing images FaG phantom (iggling FbG and listening in FcG. 1fter an unsuccessful attempt at separating the practitioner immediately starts obser&ing the &oid behind the eyes. )f images begin to appear (ithin 8 to ; seconds obser&ation should continue (ithout scrutini=ing the images in detail or the image (ill e&aporate. 1s a result of this action the image (ill 2uickly become more and more realistic and colorful engulfing the practitioner. )f e&erything comes together correctly a sudden translocation into the picture (ill occur or (hen the picture becomes &ery realistic attempt to separate
from the body. )f nothing happens after 8 to ; seconds then the practitioner should transition to the techni2ue of phantom (iggling. For 8 to ; seconds the practitioner 2uickly searches the entire body for a part that can be (iggled. Or the entire period of time is spent in an attempt to (iggle a specific body part- a finger hand or leg. )f the desired effect occurs then the practitioner should continue (ith the techni2ue and achie&e the ma#imum possible range of mo&ement. 7uring this process a number of things can happen including spontaneous separation a successful separation attempt free mo&ement of the (iggled part or the presence of sound or &ibrations. 1ll of these e&ents are of great ad&antage. )f nothing (iggles o&er the course of 8 to ; seconds then the practitioner should mo&e on to listening in. The practitioner should try to detect an internal sound. )f the sound is there listen and try to amplify it. 1s a result the noise may gro( into a roar and spontaneous separation (ill occur separating through the use of a techni2ue (ill be possible or &ibrations (ill occur. )f no noise occurs o&er the course of 8 to ; seconds then the entire cycle should be repeated. )t is beneficial to e#amine the reason behind the use of a set of three indirect techni2ues. This is moti&ated by the fact that the body often reacts to techni2ues in &ery peculiar (ays. .ith one person a techni2ue may (ork one day and not (ork on another day (hich is (hy if only one techni2ue is used e&en a &ery good techni2ue that (orks often a practitioner can miss out on a lot of different e#perience through the lack of &ariety in practice. Thus a practical repertoire should consist of se&eral techni2ues. Interesting Fact! So$eti$es, the first techni4ue that &or+s for a practitioner never results in a repeat of phase entrance again, although other techni4ues that &ere not i$$ediately effective at the novice stages of practice later "egin to &or+ regularly and successfully(
%D 9epeating the Cy le of Indire t #e hni$ues )f the first cycle of 8 techni2ues does not yield any clear results this does not mean that all is lost. E&en if the techni2ues do not (ork they still dra( the practitioner closer to the phase state and it is simply necessary to continue using the techni2ues by again obser&ing pictures phantom (iggling and listening in I and repeating this process at least three times. 6a&ing performed one cycle of techni2ues one can easily go on to doing a second cycle a third one a fourth one and so on. )t is 2uite probable that during one of these cycles a techni2ue (ill suddenly pro&e itself e&en though it had not been (orking at all %ust a fe( seconds beforehand. 1 serious practitioner should commit to a minimum of : cycles. The problem lies in the fact that it is psychologically difficult to do something that has sho(n itself not to (ork and one may gi&e up taking further action e&en though one could be at the cusp of falling into the phase. Beep trying and then try again and againH There ha&e been cases (here it took t(enty cycles to produce results. 1 monumental effort yes but one (orth the outcome. &D /alling 3sleep 6ith the Possi0ility of #rying 3gainD )f a practitioner is unable to enter the phase after performing cycles and attempts to separate or e&en if e&erything (orked out it is still better to go back to sleep to facilitate subse2uent attempts. 1gain it is &ery important to go to sleep (ith a clearly defined intention of actually performing the cycles upon a(akening. 4uch intention &astly increases the probability that the ne#t attempt (ill occur soon. That is one should not fall asleep (ith an empty head and the desire to simply get a good nightDs sleep. )f using the deferred method then clear intention is mandatory as se&eral attempts are possible o&er the course of a sleep cycle. E&en if only a fe( attempts are made accompanied by decided and concentrated effort then the four steps described in the algorithm (ill undoubtedly produce entrance into the phase.
)n order to more effecti&ely use the system of indirect cycles it is necessary to discuss (hat to do if one techni2ue (orks and progress ceases during the cycle and phase entry does not occur.
First understand that if a techni2ue has begun to (ork only lack of e#perience and skill (ill pre&ent the phase. 4econd barriers are o&ercome by temporarily s(itching to other techni2ues. 0et us suppose that noise arising (hen listening in gro(s louder and louder and then peaks in &olume. )t (ould surely be beneficial to s(itch to forced falling asleep or obser&ing images for se&eral seconds and then return to listening in. The sound may then become much louder and pro&ide an opportunity to proceed (ith the techni2ue. 4ometimes it makes sense to break off se&eral times into &arious techni2ues and then return to the primary techni2ue that yielded some results. )t is often possible to simultaneously perform t(o or e&en three techni2ues and e#perience no negati&e effect to results. )t is also normal and natural to skip around from techni2ue to techni2ue de&iating from a specific plan of action. For e#ample sounds often arise during phantom (iggling. )n this case a practitioner may %ust
simply s(itch o&er to listening in. Other oft"encountered results pairings are- images from sound sound from rotation sound from straining the brain a strain on the brain from listening in &ibrations from rotation &ibrations from phantom (iggling and so forth. 3uring initial atte$pts at using cycles of indirect techni4ues, the pro"le$ of confusion during a critical $o$ent $ay arise, &hen a novice practitioner suddenly forgets e#actly &hat to do and ho& to do it( This is nor$al, and the solution is to i$$ediately do &hatever co$es to $ind( Results can "e achieved in this $anner( 5hen a practitioner is $ore rela#ed a"out the practice, such pro"le$s &ill no longer occur( 7IN#S /9OM #7E MIND 9aried cycles of indirect techni2ues is an almost mandatory precondition for getting the best result. There are some e#ceptions. 4ometimes through indirect indicators a practitioner may be inclined to begin (ith certain techni2ues regardless of (hat had been planned. These are a sort of hint from the body and the ability to use such cues plays an e#tremely important role in the use of indirect techni2ues because they enable a practitioner to substantially increase the effecti&eness of practice. 7int NoD 1C I'ages )f the practitioner becomes a(are upon a(akening that some images pictures or remnants from dreams are before him then he should immediately proceed to the techni2ue of obser&ing images (ith all of the results that arise from it. )f this does not lead to anything then cycling (ith a set of techni2ues should begin. 7int NoD "C Noises )f the practitioner reali=es upon a(akening that he hears an internal noise roaring ringing (histling and so forth then he should immediately begin from the techni2ue of listening in. )f this has no effect then cycles of indirect techni2ues ought to commence.
7int NoD %C ?i0rations )f a practitioner feels &ibrations throughout the body (hile a(akening they should be amplified through the use of straining the brain or straining the body (ithout using muscles. .hen the &ibrations reach their peak the practitioner can try to separate. )f nothing happens after se&eral attempts indirect techni2ue cycles should start. 7int NoD &C Nu'0ness )f a practitioner (akes to numbness in a body part phantom (iggling of that part should be attempted. )f no result is achie&ed after se&eral attempts cycling should be tried. Of course it is better to refrain from techni2ues if the numbness is &ery intense and causes substantial discomfort. 3GG9ESSION 3ND P3SSI?I#8 7uring the practice of indirect techni2ues including techni2ue cycles unsuccessful attempts may result in falling asleep or becoming completely a(ake. These results indicate a deficiency or e#cess of aggression. )f a practitioner usually falls asleep (hile attempting to enter the phase then more aggressi&e action is needed (hile performing indirect techni2ues. )f on the other hand most attempts end in a full and alert a(akening then aggression should be curbed and techni2ues should be conducted more slo(ly and in a more rela#ed manner. 5alance bet(een passi&ity and aggression is imperati&eJ the phase state is easily attained by those practitioners (ho find a stable medium bet(een passi&ity and aggression. The issue of aggression re2uires a closer e#amination. =uite often, atte$pts at indirect techni4ues are $ade leisurely, &ithout desire or real effort, to >chec+ the$ off the list?( Results $ore easily reali*ed if the practitioner possesses an aggressive desire to enter the phase( More often than not, practitioners lac+ aggressive desire, instead of having too $uch of it( Thus, each effort re4uires a distinct &ant to succeed(
S#93#EG8 /O9 3C#ION 4ome mistakenly belie&e that indirect techni2ues (ill produce 2uick easy results like a pill. 7espite the fact that the techni2ues described in this guidebook are the best means to entering the phase strong effort still needs to be e#erted. This is not important for some as e&erything comes 2uite easily to them but for others this is of great importance. )ndirect techni2ues (ill definitely (ork if practiced consistently and as described. )t has already been noted that in the ma%ority of cases making se&eral concentrated attempts upon a(akening (ithout mo&ement is sufficient enough to produce results. )t may take a lot of time and effort to achie&e phase entrance so practitioners (ho set goals and (ork diligently (ill be presented (ith a cro(n of success. 1ttempts are important in large measure not only for the final result but also for the process itself. 7uring practice the practitioner independently learns and sol&es issues that may not ha&e been understood in the guidebook. Other times the practitioner (ill encounter situations that ha&e ne&er been described at all. )tDs impossible to prepare a student for e&ery possible scenario so as a practitioner mo&es deeper into practice a uni2ue indi&idual perspecti&e and portfolio of e#periences de&elops (hich (ill certainly pro&e useful in the future. Until then diligent practice of the information presented in this book (ill ready a practitioner for that personal frontier. 1ctions in practice re2uire strict attention. 4tudy the techni2ues and selects those that (ork best. 4et the goal of consistent conscious (aking (ithout mo&ement. Make an ob%ecti&e of performing cycles of indirect techni2ues (hile (aking up day in and day out. 5ith such a clear course of action, the practitioner should never defocus his attention or dissipate his energy on other related actions, li+e, for e#a$ple, on direct techni4ues for entering the phase( )f the indirect techni2ues do not (ork in the course of se&eral days continue trying. The latest results occur in a matter of (eeks not months or years
like some sources maintain. 3oals are meant to be stubbornly pursued step"by"step firmly and diligently. )f no results occur after 1A to +A days it is better to cease practice for a (eek and take a rest and then return (ith a fresh resol&e to master the practice. )nterestingly enough it is e#actly during such a break that spontaneous entrances into the phase through the most di&erse methods occur. )f success is still elusi&e e&en after 1 to + months of trying then a thorough analysis of the regimen should be conducted to root out any ob&ious mistakes or deficiencies. )f o&ercoming them pro&es difficult or impossible s(itching o&er to direct techni2ues is not recommended since they pro&e much more difficult than indirect techni2ues. )nstead techni2ues for entering the phase through conscious dreaming should be practiced. )t is also not (orth skipping o&er problematic areas and trying to make up for mistakes by e#pending e&en more effort. For e#ample ignoring the precondition of a(akening (ithout mo&ing (ill pro&e fruitless. 5ypassing this re2uirement (orks for &ery fe( people. Facing e&ery problem head"on and (orking hard to break through (ill be richly re(arded (ith an unforgettable treasured e#periences. Beep tryingH #8PIC3; MIS#3=ES (I#7 INDI9EC# #EC7NI<4ES )nternal certainty that nothing (ill happen instead of belie&ing in positi&e results. 4topping the performance of techni2ues after an unsuccessful cycle (hen a minimum of four cycles should be practiced. ,onstantly a(akening to mo&ement instead of remaining still. Performing direct techni2ues in the e&ening. Total concentration on indirect techni2ues is re2uired from the morning on if a practitionerDs goal is access to the phase.
Performing indirect techni2ues for an e#tremely long period of time F+ minutes or moreG. This is a complete (aste of time in most cases. 4(itching from techni2ues that ha&e begun to (ork (hen practice should be follo(ed through to the end. Passi&ely performing techni2ues instead of being determined and aggressi&e. Performing each techni2ue separately for too long a period of time e&en if the techni2ue does not (ork instead of s(itching to another techni2ue (ithin se&eral seconds. E#cessi&e thinking and analysis (hile performing indirect techni2ues (hich re2uire mental tran2uility and inner stillness. 4topping and concentrating on unusual sensations (hen they arise &ersus continuing the techni2ue that brought them about in the first place. E#tremely long anticipation upon a(akening instead of immediately performing techni2ues. Premature attempts at separating instead of performing phase creation techni2ues through to the end of progress. 6olding the breath (hen unusual sensations appear. 5e calm instead. Opening the eyes (hen the only recommended mo&ement is breathing or mo&ing the eyes behind closed lids. 5eing agitated instead of rela#ed. ,easing attempts to separate e&en (hen partial success is met. 4training the physical muscles (hile performing the techni2ues &ersus remaining physically motionless. 'ot practicing after an alert a(akening (hen techni2ues are best applied " especially in the e&ent of (aking (ithout mo&ement. Merely imagining the techni2ues instead of really understanding them and performing them if of course one is not performing rotation or other imagined techni2ues.
4imply (iggling phantom limbs instead of employing a fi#ed determination to increase the range of mo&ement Falling right asleep during forced falling asleep instead of ha&ing the firm intention of continuing efforts (ithin only ; to 1A seconds. 4crutini=ing the details of images (hen using the techni2ue of obser&ing imagesJ the (hole image should be obser&ed panoramically lest it disappear. )ntentionally trying to force pictures (hen obser&ing images instead of looking for (hat is naturally presented. 4imply hearing noise (hen employing the techni2ue of listening in instead of attenti&ely trying to pay attention catch something and listen in.
1+. 1ccording to statistics from classes held at the 4chool of Out" of"5ody Tra&el (hich indirect techni2ues are the most effecti&e/ 18. .hy should one practice all of the primary techni2ues in a rela#ed state/ 1:. .hat helps practitioners to enter the phase one"third of the time (hile using indirect techni2ues/ 1;. )s le&itation the most popular separation techni2ue/ 1<. .hat is the essential difference bet(een indirect techni2ues and separation techni2ues/ 1>. 6o( does the separation techni2ue of rolling out differ from the indirect techni2ue of rotation/ 1?. )s it necessary to imagine anything (hile trying to separate/ 1@. .hen is the best time to use indirect techni2ues/ +A. ,an techni2ues that are traditionally used upon a(akening be attempted during the day/ 6o( effecti&e are these techni2ues during the day/ +1. )s becoming consciousness (hile dreaming the same as conscious a(akening/ ++. .hen employing indirect techni2ues does an inability to a(aken (ithout mo&ing ha&e an effect on oneEs practice/ +8. .hat are the components of the algorithm of cycling indirect techni2ues/ +:. .hat first step must be taken (hile cycling through indirect techni2ues/ +;. 6o( many different techni2ues should a cycle consist of/ +<. .hat is the minimum number of cycles that must be practiced/ +>. )f a lot of time has passed after a(akening is this good or bad for cycles of indirect techni2ues/ +?. .hat must be done if a techni2ue gets stuck at an unsatisfactory le&el of results/ +@. )f the cycles do not (ork (hat should be done/ 8A. .hat are hints from the mind/ 81. )n (hat cases is it necessary to introduce aggressi&e effort (hen performing indirect techni2ues/
#as!s 1. Try all of the primary indirect techni2ues (hile in a rela#ed state and single out 8 to ; techni2ues that seem to (ork. Repeat such training another couple of times on other days. +. Try all of the separation techni2ues in a rela#ed state. 8. 1chie&e one conscious a(akening follo(ed by cycles of indirect techni2ues. :. 1chie&e one conscious a(akening (ithout any physical mo&ement and attempt an indirect techni2ue. ;. Upon a(akening (ithout mo&ing perform a full cycle of indirect techni2ues and repeat this e#ercise until phase entrance is achie&ed.
+no&ledge of indirect techni4ues &ill $a+e it considera"ly easier to achieve direct entry into the phase( Ouality of the phase e#perience is not dependent upon the chosen entrance techni2ue. 7irect techni2ues do not necessarily pro&ide a deeper more lasting phase o&er indirect techni2ues. 7irect techni2ues are better suited for some practitioners and not others but this ban only be said for a minority of the practicing population. Mean(hile indirect techni2ues are accessible to absolutely e&eryone all of the time. )f a practitioner has decides to begin practice (ith direct techni2ues or has gained the necessary e#perience (ith indirect techni2ues the underlying principles of the techni2ues must still be learned. .ithout these nothing (ill occur e#cept coincidentally and in rare cases. The key to the successful use of direct techni2ues rests in achie&ing a free"floating state of consciousness. 6o(e&er (e (ill first e#amine a large &ariety of &ery useful aspects and factors that make direct entry into the phase much easier. First (e (ill e#amine (hen it is best to perform the techni2ues and ho( intensi&ely to e#ercise their practice. Then (e (ill e#amine the &ery important factor of body position and the no less crucial issue of ho( long the techni2ues should be performed. Then (e (ill briefly in&estigate the issue of rela#ation and then (e (ill immediately mo&e on to the actual direct techni2ues. Only after co&ering all of the abo&e are (e able to del&e into the issue of (hat a free"floating state of consciousness is and ho( to achie&e it. #7E BES# #IME #O P93C#ICE The issue of time is not important (ith indirect techni2ues since the ma%or prere2uisite is that they are performed immediately after a(akening occurs. )n the case of direct techni2ues the issue of timing is much more critical. 'aturally the best method for finding the right time to perform direct techni2ues is the same as indirect techni2ues I the deferred $ethod. 6o(e&er there are some serious differences here. First of all one may interrupt oneDs sleep at practically anytime of the night
or early morning. 4econd after ha&ing (oken up F;"1; min.G one should not fall back asleep but should immediately proceed to the techni2ues. 7irect techni2ues are many times more effecti&e (ith the deferred method than at any other time. This is due to the fact that (ith the deferred method the mind does not ha&e time to become 1AAK alert and it is easy to fall into the altered state of consciousness that (ill allo( results. .hen it comes to specific steps one should a(aken in the middle of the night either on oneEs o(n or (ith the help of an alarm clock. Then one should get up and do something for 8 to 1A minutes and then lie do(n again in bed and perform the techni2ues. )f it is probable that the practitioner (ill (ake up in too alert a state and thus not e&en be sleepy then the inter&al bet(een a(akening and performing the direct techni2ue should be shortened and fe(er things should be done during that period of time. )t should be noted that (ith this setup a free"floating state of mind plays a far lesser role that (ith other procedures. The second most effecti&e (indo( of time is "efore falling asleep at night (hen the practitioner goes to bed. 7uring this period of time the brain needs to shut do(n the body and mind in order to rene( its strength (hich has been e#pended o&er the course of the day. This natural process can be taken ad&antage of by introducing certain ad%ustments to it. 1ttempts at performing direct techni2ues during the day are less effecti&e. 6o(e&er if fatigue has already had a chance to build up by this time this can be taken ad&antage of because the body (ill try to fall into sleep. This is especially suited for those (ho are accustomed to napping during the day. 3enerally other (indo(s of time produce a substantially (orse result (hich is (hy one should start (ith performing direct techni2ues in the middle of the night or before a nightEs sleep. Only after such techni2ues ha&e been mastered (ill it be possible to e#periment (ith daytime attempts. IN#ENSI#8 O/ 3##EMP#S
The degree of enthusiasm that is de&oted to any pursuit is directly related to successfully reaching a goal. 6o(e&er it is &ery important to kno( (hen to ease up especially (ith the delicate matter of phase entry. One attempt per day using a direct techni2ue is sufficient. )f more attempts are made the 2uality of each attempt (ill suffer considerably. Interesting Fact! Many approach direct techni4ues as if digging a ditch' the $ore - the faster and the "etter( The result' do*ens of atte$pts that yield no fruit( 1 lot of practitioners belie&e that do=ens of attempts o&er the course of a day (ill yield the phase. This is not the path to success and (ill 2uickly lead to disillusionment (ith the practice. E&en if after a (eek or a month no results are seen direct techni2ues should be attempted only once daily. Persistent analytical and sensible stubborn resol&e to practice properly (ill produce the desired effect. D493#ION O/ 3N 3##EMP# )t is useless to attempt entering the phase using a direct techni2ue by lying in bed and resol&ing neither to sleep nor get up until the phase occurs. 4uch coarseness in handling delicate nature of the mind (ill produce nothing besides rapid emotional e#haustion. Rigid timeframes apply (hile performing direct techni2ues before a sleep or in the middle of the night. 7irect techni2ues attempts should only last 1A to +A minutes. 0onger durations inhibit sleepiness because the mind (ill concentrate too long on the techni2ues and the desire to fall asleep (ill dissipate resulting in insomnia that often lasts se&eral hours. O&erdone efforts negati&ely affect natural enthusiasm due lost sleep and being tired the follo(ing day (hich is compounded by the reality of a gro(ing number of failed attempts. )f direct techni2ues produce no effect o&er the course of 1A to +A minutes before sleep or in the middle of the night then it is better to
go to sleep (ith the thought that e&erything (ill (ork out another time. This is the positi&e outlook a practitioner ought to al(ays maintain. BOD8 POSI#ION .ith indirect techni2ues body position isnDt important since conscious a(akening regardless of body position is the goal. 6o(e&er the position of the body is crucial (hile practicing direct techni2ues. There is not an e#act body position that each practitioner should assume since once again indi&idual characteristics and instincts differ (idely. There are specific rules that allo( one to select the right position based on indirect indicators. Many hold a belief that the correct pose is that of a corpse I lying on the back (ithout a pillo( legs and arms straightened. This notion has probably been borro(ed from other practices claiming that it helps achie&e an altered state of mind. 6o(e&er this position seriously impairs the efforts of the ma%ority of practitioners. The corpse pose should only be used (hen it is probable that a practitioner (ill 2uickly fall asleep (hile performing techni2ues in this pose e&en though it generally pre&ents sleep. )f a practitioner e#periences difficulty falling asleep and is constantly a(ake (hile performing direct techni2ues then the most comfortable position for the indi&idual should be used. -f sleep co$es 4uite easily to a practitioner, a less natural position should "e ta+en( -f a practitioner e#periences fe&er gaps in consciousness &hen the techni4ues are perfor$ed and has a harder ti$e falling asleep, a $ore co$forta"le a position should "e used( 7epending on the situation there are many possible positions- lying do(n on the back on the stomach on the side or e&en in a half" reclined position. )t is possible that a practitioner (ill ha&e to change positions from one attempt to another introducing ad%ustments related to a free"floating state of mind. 9E;3E3#ION
5y nature one should clearly understand that direct techni2ues are in and of themsel&es rela#ation methods inasmuch as no phase can occur (ithout one being rela#ed. 1ccordingly one can go immediately into the phase (ithout any prior rela#ation. 4ince the most effecti&e (indo( of time for using direct techni2ues occurs before sleep and at night and lasts only 1A to +A minutes in any case additional time should not be (asted on trying to rela# nor should time for rela#ation be subtracted from the re2uisite 1A to +A minutes. ,orrect and 2uality rela#ation is a difficult pursuit and many go about it indi&idually producing an opposition to natural rela#ation. For e#ample many endea&or to rela# their bodies to such a degree that in the end the mind is as acti&e as it (ould be (hile trying to sol&e a difficult mathematical e2uation. )n this type of situation entering the phase is impossible. The body automatically rela#es (hen the mind is rela#ed. The body in turn (ill ne&er rela# if the mind is acti&e. Therefore it is better for beginners refrain from the trouble of the nuances of rela#ation and sa&e their energies for more elementary matters. )nstead of forcing a technical rela#ation a practitioner should simply lie do(n for se&eral minutes and this (ill pro&ide the best rela#ation. 0ying do(n acti&ates natural rela#ation processesJ the most po(erful kind. ,omplete peaceful rela#ation may only be coerced by those (ith speciali=ed in"depth e#perience. 3enerally these are people (ho ha&e spent a great amount of time and effort mastering trance and meditati&e states. Rela#ation in these cases should take no more than 1 to 8 minutes and no longer as because (hen a practitioner is e#pert at rela#ation it is sufficient to %ust think about it and it occurs. 1ll 2uality rela#ation techni2ues may (ell ser&e as direct techni2ues if a free"floating state of mind occurs (hile they are e#ercised. 1fter gaining the necessary e#perience (ith trance and meditation a practitioner of these mental arts may proceed to mastering the phase.
?39I3#IONS O/ 4SING DI9EC# #EC7NI<4ES Techni2ues used to gain direct entrance to the phase are e#actly the same as those used during indirect attempts. The only difference is in the method of implementation. The techni2ues are described in detail in ,hapter +. 6o(e&er since direct techni2ues mostly re2uire passi&ity not all techni2ues (ork e2ually (ell for both direct and indirect entries into the phase. For e#ample acti&e techni2ues like straining the brain cannot be used to gain a smooth entrance into the phase. 7irect techni2ues differ from indirect techni2ues in their implementation because of the slo( halting production of results that occurs from the beginning of a direct attempt through the end of it. )f upon a(akening something happens to (ork then this can practically al(ays lead to entrance into the phase. For e#ample the same phantom (iggling before sleep can begin 2uickly enough but range of mo&ement (ill not be easy to increase and the entire implementation of the techni2ue (ill rely on protracted rhythmic mo&ement. Results take much longer- ten minutes instead of ten seconds. These differences also apply to e&ery techni2ue described in this guidebook. 0ike the practice of indirect techni2ues to begin the practice of direct techni2ues a practitioner should choose 8 or : of the most suitable techni2ues from those that pro&e most effecti&e to the indi&idual. )n order to assist the practitioner a table has been pro&ided detailing the documented effecti&eness of the direct techni2ues-
#he Most Effe ti>e Dire t #e hni$ues at Se'inars of the S hool of Out-of-Body #ra>el Phantom .iggling 1;K Rotation 1;K 0istening in 1;K 9ibrations Foccurring amid the use of other 1;K techni2uesG Obser&ing )mages 1AK Mi#ture of Techni2ues 1AK 4imple separation Fusually mi#ed in (ith other 1AK techni2uesG Other Techni2ues 1AK The primary difference in (orking (ith direct techni2ues is the time that it takes to e#ercise each. )f testing a specific indirect techni2ue takes only 8 to ; seconds then in this case se&eral minutes (ill be spent. 7uration &aries depending on certain factors. There are three primary (ays of performing the techni2uesclassical se2uencing and cycling " similar to the cycling used (ith indirect techni2ues. To understand (hich &ariant should be used consider the follo(ing table?ariations of 4sing the (hen to 4se It #e hni$ues :lassical Bpassive) variation' " (hen learning direct One attempt of 1 techni2ue. techni2uesJ The techni2ue may be alternated " (hen a practitioner generally after each attempt. sleeps poorlyJ " if attempts lead to (aking upJ " if attempts (ith other &ariations occur (ithout lapses in consciousnessJ " if the body and consciousness are in a rela#ed stateJ Se4uencing B$iddle)' " used if falling asleep occurs
One attempt (ith + to 8 techni2ues for 1 to ; minutes. Techni2ues are alternated infre2uently. 1ggression fluctuates (ith the length of time that the techni2ues are performed. :ycling Bactive)' 1lgorithm of cycling 8 techni2ues like (ith indirect entry to the phase but performing each techni2ue for 1A seconds to 1 minute and not 8 to ; seconds.
(hile using the classical &ariation or if cycling results in becoming (ide a(akeJ " (hen a practitioner generally falls asleep 2uicklyJ " if the classical and se2uencing &ariations put one asleepJ " (hen one generally falls asleep &ery 2uicklyJ " can also be employed (hen e#hausted or sleep depri&edJ
1 practitioner should al(ays begin (ith the classical &ariation i.e. using one techni2ue o&er an entire attempt. 7ue to the unusual nature of the efforts in&ol&ed a beginnerDs enthusiasm may sustain a completely alert state. 0ater ho(e&er strong prolonged lapses of consciousness into sleep may occur. 6ere it may be necessary to increase the le&el of acti&ity by transitioning to the se2uencing &ariation. 4e2uencing is the primary &ariation used for direct techni2ues because of its elasticity in application. )t can be passi&e if o&er the course of 1; minutes (hen a practitioner alternates t(o techni2ues for fi&e minutes. )t may also be aggressi&e if used se2uencing three techni2ues for one minute. E&erything bet(een these t(o e#tremes allo(s proper practice of the techni2ues and selection of the best &ariation to achie&e a free"floating state of mind. )f falling off to sleep stubbornly occurs e&en (ith the acti&e form of se2uencing then one should start cycling through indirect techni2ues but performing each techni2ue from 1A seconds to 1 minute. 1s long (ork (ith the techni2ues is implied one should not torment oneself if one does not (ant to do something other(ise one may
2uickly tire out. E&erything should be a pleasure to do and not cause any e#cessi&e emotional tension. #7E /9EE-/;O3#ING S#3#E O/ MIND There are almost infinite descriptions of direct entry techni2ues offered in literature stories on the )nternet and at seminars. 4ometimes one description fundamentally differs from another. )n the ma%ority of cases ho(e&er common threads e#ist that unite almost e&ery description of a particular techni2ue- short lapses in consciousness memory gaps and drifting in and out of sleep all of (hich are hallmarks of the free"floating state of mind. 1fter any of these phenomena occur all manner of unusual pre"phase or phase sensations arise. 0apses in consciousness may last for seconds se&eral minutes or more than an hour. They may range from a simple loss of consciousness to entrance into a full"fledged dream. They may be singular and rare or may occur se&eral times o&er the course of a minute. .hate&er a lapse entails the mind attains a mode of operating that is ideal for phase e#perimentation pro&ided the practitioner is able to refrain from deep sleep and 2uickly return to a conscious (aking state. 'ot e&ery lapse of consciousness leads to the phase. The lapse must ha&e sufficient depth to be effecti&e. Thus (ith e&ery unsuccessful lapse another deeper lapse should be incurred.
The primary practical dra(back of the free"floating state of mind is the possibility of falling completely asleep during lapses instead of only temporarily dipping into sleep. Techni2ues are definitely necessary to ensure the desired result. 4uch techni2ues more or less fulfill an au#iliary function and thus one need not be strict about them. Interesting /a tF -t does not $atter &hich direct techni4ue is used@ as long as it leads to lapses in consciousness, success is possi"le( .hen performing the &ariations of the techni2ues a practitioner can begin to &acillate bet(een full alertness and complete asleep coming to and then nodding off again. To a&oid falling asleep re2uires a strong desire to return to (akefulness. This is accomplished by a strong resol&e on the part of the practitioner e&en if (hile performing a direct techni2ue drifting in and out of sleep occurs. The practitioner must firmly assert that at
the moment consciousness tapers off a(akening (ill immediately occur. On the other hand if lapses do not occur and are replaced by complete alertness the follo(ing tricks of the trade may help- full concentration on mental actions or con&ersely musing and daydreaming in parallel (ith the techni2ue being used. )t should be noted that these are only effecti&e at the initial stages of (orking (ith direct techni2ues since such techni2ues ha&e a strong sleep"inducing effect. )f direct techni2ues do not lead to light sleep or singular lapses after a long period of regular practice then it must be assumed that the practitioner is dealing (ith some appreciable error in techni2ue or in the length of performance. Regulating the number of lapses that occur may be modified by body position during practice or by changing the &ariation used (hile performing techni2ues. Entering the phase (ith a free"floating state of mind most often occurs as the result of three key factors. First one techni2ue or another may begin to (ork (ell during a lapse. 4econd nearness to the phase may une#pectedly manifest itself through sounds or &ibration after a lapse. 7uring this transitioning to techni2ues that correspond to the abo&e symptoms Flistening in straining the brainG may be applied. Third (hen e#iting a lapse it is sometimes easy to separate or 2uickly find a (orking techni2ue by paying attention to initial indicators. 0apses in consciousness are not bound to occur in 1AAK of cases. 6o(e&er stri&ing to achie&e lapses plays a &ery important role since they are not al(ays percei&able and a lapse occurrence is not al(ays ob&ious. They can be &ery short in duration or shallo(. Or they may not occur at all. 'onetheless properly applied techni2ues to produce lapses may gi&e entrance to the phase. 34EI;I398 /3C#O9S Using direct techni2ues in the e&ening or in the middle of the night take ad&antage of the bodyDs natural state of fatigue and for
practical purposes this natural tiredness may be amplified. For e#ample direct techni2ues more easily lead to success if the practitioner is considerably sleep"depri&ed. Moreo&er in such a state inducing a free"floating state of mind may be forgone. The most important thing is simply not to fall asleep immediately in addition to employing the appropriate &ariations (ith the techni2ues. .illful depri&ation of sleep is torturous and useless e&en though great results may be achie&ed by an e#perienced and kno(ledgeable practitioner in a se&erely fatigued state. 5eginners are better off approaching all forms of practice in a natural balanced (ay. 1n intense longing sleep is not limited to long periods of sleep depri&ationJ physical and emotional fatigues also play important roles. )n that case the most important thing is not to fall asleep (hen performing the techni2ues and thus one must select a more acti&e techni2ue &ariation than usual. S#93#EG8 /O9 3C#ION 7irect techni2ues seldom produce 2uick and clear results unlike entering the phase &ia becoming conscious (hile dreaming or through the use of indirect techni2ues. 1t first direct techni2ues produce sporadic results (hich is (hy the path of practice should not begin (ith direct techni2ues hoping for fast results. )t is better to systematically practice a techni2ue (orking to(ard mastery on a consistent basis. There is no cause for (orry if results are achie&ed after a month of daily attempts. 1 continual effort to analy=e practice and impro&e should be the primary focus because failures are al(ays caused by distinguishable mistakes. 1lthough difficulties may arise (ith direct techni2ues one should ne&er abandon (hat (orked until then Fi.e. indirect techni2uesG as this could temporarily depri&e one of the e#perience that one has gained so far. 1 combination of direct and indirect techni2ues should ne&er be used during the course of a single day since this (ould be detrimental to practical focus and enthusiasm. )t is better to separately perform
each type of techni2ue on different days. For e#ample direct techni2ues could be used before falling asleep during the (ork(eek (hile indirect techni2ues may be practiced during the (eekends (hen a practitioner has more chances to e#periment using the e#tra opportunities to sleep. #8PIC3; MIS#3=ES (I#7 DI9EC# #EC7NI<4ES 1ssuming an incorrect position (hen lying do(n. Performing direct techni2ues during the day (hen a practitioner is ine#perienced instead of in the e&ening or at nightJ Performing more than one attempt per day. Performing protracted rela#ation before the techni2ues e&en (hen this may play a negati&e role. Performing the techni2ues for too long (hen they should be e#ercised for no more than +A minutes. Forgetting to affirm a strong intention of a(akening during a lapse of consciousness. 0ack of a free"floating state of mind. This is mandatory Falling asleep during lapses in a free"floating state of mind instead of (orking to(ard multiple lapses (hile a(akening. Forgetting separation techni2ues and a(aiting some unkno(n e&ent upon emergence from a lapse instead of taking ad&antage of the moment. E#cessi&ely alternating the techni2ues in a primary repertoire instead of testing them in a planned and systematic manner. 6olding the breath (hen unusual sensations are encountered. 1l(ays be calm. 6alting practice (hen unusual sensations occur (hen it is necessary to continue (hat brought about the sensations. E#cessi&e e#citement (hile performing direct techni2ues. 0ack of aggression during attempts due to fatigue and sleep depri&ation.
0ack of a clear plan of action. Understanding and planning the use of distinct &ariations of the techni2ues beforehand is crucial to the analysis of subse2uent errors in practice.
1<. 4hould a(akening be attempted if falling asleep occurred (hile using direct techni2ues/ 1>. .hat is the probability of entering the phase (ithout a free" floating state of consciousness/ 1?. .hat do unsuccessful attempts using direct techni2ues most often end in/ 1@. )s se#ual acti&ity before an e&ening attempt using direct techni2ue beneficial/ #as!s 1. ,hoose the best body position for direct techni2ues based on your indi&idual preferences. +. Use the classical &ariation of performing direct techni2ues until it phase entrance or falling asleep se&eral times. 8. Using a combination of &ariations for direct techni2ues achie&e a free"floating state of mind. :. .hen performing direct techni2ues try to achie&e no less than three lapses in consciousness before +A minutes elapse or before you fall asleep. Repeat this challenge until phase entrance is achie&ed.
&ery moment. 1nd after a(akening he should not think that (hat happened (as absurd or une#plainable. 7uring the process of becoming conscious in a dream a practitionerDs actions must be completely subordinated to the desire to e#perience a 2uality phase. This is (hy upon becoming conscious in a dream proceeding to techni2ues related to deepening and maintaining is crucial. Techni2ues for becoming conscious in a dream differ &ery much in nature from other techni2ues and there are good reasons (hy these methods are differentiated from other practices like so"called astral pro1ection or out-of-"ody e#perience BOB2). 6o(e&er their characteristics differ &ery little in terms of results. The techni2ue"related peculiarities rest in the fact that specific actions are not re2uired to produce immediate concrete results. 1ll techni2ue"related elements are performed outside of (hen consciousness (hile dreaming occurs. This is because it is impossible to take some action if you are not conscious and do not reali=e that you are dreaming. 1ll efforts are directed at making that &ery reali=ation someho( occur. Interesting Fact! 2ven if a practitioner pays no heed to the techni4ues for "eco$ing conscious &hile drea$ing, "ut applies direct or indirect techni4ues, on average each fifth phase &ill still occur through "eco$ing conscious in a drea$( This has "een statistically proven at se$inars of the School of Out-of-Body Travel( Many stri&e to achie&e consciousness during each dream o&er the course of an entire nightJ ho(e&er this is rarely possible due to physiological barriers. There is a good reason that sleep and dreams are an important part of a human life. There is an important need to s(itch off not only body but also consciousness so that it may unconsciously sift and process the &ast &olume of information obtained in e&eryday life.
The timeframe for achie&ing conscious dreaming is &ery difficult to estimate due to the nature of re2uired actions. )ntensity and intention definitely e#ert hea&y influence. 1 practitioner may become conscious in a dream (hen first lapsing into sleep regardless of (hen it occurs. Or (ith regular attempts this could happen in t(o (eeks to a month. 'e&ertheless these techni2ues promise a much higher likelihood of success than direct methods and can be compared (ith indirect techni2ues " inferior to the latter only in terms of the speed at (hich results are achie&ed and the amount of effort re2uired. .hile indirect techni2ues yield ma#imum results in light of a full nightDs rest the amount of time spent in bed is not a significant factor to achie&ing dream consciousness. Therefore this techni2ue is sure to guarantee entry into the phase especially if difficulty has been encountered (hile practicing other techni2ues. Techni2ues used to attain dream consciousness should not be combined (ith other types of techni2ues. )t is better to focus on one thing at a time. -nterestingly, &hen a techni4ue is practiced on a regular "asis, there is nearly a 1 7 guarantee that drea$ consciousness &ill spontaneously occur( % practitioner $ust +no& ho& to react &hen this happens( #EC7NI<4ES /O9 BECOMING CONSCIO4S IN 3 D9E3M )t is possible to simultaneously practice se&eral techni2ues for becoming conscious in a dream since e&ery techni2ue is directly compatible and complementary to another. 9e'e'0ering Drea's There is a (ell kno(n and (idespread of fallacy that supposes that dreams do not occur for some people. E&eryone dreams but not e&eryone remembers their dreams. E&en those (ho acti&ely dream remember only a small fraction of these nightly e#cursions. 6ence one should not think that it is impossible for someone (ho does not remember dreams to become conscious in one. 4uch a person should simply try to use the techni2ues.
1t the same time there is a direct correlation bet(een the number of dreams remembered and the probability of becoming conscious (hile dreaming. That is (hy de&eloping the ability to remember dreams is crucial. )n essence the ability to achie&e dream consciousness rests (ith the conscious mind (hich is &ery much interconnected (ith memory"related processes. ,onsciousness is naturally inherent in dreams but it lacks rapid operati&e memory. 7reamers may kno( (ho they are their names ho( to (alk and ho( to talk but may not kno( ho( surrounding e&ents are related or the nature of their significance. 5y increasing the fre2uency of remembered dreams short"term dream memory becomes more de&eloped (hich enables more realistic dream e#periences follo(ed by a higher probability of dream consciousness. There are three techni2ues dedicated to increasing the number of remembered dreams. The first is to simply recall the details of dreams upon a(akening. .ithin the first fe( minutes of (aking up try to remember as many dreams from the night before as possible. This should be done (ith a great amount of attention and diligence because this e#ercise strengthens the memory. )f possible during the day or better yet before going to sleep at night recalling the pre&ious nightDs dreams once again is highly beneficial. .riting dreams do(n in a special dream %ournal is much more effecti&e than simple recall. Record dreams in the morning (hile memories are still fresh. The more details recalled (hen recording the dream the better the ultimate results. This is a &ery attenti&e approach that demands a higher a(areness than simple recollection. .riting dreams in a %ournal significantly increases a(areness of actions and aspirations. 1nother (ay of remembering dreams is to create a map of the dream (orld. This is called drea$ cartography and is similar to keeping a %ournal though an enhanced le&el of a(areness is de&eloped by connecting dream episodes on a map. First record one dream describing locations and e&ents (hich are plotted on the map. This cartographic process is repeated (ith each
subse2uent dream and after se&eral dreams an episode (ill occur that is someho( related to the location of a dream that has already been recorded. The t(o dreams that took place near each other are plotted ne#t to each other on the map. O&er time more and more interrelated dreams (ill occur and the map (ill become increasingly concentrated rather than disconnected. 1s a result the fre2uency and realistic 2uality of remembered dreams (ill increase and the dreamer (ill increase the ability to achie&e consciousness (hile dreaming. )t is best to set remembered dreams to memory after temporary a(akenings &ersus (aiting until morning. To accomplish this it helps to ha&e a pen and a piece of paper nearby so that a practitioner may 2uickly %ot do(n a phase or se&eral key (ords from the plot of the dream before falling back asleep. Using this information the ma%ority of dreams are 2uickly and completely recalled. The initial result from e#ercising these techni2ues is a rapid increase in the number of remembered dreams. .hen this number becomes significant Fany(here bet(een fi&e and 1A per nightG dream consciousness follo(s on a regular basis. Intention )ntention is crucial to the success of any techni2ue. .ith regard to dream consciousness its significance is multiplied. The creation of intention is ine#tricably linked to the creation of internal aspiration (hich has re&erberations in both conscious and unconscious states. )n reality an ele&ated degree of intention operates as a po(erful method of mental programming. This techni2ue is performed before falling asleep by affirming a strong desire to become conscious (hile dreaming. For best results alongside a strong clearly defined intention think through (hat actions (ill be taken (hen dream consciousness is achie&ed. Creating an 3n hor 4ince dream consciousness is not linked to specific actions that take place (ithin a dream and sensory perception continues to operate in the dream state it is possible to de&elop and use an artificially conditioned refle# to achie&e consciousness. The essence
of this techni2ue is to train the consciousness to uniformly react to certain stimuli that occur (hile being a(ake and (hen dreaming establishing a habit of specific response e&ery time a certain situation occurs. For e#ample (hile a(ake a practitioner may ask !1m ) dreaming/$ e&ery time they see an anchor. 1n anchor is any ob%ect that is often encountered (hile a(ake and (hile dreaming. E#amples of anchors include a practitionerDs o(n hands red ob%ects or running (ater. .hen first using this techni2ue a practitioner (ill be unable to 2uestion (hether a dream is in progress e&ery time a pre"established anchor is encountered. 6o(e&er (ith training and a strong desire this techni2ue 2uickly produces results. O&er time subconscious 2uestioning of the practitionerDs state becomes habit happening (hile a(ake and dreaming. The end result is dream consciousness. )t is important to note that one needs not only to simply ask this 2uestion but that it is also important to ans(er it mindfully trying to isolate oneself from surrounding e&ents in order to be able to ans(er it in an as ob%ecti&e and unpredetermined (ay as possible. Failing to ans(er ob%ecti&ely (ill al(ays result in a negati&e response FnoG and dream consciousness (ill not be achie&ed. Natural 3n hors )n addition to creating deliberate anchors that induce conscious dreaming natural anchors should be gi&en focused attention. These are ob%ects and actions that regularly cause dream consciousness e&en (hen consciousness is not desired. 5eing a(are of the e#istence of natural anchors actually doubles the chances of their appearance. The follo(ing e#periences are common natural anchors that are present in dreams- death sharp pain intense fear stress flying electric shock se#ual sensations and dreaming about phase entrance or the phase en&ironment. .hen attempting dream consciousness identifying natural anchors produces results nearly 1AAK of the time. One may try to start flying each time that one ans(ers the 2uestion. This is of course pointless (hen in (aking reality. 6o(e&er (hen dreaming this (ill most likely lead to flight and once again pro&e that e&erything around is %ust a dream.
Self-3nalysis ,onsistent analysis of dreams helps to ascertain reasons for an absence of conscious a(areness- these analyses are significant to attaining dream consciousness. O&er the course of a lifetime the mind gro(s accustomed to the parado#ical nature of dreams and pays less attention to them. This becomes apparent (hile trying to understand that a red crocodile is unable to talk cannot be red nor can it rent an apartment. .hile dreaming these impossibilities are ne&er called into 2uestion. The essence of self"analysis is remembering dreams and thinking hard about (hy their parado#ical features had not been ade2uately recogni=ed in the dream state. .ith e#perience the e&eryday analysis of the correspondence of dreams to reality begins to ha&e an effect on a practitionerDs reasoning (ithin the dream state. For e#ample that red crocodileDs presence in a rented apartment could cause doubts that gi&e pause for reflection (hich could in turn lead to the understanding that e&erything happening is %ust a dream. 3C#IONS #O BE DONE (7EN BECOMING CONSCIO4S (7I;E D9E3MING To ensure that dream consciousness leads to a fully de&eloped phase e#perience one of three specific actions must be taken. The best is the techni2ue is deepening (hich should be immediately applied once dream consciousness occurs. 7eepening must be performed (ithin the dream episode before all other techni2ues. 7oing so &irtually guarantees entrance to the phase. The choice of actions that follo( deepening is dependent upon a practitionerDs predetermined course of plan in the phase. .hen becoming conscious (hile dreaming it is 2uite dangerous to try to return to oneDs body in order to roll out of it right a(ay unless one has deepened beforehand. This could result in a situation (here after ha&ing easily returned to oneDs body one (ould not be able to separate from it as the phase becomes significantly (eaker (hen physical sensations coincide (ith the position of a real body. )f
one is to employ such an option then in order to return to oneDs body one should simply think about it (hich is often sufficient to make the transition occur almost immediately. 1nother option is the use of translocation techni2ues to arri&e at a desired place (ithin the phase (orld. )t is also dangerous to employ this &ariation (ithout first deepeningJ translocating in a shallo( phase makes a return to the (akeful state &ery likely. Translocation is often accompanied by a substantial decrease in the depth of the phase state. S#93#EG8 /O9 3C#ION To achie&e dream consciousness constant practice is highly necessary because sporadic practice (ill fail to de&elop the re2uisite background thought processes. 1s a rule employing phase entry techni2ues (ithin the conte#t of dream consciousness produces results after se&eral (eeks and the effects of the techni2ues are increasingly pronounced (ith time. )f there are no results (ithin a month or t(o refrain from these techni2ues for a period of time take a break for a (eek or t(o and resol&e to assume a fresh start later. Practitioners often stop using these techni2ues after initial results as later effects become elusi&e and the fre2uency of dream consciousness rapidly declines. These techni2ues should not be abandoned after first yielding results though a gradual decrease in practice is generally acceptable. #8PIC3; MIS#3=ES (7EN P93C#ICING BECOMING CONSCIO4S (7I;E D9E3MING Percei&ing the state of dream consciousness as a non"phase state e&en though this phenomenon is one and the same (ith the phase. 1ttempting dream consciousness (hile performing other phase entrance techni2ues (hen it is better to focus on dream consciousness alone.
.hen falling asleep lacking sufficient desire to e#perience conscious dreaming e&en though this is critical. ,ontinuing to yield to the plot of a dream e&en after achie&ing dream consciousness (hereas subse2uent actions must be independent and based on free (ill. )ncorrectly ans(ering the 2uestion !1m ) dreaming/$ (hile dreaming. Forgetting to immediately begin deepening techni2ues (hen dream consciousness has been achie&ed. .hen e#ercising memory de&elopment recalling the most &i&id dreams instead of e&ery dream. )nconsistent concentration (hile practicing dream consciousness techni2ues.
1A. .hat e#periences in dreams often spontaneously gi&e rise to a state of conscious a(areness/ 11. .hat must immediately be done after becoming conscious (hile dreaming/ #as!s 1. E&ery day immediately before going to sleep culti&ate a strong desire to become conscious in future dreams. +. .hen you (ake up recall or (rite do(n the episodes and plots of your dreams e&ery day. 8. Try to achie&e at least one instance of dream consciousness.
C4EING #EC7NO;OGIES Of all non"autonomous assistance methods cueing technologies yield the best results. The operating principle behind cueing technologies is 2uite simple- a de&ice detects rapid eye mo&ement FREMG and sends signals to a sleeping practitioner prompting dream consciousness or an a(akening that may be follo(ed by indirect techni2ues. ,ueing programs or de&ices may also send indicators o&er specific inter&als of timeJ these are recei&ed during REM sleep and are meant to cause a sleeping practitioner to a(aken and attempt indirect techni2ues. More sophisticated REM"detecting technologies may be purchased at speciali=ed stores or through online merchandisers. REM"detecting technologies (ork by &irtue of special night mask e2uipped (ith a motion sensor that detects the fre2uency of specific eye mo&ements that occur during REM sleep. .hen the eye mo&ements reach REM 2uality the de&ice sends discreet signals to the practitioner through light sound &ibrations or a combination of these. )n turn the practitioner must discern the signal and react to it (hile sleeping (ith the goal of phase entry through dream consciousness. The effecti&eness of REM"detecting de&ices is more plausible in theory than in practice. The mind 2uickly de&elops a tolerance for these types of e#ternal stimuli and stops reacting and as a result such technologies are hardly used more than one or t(o nights per (eek. 4econdly a practitioner (ill detect only a small portion of the signals and conscious reaction occurs in e&en smaller instances. ,ueing technologies are best used to send signals that allo( a practitioner to a(aken (ithout mo&ing during REM sleep (hich facilitates a high probability of phase entrance through indirect techni2ues. Pricing of these !mind"machines$ Fthe common moniker of any de&ice that purports to produce altered consciousnessG (idely &aries and is determined by 2uality of REM detection and signaling. 1&ailable models include7ream4talker 7reamMaker F'o&a7reamerG REM"7reamer 1stral ,atapult among many
others. 4ince the use of these de&ices does not guarantee increased success in practice in&esting money in the technology is not recommended. )f a practitioner is curious about cueing technologies similar de&ices may be constructed at home using a special computer program and a run"of"the"mill optical mouse. 7esigns for a homegro(n setup are easily located on the )nternet. 1nother do"it"yourself (ay of e#perimenting (ith cueing is through the use of a computer a music player or e&en the alarm clock function on a mobile phone. The practitioner sa&es short sounds or phrases played as an alarm e&ery 1; to 8A minutes (hile sleeping. These sounds (ill signal the practitioner to (ake up and attempt indirect techni2ues. )f the practitioner decides to use cueing technology se&eral fundamental principles should be considered as results (ill be less likely if they are ignored. First mind"machines should be used no more than t(ice a (eek. Other(ise too high a tolerance (ill be built up rendering the machines ineffecti&e. 4econd use cueing technology in combination (ith the deferred method (hich (as co&ered in the section on indirect techni2ues. )t is better to sleep for si# hours (ithout distraction and then after sleep has been interrupted put on a sleep"mask or earpiece and continue sleeping. 4leep (ill be light for the remaining t(o to four hours as there (ill be more REM sleep making it easier for the mind to detect cueing signals. Finally master indirect techni2ues before making use of cueing technologies to attain dream consciousness and subse2uent phase entrance. (O9=ING IN P3I9S .orking in pairs is considered the second most effecti&e non" autonomous methods of entering the phase. One practitioner is to be the acti&e one and the other fills the role of helper. The acti&e one practitioner attempts to enter the phase (hile the helper pro&ides &arious types of support to this end. For e#ample the acti&e practitioner lies do(n in bed (hile the helper stays nearby (aiting for the acti&e one to fall asleep. .hen
sleep occurs the helper obser&es the eyes of the acti&e (atching for the signs of REM sleep (hich is mainly characteri=ed by 2uick eye mo&ements. .hen REM is apparent the helper (hispers to the sleeper communicating that e&erything the practitioner is e#periencing is a dream. The helper may &ary the &olume of the (hisper use touch to strengthen the signal or shine a flashlight on the sleeperDs eyelids I (hich is &ery effecti&e. The acti&e practitioner should detect the signals (ithout (aking and indicate a state of conscious a(areness by performing 2uick cyclical eye mo&ements. )f no such indication is gi&en the helper continues to rouse the acti&e practitioner (ho may finally (ake. )f the acti&e practitioner is unable to stay in the dream indirect techni2ues should be performed. The acti&e practitioner should under no circumstances mo&e upon a(akening or (aste &aluable seconds before transitioning to indirect attempts. )f phase entrance does not occur after e#ercising the techni2ues the practitioner should again fall asleep (ith the intention of making another attempt. 3enerally se&eral such attempts are enough to glean results. .orking in pairs is best performed %ust prior to a daytime nap or (ith the same deferred method used for indirect techni2ues " an early"morning interruption of a practitionerDs nighttime sleep. #EC7NO;OGIES /O9 IND4CING #7E P73SE The ambition to create a de&ice facilitates 2uick and easy phase entrance has led to the appearance of assorted technologies that claim to fulfill such a role. 1s already stated none of these de&ices has been pro&en effecti&e. The most famous of these is the 6emi"4ync system (hich purports to synchroni=e the t(o hemispheres of the brain. 6emi"4ync (as de&eloped by Robert Monroe an 1merican esotericism e#pert researcher. The idea behind 6emi"4ync is that out"of"body sensations may be induced by achie&ing synchroni=ation of the brainDs t(o hemispheres. 6o(e&er this type of approach yields a parado# for the lack of scientific For pseudo"scientificG e&idence that hemispheric synchroni=ation influences sensory perception. 1ctually it is the
cerebral corte# and constituents that are primarily responsible for sensory perception. 1t the beginning of the +Ath century it became clear that the key roles in sensory processes are played by &arying le&els of inhibition and acti&ity in the cerebral corte# and almost not else(here. The key to sol&ing the problem of technologically induced phase entrance rests in the inhibition processes of the cerebral corte#. 4ynchroni=ation de&ices ha&e no effect on the operation of the cerebral corte#. The idea of using sounds of &arious fre2uencies to induce a specific le&el of electrical acti&ity in the brain is so far considered impossible. Thus the sounds and noises used to assist separation from the body cannot directly affect the process but merely ser&e as cueing signals. 4uch a system (orks only after ha&ing been used for a long time if it (orks at all. Moreo&er it might only (ork once or t(ice. 'e&ertheless synchroni=ation systems are able to help practitioners reach a free floating state of consciousness since the systems pre&ent sleep or induce (akefulness pro&iding fertile ground for direct phase entry. 6o(e&er the systems ha&e nothing at all to do (ith synchroni=ing the t(o hemispheres of the brain. The idea of inducing &arious phase states through sound has gained (ide attention. Many other programs and technologies ha&e appeared as a result including for e#ample the 5rain .a&e 3enerator F5.3G (hich allo(s the practitioner to independently e#periment (ith a (ide array of sounds and fre2uencies and &arious methods of transmission. The effect is the same- cueing during sleep or the maintenance of a transitional state. Thus there is no noticeable difference bet(een using machines and listening to similar sounds or musical compositions. )nasmuch as the de&ices described abo&e ha&e not deli&ered notable result the search for ne( technologies continues unhindered. The number of ideas to e#ert nonin&asi&e influence o&er the brain and its constituent parts is increasing. For e#ample there is a theory that phase e#periences may be induced by electromagnetically stimulating the left angular gyrus. 6o(e&er this like all other non" autonomous methods is strictly based on theory. 1t present
consistent focused unassisted practice is the simplest and only guaranteed means to achie&ing phase entrance. 78PNOSIS 3ND S4GGES#ION 6ypnosis is a little"studied method of entering the phase. The idea is that a hypnotist is able to cause a person to enter the phase through suggestion or affirmation. There is no doubt that hypnosis is an interesting concept especially for persons (ho easily yield to po(er of suggestion but such indi&iduals account for only 1K of the population. 7ue to specific characteristics of human perception the chances are nil that hypnosis is a likely conduit to phase entrance. 4o it seems unlikely that hypnotic techni2ues (ill become (ell"kno(n or that a top"notch hypnotist (ould through suggestion easily be able to lead a sub%ect directly into the phase. 6o(e&er it is completely feasible that hypnotic suggestion may promote higher fre2uency in dream consciousness or a(akening (ithout mo&ing Fand remembering to do indirect techni2uesG. 6ere again this method is only a facilitator (hile actual phase entrance depends on the efforts of the practitioner. P78SIO;OGIC3; SIGN3;S The simplest (ay to supplement the practice is establishing a reminder that prompts conscious a(akening and subse2uent indirect techni2ues. This may be accomplished by blindfolding the eyes or tying a cord taut around an arm or leg. The idea is that the reminder is immediately felt (hen the practitioner (akes prompting the attempt of indirect techni2ues. )n actuality mind"machines (ork using the same principle since these are most effecti&e as cues that arouse an intention to perform a specific action. 1 more sophisticated e#ample of a reminder is (hen a practitioner do=es off in a position meant to cause numbness to a certain body part. .hile a(akening the practitioner (ill take the physical numbness a cue to practice indirect techni2ues. 1 secondary
benefit to this method of physiological signaling is that the numb body part may easily be used to perform phantom (iggling. Falling asleep (hile lying on the back (ith an arm behind the head or by lying directly on an arm are effecti&e e#amples. These and other postures (ill impede circulation cause numbness and promote a(akening. 'aturally the numbness should not be e#cessi&e. 7i&erse e#periments that e#ploit physiological needs are especially popular for inducing conscious a(akening or becoming conscious (hile dreaming. For e#ample a practitioner may forgo (ater o&er the course of the day before attempting to enter the phase. The effect is an acute thirst (hile dreaming (hich may be used to communicate that the dream state has taken o&er. Or thirst causes repeated a(akenings during (hich the practice of indirect techni2ues may commence. 1n alternati&e to depri&ing the body of (ater is including more salt in foods consumed before going to sleep. 1nother method is to drink a lot of (ater before sleep causing the practitioner to a(aken naturally producing an opportunity to perform indirect techni2ues. Using this has been kno(n to result in dream consciousness. 1nother popular method helps (ith direct techni2ues. )t (orks by falling asleep (hile keeping the forearm propped up at the elbo(. .hen the practitioner falls asleep the forearm falls to the bed as the body shuts do(n. Feeling the arm fall signals a lapse of consciousness after (hich direct techni2ues may be attempted. )f this method fails to produce results on the first try it may be repeated by raising the forearm before falling asleep. This method helps some but rarely on the first try. )t should not be counted as panacea. 0ike all other non"autonomous methods practicing phase entrance using physiological signals should not be done on a regular basis. There are more pleasant autonomous techni2ues that only re2uire a natural (illpo(er and healthy desire. C7EMIC3; S4BS#3NCES 4ince the beginning the history of ad&ances in phase entrance methodologies has included a direct link to the use of consumable
supplements starting (ith plants and mushrooms in ancient times. The use of speciali=ed herbs mushrooms and cacti is still practiced in isolated culturesJ 4iberian shamans and 'orth 1merican )ndians for e#ample. 1mid the hunger for altered states of a(areness these chemical supplements ha&e reached e&ery corner of the de&eloped (orld. 6o(e&er the proliferation of these substances has caused a marked degradation in the progress of modern phase practice. The names and descriptions of these &arious chemical concoctions herbs and plants included are not (orthy of inclusion in this te#t. They are officially considered illegal in some countries (hile still a&ailable in the pharmacies of othersJ ne&ertheless they are all dangerous. There are t(o primary problems (ith using such supplements. First practicing the phase through the consumption of chemical substances and &arious herbal supplements is not a path to de&elopment but to ruin. 7rug abuse and personal de&elopment are polar opposites in no (ay compatible. ,heap thrills are consistently follo(ed by chemical dependencies and health problems. 4econd although a user may e#perience phase sensations under the influence of such substances the 2uality of e#perience is completely different. )t is not only the stability or depth of phase that are affected by these supplements but a userDs consciousness and a(areness. The use of substances and the resultant alteration of mental processes negati&ely impact self"a(areness. The phase must be accompanied by t(o things- phase sensations and a complete conscious a(areness. )f one of these is missing then the state e#perienced by definition is not the phase. .hen descriptions of these chemically !enhanced$ e#periences are studied the hallmark of e&ery one is a complete lack of control. Using any type of chemical or herbal substance to reach the phase must be ruled out. 4ummarily these make it impossible to e#perience the phase and ultimately destroy physical and mental health. #7E /4#49E O/ NON-34#ONOMO4S ME#7ODS /O9 EN#E9ING #7E P73SE
E&en though no beneficial non"autonomous technologies currently e#ist the future is (ide open before them. .ith the de&elopment of effecti&e technologies the phase (ill cease as the e#clusi&e domain of the initiated and become a (idespread practice. Only then (ill the Fsometimes %ustifiedG stereotypes and pre%udices connected to the mystical nature of the phenomenon be dispelled and only then (ill the phase gain the necessary attention from researchers needed to ably de&elop the science of phase practice. .hen e#ternally applied methods that cause phase entrance are disco&ered the human e#perience (ill drastically change. These technologies for inducing and monitoring phase e#periences (ill open up incredible possibilities. For e#ample it (ill be possible to participate in a mo&ie instead of %ust (atchingJ people (ill be able to try and e&aluate products (ithout lea&ing homeJ tra&el throughout designed (orlds (ill take placeJ computer games (ill be substituted (ith analogous e#periences including real physical sensations. The ultimate step (ould be the unification of phase e#periences into a collecti&e parallel (orld integrated to e#istent digital net(orks- the Matri# Fthe MindnetG. Using this Matri# it (ill be possible to communicate (ith someone on the other side of the planet " not %ust through a broadband &ideo link but literally tCte D tCte. This &ision of the future is a drop in the ocean of possibilities that (ill open (ith phase entrance technologies. The first step to(ard the future is a thorough pragmatic and correct application of the techni2ues no( a&ailable. #8PIC3; MIS#3=ES (I#7 NON-34#ONOMO4S #EC7NI<4ES The belief that de&ices are able to phase entrance if autonomous techni2ues fail e&en though it is much easier to enter the phase through strictly indi&idual efforts. .asting a large amount of time and effort on &arious technologies to create a phase state. 'o such technology e#ists.
Using cueing technologies on a daily basis e&en though they arenDt supposed to be used more than t(ice a (eek. Using cueing technologies all night long (hen it is much better to use these in con%unction (ith the deferred method. Using cueing technologies (ithout affirming a personal intention of appropriate reaction to the signals- this is crucial to cue effecti&eness. .orking in pairs during the first hours of nighttime sleep e&en though REM sleep occurs infre2uently and then for only short periods of time. .hile (orking in pairs the helper gi&ing an acti&e practitioner too strong a signal. 4ignals should be kept discreet to pre&ent (aking the sleeper. Employing an amateur hypnotist to increase the fre2uency of dream consciousness. The use of hypnotic suggestion to a practitioner (ho is not susceptible to hypnosis. Using physiological signals on a daily basis causing physical discomfort &ersus getting en%oyment out of the practice. The belief chemical substances promote dissociati&e e#periences. 1cting on this belief is e2ui&alent to drug abuse.
;. .hat happens if a practitioner uses cueing technologies for se&en days in a ro(/ <. ,an cueing technologies make use of light signals/ >. ,an feasting on peanuts before sleep help the process of phase entry/ ?. .ill putting a tight rubber band around an ankle promote phase entry/ @. .hile (orking in a pair are both practitioners re2uired to enter the phase/ 1A. ,an the helper be compared to a cueing de&ice (hile (orking in a pair/ 11. .hen should the helper gi&e the signal that the acti&e practitioner is dreaming/ 1+. .ould a hypnotist making suggestions about entering the phase be helpful to e&ery practitioner/ 18. .hy do phase"inducing technologies sometimes (ork e&en though these are based on fla(ed theories/ 1:. .hat is absent in a phase induced by chemical substances/ #as!s 1. Try using a cueing de&ice se&eral times in con%unction (ith the deferred method. ,reate a short sound file and set it to a de&ice that plays the file bet(een 1;"minute inter&als of silence. +. 5efore going to sleep at night try the raised forearm method of entering the phase se&eral times. 1ttempt this using the deferred method. 8. )f you ha&e the opportunity try to achie&e entry into the phase by (orking in pairs.
Chapter + - Deepening#7E CONCEP# O/ DEEPENING 3eepening refers to techni4ues that induce realistic perception and a&areness in the phase state( The phase is not an e#act fi#ed state (here a practitioner is present or not. )t is a realm of states characteri=ed by a transition from the usual perception of the physical body to a complete alienation from it (hile maintaining consciousness and reality of perception albeit in a different frame of space. The transition begins (ith perception of the natural physical body follo(ed by a moment of ambiguity (here a clear e#perience of body is intermingled (ith a sense of the percei&ed body. 1fter(ard the percei&ed body enters the phase space (hile the physical body becomes a memory. 1t this point the percei&ed senses may be 2uite dullJ for e#ample &ision may be blurred or completely absent. 7eepening techni2ues sol&e the problem of diminished or absent sensory perception in the phase. 4ensory e#periences (ithin a fully reali=ed phase e#perience are as realistic as those in e&eryday reality. )n almost one"half of all cases practitioners obser&e that reality"based surroundings pale in comparison to &ibrant detail and color of the phase space. To this end after entering the phase a practitioner must perform deepening techni2ues to enhance and solidify the degree and 2uality of phase reality.
Full spatial perception in the phase only occurs after deepening techni2ues ha&e been applied. There (ould be no point to remaining in the phase (ithout deepening. For e#ample (hat is the point in finding a person in phase if it is not e&en possible to discern his or her eyes there/ -n a considera"le nu$"er of cases, deepening is not necessary, since the phase e#perience is co$pletely realistic, if not hyperrealistic( -n cases li+e these, deepening $ay "e "ypassed( 7eepening is also related to the length of time a practitioner may remain in the phase. )f an action is taken (ithout a deep realistic phase the e#perience (ill al(ays be se&eral times shorter in duration than a phase (here deepening techni2ues had been applied. The properties of the phase space &ery much depend on its depth. .hen surroundings are blurry and unclear the stability of ob%ects is &ery (eak. There is a direct correlation bet(een the realism of a phase and a practitionerDs le&el of a(areness so it is e#tremely important to ensure a deep phase in order to promote ma#imum a(areness.
Interesting Fact! The realis$ of a deep phase space is often so great that it causes uncontrolla"le fear or shoc+( 7eepening should only be performed follo(ing complete separation from the body. )f initiated before separation the phase may end prematurely. )f complete separation does not occur primary deepening should be used. 1s regards the deepening techni2ues themsel&es there is one main one and there are se&eral subsidiary ones. The main techni2ue (hich does not present any difficulties is sufficient for ha&ing a successful practice. Interesting Fact! -gnorance of deepening techni4ues has led to a great nu$"er of "aseless theories and superstitions( So$e practices treat differing phase depths as various states and even &orlds( -n reality, there are si$ple actions that ensure a singular phase e#perience(
P9IM398 DEEPENING #EC7NI<4ES The goal of primary deepening is to achie&e complete separation from the body allo(ing further actions (ithin the phase. Primary deepening entails achie&ing t(o principal ob%ecti&es- complete separation from the physical body and anchoring the percei&ed body (ithin the phase space. .hen separation from the body occurs through the use of a separation techni2ue a posture must be assumed that completely different from the posture of the real physical body. The greater the degree of postural similarity bet(een the physical and percei&ed bodies the more shallo( and brief the phase (ill be. For e#ample in the case of hori=ontal le&itation a 1?A turn must immediately performed arms and legs spread adopting a &ertical posture. Under no circumstances should a practitioner in the phase remain in a posture identical to that of the physical body. )f a practitioner is pulled back to(ard the body after separation anchoring should be initiated that facilitates standing or sitting in the phase. Resisting the gra&ity of the physical body is paramount to remaining in the phase. The result of (illful resistance is directly proportional to the degree of applied effort. )t (ill help to grab hold of surrounding ob%ects and hold on to themJ any means of anchoring the percei&ed body (ithin the phase are appropriate. )t is possible to start rotating around an a#isJ not simply imagining the rotation but performing it (ith the percei&ed body as (ell. DEEPENING #79O4G7 SENSO98 3MP;I/IC3#ION The more a phase is e#perienced by the sensory faculties the deeper and longer the phase (ill be. 4ensory amplification in the phase is the most effecti&e deepening techni2ue precisely because it allo(s the acti&ation of primary internal sensations during the transition from reality to the phase. There are se&eral (ays to perform sensory amplification.
Ealpation is the first deepening techni2ue that should be recalled (hen entering the phase. 9ision may be absent at the beginning of a phase e#perience but the sensation of occupying a defined space is almost al(ays present. )n the case of a completely absent sense of sight only tactile" kinesthetic perception is possible. That is mo&ement throughout a space and the touching ob%ects there is the only option (hen &ision is absent. The sense of touch plays a key role in the perception of e&eryday reality. 1ccordingly if the sense of touch is acti&ely used in the phase space it is only natural that the phase (ill deepen and reach its ma#imum potential. Palpation is performed by fleetingly touching anything that may be found in the immediate surroundings. This should be done by 2uickly but carefully percei&ing the feel of surfaces and shapes. 6ands should not remain on a particular place for more than one second remaining constantly in motion to locate ne( ob%ects. The goal of palpation is to touch and also to learn something about encountered ob%ects or shapes. For e#ample if one feels a mug one may touch it not only from the outside but also from the inside. Once a practitioner has rolled out of the body the bed may be touchedJ the physical body lying in bed may be touched as (ell as the floor the carpet nearby (alls or a bedside table. 1nother palpation techni2ue is performed by rubbing the palms against each other as if trying to (arm them on a cold day. 5lo(ing on the palms also produces sensations that (ill help deepen the phase. 4ince tactile perception of the (orld is not limited to the palms the hands should be mo&ed o&er the entire body (hile in the phase to e#cite and fully acti&ate the sense of touch. 1s soon as palpation begins the feeling that the phase is deepening and becoming fi#ed soon follo(s. Usually it takes fi&e to 1A seconds of palpation e#ercises to reach the ma#imum le&el of deepening. 1fter performing this techni2ue the pseudo"physical sensations (ill be indistinguishable from those of e&eryday reality. )f &ision is absent on phase entry it 2uickly emerges during palpation.
Eeering is the primary technical &ariation of sensory amplification. 6o(e&er it is not al(ays initially accessible since it re2uires &ision (hich may begin as absent in the phase. Once &ision appears or has been created using special techni2ues Fsee ,hapter ?G peering may begin. The effecti&eness of this techni2ue originates in the fact that &ision is the humanDs primary instrument of perception. Therefore by e#citing &ision to its ma#imum potential (ithin the phase it is possible to attain a fully immersi&e phase state that is completely apart from normal reality. Peering should be done at a distance of four to si# inches from ob%ects (ithin the phase. 1 practitioner should glance o&er the minute details of ob%ects and surfaces to bring definition to the phase space (hile increasing the 2uality of &ision. .hen looking at hands the lines of the palm or the fingernail and cuticles should be e#amined. )f obser&ing a (all study the te#ture of its (allpaper. .hen looking at a mug one should look carefully at its handle the cur&e of its rim or any inscriptions. 1ttention should not remain on one area of an ob%ect for more than half a second. 1cti&e obser&ation should constantly mo&e to ne( ob%ects and their minute details approaching ob%ects or picking them up to dra( them nearer. )tDs best (hen ob%ects near one anotherJ other(ise too much time is spent mo&ing around. Peering brings 2uick and clear results. Usually if &ision is blurry and there is a yearning to return into the physical body (ith %ust 8"1A seconds of peering all of this (ill be gone (ithout a trace. 1fter peering &ision ad%usts as 2uickly and clearly as if a camera lens (as correctly installed in front of the eyes capturing the image in the sharpest of focus. Si$ultaneous peering and palpation pro&ide the ma#imum possible deepening effect in the phase. This method of sensory amplification engages the t(o most important percepti&e thus the effect is t(ice greater than (hen the t(o actions are separately performed. )f &ision is present in the phase simultaneous peering and palpation is an absolute necessity because it facilitates good phase depth in the 2uickest and simplest manner.
The combination of palpation and peering must not only be performed simultaneously but also upon the same ob%ects. For e#ample (hile a practitioner may look at the hands and simultaneously rub them against each otherJ or (hile looking at a coffee mug all of its parts may be obser&ed and touched at the same. )t is necessary to maintain dynamism of action remembering that feelings should be e#perienced not half"heartedly remembering that full concentration on sensory amplification is an e#cellent means to a deep 2uality phase. SECOND398 DEEPENING #EC7NI<4ES Di>ing 7eadfirst 7i&ing headfirst is used if sensory amplification techni2ues do not (ork or (hen the practitioner in the phase is located in an undefined space (here there is nothing to touch or look at. This techni2ue (orks thanks to the unusual &estibular sensations that it causes (hich help to enhance perception. This techni2ue is performed (ith the eyes shut if &ision is a&ailable and the practitioner literally di&es headfirst into the floor or space at the feet. 1 feeling of mo&ement a(ay from the physical body (ill immediately arise during the flight do(n and the di&e itself (ill be e#perienced as if it is really happening. 4imultaneously the surrounding space may darken and become colder. 1gitation or fear may also appear. 1fter fi&e to 1; seconds of flight the practitioner is either arri&es in an undetermined place in the phase or hits a dead end like a (all. )n the case of a dead end a translocation techni2ue should be used. Translocation may also be attempted if deepening does not occur during the flight if sense perception stops impro&ing or if a good degree of realism has already been achie&ed. 1n alternati&e to the translocation techni2ue- hold the hands about four to si# inches in front of the face and try to obser&e them (ithout opening the eyesJ this (ill mo&e the practitioner to another random location. .hen falling headfirst do not think about the floorJ assume that it (ill be penetrated. This &ery effecti&e if the phase has not reached a fullness of depth.
1 desire to not simply fall do(n obser&ing oneDs perceptions but instead race s(iftly do(n(ard (hile trying to mo&e a(ay from the body is e#tremely important. )n case of failure to do so instead of deepening such a fall may lead to a return to the state of being a(ake i.e. to a foul. ?i0ration 0ike falling headfirst the &ibration techni2ue should be used if sensory amplification techni2ues do not (ork or (hen the practitioner in the phase is located in an undefined space (here there is nothing to touch or look at. 1fter separating from the body it is normally 2uite easy to create &ibrations by thinking about them by straining the brain or by straining the body (ithout using muscles. The occurrence of &ibrations pro&ides a significant opportunity to deepen the phase. 1n ad&antage of this techni2ue is that it does not re2uire any preliminary actions and thus may be practiced at any moment. The brain is strained to the ma#imum e#tent possible (hich cause &ibrations that may be intensified and managed through spasmodic or prolonged straining. )f this techni2ue does not produce deepening after fi&e to 1A seconds the techni2ue has to be changed or action should be taken at the practitionerDs current depth in the phase. 3ggressi>e 3 tion This techni2ue may be used as an alternati&e to any other deepening techni2ue since it can be used at any moment. Practicing this techni2ue only re2uires aggressi&e action of the percei&ed body. 1 practitioner may run roll on the floor perform gymnastics or mo&e the arms and legs. Ma#imum acti&ity and aggression are paramount to the successful use of this techni2ue. )f the practitioner is stuck in a dark space (a&ing the arms and legs from side to side is appropriate. )f the practitioner is in (ater s(imming (ith determined po(erful strokes (ould be suitable recourse. The type of action &ery much depends on the specific
situation along (ith an aggressi&e desire on the part of the practitioner. 1s a rule the effect of such mo&ements and relocations comes 2uite 2uickly especially if attention is focused on all the accompanying sensations. I'agining reality This interesting techni2ue should be used by e#perienced practitioners or if all other deepening techni2ues fail. 1 practitioner aggressi&ely imagines being located in the physical (orld e#periencing its intrinsic reality of perception and not in the phase. This should be done (hile in a state of separation from the body (ith a sense of &ision present. )f successful the surrounding phase space (ill immediately brighten and sensory perception of the phase (ill e#ceed the normal e#perience of reality. )f this techni2ue produces no clear results after a fe( seconds another techni2ue should be used. GENE93; 3C#I?I#8 1ll deepening techni2ues should be practiced (ith a high le&el of aggression (ith no pauses only continuous deliberate action. )f techni2ues are practiced in a calm rela#ed manner then deepening attempts (ill most often result in falling asleep or returning to the body. #8PIC3; MIS#3=ES D49ING DEEPENING Forgetting to perform deepening techni2ues (hen necessary. ,arrying out unnecessary deepening (hile at a sufficient depth. 6alting deepening techni2ues before reaching ma#imum realism in the phase. ,arrying out main deepening techni2ues prior to ha&ing become completely separated from the body although at this time only primary deepening should be used.
,ontinuing deepening techni2ues (hen results ha&e already been achie&ed. 1lternating too 2uickly bet(een deepening techni2ues instead of concentrating on each of them for at least fi&e to 1A seconds. Performing the techni2ues slo(ly and calmly instead of aggressi&ely. 1pplying techni2ues of sensory amplification (hile stuck in a shapeless dark space (hen these should only be performed in a &i&id and realistic place. Obser&ing ob%ects located too far from the eyes during &isual sensori=ation instead of the re2uired four to fi&e inches. .hen peering scrutini=ing a single detail of an ob%ect for too long (hen it is necessary to 2uickly s(itch from one detail to another. Taking in a (hole ob%ect (hen peering (hile only parts of it should be obser&ed. ,oncentrating too long on the details of a single ob%ect instead of focusing on different ob%ects in 2uick succession. 0ong palpation of a single ob%ect during sensory amplification instead of rapidly s(itching from one ob%ect to another. 7eepening (hile standing in place (hen it is important to maintain constant motion. Falling headfirst (ith the eyes open although the eyes must be shut to a&oid crashing into the floor. Falling headfirst (ithout the desire or intention of falling far and 2uickly. Forgetting to use translocation techni2ues after hitting a dead end. Forgetting to alternate deepening techni2ues if some of them are not (orking. Fear of the hyperrealism of the e#perience and halting deepening instead of calmly continuing (ith the techni2ue.
<uestions 1. 1fter (hich phase entrance techni2ues is deepening necessary/ +. .hy is phase deepening necessary/ 8. 1re there cases (here phase deepening is unnecessary/ :. .hat le&el of reality should be achie&ed by deepening/ ;. .hen should deepening begin after entering the phase/ <. 7oes deepening influence the length of a phase e#perience/ >. .hy is primary deepening necessary/ ?. May one touch oneDs head (hen the performing sensori=ation of feelings/ @. 4hould a practitioner look at curtains (hile peering/ 1A. )s it effecti&e to apply peering at phase ob%ects from a distance of 1 to 1.; yards/ 11. ,an peering be used during palpation/ 1+. .hen should the eyes be closed (hile falling headfirst/ 18. .ould thro(ing punches like a bo#er help a practitioner to deepen/ 1:. 6o( calmly should the deepening techni2ues be performed/ #as!s 1. 7e&ote the ne#t three successful phases to perfecting deepening techni2ues using all of the methods described in this chapter. +. Using personal e#perience try %udging (hich techni2ue suits you best from personal e#perience.
Chapter , - Maintaining#7E GENE93; CONCEP# O/ M3IN#3INING Ehase $aintenance or >$aintaining? refers to techni4ues that allo& a practitioner to re$ain in the phase for the $a#i$u$ a$ount of ti$e possi"le( .ithout kno(ledge of !maintaining$ techni2ues the duration of the phase (ill be se&eral times shorter than it could other(ise be. The shortest phases last %ust a fe( seconds. 5eginning practitioners usually fear not being able to e#it a phaseJ this shouldnDt e&er be a concern because the real challenge is being able to maintain the phase state (hich is easily lost unless phase maintenance techni2ues are used.
Phase maintenance consists of three primary principles- resisting a return to the (akeful state Fkno(n as a foulG resisting falling asleep
and resisting a false e#it from the phase. 1s a rule the first t(o problems Freturn to a (akeful state or falling asleepG are often encountered by beginners but the third difficulty Ffalse e#itG manifests at later stages of practice. Resistance to returning to the body is self"e#planatory (hereas resistance to falling asleep is unclear to many. 'ot e&eryone kno(s that almost half of phase e#periences usually end in a 2uite tri&ial (ay " falling asleep. 1 person usually looses attenti&eness his or her a(areness dissipates and e&erything around gradually looses clarity and turns into (hat is for all intents and purposes a usual dream. Resisting a false e#it from the phase is a lot more surprising and dramatic. 4ometimes a practitioner detects an impending e#it from the phase subse2uent deepening techni2ues fail to (ork resulting in (hat seems to be a return to the body and physical reality. 4ure that the phase has ended a practitioner may stand up and the fall asleep after percei&ing a fe( steps. )n such cases falling asleep most often happens (ithout any mo&ement but (hile still lying in bed. The problem is that the difference bet(een the phase and reality can be so subtle that in terms of internal or e#ternal indicators the phase practically canDt be distinguished from reality. Therefore one must kno( the necessary actions to take in the e&ent that the phase ceases since the end of a phase could actually be a trick and purely imagined. There are specific solutions for the three problems described in addition to general rules that apply to any phase e#perience. 4tudying these rules should be gi&en %ust as high a priority as studying the specific solutions since only some of them (hen applied separately may help one to remain in the phase se&eral times longer than usual. )n some cases techni2ues for maintaining are not applicable. 6o(e&er kno(ledge of ho( to maintain is useful for the ma%ority of e#periences. 1lso there might be situations (hen someone need only resist a foul (hile someone else may need to resist falling asleep. 1ll of this is &ery specific to each case and can be determined only in practice. .ith perfect kno(ledge of all the techni2ues for maintaining a phase may last t(o to four minutes (hich doesnDt sound like an
e#tended duration but really is. 1 particularity of the phase space is that achie&ing something and mo&ing around in it takes a minimum amount of time mere seconds. Thus so much can be done during 8 minutes in the phase that one literally needs a list so as not to (aste any time. There are theories that ha&e neither been pro&en nor dispro&en claiming that time in the phase contracts and e#pands relati&e to real time. Thus one minute of real time (hile in the phase may feel much longer in terms of phase time. Perception of time &aries from practitioner to practitioner. 'o&ices especially percei&e a real minute as more like fi&e to 1A minutes in the phase. This is determined by the particularities of indi&idual psychology state of mind and the type of e&ents that occur in the phase. )n order to understand ho( long a phase really lasted one does not need to try using a stop(atch in the real (orld. )t is better to count ho( many actions took place in it and ho( much time each of them could ha&e taken. The result (ill differ from oneDs first rough estimate se&eral times o&er. The ma#imum duration the phase &aries depends hea&ily on the ability to apply phase maintenance techni2ues. 4ome practitioners ha&e difficulty breaking the t(o"minute barrier (hile some find it easy to remain in the phase for 1A minutes or longer. )t is physically impossible to remain in the phase fore&er because e&en a +A"minute phase is unheard of. #EC7NI<4ES 3ND 94;ES 3G3INS# 9E#49NING #O #7E BOD8 Of the follo(ing techni2ues constant sensory amplification and as"needed sensory amplification are applied the most often (hile performing phase maintenance. 6o(e&er as opposed to other technical elements of phase e#ploration other secondary techni2ues of maintaining often become mainstream and the most appropriate for certain indi&iduals. Thus all the techni2ues should be studied but the first t(o should be considered &ery carefully.
Constant Sensory 3'plifi ation The same sensory amplification described in the chapter on deepening F,hapter <G also applies to !maintaining$. )n essence ha&ing achie&ed the necessary depth of phase one should not stop to acti&ely agitate his or her perception but should keep on doing this all the (hile albeit not as acti&ely as during deepening. The idea is that during the entire duration of the phase all action should be focused on e#periencing the ma#imum possible amount of tactile"kinesthetic and &isual perceptions. This entails constantly touching and e#amining e&erything in minute detail. For e#ample if passing by a bookcase touch and e#amine some of the books in it including their pages and corners. Tactile obser&ation should be performed on e&ery encountered ob%ect. Palpation may be applied separately as a background sensation. This is done in order not to o&erload the sense of sight. The hands should be touching something all the time or better still rubbing each other. 3s-Needed Sensory 3'plifi ation 1pplying the as"needed sensory amplification techni2ue is no different than constant sensory amplification. )t is used only (hen a foul Fa return to a (akeful stateG is imminent or (hen phase &ision starts to blur and fade. For e#ample (hile tra&eling in the phase e&erything may start to blur signaling a (eakening of the phase. 1t this moment the practitioner should touch e&ery a&ailable ob%ectJ obser&e e&erything in fine detail. 1s soon as returns to a clear and realistic state actions may be continued (ithout needing to perform amplification. Constant ?i0ration This techni2ue is used to maintain constant strong &ibrations in the phase. 1s pre&iously noted &ibrations are generated by straining the brain or tensing the body (ithout using muscles. Maintaining strong &ibrations (ill ha&e a positi&e effect on the length of the phase.
Strengthening ?i0rations as Needed )n this case &ibrations are created and strengthened only if signs of a foul become apparent. E#amples of foul indicators include duality of perception or blurred &ision. 4trengthening &ibrations (ill help to deepen the phase allo(ing a practitioner to stay and continue (ithin the phase. Di>ing 7eadfirst This techni2ue is the same as the deepening techni2ue of the same name. )f a phase is about to dissol&e di&ing headfirst (ith the eyes shut and a desire to di&e as 2uickly and deeply as possible. 1s soon as phase depth returns translocation techni2ues may be used to keep from arri&ing at a dead end. /or ed /alling 3sleep 1s soon as indicators of a foul appear immediately lie do(n on the floor and attempt forced falling asleepJ the same as the phase entry techni2ue. 1fter successfully performing the techni2ue F8" 1Asec.G a practitioner may get up and continue to tra&el through the phase since the perception of reality and its depth (ill most likely be restored. Resist actually fall asleep. 9otation )f indicators of a foul appear the practitioner should start rotating around the head"to"feet a#is. Unlike the phase entry techni2ue of the same name the mo&ement does not ha&e to be imagined. This is an absolutely real rotation in the phase. 1fter se&eral re&olutions depth (ill be restored and actions may be continued. )f indicators of a foul persist rotation should continue until proper depth is achie&ed. Counting 7uring the entire phase count to as large a number possible " not %ust for the sake of counting but (ith a strong desire to reach the highest number possible. ,ounting may be performed silently or out loud.
This techni2ue (orks by creating a strong determination to remain in the phase by pro&iding a goal that re2uires action in the phase. ;istening in )f there are any background sounds similar to those heard (hile entering the phase " rumbling (histling ringing bu==ing or si==ling I these sounds may be used to prolong duration of the phase by aggressi&e attempts at listening in hearing the entire range of internal sounds. The forced listening in techni2ue may also be used for phase maintenance. 7oo!ing onto the phase 1nother interesting method of !maintaining$ is hooking onto the phase. )n the e&ent of an impending foul grab onto an ob%ect in the phase acti&ely palpate or s2uee=e it. E&en if a return to the body occurs during this techni2ue the hands (ill continue to hold the phase ob%ect and the physical hands (ill not be percei&ed. 5eginning (ith these phantom feelings in the hands separation from the body is possible. 1ny nearby ob%ect may be hooked- the leg of a chair a drinking glass a doorknob a stone or a stick. )f there is nothing to grab hold of clasp the hands together or bite do(n on a lip or the tongue. T(o rules apply to using the techni2ues that help to resist a phase e#it. First of all ne&er think that the phase might end and result in a return to the bodyJ thoughts like this are like programming that immediately send the practitioner to a (akened physical state. 4econdly do not think about the physical body. 7oing (ill also instantly return the practitioner to the body e&ery time.
#EC7NI<4ES 3ND 94;ES /O9 9ESIS#ING /3;;ING 3S;EEP Constant 4nderstanding of the Possi0ility of /alling 3sleep Most of the time falling asleep (hile in the phase can be o&ercome by a constant a(areness that sleep is possible and detrimental to a continued phase. 1 practitioner must al(ays consider the probability of falling asleep and actions must be carefully analy=ed to ensure that they are based on real desires and not on parado#ical notions (hich are common to dreams. Periodi 3nalysis of 36areness Periodically asking the 2uestion !1m ) dreaming/$ (hile in the phase helps appraise situations and the 2uality of the actions being performed at any moment. )f e&erything meets the standards of full phase a(areness actions may be continued. 1sked on a regular basis this 2uestion becomes habit automatically used (hile transitioning to the phase state. )f you keep asking this 2uestion regularly sooner or later it (ill arise automatically at the moment (hen you are actually transitioning into a dream. This (ill then help one to (ake up after (hich it is possible to continue to remain in a full"fledged phase.. The fre2uency of the 2uestion should be based on a practitionerDs ability to consistently remain in the phase. )f a phase usually lasts fi&e to 1A minutes or more it is not necessary to ask the 2uestion more than once e&ery + minutesJ other(ise this 2uestion has to be asked fre2uently literally once a minute or %ust a little less often. There is another important rule related to resisting falling asleepno practitioner should engage or participate in spontaneous e&ents occurring in the phase. E&ents that are not planned or deliberate lead to a high probability of being immersed in the side action (hich results in a loss of concentrated a(areness.
#EC7NI<4ES 3G3INS# 3N 4N9ECOGNIBED P73SE 4ince the techni2ues of testing the realness of the end of the phase are a little absurd and demand additional attention to actions they should only be used in those cases (hen they are indeed re2uired. Until then one should simply bear them in mind and use them only in moments of doubt. The same methods may be used to safely determine (hether or not the practitioner is in the phase (hen using techni2ues for entering it. 7yper- on entration 4ince the cessation of the phase e#perience may be simulated and no different in terms of perception from a real e#it differences bet(een the physical (orld and the phase (orld must be acti&ely discerned. )n other (ords a practitioner must kno( ho( to determine (hether a genuine phase e#it has occurred. 1t present only one e#periment is kno(n to guarantee an accurate result. The phase space cannot (ithstand prolonged close &isual attention to the minute details of ob%ects. .ithin se&eral seconds of acute e#amination shapes begin to distort ob%ects change color produce smoke melt or morph in other (ays. 1fter e#iting the phase look at a small ob%ect from a distance of four to si# inches and remain focused on it for 1A seconds. )f the ob%ect does not change a practitioner can be assured that the surroundings are reality. )f an ob%ect is someho( distorted or aske( a practitioner kno(s that the phase is intact. The simplest option is to look at the tip of the finger since it is al(ays close at hand. )t is also possible to take a book and e#amine its te#t. Te#t in the phase (ill either blur or appear as alphabetical gibberish or full of incomprehensible symbols. 3u*iliary te hni$ues There are a &ariety of other procedures to test the occurrence of a foul. 6o(e&er since any situation any property or any function can be simulated in the phase these procedures are not al(ays applicable.
For e#ample some suggest that it is sufficient to attempt doing something that is realistically impossible and if a practitioner is in the phase the impossible action (ill be possible. The problem (ith this suggestion is that the la(s of the physical (orld may be simulated in the phase so flying passing through (alls or telekinesis may not be possible e&en in the deepest phase. )t has also been suggested that looking at a clock t(ice in a ro( may help a practitioner determine (hether or not the phase is intactJ allegedly the clock (ill display a different time each time it is obser&ed. 6ere again the clockDs display may not change in the phase. Of all the au#iliary procedures one deser&es mention and (orks in the ma%ority of cases- searching for differences from reality in the surroundings. 1lthough the usual surroundings of a practitioner may be 1AAK accurately simulated in the phase it is &ery rare. Therefore it is possible to figure out (hether a phase is intact by carefully e#amining the room (here e&erything is taking place. )n the phase there (ill be something e#tra or something (ill be missingJ the time of day or e&en the season (ill be different from reality and so on. For e#ample (hen &erifying (hether a foul occurred a room may be missing the table supporting a tele&ision set or the table may be there but be a different color. GENE93; 94;ES /O9 M3IN#3INING The rules for maintaining the phase deal (ith resisting all or most of the problems (hich cause a phase to end. 4ome of these rules are capable of increasing the length of stay in the phase by many times and must be follo(ed. The practitioner should not loo+ into the distance( )f fara(ay ob%ects are obser&ed for a long period of time a foul may occur or one may be translocated to(ards these ob%ects. )n order to look at distant ob%ects (ithout problems a practitioner has to employ techni2ues for maintaining. For e#ample from time to time the practitioner should look at his hands rub them against each other or maintain strong &ibrations.
:onstant activity( Under no circumstances should a practitioner remain passi&e and calm in the phase. The more actions performed the longer the phase is. The fe(er actions I the shorter the phase. )t is enough to pause for thought and e&erything stops. Elan of action( There should be a clear plan of action consisting of at least ; tasks to be carried out in the phase at the earliest opportunity. This is necessary for se&eral important reasons. First the practitioner must not pause in the phase to think about !(hat to do ne#t$ (hich fre2uently results in a foul. 4econd ha&ing a plan the practitioner (ill subconsciously perform all of the actions necessary for staying in and maintaining the phase to carry out all the tasks that ha&e been planned. Third intelligent and pre"planned actions permit focused ad&ancement of purposeful actions &ersus (asting phase e#periences on (hate&er comes to mind at a gi&en moment. Fourth a plan of action creates necessary moti&ation and conse2uently pronounced intent to perform the techni2ues to enter the phase. Stopping the -3( The less )nternal 7ialogue F)7G and reflection that occurs in the phase the longer it lasts. 1ll thinking must be concentrated on (hat is being achie&ed and percei&ed. Talking to oneself is completely prohibited. The reason for this is that many thoughts may act as programming in the phase and e&en announcing them internally may introduce alterations including negati&e ones. For e#ample thinking about the body cause a return to it. The practitioner may also get lost in thought (hich (ill lead to a foul. 1lso sporadic thoughts usually and 2uite easily cause the practitioner to simply fall asleep. % practitioner $ust try to re-enter the phase after e#periencing a foul( 1l(ays remember that a typical phase e#perience consists of se&eral repeated entries and e#its. Essentially in most cases it is possible to re"enter the phase through the use of separation or phase state creation techni2ues immediately after returning to the body. )f the practitioner has %ust left the phase the brain is still close to it and appropriate techni2ues may be applied in order to continue the %ourney.
#8PIC3; MIS#3=ES (I#7 M3IN#3INING Forgetting to try to re"enter the phase after it is o&er although doing so greatly helps to increase number of e#periences had. 4taying focused on techni2ues for !maintaining$ instead of performing them as background tasks. 3etting distracted by e&ents and dropping phase maintenance techni2ues instead of continually performing (hatDs needed to maintain the phase. 4uccumbing to the idea that maintaining is not necessary (hen the phase appears &ery deep and stable e&en though these could be false sensations. Using the necessary techni2ues too late. 4topping due to uncertainty about further actions (hile there must al(ays be a plan. Forgetting that it is possible to fall asleep in the phase (ithout reali=ing it. Recogni=ing the risk of falling asleep must be a primary focus. 3etting pulled into e&ents occurring in the phase instead of obser&ing and controlling them from the outside. Forgetting that techni2ues for !maintaining$ must al(ays be used to remain in as deep a phase as possible and not %ust for maintaining any odd state. 4topping the use of techni2ues for !maintaining$ during contact (ith li&ing ob%ects (hen the techni2ues must be used constantly. ,ounting (ithout the desire to count as high as possible. Performing imagined rotation instead of real rotation. Passi&eness and calmness instead of constant acti&ity. E#cessi&e thinking and internal dialogue (hen these should be kept to an absolute minimum.
<uestions 1. .hat is a foul/ +. .hat is the minimum duration of the phase/ 8. .hat do phase maintenance F!maintaining$G techni2ues counteract besides fouls and falling asleep/ :. .hy might a practitioner think that the phase has ended (hen it actually is still in progress/ ;. 4hould !maintaining$ techni2ues al(ays be used/ <. .hat primary techni2ues (ork against the occurrence of fouls/ >. 6o( can a practitioner hook onto the phase/ ?. .hile in the phase (hat do thoughts about the body lead to/ @. .hat 2uestion should be asked in the phase in order to reduce the probability of falling asleep/ 1A. .hat happens to an ob%ect during hyper"concentration/ 11. 6o( else apart from hyper"concentration might a practitioner effecti&ely recogni=e a false foul/ 1+. .hile in the phase is it permitted to look into the distance for a long time/ 18. .hat is )7 and ho( does the degree of it affect the duration of a phase e#perience/ 1:. .hat should a practitioner al(ays do after an inad&ertent return into the body/ #as!s 1. 7uring the ne#t fe( phases dedicate yourself to the single goal of maintaining as long as possible using as many maintaining techni2ues as you can. +. Figure out (hich techni2ues ha&e pro&en the most effecti&e and comfortable for you so that you may use these later. 8. )ncrease the duration of your a&erage phase to at least 8 minutes Fe&aluated ob%ecti&elyG.
Problems (ith phase identification during entry often arise at the initial stages of studying the phase. 1 practitioner simply cannot understand (hether or not he or she is already in the phase. This uncertainty can manifest (hile lying do(n or (hile practicing in other postures. )f a practitioner is simply lying do(n physically percei&ing his o(n body and doing nothing then it is indeed difficult to determine (hether or not he is present in the phase. )t is sufficient to note that there might be no signs of a phase state. On the contrary there may be a host of signs and unusual sensations but they by no means necessarily indicate the onset of the phase. The problem of the uncertainty of a phase state is al(ays sol&ed through actions. )f the practitioner is lying do(n then standard separation techni2ues may produce indication of phase achie&ement " in the ma%ority of cases I since such techni2ues may often be incorrectly performed. )t is possible to perform techni2ues that are only achie&able in the phase state. )f a practitioner stands up and does not recogni=e his surroundings then it can be assumed that the practitioner is standing up in the phase. 6o(e&er often based on the obser&ation that !e&erything is as in reality$ a practitioner may stand up and note that e&erything is in fact !as in reality$ simply because the practitioner is still in !reality$. )n ans(er to this dilemma the phenomenon of hyper"concentration has been pre&iously mentioned in relation to maintaining phase. 5y using hyper"concentration it is al(ays possible to ascertain (hether the practitioner is in the phase. 6o(e&er as a rule hyper"concentration is rarely necessary. Most often the follo(ing signs indicate that separation has occurred in the phase- unusual sensations in the body during mo&ement e#treme tightness during mo&ement a strong physical urge to lie back do(n dis%ointedness of surroundings and blurred or complete absence of &ision. Often the problem resides in the use of direct techni2ues (here the practitioner e#pects fast results and attempts to determine (hether the phase has been achie&ed. 1s a principle this should not be done. .hen using direct techni2ues the phase manifests itself clearlyJ
therefore if an attempt to determine its presence is made it is an indicator that the phase is 2uite likely still far off. EME9GENC8 9E#49ND P393;8SIS 4tatistics sho( that in one"third of initial phase e#periences a practitioner is faced (ith a degree of fear that forces a return to the body. Periodically e&en e#perienced practitioners face situations that re2uire an abrupt return to (akefulness. This presents a number of concerns. )n and of itself returning to the body is almost al(ays unproblematicJ remembering and thinking about the body often suffices and (ithin moments the practitioner is returned to the body from (hate&er location in the phase. 1dmittedly it is ad&isable during this type of situation to shut the eyes and abstain from touching anything. 1s a rule (hen these actions are performed simply standing up in the physical (orld is all that is re2uired to complete a returnJ ho(e&er this is not al(ays simply achie&ed. 4ometimes after reentering the body the practitioner suddenly reali=es that physical functionality has ceased due to the onset of sleep paralysis or the sensation that the body has been s(itched off. 7uring sleep paralysis it is impossible to scream call for help or e&en mo&e a finger. )n the ma%ority of cases it is also impossible to open the eyes. From a scientific point of &ie( this is a case of an abrupt unnatural interruption of the rapid eye mo&ement FREMG phase of sleep during (hich this paralysis is al(ays present and it can persist for some time after the phase is interrupted. This is (here it gets interesting. People in the physical (orld are accustomed to an important rule- if you (ish to achie&e something then do it and do it as acti&ely as possible. This rule though good is not al(ays applicable to certain conditions linked to the phase and applies least of all to e#iting the phase. 4ometimes e#treme effort makes it possible to break through sleep paralysis and resume mo&ement though most of these efforts tend to e#acerbate immobility.
7ue to the unusual nature of a negati&e situation follo(ing a deliberate fear"induced return to the body the depth of the phase may greatly increase because of the bodyDs natural protecti&e inhibition of functions originating in the cerebral corte#J this results in e&en greater agitation greater fear. The paralysis gro(s stronger. This is a &icious circle that leads to unpleasant feelings and emotions (hich may e&aporate any desire to practice the phase. )gnorance of correct procedures has led to the (idespread opinion that such ad&erse situations may make it impossible to come back from the phase at all. These opinions suppose that it is therefore dangerous to get in&ol&ed (ith the practice. 6o(e&er the solution to this problem rests in &ery simple actions and procedures that can pre&ent a large number of negati&e e#periencesCo'plete 9ela*ation )n the section on deepening and maintaining it (as noted that the more acti&e a practitioner is (hile in the phase the better. ,on&ersely if there is less acti&ity the 2uality of the phase declines allo(ing for an easy e#it. Thus in order to lea&e the phase the practitioner only needs to completely rela# and ignore any percei&ed sensations actions or thoughts. 1 practitioner may also recite a prayer mantra or rhyme since that helps the consciousness to be distracted from the situation more 2uickly. Of course one needs to calm do(n and try to get rid of the fear (hich in and of itself is capable of keeping such a state going. Periodically the practitioner should try to mo&e a finger in order to check (hether attempts at rela#ation ha&e had an effect. Con entration on a /inger 1 practitioner e#periencing sleep paralysis should try mo&ing a finger or a toe. 1t first this (onDt (ork but the practitioner has to concentrate precise thought and effort on the action. 1fter a little (hile the physical finger (ill begin to mo&e. The problem (ith this techni2ue is that the practitioner may accidentally start making phantom motions instead of physical mo&ements (hich is (hy an
understanding of the difference bet(een the t(o sensations is necessary since it is often not &ery ob&ious.
Con entration on Possi0le Mo>e'ents The physiology of sleep paralysis the phase state and dreams are such that (hen the practitioner is in one of these states some actions are al(ays associated (ith mo&ements made in the real body. This is true (hen mo&ing the eyeballs the tongue or (hile breathing. )f the practitioner concentrates attention on these processes it is possible counteract inhibitions to physical mo&ementJ as a result a sleep" paraly=ed practitioner (ill become able to mo&e in reality. 9ee>aluating the Situation Under normal circumstances deliberate e#it from the phase is not the norm. 7eliberate e#it is commonly caused by certain fears and pre%udices. )f a practitioner is not able to acti&ate the body using other emergency return techni2ues a careful consideration the possibilities offered by the phase is recommended. There are many interesting and useful things that can be e#perienced in the phase. .hy ruin the possibility of great opportunity because of a baseless fear/ To be fair it must be noted that emergency e#it techni2ues do not al(ays (ork. 1s a rule after a long period of sleep depri&ation or at the beginning of or in the middle of a nightDs sleep the urge to sleep is so great that it is difficult to resist the sleep paralysis phenomenon. )n this respect ree&aluating the situation is highly recommended so that a practitioner is able to take ad&antage of the situation &ersus suffering by it. 4leep paralysis is easily transmuted into a phase state by means of indirect techni2ues. By the &ay, +no&ing ho& to e#it paralysis is i$portant not only for practitioners of the phase, since such paralysis occurs even &ithout the phase for appro#i$ately one-third of the hu$an population at least once in a lifeti$e( -t usually happens "efore or after sleep( /IG7#ING /E39
Fear in the phase is a &ery common occurrence. The practitioner may e#perience fear at any stage although it is e#pressed much more clearly during initial practice. The causes of fear are &ery di&erse- a feeling that returning to the body is impossibleJ a fear of deathJ (orrying that something bad is going to happen to the bodyJ encountering something scary and terrible in the phaseJ painful sensationsJ o&erly sharp hyper"realistic sensations. One fear dominates all others- the instinct of self"preser&ation (hich (ithout any apparent reason can induce a feeling of absolute horror I a feeling that cannot be e#plained or controlled. For a no&ice stricken by insurmountable fear that causes paralysis there is only one (ay to gradually o&ercome. Each time a no&ice enters the phase an attempt should be made to go a step further than the pre&ious time. For e#ample in spite of feeling terrified the practitioner should try to raise the hands and then mo&e them back to the initial position. The second time the practitioner should attempt to sit do(n. The third time standing up should be attempted. The fourth time (alking around in the phase is ad&ised. Then after incremental steps to(ard e#periencing the harmlessness of the phase state producti&e calm action may ensue. Interesting fact! Fear itself can "e used to enter the phase and re$ain there for a long ti$e( Once fears are allayed, a cal$ed practitioner is e#periences increased difficulty &ith entry into the phase( For a practitioner (ho faces periodical fears reali=ing that there is no real danger encourages progress in practice. Urges to rapidly return to the body are then made baseless. 4ooner or later calmer thought dominates e&ents in the phase and fear happens less often. .hen dealing (ith momentary fear caused by e&ents in the phase the simplest solution is to tackle it head"on and follo( through to the end in order to a&oid a fear"dri&en precedent. )f a practitioner al(ays runs a(ay from undesirable e&ents the e&ents (ill occur more and more fre2uently. )f a practitioner is incapable of facing fear in the
phase it is best to use the translocation techni2ue to tra&el else(here although this solution only produces temporary relief.
C9E3#ION O/ ?ISION 9ision is often a&ailable at the &ery beginning of a phase especially (hen the practitioner uses image obser&ation and &isuali=ation techni2ues to enter. 4ometimes &ision appears (ithin the first fe( seconds. Other times it manifests during the deepening process. 6o(e&er there are cases (here &ision is not a&ailable and must be created 2uickly at any cost. 9ision may arri&e as soon as it is thought about but if this does not occur a special techni2ue is necessary. To create &ision a practitioner needs to bring the hands four to si# inches in front of the eyes and try to detect them through the grayness or darkness. Peering aggressi&ely and attenti&ely at the minute details of the palms (ill cause them to appear much like they are being de&eloped on Polaroid film. 1fter se&eral seconds &ision (ill become clear and along (ith the palms the surroundings (ill also become &isible. Under no circumstances should the physical eyelids be opened. 9ision (ill appear on its o(n and (ill not differ from that of reality and the physical sensation of opened eyes (ill emerge. )t is possible to shut the eyes in the phase an infinite number of times e&en (ithout ha&ing opened them at all since the latter is not needed for creating &ision. The physical eyelids may be open only (hile e#periencing a &ery deep phase. )n a shallo( phase opening the eyes (ill cause a return to (akefulness. The practitioner must also keep in mind that &ision should only be created after a complete separation from the body and a subse2uent translocation has been achie&ed. 1ttempting to &ie( the hands during flight or (hile ho&ering in an unidentified space leads to arbitrary translocation. CON#3C# (I#7 ;I?ING OBGEC#S T(o problems may surface (hile con&ersing (ith animate ob%ects in the phase- silence or a return to the body. )n &ie( of the fact that many phase applications are based on contact (ith people for one
purpose or another it is necessary to understand ho( to correctly manage contact (ith li&ing ob%ects. )n order to a&oid a foul Fe%ection from the phase into realityG the elementary rules of !maintaining$ must be obser&ed. 1cti&ely obser&ing the facial features or clothing of a person you (ant to communicate (ith. .hile communicating the practitioner should constantly rub the hands together or maintain strong &ibrations by straining the brain. Remember to perform the techni2ues to a&oid becoming absorbed in communication. 1 more comple# problem is o&ercoming the communicati&e unresponsi&eness of ob%ects in the phase. )n many cases the speech of an ob%ect is blocked by the internal stress of the practitioner. 4ometimes the problem stems from an e#pectation that an ob%ect (ill not be able to communicate in the phase. )t is important to treat the ob%ects in a calm manner. There is no use trying to shout or beat the ob%ect to force communication. On the contrary it is much more effecti&e to treat the ob%ect gently (ithout applying pressure. 7o not peer at an ob%ectDs mouth e#pecting sounds to emerge. )t is better to look else(hereJ taking a passi&e interest in communication generally yields the best results. 1s a rule the first time that communication (ith a li&ing ob%ect is successful future attempts go unhindered. ,ommunication methods in the phase are should be no different than those used in ordinary life- talking facial e#pressions gesturing (ith the hands body language. Telepathy is not necessary. 9E3DING Reading te#t in the phase may be accompanied by a number of difficulties. First small print becomes illegible because the affects of hyper"concentration may distort te#t. This problem is sol&ed by using large"font te#tual sources of information. For e#ample the te#t of a normal book blurs (hen obser&ed too attenti&ely but the large font on the co&er of a book is easily read since its si=e is sufficient for rapid reading (ithout detailed scrutiny.
The second problem encountered (hile reading in the phase is (hen te#t is legible but is completely meaningless in compositionJ gibberish. This problem is sol&ed by turning o&er the pages looking for a readable message. )t is also possible to find another copy or create it ane( using the ob%ect"finding techni2ues. The same applies to cases (here the te#t is seen as a set of incomprehensible symbols or signs. .hile reading in the phase the practitioner should not forget about performing !maintaining$ techni2ues to pre&ent a foul by becoming too rela#ed. ?IB93#IONS The phase is often accompanied by an unforgettably unusual sensation that may be used successfully to enter deepen or maintain the phase. )t is difficult to describe it better than the sensation of a hea&y current passing through the entire body (ithout causing any pain. )t may also feel like the (hole body is contracting or a tingling sensation similar to numbness. Most often the sensations are similar to high"fre2uency &ibrations of the body (hich e#plains the origin of the term !&ibration$. )f the practitioner is not sure (hether or not he e#perienced &ibrations then there is a good method to sol&e his problem- if he really did he (ill not ha&e any doubts about it. )n all other cases (hen there are doubts and uncertainty the practitioner is definitely not dealing (ith &ibrations or is dealing (ith another form thereof. )f you ha&e e#perienced &ibrations at least once the recollection of these sensations helps greatly during the simultaneous application of indirect techni2ues. They are created supported and strengthened by straining the brain or tensing the body (ithout using the muscles. For &ibrations to appear it often suffices merely to think about them. 7uring the first e#perience one should e#periment (ith them for a (hile by rolling them around the body and its parts as (ell as strengthening and (eakening them.
0o&ever, one should not thin+ that the presence of vi"rations is a necessary condition for "eing in the phase( Many no&ices often stri&e not for the phase but for &ibrations after (hich the former must supposedly follo(. That should not be the case. There are indeed specific techni2ues that make it possible to get into the phase by creating &ibrations but in all other cases they are not necessary and some practitioners may ne&er ha&e them at all. #EC7NI<4ES /O9 #93NS;OC3#ING #79O4G7 OBGEC#S )n a deep phase the properties of the surrounding en&ironment become &ery similar to the physical (orld. 6o(e&er it may sometimes be necessary to pass through a (all or translocate to a&oid a physical barrier in the phase. There are t(o basic options for passing through barriers like (alls. Usually mastering these re2uires se&eral attempts. Interesting fact! -f a practitioner concentrates on the physical sensations associated &ith passing through a &all, it is possi"le to get stuc+( % practitioner $ay even e#perience the feeling of o"structed "reathing &hen this happens( %t such a ti$e it is necessary to return to the "ody( 9apid Defo used Penetration Run or %ump at a (all (ith a burning desire to penetrate it. 7onDt focus on the (allJ instead concentrate on the immediate surroundings. 7o not try to take anything from the current location since this may impede a successful passage through the (all. #he Closed Eyes #e hni$ue .hen approaching a (all the practitioner must close his eyes and completely focus on a desire to pass through it (hile imagining that
the (all does not e#ist or that it is transparent and penetrable. 4urface resistance should be pressed through continuing on (ith the aggressi&e desire and concentration. /;IG7# Taking flight in the phase is a simple matter of remembering past dreams of flight. 'othing needs to be tensed no (ord need to be said. 1ttempting flight (ith closed eyes produces a high rate of success but presents an increased probability of inad&ertent translocation. )f a flight attempt is unsuccessful a practitioner may try %umping from a high ele&ation or from a (indo(. The natural instinct of dream flight takes o&er and the fall becomes a controlled flight. 6o(e&er %umping from (indo(s or other ele&ations is ad&isable only to practitioners (ith e#perience since no&ices may not al(ays be able to determine (hether they are in the phase or in reality. 1nother (ay to fly is to try to suspend oneself in the air (hen %umping up. S4PE9-3BI;I#IES The realism of the phase space does not impose limits on the ability to perform actions that cannot be performed in the physical (orld. )t is important to remember that only a practitionerDs apprehension places limits on (hat may be done in the phase. For e#ample if a practitioner needs to get to a location " e&en &ery far a(ay " it may be reached by teleportation. )f an ob%ect needs to be mo&ed from one side of the room to the other it may be mo&ed by telekinesis. One of the ma%or benefits of the phase e#perience is unencumbered freedom of action. To master unusual abilities only a fe( phases need to be spent in concentrated de&elopment of the methods. #ele!inesis
)n order to learn telekinesis Fmo&ing ob%ect by thoughtG the practitioner concentrate on an ob%ect (hile e#periencing a deepened phase and attempt to mo&e the ob%ect by thinking about the mo&ement. The only re2uired action is aggressi&e &isuali=ation of the ob%ectDs mo&ement. 'o specific e#ternal actions are re2uired. Telekinetic ability is inherent to e&ery human being. )f attempts are unsuccessful at first press on. 5efore too long the full effect of the practitionerDs (ill yield results. Using this ability helps to encourage a good phase e#perience by pro&iding a tool for carrying out planned tasks. Pyro!inesis )gniting an ob%ect in the phase %ust by staring at it re2uires a strong desire to heat up and set fire to the ob%ect. Performed successfully an ob%ect (ill smoke distort darken and then burst into flames. #elepathy To de&elop telepathy in the phase it is necessary to peer at animate ob%ects (hile listening surrounding e#ternal and internal sounds (ith the intention of hearing thoughts e#pressed by thought. E&en e#perienced practitioners encounter difficulty (hile de&eloping telepathy but (hen successful contact (ith people in the phase is substantially simplified. Using telepathy discerning the thoughts of people animals and ob%ects is possible. 6o(e&er this should not be taken too seriously since it is merely the nature of the phase to simulate (hat is e#pected. #rans'utation Transforming an ob%ectDs form re2uires the techni2ue of transmutation Frefer to ,hapter @G. )t should also be noted that if the goal is not to con&ert something but rather to transform oneself then it is necessary to use the translocation techni2ues Falso described in ,hapter @G (hereby attention has to be concentrated not on the desired place but on the desired form. 6ere again there are no limitations apart from indi&idual courage and fantasy. )t is possible to
become a butterfly or a dinosaur. )t is possible to become a bird or a (orm. )tDs e&en possible to become a child or a person of the opposite se#. These are not simply e#ternal changes but real transmutations (ithin and (ithout. )f a practitioner becomes a butterfly it accompanies the sensation of ha&ing (ings many legs and an unusual body. The practitioner (ill intuiti&ely kno( ho( to control each part of this ne( body. This is a superficial description of the transmutation e#perience (hich ob&iously defies a customary understanding of reality. #7E IMPO9#3NCE O/ CON/IDENCE 1 crucial factor in de&eloping phase abilities is self"confidence in the ability to use the skills. )nitially these abilities are absent because the human brain tuned in to ordinariness blocks confidence in the ability to do anything unusual. 1s soon as strong confidence is reached in the performance of phase abilities all others become easy to achie&e. 1lthough confidence in phase abilities may gro( strong practitioners should remain soundly a(are that abilities in the phase are limited to the phase. 1ttempting telekinesis pyrokinesis or transmutation in the real (orld is a (aste of time and energy. CON#9O;;ING P3IN 1long (ith all the positi&e e#periences and sensations that may be en%oy in the phase painful e#periences nature may also manifest. Punching a (all in a deep phase state (ill cause the same pain as if a (all had been struck in physical reality. 4ome actions in the phase may una&oidably cause unpleasant feelings of painJ therefore it is necessary to kno( ho( to a&oid painful actions. Focusing on an internal confidence that pain (ill not result from an action (ill alle&iate the problem. 1 practitioner may e#periment (ith this type of focus by pummeling a (all (hile resol&ing that there is no pain. )f the e#periment succeeds then
obtaining the same result (ill ne&er again re2uire the same le&el of effortJ thinking that the phase is painless (ill suffice. MO93; S#3ND39DS IN #7E P73SE From the &ery beginning it should be understood that the moral compass of phase space has nothing in common (ith the properties and la(s in the physical (orld that promulgate reality. The phase space seemingly imitates the physical (orld (ith all its properties and functions only because (e are used to percei&ing it and are not e#pecting anything else. Moral principles and rules apply only to the place (here these ha&e been. )t does not make sense to follo( the same rules (hile in the phase. The practitioner should not refrain from certain actions in the phase because some (ould be unacceptable improper or bad in the real (orld. These are merely beha&ioral patterns that are unfounded in the (orld of the phase (here e&erything operates on the basis of entirely different la(s. The only moral rules that might e#ist in the phase are those that the practitioner establishes. )f desired complete unhindered freedom may be e#perienced. S#4D8ING POSSIBI;I#IES 3ND SENS3#IONS 'o&ice practitioners should not immediately rush to(ards a single specific goal if long"term practice is desired. )t is better to e#tensi&ely in&estigate the phase and its surroundings before focusing on accomplishment. This (ill build intimacy (ith the e#perience and allo( unhindered entry and interaction (ith the phase. 1s in reality learning (hate&er first re&eals itself is the key to increasing and speciali=ing kno(ledge. 1 beginning practitioner should at first en%oy the simple fact of actually being in the phase then lean its details and functions. Once inside the phase a
practitioner should e#plore it e#amining and interacting (ith e&erything encountered. 6e should also try to fully sharpen all the possible feelings in the phase in order to fully understand ho( unusual the phase is in its realism. 1 practitioner must e#perience mo&ement- (alking running %umping flying falling s(imming. Test the sensations of pain by striking a (all (ith a fist. The simplest (ay to e#perience taste sensations is to get to the refrigerator and try to eat e&erything that you find there at the same time not forgetting to smell each item. .alk through the (alls translocate create and handle ob%ects. E#plore. 1ll these actions are &ery interesting in and of themsel&es. The possibilities really are infinite. 6o(e&er only (hen they are (ell understood and thoroughly e#plored can it be said that the practitioner really kno(s (hat the phase is about. #8PIC3; MIS#3=ES (I#7 P9IM398 S=I;;S .hen trying to discern (hether or not a phase is intact a %udgment is based on a similarity to the departed physical en&ironment. )n the phase physical attributes are simulations. 6yper"concentrating on an ob%ect for too short a time (hile trying to determine (hether the surroundings are in the phase or in the physical (orld. 7eliberately attempting to end the phase prematurely (hen the entire natural length of the phase should be taken ad&antage of. Panic in case of paralysis instead of calm rela#ed action. Refusal to practice the phase because of fear though this problem is temporary and resol&able. Opening the eyes at the initial stages of the phase since this fre2uently leads to a foul. Premature attempts to create &ision in the phase (hereas separating from the body and deepening should occur. E#cessi&e haste (hile creating &ision although in the ma%ority of cases &ision appears naturally.
.hile concentrating on the hands to create &ision doing so at an e#cessi&e distance &ersus the recommended four to si# inches. Forgetting about the techni2ues for !maintaining$ (hile in contact (ith li&ing ob%ects. Forgetting to shut the eyes or defocusing &ision (hen translocating through (alls or other solid ob%ects. 7esiring to do something superhuman in the phase (ithout the re2uired internal desire and confidence. Fear of e#periencing pain in the phase instead of learning to control it. Obser&ing moral standards in the phase (hen they do not apply. 1 tendency to immediately use the phase for something practical instead of first thoroughly e#ploring and interacting (ith the surroundings.
E*er ises for Chapter <uestions 1. 1re there skills in the phase that must first be mastered before the phase may be used to its full e#tent/ +. )s it possible to understand (hether a phase is intact by attempting to fly/ 8. 6as a practitioner most likely gotten up in the phase or in reality if there are doubts about this/ :. )s it sufficient to think about the body in order to return to it and is it only re2uired to return into the body in order to control it/ ;. .hich arm should be acti&ely and aggressi&ely mo&ed to o&ercome sleep paralysis/ <. )s it possible to tell %okes to oneself to o&ercome sleep paralysis/ >. )s it possible to mo&e the physical eyes (hile in the phase/ ?. .hat should be done if sleep paralysis cannot be o&ercome/
@. ,an sleep paralysis occur (ithout practicing the phase/ 1A. .hat if fear is not addressed and con2uered/ 11. )s it possible to gradually master the phase in order to o&ercome fear/ 1+. )s there cause for fear of anything in the phase/ 18. 1t (hat point can &ision be created in the phase by opening the eyelids and not through the use of special techni2ues/ 1:. .hat (ould happen (ith an attempt to open the eyes after sitting up in bed i.e. before becoming completely separated from the phase/ 1;. .hy may contact (ith li&ing ob%ects in the phase cause a return to the body/ 1<. .hat problems might occur if a practitioner studies the mouth of a talking ob%ect/ 1>. )n the phase ho( 2uickly can small te#t be read/ 1?. .hich is easier to read in the phase- te#t in a ne(spaper or te#t on a large billboard/ 1@. )s it possible to see hieroglyphs instead of te#t (hile reading in the phase/ +A. )s it possible to burst through a (all after running up to it (ith the eyes shut/ +1. .hich muscles of the body must be tensed to start flying in the phase/ ++. 1re there any e#trasensory abilities that are inaccessible in the phase/ +8. ,an a practitioner transform into a ball (hile in the phase/ +:. 6o( does pain in the phase differ from pain in the physical (orld/ +;. 4hould a practitioner gi&e up a seat to an elderly person (hile in the phase/ +<. 7ue to moral considerations (hat is prohibited in the phase/ #as!s 1. 7uring your ne#t phase session (alk around your home in&estigating the rooms kitchen and bathroom in detail.
+. 0earn to pass through (alls. ,ompletely dedicate one long phase e#perience to perfecting this skill. 8. 0earn to fly in the phase. :. .hile in a deep phase learn to control pain by hitting a (all (ith your fist. ;. .hile in the phase learn telekinesis Fthe ability to mo&e ob%ects by thoughtG and pyrokinesis Fsetting ob%ects on fire also performed by thoughtG. <. 7edicate a lengthy phase e#perience to an e#periment (ith &ision- create it if it is not already a&ailable and then shut your eyes and recreate &ision. 7o this at least ten times o&er the course of a single phase >. 3et ob%ects in the phase to start talking. ?. 7edicate a long phase to searching for different kinds of te#ts in order to e#periment (ith reading &arious si=e fonts.
practitioner simply belie&es that an entry attempt (as unsuccessful. 6o(e&er if reality is mistaken for the phase a practitioner may perform dangerous or e&en life"threatening actions. For e#ample after getting out of bed in a (akeful state thinking that e&erything is happening in the phase a beginner may approach a (indo( and %ump out of it e#pecting to fly as is customary in the phase. For this reason alone shortcuts to flight should only be taken after gaining a le&el of e#perience that makes it possible to unambiguously distinguish the phase from a (akeful state. )f a glitch occurs (hen practicing translocation techni2ues Ffor e#ample landing in the (rong placeG a practitioner should simply repeat the techni2ue until the desired result is obtained. Either (ay initial training is a must in order to make e&erything easier for you later on. 1s far as ob%ect"finding techni2ues are concerned these are used for both inanimate and animate ob%ects. )n other (ords these techni2ues are e2ually effecti&e for finding for e#ample a person or a utensil. 6o(e&er there are se&eral techni2ues that are only suitable for finding li&ing ob%ects. B3SIC P9OPE9#8 O/ #7E P73SE SP3CE 1ll methods for controlling the phase space stem from a primary la(- the degree of changeability of the phase space is in&ersely proportionate to the depth of the phase and the stability of its ob%ects. That is the deeper and more stable the phase the more difficult it is to perform something unusual in it because in a deep stable phase the la(s of it begin to closely resemble those of the physical (orld.
1ll translocation and finding ob%ects techni2ues are based on the kno(ledge of methods that bypass the primary la(. The secret lies in the fact that not only phase depth affects the controllability of the phase but so does phase stability (hich in turn depends to a large e#tent on the number of sensations e#perienced in the phase. The techni2ues for translocation and finding ob%ects are used (hen these e#perienced sensations are (eakened through certain actions. )n other (ords if a practitioner located in the phase holds a red pencil and e#amines it tactile and &isual perceptions are engaged (hich under sharp agitation cause the ob%ect to e#ist in its complete form. 6o(e&er as soon as the eyes are shut the stability of pencil image (eakens. )n this situation it (ill be enough for the practitioner Fafter sufficient trainingG to concentrate on belie&ing that the pencil is dark"blue in order for it to appear dark blue after opening the eyes. This phenomenon occurs because the color of the pencil is no longer determined by perceptual areas of the brain and therefore it is possible to change it. )f a red pencil is placed on a table and the practitionerDs eyes are shut and there is concentration on a thought that the pencil is no
longer on the table then after opening the eyes the practitioner (ill find that the pencil has disappeared. )n essence (hen the pencil is lying on the table and the practitionerDs eyes are closed and the pencil is not being held no perception is being in&ested in the pencil (hich the practitioner deletes using autosuggestion.
Using certain techni2ue"related methods a practitioner may cause the stability of the phase state to remain in flu# using techni2ues that best suit the practitionerDs indi&idual personality. #EC7NI<4ES /O9 #93NS;OC3#ION #ranslo ation through #eleportation This is one of the simplest and most accessible techni2ues that beginners should use right a(ay. To apply it shut the eyes Fif &ision is presentG and then concentrate attention on a thought"form or image of a location else(here in the phase. 1t this moment there (ill be a string sensation of s(ift flight and (ithin t(o to 1A seconds the destination (ill be reached. The success of this techni2ue depends on a strong concentration upon a single goal- the desired location. Practice must be performed &ery clearly confidently aggressi&ely and (ithout distractions. 1ny unrelated thoughts ha&e a profoundly negati&e influence on the
performance of this techni2ue. They unnecessarily prolong the flight cause a foul or result in arri&ing at an undesired location. #ranslo ation through a Door )n order to use this techni2ue approach any door (ith the strong belief that it leads to the re2uired location. 1fter opening the door the practitioner (ill see and be able to step into the destination. )f the door (as originally open it must be completely shut before applying the techni2ue. 1 dra(back to this techni2ue is that its practice al(ays re2uires a door. )f there is no door users of this translocation techni2ue should create one using an ob%ect finding techni2ue. #ranslo ation through #eleportation 6ith the Eyes Open This techni2ue is difficult because it re2uires an unstable phase space caused by a strong desire to translocate to another location. 7uring teleportation by teleportation (ith eyes shut the practitioner disengages from the current location. .hereas during teleportation by flight (ith eyes shut the practitioner disentangles himself from the current location that is not the case here. Therefore this techni2ue should be used only by e#perienced practitioners (ho are confident that they are capable of remaining in the phase. 1s far as implementing the techni2ue is concerned the practitioner simply needs to stop and concentrate on the thought that he is already present in the desirable location and focus on its image. )t is important to not stare at or touch anything during the thought. 4urrounding space (ill dim blur and then disappear during this time and then the intended location (ill gradually start to appear. The rate of space metamorphosis depends on the degree of desire to reach the re2uired location. )f concentration is (eak or phase depth is poor then after space destabili=es it may not be restored " and a return to the (akeful state (ill occur. #ranslo ation 6ith Closed Eyes
This is one of the easiest techni2ues. To use this techni2ue the practitioner simply needs to shut the eyes and ha&e an intense desire that (hen the eyes are ne#t opened the re2uired location (ill be reached. )n order to considerably increase the effecti&eness of this techni2ue it (ould be useful to imagine at the moment you close your eyes that you ha&e already reached the desired location. Translocation must occur then and it has to happen (ithout the flight sensations that occur during teleportation (ith closed eyes. Translocation must occur right then and it has to happen (ithout the flight that occurs in teleportation (ith closed eyes (hich must be a&oided. #ranslo ation 0y Con entration on a 9e'ote O01e t To perform this techni2ue the practitioner should peer from a distance at a minor detail of the desired location. The greater an intention to see an ob%ectDs detail the 2uicker the arri&al at the ob%ectDs location. 1 dra(back to this techni2ue is that this type of translocation is possible only for places that are already &isible albeit from a great distance. #ranslo ation during Separation The simplest (ay to translocate is to do so (hile separating from the body. Employing this techni2ue is e#tremely simple and &ery con&enient. )t may be combined (ith almost any separation techni2ue and is performed by focusing on the image and feel of a desired location during the initial stages of e#iting the body. )t is e&en better to imagine that phase entry (ill occur and separation (ill complete in a chosen location. Interesting fact! %fter having changed his place of residence, the practitioner &ill very often continue for so$e ti$e to separate fro$ the "ody in the sa$e house &here he &as used to doing this previously(
1 dra(back of this techni2ue is that separation occurs only in the beginning of the phase e#perience and therefore can only be used once. Other options should be considered after the first translocation. #ranslo ation 0y Passing through a (all This techni2ue is performed by (alking or flying through a (all (ith the eyes shut and a firm con&iction that the re2uired location is behind the (all. The barrier does not necessarily ha&e to be a (all. )t can be any non"transparent ob%ect through (hich a practitioner may (alk or fly- a screen a (ardrobe and so on. The main dra(back of this techni2ue is the necessity of appropriate skills for penetrating through solid ob%ects of the phase. 1nother necessary condition for applying this techni2ue is the presence of barriers to pass through. #ranslo ation through Di>ing This techni2ue is identical to passing through (alls (ith the only difference being instead of a (all " (hich may not al(ays be a&ailable " the practitioner (ill use the floor or the ground. The practitioner must di&e headfirst (ith the eyes shut and ha&e complete confidence that the re2uired location is underneath the solid surface. The ability to pass through solid ob%ects is naturally also re2uired. 1 practitioner may di&e through the floor or the ground and also into any flat hori=ontal surface- a table a chair a bed and so forth. #ranslo ation through 9otation 1pply this techni2ue a practitioner in the phase (ill to start rotating on an a#is (hile simultaneously concentrating on a belief that a desired location (ill be reached once rotation is stopped. The eyes must be shut during the rotation or &ision must not be focused on anything in particular. 1s a rule t(o to fi&e re&olutions on an a#is are sufficient. Once again e&erything depends on the ability to fully concentrate on a desired goal (ithout any distractions.
OBGEC# /INDING #EC7NI<4ES #e hni$ue of #ranslo ation 1ll translocation techni2ues are also applicable to ob%ect finding techni2ues since the use of both techni2ues re2uires altering the surrounding the space. )nstead of concentrating on a location the practitioner is to focus on the specific detail of a space that is to be found or changed. 1s a result finding the necessary ob%ect Fpro&ided this techni2ue has been masteredG is guaranteed but maintaining the original location (here the action begins is not guaranteed. )f the goal is to find an ob%ect (hile remaining in the present location use the speciali=ed techni2ues described later on- techni2ues that change only a portion of the phase space. /inding 0y Calling a Na'e This techni2ue is only used to find li&ing ob%ects. The practitioner must call a person or an animal by name to cause the animate phase resident to enter or appear nearby. The call should be loud nearly a shout other(ise it (ill not al(ays (ork. 3enerally it is often enough to pronounce a name se&eral times to achie&e results. )f the desired animate ob%ect does not ha&e a name or the practitioner does not kno( it then any name or general summoning (ill do like !,ome hereH$ This should be done (hile mentally focusing on a clear image of the desired person or animal. /inding 0y In$uiry To perform this techni2ue approach any person in the phase and ask him For herG (here to 2uickly find a desired ob%ect. 1n accurate ans(er is usually gi&en straight a(ay and it should be follo(ed. 6o(e&er to a&oid (asting time do not forget to mention that the ob%ect must be found !2uickly$ or specify that the ob%ect should be !nearby$. 7uring this communication under no circumstances should there be a doubt about the accuracy of the information since other(ise it may lead to a simulation of (hat is e#pected.
The dra(back of this techni2ue is that it re2uires the presence of an animate person and good skill at communicating (ith ob%ects in the phase (hich can pro&e difficult. /inding 0y #urning 3round )n order to use this techni2ue the practitioner must concentrate and imagine that the re2uired ob%ect is located some(here behind his back and after turning around he (ill actually see it there e&en if it (as not there %ust a moment earlier. This (orks best if the practitioner prior to turning around did not &ie( the place (here the ob%ect is e#pected to appear. /inding 3round a Corner .hen approaching any corner concentrate and imagine the re2uired ob%ect is %ust around the corner. Then after turning the corner the ob%ect (ill be found. 1nything that limits space &isibility may be regarded as a corner. This does not ha&e to be the corner of a house or another type of buildingJ it could be the corner of a (ardrobe the corner of a truck etc. The dra(back of this techni2ue is that it re2uires the a&ailability of a sufficiently large corner that blocks the &ie( of anything around the other side of it. /inding in the 7and This techni2ue is in essence only applicable to finding ob%ects that can fit in or be held by the hand. To perform this techni2ue concentrate on the idea that the ob%ect is already in hand. 1t that moment the practitioner must not look at it. 4oon after beginning to concentrate on this idea the practitioner (ill at first feel a slight sensation of the ob%ect lying in his hand follo(ed by a full sensation and appearance of the desired ob%ect. /inding 0y #rans'utation This techni2ue distorts the phase space (hile not completely disengaging a perception of the space. The practitioner must gi&e strong attention to a thought that a re2uired ob%ect is going to appear
in a desired location. There must be sufficient confidence that the practitionerDs desires (ill be reali=ed. 1t this moment the process of metamorphosis (ill begin- space (ill distort and dim and the re2uired ob%ect (ill begin to manifest itself. 1fter this brightness and focus (ill be restored (ith necessary alterations made present in the phase space. This techni2ue is relati&ely difficult to perform in comparison to others and therefore it is better to use it only after a high le&el of e#perience has been reached because it is difficult to remain in the phase during any metamorphic process. 1s is e&ident in the name of this techni2ue it can be used to find ob%ects and also create ne( ob%ects from found ob%ects. #8PIC3; MIS#3=ES (I#7 #93NS;OC3#ION 3ND /INDING OBGEC#S 1pplying translocation and ob%ect finding techni2ues (ithout the precondition of a steady phase. )nsufficient concentration on a desire to tra&el to a location or to find an ob%ect. 7oubting that results (ill be achie&ed instead of ha&ing complete confidence. Passi&e performance of the techni2ues instead of a strong desire and high le&el of aggression. Forgetting to repeat translocation or ob%ect finding techni2ues (hen the techni2ue did not (ork or (orked incorrectly during the first attempt. 3etting distracted by e#traneous thoughts during the lengthy process of teleporting (ith eyes shut. Total concentration is re2uired at all times. 1pplying the techni2ue of teleportation (ith eyes open (ithout ade2uate e#perience. Failing to immediately translocate (hen using the closed eyes techni2ueJ this may induce flying a la the teleportation techni2ue.
3lossing o&er minute details or only obser&ing the broad features of a remote ob%ect (hile applying translocation by concentration. 1 delayed desire to mo&e (hile translocating during separation. 1n instantaneous desire to immediately mo&e is necessary. Forgetting to first shut a door completely (hen using translocation through a doorJ other(ise there (ill be contact (ith (hat is already behind it. Using a translocation techni2ue to go through a (all (ithout kno(ing ho( to pass through solid ob%ects. Paying too much attention to the process of translocation through a (allJ this leads to being trapped in the (all. Forgetting to shut the eyes (hile translocating di&ing headfirst. The eyes should remain closed until after the techni2ue is complete. )nsufficient internal association (ith an animate ob%ect (hile finding it by calling its name. Trying to find an ob%ect &ia interrogation instead of passi&ely communicating (ith li&ing ob%ects of the phase. Using distant corners (hen applying the techni2ue of finding an ob%ect around the corner. ,hoose nearby corners to a&oid (asting precious tra&el time. 1pplying transmutation techni2ues (ithout possessing sufficient e#perience in managing F!maintaining$G the phase space.
:. .hat is the sole limitation on the possibilities offered by translocation and finding ob%ects/ ;. 6o( may one translocate across &ery short distances/ <. .hen the flight techni2ue by %umping out of a (indo( be attempted/ >. .hat should be done if translocation and ob%ect finding techni2ues do not yield the re2uired result/ ?. )s it possible to find a person from real life using the techni2ue of finding ob%ects/ @. 7oes the stability of space decrease in a deep phase/ 1A. .hat are the fundamental components of space and ob%ect stability/ 11. 6o( large is the role of auditory perception in the stability of space/ 1+. .hat is most important (hile using a teleportation techni2ue/ 18. .hat does speed of mo&ement depend on during teleportation/ 1:. 4hould a no&ice apply the techni2ue of teleportation (ith open eyes/ 1;. .hat techni2ue might the translocation (ith closed eyes techni2ue turn into/ 1<. 4hould large or small details be scrutini=ed (hile translocating by concentration on remote ob%ects/ 1>. )s the techni2ue of translocation during separation applied after separation or (hile beginning to separate/ 1?. .hen applying the techni2ue of translocation through a dooris it better if the door is open or closed/ 1@. .hy might translocation by passing through a (all fail/ +A. .hen using translocation by di&ing is it important to be in a place (here there is something to stand on/ +1. .hile applying the techni2ue of rotation should rotation be imagined or real/ ++. )s it possible to use a translocation techni2ue to attempt finding ob%ects/ +8. .hen using the techni2ue of calling by name (hat should be done if the name of a desired person in the phase is unkno(n/
+:. .hile looking for an ob%ect using the method of in2uiry is it important to specify that the ob%ect needs to be found !2uickly$/ +;. 6o( far back must a turn occur (hen the techni2ue of finding ob%ects by turning is being used/ +<. .ould the corner of a fence be suitable for applying the techni2ue of finding ob%ects around the corner/ +>. )s it necessary to shut the eyes (hile using the transmutation techni2ue/ #as!s 1. 7edicate the ne#t three phases to e#periments (ith translocation techni2ues using all of them and tra&elling (here&er you (ant. +. 1fter e#periencing three phases dedicated to translocation select the techni2ues that (ork best for you. 8. 7uring the ne#t phase tra&el to the Eiffel To(er to the Moon and to the homes of some of your relati&es. :. 7edicate the ne#t three phases to e#periments (ith the full range of techni2ues for finding ob%ects including translocation techni2ues. ;. 1fter three phases dedicated to finding ob%ects select the techni2ues that you are most comfortable (ith. <. )n the ne#t phase that you e#perience find your mother and then at the same location locate this te#tbook a red globe and a green rose.
the practitioner adheres to a mystical or pragmatic (orld&ie( a full range of access is inherently possible. Possible applications of the phenomenon certainly e#ceed the scope of descriptions related through this chapter. )t is possible that other applications simply ha&e not been pro&en yet and so far the correct methods of practicing these unkno(n. Only the practitioner may determine the limits of possibility (ithin the phase. Of course common sense should be applied or it (ould be logically and psychologically difficult to disengage misconceptions. The goal of this chapter is to provide a real Bthough $ini$al) foundation that is fir$ and unyielding, &hatever the circu$stance( -f the practitioner follo&s a strict approach to practice, it &ill "e $uch $ore difficult to "eco$e lost during further practical and theoretical studies( 3PP;IC3#IONS B3SED ON SIM4;3#ION Many (onder about the nature of the phase state in relation to the brain i.e. (hether or not the phase is all in oneDs head. 5ut in the conte#t of applying the phase this is not a &alid concern. Perception of the entire physical en&ironment is performed through sensory organs. )n the phase perception is the same sometimes e&en more realistic. .hether e&erything described in this chapter occurs in reality or is merely simulated makes no difference in terms of the encountered sensations. #ra>elling %round the &orld' )t is possible to reach any point of the planet and it is particularly interesting to re&isit places (here the practitioner once li&ed or &isited and &isit places that the practitioner has a strong desire to &isit. E&ery sight and beauty of the Earth become accessible be it the Eiffel To(er or an island in Oceania the Pyramids of Egypt or 1ngel Falls. Through Outer Space- 1lthough humankind is not going to reach Mars any time soon any practitioner may stand on its surface and e#perience its uni2ue landscape through the use of translocation
in the phase. There is nothing more ama=ing than obser&ing gala#ies and nebulae planets and stars from the &antage pint of &ast space. Of all phase applications a&ailable this one pro&ides practitioners (ith the most striking aesthetic e#periences. To different places in ti$e' This makes it possible to &isit a childhood to see (hat a person (ill look like in the futureJ a pregnant (oman in the phase may see (hat her child (ill look like. Tra&el far back in time and (itness the construction of the Pyramids at 3i=a see Paris in the 1>th century (ander among the dinosaurs of the Curassic period. Through different &orlds' Tra&el a (orld that has been described in literature or %ust in&ented by the practitioner de&eloped in the imagination. These could be e#traterrestrial ci&ili=ations parallel (orlds or uni&erses from fairy tales and films. 1ny destination is nearby. En ounters 5ith relatives' 4ince relati&es cannot al(ays see each other there is the remarkable possibility to meet each other and talk in the phase. Of course this does not entail mutual presence. )t is enough for one person to possess the re2uired desire " the second person may ne&er e&en kno(. Reali=ing the desire to contact a close relati&e and e#change information is a treasure. 5ith ac4uaintances' ,ircumstances often pre&ent seeing people (ho are important. This is an opportunity to reali=e a desire and finally meet that certain person again. 5ith the dead' Regardless of the nature of the phase phenomenon nothing else yields the possibility to see talk to and embrace a deceased lo&ed one. These are &i&id personal e#periences accessible to e&eryone and achie&ing these encounters does not re2uire ma%or difficulty. ,ourage is the only necessity. From a techni2ue"related point of &ie( a stable phase and application of the finding ob%ects techni2ue sets the stage for (hat at first may seem impossible. )t should be noted that (hen a deceased person is encountered in the phase the distortions caused by the ob%ect finding
techni2ue may lead to some &ery undesirable occurrences. )f you are interested in this sub%ect you should carefully study the guidebook :ontact &ith the 3eceased Fauthor- Michael RadugaG. 5ith cele"rities' Through the use of ob%ect finding techni2ues a practitioner has the opportunity to meet any famous person. This could be a historical persona a contemporary politician or an artist. )n the phase state they are all accessible for any type of interaction. For e#ample a practitioner could meet Culius ,aesar Cesus ,hrist 'apoleon ,hurchill 4talin 6itler El&is Presley Marilyn Monroe and a great many others. 9ealiHing Desires E&eryone has dreams. Regardless of (hether they e&er come true in reality they may at least en%oy be reali=ed in the phase. 4ome dream of a &isit to 0as 9egas some to dri&e a Ferrari some &isit Outer 4pace others (ould like to bathe in a pile of money and some desire se#ual e#periences. 1ll of these may finally be e#perienced in the phase. 3lternati>e to the ?irtual (orld )n the phase young men may participate in game battles as if the battles are real. 1 practitioner can &isit unusual (orlds and places (hile en%oying completely realistic sensations feel a (eapon in his hands and e&en the smell of gunpo(der. )f desired e&en the sensation of battle (ounds may be e#perienced. 3aming possibilities in the phase are not limited by the po(er of a microprocessor but the e#tent of a practitionerDs imagination. Creati>e De>elop'ent :reating &or+s of art' Using the methods of ob%ect finding or translocation an artistic practitioner can purposefully seek an ob%ect in the phase that may be composed in real life. )f necessary it is possible to easily return to study an ob%ect in the phase. For e#ample a painter may find a stunning landscape and puts it to can&as in the
real (orld (hile periodically returning to the same landscape in the phase. Fie&ing future co$pleted &or+s of art' )f an artist is in the process of reali=ing an idea then a preliminarily look at the end result of a design may be seen in the phase. 1 painter can e#amine a painting in ad&anceJ a sculptor may see a completed sculpture and an architect (ill be able to (ander through a house that is still in the early stages of design. 1ny creati&e (ork can be simulated in the phase. % source of inspiration and fantasy' The phase practice imparts ideas and desires that positi&ely affect creati&e endea&ors. Furthermore the reali=ation of desires and tra&els through unusual spaces e&oke great emotions (hich pro&ide e#cellent inspiration. 3PP;IC3#IONS B3SED ON CON#3C# (I#7 #7E S4BCONSCIO4S MIND 1ssume that the phase state is %ust an e#ceptionally unusual state of brain and that perception (ithin it is no more than an unusually realistic play of its functions. 1ssume that a practitioner in the phase decides to tra&el to a forest. To do so the translocation (ith closed eyes techni2ue is used and as a result a forest appears. .hat happens if the &ision contains &ery detailed kno(ledge of forests (hat forests consist of and (here forests originate/ The brain creates a hyper"realistic space superior to that of e&eryday reality consisting of millions of blades of grass lea&es hundreds of trees and a multitude of sounds. Each blade of grass has depth and build not %ust a point. Each leaf also consists of component parts. 1 uni2ue natural pattern makes up the bark of each tree. 4uddenly a (ind begins to blo( through the forest and millions of lea&es and blades of grass follo(ing a mathematical model of the propagation of air masses begin oscillating in a (a&elike fashion. Thus a certain resource inside us is capable in mere seconds not only of creating millions of details in the desired scene but also to control each of those details indi&iduallyH
E&en if the phase is %ust a state of mind this does not mean that there are no sources of information (ithin it. The mind possesses great computing ability and is e2uipped to imagine the full e#tent of the impossible. 'o computer ho(e&er po(erful is capable of similar feats. 1 practitioner is able to someho( tap into ama=ing resources (hile in the phase. )t only remains to learn e#actly ho( to achie&e mastery. )t is possible that the phase space is go&erned by the subconscious mind. This means that the practitioner is able to contact the subconscious (hile in the phase state. 7uring e&eryday life the subconscious mind sends information based on calculations determined by enormous capabilities. 6o(e&er humans neither hear nor percei&e these signals because people are accustomed to recei&ing information linguistically. The subconscious mind hardly operates (ithin the limitations of language. ,ommunication (ith the subconscious mind on a conscious le&el is only possible (ithin the phase. )f all phase ob%ects are created and controlled by the subconscious mind then it is possible to use them as translators. For e#ample (hen talking to a person in the phase normal (ords are heard (hile the ob%ect and communicated information is controlled by the subconscious mind. 1n e#planation of ho( information is obtained in the phase can hardly be une2ui&ocally pro&en. Perhaps there are other undisco&ered resources. 5ut that is not so important. The most important thing is definitely kno(n- ho( to obtain information in the phase. The algorithm for obtaining information from the phase is not comple#. 1fter entering the phase only the techni2ues for obtaining information and the methods of &erifying it need to be learned to increase in kno(ledge gleaned from the phase.
5ased on the pragmatic e#planation of the nature of the phase as an unusual state of brain controlled by the subconscious it may be assumed that the amount of information obtained in the phase is limited. )f the phase e#ists (ithin the confines of the brain then the brain can only operate on data that has been recei&ed by the brain o&er the course of its e#istence. )ndeed it appears that e&erything percei&ed through the sensory organs is remembered and correlated (ith other dataJ this obser&ation concern conscious and unconscious perception. )f any e&ent is actually a conse2uence of other e&ents (hich (ere in turn also conse2uences of pre&ious happenings then nothing occurs by chance. The initial data is kno(n " then it is possible to calculate (hat is implied by it. 1s a result if e&erything is based solely on the resource of the subconscious mind then information may be obtained about e&erything that is related to an indi&idual life- the practitionerDs e#periences and the e#periences of those (ith (hom the practitioner e#periences life. 0essons are learned from the future and past and the future and past of others. 1ll in all in order to approach kno(ing the (hole of the information a&ailable in the phase personal kno(ledge capacity (ould need to increase by 1AA or e&en 1 AAA times.
The only information that is not a&ailable in the phase is that about (hich the subconscious mind does not ha&e any preliminary information. For e#ample (here to purchase a (inning lottery ticket that (ill (in millions of dollars cannot be learned since there is no data that could support the necessary calculation. The subconscious mind (ill also not be able to sho( the practitioner (hat a random street in a small to(n on the other end of the Earth looks like. 1 practitioner should not try guessing (hat information the subconscious mind has to offer and (hat it doesnDt because mistakes are easily made. For e#ample if a practitioner has ne&er been to Paris and ne&er seen the Eiffel To(er it might be assumed that the practitionerDs subconscious mind kno(s nothing about it either although through o&er the course of life the mind has already recei&ed an enormous 2uantity of information from pictures photographs stories &ideos books and so forth. There are three basic techni2ues for obtaining information in the phase. Each of them has its ad&antages and disad&antages that must be studied and learned before use. 3ni'ate O01e ts #e hni$ueD To perform this method of obtaining information the practitioner in a full deep phase must locate a person by techni2ues for finding ob%ects and procure the necessary information from that person through the use of simple 2uestions. )f the re2uired information is linked to a certain person then that person should be located in the phase. )f the information is not related to anyone in particular then it is possible to create a uni&ersal information source (hich must be associated (ith (isdom and kno(ledge. For e#ample this could be a (ise recluse a (ell"kno(n philosopher or a guru. The ad&antage of this techni2ue is that it is easy to pose additional 2uestions and it is also easier to &erify (hate&er information is obtained. 1 dra(back of this techni2ue is that for many it is difficult to communicate (ith li&ing ob%ects in the phase because of ob%ectsD unresponsi&eness or a practitionerDs problems (ith maintaining the phase (hile talking (ith ob%ects.
Inani'ate O01e ts #e hni$ueD Use techni2ues for finding ob%ects in order to locate information from sources like inscriptions books or ne(spapers. .hile trying to locate the source of information remember to concentrate of a belief that (hat is found (ill ha&e the desired information. 4ource types are not limited to paper mediaJ e&en radios or tele&isions may be (atched or listened to and computer search engines and file systems also may produce results. 1 huge dra(back of this techni2ue is that considerable complications arise if an additional or a follo("up 2uestion emerges (hich may cause the practitioner to ha&e to stop and repeat the searching process. The upside to this techni2ue is that if a practitioner has problems communicating (ith animate ob%ects this techni2ue can temporarily ser&e as a reasonable alternati&e. Episode #e hni$ueD )n order to recei&e information using this method imagine an e&ent or series of e&ents that (ill communicate the desired information. Then mo&e to the area (here predetermined e&ents are e#pected to take place by using translocation techni2ues. 1fter arri&ing at the destination use &isual obser&ation to understand (hat is taking place and the information that the e&ents are communicating. The episode techni2ue is suitable only for cases (here information can be obtained by obser&ation. 0o& to verify the infor$ationG The techni2ues for recei&ing information in the phase are not comple# in and pro&e successful after %ust a fe( attempts. 6o(e&er as (as already mentioned earlier the properties of phase spaces that do not fall under the category of &i&id perception are not particularly stable " not only in terms of appearance but also in terms of their properties. ,orrectness of information also depends on the ob%ects themsel&es. The problem rests in that the practitioner may not be able to properly control the ob%ect in 2uestion and may recei&e false information.
Interesting fact! The phase space is not everyday reality@ therefore, it should not "e treated &ith the nor$al "elief that every o"servation should "e regarded as fact( E&en (hen a practitioner has learned to find animate and inanimate ob%ects (ith an absence of doubt there is still no guarantee that the recei&ed information is al(ays accurate. 1 fe( techni2ue" related tricks are able to test an ob%ectDs ability to speak the truth. For e#ample an ob%ect can talk about something (ith absolute confidence but that does not mean that (hat it communicates is all true. )f doubt is e#perienced (hile finding the ob%ect then doubt may ha&e an effect on (hat the ob%ect says. This is (hy doubt must be a&oided at all costs " although beginners are bound to initially ha&e problems (ith this. To determine (hether an ob%ect is able to gi&e accurate information a control 4uestion should be askedJ a 2uestion that the subconscious mind cannot kno( the ans(er to. For e#ample a practitioner might ask a found ob%ect- !.here can ) buy the (inning lottery ticket for the Mega 5all %ackpot/$ )f the ob%ect starts ans(ering such 2uestions seriously going into great detail then the ob%ect should be created ane( since its properties allo( the possibility that it (ill lie. 1 proper ob%ect (ill remain silent or say that it does not kno( the ans(er to the control 2uestion. 1fter accurate information is obtained through the use of a control 2uestion it must be confirmed. This is done by means of a clarifying 4uestion. The practitioner needs to ask the ob%ect (here the information came from to find out the details that offer proof of the informationDs authenticity in the real (orld. The ob%ect may also be asked the same 2uestions more than once pro&ided they are re(orded. The ans(ers to re(orded 2uestions must be identical. Remember the more important the nature of the information and the more serious action it implies the more effort needs to be in&ested in &erifying it in the real (orld since a certain percentage of the information is bound to be incorrect despite correct performance of information"related techni2ues.
3PP;IC3#ION B3SED ON IN/;4ENCING P78SIO;OG8 There are three main elements that (ith the help of the phase may influence the physiology in &ery beneficial (ays. First it is possible to contact the subconscious mind to learn ho( to influence physiology. 4econd the brain reacts more strongly to sensations than to real e&ents. For e#ample if running (hile in the phase the physical processes of the body (ould be consistent (ith the processes occurring in the body of a person running in realityrespiration accelerates blood pressure increases the heartbeat 2uickens and e&en blood flo( to the feet becomes greater. Third (hile the practitioner e#periences profound changes of consciousness in the phase this is (hen all direct and indirect forms of autosuggestion are most effecti&e. 'ot all influences on physiology are 1AAK effecti&e. 6o(e&er e&en (ithout a guaranteed rate of success the effort to influence physiology is (orthy of attention because ama=ing results can be obtained. 1l(ays remember that achie&ing a good result may re2uire repeated influence from the phase. E&en in the physical (orld medications re2uire repeated ingestion. )f the goal is to cure a disease do not rely solely on the phase. 4ick persons must use the phase alongside treatment from physicians. The more serious the illness the more strongly this rule applies. O0taining Infor'ation The diagnosis of health problems may be performed (ith the same techni2ues used for obtaining information. )t is also possible to learn methods to cure health problems if such methods e#ist. 5oth of these possibilities apply to third parties being helped by efforts in the phase. )nformation gathering is the only pro&en (ay to influence the physiology of other people by using the phase. For e#ample it is possible to find a (ell"kno(n healer in the phase and ask about personal health problems or the problems of a friend or family
member. 1 clarified ans(er may be used in the assistance of traditional medical treatment. 3ttention fro' Do tors Find a doctor in the phase by using the techni2ue of finding ob%ects and ask the doctor to take e#amine or treat a kno(n illness or other health problem. For e#ample in case of abdominal pains the doctor may palpate the belly apply pressure to &arious points and perform a special massage. 1ny actions are possible including an operation. 1fter lea&ing the phase the practitioner (ill feel a positi&e result. #a!ing 'edi ines The placebo effect is much stronger in the phase than in reality since all actions occur in a highly modified state of consciousness and are percei&ed directly. Ob%ect locating techni2ues may be used to find medications used to treat e#isting problems. )t is also possible to create self"made substances to produce the desirable effect. For e#ample in case of an acute headache in reality a practitioner may take a painkiller (hile in the phase and its effect (ill be partially felt in the (akeful state. Dire t Effe t 1n illness or problem may be directly affected by actions in the phase. For e#ample a sore throat may be (armed by en&isioning a burning sensation in the throat or by mo&ing to a hot location like a sauna. )f a practitioner (ould like to increase physical fle#ibility then stretching in the phase (ill cause the body to ad%ust to the none#istent action by rela#ing and tensing the corresponding tendons and muscles. Progra''ing This is nothing more than normal autosuggestion or auto"training in the phase (hich is more potent in the phase than reality. 1 practitioner should repeat a desired goal silently or aloud and if possible should imagine e#periencing the desired result. For
e#ample if the aim is to get rid of depression a practitioner should attempt to recreate a happy mood in the phase e#periencing it to the fullest e#tent possible. 4imultaneously silent repetition of a goal (ith complete understanding and e#pectation that e&erything (ill be alright that e&erything is (onderful (ill undoubtedly produce the desired effect. 4seful e*perien es E&erything (ith useful properties in reality should be e#perienced as useful in the phase since the body (ill react in practically the same manner. Useful e#periences may include e#ercising going to the gym ha&ing a massage taking mud or salt baths and e#periencing pleasant emotions. Psy hology Practicing phase"related techni2ues fa&orably affects the psychology because it offers ne( opportunities and e&okes ne( emotions. 6o(e&er there are specific applications of the phase that produce differing psychological effects. For e#ample it is possible to use the phase space as a bridge for dealing (ith phobias by facilitating a setting (here a practitioner may confront and deal (ith certain fears. 9arious comple#es may be defeated in a similar manner. The use of a (ell"kno(n techni2ue called re"&isiting FrecapitulationG (here a person re"e#periences ad&erse e&ents (hile trying to relate to them in a ne( (ay has been used successfully in the phase. #raining 1ny motor skills can be sharpened by using it in reality and in the phase because the algorithm of rapid physical action is generated at the le&el of interaction bet(een areas of the brain that correspond to muscle action. )n the phase (restlers may practice thro(s karate fighters may practice punches and kicks and gymnasts may practice acrobatics. 6a&ing enough time to practice these actions in the phase is another matter.
4NP9O?EN E//EC#S People often approach the practice of &arious phase states (ith deep"rooted misconceptions about (hat can actually be achie&ed through practice. E&erything listed in this section refers to these misconceptions. )t has not been pro&en that any of these things is impossibleJ ho(e&er actions should be based on pro&en and &erified methods in order to a&oid making mistakes and (asting time. Ehysical e#it' )f the first e#perience (ith the phase phenomenon happens by accident it is almost impossible not to interpret it as a real separation of the soul from the body I a physical e#it. This is ho( the initial phase e#perience really feels. .ith e#perience it becomes easily noticeable that certain things in reality do not match things in the phase like the placement of ob%ects or furniture in the house (here a phase is first encountered. 'o actual physical e#it from the body has e&er been pro&en through scientific e#perimentation and obser&ation. For e#ample in the phase it is not possible to fly around to locations in physical (orld although it may seem so the locations that are e#perienced are produced (ithin the mind. 'or is it possible to pinch someone in the phase and then to find a bruise on the person (hile in reality. Other &orlds' The phase space is similar to the physical (orld and a practitioner may be inclined to think that the soul has left the body. 4ometimes the phase takes on an absolutely unnatural form. 1s a result the practitioner may decide that a parallel (orld has been entered- the (orld beyond the astral plane mental space or the ether. 1lthough tra&el in the phase can lead to many places this does not mean that the phase allo(s tra&el through or use of actual alternate (orlds. The practitioner should be reasonable. 3evelop$ent of super-a"ilities' )t is partially correct to consider the practice of the phase as an e#trasensory ability since it is an actual de&elopment of e#tremely unusual skills that ha&e al(ays been considered mystical. Times ha&e changed and the phase should hardly be shuttled off to the esoteric obscure corners of kno(ledge. There e#ists an unpro&en theory that the practice of the phase can impart unusual abilities. .hile literature is full of references to this
effect these abilities ha&e not yet been pro&en by anyone. The same applies to intentionally de&eloping unusual abilities in the phase. Pes these may be trained (hile in the phase but this does not mean that training in the phase (ill yield the same results in the real (orld. Practice should not be for the sake of achie&ing super"abilities since there are many pro&en applications that do translate to reality in &aluable (ays. 5e realistic. 4SE O/ #7E P73SE B8 #7E DIS3B;ED .hile practicing the phase may still be &ie(ed by the ma%ority as entertainment or an element of self"de&elopment at best phase practice takes on a (hole ne( meaning for the physically disabled. For them the phase may be the only place (here the handicaps of reality dissol&e and disabled practitioners e#perience a range of possibility greater than the life e#perienced in reality. 1 blind person (ill see again in the phase e&en more clearly than seeing people do in reality. 4omeone (ho is paraly=ed (ill be able (alk run and also fly. 1 deaf person (ill hear the murmur of streams and the chirping of birds. For the disabled the phase practice is a chance to disco&er ne( incomparable (orlds free of physical limitation. 'aturally there are some nuances that must be understood. First for e#ample if a person (as born blind then there is the 2uestion as to (hether or not they (ould be able to see in the phase the same (ay ordinary people see. 6o(e&er this issue has not been fully studied and blind people should simply carry out their o(n independent research. 4econd some types of disabilities can negati&ely affect the practice of the phase states. For e#ample people (ho ha&e gone blind ha&e greater difficultly catching the intermediate state bet(een sleep and (akefulness since unlike seeing people they may a(aken (ithout opening their eyes to the perception of sound. Third a purely psychological disability plays an enormous negati&e role. Psychologically disabled people ha&e a (hole range of specific beliefs and attitudes that may present an obstacle for them.
.hate&er the indi&idual issues this particular area of phase applications re2uires additional study. )t deser&es significant attention because it is a &alid tool for the rehabilitation of the disabled. )t is (orkable uni2ue and e#tremely surprising in terms of the e#periences that it offers. #8PIC3; MIS#3=ES (7EN 4SING 3PP;IC3#IONS 1ttempting an applied use of the phase (ithout reaching a good depth. 7eepening must al(ays be performed before applications are attempted. 5eing so in&ol&ed in phase applications that !maintaining$ techni2ues are forgotten. Forgetting to consider ho( to breathe (hen tra&eling through Outer 4pace or under(ater (hich may lead to asphy#iation. ,oncentrating on a certain ob%ect (hile tra&eling through time instead of concentrating on time tra&el (hich should be the focus since it is the point of performing the applications. Forgetting techni2ues for !maintaining$ (hen animate ob%ects are encountered (hen these techni2ues must al(ays be kept in mind. 1n inability to o&ercome fear during contact (ith deceased people. This fear must be o&ercome once and it (ill ne&er resurface again. 0imiting desires (hile practicing the phase. There is no limit to desire (ithin the phase. 0imiting the performance of certain actions although there are no customary norms of beha&ior in the phase unless the practitioner decides upon specific limits. .hile looking for information in the phase attempting to obtain kno(ledge (hich clearly e#ceeds the scope of the subconscious mind. 1pplying the techni2ue of obtaining information from animate ob%ects (ithout kno(ing ho( to communicate (ith them.
Forgetting to check the ability of an ob%ect to con&ey &alid kno(ledge. The probability of bad information is much higher if it is not &erified. Failing to &erify information in the phase before using it in reality. Forgetting to &erify serious information obtained in the phase in reality before using it. 9erification absolutely must be performed to a&oid using bad information in reality. 1 single attempt to influence the physiology through the phase. )n the ma%ority of cases results are gained through repeated effort. 1n attempt to cure some disease only using the phase (hereas it is compulsory to seek medical ad&ice. )nitially belie&ing that the phase is the e#it of the soul from the body (hile this is easily refuted in practice. ,oncentrating only on unpro&en applications despite all the e&idence out there that this is most likely a (aste of time.
@. .here can one reali=e any cherished dream/ 1A. ,an a practitioner appear in the computer game 3oo$/ 11. ,an a musician use the phase for creati&e purposes/ 1+. 7oes the practicing the phase influence a personDs imagination/ 18. .hat most probably go&erns the phase space/ 1:. .hat kind of information is obtainable in the phase/ 1;. .hile in the phase is it possible to find out (here the lost key to an apartment is located/ 1<. .hat kind of people can disco&er (here treasure is hidden in the phase/ 1>. 4hould any information obtained in the phase be construed as accurate/ 1?. 4hould information obtained in the phase be &erified after (aking up e&en if itDs already &erified in the phase/ 1@. 4hould obtaining information occur before deepening has been performed/ +A. To obtain information (hile using the animate ob%ects techni2ue (ho should be talked to if the goal is it to find out the thoughts of a boss at (ork/ +1. 6o( might information from an animate ob%ect be obtained/ ++. ,an an inscription on a (all be used as an inanimate source of information/ +8. )s it possible to use the episode techni2ue to learn (here one has lost the key to oneDs apartment/ +:. 4hould a doctor be consulted before trying to cure a disease through phase practice/ +;. 1re results from influencing physiology in the phase al(ays 1AAK guaranteed/ +<. .hat phase techni2ues might be used to influence the bodies of other people/ +>. )s it possible to obtain information that can be used to influence the body and its functions/ +?. )s it possible to take a (ell"kno(n painkiller in the phase and feel its effects on e#it/ +@. )s it possible to use autosuggestion in the phase/
8A. ,an athletes use the phase to de&elop their skills/ 81. )s it realistic to e#pect to the soul (ill e#it the body (hile practicing the phase/ 8+. )s it possible to enter a parallel uni&erse through the phase/ 88. 4hould a practitioner hope to de&elop super"abilities in the phase/ #as!s 1. 9isit the Pyramids of 3i=a in the phase. Meet your fa&orite singer and tra&el to your dream house. +. .hile in the phase find a (ise person (ho is an authority on matters of the phase and learn from them (hat entrance techni2ues (ill best suit your practice. 8. Try to percei&e heat throughout the entire body by translocation to a sauna or through auto"suggestion. :. 0earn to mo&e ob%ects by simply staring at them in the phase and appreciate the e#tent to (hich this skill is reflected in reality.
INDEPENDEN# 3N3;8SIS )f a practitioner is only interested in ha&ing phase e#periences then the simple treatment of this guidebook and other materials may suffice. 6o(e&er if a practitioner (ants to achie&e the best results ample focus must be gi&en to indi&idual thought and formation of opinion based on personal analysis. Until all 2uestions are ans(ered through a search for ans(ers in &arious sources of information no real progress should be e#pected. Many things cannot be described or e#plained. The resolution of many issues (ill al(ays remain up to indi&idual %udgment and understanding. Finding all of the ans(ers is impossible. Moreo&er trying to possess all of the ans(ers is a serious inhibitor to real progress because the practitioner (ould ha&e to digress into dubious literature and con&ersation aside from real formati&e practice. The ad&ice and e#periences of others may lead to error. )n no case should there be any authorities or unachie&able ideals. 1 logical e&en skeptical approach should be taken during research and practice. The goal of this guidebook is to pro&ide the reader (ith linear factual information sufficient for the de&elopment of independent analysis. Each time a practitioner encounters some incomprehensible phenomenon or problem (hen performing phase techni2ues an independent analysis of the phenomenon should be formed before looking else(here for the cause. )f a seeker looks for ans(ers outside of personal reasoning there is a high risk of assimilating and acting upon a fallacy. Many practitioners are not (illing to analy=e personal successes and failures and instead search all sorts of books (hich often contradict one another and using a hodge"podge of e#traneous un&erified information can only lead one to further and 2uite infectious fallacy. 3PP9O3C7 #O ;I#E93#49E
0iterature of e&ery sort has al(ays been the main &ehicle for disseminating information about the phase state. The phase phenomenon is referred to by other terms- astral pro%ection out"of" body tra&el or lucid dreaming. )n addition to disseminating information many books are often &ehicles for disseminating fallacies. This is easy to recogni=e (hen researching se&eral such books and comparing described e&ents and theories. The information is more often than not contradictory and based on opinions that ha&e ne&er been &erified by anyone including the authors. The result is a mass of speculation that has no bearing on reality nearly al(ays accompanied by a false certainty about the sub%ect matter. 6o(e&er unlike the real (orld the phase is not a place (here one can belie&e oneDs eyes or feelings. The phasesD appearance and 2ualities depend &ery much on the person e#periencing it. For e#ample if a practitioner belie&es upon entering the phase the body (ill be lying nearby on the bed then it (ill al(ays be there. )f a practitioner belie&es that the percei&ed body should al(ays be tethered to the physical body then in the practitioner (ill al(ays see and e&en feel a tether in the phase. This is a simple case of e#pectations becoming reality. 4imilarly someone (ho has entered the phase by accident and thinks that the time of death has arri&ed may see angels and a tunnel (ith a light at the end. )f someone is e#tremely religious there may be a perception that something holy e&en 3od has appeared. )f entry to the phase is construed as a result of being abducted by aliens then that is e#actly (hat (ill happen. This (ould all be 2uite funny if it (ere not actually encountered. .hen it occurs the only thing left to do is to belie&e. To belie&e to tell others about it and (rite books about it... There are authors (ho impart no illusions but it is often difficult for a no&ice to separate the truth from illusion or open fabrication (hich is (hy a skeptical approach to the contents of any book is (arranted. The only truth con&eyed in any book is that (hich has been &erified by personal e#perience. The rest should simply be noted and possibly taken into consideration.
)n conclusion books should be studied to disco&er techni2ue" related information that allo(s a practitioner to enter the phase and control the e#perience. This is the only point of intersection among all beliefs and theories. P93C#ICE EN?I9ONMEN# 4ince techni2ues used to enter the phase are associated (ith a specific type of mental operation it is necessary to create comfortable conditions so that e#ternal distracters are kept to a minimum. 1 room should neither be too cold or too hot nor too bright. Performing techni2ues at a comfortable temperature in a darkened room or (hile (earing a sleeping mask are (ays to promote unhindered practice. )nterfering noises are often also ma%or distracters and isolation from such noises is necessary to successful practice. )t is often sufficient to turn off the phone and close doors and (indo(s. )f this does not help or if it is e#tremely loud outside the (indo( one can use standard earmuffs. )t is also helpful to gi&e ad&ance notice to people so that they are not alarmed. )t is also preferable that no one is in the bed (ith the practitioner. Most often domestic animals interfere (ith the performance of techni2ues (hich is (hy they should be fed beforehand and kept out of the room (here direct or indirect techni2ues are practiced. #3;=ING (I#7 ;I=E-MINDED PEOP;E 3reat benefit is deri&ed by discussing personal e#periences (ith other practitioners. This leads to an e#change of information ne( kno(ledge and mutual help concerning certain problems and issues. The greatest effect comes through communication in person and not solely through mail forums and blogs. Meeting face"to"face (ith like"minded people promotes camaraderie and a useful kno(ledgebase to consider during indi&idual practice.
7ue to the fact that kno(ledge of the phenomenon is underde&eloped difficulties may arise in finding someone to talk to. This can be sol&ed by personally sharing phase e#periences (ith friends and family members regardless of (hether they are fello( practitioners. )t is e&en better to pass on training literature like this guidebook. The (ebsite also has a discussion forum de&oted to the phase making it possible to obtain and e#change a large amount of information. The site also has the contact information for the coordinators of Phase Practitioner ,lubs all around the (orld (hich is a non"commercial association of enthusiasts (ho meet to e#change and discuss e#periences. #7E 9IG7# (38 #O =EEP 3 GO49N3; Beeping a %ournal can be of much help (hile learning and practicing the phase. .hen properly kept a %ournal can help a practitioner to de&elop an analysis that (ill increase the 2uality of phase e#periences. 5y and large keeping a %ournal helps to iron out a sporadic practice turning it into a structured discipline that can be mastered. 1n effecti&e diary should contain a massi&e amount of indicators that allo( a statistical study to unco&er patterns. )t is essential that each entry include the date time of day or night a detailed account of entries into the phase and phase e#periences. 7escriptions of mistakes and a plan of action for the ne#t phase should also be recorded. 7uring the no&ice stages of practice e&en noting unsuccessful entry attempts is beneficial. 0ater on only successful phase e#periences may be recorded. 6ere is an e#ample of a proper %ournal entryDataC 2#perience /o( 12 January 6th, 2 H 2'88 EM
E*perien eC - &o+e up early in the $orning( %fter e#ercising, - too+ a sho&er and ate "rea+fast( - &atched TF and read "oo+s until lunch( - laid do&n for a nap at 1 EM, right after lunch( - felt li+e perfor$ing indirect techni4ues, and affir$ed this intention( &o+e up the first ti$e to $ove$ent, "ut after trying to e$ploy forced falling asleep Bin order to negate the effects of the $ove$ent), - fell asleep( - &o+e up the second ti$e &ithout $ove$ent and tried to roll out( This didn.t &or+ and - tried levitating and getting up( %fter that, - $oved on to phanto$ &iggling( Move$ent occurred in $y right hand( %fter doing this for several seconds, - decided to try listening in( Sounds started, "ut - &as una"le to $a+e the$ louder( 0o&ever, i$ages appeared "efore $y eyes and - started to vie& the$( %fter they "eca$e realistic, - decided to try rolling out and it &or+ed &ithout a hitch( My vision &as di$, as if through a veil( But then, the rest of the sensations - felt reached the verge of reality( This is &hen - &ent to the &indo&( For so$e reason, it &as su$$er outside, and not &inter( There &as a red fire-truc+ outside the &indo&( There &ere really lo& clouds in the s+y( The sun &as a"ove the$( /e#t, everything 4uic+ly faded a&ay and - found $yself "ac+ in $y "ody( Then, - got up and loo+ed at the ti$e( -t &as 2'16 EM( Mista!esC 1( 5hen the phanto$ &iggling &or+ed, - should have aggressively tried to increase the range of $ove$ent, and not si$ply done &iggling, let alone change to another techni4ue( %fter all, if &iggling occurs, the phase can al&ays "e entered( 2( The sa$e &ith the sounds( - had no great desire to a$plify sounds or even listen in( 2verything &as done lac+adaisically( 8( - should have started &ith deepening and not actions, as visual sensations &ere not vivid( I( - should have e$ployed
techni4ues for $aintaining( 6( Jou can.t loo+ do&n for long &ithout si$ultaneously using techni4ues for $aintaining, yet too+ in everything outside the &indo& and in the s+y( K( forgot a"out the plan of action( L( - should have tried again to enter the phase( Plan of a tion for ne*t ti'eC 1( 3efinitely deepen the phase as $uch as possi"le( 2( should try to go through a &all( 8( Translocate to $y %untie in /e& Jor+( I( Translocate to the Statue of Mi"erty and e#a$ine her cro&n( 6( Try to conduct the e#peri$ent of putting $y hand into $y head(
able to enter the phase (ithout any complicated or incomprehensible techni2ues. The reader (ill understand that the key is to take right actions at the right moment trying to master the phase (ith calmness and confidence. .hile re&ie(ing and analy=ing other peopleDs e#periences in this section the reader should remember that these e#periences are based on personal beliefs about the phenomenon (hich is (hy occult terminology and notions may be encountered. 6o(e&er such aspects of the descriptions are not important. Focus should be gi&en to techni2ue"related actions described in the accounts. The reader should also take into account that some nuances Flike e#periential realismG are not al(ays clear in the te#t and that it is not al(ays possible to determine (hy certain e&ents occurred in the phase e#periences described here. 1ll of the follo(ing descriptions belong to real people (ho either related the accounts orally (rote them do(n during classes at the 4chool of Out"of"5ody Tra&el submitted them &ia email or posted them on the forum at. Though the total number of recorded &erifiable phase descriptions e#ceeds one thousand only se&eral cases that are illustrati&e and useful for de&eloping analysis ha&e been selected. Primarily these are descriptions of the practitionersD initial phase e#periences (hich are most rele&ant to ne( practitioners. The large number of mistakes made by almost e&ery practitioner regardless of their le&el of e#perience should not be taken too seriously (hile reading the comments. 1ctually it is a rare occasion that the phase is e#perienced (ithout any techni2ue"related errors. E&erybody makes mistakes. E#periments are listed in ascending order of 2uality and number of properly performed actions. 1ccounts ha&e been published (ith the permission of the authors.
3N3;8SIS O/ SE;EC#ED P93C#I#IONE9SI EEPE9IENCES NoD 1 Boris Pronya!in Copy6riterD =ie>J 4!raine - &o+e up in the >correct? state( - i$$ediately felt vi"rations, and "efore - had ti$e to ti$e to thin+ a"out anything, - &as +noc+ed out of $y "ody "y a strong +ic+( - started falling( - had no vision, the floor &as gone( Mi+e a nose-diving airplane, - &as in a free-fall( +ept dropping faster and faster( - started to feel that - &as losing control( The only thing - could do &as increase the speed &ith &hich - fell, all of the &ays that occurred to $e to try $aintain the phase that - atte$pted at that $o$ent only lo&ered $y degree of a&areness( Touching did not do anything for $e, as - &as 1ust an une$"odied spirit in a co$plete vacuu$( Fision &as also $issing( started to panic due to the i$$inent foul( But the acceleration of the fall did not help either, and - &as flying and &aiting for the $o$ent &hen - &ould "e thro&n out into the drea$ &orld( %nd - dropped li+e this until - fell asleep( <uestionsC 7id 5oris describe a direct or indirect techni2ue/ .hat could he ha&e done if no spontaneous separation had occurred/ 6o( could 5oris ha&e more correctly used deepening techni2ues/ .hy (asnEt 5oris thro(n into a phase episode/ .hy did he fall asleep/ 3ns6ers and Co''entsC 1n indirect techni2ue (as employed. )f spontaneous separation had not occurred 5oris could ha&e tried to separate on his o(n. )f an attempt to separate had failed it (ould be necessary to implement indirect techni2ues by intensifying the &ibrations and then try once again to separate. )n order to deepen and mean(hile reach a destination (hile falling 5oris should ha&e applied translocation techni2ues and upon reaching a location continued to deepen by means of sensory amplification. For e#ample he could ha&e applied the techni2ue of translocation by teleportation (ith his eyes closed or simply tried to catch sight of his hands through the darkness (hich also (ould ha&e induced an e#it.
5oris also did not pay any attention to the roar in his ears. )t could ha&e been used for the techni2ue of listening in (hich (ould ha&e helped him to deepen and maintain. The lack of a set aim to land some(here resulted in his endless fall though it does not al(ays happen this (ay. 5oris fell asleep due to his passi&ity and also because he forgot that falling asleep (as a possibility though he did remember about the possibility of an inad&ertent return to reality Fa foulG. NoD " 3le*ei Ba!hare> EngineerD So hiJ 9ussia This &as the first ti$e that - $anaged to "eco$e conscious &hile drea$ing( Before falling asleep, - concentrated on the dar+ness "efore $y eyes and tried to re$ain consciousness as long as - could( %ll of a sudden, - drea$t that - &as levitating to the ceiling, &hich resulted in $y "eco$ing conscious that - &as drea$ing( My phanto$ "ody responded poorly to atte$pts to control it, and si$ply hovered "eneath the ceiling( There &ere t&o people sitting on the floor "elo&( They &ere loo+ing in $y direction, "ut it see$ed that they did not see $e( %t this point - &o+e up and felt so$e sort of tingling and itching in $y legs( <uestionsC .hat factors led to the entry into the phase through dream consciousness/ .hat needed to be done (hile ho&ering about beneath the ceiling/ .hy did the foul happen so fast/ .hat should ha&e been done immediately after returning to the body/ 3ns6ers and Co''entsC 7ream consciousness occurred due to the 1le#eiDs intent to concentrate on the space before his eyes and his desire to remain conscious for as long as possible. The process of becoming conscious (as caused by the sensation of flying (hile dreaming. Flying almost al(ays becomes an anchor for dream consciousness. )mmediately after the phase occurred 1le#ei should ha&e started deepening. )nstead he simply ho&ered about and obser&ed. .hile all the mo&ements may ha&e been difficult to perform they should ha&e ne&ertheless still been done &ery acti&ely. 1s a result lightness and a deepening of the phase (ould ha&e
ensued. 6is inad&ertent e#it from the phase happened due to passi&ity failure to deepen and non"compliance (ith the rules for maintaining the phase. E&en upon returning to his body 1le#ei should ha&e tried to separate again. NoD % D'itry Mar!o> 9adio Me hani D Mos o6J 9ussia My first ti$e &as the $ost terri"le event in $y life( - had never e#perienced such terror( -t happened in 3ece$"er, 1!! ( - &as falling asleep in $y "ed at ho$e( Suddenly, - heard so$eone enter $y roo$, "ut - did not pay attention to the >intruder?( Then, t&o fe$ale hands gra""ed $e fro$ "ehind, and &hile pressing $y "elly, started to lift $y "ody up( - distinctly felt thin fingers &ith long nails on $y "elly, "ut &as co$pletely paraly*ed and a"solutely una"le $ove any part of $y "ody or put up any +ind of resistance( - felt $y "ody go through the ceiling, "ut then &as pulled still higher and higher( - got scared that this could "e death( - &as afraid not so $uch of death as of the un+no&n( %ll of this happened so s&iftly that - found $yself unprepared for such a crossover( - started to pray( - as+ed ;od to help $e free $yself and go "ac+( - panic+ed( - can.t say ho& $any seconds $y forced levitation lasted or ho& high - &as lifted a"ove $y house, "ut the $o$ent ca$e &hen - instantly returned to $y "ed( <uestionsC .as this entry into the phase deliberate/ .hat kind of techni2ue led to the phase/ .hat is the name for the complete immobili=ation that 7mitry encountered/ .hat should he ha&e done in order to start mo&ing/ .hy did his body easily go through the ceiling/ .hy (as he able to stop this terrible e#perience by praying/ .hat could he ha&e done immediately upon returning to his body/ 3ns6ers and Co''entsC This phase e#perience (as spontaneous and falls under the category of direct techni2ues since there (as no significant lapse into sleep. The (hole e#perience (as accompanied by sleep paralysis (hich is (hy it (as difficult for 7mitry to do anything. )n order to mo&e in this type of situation it
(ould ha&e been necessary to intensify the phase state by using an indirect techni2ue or redouble efforts to mo&e.p 7mitryDs body (ent through the ceiling (ithout any difficulty because there (as no &ision and the phase itself had not been deepened other(ise this (ould not ha&e happened so easily. Praying and appealing to 3od helped in this case because praying facilitated a rela#ation of perceptions and an intention to go back to reality- t(o factors (hich are crucial during emergency return techni2ues. Upon returning to his body he could ha&e still tried to separate again though this (ould ha&e been easier said than done due to the fear associated (ith the first e#perience. NoD & I>an 8a!o>le> StudentD 3nt6erpJ Belgiu' - don.t +no& &hat &o+e $e up, "ut - +ne& right a&ay that so$ething &as out of order( - could not open $y eyes, and $y "ody &as al$ost 1ust as+ing to rise up( - understood &hat &as going on N all of this indicated that - &as having an out-of-"ody e#perience( The first thing - tried &as to lift $y left hand up, and it &or+ed( understood that this &as an astral hand, "ecause - could see through it( - $oved hastily and carefully to the other side of the "ed BThere &as a strange sensation in $y head at that ti$e)( - cal$ed do&n and tried to do so$ething again( - levitated a"out half a $eter a"ove the "ed( Fision ca$e "ac+ to $e right then and - sa& &hat appeared to "e $y roo$, "ut not e#actly it, as the rug on the floor &as of a different color pattern and the door &as closed for so$e reason( could not co$prehend &hy everything &as lit fro$ "ehind $y "ac+( Then, - loo+ed over $y left shoulder and sa& a s$all "right &hite "all "ehind $y shoulder "lade at a distance of H inches( -t &as lighting up the roo$ up( Then - tried to go through the door, "ut &as una"le to( Out of the fear that - &ould never return to $y real "ody, &o+e up in the everyday &orld( <uestionsC 7uring the beginning of his e#perience (hat phenomenon typical to the phase and a(akening did )&an encounter/ .hat kind of techni2ue direct or indirect led to the phase/ .hat
specific techni2ues (ere employed/ 6o( could the sensation of !the body %ust asking to rise up$ ha&e been used/ .hat should ha&e been done immediately (hen he reali=ed that it (as possible to raise his hand/ .hat should ha&e been the first actions taken after le&itation/ .hy (as it unnecessary to immediately try to go through the door/ .hat should ha&e been done (hen )&an returned to his body/ 7oes this practitioner ha&e a do(n"to"earth &ie( or an esoteric &ie( of the nature of this phenomenon/ 3ns6ers and Co''entsC Upon a(akening in a state of sleep paralysis )&an understood that he could use this opportunity for the phase and immediately started attempts to separate (ithout employing techni2ues for creating the state as they (ould ha&e been superfluous. This (as an indirect techni2ue by nature. 6e could ha&e follo(ed his impulse to le&itate from the &ery beginning instead of mo&ing his hands. 1fter his hand started to mo&e he could ha&e stood up or separated. )nstead )&an simply rolled o&er and calmed do(n for an instant although doing so is strongly discouraged and is a (aste of the progress made up to this point. Then after starting to le&itate he should ha&e first of all assumed a position distinct from that of his real body stood up on the floor and immediately started deepening. )nstead he di&erted his attention to the light source and an attempt to go through the door. E&en if e&erything had been done correctly from the beginning there (ould ha&e been no reason to attempt to go through the door. )&an could ha&e simply opened it. The skill of going through ob%ects should be learned after first fine"tuning the ability to deepen and maintain the phase. There (as no reason to return out of fear but e&en a return to the body another immediate attempt at separating (ould most likely ha&e been successful. The use of the term of !astral hand$ indicates that the practitioner harbors esoteric &ie(s on the sub%ect.
NoD ) Natalya =oHheno>a EngineerD Sh hel!o>oJ 9ussia 5hen - &as a"out 1L or 1H years old, - read so$e esoteric articles on astral pro1ection( They see$ed 4uite interesting to $e, "ut no $ore than a curiosity N - did not particularly "elieve in such things( One evening, - &ent to "ed as usual( - &o+e up in the $iddle of the night, "ut &as una"le to $ove $y "ody and there &as a loud noise in $y head( 0aving "een re$inded of those articles, - si$ply tried to levitate and - $anaged to do so, as if through $y forehead so$eho&( The sensation of flying &as very realistic, to $y great surprise( The first thought that occurred to $e &as, O5o&, these astral guys &eren.t lying,? - hovered a"ove $y "ody for so$e ti$e in the dar+( - thought of vision, and it started to appear( - then fle& to&ards the &indo&, and upon turning around in to face $y "ody, sa& it in its proper place( - decided to fly "ac+ to it and touch it( 5hen - finally po+ed it, it suc+ed $y "ac+ into it, causing a 4uite strange sensation( <uestionsC .hat type of techni2ue did 'atalya use/ .hat (ould she ha&e needed to do if her attempt at le&itating had been unsuccessful/ .hy (as the phase short"li&ed/ .hat should she ha&e done upon returning to her body/ .hy did she use the term !astral$/ .ere the articles about astral pro%ection of any significant help/ 3ns6ers and Co''entsC Upon a(akening in a state of a sleep paralysis 'atalya stumbled upon the idea of employing indirect techni2ues. 4he managed to separate immediately but if sheDd encountered problems in doing so she could ha&e started the techni2ue of listening in to the !noise$ in her head. The phase (as short"li&ed due to a lack of acti&ity and failure to perform deepening and !maintaining$ techni2ues. 1fter returning to her body she should ha&e tried to immediately separate. 'atalya holds esoteric &ie(s on the nature of the phase phenomenon (hich is (hy she uses such terminology for it. 6o(e&er the articles helped her to perform the right actions at the right moment.
No + 3le*ander /ur'en!o> StudentD Saint Peters0urgJ 9ussia - &o+e up at early in the night after so$e difficulties &ith falling asleep( Blurred i$ages started to float "efore $y eyes and - reali*ed that - could enter the phase( - started to discard unnecessary i$ages, and after getting ahold of one of the$, - e$erged in so$e +ind of a yello& corridor( The level of general realness and a&areness of the e#perience &as a"out H 7 to ! 7 of that of reality( - re$e$"ered a"out the $ethods for deepening, &hich is &hy - started to loo+ at everything going on around $e, "ut this did not yield any serious results( - started to touch $yself, "ut all sensation see$ed so$e&hat da$pened( - reali*ed that - &as losing a&areness( - ca$e round, "ut nevertheless fell asleep in a"out 2 seconds( <uestionsC )s it possible to call the techni2ue used in this description a direct techni2ue/ .hat specific techni2ue for creating the phase (as employed/ .hich separation techni2ue did 1le#ander use/ .hat could ha&e been the reason for the !dampened sensation$ and inability to deepen/ .hat caused him to fall asleep/ 3ns6ers and Co''entsC The techni2ue employed cannot be considered a direct one though it (as used at the beginning of the night. 1s a matter of fact it appears that the preliminary lapse of consciousness into sleep (as significant. )f such preliminary sleep had lasted only se&eral minutes the techni2ue could ha&e been considered partially direct. The techni2ue for obser&ing images (as employed correctly because the images appeared on their o(n. 1le#ander did not employ any techni2ues for separation as the obser&ing images techni2ue often brings the obser&er into the obser&ed image or some other (orld (hich is e#actly (hat happened here. Most likely the (eakness of the phase (as due to meager le&els of acti&ity and moti&ation (hich (ere caused by the fact that it (as early in the night. The practitioner fell asleep because he failed to deepen sufficiently and not keep from falling asleep. 3eneral acti&ity (as also &ery lo(. The bodyDs desire to fall asleep played a
ma%or role in the process. 1le#ander had after all been ha&ing problems sleeping. NoD , 9o'an 9euto> Syste' 3d'inistratorD Sa'araJ 9ussia Truly, the $ost interesting things al$ost al&ays happen une#pectedly( %fter a sufficiently long "rea+ in $y atte$pts to go to the other &orld, tonight - decided to try it again( - thre& in the to&el after yet another unsuccessful atte$pt, rolled to $y other side, and decided to si$ply get a good night.s sleep( - do not +no& e#actly ho& $uch ti$e passed &hile - lay do&n and thought a"out &hat - &as still doing &rong &hile o"serving interesting i$ages that $y i$agination &as dra&ing( But at one fine $o$ent, - suddenly felt the pheno$enon that is co$$only referred to as vi"rations( - started to intensify the$ B- should add that the feeling is indescri"a"le), "ut - could not levitate, though - really &anted to ta+e a loo+ at $yself fro$ the outside( - decided to si$ply stand up, and that.s &hen it all "eca$e $ost interesting, The entire process of transitioning fro$ a hori*ontal position to a vertical one &as acco$panied "y increasingly palpa"le vi"rations and a louder and louder roaring sound in $y head( The sensation &as the sa$e as that e#perienced after going to "ed after not having slept for 2I hours and then "eing suddenly roused "y so$e"ody' $y head spun, everything started crac+ling inside of it, and - &as a"out to lose consciousness( Then, a flic+ering picture started to appear( -t sta"ili*ed after one or t&o seconds, the roaring in $y head died do&n, and - reali*ed that - &as sitting on $y "ed( - &as in $y apart$ent, thought it &as noticea"ly altered( My roo$ see$ed $ore or less the sa$e, though the interior &as indeed different upon detailed e#a$ination( For e#a$ple, $y $o"ile phone, &hich is al&ays &ithin a reach, &as so$eho& an older and different $odel( -t turned out to "e the first o"1ect that - tested, as - suddenly &anted very $uch to find out &hat ti$e it &as and chec+ &hich day of the $onth it &as( - distinctly felt the phone in $y hand, "ut upon
atte$pting to concentrate on and loo+ at the display, - &as thro&n "ac+ into the reality( - i$$ediately cli$"ed "ac+ out of $y "ody and decided to si$ply pace around the apart$ent &hile trying to re$e$"er &hat - could e#peri$ent on( - tried to con1ure an o"1ect, "ut that didn.t &or+ and resulted in so$e $ental activity( This caused the phase to fade and $y "eing thro&n "ac+ into reality( -n total, there &ere a"out five successive entries into the phase that lasted for 2 to 8 $inutes each( The e#periences &ere not sta"le at all, &hich is &hy - &as e#a$ining $y surroundings in a hurry, al&ays trying to get ahold of anything - could get $y hand on( 0o&ever, there &ere a good a$ount of i$pressions, considering that it &as $y first entry( <uestionsC .hat type of techni2ue did Roman use to enter the phase/ .hat (ere the key precursors of the phase/ .hich separation techni2ue (as used/ )f Roman had failed to completely separate (hat techni2ue besides &ibrations should he ha&e considered/ .hat is the most likely reason for all of the fouls/ .hich single action allo(ed the practitioner to make the phase fi&e times longer/ 3ns6ers and Co''entsC The phase (as entered through a direct techni2ue (ith the comfortable position that Roman (as lying in being the main catalyst. 1s long as Roman (as lying in an uncomfortable position his mind (as unable to completely turn off physical perception and this (as most likely the reason (hy there (ere no short lapses in dreaming. )f Roman (ere still unable to separate (hen using the techni2ue of standing up or any other techni2ue besides intensifying the &ibrations he could ha&e tried listening in as there (as some noise. )nstead of using his first phase e#perience to (ork on mastering the basic skills of deepening and maintaining Roman immediately indulged in comple# e#periments (hich is (hy his multiple entries (ithin the same phase (ere brief of poor 2uality and not used effecti&ely. 5ut this is all typical during initial e#periences and a lot (as still accomplished especially considering that a direct techni2ue (as used. The relati&e length of the phase (as achie&ed mainly thanks to complying (ith the single (ay to maintain the phase I repeated separation (hich Roman managed to do fi&e times.
NoD 3le*ander Dyren!o> StudentD Mos o6J 9ussia My first entry happened at night( - &as lying in "ed and thin+ing a"out the phase, as - had "een una"le to fall asleep for a &hile( do*ed off for a $o$ent and then a&o+e again, this ti$e already in the proper state, and then easily rolled out B$ore or less unconsciously and refle#ively)( - &ent deeper "y $eans of touching and then falling headfirst( -t is a pity that -.ve already forgotten a lot of the e#perience, "ut - do re$e$"er that after deepening - fell right do&n onto the yard of $y grand$other.s house, "ut then lost consciousness, and so - returned into $y "ody and rolled out of it several ti$es( - &as una"le to sharpen all $y senses' 5hen deepened one sense Btouch, for e#a$ple), another Bi(e( sight) &ould fade a&ay( %fter that, - have a gap in $y $e$ory concerning $y travels Bconsciousness and lucidity &ere &ea+, and - fell asleep and >resurfaced? several ti$es), "ut - re$e$"er having "een to a lot of places( 0ereAs ho& the episode ended' - dove headfirst into &ater fro$ a high "oard Bafter first having deepened a "it), and then $y sense of touch gre& sharper' - felt >&ater? and hit $y head against a very soft >"otto$(? - resu$ed the interrupted fall through &illpo&er, "ut then it occurred to $e that $y grand$other &anted to &a+e $e up( My level of a&areness &as not 4uite ade4uate, as it did not occur to $e that - &as actually sleeping in a dor$itory, and not at $y grand$otherAs house( That.s &hy - decided that - needed to return to $y "ody( % sharp fall occurred right after that thought, and &as follo&ed "y sensations si$ilar to those one e#periences &hen hungover( <uestionsC .as a direct or indirect techni2ue applied/ .hat made the implementation of the techni2ue successful/ .hy (as 1le#ander e%ected into his grandmotherEs yard/ .hile deepening ho( could the problem of the senses being enhanced only one at a time ha&e been sol&ed/ .hy did the practitioner ha&e gaps in his memory/ .hat (ere the main problems associated (ith maintaining the phase/
3ns6ers and Co''entsC 7espite the brief lapse in consciousness the techni2ue used (as a direct one and that &ery lapse facilitated the immediate emergence of the necessary state e&en though this (as 1le#anderDs first e#perience. The e%ection into his grandmotherEs yard (as spontaneous and (as most likely caused by some preceding thoughts about the yard or being in a habit of going there. Une#pected translocation often occurs (hen deepening (hile falling headfirst. Ouite possibly in order to a&oid ha&ing the senses of sight and touch enhance only one at a time he should ha&e simultaneously applied the techni2ues of touching and looking out. 1s for maintaining the phase there (ere three main problems that (ere also direct causes of the gaps in 1le#anderEs memory- little depth lack of a clear plan of action and non"compliance (ith the rules for maintaining the phase F(ith the e#ception of multiple entries after return to the bodyG. NoD . S>yatosla> Barano> StudentD Per'J 9ussia - &o+e up on $y side( - didn.t feel li+e sleeping any$ore, "ut closed $y eyes any&ay( 5hen - lay do&n on $y "ac+, - i$$ediately felt the sensation that - &as a"out to fall fro$ the couch B- &as lying on the edge), and so$e +ind of lapse occurred, as if - &as "eing pulled so$e&here( - lay do&n once again, and this "u**ing started, and a green light appeared "efore $y eyes( - lay "ac+ even further, and $y eyelids started to flutter( - thought that - $ight fall fro$ the couch at that $o$ent, "ut then $y vision ca$e to $e, and - o"served that - &as already lying on the floor ne#t to the couch, - got up on $y feet and noticed that the roo$ &as >spinning? as if - &ere drun+, "ut everything 4uite 4uic+ly &ent "ac+ to nor$al( %t that very $o$ent, understood that this &as it, The phase itself, -n ecstasy, - forgot a"out all the techni4ues and &ent to loo+ a"out the roo$( 2verything &as 1ust li+e in reality, "ut so$e things &ere out of place( - tried to levitate and "ent "ac+&ards, and &as so$eho& thrust outside( -t &as dus+ out there, and there &as a lot of
sno& on the ground( - &ent around the house and tried to levitate( &as a"le to soar up&ards, and sa& the hori*on and sunset( But then "egan to lose altitude( %fter having flo&n to the &indo& on the other side of the house, - &anted to go up to the roof, "ut then a foul occurred( -n a fraction of a second, - had the sensation that - &as >no&here?( But then, $y real eyes opened B&ith difficulty) and there &as once again the feeling of so$e sort of lapse( %&areness &as di$ during the phase, apparently due to not having gotten enough sleep( <uestionsC .hat kind of phase entrance techni2ue did 4&yatosla& use/ .hich specific techni2ue produced results/ .hich separation techni2ue (as employed/ )f separation (as unsuccessful (hich techni2ue should ha&e been immediately used/ .hich important actions did he not perform enough after entering the phase/ .hat should ha&e been done after the foul/ .hy (as a(areness dim during the phase/ 3ns6ers and Co''entaryC 1n indirect techni2ue (as employed. 'o phase state creation techni2ues (ere employed by 4&yatosla&. )nstead separation immediately (orked through rolling back(ards. )f separation (ere unsuccessful he should ha&e proceeded (ith obser&ing images (hich (ould ha&e been possible (ith the green light.7eepening (as not immediately performed no effort (as made to maintain and there (as no appro#imation of a plan of actionJ ho(e&er this is not a crucial factor during initial
1nother attempt to enter the phase should ha&e been made upon returning to the body but this (as also forgotten. 1(areness (as dim and memory (as (eak during the phase because of the initial shallo(ness of the state (hich (as reflected in the perception of the surrounding and also the thought processes.e#periences.
NoD 12 Oleg Sush hen!o Sports'anD Mos o6J 9ussia Mast night - spent a"out an hour developing the interplay of i$ages in $y $ind after - no left felt any feeling of +inesthetic sense( - &as lying on $y "ac+ in an unco$forta"le position( %fter sliding to&ards sleep for so$e ti$e, - felt slight vi"rations and echoes of
sounds fro$ the drea$ &orld, "ut the unco$forta"le position still hindered $e( -n the end, - thought the hec+ &ith it, and decided to lie do&n ho&ever &as co$forta"le, and turned over to lie on $y sto$ach( 3espite the fact that the $ove$ent upset the process, after a"out five $inutes the state "egan to return and "uild up( - &as a"le to get a little vi"ration this ti$e, although - &as una"le to a$plify it( - dre& a picture of $y +itchen in $y $ind, and "ecause the i$ages in that state &ere really vivid, strong, and realistic, after so$e ti$e understood that not only &ere $y attention and a&areness there, "ut so &ere $y "odily sensations( - &as 4uite surprised that the phase had "een so easy to fall in to Bthere &as no dou"t that this &as the phase)( - 1u$ped out through the &indo& and "egan to fly around the courtyard( %ctually, it &as the first ti$e that - had flo&n only upon a single $ental co$$and, &ithout any physical effort, as occurs during drea$s( The courtyard "ore only 1 7 si$ilarity to its reallife counterpart, "ut - &as not at all surprised "y this, and - si$ply en1oyed it as $uch as - could, as - &as a"le see and &as not i$$ediately thro&n out( But, after having loo+ed at and ta+en in the city, the thought of &hether or not this &as the phase and not 1ust a lucid drea$ occurred( - &as so conscious in the drea$ that - &as a"le to +no& a"out and co$prehend such ter$s, and differentiate "et&een the$ - can you i$agineG, - have to add that - gave little attention to $y $e$ory, so - can.t say ho& $uch of $y >selfa&areness? &as there, "ut - &as a&are enough to "e a"le to differentiate "et&een the phase and a lucid drea$ Bor at least thin+ a"out the difference)( - even &ent and as+ed people around if it &as the phase or a lucid drea$( Sounds funny, doesnAt itG The funniest thing &as that they ans&ered that it &as a different &orld, and they refused to discuss the topic any further &ith $e( Then, - decided to not get $y $ind all $i#ed up and 1ust go &ith the plot, &hich turned out to "e 4uite long and uninterrupted, - recalled a $o$ent fro$ the day "efore ho& - had lain do&n and induced the phase &hile lying on $y "ac+, and ho& - had turned over and flo&n a&ay( - recalled all this periodically during the course of the phase, and reali*ed that -
should try to as+ a"out &hat had "een going on &ith $e on the foru$ later( Then, later in the phase, - found $yself in a "ase$ent( %s there &as 1ust a really nasty s$ell there, - decided that - had already had enough and that it &as ti$e to go "ac+( That happened even $ore easily, as soon as - thought a"out going "ac+, a vi"ration as light as a "ree*e &ent through $e and then - &as "ac+ in $y "ody &ith full a&areness and a &ell-rested "ody and $ind( - &as co$pletely refreshed, %nd that.s despite the fact that - re$e$"er everything, every second of the drea$, fro$ the $o$ent - started flying, <uestionsC .hich type of techni2ue helped Oleg enter the phase/ .hat initially made it harder for him to enter the phase and could this ha&e had a positi&e effect on later results/ .hat can be said of techni2ues related to &ibrations in the conte#t of OlegEs entry into the phase/ .hich specific techni2ue brought him into the phase/ .hich initial actions should ha&e been taken upon entry into the phase/ .hat (as lacking that could ha&e lead to producti&e use of the phase/ .as it (orth(hile to immediately translocate by %umping through the (indo(/ .hat (as the cause of reflection on (hether the e#perience (as the phase or a conscious dream/ .as it beneficial to try to offhandedly learn from ob%ects (hat type of state this (as/ .hy did the desire to return back to the body arise and (hat could ha&e caused it/ 3ns6ers and Co''entaryC Oleg entered the phase using a direct techni2ue. 6e (as initially unable to enter due to the uncomfortable position that he had assumed although lapses in consciousness into short dreams did occur. 'e&ertheless the initially unsuccessful techni2ue still ended in a positi&e final outcome because the state that Oleg (as in (as close to the phase. 6o(e&er attention should not ha&e been gi&en to &ibration amplification techni2ues especially straining the brain and straining the body (ithout using muscles as they can be detrimental during direct techni2ues. The techni2ue of &isuali=ation (as used immediately before entering the phase instead of obser&ing images (hich is used more often. Oleg deliberately con%ured the obser&ed images instead of searching for them in front of himself (hich is (here the difference
bet(een the techni2ues lies. 6o(e&er he did not perform deepening upon entering the phase. 1dditionally he had no clear plan of action to ensure that the phase (ould be producti&e 4tarting to translocate by %umping through (indo(s should only be done by those (ith a certain amount of e#perience since beginners sometimes percei&e reality to be the phase or the phase to be reality. The reason for the reflection on the nature of the phenomenon (as due to terminological confusion (hich is 2uite (idespread. )f a practitioner is a(are but does not feel the body as in the physical (orld then it can be assumed that the phase has been entered. This is (hy there (as no reason to in2uire about this among animate ob%ects. 7eliberately returning to the body (as a big mistake. There (as no reason to thro( a(ay an opportunity to tra&el and use the phase. 5eginners are not often afforded such an opportunity. The reason for the return to the body in this case is most likely found in the absence of a plan of action and lack of clear understanding of ho( the phase might be used for practical aims. NoD 11 3le*ander ;ele!o> Co'puter Progra''erD Saint Peters0urgJ 9ussia - tried all night to use the %stral :atapult that cues you &hen you.re drea$ing, "ut - gave up on the idea after several unsuccessful a&a+enings and si$ply fell asleep( 5hen -A$ drea$ing - usually $ove "y ta+ing great leaps, $uch further than a +angaroo, a"out 1 -8 yards( This happens regularly in $y drea$s, and - usually i$$ediately reali*e that -A$ in a drea$( 3uring one of the leaps, reali*ed &hile air"orne that - &as drea$ing and also reali*ed that &as a"le to land in a s$all dirty pond( %s e#pected, - landed right in the pond and &ent deep under the &ater( %nd at that very $o$ent, found $yself in the stencil, &ith $y hands and head half stuc+ in it( - got a little nervous that this atte$pt &ould also "e unsuccessful, and so - i$$ediately tried to separate fro$ $y "ody( - &as una"le to get $y head or hands out, and for the first ti$e - tried to turn around round $y a#is and $anaged to get out( Then - either slipped do&n or fell fro$ the "ed, "ut - did not feel any pain( - cra&led for 1-2 $eters
and then felt that - could go "ac+( - started to touch the rug and so$e other thing, though - don.t +no& e#actly &hat it &as as it &as dar+, and, lo and "ehold' &ithin 2 -8 seconds - pro"a"ly felt &hat s$all +ittens feel &hen their eyes open for the first ti$e( 2verything &as foggy and "lurry at first, "ut then a picture started to appear, the roo$ filled &ith light, and colors "eca$e "right and vivid( - tried very hard to restrain $y e#cite$ent, and, to $y surprise, &as a"le to( - &al+ed around $y apart$ent thin+ing a"out &hat - should do( Reali*ing that - did not have that $uch ti$e, - decided to tal+ to an elderly $an &ho &ould ans&er $y 4uestions( - decided that there &ould "e an o$niscient elderly $an "ehind the apart$entAs front door, &hich - &as a"out to open( %nd there he &as, half-"ald, a"out K years old, in a grey coat &aiting for $e( - as+ed hi$ the 4uestion, >5hat should - do to get into the phase $ore oftenG? But he started to tell $e a"out ho& he &as raped as a child( %nd to "e $ore precise, this &as already not an elderly $an, "ut an elderly &o$an( &as not very interested in hearing her story, thus - tried to $ove a&ay fro$ her, suggesting that &e could tal+ later( But the elderly &o$an &as persistent, and - did not &ant to offend her, "ecause thought that this &as an unusual drea$ &ith its o&n set of rules, and na$ely that once you have as+ed an old &o$an a 4uestion, you are supposed to "e courteous and listen to the entire ans&er( - &ent &ith her to the +itchen of $y apart$ent( The telephone suddenly rang( - got scared that the telephone &as ringing in $y apart$ent and &ould &a+e $e up, &hich is &hy - i$$ediately started to loo+ at $y hand in order to $aintain( But the sensations &ere 4uite sta"le, and - stopped doing that( Then, $e and this lady &anted to coo+ so$ething in $y +itchen( She said that - could heat a frying pan &ithout gas( But - instead decided to try the techni4ue of putting the hands together and "lo&ing on the$, and returned "ac+ into $y "ody( <uestionsC .hich type of the entry into the phase did 1le#ander describe/ .as the cueing program of any help/ .hich type of anchor (as the leaping/ .hy (as the onset of consciousness immediately follo(ed by a transition into the stencil i.e. the real body though not completely/ .hich separation techni2ue helped him to get out of his
body again/ .hich techni2ue (as used for deepening/ .hich techni2ue for materiali=ing an ob%ect (as used correctly/ .hat should the procedure for obtaining information ha&e been started (ith/ .hat importance does a polite attitude to(ards elderly (omen in the phase ha&e/ .hy (as the return to body possible/ .hat did 1le#ander either forget to do or forget to record right after the foul/ 3ns6ers and Co''entsC 1le#ander described an entry into the phase through dream consciousness. 5y and large the onset of consciousness (as facilitated by prior (ork (ith the cueing program (hich though it failed to yield results strengthened the necessary intention to enter the phase. The leaping that accompanied the onset of consciousness may be compared (ith the sensations of le&itation that often lead to practitioners achie&ing dream consciousness. 4ince the techni2ues for deepening and maintaining (ere not used at the moment of dream consciousness a return to the body though partial naturally occurred. Furthermore 1le#ander managed to apply a separation techni2ue that most resembled climbing out. 6e then managed to deepen correctly by means of touching and immediately felt a result. 7espite the lack of a plan of action the practitioner competently decided to do something useful and employed the techni2ue of finding through a door in order to locate an animate source of information. 6e should ha&e first tried to test the sub%ect by asking special 2uestions to determine if the ob%ect (ould be able to pro&ide information Fsee ,hapter 1AG. 5eing polite to animate ob%ects in the phase is the prerogati&e of each person on an indi&idual basis but it hardly has any real basis. Most likely the return to the body (as triggered by a failure to maintain e#cessi&e thinking or temporary passi&ity. Upon e#iting the phase 1le#ander should ha&e tried to immediately return. 6o(e&er he failed to do so e&en though he had returned to the phase after e#iting dream consciousness. 4uch a step should ha&e been ob&ious due to an incomplete connection to the body.
NoD 1" Boris Bender Mo>ie #e hni ianJ E*perien ed Pra titioner of the PhaseD Mos o6J 9ussia - "eca$e conscious in $y drea$ al$ost i$$ediately after falling asleep( - &as in $y apart$ent standing in the corridor( Being surprised "y having so suddenly found $yself in the phase, - started to touch the &alls &ith $y hands to test their fir$ness or, Orealness,O as &ell as to intensify the phase "y touching( - entered the roo$( There &as a "ed standing ne#t to the &all, &ith $y $other sleeping on it( - could not see her face, only her "ody under the "lan+et( The roo$ and corridor &ere e#act replicas of their real-life counterparts( 5hile thin+ing a"out $y sleeping $other, - suddenly started to feel so$e&hat uneasy( 5hen - approached the &indo&, - sa& a grotes4ue landscape "ehind it that &as si$ilar to pictures fro$ $ovies a"out catastrophes' a &asteland, houses in ruins, odd pileups of "uilding $aterials, sla"s of concrete, gar"age, craters fro$ e#plosions here and there, and - noticed hu$an figures in so$e places( Fearing a foul caused "y the fact that - &as ta+ing in a panora$ic vie& Bthe vie& fro$ the &indo& spanned 1H degrees and cut off at the hori*on, &hich is in fact al$ost e#actly as the vie& fro$ $y apart$ent is in real life), - turned "ac+ into the roo$ and started to touch the &ardro"e, and then +nelt do&n to touch the floor( %ll the &hile, $y fear had "een gro&ing stronger and stronger' "oth out of thin+ing a"out $y sleeping $other and due to the vie& fro$ the &indo&( %n#iety turned into real fear &ithin a $atter of several seconds, and then graduated into terror and panic( - lost the a"ility to thin+ critically( - had only one thought' - had to go "ac+ to $y "ody( - darted "ac+ to $y "ed and suddenly found $yself lying on it( - closed $y eyes, "ut could not understand if - &ere in $y real "ody or still in the phase( My terror gre& even stronger &hen - halfopened $y eyes and sa& that $y $other &as getting up fro$ her "ed( She loo+ed li+e a character fro$ a horror $ovie and apparently &as hostile to $e(
- &anted to disappear, dissolve, and &a+e up, - hectically tried to recall the techni4ues for an e$ergency e#it fro$ the phase, "ut &ith poor results' - tried to free*e, rela# and touch $y fingers to $y toes in order to feel a connection &ith $y real "ody( %t so$e $o$ents felt li+e - had it, thin+ing, >The connection had "een restored,? opened $y eyes, "ut reali*ed that - &as still in the phase &hen - sa& that the roo$ had changed, and &as no& a&ash &ith gar"age( The fact that the atte$pts +ept ending &ith false a&a+enings &as driving $e cra*y( - &as especially shoc+ed &hen - got up after one of the false a&a+enings and sa& $y $other standing at $y "ed, still loo+ing threateningly at $e, li+e a va$pire or a *o$"ie fro$ a horror $ovie( Elus, she started to reach out to&ard $e &ith her hands, - nevertheless +ept on and tried to free*e and &iggle $y toes, this ti$e &ithout opening $y eyes, and not chec+ing &here - &as( started to cal$ do&n after so$e ti$e, "ut - &as una"le to feel $y real "ody, &hich &as confir$ed "y the fact that sounds &ere co$ing in fro$ the phase' - heard sparro&s chirping outside the &indo&, though it reality it &as too late for sparro&s to "e out( 0o&ever, the chirping and the associations that it "rought Bi(e( day, &ar$th, sparro&s, and sun), pro"a"ly helped $e a lot and cal$ed $e do&n, as - finally $anaged to sense $y real "ody and found $yself in reality( /evertheless, after - got up, - i$$ediately started to verify for a"out half a $inute that - &as no longer in the phase "y touching o"1ects, $a+ing sure that they &ere hard, and feeling all of $y "odily sensations( <uestionsC .hy (as there a risk that 5oris could return to his body (hen taking in the &ie( from the (indo(/ 6o( could 5oris ha&e e#amined the panoramic &ie( from the (indo( (ithout (orrying about a foul/ .hich techni2ue for deepening and !maintaining$ (as employed se&eral times/ .hat (ould ha&e happened if 5oris translocated from the source of the fear to another place/ 6o( could he ha&e o&ercome this problem/ .hy (as 5oris unable to easily e#it the phase and (hy (ere all of the techni2ues that he kne( of no practical use/
3ns6ers and Co''entsC .hen e#amining distant ob%ects in the phase there is al(ays a risk of returning to oneDs body because the acti&ity is rela#ing and rela#ation is detrimental to the length of a phase. 5oris could ha&e continued to take in the &ie( by simultaneously keeping up &ibrations periodically e#amining his hands or rubbing them together. 7uring the entire length of 5orisDs phase he performed sensory amplification by touching to deepen and maintain the phase. )f he tried to run a(ay from his mother to another place in the phase she probably (ould ha&e caught up (ith him there any(ay. 6e should ha&e tried to yell at her in an aggressi&e tone. This (ould ha&e helped him to o&ercome his fear and either scare the ob%ect a(ay or make it more agreeable. Problems (ith an emergency e#it from the phase arose because it (as the beginning of the night and the mind still needed to dream and thus kept pulling him into that process. NoD 1% 3le*ei #eslen!o I# EngineerJ E*perien ed Pra titioner of the PhaseD Mos o6J 9ussia %ctually, - &as not planning to travel that night, "ut &hen - &o+e up around $idnight - decided to try to enter the phase nevertheless( started to perfor$ phanto$ $ove$ents &ith $y ar$s, "ut then a strong sleepy lethargy overca$e $e and - suddenly &anted to give up $y atte$pts to enter the phase and si$ply fall asleep( 0o&ever, &as persistent and continued to perfor$ phanto$ $ove$ents &ith $y ar$s( -nstead of feeling the usual vi"rations that occur &hen this techni4ue is perfor$ed, - si$ply fell asleep and continued the phanto$ $ove$ents &hile drea$ing( Because of that, $y consciousness apparently did not fall asleep co$pletely, and "eca$e a&are that - &as drea$ing( - i$$ediately cli$"ed out of $y "ody( There &as no vision, conscious a&areness &as no $ore than 6 7, so the phase &as not that deep( -n order to $aintain the phase, - i$$ediately started chaotically touching everything around $e( -t helped( Fision ca$e,
though it &as $ur+y( - then found $yself in $y apart$ent( - decided to strive to deepen( 2ach ti$e that - e#ercised that techni4ue, the phase "eca$e deeper and deeper( %fter - had achieved a sta"le phase, - decided that it &ould "e good to gra" a snac+ and headed for the fridge( - should add that - &as on a strict diet at the ti$e and &as craving so$ething s&eet or fried( 0o&ever, &hen - opened the fridge, - &as 4uite disappointed( There &as a lot of food in the fridge, "ut all of it re4uired preparation Bra& $eat, fish, dill, etc()( 0o&ever, there &as a "ottle of spar+ling $ineral &ater on a special lo&er shelf in the fridge( 5ithout giving it any thought, - too+ the "ottle and started to chug it( %ll of the sensations &ere 1ust as in real life' - felt the "u""les fro$ the car"onation, that peculiar taste that $ineral &ater has, and also ho& the &ater &ent do&n $y throat( -n general, everything &as 4uite realistic, though there &as no sensation of $y sto$ach filling up &ith &ater and, $oreover, the &ater felt so$e&hat dry( -t sounds funny, "ut that very feeling of &ater.s dryness spoiled $y overall i$pression so$e&hat( %fter a foul, - reali*ed that a possi"le reason for this $ight have "een dryness in the $outh of $y real "ody( <sually, if there are, for e#a$ple, candies in the +itchen or in the fridge, - actually ta+e a handful of the$ and consu$e the$ &hile traveling through the phase( %fter going to the fridge, - &anted to see so$ething interesting( decided to e$ploy the techni4ue for creating o"1ects and people, and so - closed $y eyes and focused on the i$age of a girl &ho$ &anted to see at that very $o$ent( - affir$ed $y desire, and - then opened $y eyes, concentrating on the area to $y side( The air gre& $isty at first, and then the person - &as e#pecting $ateriali*ed out of the air, and ca$e to life, see$ingly fully autono$ous and &ith free &ill - she had the sa$e $anner of spea+ing as in real life, and acted in the sa$e &ay( The foul happened &hile $y conversation &ith the girl &as in full s&ingP <uestionsC .hich type of the techni2ue did 1le#ei ultimately use/ .hy did lethargy and dro(siness arise during phantom (iggling/ .hat should be done in this type of situation/ .hat (as most likely lacking (hen the indirect techni2ue (as performed and
(hy did the e#perience end (ith 1le#ei falling asleep/ .hat techni2ues for deepening (ere used/ .hat could ha&e been done to 2uickly fill the fridge (ith ready"to"eat food/ .hich techni2ue for finding an ob%ect (as used (ith regard to the girl/ .hat else could ha&e been used for the same purpose considering 1le#eiEs actions/ .hat should ha&e been done immediately after the foul/ 6o( many practical applications of the phase did 1le#ei manage to try/ 3ns6ers and Co''entsC The entry to the phase happened because 1le#ei had become a(are that he (as dreaming (hile he rightly tried to resist the sudden tiredness and dro(siness o&er the course of the unsuccessful attempt (ith the indirect techni2ue of phantom (iggling. Usually such dro(siness signifies that a phase is approaching signaling a need for aggression acti&eness and attention in order to o&ercome inertia and enter the phase. 6o(e&er attenti&eness (as lacking so 1le#ei fell asleep. 6o(e&er his desire to enter the phase (as so strong that the phantom (iggling continued e&en (hile he (as dreaming causing him to e#perience dream consciousness. 1mong techni2ues employed for deepening (ere sensory amplification through touching and %ogging. )t (ould ha&e been sufficient to employ the techni2ue of finding through a door to ensure that the fridge (as properly stocked. For e#ample 1le#ei should ha&e closed the door on the refrigerator focused his attention on a full stock of snacks and food and then opened the door to disco&er that e&erything heDd en&isioned (as there. The techni2ue for finding an ob%ect through transformation (as used to make the girl appear but this techni2ue should be considered only by e#perienced practitioners because it can lead to a foul in case of insufficient concentration. 5efore employing the techni2ue 1le#ei shut his eyes and only then imagined the girl right in front of him. 6e could ha&e immediately created her using the techni2ue of closed eyes (hich usually is easier to do since there is no direct &isual contact (ith surroundings. Upon returning to his body he should ha&e tried to separate again. 1ltogether 1le#ei managed to and make progress in t(o specific applied tasks though did not complete them satisfactorily.
Q1 Q1 Q1 Q1 Q1
The key feature of 0a5ergeDs (ork and achie&ements is an absolutely pragmatic approach to the nature of the phenomenon. 1rguably he is one of the fe( authors and researchers totally lacking in irrationality. E&erything that can be read and learned from his books is &erifiable and accessible for e&eryone (ith no peddling of out"of"this"(orld superpo(ers. Carlos Castaneda 7ue to ,arlos ,astanedaDs desire to follo( the spiritual practice of the .arriorDs Path (hich entails erasing oneDs personal history the details of his biography are unclear. 1s far as ,astanedaDs early years are concerned it can only be stated that he (as born outside of the United 4tates sometime bet(een 1@+; and 1@8;. 6e enrolled at the Uni&ersity of ,alifornia 0os 1ngeles FU,01G in the 1@<As (here he recei&ed a Ph.7. in anthropology on the basis of his books. ,astanedaDs entire life path (as de&oted to studying the teachings of a certain Cuan Matus or don Cuan ,achora. )t is more than likely that his persona is a composite"image of an )ndian 4haman a sorcerer and an heir of the culture of the ancient !Toltecs$. ,astaneda (rote a do=en booksJ ho(e&er the book The %rt of 3rea$ing F1@@8G has the most to do (ith the phase state. )t contains se&eral effecti&e techni2ues for entering the phase through dream consciousness. 6is sub%ect matter is soaked in a large amount of mysticism and &irtually de&oid of any pragmatism. 7espite the fact that the main orientation of ,astanedaDs (ork did not touch upon the phase state he ne&ertheless became one of the founding fathers of this field as his general popularity reached massi&e proportions (orld(ide. ,arlos ,astaneda passed a(ay in 1@@?.
9o0ert 3D Monroe Robert Monroe (as born in the United 4tates in 1@1;. )n 1@8> he graduated from Ohio 4tate Uni&ersity (ith a degree in Engineering. 6e (orked for some time as a radio program producer and director until he established his o(n radio company in 'e( Pork (hich rapidly e#panded. )n 1@;< his company also conducted a study about the effect of sound (a&es on the abilities of the mind. )n 1@;? Monroe had an accidental personal e#perience (ith the phase phenomenon (hich strongly stoked his interest in the sub%ect to (hich he (ould de&ote his entire career. )n 1@>: he founded the Monroe )nstitute (hich (as entirely de&oted to studying unusual states of consciousness and the ability to influence them through audio stimulation and other technologies. One of its main achie&ements (as the creation of the 6emi"4ync system (hich (as designed to help a person reach altered states of consciousness including out"of"body states by synchroni=ing the t(o hemispheres of the brain. 6is first book Journeys Out of the Body (as published in 1@>1. T(o books then follo(ed- Far Journeys F1@?;G and <lti$ate Journey F1@@:G. Robert Monroe has so far made the largest contribution to(ard populari=ing the phase state. 6o(e&er he understood the phase more as an actual e#it of the mind from the body (hich is (hy the term !out"of"body e#perience$ FO5EG (as introduced. The book Journeys Out of the Body (as such a massi&e success that Monroe 2uickly became an undisputed authority in the field. 6o(e&er the large influence of mysticism on MonroeDs (ork and &ie(s cannot be ignored. This is especially apparent after his second book. The ma%ority of phenomena described in the book ha&e not been &erified in practice. The only attempt at conducting a full" fledged scientific e#periment pro&ing that the mind left the body (as
unsuccessful. )n the end typical misconceptions about the phase became (idespread as did a(areness of the e#istence of out"of"body e#periences. Robert Monroe passed a(ay in 1@@;. Patri ia Garfield Patricia 3arfield (as born in 1@8: in the United 4tates. From the age of 1: she kept an uninterrupted daily dream %ournal that (ould allo( her and all of humanity great insight into dreams phenomena associated (ith the phase. 4he (as one of the founders of The 1ssociation for the 4tudy of 7reams. 7r. 3arfield holds a Ph.7. in clinical psychology. 4he is the author of a great number of books (ith the 1@>: best" seller :reative 3rea$ing being the most (idely lauded. )t (as one of the first pieces of literature to approach the phase state in a practical and non"specialist (ay and recei&ed (orld(ide interest and appreciation. The book contains good practical guidelines and also describes the dreaming practices of &arious cultures. Syl>an Muldoon 4yl&an Muldoon (as born in the United 4tates in 1@A8. 6e is considered to be the 1merican pioneer in the study of the phase although he used the esoteric term astral. 6e inad&ertently (oke up in the phase at the age of 1+ (here he sa( a cord connecting his percei&ed body to his real body. Muldoon first thought that he (as dying during the e#perience although he e&entually concluded that this (as an instance of !astral pro%ection$. 6e had repeated e#perience (ith the phenomenon but Muldoon (as still unable to become an ad&anced practitioner due to a lack of full control o&er the practice.
1fter coordinating efforts (ith 6ere(ard ,arrington the famous 1merican in&estigator of the unkno(n the t(o published the sensational %ointly authored book The Ero1ection of the %stral Body in 1@+@. The authors published t(o other books- The :ase for %stral Ero1ection F1@8<G and The Eheno$ena of %stral Ero1ection F1@;1G. 7espite a large ser&ing of esotericism MuldoonDs books Fespecially the first oneG contain a lot of helpful practical information and e#planation of the most di&erse phenomena that can occur during the phase. 6o(e&er Muldoon is considered to be the greatest populari=er of irrational esoteric terms and theories (hich subse2uently became 2uite (idespread. 4yl&an Muldoon passed a(ay in 1@>1. Charles ;ead0eater ,harles 0eadbeater (as born in England in 1?:> F1?;: according to some sourcesG. 1fter dropping out of O#ford due to hard times 0eadbeater became an ordained priest but then became 2uite acti&e in the occult. This led to his becoming a member of the Theosophical 4ociety in 1??8. 0eadbeater became one of its most famous participants. The combination of a bright mind scientific kno(ledge and interest in the paranormal led him to publish many books on many di&erse topics. One of them 3rea$s' 5hat They %re and 0o& They %re :aused F1?@?G (as one of the first (orks to touch upon the phenomenon of the phase. 0eadbeaterDs (riting is saddled (ith a ton of esoteric terms and theories. )n it the term astral plane is predominantly used for the phase. 'e&ertheless the book is not (ithout some helpful guidelines concerning techni2ues. ,harles 0eadbeater passed a(ay in 1@8:.
9o0ert Bru e Robert 5ruce (as born in England in 1@;;. 6e has performed his lifeEs (ork (hile li&ing in 1ustralia. 1fter studying and promoting dissociati&e phenomena for many years by the beginning of the +1st century he had become one of the leading authorities in the field. 6e is also a specialist in many other paranormal fields of study. Robert 5ruce (rote se&eral books the most important and (ell kno(n of (hich is %stral 3yna$ics F1@@@G. The author holds 2uite open esoteric &ie(s (hich are &ery strongly reflected in his theories and terminology. The helpful practical guidelines in his books are 2uite often loaded (ith a large amount of information that has not been &erified or pro&en by anyone. Robert 5ruce is also a propagator of typical superstitions and stereotypes concerning the phase phenomenon. 9i hard (e0ster Richard .ebster (as born in 'e( Realand (here he still resides. 6e is the author of about ;A publications that ha&e sold many millions of copies around the (orld. 6o(e&er only one of them %stral Travel for Beginners is completely de&oted to the phase state. The book is saturated (ith (idespread misconceptions about the phase phenomenon and misguided theories trying to e#plain it. The techni2ue"related aspect of the book is also presented ineffecti&ely. )t is 2uite likely that the author himself has no practical e#perience (hich can also be said for the contents of his other do=ens of books de&oted to &arious topics.
Charles #art ,harles Tart (as born in the United 4tates in 1@8>. 6e recei&ed his Ph. 7. in psychology in 1@<8 at the Uni&ersity of 'orth ,arolina. Tart also recei&ed training at 4tanford Uni&ersity. 6e (as one of the founders of transpersonal psychology. 6e became one of the most preeminent researchers of unusual states of a(areness after the publication of %ltered States of :onsciousness F1@<@G the first book that he (orked on. )t (as one of the first books to e#amine entering the phase through dream consciousness. The book recei&ed popularity (hen the use 047 and Mari%uana (ere often &ie(ed as &ehicles to ele&ated consciousness and the book e&en describes the use of chemical substances in the conte#t of phase states.
"D 3 pra titioner unintentionally opens the eyes for se>eral se onds upon a6a!eningD (hat is the 0est 6ay to start indire t te hni$ues fro' in this ase: 1G 1ttempting to separate. 5G The obser&ing images techni2ue. ,G The rapid eye mo&ement techni2ue. 7G The forced falling asleep techni2ue. EG )tDs best to not start any techni2ue and fall back to sleep (ith the intention of rea(akening and trying to do e&erything again (ithout first mo&ing. %D (hi h a tions are prefera0le for perfor'ing a dire t te hni$ue 0efore falling asleep for the night after a long period of sleep depri>ation or e*haustion: 1G Monotonously performing the obser&ing images techni2ue. 5G 5eing attenti&e and concentrating on actions. ,G The absence of a free"floating state of consciousness. 7G Ouickly alternating techni2ues. EG 6igh"2uality rela#ation. &D Mild >i0rations o ur 6hen perfor'ing a dire t te hni$ueD Can the straining the 0rain te hni$ue 0e used to a'plify the >i0rations: 1G Pes. 5G 'o. ,G )t may be used but for practical purposes " only (hen a practitioner is e#hausted or sleep"depri&ed. 7G)t may be used as long as the attempt to enter the phase is not being made during the day )D (hi h of the a tions gi>en 0elo6 in rease the li!elihood of entering the phase through drea' ons iousness 6hen used right 0efore falling asleep: 1G Performing direct techni2ues.
5G )ntending to perform indirect techni2ues upon a(akening. ,G Recalling dreams from the night before. 7G ,reating a plan of action for use in case of entrance to the phase in such a (ay. +D If a6areness o urs at the >ery last 'o'ent of a drea' that fades a6ayJ 6hi h of the a tions gi>en 0elo6 should 0e underta!en in order to enter the phase as soon as possi0le: 1G Try to fall asleep again in order to once again become self"a(are (hile dreaming. 5G )mmediately perform indirect techni2ues. ,G Take a break and perform direct techni2ues later. 7G 4tart to recall that nightDs dreams. ,D (hi h of these are 'ost li!ely to produ e a $ui ! phase entry 6hen a6a!ening in a state of sleep paralysis: 1G Rela#ation. 5G Falling asleep (ith the intention of becoming self"a(are (hile in a dream. ,G Mo&ing the physical eyes and tongue. 7G 7irect techni2ues. -D (hat should 0e done 6hen spontaneously thro6n fro' the 0ody 6hile lying do6n or 6a!ing up in the 'iddle of the night: 1G Return to the body and perform appropriate separation techni2ues. 5G )mplement a predetermined plan of action for the phase. ,G 7eepen immediately. 7G Try to 2uickly establish &ision if it is not already present. 7G Employ the forced falling asleep techni2ue. .D (hile trying to enter the phaseJ rolling out 6or!s at firstJ 0ut only partiallyJ and the 'o>e'ent annot 0e e*tended any
further no 'atter 6hat effort is 'adeD (hat is it 0est to do in this situation: 1G Try to turn back and roll out further once again and repeat se&eral times. 5G 4tart doing cycles of indirect techni2ues. ,G Take a break and try to separate after se&eral minutes. 7G Try to separate by le&itating getting up or climbing out. EG Use any indirect techni2ue for phase entry and attempt rolling out again. 12D 3 pra titioner une*pe tedly gets stu ! in the floor or 6all 6hile rolling outD (hat should 0e done to resu'e the phase: 1G Force through the obstacle. 5G Employ translocation techni2ues. ,G 1ttempt to return to the body and roll out again. 7G 5ecome able to locate an e#it from the problem. EG Perform sensory amplification. 11D 7o6 'ay a pra titioner deepen the phase 6hile flying through a dar! for'less spa e 6hile separating: 1G Employ the techni2ue of falling headfirst. 5G There is no (ay to do this. ,G ,reate and amplify &ibrations. 7G 5egin self"palpation. EG Translocate to another area in the phase and deepen it through sensory amplification. 1"D If deepening te hni$ues do not o'pletely 6or! 6ithin 1) to %2 se ondsJ 6hat an 0e done: 1G ,ontinue trying to go deeper. 5G E#it from the phase. ,G 1ttempt to return to the body and once use phase entrance techni2ues. 7G Proceed to performing predetermined actions.
1%D (hi h te hni$ue or 6ay of 'aintaining the phase should 0e used 6hen teleporting so'e6here 6ith losed eyes: 1G The techni2ue of amplifying and maintaining &ibrations. 5G Tactile sensory amplification feeling the sensation of rubbing the hands together. ,G 'o techni2ue. 7G The techni2ue of rotation. EG Repeating aloud the desire to remain in the phase. 1&D In 6hi h situations is falling asleep in the phase 'ost li!ely: 1G .hen looking for a desired person. 5G .hen communicating (ith animate ob%ects. ,G .hen completely calm ha&ing completely halted all acti&ity. 7G .hen tra&elling aimlessly. EG .hen taking part in side e&ents. 1)D (hi h of the follo6ing indi ators guarantees that the phase has 0een e*ited for reality: 1G 1 clock sho(s the right time and the same time e&en if a practitioner turns a(ay from it and then looks at it again. 5G 4ensations are completely realistic. ,G The presence of friends or family in the room (ho communicate (ith the practitioner. 7G 1n inner feeling that the phase has ended. EG 'othing happens after staring at the end of a finger from close distance for fi&e to 1A seconds. 1+D In 6hi h situations should tra>elling in the phase 0e deli0erately dis ontinued: 1G .hen a fear that a return (ill be impossible or a direct fear of death arises. 5G .hen there is a real possibility that the practitioner (ill be late for something in the physical (orld. ,G .hen frightened by some strange e&ents or ob%ects.
7G .hen there is an ine#plicable mortal fear of something unkno(n or incomprehensible. EG )f someone in the phase strongly insists that the practitioner should return to reality. FG )f sharp pain occurs in the body that is not caused by interaction (ith ob%ects in the phase (orld. 1,D (hat 6ill 'ost li!ely o ur 6hen trying to e>ade so'e a6ful 0eing or dangerous person: 1G The ob%ect (ill get bored and stop. 5G Fear of the ob%ect (ill go a(ay. ,G The phase (ill occur more fre2uently as (ell as be longer and deeper than usual. 7G The practitioner (ill become calmer and unner&ed less fre2uently. EG The more fear there is the more often the ob%ect (ill chase the practitioner. 1-D (hen should esta0lishing >ision in the phase 0e onsideredJ if it has not o urred on its o6n: 1G )mmediately upon separation (ithout deepening. 5G )mmediately after deepening. ,G .hile flying through dark space during translocation. 7G 1fter fi&e to 1A seconds of being sure that a phase entry has occurred. EG .hen there is a desire to immediately e#plore the surroundings after separation has occurred. 1.D 7o6 is it possi0le to pass through a 6all 6hile standing lose to itJ 6ithout stopping to loo! at it fro' lose range: 1G 5y gradually pushing the hands and arms through it and then the entire body and head. 5G 5y gradually pushing the head through it at first and then the entire body. ,G 5y trying to put a hole in it and then e#panding the hole and climbing through it.
7G 5y ramming it (ith a shoulder trying to bring it do(n. "2D (hile in the phaseJ a pra titioner is in a situation 6here the ar's are totally paralyHed and i''o0iliHedD #his happens in a roo' 6ith a single e*itC a door that has started to loseD (hat are the t6o easiest 6ays to !eep the door open: 1G Order the door to stay open in a loud imperious and asserti&e manner. 5G Free the arms and hold back the door. ,G 4top the door (ith telekinesis. 7G ,reate a person through the method of finding. EG There is no (ay to do this. "1D (hat diffi ulties 'ay arise for a pra titioner in the phase 6hile using the door te hni$ue of translo ation: 1G The door (ill not open. 5G The (rong place is behind the door. ,G )t is not possible to use the hand to pull the door handle because the hand goes through the handle. 7G 7ifficulties (ith internal concentration occur at the critical moment. EG 1 black &oid often appears on the other side of the door. ""D (hat are ne essary onditions for getting results 6hen translo ating in the phase after rolling out during initial separation fro' the 0ody: 1G 1bsence of &ision. 5G Practicing after sunset. ,G 1 firm intention to end up some(here. 7G ,ertainty of the final result. EG The presence of &ibrations. "%D 3 pra titioner is in a dar! roo' in the phase 6here e>erything is poorly >isi0leD #here is a handelierJ 0ut no light s6it hD 7o6 an the s6it h 0e a ti>ated to light the roo':
1G Translocate through teleportation to the place (here the toggle or s(itch for the light in 2uestion is located. 5G Find a flashlight through the method of finding and illuminate the room (ith it. ,G Rub the light bulbs in the chandelier (ith the hands. 7G ,reate a light s(itch in the room using the method of finding an ob%ect. EG ,lose the eyes and imagine that the room is already lit and then open the eyes. "&D (hen o''uni ating 6ith an ani'ate o01e t in the phaseJ a desire to add a spe ifi person to the s enery arisesD (hi h of the follo6ing a tions are ad>isa0le only for 0eginners in this ase: 1G Propose going to a neighboring room (here the needed sub%ect (ill be presented through the use of the door or corner techni2ue. 5G 4ummon the needed person by calling their name loudly. ,G Translocate back to the same place and ha&e both animate ob%ects present there upon your return. 7G 1dd the needed person through the closed eyes techni2ue. EG 1sk the animate ob%ect that you are talking to if it does not mind adding someone to the scenery. ")D (here is one not allo6ed to go using translo ation te hni$ues: 1G )nside a mammoth. 5G To the past or the future. ,G To hea&en. 7G To an episode of the mo&ie Star 5ars. "+D 7o6 6ill a de eased person differ fro' a prototype in the phase 6hen orre tly perfor'ing the te hni$ue for finding the person:
1G Only the practitioner himself can con%ure up differences or not see or percei&e them. 5G The deceased (ill ha&e a different timbre of &oice. ,G There (ill be a radiant halo around the deceasedDs head. 7G Physical perception of the deceased (ill be less realistic than in real life. EG The deceased (ill not remember anything. ",D (hat diffi ulties an arise in the phase 6hile o0taining infor'ation fro' ani'ate sour es of infor'ation: 1G )nability to remember information obtained. 5G 4ources of information are silent. ,G )nade2uateness of the sources of information. 7G 4e#ual attraction if the source of information is of the opposite or desired se#. EG 5eing gi&en false information. "-D 7o6 'ight a pra titioner a elerate the healing pro ess of a old that is hara teriHed 0y a stuffy nose and a sore throat: 1G Maintaining and amplifying &ibrations for the entire length of the phase and entering it o&er se&eral days in a ro(. 5G Taking aspirin and entering the phase o&er se&eral days in a ro(. ,G Tra&elling to hot places in the phase and entering it o&er se&eral days in a ro(. 7G E#periencing stressful situations o&er se&eral phases. EG Finding a doctor in the phase and asking him (hat it is best to do in real"life or e&en in the phase itself. ".D (hi h of the follo6ing a hie>e'ents 0elong to Stephen ;aBerge: 1G Founding the 0ucidity )nstitute. 5G 1 Ph.7. in anthropology. ,G 4cientifically pro&ing that lucid dreaming is possible. 7G 1 Ph.7. in psychophysiology.
EG Pro&ing that eye mo&ements in the phase and in reality are synchroni=ed. %2D (ho of approa hed the study of the phase state fro' a prag'ati point-of->ie6 that 6as totally de>oid of o ultis': 1G 4tephen 0a5erge 5G Robert Monroe ,G 4yl&an Muldoon 7G ,harles 0eadbeater EG Patricia 3arfield FG ,arlos ,astaneda
3ppendi*
3SSESSMEN# O/ P93C#I#IONE9S5 EEPE9IENCES @C73P#E9 1"A These assessments of the practitionersD e#periences refer only to the specific descriptions that they submitted and are not meant as an assessment of their practice as a (hole. 4ome of practitioners (ould easily be able to e#perience successful phases earning four to fi&e points at other times. This especially concerns 5oris Pronyakin 1le#ander 7yrenko& 5oris 5ender and 1le#ei Teslenko. This is also possibly true of the other practitioners (ith (hom the author is not closely ac2uainted. 'o. 1 5oris Pronyakin I A.; points 'o. + 1le#ei 5akhare& I A.; points 'o. 8 7mitry Marko& I A points 'o. : )&an Pako&le& I 1.; points 'o. ; 'atalya Bo=heno&a I 1 point 'o. < 1le#ander Furmenko& I 1 point 'o.> Roman Reuto& I 8 points 'o. ? 1le#ander 7yrenko& I 1.; points 'o. @ 4&yatosla& 5arano& I + points 'o. 1A Oleg 4ushchenko I +.; points 'o. 11 1le#ander 0eleko& I 1.; points 'o. 1+ 5oris 5ender I + points 'o. 18 1le#ei Teslenko I 8 points
3NS(E9S #O #7E /IN3; #ES# @C73P#E9 1&A 1. 1 5 , 7J +. 7J 8. 5 , 7J :. ,J ;. 1 5 , 7J <. 5J >. I ?. ,J @. 1 7 EJ 1A. 5 ,J 11. 1 , 7 EJ 1+. 1 7 1Q7J 18. ,J 1:. 7 EJ 1;. EJ 1<. 5 FJ 1>. , EJ 1?. 5 7J 1@. I +A. 1 ,J +1. 1 5 7J ++. 1 , 7J +8. EJ +:. 5J +;. IJ +<. 1J +>. 5 , 7 EJ +?. 5 , EJ +@. 1 , 7 EJ 8A. 1 EJ
3 SIMP;I/IED DESC9IP#ION O/ #7E E3SIES# ME#7OD /O9 EN#E9ING #7E P73SE 4SING INDI9EC# #EC7NI<4ES Upon a(akening (ithout mo&ing or opening the eyes immediately try to separate from oneEs body. The separation attempt should be carried out (ithout any imagining but rather (ith the desire to make a real mo&ement (ithout straining the muscles Frolling out le&itation standing up etc.G. )f separation does not occur (ithin three to fi&e seconds immediately try alternating se&eral of the most effecti&e techni2ues for three to fi&e seconds each. .hen one of the techni2ues (orks continue it for a longer period of time" Obser&ing images- Try to e#amine and discern the pictures arising before closed eyes. " 0istening in- 1ttempt to hear sounds in the head and make these louder by listening in or strengthening the (illJ " Rotating- )magine rotating around the head"to"foot a#isJ " Phantom (iggling- Try to mo&e a part of the body (ithout straining the muscles and try to increase the range of mo&ementJ " 4training the brain- Try straining the brain (hich (ill lead to &ibrations that may also be intensified by straining the brain.
1s soon as one techni2ue clearly starts to (ork continue (ith it as long as progress is apparent and then try to separate. )f separation fails return to the techni2ue that (as (orking. 7o not gi&e up alternating through techni2ues until one minute has elapsed but do not continue for more than t(o minutes. 4eparation from the body may be attempted periodically especially if interesting sensations occur. #3=E P39# IN 9ESE39C7 Take part in the research of a techni2ue. The techni2ue of imagined sensations is described in ,hapter + in the section on 4econdary Techni2ues. This techni2ue is also commonly kno(n as the !cell phone techni2ue$. .hile this guidebook (as being (ritten e#periments (ith this techni2ue (ere conducted at the 4chool of Out" of"5ody Tra&elDs seminars. Results (ere astounding. 7ue to the fact that this techni2ue is easy to understand and apply in practice it could be the most straightfor(ard and effecti&e one for achie&ing the phase state. 1lmost e&ery second attempt made (ith this techni2ue has yielded results pro&ided it is employed as an indirect techni2ue. 7ue to this techni2ueDs huge potential for populari=ing and spreading kno(ledge of the phenomenon anyone (ho is interested is in&ited to take part in a global e#periment of the techni2ueDs effecti&eness. )n addition to testing it a researcher may propose the techni2ue to interested persons or post it on the )nternet to increase the number of practitioners. Please submit the results of your e#periments (ith the techni2ue to the e"mail address- aing*aing.ru 6ere it is#7E CE;; P7ONE #EC7NI<4E The practice of this phase entry techni2ue is to imagine the sensation that something is resting in the hand desirably upon a(akening (ithout any physical mo&ement. )t is best to imagine a cell phone is in the hand because the modern person is 2uite
accustomed to this sensation although any other ob%ect (ill do. )t is necessary to acti&ely and attenti&ely focus on the sensations in the palm of the hand. Most likely the physical sensation of a phone lying in the hand (ill 2uickly arise. The sensation (ill become increasingly palpable. )f a sensation does not arise (ithin 1A seconds the techni2ue not going to (ork and it is time to s(itch to another one. .hen the sensation of a phone in the hand occurs focus e&ery bit of attention on it. )t should be noted that this (ill not be an imagined sensation but a real one. This should be understood from the &ery beginning and results should be e#pected. Once the sensation is stable start feeling the mobile phone (ith the fingers. Physical sensations should be e#perienced. The physical body of course must not mo&e or strain. )f this does not (ork only focus attention on the sensation of the phone lying in the hand and try to feel the phone (ith the fingers later. )f feeling the phone (ith the fingers is successful acti&ely roll the phone around the hand feeling all of its details. 1s soon as it is possible to roll the cell phone around in the hand separation from the body may be attempted. )n this case it is usually easiest to separate by rolling out or standing up. ,ontinue to hold the phone and roll it around (hich (ill maintain the emerging phase state. 4eparation in this case should be more like actually getting up physically or rolling out of bed rather than actually separating one thing from something else. That is do this in the same (ay as physically getting out of bed starting from the sensation of the phone in the hand. )f separation is unsuccessful continue to attenti&ely feel the phone in the hand for a little (hile longer and try to separate again. )f separation happens the ne#t step is to take actions that are typical for a phase e#perience- deepening and then accomplishing predetermined tasks (hile performing !maintaining$ techni2ues. )f only a partial separation occurs then separation by force should be attempted. 3enerally the real sensation of a phone in the hand arises (ith e&ery second attempt. Furthermore achie&ing success only re2uires e#perience and some de#terity since feeling the sensation of a phone
in the hand signifies that the re2uired state has been reached and subse2uent actions may be attempted. 3##EN#IONF .hen making attempts to enter the phase the practitioner should ha&e complete confidence that he (ill be immediately successful in e&erything. E&en a shroud of doubt (ill keep the practitioner in his body this is especially true (hen it comes to indirect techni2ues. Four typical barriers to mastering the phase encountered by @AK of practicioners1 " Forgetting to deepen the phase + " Forgetting to maintain the phase 8 " 1bsence of a plan of action (hen in the phase : " Forgetting to try to re"enter the phase after a foul #7E SC7OO; O/ O4#-O/-BOD8 #93?E; Michael RadugaDs 4chool of Out"of"5ody Tra&el conducts training seminars in many countries around the (orld. The course(ork allo(s students to master the phase phenomenon and hone their skills at tra&eling in the phase. )nformation on e#isting branches and seminar schedules are a&ailable on the (ebsite. .e also (elcome potential partners interested in organi=ing 4chool of Out"of"5ody Tra&el branches and seminars. 1ll correspondence regarding seminars partnerships and proposals related to the translation of this book may be handled by e"mail at aing*aing.ru. B9IE/ G;OSS398 O/ #E9MS 3ND DE/INI#IONS Out-of-Body e*perien e @OBEAJ lu id drea'ing @;DAJ astral a number of terms united by the phase that refer to the state in (hich a
person (hile being fully conscious reali=es consciousness outside the normal range of physical perception. Indire t te hni$ues I entry into the phase (ithin fi&e minutes of a(akening from sleep of any duration " pro&ided there has been minimal physical mo&ement. Dire t te hni$ues I entry into the phase (ithout any prior sleep after e#cessi&e physical mo&ement upon a(akening or ha&ing been a(ake for at least fi&e minutes. Drea' Cons iousness I entry into the phase through becoming consciously a(are (hile a dream episode is happening. Disso iation I separationJ in this case a scientific term describing e#periences in the phase. Sleep paralysis I a stuporJ the complete immobili=ation that often occurs (hen falling asleep a(akening and entering or e#iting the phase. Sten il I the real physical body that is no longer percei&ed (hile in the phase. Deepening the phase I methods for making the phase as realistic as possible by stabili=ing the surrounding space. Maintaining the phase I methods for maintaining the phase state by pre&enting a lapse into sleep a return to reality or an imagined return to reality. 9EM I rapid eye mo&ement sleep FREM phaseGJ a sleep phase that is characteri=ed by increased brain acti&ity that is accompanied by rapid eye mo&ement and dreaming. /oul I an inad&ertent termination of the phase through a spontaneous return to e&eryday reality. Cy les of indire t te hni$ues "" the easiest (ay to enter the phase employed by rapidly alternating certain techni2ues upon a(akening from sleep until one of them (orks.
) (ould like to e#press my gratitude to all those (ho assisted me in putting together this one"of"a"kind compilation. Pou ha&e made a contribution to this field of study and it only remains for me to (ish you further success (hich (ill sho( that my commentary on your e#periences (as right on. Michael Raduga Founder of the School of Out-of-Body Travel March 2 , 2 ! Table of ,ontentsPart 1 0ea&ing the Perception of the 5ody Part II Out"of"5ody E#periments Part III The E#periences of .ell"Bno(n 1uthors Part I? 7emonstrati&e ,ase 4tudies 3ppendi*
Proposals regarding translating and publishing this book and other (orks of M.Raduga may be sent to aing@aing.ru
#he real na'e of this 0oo! is KS hool of Out-of-Body #ra>el D 3 Pra ti al Guide0oo!L #his e-0oo! is free >ia NetD Send it to all your friendsF Post it on your sites and 0logsF. | https://it.scribd.com/document/220399486/Near-Death-Meditation-for-Beginners-Yoga-Free-E-book | CC-MAIN-2020-45 | refinedweb | 62,594 | 59.33 |
Azure Contoso Loans Azure Monitor Network Azure Monitor CPU.
Installation
This plugin requires Grafana 4.5.0 or newer (5.2.0 or newer if you are querying Azure Log Analytics).
Grafana Cloud
If you do not have a Grafana Cloud account, you can sign up for one here.
Click on the
Install Nowbutton on the Azure Monitor Monitor data source Monitor plugin with this command:
docker run -d --name=grafana -p 3000:3000 -e "GF_INSTALL_PLUGINS=grafana-azure-monitor-datasource" grafana/grafana:latest
- Open the browser at: or
- Login in with username:
adminand password:
admin
- To make sure the plugin was installed, check the list of installed data sources. Click the Plugins item in the main menu. Both core data sources and installed data sources-monitor.
- Quickstart Guide for Application Insights.
Accessed from the Grafana main menu, newly installed data sources can be added immediately within the Data Sources section. Next, click the "Add data source" button in the upper right. The data source will be available for selection in the Type select box.
Select Azure Monitor from the Type dropdown:
In the name field, fill in a name for the data source. It can be anything. Some suggestions are Azure Monitor or App Insights.)
Paste these four items into the fields in the Azure Monitor API Details section:)
If you are are using Application Insights, then you need two pieces of information from the Azure Portal (see link above for detailed instructions):
- Application ID
- API Key
Paste these two items into the appropriate fields in the Application Insights API Details section:
Test that the configuration details are correct by clicking on the "Save & Test" button:
Alternatively on step 4 if creating a new Azure Active Directory App, use the Azure CLI:
az ad sp create-for-rbac -n ""
Formatting Legend Keys with Aliases
The default legend formatting for the Azure Monitor API is:
resourceName{dimensionValue=dimensionName}.metricName
and for the Application Insights API is:
metric/name{group/by="groupbyvalue"}
These can be quite long but this formatting can be changed using aliases. In the Legend Format field, the aliases which are defined below can be combined any way you want.
Azure Monitor Examples:
dimension: {{dimensionvalue}}
{{resourcegroup}} - {{resourcename}}
Application Insights Examples:
server: {{groupbyvalue}}
city: {{groupbyvalue}}
{{groupbyname}}: {{groupbyvalue}}
Alias Patterns for Application Insights
{{groupbyvalue}}= replaced with the value of the group by
{{groupbyname}}= replaced with the name/label of the group by
{{metric}}= replaced with metric name (e.g. requests/count)
Alias Patterns for Azure Monitor
{{resourcegroup}}= replaced with the value of the Resource Group
{{namespace}}= replaced with the value of the Namespace (e.g. Microsoft.Compute/virtualMachines)
{{resourcename}}= replaced with the value of the Resource Name
{{metric}}= replaced with metric name (e.g. Percentage CPU)
{{dimensionname}}= replaced with dimension key/label (e.g. blobtype)
{{dimensionvalue}}= replaced with dimension value (e.g. BlockBlob)
Filter Expressions for Application Insights
The filter field takes an OData filter expression.
Examples:
client/city eq 'Boydton'
client/city ne 'Boydton'
client/city ne 'Boydton' and client/city ne 'Dublin'
client/city eq 'Boydton' or client/city eq 'Dublin'
Azure Log Analytics
Queries are written in the new Azure Log Analytics (or KustoDB) Query Language. A Log Analytics Query can be formatted as Time Series data or as Table data.
Time Series queries are for the Graph Panel (and other panels like the Single Stat panel) and must contain a datetime column, a metric name column and a value column. Here is an example query that returns the aggregated count grouped by the Category column and grouped by hour:
AzureActivity | where $__timeFilter(TimeGenerated) | summarize count() by Category, bin(TimeGenerated, 1h) | order by TimeGenerated asc
Table queries are mainly used in the Table panel and row a list of columns and rows. This example query returns rows with the 6 specified columns:
AzureActivity | where $__timeFilter() | project TimeGenerated, ResourceGroup, Category, OperationName, ActivityStatus, Caller | order by TimeGenerated desc
Azure Log Analytics.
Azure Log Analytics Builtin Variables
There are also some Grafana variables that can be used in Azure Log Analytics queries:
$__from- Returns the From datetime from the Grafana picker. Example:
datetime(2018-06-05T18:09:58.907Z).
$__to- Returns the From datetime from the Grafana picker. Example:
datetime(2018-06-05T20:09:58.907Z).
$__interval- Grafana calculates the minimum time grain that can be used to group by time in queries. More details on how it works here. It returns a time grain like
5mor
1hthat can be used in the bin function. E.g.
summarize count() by bin(TimeGenerated, $__interval)
Writing Analytics Queries For Application Insights
If you change the service type to "Application Insights", the menu icon to the right adds another option, "Toggle Edit Mode". Once clicked, the query edit mode changes to give you a full text area in which to write log analytics queries. (This is identical to how the InfluxDB datasource lets you write raw queries.)
Once a query is written, the column names are automatically parsed out of the response data. You can then select them in the "X-axis", "Y-axis", and "Split On" dropdown menus, or just type them out.
There are some important caveats to remember:
- You'll want to order your y-axis in the query, eg.
order by timestamp asc. The graph may come out looking bizarre otherwise. It's better to have Microsoft sort it on their side where it's faster, than to implement this in the plugin.
- If you copy a log analytics query, typically they'll end with a render instruction, like
render barchart. This is unnecessary, but harmless.
- Currently, four default dashboard variables are supported:
$__timeFilter(),
$__from,
$__to, and
$__interval. If you're searching in timestamped data, replace the beginning of your where clause to
where $__timeFilter(). Dashboard changes by time region are handled as you'd expect, as long as you leave the name of the
timestampcolumn alone. Likewise,
$__intervalwill automatically change based on the dashboard's time region and the width of the chart being displayed. Use it in bins, so
bin(timestamp,$__interval)changes into something like
bin(timestamp,1s). Use
$__fromand
$__toif you just want the formatted dates to be inserted.
- Templated dashboard variables are not yet supported! They will come in a future version.
Templating with Variables.
The Azure Monitor Datasource Plugin provides the following queries you can specify in the
Query field in the Variable edit view. They allow you to fill a variable's options list.
Application Insights
Examples:
- Metric Names query:
AppInsightsMetricNames()
- Passing in metric name variable:
AppInsightsGroupBys(requests/count)
- Chaining template variables:
AppInsightsGroupBys($metricnames)
Azure Monitor
Examples:
- Resource Groups query:
ResourceGroups()
- Passing in metric name variable:
Namespaces(cosmo)
- Chaining template variables:
ResourceNames($rg, $ns)
- Do not quote parameters:
MetricNames(hg, Microsoft.Network/publicIPAddresses, grafanaIP)
Development
To install and build the plugin:
git clonethis project into your
data/pluginssubdirectory in your Grafana instance.
yarn install --pure-lockfile
grunt
karma start --single-runto run the tests once.
- Restart your Grafana server to start using the plugin in Grafana (Grafana only needs to be restarted once).
grunt watch will build the TypeScript files and copy everything to the dist directory automatically when a file changes. This is useful for when working on the code.
karma start will turn on the karma file watcher so that it reruns all the tests automatically when a file changes.
The plugin is written in TypeScript and changes should be made in the
src directory. The build task transpiles the TypeScript code into JavaScript and copies it to the
dist directory. Grafana will load the JavaScript from the
dist directory and ignore the
src directory.
CHANGELOG
v0.3.0
- Update to whitelist for Azure Monitor metrics. Some new services now supported.
- Fix for loading the Monaco editor when using Grafana behind a reverse proxy. #75 Thank you, @netiperher
v0.2.2
- Adds support for the $__escapeMulti macro for multi value template variables in the Azure Log Analytics datasource
v0.2.1
- Adds support for $__contain macro for multi value template variables in the Azure Log Analytics datasource
v0.2.0
- Added raw query support for Application Insights.
- Add support for Azure Log Analytics with Monaco Editor and intellisense.
- Basic support for Application Insights Log Analytics.
v0.1.2
Fix for long metric names which means that the Azure WebApp Slots metrics now work. #27
v0.1.1
Small bugfix for the query editor when adding a new panel.
v0.1.0
- Variable support for both Azure Monitor and Application Insights
- Support for Azure US Government, Azure Germany and Azure China clouds
- Filter support for Application Insights
- Azure Monitor API version updated and time grain changes implemented. This is a possible breaking change for some dashboards - previously a wider range of time grains was allowed so you might get the following error after upgrading:
Detected invalid time grain input. To fix, choose a valid time grain for that metric.
v0.0.9
- Adds support for the
uniqueaggregation for Application Insights.
v0.0.8
- Adds support for legend formatting with aliases.
v0.0.7
- Adds support for the CosmoDB API.
v0.0.6
- Auto time grain fix.
v0.0.5
- Fix for breaking change in Grafana master to prevent problems in future.
v0.0.4
- Multi-dimensional filtering
- Support for the Microsoft.Sql API and for the Storage API.
v0.0.3
Uses the latest version of the Azure Monitor REST API (2017-05-01-preview). Does not currently change anything for the user but enables new features in the future.
v0.0.2
- Changes legend format for Azure Monitor to
resourceName.metricNameinstead of just
metricName.
v0.0.1
- First version. Can show metrics from both the Azure Monitor service and the Application Insights service. Can combine metrics from both services on the same dashboard. | https://grafana.com/grafana/plugins/grafana-azure-monitor-datasource?src=blog&camp=timeshift_17 | CC-MAIN-2020-40 | refinedweb | 1,622 | 55.24 |
# How we sympathize with a question on StackOverflow but keep silent

On the stackoverflow.com website, we frequently see questions about how to look for bugs of a certain type. We know that PVS-Studio can solve the problem. Unfortunately, we have to keep silent. Otherwise, StackOverflow moderators may consider it as an obvious attempt to promote our product. This article describes a particular case of such a situation that makes us suffer deeply.
The following question: "[Scan-Build for clang-13 not showing errors](https://stackoverflow.com/questions/69592513/scan-build-for-clang-13-not-showing-errors)" asked by kratos from India, made me write this article. This person asks how to look for patterns of the following type:
* writing integer values other than 0 and 1 to a bool type variable;
* virtual functions call in the constructor and destructor.
Here's the code cited as an example:
```
int f1(){
int a=5;
short b=4;
bool a1=a;//maybe warn
bool b1=b;//maybe warn
if(a1&&b1)return 1;
return 0;
}
class M{
public:
virtual int GetAge(){return 0;}
};
class P:public M{
public:
virtual int GetAge(){return 1;}
P(){GetAge();}//maybe warn
~P(){GetAge();}//maybe warn
};
int main(){
return 0;
}
```
To search for errors, kratos tried to use the Clang 13 compiler, but this isn't working.
I don't know whether you can find such errors with Clang or not – didn't study this issue. Most likely, to find errors, you just have to specify the right flag for the compiler.
However, I am tempted to reply something as: try PVS-Studio. Although no – this is not enough to post an answer, but I was eager to add the comment as:
> I can't tell you whether you can search for these errors with Clang, but the PVS-Studio static analyzer finds these errors right away: [an example on the Compiler Explorer website](https://godbolt.org/z/Kx8hfx8en). Try it, maybe it's gonna work :)
The first suspicious pattern triggers the analyzer in two ways at once. Therefore, we have 4 warnings in total:
* 6:1: note: V547 The 'A = a' expression is equivalent to the 'A = true' expression.
* 6:1: warning: V786 It is odd that value 'a' is assigned to the 'a1' variable. The value range of 'a1' variable: [0, 1].
* 7:1: note: V547 The 'A = b' expression is equivalent to the 'A = true' expression.
* 7:1: warning: V786 It is odd that value 'b' is assigned to the 'b1' variable. The value range of 'b1' variable: [0, 1].
And another two messages relating to the virtual functions call:
* 18:1: error: V1053 Calling the 'GetAge' virtual function in the constructor may lead to unexpected result at runtime.
* 19:1: error: V1053 Calling the 'GetAge' virtual function in the destructor may lead to unexpected result at runtime.
Some programmers may find this information useful. Unfortunately, no one will know about this on StackOverflow :(.
First, the answer contains a commercial tool. Moreover, it's **the first question** from kratos.

It may look as if I created a virtual user on purpose, asked a question, and answered it to promote PVS-Studio in a favorable light.
So, I can't really post an answer. StackOverflow moderators may think that it's a stupid spam trick and ban me :). Maybe we asked a question and answered it… At least we should have leveled up our virtual user asking the question… Not creative at all :).
Well, I didn't reply to the question on StackOverflow, but I wrote this little note. Eventually, I feel relieved, and readers enjoy an unusual story from the life of the PVS-Studio team :).
Note. You may tartly say that such a comment promotes a proprietary tool. And StackOverflow must fine/ban us for this. I don't think so. For many developers, it won't make any difference which tool to use. You can use PVS-Studio for free in various scenarios: "[Ways to Get a Free PVS-Studio License](https://habr.com/en/company/pvs-studio/blog/443340/)".
Thanks for your attention. By the way, since we were talking about Clang, I invite you to take a look at a recent note "[Detecting errors in the LLVM release 13.0.0](https://habr.com/en/company/pvs-studio/blog/582492/)". Wish you bugless code! | https://habr.com/ru/post/585270/ | null | null | 770 | 64.71 |
Java - Comments
The Comments are added in programming code with the purpose of making the code easier to understand. It makes the code more readable and hence easier to update the code later. Comments are ignored by compiler while running the code. In Java, there are two ways of putting a comment.
- Single line comment
- Block comment
Single line Comment:
It starts with // and ends with the end of that line. Anything after // to the end of line is a single line comment and will be ignored by compiler.
Syntax
//single line comment. statements; //single line comment.
Example:
The below example illustrates how to use single line comments in a Java script. The compiler ignores the comments while compiling the code.
public class MyClass { public static void main(String[] args) { //first single line comment. System.out.println("Hello World!."); / Java code which is ignored by the compiler while compiling the code.
public class MyClass { public static void main(String[] args) { /*first block comment. */ System.out.println(/*second block comment.*/"Hello World!."); } }
The output of the above code will be:
Hello World!. | https://www.alphacodingskills.com/java/java-comments.php | CC-MAIN-2021-04 | refinedweb | 181 | 68.26 |
UTMP(5) OpenBSD Programmer's Manual UTMP(5)
NAME
utmp, wtmp, lastlog - login records
SYNOPSIS
#include <<utmp.h>>
DESCRIPTION creat-
ed. us-
er logged in, the terminal line, and the hostname are written to the
standard in-
dicates the time prior to the change and the ``{'' character
indicates the new time.
FILES
/var/run/utmp
/var/log/wtmp
/var/log/lastlog
SEE ALSO
last(1), login(1), who(1), ac(8), init(8), newsyslog(8)
HISTORY
A utmp and wtmp file format appeared in Version 3 AT&T UNIX. The lastlog
file format appeared in 3.0BSD.
CAVEATS
The strings in the utmp and lastlog structures are not normal `C' strings
and are thus not guaranteed to be null terminated.
OpenBSD 3.6 March 17, 1994 2 | http://modman.unixdev.net/index.php?page=utmp&sektion=5&manpath=OpenBSD-3.6 | CC-MAIN-2013-20 | refinedweb | 127 | 64.3 |
Looking back to 2 days ago, Adeptus Health Inc (Symbol: ADPT) priced a 3,400,000 share secondary stock offering at $105 ADPT at a cheaper price, might benefit from considering selling puts among the alternative strategies at their disposal. One interesting put contract in particular, is the February 2016 put at the $90 strike, which has a bid at the time of this writing of $9.80. That would result in a cost basis of $80.20 per share before broker commissions in the scenario where the contract is exercised. If the contract is never exercised, the put seller would still keep the premium, which represents a 10.9% return against the $90.00 purchase commitment, or a 19.6% annualized rate of return (at Stock Options Channel we call this the YieldBoost ). ADPT's upside potential the way owning shares would, because the put seller only ends up owning shares in the scenario where the contract is exercised. The chart below shows the one year performance of ADPT shares, versus its 200 day moving average:
Looking at the chart above, ADPT's low point in its 52 week range is $23.88 per share, with $113.702 as the 52 week high point - that compares with a last trade of $112.74.
According to the ETF Finder at ETF Channel, ADPT makes up 2.21% of the SPDR S&P Health Care Services ETF (Symbol: XHS) which is trading higher by about 1.6% on the day Friday.
Top YieldBoost Puts of. | https://www.nasdaq.com/articles/use-options-chance-buy-adpt-29-discount-2015-07-31 | CC-MAIN-2021-17 | refinedweb | 254 | 73.27 |
from random import choice as randomcards
def total(hand):
# how many aces in the hand
aces = hand.count(11)
# to complicate things a little the ace can be 11 or 1
# this little while loop figures it out for you
t = sum(hand)
# you have gone over 21 but there is an ace
if t > 21 and aces > 0:
while aces > 0 and t > 21:
# this will switch the ace from 11 to 1
t -= 10
aces -= 1
return t
# a suit of cards in blackjack assume the following values
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
# > 21:
print "--> The player is busted!"
pbust = True
break
else tp == 21: 17 or 18
while True:
tc = total(comp)
if tc < 18:
comp.append(rc(cards))
else:
break
print "the computer has %s for a total of %d" % (comp, tc)
# now figure out who won ...
if tc > 21: "Thanks for playing blackjack with the computer!"
else tp == 21: | http://forums.devshed.com/python-programming-11/blackjack-code-578885.html | crawl-002 | refinedweb | 163 | 79.13 |
The Sisu project provides a dynamic dependency injection framework that can interact with OSGi services and Eclipse extensions.
The project is currently divided into three codebases:
Sisu artifacts will be made available in the Eclipse download area and published to the Central Repository. The project also plans to provide a P2 update site using Eclipse/Tycho.
Milestones will be published as committer time allows.
Sisu consists of pure Java code and is expected to run on any JVM that supports Java SE 5 or newer.
None of the Sisu deliverables are internationalized, any log and exception messages use English.
API Contract Compatibility:
To comply with Eclipse Foundation requirements, all Sisu Java types/packages will be moved into the
org.eclipse.sisu namespace. An external compatibility wrapper is available for users of Sonatype Sisu.
Source Compatibility:
To comply with Eclipse Foundation requirements, all Sisu Java types/packages will be moved into the
org.eclipse.sisu namespace. While the API will undergo some refactoring and cleanup during the move to Eclipse, only clients that use the Sisu extensions to JSR330 will need to update their imports and make minor code changes to successfully build against the new API.
The refactoring of code into the
org.eclipse.sisu namespace provides an opportunity to remove deprecated code and clean up the API to ease future evolution and to improve usability.
Back to the top | http://www.eclipse.org/projects/project-plan.php?planurl=/sisu/project-info/plan.xml | CC-MAIN-2014-41 | refinedweb | 230 | 54.22 |
Create a new action.
Execute an embedded Python Script.
Use this:
- Code: Select all
import urllib
# Get a file-like object for the Python Web site's home page.
f = urllib.urlopen("")
# Read from the object, storing the page's contents in 's'.
s = f.read()
f.close()
Change the 192.168.15.116 to the IP address of your DirecTV box.
Change "key=power" to any of these:, or enter.
You can also go directly to a channel with this page: ... inor=65535 . That would change the channel directly to 249.
It may not be clean, but its fast and works every time (unlike the IRLinc / Group Commands) | http://forums.indigodomo.com/viewtopic.php?amp=&t=7294&p=44492 | CC-MAIN-2014-42 | refinedweb | 109 | 86.91 |
This blog is created based on a following problem.
A big office supplies company was trying to send out shipment/delivery data information to the carriers based in France. The standard dispatch manifest format for the carriers in France is an EDIFACT based message called INOVERT DISPOR. As you can imagine SAP does not provide this format as a standard EDIFACT message in the B2B adapter.
This means we would need to build one from scratch.
First we needed to get the hold of the DISPOR version 3.2 structure documentation and analyse the data.
This can be found at
After the data has been analyzed we need to find a edifact version that is similar to the DISPOR structure. This is needed because we need a basic edifact message to start from.
In this case any 99+ version of IFTMIN or IFCSUM is sufficient.
In order to create our own custom version of an edifact message we will need to copy the control key of this standard EDIFACT message. A control key uses the indicators to determine how a message is to be processed in the control key list.
After we copy the control key we will need to create message with custom name and version
The options provided are creating a new version of the existing message and totally new message and version.
In this scenario we will create new message and version for DISPOR.
First we need to check if all the fields are present in the copied message structure.
We can do that in the DATA ELEMENTS menu.
In this case there are several fields that don’t exist yet. we can create them using the create data element and providing the correct specification.
Creating a new data element:
After we have created all the missing data elements we need to do the same for the Composites. Also we need to check the existing composites if they contain the correct data elements. Composites simplify administration of the Segments. They consist of single elements combined automatically. This means you can expand the structure very easy and very fast.
We need also to check the status of the fields (mandatory/conditional).
When all the composites are created and checked we then need to create our custom structure segments that are missing from the copied message
In this case we created an ICC segment containing also the custom made data elements.
In case you didn’t notice yet , the best way to build a custom edifact message is by bottom up. When all the data elements , composites and segments are created and checked, it’s time to build the message. You can also create the Segment Groups and add them to the main message.
This is how a customized edifact message looks like:
After the creation of the message we need to export the xsd and import it into SAP PO.
Importing the xsd means we have to create the data type in sap PO with name matching our xsd and the edifact structure.
After that we can map all the necessary fields and activate the mapping.
Here below are the examples of the mappings and output. The scenario is IDOC to EDIFACT exported to a SFTP server.
Mapping:
Mapping Test
Output Result:
This data can now be processed by any DISPOR 3.2 version adapter on the customer’s side.
Thanks Igor!
A truly usfull post.
Appreciate that. ➕ ➕
Hi Nimrod,
I am happy to hear that!
Regards,
Igor
Good Job.
Regards
Stefan
Hi Stefan,
Thanks!
Hi Igor,
Thanks for your blog! Fantastic use of the amazing B2B tool SAP gave us.
Could you please paste here how you populated localejbs/EdifactConverterModule parameters:
edifact.namespace ?
I am asking because when I run B2B test tool my xml gets converted to EDIFACT format.
However, when I run end-to-end ( through receiver communication channel), I am getting null pointer error.
The only tricky parameter seems to be edifact.namespace.
Hi Agnieszka ,
Thanks for your comment!
Can you please send me the screenshots of your error messages?
Regards,
Igor
Dear Igor,
This is very meaningful sharing. I learn it a lot. By the way, I cannot find the path of which the EDI styles generate the XSD file in SAP Netweaver Administrator. Could you please share the path? Thank you for your support in advance.
Many thanks & best regards,
Hubery Yao
Hubery,
This wont be there in NWA its a seperate Addon . Navigate to URL under this you have EDI Content manager where you can get the required XSD.
Br,
Manoj
Thank you Manoj for your quick response, I open the link,but it has error with 404. .My version is 7.4 dual-stack with SP15. I will check the reason.
Many thanks & best regards,
Hubery Yao | https://blogs.sap.com/2014/05/14/creating-custom-edifact-message-with-b2b-adapter-has-never-been-so-easy-before/ | CC-MAIN-2019-09 | refinedweb | 797 | 66.54 |
Build an App with Everything New & Noteworthy in Angular 7
Free JavaScript Book!
Write powerful, clean and maintainable JavaScript.
RRP $11.95
This article was originally published on the Okta developer blog. Thank you for supporting the partners who make SitePoint possible.
Angular 7 was released earlier this quarter and I’m pumped about a few of its features. If you’ve been following Angular since Angular 2, you know that upgrading can sometimes be a pain. There was no Angular 3, but upgrading to Angular 4 wasn’t too bad, aside from a bunch of changes in Angular’s testing infrastructure. Angular 4 to Angular 5 was painless, and 5 to 6 only required changes to classes that used RxJS.
Before I dive into showing you how to build an Angular app with authn/authz, let’s take a look at what’s new and noteworthy in this release.
Upgrade to Angular 7
If you created your app with Angular CLI, chances are you can easily upgrade to the latest release using
ng update.
ng update @angular/cli @angular/core
You can also use the Angular Update Guide for complete step-by-step instructions.
What’s New in Angular 7
There are a few notable features in Angular 7, summarized below:
- CLI prompts: this feature has been added to Schematics so you can prompt the user to make choices when running
ngcommands.
- Performance enhancements: the Angular team found many people were using
reflect-metadataas a dependency (rather than a dev-only dependency). If you update using the aforementioned methods, this dependency will automatically be moved. Angular 7 also adds bundle budgets so you’ll get warnings when your bundles exceed a particular size.
- Angular Material: Material Design had significant updates in 2018 and Angular Material v7 reflects those updates.
- Virtual Scrolling: this feature allows you to load/unload parts of a list based on visibility.
- Drag and Drop: this feature has been added to the CDK of Angular Material.
Bundle budgets is the feature that excites me the most. I see a lot of Angular apps with large bundle sizes. You want your baseline cost to be minimal, so this feature should help. The following defaults are specified in
angular.json when you create a new project with Angular CLI.
"budgets": [{ "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }]
You can use Chrome’s data saver extension for maximum awareness of the data your app uses.
For more details on what’s new in Angular 7, see the Angular blog, coverage on InfoQ, or the Angular project’s changelog.
Now that you know how awesome Angular 7 is, let’s take a look at how to create secure applications with it!
Create a Secure Angular 7 Application
An easy way to create Angular 7 apps is using the Angular CLI. To install it, run the following command:
npm i -g @angular/cli
The example below uses Angular CLI 7.1.0. To verify you’re using the same version, you can run
ng --version.
_ _ ____ _ ___ / \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _| / △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | | / ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | | /_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___| |___/ Angular CLI: 7.1.0 Node: 11.1.0 OS: darwin x64 Angular: ... Package Version ------------------------------------------------------ @angular-devkit/architect 0.11.0 @angular-devkit/core 7.1.0 @angular-devkit/schematics 7.1.0 @schematics/angular 7.1.0 @schematics/update 0.11.0 rxjs 6.3.3 typescript 3.1.6
To create a new app, run
ng new ng-secure. When prompted for routing, type “Y“. The stylesheet format is not relevant to this example, so choose whatever you like. I used CSS.
After Angular CLI finishes creating your app, cd into its directory, run
ng new, and navigate to to see what it looks like.
Add Identity and Authentication to Your Angular 7 App with OIDC
If you’re developing apps for a large enterprise, you probably want to code them to use the same set of users. If you’re creating new user stores for each of your apps, stop it! There’s an easier way. You can use OpenID Connect (OIDC) to add authentication to your apps and allow them all to use the same user store.
OIDC requires an identity provider (or IdP). There are many well-known IdPs like Google, Twitter, and Facebook, but those services don’t allow you to manage your users like you would in Active Directory. Okta allows this, and you can use Okta’s API for OIDC.
Register for a forever-free developer account, and when you’re done, come on back so you can learn more about how to secure your Angular app!
Now that you have a developer account, I’ll show you several techniques for adding OIDC authentication to you Angular 7 app. But first, you’ll need to create a new OIDC app in Okta.
Create an OIDC App in Okta
Log in to your Okta Developer account and navigate to Applications > Add Application. Click Web and click Next. Give the app a name you’ll remember, and specify as a Login redirect URI. Click Done. Edit your app after creating it and specify as a Logout redirect URI too. The result should look something like the screenshot below.
Use angular-oauth2-oidc
The angular-oauth2-oidc library provides support for OAuth 2.0 and OIDC. It was originally created by Manfred Steyer and includes many community contributions.
Install angular-oauth2-oidc using the following command:
npm i angular-oauth2-oidc@5.0.2
Open
src/app/app.module.ts and import
OAuthModule as well as
HttpClientModule.
import { HttpClientModule } from '@angular/common/http'; import { OAuthModule } from 'angular-oauth2-oidc'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, OAuthModule.forRoot() ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Modify
src/app/app.component.ts to import
OAuthService and configure it to use your Okta application settings. Add
login() and
logout() methods, as well as a getter for the user’s name.
import { Component } from '@angular/core'; import { OAuthService, JwksValidationHandler, AuthConfig } from 'angular-oauth2-oidc'; export const authConfig: AuthConfig = { issuer: 'https://{yourOktaDomain}/oauth2/default', redirectUri: window.location.origin, clientId: '{yourClientId}' }; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'ng-secure'; constructor(private oauthService: OAuthService) { this.oauthService.configure(authConfig); this.oauthService.tokenValidationHandler = new JwksValidationHandler(); this.oauthService.loadDiscoveryDocumentAndTryLogin(); } login() { this.oauthService.initImplicitFlow(); } logout() { this.oauthService.logOut(); } get givenName() { const claims = this.oauthService.getIdentityClaims(); if (!claims) { return null; } return claims['name']; } }
Modify
src/app/app.component.html to add Login and Logout buttons.
<h1>Welcome to {{ title }}!</h1> <div * <h2>Hi, {{givenName}}!</h2> <button (click)="logout()">Logout</button> </div> <div * <button (click)="login()">Login</button> </div> <router-outlet></router-outlet>
Restart your app and you should see a login button..
See 10 Excellent Ways to Secure Your Spring Boot Application to see how to add a CSP with Spring Boot.
You might also find Micah Silverman’s PKCE Command Line project interesting.
Limit Access Based on Group for Your Angular 7 App
If you’d like to show/hide components of your app based on a user’s group, you’ll need to add a “groups” claim to your ID token. Log in to your Okta account, navigate to API > Authorization Servers, click the Authorization Servers tab and edit the default one. Click the Claims tab and Add Claim. Name it “groups”, and include it in the ID Token. Set the value type to “Groups” and set the filter to be a Regex of
.*.
Now] } }
JHipster uses JWT authentication by default, but you can switch it to use OIDC for authentication pretty easily (hint: just add
authenticationType oauth2 to
app.jh)..
The sample JDL mentioned uses React for its
clientFramework. Make sure to change it to
angular to use Angular 7..
- Build a Basic CRUD App with Angular 7.0 and Spring Boot 2.1
- Build a Photo Gallery PWA with React, Spring Boot, and JHipster
- Develop a Microservices Architecture with OAuth 2.0 and JHipster
- What is the OAuth 2.0 Implicit Grant Type?
- What is the OAuth 2.0 Authorization Code Grant Type?
If you enjoyed this post, follow us on social media { Twitter, Facebook, LinkedIn, YouTube } to know when we’ve posted other awesome content!
Get practical advice to start your career in programming!
Master complex transitions, transformations and animations in CSS! | https://www.sitepoint.com/build-an-app-with-everything-new-noteworthy-in-angular-7/ | CC-MAIN-2021-04 | refinedweb | 1,416 | 50.33 |
Creating Processes Remotely using WMI
You can use Win32_Process.Create to execute a script or application on a remote computer. However, for security reasons, the process cannot be interactive. When Win32_Process.Create is called on the local computer, the process can be interactive.
The remote process has no user interface but it is listed in the Task Manager. A process created locally can run under any account if the account has the Execute Method permission for the root\cimv2 namespace. A process created remotely can run under any account if the account has the Execute Method and Remote Enable permissions for root\cimv2. The Execute Method and Remote Enable permissions are set in WMI Control in the Control Panel. For more information, see Setting Namespace Security with the WMI Control.
You can use Win32_ScheduledJob.Create to create an interactive process remotely. But processes started by Win32_ScheduledJob.Create run under the LocalSystem account that can confer too much privilege.
Related topics | https://msdn.microsoft.com/en-us/library/aa389769(v=vs.85).aspx | CC-MAIN-2016-30 | refinedweb | 160 | 51.04 |
I helped my students understand the decision tree classifier in sklearn recently. Maybe they think I helped too much. But I think it was good for them. We did an interesting little exercise, too, writing a program that writes a program that represents a decision tree. Maybe it will be useful to someone else as well:
def print_tree(t, root=0, depth=1): if depth == 1: print 'def predict(X_i):' indent = ' '*depth print indent + '# node %s: impurity = %.2f' % (str(root), t.impurity[root]) left_child = t.children_left[root] right_child = t.children_right[root] if left_child == sklearn.tree._tree.TREE_LEAF: print indent + 'return %s # (node %d)' % (str(t.value[root]), root) else: print indent + 'if X_i[%d] < %.2f: # (node %d)' % (t.feature[root], t.threshold[root], root) print_tree(t, root=left_child, depth=depth+1) print indent + 'else:' print_tree(t,root=right_child, depth=depth+1)
Did I do this for MILK a few years ago? I’m becoming an absent-minded professor ahead of my time. | https://healthyalgorithms.com/2015/02/19/ml-in-python-getting-the-decision-tree-out-of-sklearn/ | CC-MAIN-2018-51 | refinedweb | 162 | 70.6 |
WAPDA - HUBCO TARIFF DISPUTE
The sooner the issue is resolved the better it is
By SHABBIR H. KAZMI
Oct 09 - 15, 2000
Once again the much anticipated settlement of WAPDA-HUBCO dispute has eluded the market. The visit of HUBCO officials to Islamabad has been postponed. There are various conflicting news concerning the current situation and reasons for the delay in inking the final agreement. It is very difficult to say what is the real situation. Some of the analysts strongly believe that concluding the deal is not as simple as being portrayed by some circles. There is an urgent need that both the parties should sit on the negotiation table with a firm commitment to arrive at a consensus which is acceptable and mutually beneficial. No party should try to impose its desires on the other party. Whatever has happened is history, though very sad, now and cannot be changed. Both the parties should, trust each other and try to resolve a commercial issue in a commercial manner.
There are several issues which have to be sorted out before the two parties could reach a mutually acceptable solution. The GoP has reportedly accepted the much pressed HUBCO demands, i.e. withdrawal of cases against HUBCO officials, to give HUBCO the right of arbitration. However, the tariff remains the main point of dispute. It must be kept in mind that survival and long-term prosperity of both WAPDA and HUBCO are dependent on economically viable fundamentals.
On top of every thing, besides the tariff itself, the key issue is, will the tariff applicable with retrospective effect? The controversy had started in early 1998 and since then HUBCO has been receiving the amount fixed by the court as an interim arrangement. The Company made a provision of Rs 13.5 billion in accordance with International Accounting Standards for the year ending June 30, 2000. While the shareholders have not received any dividend for the last three years, the amount receivable from WAPDA has been causing serious cashflow problem for HUBCO.
Lately, there were strong indications that the GoP and HUBCO had reached an agreement on the long-standing WAPDA-HUBCO tariff dispute. M. Alireza, Chairman, HUBCO, accompanied by P. Windsor, representing National Power, were scheduled to meet the GoP officials in Islamabad on 6 October 2000. There were reports also that the GoP had agreed to the tariff proposed by HUBCO's major sponsors in the backdrop of their meeting with Chief Executive, General Pervez Musharraf in New York last month.
Reportedly the proposed tariff was based on the same structure as that of AES Lalpir, as demanded by WAPDA Chairman, Lt. General Zulfiqar Ali Khan. HUBCO proposed to reduce its Capacity Purchase Price (CPP) from 4.1 cents/kwh to 3.3 cents/kwh. The CPP includes debt repayment, fixed operations and maintenance charges and return on equity. HUBCO has also agreed to lower the internal rate of return (IRR) from 18 per cent to 14.8 per cent. The GoP also accepted HUBCO's demands of giving it the right to arbitration, withdrawal of criminal cases against its officials and accepting the sanctity of contracts.
According to some analysts the stance taken by WAPDA that only IPPs are responsible for its financial problems is not only incorrect but misstatement of the fact. The real causes of poor financial health are: mismanagement, power theft and its inability to recover overdue outstanding for a long time. WAPDA needs the power generated by IPPs to ensure uninterrupted supply of electricity because it cannot add new power generation facility, be it thermal or hydel, at least for the time being.
Besides, the country needs huge investment for revamping transmission and distribution work. Multilateral lenders have assured financial support provided both WAPDA and KESC are privatized. WAPDA-HUBCO controversy has hampered the whole process of privatization and the ultimate sufferer are consumers who are forced to pay for the inefficiency of the system. A workable option to rationalize cost, as suggested by many sector analysts, is privatization of WAPDA and KESC.
The analysts believe, that there is an urgent need to resolve the issue before the IMF review board meets in November. They also say that the ongoing dispute has tarnished Pakistan's image and adversely affected inflow of foreign direct investment (FDI). The recent reports that National Power is no longer interested in retaining its 36 per cent stake in KAPCO is an alarming situation. Pakistan, already suffering from precarious foreign exchange reserves position cannot afford to payback the cost paid by National Power for 36 per cent shares of KAPCO. Apart from every thing the exit of National Power from Pakistan would have long-term negative effect on flow of FDI into Pakistan.
The details of the agreement were not made public. However, using the reported figures, some analysts projected 2000-01 EPS of Rs 4.80 assuming that the revised tariff would be applicable from July 01, 2001. In case the revised tariff comes into effect from October 01, 2000, the EPS forecast would be lower, around Rs. 4.03.
*As reported by the press.
**currently estimated at 3.6 cents
***Based on tariff model of AES Lalpir | http://www.pakistaneconomist.com/pagesearch/Search-Engine2000/S.E55.php | CC-MAIN-2017-43 | refinedweb | 867 | 54.63 |
lwp_park and lwp_unpark
By user12625760 on Jan 29, 2009
When you have a program that uses the locking primitives mutex_lock() and mutex_unlock and their POSIX equivlients if you truss the process you will often see calls to lwp_park() and lwp_unpark() appering:
These system calls are, as their names imply, the calls that cause the current LWP to stop (park) and allow the current LWP to allow another parked LWP to run (unpark). If we consider the noddy example code:
#include <stdlib.h> #include <unistd.h> #include <thread.h> #include <synch.h> mutex_t global_lock; int global_count; static void \* locker(void \*arg) { while (1) { mutex_lock(&global_lock); global_count++; mutex_unlock(&global_lock); } } int main(int argc, char \*\*argv) { int count; if (argc == 2) { count = strtol(argv[1], NULL, NULL); } else { count = 2; } while (--count > 0) { thr_create(0, 0, locker, NULL, NULL, NULL); } locker((void \*. This can be seen in the truss:
. If this were a real application then there are many D scripts that could be used to help track down your issue not least one like this:
pfexec /usr/sbin/dtrace -n 'syscall::lwp_park:entry /execname == "mutex"/ { @[ustack(5)] = count() }' | https://blogs.oracle.com/chrisg/tags/lwp_park | CC-MAIN-2016-26 | refinedweb | 186 | 58.52 |
Linux
2019-03-06
NAME
pid_namespaces - overview of Linux PID namespaces
DESCRIPTION
For an overview of namespaces, see namespaces(7)..). fail with the error ENOMEM; it is not possible to create a new process).. namespaces..’s idea of its own PID (as reported by getpid()), which would break many applications and libraries..’s PID namespace, rather than the "init" process in the child’s own PID namespace.
Compatibility of CLONE_NEWPID with other CLONE_* flags
In current versions of Linux, CLONE_NEWPID can..
/proc files
Miscellaneous
CONFORMING TO
Namespaces are a Linux-specific feature.
EXAMPLE
See user_namespaces(7).
SEE ALSO
clone(2), reboot(2), setns(2), unshare(2), proc(5), capabilities(7), credentials(7), mount_namespaces(7), namespaces(7), user_namespaces(7), switch_root(8) | https://reposcope.com/man/en/7/pid_namespaces | CC-MAIN-2022-21 | refinedweb | 120 | 50.23 |
In python, we don’t have any specific functions like
random() to generate random values. If you want to generate some random values, you need to import a built-in
random module.
Following is the example of importing a built-in random module to generate the random number.
If you observe the above example, we imported the
random module using the
import keyword and used the
random() method to generate a random number. Whenever you execute the above python program, you will get a random value between
0.0 to
1.0.
Like the
random() method, the
random module has different methods to generate random numbers based on your requirements.
If you want to generate the random integer values between the defined range of values, you need to use
randint() method.
Following is the example of importing a built-in
random module to generate the random number between
2 to
10 in python.
In
randint() method, the two parameters (start, end) are required. Whenever you execute the above python program, you will get a random value between
2 to
10.
Same as the
randint() method, the
randrange() method also will generate the random value between the specified range, but it will accept three parameters (
start,
stop,
step).
The first parameter is to define the starting position and its optional. By default, it will consider
0 as the starting position. The second parameter to define the stop position and its required. The third parameter to specify the incrementation and its optional. By default, it's
1.
Following is an example of using the
randrange() function to generate the random number based on python's defined range values.
The above random module program will generate the random numbers between the defined range values using the
randrange() method.
If you want to generate the same random number when you execute the above program, you need to use the
seed(n) method in the random module. Here, the value
n should always be the same; if you want to change the random value, then change the
n value.
Following is an example of the random module to generate the same random number in python.
The above program will always generate the same random number (
6) between
2 and
10 based on the seed value. If you want a different random value, you can change the value of the
seed() method.
The random module
choice() method is useful to return the randomly selected element from the specified sequence. The given sequence must be non-empty.
Following is the example of using the random module
choice() method to get the randomly selected element from the given sequence in python.
The above random module example will return the result as shown below.
The following table lists the different methods available in the random module to randomly generate the numbers, randomly pick the elements, etc., based on our requirements. | https://www.tutlane.com/tutorial/python/python-random-module | CC-MAIN-2021-21 | refinedweb | 481 | 55.54 |
import "github.com/tychoish/lru"
Package lru provides a tool to prune files from a cache based on LRU.
lru implements a cache structure that tracks the size and (modified*) time of a file.
* future versions of lru may use different time method to better approximate usage time rather than modification time.
cache.go file.go heap.go populate.go prune.go
Cache provides tools to maintain an cache of file system objects, maintained on a least-recently-used basis. Internally, files are stored internally as a heap.
DirectoryContents takes a path and builds a cache object. If skipDir is true, this option does not include any directories, otherwise all directories are included in the cache. When including directories in the cache, lru includes the aggregate size of files in the directory.
NewCache returns an initalized but unpopulated cache. Use the DirectoryContents and TreeContents constructors to populate a cache.
TreeContents adds all file system items, excluding directories, to a cache object.
func (c *Cache) Add(f *FileObject) error
Add takes a defined FileObject and adds it to the cache, returning an error if the object already exists.
AddFile takes a fully qualified filename and adds it to the cache, returning an error if the file does not exist. AddStat returns an error if the stat is invalid, or the file already exists in the cache.
AddStat takes the full (absolute) path to a file and an os.FileInfo object and and constructs the FileObject and adds it to the cache. AddStat returns an error if the stat is invalid, or the file already exists in the chace.
Contents returns an iterator for
Count returns the total number of objects in the cache.
func (c *Cache) Get(path string) (*FileObject, error)
Get returns an item from the cache by name. This does not impact the item's position in the cache.
func (c *Cache) Pop() (*FileObject, error)
Pop removes and returns the oldest object in the cache.
Prune removes files (when dryRun is false), from the file system until the total size of the cache is less than the maxSize (in bytes.)
Size returns the total size of objects in the cache.
func (c *Cache) Update(f *FileObject) error
Update updates an existing item in the cache, returning an error if it is not in the cache.
type FileObject struct { Size int Time time.Time Path string // contains filtered or unexported fields }
FileObject is a simple struct that tracks data
func NewFile(fn string, info os.FileInfo) *FileObject
NewFile constructs a FileObject from its pathname and an os.FileInfo object. If the object is a directory, this method does not sum the total size of the directory.
func (f *FileObject) Remove() error
Remove deletes the file object, recursively if necessary.
func (f *FileObject) Update() error
Update refreshs the objects data, and sums the total size of all objects in a directory if the object refers to a directory.
Package lru imports 9 packages (graph) and is imported by 1 packages. Updated 2017-04-21. Refresh now. Tools for package owners. | https://godoc.org/github.com/tychoish/lru | CC-MAIN-2018-26 | refinedweb | 509 | 64.41 |
Hi,
i have an ear application containing one ejb and two war modules.
i wrote a bootstap class in order to start some scheduling:
@Name("bootstrap") @Scope(ScopeType.APPLICATION) @Startup public class Bootstrap { @In EntityManager entityManager; @Create public void start() throws Exception { Events.instance().raiseTimedEvent("activationEvent", new CronSchedule((Long) null, "0 0/1 * * * ?")); } @Destroy public void stop() { } }
Does it fire twice even if it's only included in one module? If it is really the same instance, you could add a boolean fired flag and something like
if (!fired) { Events.... fired = true; }
You are right, but fired should be declared static.
Thanks
V. | https://developer.jboss.org/thread/141057 | CC-MAIN-2017-39 | refinedweb | 103 | 57.87 |
When the Fabric team at Twitter wrote their new iOS app, they turned to Swift. Why? Javi Soto walks through their decision, and tells why they picked a language that emphasizes stability and maintainability & supports dependency injection, code generation, MVVM, and error reporting.
Introduction (00:00)
I love what Realm does for the Swift community by hosting these meetups. I am humble that I get to speak here. [Ed. note: Thanks Javi! We are honored to host such illustrious speakers! 😊]
I am Javi. I am originally from Madrid, Spain, but I have been working in the Bay Area for around four years. Previously I worked at Pebble, the Kickstarter-funded smart watch company, on the iOS app. I started writing Swift when it first came out and last year my brother (Nacho, sitting in the audience) and I released our first app fully written in Swift. It was Swift 1.1 at the time, and it was an Apple Watch app to follow Chad’s broadcasts. Now I work in Twitter in San Francisco on the Fabric team.
I ❤️ talking about Swift. Building the (recently launched!) Fabric.app was fun. I simply wanted to share some of the things that I did differently when building this app (compared to all the apps that I built in the past).
What is Fabric.app? (02:01)
Fabric.app is a set of tools for mobile developers. The two main ones are Crashlytics and Answers. We set out to build a mobile app because we realized that sometimes important issues do not happen when you are at your desk, and many of us like to be able to keep an eye on how our app is doing no matter where we are.
This is what the Fabric dashboard looks like on the web. (See the slide above. 👆) We show you (a ton of) realtime and historic information about the usage and stability of your app. But we did not want to just replicate what you can see here in the mobile dashboard: we wanted the app to shine on mobile. And one of the great things that we can do on mobile is notifications. Fabric.app is able to alert you if there is something wrong about your app (e.g., the overall crashfree users are dropping very quickly). We also put attention into how noisy notifications can be: we offer fine-grained controls on how many notifications you want to receive, and you can even mute notifications for a couple hours or a couple of days (nobody wants to receive notifications about crashes when you are on vacation!).
Tools (03:35)
Dependency management (03:39)
There is much discussion recently in the iOS community about how many third-party libraries you should use in your app, or whether you should use any at all. In a big team, with the resources to solve every problem needed to build an app, maybe you want to minimize the number of external dependencies. But the Fabric app had a total of one engineer (for most of its development time), and it also started as a proof of concept. At the beginning we wanted to prove that Fabric.app could offer value, and we wanted to prove that quickly. We did not want to implement a networking library to prove that. The initial goal was to avoid reinventing the wheel. These are some of the problems that, regardless of the complexity in solving them, I did not want to spend additional time solving. Especially because many people have already done a fantastic job in solving them. The iOS open source community is fantastic. There is great code out there.
The Fabric.app uses both CocoaPods and Carthage. Using more than one dependency management system is not recommended. They will not be able to see each other’s dependency graph, and you may end up with both resolving the same dependency (and that added to your app twice). However (if you know what you are doing) both of them have advantages. I like both of them for different reasons.
CocoaPods (05:27)
CocoaPods is widely adopted. The libraries are easy to integrate because it modifies the Xcode project for you. But more importantly, it is easy to add a dependency only on debug builds. We used it to add some tools during development, but we did not want to ship it in the final binary. You could think: CocoaPods does everything and mostly every library supports CocoaPods, we could have stopped there. Why did we decide to add Carthage on top of that? The reason is: compilation speed. The Swift compiler is not as fast as the Objective-C compiler. And while it may get better, I believe that this may always hold true. Pre-compiling code that you are not constantly changing may always be a good idea. Pre-compilation of some of the libraries speeds up our total app compilation time.
Unfortunately there have been Xcode- and LLDB-related issues to using pre-compiled libraries that were compiled outside of your Xcode project for over a year. There are some trade-offs. In any case, in the near future I cannot wait until I can move over to the Swift Package Manager. I cannot wait to see how the Xcode integration turns out.
Interface Builder (07:01)
I am a big fan of Interface Builder. There is little layout code in the Fabric.app. Only some views must dynamically create some constraints, and we use the Cartography library for that because it simplifies the syntax.
Auto Layout (07:22)
Being able to set up Auto Layout constraints in Interface Builder reduced the amount of UI code. Despite all the complexities, one of the biggest wins of Auto Layout is self-sizing table view cells, which finally work well in iOS 9. In the pre–Auto Layout world, apps with multiple table views or multiple types of cells with dynamic heights require a non-trivial amount of manual and sizing layout code. And this is horrible for quick iteration, when you are just trying to add new views and move things around.
Get more development news like this
That is not to say that Auto Layout is perfect or easy to use (e.g., see the screenshot: if you plug in your phone to your Mac, look at the logs that Springboard is outputting). Not even Apple can get this right. It is really hard. Bit I believe it is worth it, for the most part.
Storyboards (08:28)
The first release of the Fabric.app, version 1.0, shipped with most of its UI in one storyboard. I started building the app with them because, honestly, I had not done it before and I wanted to give them a try. When my co-worker Josh joined the team, we quickly realized that it was not going to work well with more than one committer. In version 1.1 we moved everything over to separate XIB files.
UIStoryboard (09:10)
Besides the well-known problems of putting all of your UI in the same file, I would stay away from storyboards.
This is the only API available to instantiate a view controller from a storyboard. Even if you are using segues, you are also using this API. This is what it looks like in a hypothetical view controller that you would instantiate:
class UIStoryboard { func instantiateViewControllerWithIdentifier(_ identifier: String) -> UIViewController }
We instantiate it and then we pass values to it. We set up a bunch of properties on it.
What does this look like on the view controller itself? You are going to end up with implicitly unwrapped optionals (and I am sure you do not like implicitly unwrapped optionals) - this means you cannot do proper dependency injection. For example, in this method we have no guarantee that other required parameters (e.g., this user session one) will be set at runtime.
let vc = mainStoryboard.instantiateViewControllerWithIdentifier("ApplicationOverviewID") as! ApplicationOverviewVC vc.userSession = ... vc.applicationID = ...
At that point, when this view controller is on the screen, we can either crash if we read that implicitly unwrapped optional and it’s nil, or we can leave the app broken if we check for nil and then do nothing (because there is not anything useful that we can do in many cases).
final class ApplicationOverviewVC { // I hope you like "!"s... var userSession: UserSession! var applicationID: String! func viewDidLoad() { super.viewDidLoad() self.userSession.foo() } }
I did write a hack in Objective-C that shipped in this 1.0 version, which worked around this issue. Interestingly, I had to do it in Objective-C because Swift would not let you do that (that tells you how much of a hack it was). But it also involved implicitly unwrapped optionals, so it was not safe either. If you are curious about it I can share the gist.
This is what I think view controllers ideally look like. The API in this view controller makes explicit to its user which parameters are required. And not providing a required parameter results in a compile-time error. Another benefit is that members can now be
let constants - it also simplifies implementation because we do not have to worry about the values changing after initialization.
final class ApplicationOverviewVC { let userSession: UserSession let applicationID: String init(userSession: UserSession, applicationID: String) { self.userSession = userSession self.applicationID = applicationID super.init(nibName: ..., bundle: ...) } func viewDidLoad() { super.viewDidLoad() // Compile-time guarantee of object fully initialized self.userSession.foo() } }
No storyboards == better code.
fastlane (11:19)
I love fastlane. 💖 We use it in the app and we automate many tasks: automatically bumping the version build numbers, creating tags, building for beta app store, taking the screenshots, uploading the screenshots. I heavily recommend it, it saves us time during development and, even after we shipped the first version, continues to save us time.
The fastfile, which is where the configuration goes for the different tasks that we automate, is open source in this fastlane example we built.
ReactiveCocoa (06:46)
Fear not, I am not going to cover ReactiveCocoa. I encourage you to watch the talks that I have given previously at Swift Summit if you are interested in that topic. I wanted to mention that it plays a big role in the architecture of the Fabric.app.
I want to show one tiny example of how, with ReactiveCocoa, we are able to reuse and compose logic, in an easy way. In this example, we have created extension methods for ReactiveCocoa and this code sets up an asynchronous task which mutes all notifications in your account. By calling this method that we implemented on that task, it allows us to make sure that this request continues, even if the app is backgrounded.
self.accountService.muteAllNotifications(untilTime: date)
The code to implement this is written once and can be reused in any asynchronous task around the app. That is one simple call out to ReactiveCocoa.
self.accountService.muteAllNotifications(untilTime: date) .continueWhenApplicationIsBackgrounded(taskName: "Muting notifications")
Architecture (13:25)
It is hard to describe in slides what the overall architecture of an app looks like, but I am going to mention a couple of things. Based on my past experience, I decided to take a pragmatic approach with the Xcode setup. Ideally I would like to split the code base into small isolated frameworks. But this introduces a huge amount of complexity in your Xcode setup. For that reason we separated most of the business logic into one single
Fabric API.framework. The idea behind this is to make a framework that does not depend on UIKit.
Fabric API.framework is, for the most part, all the networking and data models that the app needs to talk to the Fabric backend. It could be reused, perhaps, in a different architecture or platform.
Multiple screens in the Fabric.app are
UITableViews, and I wanted to cover how I handle that to reduce the amount of boilerplate. There is nothing hugely novel, the main purpose was to avoid massive view controllers. The pattern that I used could be called MVVM. Although I do not strictly follow it, I have taken inspiration from sources I read online. We put all the interesting logic that powers each screen in the view model. This keeps the view controller thin. Also, this view model makes the necessary network requests to pull the data needed for our particular view, and combines all of them into one struct. The API that it exposes is an observable view into that struct, that changes over time as the requests finish and then can be observed by the view controller.
GenericTableViewDataSource (15:43)
But I was doing the same thing over and over: I was observing that struct and updating the contents of that table view. I came up with this abstraction. Many of the table views update asynchronously, as those requests finish in the background, and they also show different types of data in the same screen.
protocol TableSectionType { associatedtype AssociatedTableRowType: TableRowType var rows: [AssociatedTableRowType] { get } var title: String? { get } } protocol TableRowType { }
This is some of the code that I wrote to generalize this. First, I started with two protocols to represent types that are sections, and types that are rows. A section is something that can return an array of rows and an optional title.
I created this data source that I can instantiate with the few things required to power one table view.
final class GenericTableViewDataSource<Elements, SectionType: TableSectionType, RowType: TableRowType where SectionType.AssociatedTableRowType == RowType, SectionType: Equatable, RowType: Equatable>: NSObject, UITableViewDataSource
In the implementation of this
GenericTableViewDataSource, I can implement once all the logic to diff the changes from two snapshots of the data in the view, and update a table view with animations, only updating the rows and sections that changed. And this is what it looks like when you implement one of those table views.
enum ProjectIssueRow: TableRowType, Equatable { case Loading case NoIssues case ErrorLoadingIssues case ProjectIssue(Issue) } return GenericTableViewDataSource( tableView: tableView, tableViewData: observableProperty, // Observable<Elements> computeSections: { elements in ... }, /// Pure function from `Elements` to `[SectionType]` configureRow: { row, indexPath in ... } /// Function from `RowType` to `UITableViewCell` )
You can implement your own type for a row, and we have a few different cases. For example, we can have a loading row; this is for a new feature that we just shipped in version 1.2 where we show you all the issues in your application. You need to pass the table view, the table view data, which is the observable property, using ReactiveCocoa. And then two important closures. The first one is a pure function that sets up the sections and rows that must be shown given a current state of the data. If the requests are still loading, it can set up a row with a spinner, if a request is failed it can show the appropriate error row. Lastly another closure that, given a row, returns a cell. I will show below how we easily dequeue table view cells in a type-safe way. If you want to see more of this code, I will be happy to share some of it online.
Better with Swift (18:08)
I want to mention three things that I love about Swift that were a huge help in building the first big app that I worked on in Swift after years of building apps in Objective-C: nullability, type-safe JSON parsing, and code generation.
Nullability (18:26)
Ayaka (who is sitting in the audience), wrote this great Tweet (If you do not follow her I recommend it: she has great Swift content and has given great talks):
Optionals are great because we can make things non-optional.
It is not simply a philosophical idea. Thanks to this idea, in Fabric.app we can prove things at compile time. And this eliminates the need to add verbose and redundant tests (and allows me to sleep better at night).
I want to show two examples. The first one has to do with user authentication. I want to show some abbreviated and simplified code that powers this screen. It is the list of apps in your account. Let’s look at this view controller.
final class ApplicationListViewController: BaseFabricTableViewController
It is the first screen that appears after you log in, and it displays the list of apps in your account. For this we need to access some object that encapsulates this user session. This is an oversimplified version of what that could look like. In my experience, this is a very common approach to solving this, using a global accessor. We have user session class and we could have a static method or var, it is a mutable singleton. But the problem (and Swift makes you realize that very quickly) is that property
UserSession.currentUserSession must return an optional because, before the user logs in, there is no user session.
final class ApplicationListViewController: BaseFabricTableViewController { override viewDidLoad() { super.viewDidLoad() let session = UserSession.currentUserSession if let session = session { session.requestApplications()... } // or... session!.requestApplications()... }
When we get to this viewDidLoad() method and we get the user session, what do we do? Do we conditionally unwrap this user session, or do we use an exclamation mark? None of the two options are great. One would lead to the screen being broken, because in the
else case we cannot really do anything useful. This screen was not meant to be shown if you are in a locked in. It would essentially leave the app broken. And in the other one, it leads to a crash. That is obviously not great. And you could think, in the code outside of view controller we know that this is not presented before you log in, we are safe. But, are we safe with this? There could be a risk condition in the code that sets that
currentUserSession property and then presents the view controller. This could definitely go wrong.
final class ApplicationListViewController: BaseFabricTableViewController { init(viewModel: ApplicationListViewModel) } final class ApplicationListViewModel { init(fabricAPI: AuthenticatedFabricAPI) } public final class AuthenticatedFabricAPI { public init(authResponse: AuthResponse) } public final class AuthResponse { let accessToken: String }
This is how I strongly recommend to approach this problem. In this code the view controller needs a view model, which will be in charge of making the network requests. The view model has to be instantiated with a not null (and that is important)
AuthenticatedFabricAPI.
AuthenticatedFabricAPI itself can be instantiated without an
AuthResponse struct, which itself needs an
accessToken, that is also not null. This means that we can prove, at compile time, that this view controller (which shows user data) can not be presented in this screen without first acquiring a user session and an access token to make authenticated requests. And that is great.
Let me quote Ayaka again:
Optionals are great because we can make things non-optional.
In the code above, nothing is optional. And this gives us a guarantee that things that are required will be present at run time.
Let’s look at that in a slightly different example. This is a recent development (something that I improved after I kept making the same mistakes over and over). Let’s look at the same view model again:
final class ApplicationListViewModel { var applications: [Application]? }
It exposes this
applications property that changes over time, and it is an array of application values to indicate that we may be in a state where the request has not yet finished. It is an optional array. If it is nil, it means that we have not finished the request yet. How can the view controller tell the request finished but failed? Will there be an empty array or will it be nil too? I am sure most of you think that nil is a better answer to that question but, for some reason in the past I had a different opinion and then I was confused about it. I think the underlying problem is the lack of explicitness; we are trying to represent many possible cases just using one optional. And that can be error prone. This is what I came up with:
enum DataLoadState<T> { case Loading case Failed case Loaded(T) } final class ApplicationListViewModel { var applications: DataLoadState<[Application]> = .Loading }
It is not rocket science. 🚀 I took advantage of Swift enums, which are fantastic to represent values that can take only one of a finite set of forms. In this case we can be loading, have failed to load, or loaded data. Optional only has two cases and we wanted three; the UI can show the user whether we are loading, we have failed and we want to show an error, or that we have loaded successfully but we have an empty array of applications (we can tell that case very explicitly). When we read the applications variable, we can thus know if it is loading. And I am not saying that this is a great API and you should adopt it, but it simplified some of the code that I was writing that had to deal with this, making it clearer, safer, and harder to make a mistake.
Type-Safe JSON Parsing (24:47)
Do not worry: I am not introducing a new JSON parsing library (there are enough already!). Let’s look at a couple of JSON parsing anti-patterns.
public struct Application { public var ID: String? public var name: String? public var bundleIdentifier: String? public mutating func decode(j: [String: AnyObject]) { self.ID = j["id"] as? String self.name = j["name"] as? String self.bundleIdentifier = j["identifier"] as? String } }
This is a very simple way of doing JSON Parsing. We can make all the members of our struct optional and when we parse we just set the ones that are present in the JSON dictionary and with the right type. These can’t crash, since we are checking the types, but we end up with a struct where some things may be nil. And this is less than ideal because, whenever we are implementing any part of the app that interacts with this struct, we need to constantly unwrap values. That means handle the case where some of them are nil, and it is obviously not clear what the best answer is in that case. It is also cumbersome. Remember, optionals are great because we can make things non-optional. Having to handle nil everywhere is not great.
This is an improvement, another very common way of doing JSON parsing. We change to not having optionals instead of a struct, and we have a static function that returns an optional application. If parsing any of the fields failed, we return nil. And this is already better than what we had before. We do not have to deal with nil members.
public struct Application { public let ID: String public let name: String public let bundleIdentifier: String public static func decode(j: [String: AnyObject]) -> Application? { guard let ID = j["id"] as? String, let name = j["name"] as? String, let bundleIdentifier = j["identifier"] as? String else { return nil } return Application( ID: ID, name: name, bundleIdentifier: bundleIdentifier ) } }
But here is what is wrong with this code: if we fail to parse some of the fields, we have no way of knowing exactly what went wrong (e.g was a key missing, was the wrong type?). In the Fabric app we use the great Decodable library.
Code Generation (27:28)
Here is a snippet of code from the Fabric app:
import Decodable /// public struct Application: Decodable { public let ID: String public let name: String public let bundleIdentifier: String public static func decode(j: AnyObject) throws -> Application { return try Application( ID: j => "id", name: j => "name", bundleIdentifier: j => "identifier" ) } }
There are MANY great JSON libraries, and I do not particularly recommend this one. But I do advocate for using a library that allows you to create your model structs from JSON in a typesafe way. Detailed errors when we fail parsing is where Decoable excels. During development this saved us time that we did not need to spend debugging. And we are able to get that for free without sacrificing the complexity of the code that we needed to implement.
I want to show another cool tool that we used in the Fabric app to increase our confidence that every time we build, things are going to work. When Swift came out, there was a huge emphasis in safety. However, there were a couple of things that were unsafe. I refer to them as string typing.
/// Swift < 2.2 UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: Selector("buttonTapped")) // Swift 2.2 UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(ViewController.buttonTapped))
One of them was creating selectors. In Objective-C we (at least) had the
@selector syntax, but in Swift it became worse than it used to be in Objective-C. Thankfully this was fixed in Swift 2.2, and now we have the new
#selector syntax, which verifies at compile time that we are creating a valid selector that exists in that class.
This is another example of string type API:
super.init(nibName: "ViewControllerNibName", bundle: nil) let nib = UINib(nibName: "NibName", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: "ReuseIdentifier") let cell = tableView.dequeueReusableCellWithIdentifier("ReuseIdentifier", forIndexPath: indexPath) as! MyTableViewCell let image = UIImage(named: "ImageName")!
Instantiating view controllers, getting nibs, registering nibs with cell reuse identifier, getting images from the bundle: this is incredibly fragile. As the number of types of cells in your application increases, especially if you want refactor any part of your app, the chances that something will break are high.
R.swift (29:56)
In the Fabric app we use this library called R.swift. This is a snippet from our open source fastfile (see slides).
Whenever we add a nib to our application or make any other change, we call in our command line
fastlane code_gen, which calls into R.swift and this automatically generates an
R.generated.swift file that contains:
- references to nibs
- reuse identifiers from cells
- images in the asset catalogs, and other file names
What does this enable? What does this look like when we use it?
super.init(nibResource: R.nib.myViewController) class MyTableViewCell: UITableViewCell, ReusableNibTableViewCell { /// This will even fail to compile if it's not the right cell static let nibResource = R.nib.myTableViewCell } tableView.registerReusableNibCell(MyTableViewCell) let cell = MyTableViewCell.dequeueFromTableView(tableView, indexPath) let image = R.image.imageName
These are some example of lines of code that use that, some using helper APIs that I wrote to simplify that code. But it is all powered by having those strings auto-generated and assigned to constants that we can reference statically. Here we get compile-time verification for the names of the nibs, reuse identifiers, image names, etc. And this is fantastic, I would not be able to go back to hardcoded identifier strings anymore. One cool thing with cells: I got it to even verify that the nib resource that I was returning matched the type of the cell.
Error Reporting (30:42)
Often when we write code we call APIs that can fail and report an error. We looked at an example with JSON parsing, but this is another one:
do { try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil) /// ... } catch { print("Error: \(error)") }
Say we are calling into this Foundation API that can throw an error. Often when we call into this API and get an error, we write this code that maybe will show an alert to the user. But often we just print it to the console and move on because we do not have a better thing to do. This is basically what I have done for years. But you always wonder, is this happening in production? And in this code it is not clear if we have something that we can do to prevent this error or work around if it happens, but it could be caused by some other code in your application. It could break in some version of the app, and we would have no way of finding out. Imagine that your app was crashing in production and you could not find out because you did not have a crash reporter. This is the state for all other types of errors that are non-fatal, they will not make your app crash but it could potentially be leading to a less-than-optimal experience for the user. This is why I was really happy when Crashlytics released the logged errors API:
do { try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil) /// ... } catch { Crashlytics.sharedInstance().recordError(error, withAdditionalUserInfo: userInfo) }
Just one line of code (very similar to
This is a real example of what that would look like in the Fabric app (see slides). For a JSON error, we can see that some JSON was a key (called
stability) that was missing from some JSON. I really encourage you to try this out. If you want to ask any questions about any part of the presentation or the application, we are pretty open about it.
If you are curious about how we build something please feel free to reach out to me on Twitter or send an email ([email protected], [email protected]).
Thank you!
Questions? (33:16)
Q: I was curious about your approach with view models. I am also a fan of view models, but I do not know what is the preferred way of implementing them. One thing that I like is that when I use a view model, I prefer to use pure simple object in the language, and I noticed that you used a very complex object such as an API. What is your consideration about that, because it makes a bit harder to test, because maybe you need now to mock an object to make a test?
Javi: I will be honest, we are not testing any of the view models on the application, we are testing some of the code that the view models themselves go into. But it is true, we are passing that
AuthenticatedFrabricAPI object into the view model. If you wanted to test that, you would have to make that a protocol, you can create a fake version of it, it is definitely a challenge, especially in Swift where maybe you cannot subclass that. I do not have a great answer, but I think if you keep your objects dumb and the API surface clear, it is easier to pass something that looks like the real object and does not send any requests. Another thing that we do when we want to mock a network request, they are not unit tests, but we do mock the network request using OHHTTPStubs. We let it go through all the networking code, and capture the request before it hits the network. That is another approach.
Q: Great talk, my question is how do you handle preconditions in the app? I think this might not be very common, but sometimes you have things that you may want to assert, but if the app goes to a wrong state, it might crash in production. How do you handle that conflict?
Javi: It is challenging, I am personally of the opinion to leave certain asserts and nils in production, and I used to ship with more assertions, but in Swift what I think ended up happening is there are more things I can verify at compile time. For example one of the things I would assert always in Objective-C every method that I wrote would have
NSParameterAssert to verify some objects that are required are not nil. In Swift I do not have to do that. And another thing was if there is an error or something that it is a condition that should not happen, I used to crash for that. Now I have the option of reporting that error, and at least learning about it, and not making the app crash. But if it is going to leave the app completely broken, I sometimes prefer to crash. I cannot come up with an example of that in the Fabric app, and then we have a couple of assertions that are only enabled in debug that verify that some method is called on the main thread, you know sometimes threading can get complicated, and you can accidentally call something on a background thread and you know that that hits the UI. There are a couple of those. Yes, there are not a ton of assertions, I think I was lucky that I was able to do things at compile time, for example with code generation, I do not have to assert if casting a
UITableViewCell returns me the wrong class, that always works.
Q: Great talk (like everyone said). I noticed in your view model you said you had a mutable changing property, but you also said you used ReactiveCocoa. I was wondering, if you could speak to why you did not make that an observable as well.
Javi: Let me go to the slide that I think you are referring to, this is fake code. I did not want to use ReactiveCocoa syntax, but using
var makes it clear that that is going to change over time, the real code would be
let, and any property of any application. Internally there is a mutable property, but that one is private, only we control our rights to it, and any property is an immutable view into the mutable property.
Q: I just wanted to ask about the graphs, what are you using to do the graphs?
Javi: I did not mention them at all. We used this library called JBChartView.
Q: I have a couple of questions about the non-fatal crashes, I missed the announcement of this feature, is that being reported even if your particular app does not crash?
Javi: Yes. It looks like a crash - it will keep track of stack trace, but they are sent as a different type of an event even if it does not crash. You can send as many as you want as the app is running.
Q: Cool. Please publish the Objective-C hack for Storyboards, I am curious because I had a couple of things on my own to write.
Javi: I will tweet about it.
Q: …and table view, I am not sure are you supporting iPads, or are you planning to? Because adaptivity and out of sizing and it just does not yet work for us for some reason. Javi: I am not super excited about it either. The app is iPhone only, we figured that most people would be using an iPhone and it is definitely a lot of complexity to support both. We decided to ship faster. I cannot speak about the plans to support or not iPad, but it will. I do not know how well the current setup with nibs will help, because it also depends on how different you want to make your iPad be. If you just want to make it bigger, I guess you know I can make that compile in five minutes. I do not know how well it will look.
Q: Have you tried it with collection view cells because that part does not work for us pretty much. Javi: Yes, I guess I have been using table views for so long that I am biased towards that. I have been running into some issues with table views, and I have been wondering maybe I should try with collection views, and I can work around those issues. Maybe one day I will trade up.
Q: Cool and the last question was, you mentioned that by passing the API clients to view controllers, you can make sure that is authenticated, how do you get it secure of the fact let’s say token expired while you have several controllers in the stack pushed on top of each other, and then how do you propagate this information back through? Javi: That is a really good question, it is tricky to do, and I will tell you how we did it, I do not know if it is the best way, or if there is a better way, I would have to learn about it. It was challenging to do. One thing is that that API client is shared around the app, which is maybe less than ideal. And it handles refreshing the token itself. And it does it in its own serial queues. If there are requests coming in, they will wait until the refresh happens. If your controllers do not have to worry about that, as long as they have an authenticated Fabric API object, that has a token, even if it is invalid at the time that you created it, it will be refreshed.
Q: We found that creates another issue, that is basically we tried to refresh it, let’s say once or twice, but then if credentials, if we banned an account, it will not succeed at all? Do you cover that case?
Javi: No, but my idea, when we probably fix that, was to detect that case like if we were getting a bunch of
401s in a row, pipe that somewhere that will log you out. And what we are doing when you click on logout, I took a very simple approach where I tear everything down. I changed the root view controller of the window, which de-allocates the view controller that is currently there and I allocate the login screen, and that is what is on screen we could do that.
About the content
This content has been published here with the express permission of the author. | https://academy.realm.io/posts/slug-javi-soto-building-fabric-in-swift/ | CC-MAIN-2019-43 | refinedweb | 6,282 | 63.19 |
1. Ring:bit Python Samples
1.1. Add Python Documents
Download and unzip the package: EF_Produce_MicroPython-master Go to Python editor
For programming, we need to add the file of Ringbit.py. Click Load/Save first and again with Show Files(1), choose “add file” to get to the download page to find the file folder of EF_Produce_MicroPython-master, then add Ringbit.py.
1.2. Sample Code
1.3. Project 01: Drive at full speed
from microbit import * from Ringbit import * RB = RINGBIT(pin1,pin2) RB.set_motors_speed(100,100) # Set the speed of both motors
1.4. Result
The speed of both wheels is 100, the car drives at full speed.
1.5. Project 02: Obstacle-avoidance car
from microbit import * from Ringbit import * RB = RINGBIT(pin1,pin2) while True: i = RB.get_distance(0) if i>3 and i<30: RB.set_motors_speed(-100, 100) sleep(500) else: RB.set_motors_speed(100, 100)
1.6. Result
The car changes its direction immediately if the ultrasonic sound sensor detects any obstacles.
1.7. Project 03: Line following
from microbit import * from Ringbit import * RB = RINGBIT(pin1,pin2) while True: i = RB.get_tracking() if i == 10: RB.set_motors_speed(10, 100) if i == 1: RB.set_motors_speed(100, 10) if i == 11: RB.set_motors_speed(100, 100)
1.8. Result
The car runs along with the black line. | https://www.elecfreaks.com/learn-en/microbitKit/ring_bit_v2/ring-bit-python.html | CC-MAIN-2022-21 | refinedweb | 221 | 69.79 |
Imagick is a native PHP extension to create and modify images using the ImageMagick API. The name causes some confusion as people think that ImageMagick and Imagick are the same thing, however they aren't. You can use ImageMagick without Imagick but you need both Imagick and ImageMagick installed to run it within your PHP code.
You can check with PHP code wheter the Imagick extension is installed or not using:
<?php if (!extension_loaded('imagick')){ echo 'imagick not installed'; }
Or just errors in your code that implements Imagick will tell you ... :
Attempted to load class "Imagick" from the global namespace. Did you forget a "use" statement?
Class 'Imagick' not found
In XAMPP for Windows, Imagick isn't built-in, therefore is up to you its installation and implementation. If you have already searched previously how to install Imagick in XAMPP to make it work, and you just can't do it, you're probably out of bounds and you want to kill yourself.
Fortunately, in this article you'll find the definitive installation of Imagick for XAMPP in Windows.
Pre-installation notes
We need to mention that the installation of Imagick is not easy (can be a little confusing) and you may get errors during the installation if you don't follow carefully every step by step. Besides, you need to know the following information about your PHP distribution:
Note: according to the version of XAMPP that you use, these values can vary.
You can get those values with the
phpinfo() function of PHP executing this function within an empty script:
<?php phpinfo();
Once you know the values, these will instruct with files with which architecture you need to download from all the following steps.
Note: don't forget neither to execute every setup with administrator rights.
1. Download and install ImageMagick for Windows
Navigate in your browser to the Downloads area of the website of Imagick and scroll to the Windows zone. ImageMagick runs in almost every version for Windows (from Windows server 2009, XP to Windows 10), now from this list is important to download the latest available version with
X86 architecture and DLL version because that's the architecture that XAMPP uses (normally, if not refer to the PHPINFO and download the correct version, e.g
ImageMagick-<version>-Q16-x86-dll.exe):
Download the executable and wait. prompt executing (that should print the version in the console):
magick -version
2. Download Imagick for PHP
Now navigate to the Imagick package in the PECL website here and select the DLL version from the latest available version (in case you've downloaded an older version of ImageMagick then download a version that accepts your version):
Then a new window will load, in this page scroll to DLL List and click on the right version for your PHP version with correct architecture (of XAMPP not your operative system) and the Thread Safe in case that it's enabled in your distribution (Refer to phpinfo to know wheter your php distribution uses Thread Safe or not):
This will start the download of a zip file "
php_imagick-<version>-<thread-safe-or-not>-<php-compiled-version>-<architecture>.zip". From this
.zip you will need to extract only the
php_imagick.dll file. Copy
php_imagick.dll file and paste in the
php/ext folder inside your xampp installation path (tipically
C:\xampp\php\ext):
Then, proceed to enable the extension in your
php.ini file by adding the following line:
;;;;;;;;;;;;;;;;;;;;;; ; Dynamic Extensions ; ;;;;;;;;;;;;;;;;;;;;;; ; Add the following line where the other extensions are loaded extension=php_imagick.dll
Now the extension is loaded, but Imagick still won't work as it won't even be recognized as an extension if you check the phpinfo file because we need to load all the methods and the binaries that you can retrieve from the next step.
3. Download required Imagick binaries
At this point you may be asking to yourself, really dude ? 3 different downloads? The problem with Imagick is that there are a lot of builds from different sources and if you don't download and install the right ones, it wont work or it will be loaded but if you check the Imagick extension (later, not yet) in phpinfo you'll see :
ImageMagick number of supported formats: 0
That's why you need to follow the steps as mentioned, otherwise you won't make Imagick to work. To prevent any implementation error, the binaries needs to come from the same source, in this case
windows.php.net. To download the required binaries, navigate to PECL Deps here and search in the list for Imagick:
Download the version that matches with the architecture of xampp and check the compiler version. In this case, we download the third option with a filesize of about 30MB (
ImageMagick-6.9.3-7-vc11-x86.zip). Now, extract all the files of this zip in a folder wherever you want, in this case we are going to extract the content of the zip in a folder in the desktop.
Once the content of the file is extracted, open the
bin folder and copy all the .dll files (except
ImageMagickObject.dll) that would be about 146 files (with prefixes
CORE_* and
IM_MOD_*) and then paste the copied files into the
apache/bin folder of xampp (tipically
C:\xampp\apache\bin).
Now start the apache service (or restart it in case it's already running) and go to
phpinfo again. Now you should see imagick loaded as an extension:
And you can finally after hours of suffering, use Imagick with PHP for XAMPP in Windows.
In case of console error
If after the implementation you still getting the following message error everytime you use PHP (at least in the console):
PHP Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_imagick.dll' - The specified module could not be found.
You will need to add the
bin directory of Apache (
C:\xampp\apache\bin) to the PATH environment variable of Windows and the problem will be solved.
Happy coding !
Become a more social person | https://ourcodeworld.com/articles/read/349/how-to-install-and-enable-the-imagick-extension-in-xampp-for-windows | CC-MAIN-2020-05 | refinedweb | 1,011 | 55.98 |
2005-10-19
ACPI, which stands for Advanced Configuration and Power Interface, is the successor to APM (Advanced Power Management). The specification provides for many functions besides power management, such as thermal management and plug-and-play events. This document covers those functions supported by Linux to-date. This document describes how to compile, install, and use the ACPI driver for Linux and its associated applications.
I test ACPI on a 32-bit x86 system, so this document is biased towards that hardware. In particular, I do not discuss the ARM or x86_64 implementations at all, SMP systems, nor ACPI on embedded systems. For information on those topics, see the links in ACPI on other architectures.
The current Linux kernel is 2.6.14-rc4. This document covers configuration, installation, patches and problems for2.6.14-rc3 except for swsusp3, which has been tested only for 2.6.14-rc4. Some options or capabilities discussed here may not be available in earlier 2.6 or 2.5 series kernels. For information about the (early) 2.4 kernel series, please check the previous EXTREMELY old version of this document, at.
The current version of this document can always be found at. You can also find other formats of this document at.
This document, ACPI HOWTO, is copyrighted (c) 2005 by Ariel T. Glenn..
This document is provided ``AS IS'', with no express or implied warranties. No liability for the contents of this document can be accepted. There may be errors and inaccuracies that could be damaging to your system. The author(s) do not take any responsibility; use the concepts, examples and information at your own risk.
All copyrights are held by their by their respective owners, unless specifically noted otherwise. Use of a term in this document should not be regarded as affecting the validity of any trademark or service mark. Naming of particular products or brands should not be seen as endorsements.
I've been paying great attention to the postings of Len Brown, Matthew Garrett, Pavel Machek, Jon Smirl, Li-Ta Lo, and Carl-Daniel Hailfinger. Dave Jones' posts got me through swsusp with swap on LVM on Fedora. Emma Jane Hogbin nagged me last year to get back to work on this stuff so I finally did. The City of Oakland kindly provided money for this laptop (lawsuit settlement, that's another story). Greg Michalec is loaning me hardware to test suspend on ATI Radeon hardware. My housemates endured long days of obscure rambling about these topics. Thanks to everyone.
Please send suggestions, complaints or comments about this document to ariel@columbia.edu. Please do NOT send me bug reports about the driver; see Submitting useful bug reports for more information on reporting ACPI bugs.
This document is a work in progress. Since it's been 4 years since I updated this, there has been a lot of catching up to do. I have left some sections blank and they'll get filled in Real Soon Now. Other sections are marked with the warning [FIXME] which tells me I have more work to do on that section, and it tells you that you should be extra careful when using information from that section. Thanks for your patience.
I heard rumors that the earlier nVidia X drivers, version .6xxx, may suspend to RAM properly where the .7xxx series does not. I need to test this.
I have not worked with the Radeon patches, though a friend of mine has generously offered to let me borrow his hardware to do some testing.
If there are utilities for suspend to RAM/disk or additional notes on suspend on lid close, I should add them, or remove those sections.
Some kernel CONFIG options have yet to be documented, and explanations of a few of the boot parameters are incomplete.
I need to add pointers to information for ACPI on other architectures, especially 64-bit platforms. First, there needs to be some information. *sigh*
The description of the /proc interface for the video driver is almost nonexistent.
There should be more examples of acpid event handling scripts.
Clean up and fill out documentation of how to trigger debugging for select pieces of acpi/suspend/hotkeys drivers.
Write up polling method for hotkeys driver.
Document how to do suspend to disk with raid. [How can I do this without testing?]
Fill out the comparison for the various suspend to disk patchsets.
Detail more steps for debugging when suspend to disk doesn't work.
Test and document suspend to file with swsusp2.
Power management is a catch-all term for functionality that lets you conserve power or use power resources for your computer more efficiently. For example, you may wish to reduce the brightness of your LCD panel when you're running your laptop off of batteries, or you may want your CPU to run in a lower power state if it's idle, or you may want the system to hibernate after 20 minutes if you haven't been typing. All of these are examples of power management.
These days, power management includes support for things like automated system wakeup at a given time, switching video displays, and monitoring fan speed or chipset temperature. Eventually it will probably grow to replace the desktop OS. (Just kidding...)
ACPI, or Advanced Configuration and Power Interface, is a set of specifications for power management functions of devices and the OS interface to them. It consists of descriptions of power specifications for classes of devices that describe which power states and what other functionality a class of devices must support, the definition of AML, an interpreted language for describing these various functions, and a description of how the OS calls these functions and in what context.
You may want ACPI if you are running a laptop and power conservation is a big concern, or if you want to put your desktop system to sleep during inactive periods, or if you want to monitor the temperature of various chipsets and to increase or decrease fan speed depending on those temperatures. You may want it so that you can shut your laptop lid, take your laptop to work, and open it up again, ready to go at the touch of the power button. And your computer vendor may expect you to be using ACPI so that the OS will take appropriate action if the CPU or other chipsets get too hot.
But I prefer to think of ACPI not as an optional add-on component but as an integral part of your system; in today's world, where we are all conscious of our energy use and we don't think twice about turing off the light switch when we leave a room, enabling basic ACPI functionality is common sense.
In very specific cases you may be required to enable ACPI for your system to function properly. 64-bit Itanium platforms require this; you won't get a choice in the kernel configuration menu to choose it or not, it will just be done for you. NUMA-enabled systems often require it, and systems with new Intel processors that support hyperthreading require it because they use ACPI tables for virtual processor discovery.
APM, or Advanced Power Management, is the predecessor to ACPI. It required the BIOS to handle all power management. Devices were put into lower power states based on device activity timeouts. Only standby and hibernate system sleep states were supported. Some power management features such as reducing power usage of various devices when switching from ac adapter to battery were not implemented because this would have required building support for more power states and for various power usage policies directly into the BIOS. Adoption of the ACPI standard started in 1997 when developers understood that putting most of the code in the OS would allow for more features and greater flexibility. Version 3.0, the current ACPI specification, was released in 2004.
The Linux APM driver is very stable. It supports standby and hibernation, but some newer systems may not have support for APM in the BIOS at all. Although APM support in the kernel is very mature, patches still come in once in a while. ACPI, by contrast, is under furious development. A feature may be broken in one release, work in the next, and disappear completely in the next. This is no joke. As I type this, the latest FC4 kernel (2.6.12-1.1447_FC4) has suddenly made the /proc/acpi/button directory disappear; acpid relies on this to do the right thing (TM) when you close or open your laptop, or press the power button on resume. It was there in the previous version; an overaggressive patch in 2.6.13-rc5 made it go away.
As of kernel 2.6.13, you can do the following (if you are lucky):
Suspend to RAM (S3 power state)
Suspend to disk (S4 power state)
Enter standby (S1 power state)
monitor your battery and set an action to take on low charge
monitor CPU temperature and set actions to take when it gets too hot
monitor CPU speed, throttle your CPU, and put your CPU into different power states
monitor and turn on or off your fan
change your video display brightness, or enable an external video display
Set an action to take when you close your laptop
Set an action to take when you press the power or sleep button
Set your system to wake on a certain event
And much more to come!
Not all of these may work depending on what your particular hardware/BIOS setup supports and on the state of linux support for that hardware.
Older systems have only APM support. In general, if you are working with hardware that is older than 1997, it will not have ACPI support, and if it's older than 2000, it will have only limited support.
Support for modern ATI and nVidia video chipsets is spotty under Linux. Older video chipsets tend to have better support. Cards based on the ATI Radeon have support with workarounds. This is very dependent on the version of X you happen to be using, and on the version of any X proprietary driver as well. [FIXME should test with earlier .6xxx nVidia to see if suspend works, just for shits and grins]
For comprehensive lists of laptops, their configuration, and their functionality under ACPI in Linux, see ACPI on Linux laptops.
Suspend/resume for SATA devices is not working well yet. Jens Axboe has a patch that will help for some users; see the SATA driver section for more.
Brightness controls for LCD panels is sometimes not controllable by ACPI; often, the vendor uses some proprietary method, having the BIOS adjust brightness directly when certain hotkeys are pressed. In this case you are liable to see odd messages in your log like these:
Various ethernet cards have problems, but there are patches. See the Ethernet cards section for more.
ATI Radeon cards usually need help for suspend to RAM. See the RadeonFB patches section for more. [FIXME and see if this helps X].
See also the note above about supported hardware for information about other video devices.
Any BIOS that claims to support ACPI can be used under Linux. In practice, BIOSes older than 2001 that claim to have ACPI support are often broken. Current BIOSes are often broken too because they have broken DSDT tables or missing ECDT tables.
If your DSDT is buggy, in the best case, Linux ACPI functionality will be enabled but some functions will not work; in the worst case, your system may freeze. Fortunately, there is often a workaround available. See DSDT editing for more information.
If your ECDT is missing, there's a boot parameter, acpi_fake_ecdt, which can help you. See Boot parameters reference for more information.
Some BIOSes are known to be broken and they are included in a blacklist in the ACPI driver. Systems with those BIOSes at this writing are:
Compaq Presario 1700
Sony FX120, FX140, FX150M
Compaq Presario 800, Insyde BIOS
IBM 600E
all systems with ASUS P2B-S BIOS
The most reliable way to tell is to boot with an ACPI-enabled kernel and look for ACPI messages in the log. You should see at least
and messages like this if you have PCI slots:
If you see messages like this:then your BIOS does *not* have ACPI support.
If you want other ways to check your system, you can look at your BIOS settings; many systems have ACPI-related options in their BIOS menus, though not all. For example, the Dell XPS Gen 2, while fully ACPI-compliant, has no mention of ACPI in the BIOS settings at all.
You can also run acpidump, which is packaged with most distributions. To run it, be root and at the command prompt, type acpidump.
If your system is ACPI-compliant, acpidump should print out a long list of tables and their contents, including the RSDT and the DSDT. If you don't see a line something likeyou may have a problem. If acpidump produces no output, it probably has failed to find any tables. Check the exit code; if it's 0x0005 then you (probably) don't have ACPI support at all.
If you want to look through memory yourself, and you have 32-bit hardware which is not EISA/MCA based, you could try looking for "RSD PTR" in 0e0000h through 0fffffh by grepping it out of /dev/mem, like this:
If you see output like this, you know you have the root table stricture for ACPI, which means that you have at least some degree of support.
Note that none of these methods guarantee that the BIOS support for ACPI is bug free, just that it exists.
If the problem is related to the video card, and you're using a proprietary driver, the outlook is not good. It depends however on your particular card and BIOS. If posting your video card after resume helps your problem, then eventually that will be fixed because sooner or later that code will make it into X or into the kernel. It's also possible that your video card vendor may provide X drivers that do the proper card reinitialization at some point.
If the problem is related to hotkey support, some laptops have specific hotkey drivers, but a generic hotkey driver is available which you should check out as well. See the Kernel configuration reference for the CONFIG_ACPI_HOTKEY option.
Detailed bug reports are extremely helpful, as are volunteers to do testing and debugging on their hardware. See Debugging tips to get started.
All Linux 2.6 kernels and the current 2.4 series have ACPI support out of the box. If you are running one of the 2.2 series, you are out of luck. Not all new features from 2.6 are backported into the 2.4 series kernels. Your favorite distribution probably has ACPI support turned on by default. Checked for: Fedora Core x; Suse 9.x; Debian 3.x, Ubuntu, Gentoo.
If a feature doesn't work for you in one kernel, try the next one, or even an rc intermediate release, because so much changes from one week to the next.
For the very latest in ACPI support, however, you should build your own kernel and look at the most recent ACPI patches, as there is much hard work being done on this subsystem. The most recent patches can be found at.
Basic ACPI support is included in the linux kernel. You need acpid if you want to capture ACPI events and take certain actions based on those events. You do not need to use acpid if you want to do suspend to RAM or suspend to disk and you are willing to run a script by hand or work directly with the sysfs interface. If you want to be able to shut down cleanly by pressing the power button, you should use acpid; in addition, if you want to hibernate or suspend on laptop lid close, you need acpid. See the acpid event handling daemon to learn how to build and use it.
Here are some of the userspace utilities for ACPI power management. You don't have to use any of them to get ACPI functioning, but they can be much more convenient than accessing /proc/acpi or sysfs directly. This is not meant to be a comprehensive list. However, if you know of an application that is currently maintained and that you think should be on this list, let me know.
acpitool -- command line utility to get battery/fan/temperature/cpu information or to suspend to RAM/disk, turn on/off fans, and control wakeup capable devices
battstat-applet-2, bbacpi, wmacpi -- battery monitoring
wmpower, yacpi -- battery, temperature and other monitoring
powersave, with front ends kpowersave, gkrellm-powersave, wmpowersave -- all purpose utility covering APM, ACPI and other power management features
xrg -- all purpose monitor that watches everything from CPU activity and battery status to the weather and stock market data
All major distributions come with ACPI support built into the kernel by default. Fedora ships out of the box with acpid and battstat-applet-2, Debian has acpid and wmacpi, Suse has acpid and powersave, and Gentoo has acpid and quite a number of monitoring/power management utilities. Check your distribution's documentation to see what prepackaged options you have.
To build your own kernel with ACPI support, you need the following:
Make sure that you're building with the appropriate version of gcc (at this writing, at least version 3.2).
Turn on these configuration options for base ACPI support: CONFIG_PM, CONFIG_ACPI and CONFIG_PNPACPI.
For ACPI control of some basic devices, set these: CONFIG_ACPI_AC, CONFIG_ACPI_BATTERY, CONFIG_ACPI_BUTTON, CONFIG_ACPI_VIDEO, CONFIG_ACPI_FAN, CONFIG_ACPI_PROCESSOR, and CONFIG_ACPI_THERMAL.
For suspend to RAM, set CONFIG_ACPI_SLEEP, and for suspend to disk, set CONFIG_SOFTWARE_SUSPEND, and also supply the name of the partition reserved for writing suspend data to CONFIG_PM_STD_PARTITION. NOTE: if you are suspending from something other than a standard swap partition, read the Suspend to disk section because you may want to set CONFIG_PM_STD_PARTITION to "".
For more details on these config options or for the other kernel configuration options for ACPI, see the Kernel configuration reference.
Most ACPI-capable BIOSes have settings that the user can tweak for power management. For example, recent versions of the AMI BIOS have an entire section for ACPI settings, including ACPI-Aware OS, ACPI 2.0 compliance, BIOS->AML ACPI table, all of which should be enabled; Suspend to RAM support, and Repost video on S3 resume which may be useful if your video doesn't come back after resume from suspend to RAM. Check your BIOS to see what power management features it offers you.
If you see APM settings in your BIOS you can ignore those. As long as you have ACPI built into your kernel and enabled, the APM settings will not be used.
You should not need to pass any special boot parameters once ACPI is built into the kernel. If you run into problems, or you have special requirements, check the Boot parameters reference for a comprehensive list.
Older versions of acpid used to act as an intermediary between the kernel and the BIOS, looking up hex values that could be used to invoke certain sleep types and installing sleep methods; it also used to provide battery information and it had the entire AML interpreter in it. But it didn't support suspend to disk or suspend to RAM.
These days, the entire interpreter for AML now lives in the kernel. I stopped maintaining this document shortly after that patch () got accepted about 4 years ago. It singlehandedly added around 72000 lines of code to the kernel. One developer [fn1] is pretty sure that ACPI was designed by a bunch of monkeys on LSD, but if it had, it would at least be visually appealing. And this ain't.
OTOH, the acpid daemon has become much simpler. It now watches for all acpi-generated events and allows the user to define the appropriate action to take on receiving those events.
Most distributions come with acpid out of the box. If you want to build your own, you'll find the latest version at
[fn1] See.
Make yourself a build directory and untar the file: zcat acpid-1.0.4.tar.gz | tar xvfp - cd into the directory: cd acpid-1.0.4
If you download the tarball, edit the Makefile if you're using gcc 4.x: change the line CFLAGS = -Wall -Werror -g $(DEFS) to read CFLAGS = -Wall -g $(DEFS) (This is fixed in cvs.)
build it: make install it: make install This puts acpid in /usr/sbin and acpi_listen in /usr/bin It also installs the man pages.
These programs use /proc/acpi/events (boo). When will they use /sys?
Linux sees ACPI events, in some cases takes an action, and then writes a description of the event to /proc/acpi/events so that userspace applications can take actions as well. Acpid watches /proc/acpi/events and, for every event logged there, looks at its set of rules to see what action(s) to take. These actions are specified by you, the user.
Acpid looks for its rules by default in /etc/acpi/events at all files in that directory (no subdirectory walking though). Each file in there is expected to contain rules that tell acpid what to do on each event.
Each file may have blank lines or comments starting with # Then you must include at least one line defining an event and one line defining an action.
Here's an example:
That file ships with Fedora Core 4 and tells acpid to shut down when the power button is pressed (so you don't have to give the three-finger salute).
%e and %% are special strings; if you use %e in the event description or in the action description, the full text of the event as described in the previous section will be substituted into the string, and if you use %% in either description, the character % will be substituted in. If you use % in any other combination, you'll get an error.
You can define multiple actions for the same event, but they won't necessarily be processed in the order you list them in the file.
You can also put multiple event lines in one file and use the same action for all of them. [FIXME examples would be nice]
If you have acpid source from CVS or tarball, you can look at more interesting examples such as the battery.sh script which is intended to be used from one of these rule files. It reacts on any battery event, checks to see whether the system is on AC or battery, and sets or disables hard drive spindown time appropriately. Note that this script may not work for you out of the box, as your AC adapter may have a different name (mine is called /proc/acpi/ac_adapter/AC); it's here as an example only.
On FC4 you are expected to put all your fancy scripts into /etc/acpi/actions but nothing in the acpid code requires this. Put them where you want.
It is not possible to provide a comprehensive list, because the list of events depends on your vendor's hardware and their ACPI implementation. However, it is possible for you to figure out what events will be issued on your hardware by looking at /sys/firmware/acpi and collecting some information.
First, let's see what an event looks like. If you are running acpid, and you are running ACPI with any applet to monitor battery status of control cpu speed, you can look in /var/log/acpid at events it has received. You may see messages like this:
Each event as logged consists of the device class name, the bus id name, the event type, and the event data. Device class names are standardized, and you can get the list by looking for all #defines of "CLASS" in the kernel code in drivers/acpi. My list is:
ac_adapter, battery, button, container, embedded_controller, fan, Hotkey (because the asus driver got the word "hotkey"), lid, memory, pci_bridge, pci_irq_routing, power, power_resource, processor, sleep, system_bus, system, thermal_zone, video
Note that some of these are subclasses; power, sleep and lid are subclasses of button, and they'll get written as button/lid, button/power and button/sleep in the log.
Bus IDs are not standardized; they are defined in a vendor's implementation. Fortunately, the names vendors use are similar and usually recognizable.
You can find out which Bus IDs your vendor is using on your current hardware by looking in /sys/firmware/acpi/namespace/ACPI/. My system shows
You may decide you don't need to know what the event type is; for example, if you get a battery event, you might look at /proc/acpi/battery/BAT0/info (or BAT1/state, or whatever your battery device is called), check the remaining capacity and take any appropriate actions.
However, there is a list of event types in the ACPI specification. Here's the summary:
For all devices, 0 = bus check (time to rescan the bus); 2 = device removed or added; 3 = device awakened; 4 = device eject, 5 = device removed or added ("device check light", don't ask me what the difference between this and 2 is); and some other events that you probably won't care about as a user. See page 142 of the specification if you want the rest.
For specific devices:
Battery: 0x80 = battery status changed, 0x81 = battery information has changed (i.e. you have a different battery in there now); 0x82 = check battery maintenance flags.
Power source: 0x80 = power source status changed. (Think AC adapter.)
Thermal zone: 0x80 = thermal zone temperature changed; 0x81 = thermal zone trip points changed; 0x82 = thermal zone device lists changed; 0x83 = values in thermal relationship table changed
Power button: 0x80 = power button pressed. Warning: If the power button is pressed with the system in S1 through S4, you will not see this event; instead you will see a Device Wake (0x02)!
Sleep button: 0x80 = sleep button pressed. Warning: If the sleep button is pressed with the system in S1 through S4, you will not see this event; instead you will see a Device Wake (0x02)!
Lid: 0x80 = Lid status changed (either open or closed).
Processor: 0x80 = number of supported processor performance states (P states) has changed; 0x81 = number or type of supported power states (C states) has changed; 0x82 = number of supported throttling states has changed.
video (part 1): 0x80 = state of one of the displays attached to the graphics adapter has been toggled; 0x81 = re-enumerate all devices on the adapter (i.e. a device has been added or removed); 0x82 = cycle display output (next display activated and if the last one was active then the first one now is); 0x83 = next display activated; 0x84 = previous display activated. Note: for these events, when a new display is activated, Linux deactivates the previously active one. If you want more than one display to be active, you should activate them by using the /proc/acpi/video/VID/*/state interface. See Proc entries reference for the /proc entries. Also, I'm unsure if cycling the display output really should put you back to the first device if you are at the end of the list; at least, Linux doesn't appear to do this, from a quick scan of the code.
video (part 2): 0x85 = display brightness increased one level and if it was at max, it got set to min level; 0x86 = display brightness increased one level and if it was at max, it stayed there; 0x87 = display brightness decreased one level and if it was at min, it stayed there; 0x88 = display backlight turned off; 0x89 = display off WARNING: these values are right out of the ACPI 3.0 spec. But they are not the values Linux uses! It uses: 0x82, 0x83, 0x84, 0x85, 0x86 for each of these things in order. Uh oh... I don't have (ACPI) brightness control support, so I can't test this to see what should happen. Anybody?
Some events that Linux passes on are not defined in the spec; that is, I can't find a table with numbers for these. I got the values by looking for invocations of acpi_bus_generate_event() in the kernel acpi driver code, and checking the event passed in that function.
thermal zone: 0xf0 = critical temperature trip point is being passed which requires immediate shutdown; at this point Linux will shut down by calling /sbin/poweroff. You don't really have much time to process this event. :-) 0xf1 = critical temperature trip point is being passed which requires the OS to put the system into S4 (hibernate) if that state is supported. The Linux kernel does not yet do this. It has a comment placeholder where the code ought to go.
If you use the generic hotkey driver (CONFIG_ACPI_HOTKEY), then when you press an authorized hotkey, you'll get an event sent to /proc/acpi/events for it. That list is described in How do I use the hotkey driver?
No, I'm not documenting the state data; look it up your own darn self :-)
Acpid logs all of its activity to /var/log/acpid by default. Check your init scripts to see where your distribution directs its logging.
You can also run acpi_listen. This command will connect to acpid and write every event that acpid sees to stdout, in exactly the format the event appears in /var/log/acpid, but without the extra commentary.
A few nice Thinkpad scripts can be found at
Unfortunately, scripts are very dependent on your particular hardware configuration.
Some folks have put up acpid scripts on their pages describing the installation of some distribution on their laptop. Check these resources for more information.
ACPI gives you unprecedented control over your CPU's power consumption. You can control power usage in three different ways: setting idling power states, changing cpu frequency, and throttling the CPU.
First, the CPU can enter different idle power states, C1 through Cn (usually C1 through C4). If a processor is in state C0, it is working normally; in any other state, it is idle (doing no work). Lower power states use less power but the CPU will take longer to transition to a higher power state. So if your CPU is in C4 it will use less power than in C3 but it will take longer to come out of idle than from C3.
You don't have to do anything to make the CPU go into the appropriate idle state; the kernel will place the CPU into a lower power state automatically when it is not busy. However, you do need to build this capacity into the kernel by enabling CONFIG_ACPI_PROCESSOR. See the kernel configuration reference for the CONFIG options.
You can look at the /proc/acpi/processor/power file to see how long your CPU spends in each state; see Proc entries reference for more on this file. You can also look at /sys/module/processor/parameters/max_cstate to see what the lowest power state the kernel will give you is; see Sysfs entries reference for more on that.
And you can adjust max_cstate by using the processor.max_cstate boot parameter. In some cases machines that enter C3 or C4 produce a loud whine, and you may want to limit your system to C1 and C2. In some cases you may want your system to enter C3 or C4 but it's been blacklisted by the kernel and limited to C2; you can use this same parameter to override the blacklist. See Boot parameter reference for details.
Second, you can also run the CPU at lower frequencies when it isn't doing so much work. If you're spending most of your time typing text instead of compiling, this can be very useful for power savings. In ACPI lingo, the CPU enters various P-States, P0 through Pn, where at P0, the CPU is running at its highest frequency and at Pn it runs at a lower frequency the greater the value of n. These performance states are only valid when the CPU is in power state C0; the rest of the time the CPU is in some idle state and so adjusting its clock frequency doesn't make any sense.
To benefit from this, you'll need to enable CPU frequency control by setting CONFIG_CPU_FREQ. Then you can choose which of several performance managers to build in; these adjust the frequency based on different criteria. Then you can choose which hardware-level driver to build in. Only certain of these drivers support ACPI P-States; the rest use a proprietary method of regulating CPU frequency and are not discussed further in this document. Further, of those that use the designated P-States, only the ACPI P-States driver (CONFIG_X86_ACPI_CPUFREQ) actually notifies the ACPI subsystem of P-State changes. If you think this is confusing, you're right.
After your kernel is set up, you can either use one of several userspace applications to automatically set your CPU to a lower frequency depending on the load, or you can use an applet that lets you set the frequency manually as you desire, or you can use one of the performance managers that adjusts frequency for you in kernel space. For all the details, see CPU_FREQ reference.
Third, you can throttle your CPU. This means that you force the cpu to be idle a fixed percentage of its cycles per second. Throttling states are called T1 through Tn, where in T1 the CPU has no forced idle cycles, and the percentage goes up the greater n is. For example, on my system, T4 forces the CPU to be idle for half of the cycles.
This is different from changing the frequency, which makes the cpu have fewer cycles per second, and it's different from running in a C state other than C1, because those are states where the CPU is idle for all cycles.
If you have a certain amount of work to get done, then throttling the CPU will cause the work to take longer to get done. However, if temperature is a concern, then this will keep your CPU running cooler.
Note that this does not reduce voltage, and since all tasks will take longer (since the CPU is forced idle part of the time), you actually use more power to get any given task done. This is in contrast to CPU frequency management; when the CPU frequency is lowered, voltage is lowered too, and any given task should draw less power unless it requires the CPU to run full out for the duration of the task.
You can check which throttling states are supported by your CPU by looking at /proc/acpi/processor/CPU*/throttling. This file will also show you what percentage of idle time each state enforces. You can set the current throttling state for your CPU by writing the state number to /proc/acpi/processor/CPU*/throttling. Read it back to make sure the change works; if it doesn't, you may have a bug in your DSDT or elsewhere.
Note that throttling states only work when the CPU is in the power state C0. But they work for any performance state (P-state); this means that no matter what frequency the CPU is running at, you can still do throttling. For information on how to do this, see Thermal management.
ACPI provides several means for monitoring and controlling system temperature. Via thermal zones, you can adjust the system cooling mode when it's too hot, you can turn on and off fans when you reach certain temperatures, and you can throttle your CPU when it gets too hot, taking into account the performance state it's running in. Not all platforms support all of these features, but the ACPI 3.0 specification provides all of these mechanisms.
If your vendor's implementation of ACPI supports thermal management, you'll have one or more thermal zones, which you can monitor by checking /proc/acpi/thermal_zone for these devices. They'll be called something like THM or THRM0.
I haven't seen a system with multiple thermal zones. Typically a system has one big thermal zone which includes the entire interior region of the case. Practically speaking, it must be connected to a sensor somewhere, probably by the CPU.
Linux should poll the temperature every so many seconds. In practice, however, Linux tries to figure out how often to poll by invoking the _TZP method, which many vendors don't provide. When that fails, Linux disables polling altogether. Fortunately, you can enable it by echoing a number to the file, for example, echo 30 > /proc/acpi/thermal_zone/*/polling_frequency, to have Linux check the temperature every 30 seconds.
You can monitor the temperature for each thermal zone yourself by reading the file /proc/acpi/thermal_zone/*/temperature.
A cooling mode is a description of how your system is cooled in a certain temperature range. Your cooling mode can be critical, passive, or active. Active cooling means that a fan or other cooling device can be turned on when the temperature passes a critical point. Passive cooling means that devices can be put into a lower power state when the temperature is too hot. Critical cooling means that when the temperature passes one trip point, the so-called "hot point", the OS will transition into S4 (suspend to disk) if possible, and if the temperature passes a second trip point, called the "critical point", the OS will shut down the system.
If your platform supports it, Linux will set the cooling mode to active by default. If this isn't successful, but both active and passive modes are supported, then the cooling mode which supports the lowest trip point is the one in use. If only one of passive or active cooling modes is supported, Linux will use that. Failing that, it will fall back to critical cooling mode, which must be supported by your vendor.
Some platforms allow you to change the cooling mode. You can do this by echoing 1 to /proc/acpi/thermal_zone/*/cooling_mode to set passive cooling, or 0 to /proc/acpi/thermal_zone/*/cooling_mode to set active cooling. Critical cooling will always be active, in case your system heats up so much that drastic measures must be taken, even with fan use or power reduction.
Trip points are set temperatures that, when the system temperature reaches them, trigger some sort of action. Typically this can be a change in cooling mode, or something more drastic. The critical cooling mode has two predefined trip points. If the system reaches the first one, called the "hot point", Linux will try to put the system into S4 (suspend to disk) if possible, and if the temperature passes the second one, called the "critical point", Linux will call /sbin/shutdown -h now.
You can define multiple trip points each with their own cooling policy. If you do, they'll show up in /proc/acpi/thermal_zone/*/trip_points like this:
You can set critical, hot, passive, and up to 9 active trip points. Here's how you do it: echo a string of numbers to /proc/acpi/thermal_zone/*/trip_points separated by a colon. These numbers are the various trip points in Celsius. NOT IN Fahrenheit! So you *can* echo 99:80:35:75:60:55:50:45 > /proc/acpi/thermal_zone/*/trip_points to set the critical trip point at 99C, the "too hot, suspend now" trip point at 80C, the passive trip point at 35C, the first active trip point at 75C, the next one at 60C, and so on through the fifth active trip point at 45C, but in practice that's a lot of trip points. You probably only need one or two; after all, how many extra fans do you have? However, Linux expects to see at least 5 values, and if it doesn't see them it throws an error and refuses to process the change. So even if your system only does passive cooling, you must supply values for active[0] and active[1]. Just set them to 0 if they don't make sense for your platform.
Unfortunately, if you write values to trip_points (at least 5) and these other cooling methods are not supported, Linux will not inform you about it. It will silently accept the values and move on. On my system I can't even reset the lone critical trip point permitted me; but no errors are generated; the only way I can tell is to read the trip_points file again and see that it hasn't changed.
These limits set the highest (highest frequency) P-State, and highest (least throttling) T-state your platform is permitted to use under certain circumstances, where P0 is a higher P-State than P1, and T0 is a higher T-state than T1. Sorry for the lousy terminology.
You can see what the current throttling/p-state limit is, by looking at the file /proc/acpi/processor/limit. Look at the active limit, which will show a performance state, like P0, and then a throttling state, like T0.
To set a limit, write two numbers separated by a colon, like "0:0" into limit. The first number is the processor performance state, and the next number is the processor throttling state. This will set the user limit, which you also see when you read that file. The active limit is chosen as the maximum of the user and thermal limit T-state numbers; i.e. if the user limit is T2 and the thermal limit is T3 then the active limit will be T3.
Unfortunately, Linux does not seem to use the first number for anything. It always uses the value of 0 to update its internal copy of what it thinks the P-State is for display in the limit file. Maybe that's ok, since it never actually sets the P-State from that value :-(
Warning, esoterica: Only the ACPI P-States cpufreq driver updates the CPU's P-States. This file could either show the actual P-State (and update it on demand) for that one driver, or it could map frequency changes from all drivers into P-States by name, and reflect the change by changing frequency according to the registered cpufreq driver. Right now it just leaves the Px value around in the limits file to be confusing to the user, the worst of both worlds.
In any case, the second value does get stuffed into the user limit thermal value, and you can verify that by reading the file. It takes effect immediately. Note that the user limit can never be a higher (less throttling) state than the thermal limit; for example, if the thermal limit is T1, then the user limit cannot be T0.
The generic hotkey driver allows you to make those nifty hotkeys on your laptop work. The concept is simple; your laptop has a hotkey that Linux doesn't understand and that has no effect. You expect it to actually set the brightness of your LCD to max, for example. So, you define a function that includes the ACPI event number generated by your hotkey, the hotkey driver event number that corresponds to the function you want the key to do (here, increase brightness), information required to find the right video device, and the ACPI method name for increasing brightness. Once the function is set up, any time you press the hotkey, an event will be generated that acpid can pick up, and once you define the right rule for acpid, you'll have your hotkey working.
This does not work for all laptops; your laptop must generate an ACPI event when you press the particular hotkey you want to use. This means that in your DSDT, you will have something like \_SB.PCI0.LPC.EC.HKEY.BTIN () (IBM laptops), or Name (_HID, "ATK0100") (ASUS), or Device (HKEY) (Panasonic).
If you want to know if your hotkeys generate ACPI events, one way you may test this is to turn on debugging (CONFIG_ACPI_DEBUG = y) in your kernel, boot up, echo '0xffffffff' to both /proc/acpi/debug_level and /proc/acpi/debug_layer, and then press a hotkey. Just one! Once! This will either generate a lot of error messages in your log, or none at all. If it generates none, you are out of luck. Otherwise, you should be able to use this driver. [FIXME see which parts of the debug layer we can minimally turn on to get useful messages.]
You can try just pressing the key and see if anything shows up in /var/log/messages. If not, you'll have to resort to the method described above, i.e. build in ACPI debugging, turn on all debugging bits, and then slog through the log.
The event number that your hotkey generates can then be retrieved by looking for lines in your log like "ev_queue_notify_reques: Dispatching Notify(80)".
Let's take our earlier example. Say your laptop has a hotkey that should set the brightness of your LCD to max. So, you define a function that includes the event number generated by your hotkey (which you must determine by looking at log output after pressing the hotkey), the appropriate hotkey driver event number, in this case 0x86, the ACPI bus name on your platform, the ACPI full path name for your LCD, and the AML method you are going to call, which in this case is _BCM, the AML method to control the brightness level.
On my system, if Dell actually had hotkeys implemented through ACPI, which it doesn't, I'd do the following:I've used a made-up value for the event number generated by pressing the hotkey, since Dell hotkeys don't generate ACPI events, but the rest is correct for my platform. I could then verify that the setup worked by looking in the log for errors and by reading /proc/acpi/hotkey/event_config, which would give me
Let's look at that in a little more detail. In the example above, we have 7 arguments, which you must always provide to add a new key. The first argument must be 0 which indicates that this is a new key definition. The second argument is the name of the bus on which your device sits that you're going to affect; the LCD panel on my system is on the _SB bus. The third argument must be omitted for event-based key definitions. The fourth argument is the full ACPI namespace path name of the device, and the fifth argument is the AML method you are going to call. The sixth argument is the event number that your key press sends to the ACPI driver, and the seventh argument is the hotkey driver event number which the driver will use to look up the event in its tables. For the seventh argument, you can use any hotkey event number you like (as long as it's known to the driver), but you may kick yourself later when you have to read your script and understand what it does.
You can also set up keys to use a polling method; I'll cover that in a future version of this document. [FIXME]
Fun fact: you don't have to map the hotkey to a method that has anything to do with the intended function of the hotkey, or with the intended meaning of the event number you chose from the hotkey driver event list. So you could map your wireless activation hotkey to turn of your fan via the _OFF control method, if your fan supports that control method. I'm not saying you should; I'm just saying you *could*.
To remove the key definition, just do echo '1:::::128:136' > /proc/acpi/hotkey/event_config where the 128 should be replaced with the actual ACPI event generated by the key press, and the 136 should be replaced with the hotkey driver event number you actually used.
To change the definition, just put the new definition to /proc/acpi/hotkey/event_config but use '2' as the first argument, which indicates that the key definition already exists and should be updated with the new values.
The list, grabbed from hotkey.c, is
video (see video events above for more on what these do):
0x80, cycle output device hotkey pressed;
0x81, output device status change hotkey pressed (maybe it disconnects one of the devices);
0x82, cycle display output hotkey pressed;
0x83, activate next display output hotkey pressed;
0x84, activate previous display output hotkey pressed;
0x85, cycle display brightness hotkey pressed;
0x86, increase display brightness hotkey pressed;
0x87, decrease display brightness hotkey pressed;
0x88, set display brightness to zero hotkey pressed;
0x89, turn display off hotkey pressed
sound (why are these here? they aren't ACPI related):
0x8a, volume mute hotkey pressed;
0x8b, volume increase hotkey pressed;
0x8c, volume decrease hotkey pressed
sleep states buttons:
0x8d, Suspend to Ram hotkey pressed,
0x8e, Suspend to disk hotkey pressed,
0x8f, Soft power off hotkey pressed
Once the definition is set up, if I pressed the hotkey, an event of type "Hotkey Hotkey 0x00000086 0" would be generated, and acpid could pick it up and do the right thing with it. The right thing is already almost predefined: it should echo "136:1::100" > /proc/acpi/action where 136 is the event code that acpid was given in /proc/acpi/events converted to decimal, the "1" means it is event based rather than poll-based, i.e. the event was read from /proc/acpi/events, the third missing argument is only needed for poll-based hotkeys, and the 100 is the argument to _BCM to set the brightness to the maximum level.
The trick is that most of these methods actually don't do exactly what you want the hotkey to do. Here's a summary of the relevant AML methods from the ACPI spec.
_BCM controls brightness. Pass the number (percent of 100) to set the level to. Supported brightness levels can be retrieved by reading the file /proc/acpi/video/VID/*/LCD/brightness (or CRT, or whatever device you are checking). That means that if you have a hotkey for increasing brightness, mapping it to this method will not be enough. You should use a script that gets the current brightness, checks the supported levels, and sets the next one. That script can use /proc/acpi/action, but it will have to have figured out the right brightness level as the argument to _BCM first.
_DSS makes the display active or inactive. Pass 0x80000000 to inactivate, and 0x80000001 to activate. You can see the state of each device by reading the file /proc/acpi/video/*/LCD/state (or CRT, or whatever device you are checking). That means that if you have a hotkey to switch between CRT and LCD, mapping it to this method will not be enough. You should use a script that gets the current active device, inactivates it, and sets the other one as active.
There are no methods for sound control in ACPI; that's not really a power management feature. In order to get the sound-related hotkeys to work, you may have to have acpid run alsamixer or some such to do the right thing.
The sleep state hotkeys are another bit of a kludge. What you want to do here is to have acpid do any prep work for the suspend or power off; for suspend, you may have modules you want to remove, and so on. Then you want to actually do the suspend by echoing the right state into /sys/power/state, and finally do the right thing on wakeup, by reinserting modules and so on. For poweroff, you can have acpid call /sbin/shutdown -h now, or whatever other shutdown mechanism seems good to you. Once again, these hotkeys must be set up with placeholder bus names, device paths, and AML method names; these items are only there so that the hotkey driver will register the key definition and not throw an error.
So what this means is that in all of these cases you are going to use a script to handle the event. There is perhaps one exception: if you have a hotkey that turns off the display, or turns the brightness down to zero, you can map that directly to the appropriate method with a fixed argument. In the rest of these cases, you still have to pass a valid bus name, device path, and AML method name, so choose something harmless and then don't ever use /proc/acpi/action with it. I recommend _SB for the bus name, _SB.PBTN (or whatever your power button is called) for the device name, and _PSW for the method name, since you won't need these for anything else. This assumes your power button supports _PSW; if not you may have to look around in your DSDT yourself for some ideas.
Bus names are easy; see the discussion of bus names as part of events in How do I use acpid? Device paths are not easy, because device names are set by the vendor and vary from one platform to the next. You can get valid device paths for your system out of the ACPI namespace by looking at /sys/firmware/acpi/namespace/. Find the device you're going to affect somewhere in the directory tree, say LCD, and grab the full name, starting with _SB and ending in the device name. You need to put a "." instead of a "/" between directory names, so that you get something like _SB/PCI0/AGP/VID/LCD converted to _SB.PCI0.AGP.VID.LCD as the device path. Again, this is only useful in the rare case where you have a hotkey that does a fixed action (not increasing the brightness, but setting it to max/min; not switching the active display but turning one off or on).
Suspend to RAM is part of the kernel. Make sure you have ACPI enabled in the BIOS and the kernel, and that you have the CONFIG_ACPI_SLEEP option set.
It's a good idea to remove all usb devices and modules, as well as any firewire devices and modules. If your suspend works well without them, try adding them back in.
Then echo mem > /sys/power/state You'll see some messages on the console about suspension, ending withThen your system should go to sleep.
Pressing the power button should bring the system back, starting with some hard disk activity.
Type an innocuous command such as ls and press <Enter>; some folks report that their display comes back on the first <Enter> key press.
If your laptop supports display brightness adjustment, and that works on your system before suspend, try using that after suspend and see if your video comes back.
See if switching your video display from your internal LCD to an external CRT and back brings back your video. You can do this even if you don't have an external CRT hooked up. See [] on how to do this.
If none of those things work, see if your system responds to keypresses. Does pressing the Caps Lock key turn the Caps Lock LED on? If not, wait about 5 minutes, and try the same activity again. Sometimes the kernel has gone out to a short snack instead of out to lunch. This works for me.
If you have Caps Lock responsiveness, try suspension with networking enabled, and see if your computer is pingable (again, wait 5 minutes if there is no initial response).
If it is, you might try again with sshd and see if you can log into the system. Then you can try some vbetool tricks to muck with the display. See Vbetool for vbetool usage and tricks.
If you don't have network access, see if typing sync gives you disk activity. If so, you can try the vbetool tricks mentioned above. Set up a script ahead of time so that you can minimize typing mistakes while typing blind.
If none of those things work, you can try a few specialized boot parameters: acpi=s3_sleep, acpi=s3_mode, or pci=routeirq. See Boot parameters reference for more information.
Build usb support and the specific driver support for those devices as modules and write an acpid script that removes these modules before suspension and reinserts them afterwards. Here's an example, adapted from Gentoo's wiki page on the Samsung X20 at:
Help us debug the problem. Here are some steps to take:
Rebuild your kernel with support for as few devices as possible, preferably no usb, and no pcmcia unless your network is pcmcia and you have network after you resume.
Turn off optional devices in your BIOS; my Dell laptop lets me turn off the modem and wireless devices.
Turn off the framebuffer device.
Boot as single user, turn on networking and sshd if your machine is pingable after resume, turn on syslogging, and try suspend/resume from there.
Turn off networking for good measure and try that, just to see if that has an impact.
Make sure your BIOS is the most recent possible.
Check your DSDT; see DSDT editing for instructions.
If you are running an old distribution, in particular an old version of X, update it/them. If you are using proprietary drivers, make sure you are using the most recent version.
Try suspend from X as well; video drivers don't live in the kernel except for framebuffer drivers, and the X drivers sometimes know how to reinitialize recent video cards.
Look also at Documentation/video/blot.txt for more things you can try.
If you still can't resume, get what you can from the logs and submit a bug report.
Note: Suspend to disk is entirely independent of the ACPI subsystem. But it's included in this document because, hey, what the heck.
There are three different patches around for suspend to disk. As of this writing, the kernel has a set of patches inline, which are called swsusp and which in this document I will refer to as swsusp1. Software Suspend 2 is a set of patches not yet merged into the kernel; Software Suspend 3 is a user-space implementation still in the works. Pm-disk, which used to be yet another fork from swsusp1, was combined with swsusp1 in mid-2004., there is support also [FIXME].
Back up your data before your first test. No joke! If you happen to have an unsupported driver, bad things can happen.
Get a few patches first: the data free patch at; the pagedir patch at; and the memory leak patch at. These apply to 2.6.14-rc2 cleanly.
Now, build your kernel with CONFIG_SOFTWARE_SUSPEND=y. According to gossip on the Linux kernel mailing list, CONFIG_PM_STD_PARTITION is going to be removed someday; the approved method of specifying the resume partition is to pass it as an argument at boot time. For Grub users, this means appending the argument "resume=/dev/something" to your kernel boot line, where "/dev/something" should be replaced with the full name of your swap partition.: swsusp: Error -6 check for resume file,: echo shutdown > /sys/power/disk; echo disk > /sys/power/state!
On a system where your swap partition is an LVM partition, you must take a different approach. You must use initrd/initramfs. enable LVM.. It will also cause the kernel to write this message to /var/log/messages: resume= option should be used to set suspend device. Ignore that error.. Just), find the major and minor numbers of your swap partition, and echo them into /sys/power/resume. For example, if your swap were on /dev/mapper/VolGroup00-LogVol01 which showedthen you would echo 253:1 > /sys/power/resume. All of this must be done before any filesystems are mounted. If you wait until afterwards, you are almost guaranteed to have data corruption. It should also have a fallback present in case the resume fails (i.e. the next line after the echo into /sys/power-based suspend: echo shutdown > /sys/power/disk; echo disk > /sys/power/state. For those who want to know more than they should, the resume works by writing the device name as major:minor device numbers into /sys/power/resume, which causes the kernel to try to resume from the swap on that device. (It bypasses the normal kernel resume path which would use the swap partition name -- something like /dev/mapper/VolGroup00-LogVol01 -- to try to find an underlying physical partition and would fail to find it and fail to resume.) This leads to one last caveat: never write into /sys/power/resume yourself, or you will cause the kernel to try to resume from whatever device you specify, right then and there. That is a sure recipe for disaster!
Using Nvidia drivers with swsusp1 is easy. This document describes the procedure for driver release 7676. Unpack the driver, edit nv.c to change this stanza:to read Rebuild your module and you're ready to go. If you are using the intel_agp module, you may need to use the line in the "Device" section of your X configuration file; other than that, no special tweaks should be needed. In some cases, your X display may come back fine but switching to other consoles may give you garbage; I find this to be true on my hardware.
[FIXME put info about ATI drivers here, as: the official name of this code is "Software Suspend 2". In this document, it is usually referred to as swsusp2, even though that's not the preferred name. With three different suspend to disks floating around, it helps me to keep them all straight.
Since Suspend to disk 2 has not been merged into the kernel, you'll have to download the patchset from. Version 2.2-rc8 has been released for 2.6.14-rc3 and it applies cleanly. This document only describes working with this version of the patchset. To apply the patch, unpack it, cd into the root of your kernel source tree, and run /path/to/patch-unpacked/apply /path/to/patch-unpacked (the name of the script is apply, and you must tell it where the unpacked patch tree is).
You must also download the hibernate script which goes with it, from the same place. Make sure the hibernate script version goes with the kernel patches. Both rpms and tarballs are available. Assuming you retrieved the hibernate tarball, unpack it, change into the directory where you unpacked it, be root and then run ./install.sh. This puts the scripts and config file in appropriate places. You may want to check /etc/hibernate/hibernate.conf, and the list of modules that hibernate will attempt to unload before suspending, in /etc/hibernate/blacklisted-modules. The defaults are usually ok to test with.
You can either use a swap partition or a file for saving your suspend image. Using a file will be covered in a later version of this document. [FIXME] Make sure you have a swap partition that is at least twice as big as your memory. If your swap is on an LVM partition, read the later part of this section; if it's on raid, there is support also [FIXME].
Back up your data before your first test. No joke! If you happen to have an unsupported driver, bad things can happen.
Now, build your kernel with CONFIG_SUSPEND2=y, CONFIG_SUSPEND2_SWAPWRITER=y, CONFIG_SUSPEND2_CRYPTO=y, CONFIG_SUSPEND2_USERSPACE_UI=y, and CONFIG_SUSPEND2_DEFAULT_RESUME2="". You should specify your resume partition by passing an argument at boot time. Of course, to avoid typos, edit your boot configuration. For Grub users, this means appending the argument "resume2=swap:/dev/something" to your kernel boot line, where "/dev/something" should be replaced with the full name of your swap partition.
If you want to use compression, you should build LZF capability into the kernel, by setting CONFIG_CRYPTO=y and CONFIG_CRYPTO_LZF=y. You can make them into modules but then you must use an initrd image to supply these modules at boot time.: Can't translate "/dev/..." into a device id yet.,: /usr/local/sbin/hibernate You will see all devices suspend and then resume again briefly; at this point the swap image will get written and you'll see a progress count. After the image is written, devices will be suspended again and then your system should power off. It's really fast, much faster (in my experience) than swsusp1.!
Many other useful entries for swsusp2 are available under /proc/suspend2/. Warning: please note that this location is only valid for swsusp2 versions 2.2-rc8 and later! For earlier versions, you must look in the directory /proc/software_suspend/ instead.
On a system where your swap partition is an LVM partition, you must take a different approach. You must use initrd/initramfs.
Build your kernel with the same configuration options as before., with some hacking. Change the lineto . Warning: please note that this location is only valid for swsusp2 versions 2.2-rc8 and later! For earlier versions, you must use the file /proc/software_suspend/do_resume instead. Then you can), and echo *gt; /proc/suspend2/do_resume. All of this must be done before any filesystems are mounted. If you wait until afterwards, you are almost guaranteed to have data corruption. It should also have a fallback present in case the resume fails (i.e. the next line after the echo into /proc/suspend2/do/initramfs-based suspend: /usr/local/sbin/hibernate. And if you haven't realized it yet, never write into /proc/suspend2/do_resume yourself, or you will cause the kernel to try to resume from whatever device you specify, right then and there. That is a sure recipe for disaster!
Using Nvidia drivers with swsusp2 may take a little work. You'll have to rebuild your nvidia module as described above for swsusp1, and install it. Change any settings in your xorg.conf file as well, as described above.
Then try the suspend. If it doesn't work, what may happen is that you see some disk activity, the screen goes blank, there's more disk activity, and then the machine stays on. If this happens to you, see if Ctl-Alt-Delete will let you reboot your machine. If it does, then check your logs to see if there is a complaint like "Pageset1 has grown by 381 pages. Only 100 growth is allowed for!". If there is, you can (probably) change one line and get swsusp2 to run.
If in your log you instead see a lot of lines likethere may be so many of them that they overflow the message buffer and you don't see all the steps for suspend/resume logged. To turn these off for the moment, you'll need to edit kernel/sched.c, and in the schedule() function, edit this bit: to comment out the and the lines. Then run the suspend again; you should be able to see the real suspend/resume errors and check what's wrong. When you are done, uncomment these lines and rebuild your kernel again, because these catch other errors than those just in swsusp2.
In your linux kernel source tree with the suspend2 patches applied, edit kernel/power/prepare_image.h: and change the lineto read . This assumes that the pageset1 growth is < 500 pages. If it's much more than that, this may be a sign of some other problem.
In some cases, your X display may come back fine but switching to other consoles may give you garbage; I find this to be true on my hardware.
[FIXME put info about ATI drivers here, as needed.]
Note: If you are using Fedora Core 3 or 4, Matthias Hensler maintains kernel rpms and special versions of mkinitrd at which you can use. Rpms for the hibernate script are also available for download there.
If resume fails after a successful suspend, you have a suspend image written to your swap and you'll have to deal with it.
Add the boot parameter "noresume2": there is no official name for this version of suspend to disk. It's referred to as swsusp3 in this document because that name has been used in a couple of postings (and rejected, too :-)) And it is the third set of code in current development.
Swsusp3 is a set of very preliminary patches that Pavel Machek is cooking up. Don't use these unless you like being on the very bleeding edge and don't mind restoring all of your data. These patches were first introduced on the Linux kernel mailing list and linux-pm in mid-September; see and for the patches and discussions on both lists.
So you really really shouldn't do this at home, kids.
But if you just have to try it anyways, first, back up all of your data. Really. Not like you pretended to back it up for swsusp1 or swsusp2 and you went ahead and built the kernel and crossed your fingers and hoped. Go Do It Now., you're on your own.
The patches on the linux kernel mailing list are a bit older. I have a patch generated from Pavel Machek's git tree which almost applies cleanly to 2.6.14-rc4, and the one piece that doesn't, doesn't matter right now (it's a comment and one line of code).
You can get the patch from for the moment. Or you can pull his tree for yourself and generate your own bleepin' patch.
Now, build your kernel with CONFIG_SOFTWARE_SUSPEND=y.. Swsusp3 will complain if it can't find your swap partition; if so, check that your swap is on a physical partition and that any underlying modules that need to be loaded before the partition can be found. Check that IDE and/or SCSI support is built in directly to the kernel, and try again until the message goes away.
You have a little bit of prep to do first before using this suspend. Go to the root of your linux kernel tree and cd into usr/. Edit the file swsusp.c, changing the linesto Build the program swsusp.c by running gcc -g -Wall usr/swsusp.c -o usr/swsusp-bin -static -I. You need this to be statically built because it's going to go into your initrd image which you are going to have to build and use.
Now you must get several supporting utilities or patches to them. [FIXME other distros...]
For RedHat/Fedora, you need mkinitrd version 4.2.22-1 or later; util.
Because swsusp3 clears the special suspend signature ("swsusp3") in the swap file and sets the signature area to zeros, there is not an easy patch or even a hard one to e2fsprogs/swapon to write the swap signature back in. You are going to have to run mkswap on your swap partition after every successful resume instead.
Now it's time to work on the initrd/initramfs image..
Make sure that the newly compiled swsusp binary is in your initrd/initramfs image somewhere useful, say in /bin. In Fedora Core 4 you can just add the line inst /src/kernel/swsusp-bin "$MNTIMAGE/bin/swsusp" just before the write of the init file, i.e. before the line echo "#!/bin/nash" >| $RCFILE.
Now you must add commands that create /dev/kmem and that do the resume, to your init or linuxrc script in your initrd. In Fedora Core 4, if you look at the init file that is generated by mkinitrd, you can see a section where there is a series of mknod commands; mknod /dev/console, mknod /dev/null, and so on, that are getting stuffed into the init file. Add the line mknod /dev/kmem c 1 2 at the end of that list. For other distributions, your method may vary.
Now make sure the resume will happen: the line resume /dev/swap-partition-name must also be written into the init file so that it will happen before any file systems are mounted. In Fedora Core 4, you can comment out the line # echo "resume $swsuspdev" >> $RCFILE and add the line echo "swsusp $swsuspdev -r" >> $RCFILE right after it. It should also have a fallback present in case the resume fails (i.e. the next line after the swsusp command should handle resume failure).
Once you've got your initrd in place, make sure you edit your grub.conf or other boot configuration file to use the new initrd image file: add a line initrd /initrd-2.6.14-rc4.img (or whatever your kernel name is) to the stanza for booting your new kernel. Example:
Finally, put the swsusp-bin file somewhere on your root filesystem in your path, so you can run it from userspace to do the actual suspend. I have it in /tmp/swsusp for testing. For the first test, you might want to be root and init 3 so that X isn't running. It's also a good idea to unload usb modules, PCMCIA modules, and network/wireless modules.
Now give the following command: echo shutdown > /sys/power/disk; /tmp/swsusp /dev/swap-partition-name -s -o.
On a system where your swap partition is an LVM partition, you must add yet more things to your initrd. If you are using Fedora Core 4 and you got the updated version of mkinitrd as described above, then you don't have to add anything; mkinitrd has been updated to get your logical volumes set up already.
Otherwise, you can build one yourself. At a minimum, it should have a statically linked version of /bin/lvm. Your init or linuxrc script should create /dev/mapper/control, run lvm vgscan --ignorelockingfailure, and run lvm vgchange -ay --ignorelockingfailure VolGroup00. (you should include the volume groups that contain your rootfs and your swap partition). It must, of course, do this before trying to resume.
To suspend, do exactly the same as before, but provide /dev/mapper/where-to-find-your-swap as the first argument to swsusp, and observe the same caveats; no hardware changes, don't touch any partition that was mounted when you suspended, don't touch the swap partition.
Don't even think about Nvidia or ATI drivers with this. Don't even think about using X. Be happy if you don't have to reinstall your OS afterwards. :-)
"I told you so." Ok, seriously: if you can boot your system ok, then you may be able to recover grace.
[FIXME give more details in this comparison.] Swsusp1 worked for me with the least fidgeting. It took a while to figure out that I had to build in CONFIG_PM_STD_PARTITION="" with LVM. That was frustrating. But after that it was smooth sailing. Swsusp1 is bare bones but gets the job done.
OTOH swsusp2 has many more configuration options for the hapless user, and given the state that suspend support is currently in, this is a good thing. I had to get around the "scheduling while atomic" error messages on resume failure, but after that it was very easy to debug and use. It was also faster to suspend and resume than swsusp1. I hear there is eye candy for it but since I don't/can't use that (no text consoles during or after suspend), I don't include it in this comparison. There's a wiki, a mailing list, and all kinds of documentation, too. (See for the wiki, and for the users mailing list.) For people who want to suspend to a file rather than a partition, swsusp2 is the only patchset that permits this. You can also write to a file over the network. (!)
So, if you want a lot of user support and configuration options, go with swsusp2, or if you want to suspend to something other than a swap partition. If you don't want to build your own kernel (and your distribution comes with the right configuration options built in), use swsusp1. Maybe we'll get the best of both in some version in the future.
Swsusp3? Surely you jest. But if you have to be able to boast about using something that's so cutting edge there's no release of it yet, then, this is the version for you. Urk!
Try building in support for these as modules, and unload them before suspending. Swsusp2 has support for this in its configuration files. Some folks have acpid suspend on lid close and unload the modules just before suspension. If you use a script to suspend, unload the modules in there, and reload them after resume.
Additionally, USB has suspend support available. You can try enabling that vis CONFIG_USB_SUSPEND to see if USB devices work better for you.
For 2.6.14-rc4, there are several patches for usb you can add, as well. Try them in this order: first, Greg KH's patches as one giant file, at; then the suspend/resume patch for usb storage, at; and finally, one more tweak for these patches, at.
Help us debug the problem. Here are some steps to take:
Rebuild your kernel with support for as few devices as possible. Turn off usb, pcmcia and networking support. Turn off firewire and wireless too.
Turn off the framebuffer device.
Turn off optional devices in your BIOS; my Dell laptop lets me turn off the modem and wireless devices.
Boot as single user and try to suspend/resume from there. If it works, try building in support for the things you removed as modules, and insmod them one at a time to test with suspend/resume to see if you can find out which driver is causing the problem.
If you still can't resume, turn on any debugging level logging available, get what you can from the logs, and submit a bug report.
[FIXME get more specific here]
Vbetool is a set of userspace tools for controlling your display by communicating directly with your graphics adapter. This tool bypasses the BIOS. It is safer to use than the same techniques in the kernel which could send the kernel into a hung state.
Most distributions come with vbetool. If you want the latest version, you can find it at. The file with "orig" in the name will build on any linux platform; the patches are for a Debian package.
To build it, unpack the tarball, cd into the directory where you unpacked it, ./configure, and then you may have to edit the Makefile. If you try make, and you get these errors:
then you need to edit the Makefile to change the line to . Then make should produce the executable vbetool. Do make install to install it into /usr/sbin and to install the man page.then you need to edit the Makefile to change the line to . Then make should produce the executable vbetool. Do make install to install it into /usr/sbin and to install the man page.
Vbetool will use the VESA 4Fh call to save or restore hardware state. This includes the hardware state, the video BIOS data state, the video DAC state, and the Super VGA state. The state information is requested directly from the video BIOS of the graphics adapter.
Save it into a file just before you suspend and then read it back from that file after the resume: vbetool vbestate save > video-state suspend, resume, and then vbetool vbestate restore < video-state
DPMS stands for Display Power Management Signaling. DPMS compliant monitors use Hsync and Vsync to put the display into normal, standby, suspend and power off modes. LCD panels don't use the same method but they support these same four states.
vbetool dpms off turns the display off and vbetool dpms on turns it on. This is reported to work for some people to re-enable the video, sometimes in combination with other options.
The post option reinitializes the video adapter by executing the code at the 3rd byte of the expansion ROM in the card. Strictly speaking, it jumps to the third byte of a copy of the ROM which Linux has placed into c000:0000h.
This approach can fail; the expansion ROM can later jump to someplace in the system BIOS code, expecting system BIOS functions to be available to vbetool, and they won't be. Or, it can jump somewhere which has zeros; this can happen because video adapter initialization code is typically thrown away by the BIOS after boot, and sometimes not made available again after suspend/resume.
I have heard rumors that some laptops have expansion ROM that contains compressed data which is both the video rom and the system bios; these may not get uncompressed and stuffed back into the shadow rom memory area after suspend/resume.
Use this option by typing vbetool post.
Suspend to RAM/Resume for the SATA subsystem is incomplete. Jens Axboe has a patch that has worked for some people including me. If you have a laptop with a device that is recognized as SATA (this includes devices that are PATA but have a PATA->SATA bridge, like the Dell XPS Gen 2), you should consider using this patch. You can find it at and it applies cleanly to this kernel. SUSE, Ubuntu, and some other distributions have this patch already applied. A secondary patch that is needed sometimes on SUSE kernels is at. Fortunately, there is some discussion of getting this patch merged real soon now; see for the full thread.
Symptoms of the problem include a message in your logs likeor having the hard drive LED remain on continuously and your system lock up after resume.
There is a series of patches for the radeonfb driver which... [FIXME]
There is a kernel patch that allows you to specify that your graphics adapter should be reinitialized during resume. [Where in the process does the reinit happen?] You can try using this if you have no video after reboot, though it's not clear that this will do anything for you that vbetool won't do.
tgs had some problems, go look them up. I think they are fixed.
Problems have been reported with the IRQ reassignment after suspend/resume. One fix is [HERE] though it has not yet made it into the kernel. Here's why...
Symptoms of this problem are:...
Turn on debugging in your kernel. Here are the debugging options that produce useful messages in the log:
Try the hwsleep suspend simulation patch. This skips the final step in suspend, i.e. change to power state. If your system does not come back after this, but hangs somewhere weird, you might be able to recover everything out of the logs up to the failure [FIXME is this true?]. And if it works well, you may have a problem with BIOS/hardware/initialization issues. You probably have to apply this patch manually, right after the linesand right after the lines
Look at your DSDT (see below).
DSDT stands for Differentiated System Description Table. This is a pile of code which defines all of the devices that ACPI is going to interact with, and all of the methods used to interact with them.
The ACPI specification requires some functions such as _WAK (wake from suspend) to be implemented, and it requires so many arguments, certain return values, and so on. If your system's DSDT does not meet these specifications, some functions may not be recognized or enabled.
There are three quick ways you can check your DSDT. First, you can look at linux-laptops.net (or acpi4linux) at the list of laptops and see what they say about yours.
Second, you can use acpidump to extract your dsdt. See Extracting ACPI tables with pmtools for information about getting and building acpidump. To get at the dsdt table, do the following:
Now you have the DSDT table in binary form. To disassemble it, get iasl (see ASL compiler / AML disassembler iasl for how to do this), build it, and then doand it will create the output in mydsdt.dsl
Alternatively you can cat /proc/acpi/dsdt into a file, then and then run iasl on that file.
To see if your DSDT is broken, you recompile it: iasl -tc mydsdt.dsl
You'll get output like this:Warnings can generally be ignored; errors must be fixed.
Look at the resources in ACPI on Linux laptops to see if your errors are documented. If not, check the ACPI specification. Edit the disassembled file, run iasl on it again and see if you have eliminated the errors. An example: [FIXME put one!]
You need to build it into your kernel or add it to initrd. Here's how to do either of those:
To build it into your kernel, first you must get it into the correct form. You need to convert it to the human-readable hex format that the kernel expects. This file will have a line near the beginning which readsTo convert your DSDT source file into this format, use the command ./iasl -tc mydsdt.dsl, where mydsdt.dsl should be the name of the file containing your disassembled dsdt file that you edited. You'll get an output file with the same naming ending in .hex. You'll also get a file called DSDT.aml which you can get rid of.
Put this new file someplace convenient for building into your kernels; say, /usr/src/dsdts/mydsdt.hex. Now you can rebuild your kernel; set CONFIG_STANDALONE=n first, so that you get the other options to show up in your config file. Then set CONFIG_ACPI_CUSTOM_DSDT=y and CONFIG_ACPI_CUSTOM_DSDT_FILE="/usr/src/dsdts/mydsdt.hex" (substitute the full name of your file here). Make and install, and your new DSDT table will be used in place of the old buggy one. You can check this by catting /proc/acpi/dsdt to a file, using iasl to disassemble it, and checking that your changes are there.
If you don't want to build your DSDT into your kernel every time you upgrade it, you can use an initrd/initramfs image and put it there. Some distributions come with support for DSDT in the initrd already; Fedora Core 4 does not.
You'll need to get the appropriate patch first, from; choose the one that goes with your kernel version or close to it. For 2.6.14-rc4 there is the acpi-dsdt-initrd-v0.7e-2.6.14.patch which applies cleanly. This patch also includes the cleanup for initramfs, in case your distribution uses an initrd that is an initramfs image (a initrd image that is in cpio format, with init as the script that runs, rather than linuxrc).
Now build your kernel with CONFIG_ACPI_CUSTOM_DSDT *off* and with CONFIG_ACPI_CUSTOM_DSDT_INITRD=y. If you turn on CONFIG_ACPI_CUSTOM_DSDT by mistake, then this will override the CONFIG_ACPI_CUSTOM_DSDT_INITRD option, which is not what you want. Make and install your kernel.
Now you need to add your DSDT to your initrd/initramfs image. You can just tack it on at the end, instead of using mkinitrd to shove it in there. Do the following:The INITRDDSDT123DSDT123 string marks the next piece as the DSDT; this is why the table can go anywhere in the initrd image. Note that this patch needs the Aml (i.e. binary) form of the DSDT, not the hex version that gets built directly into the kernel. If you ran iasl -tc mydsdt.dsl earlier after fixing your DSDT, you now have the file DSDT.aml which can be used exactly for this purpose.
On reboot with your new kernel and image, you should be using the new non-buggy DSDT. You can check this by catting /proc/acpi/dsdt to a file, using iasl to disassemble it, and checking that your changes are there.
First, be sure you have read the appropriate sections of this HOWTO and tried all of the workarounds documented there.
If you are trying Suspend-to-RAM, have you tried the various boot parameters? Have you tried all of the vbetool options? Did you try suspending after booting single user and removing all unnecessary modules?
If you are trying suspend to disk, have you...??
Are you using the most current BIOS, acpid, kernel included with your distribution or vanilla kernel, and X for your system?
Second, read Documentation/power/video.txt and make sure that you have tried everything listed there. Also read Documentation/power/tricks.txt and try those too.
Third, search the existing bug reports at bugzilla.kernel.org under component ACPI to see if your problem has been reported for your hardware.
If it hasn't, continue on to the next section to see what to put in your bug report.
Please submit all bugs to bugzilla.kernel.org under the component ACPI.
You should include the following information:
Name and version of the distribution you are using
Version of the kernel you are using and whether it is provided by your linux distribution or whether it is a vanilla kernel
Description of any patches you have applied to your kernel
The full output of acpidump (See The acpid events handling daemon.)
The output of dmidecode (See dmidecode for more information on this utility.)
Output from dmesg
Output from /var/log/messages
/sbin/lspci -vvxxxx output from before and after suspend/resume
List of any boot options you used
Your .config file for your kernel build
The contents of any script you use for suspend/resume
Step by step description of what you did from boot through suspend/resume and what the outcome was
Whether you are using proprietary X drivers, if you are suspending from X
Download pmtools from. The most recent version as of this writing is pmtools-20050823.
Unpack the tarball, cd into the directory where you unpacked it, and type make to build acpidump. Also included are the scripts acpixtract and acpitbl. These three files should now be copied into a useful location like /usr/local/bin.
To run acpidump, be root and at the command prompt, type acpidump.
If your system is ACPI-compliant, acpidump should print out a long list of tables and their contents, including the RSDT and the DSDT.
You can use acpixtract to extract your dsdt or any specific table. To get at the dsdt table, do the following:This also works for any other table name including the FACP, SSDT, and RSDT.
If you need to extract a table which has more than one instance, such as the SSDT on my platform, you can use a slightly different version of acpixtract which I changed to allow you to specify a count after the table name. So if you dothen you'll get the third instance of the SSDT table. If you have no such instance, you'll get an empty file. If you leave off the count, you'll get the default behavior, a dump of the first table instance. The code for the modified acpixtract is at the end of this HOWTO.
Iasl is a compiler for ASL, ACPI Source Language, defined in the ACPI specification. It is also a disassembler for AML, the ACPI Machine Language, also defined in the ACPI specification. It will disassemble AML into ASL. You can use this tool on various ACPI tables, in particular, the DSDT, so that you can edit it, compile it, and use the edited version instead of the buggy one your vendor may have provided in the BIOS.
You can find the most recent version at Intel's ACPI downloads page, at. Scroll down to the "Source Code" section and look for the "ACPI CA - Unix Build Environment" link. The most recent version at this writing is acpica-unix-20050902.
Unpack the tarball, cd into the directory where you unpacked it, cd compiler, and make. This will produce the executable iasl which you can put in some useful location like /usr/local/bin/.
To disassemble a table, first get the table in binary form, for example, acpidump | acpixtract DSDT > mydsdt.bin, and then do iasl -d mydsdt.bin. This will produce an output file called mydsdt.dsl which you can now edit.
To compile a table into AML, simply do iasl -tc mytable.dsl where mytable.dsl is the table in ASL.
Although these options will probably get you through the uses of iasl described in this document, there are many others; type iasl --help to se them all.
Dmidecode queries your BIOS about your system's hardware details. This includes, according to the dmidecode project page at, the system manufacturer, model name, serial number, BIOS version, and often information about expansion slots and I/O ports. This information is useful in conjunction with bug reports about ACPI, when someone is trying to decipher what is going wrong on your hardware.
Most distributions come with it prepacked. Fedora Core 4, Gentoo, and Debian ship with it. It may be in /usr/sbin rather than your normal path, so poke around.
You can download the sources from. At this writing, the most recent version is dmidecode-2.7.
Uncompress the tarball, cd into the directory where you unpacked it, and type make to build it. This will give you the executables dmidecode, biosdecode, ownership, and vpddecode. You can install these into /usr/local/sbin by typing make install. This will also install the man pages and other documentation.
Be root, and at the command prompt, just type dmidecode > lots-of-output.txt. Volumes of information should now be present in the output file.
There are 6 system power states, S0 through S5; 5 device states, D0 through D4; and a number of CPU power states, depending on your processor; my Dothan Pentium M supports states C0 through C4.
S0 is when the system is functioning normally, with all devices in their highest power state, S5 is when the system is in "soft off", powered off but AC or some other power source is still connected, and the other states are in between. In particular, S3 is suspend to RAM, and S4 is suspend to disk (also called hibernation). The idea is that a given state Sn is closer to S0 (fully awake) the smaller n is; it will use more power in that state but take less time to wake. So in S3, you can resume pretty fast compared to S4, but you use more power staying in S3 for a given length of time than in S4.
If a device is in D0, it is completely functional, and if it is in D4, it is powered off. The other states are in between; in particular, D3-hot is when the device has lost all context but still has power; the OS should have saved any context that needs to be restored when the device becomes operational again. D3-cold is when the device has lost all context and no power is applied. Devices coming back from D3-cold to D0 are expected to be uninitialized but D3-hot devices may or may not require initialization upon waking. Many devices do not support D1 or D2 states. As with S0-S5, a device in Dn for smaller n should consume less power but have lower wake latency than for a larger n.
When your system is in S0, some devices may not be in D0 because your power management profile suspends them if they are not in use.
If a processor is in state C0, it is fully functional; in any other state, it is idle (doing no work). Lower power states use less power but the CPU will take longer to transition to a higher power state. So if your PCU is in C4 it will use less power than in C3 but it will take longer to transition to C0 than from C3. The kernel will place the CPU into a lower power state automatically when it is not busy, if you enabled CONFIG_ACPI_PROCESSOR. See the kernel configuration reference for the CONFIG options.
Let's start with the Root System Description Pointer (RSDP) which lets you know how to find everything else. This pointer tells you where to find the Root System Description Table (RSDT) and/or the Extended System Description Table (XSDT). The RSDT is a holder from the 1.0 ACPI spec; the XSDT has the same information but allows the use of 64-bit addresses. This table contains pointers to the Fixed ACPI Description table (FADT) and other tables.
The FADT describes various ACPI registers, information about the SCI interrupt used by the ACPI subsystem, and information about legacy power management support (SMI). it also contains a pointer to the Firmware ACPI Control Structure (FACS) and the Differentiated System Description Table (DSDT). The DSDT contains descriptions of various functions that allow you to retrieve information about fan, temperature, button status, and so on, as well as to control various devices through the ACPI interface.
The Secondary System Description Table (SSDT) is an extension of the DSDT. Your platform may have more than one such table. A pointer to it is located in the RSDT. These are meant to be add-on tables that describe various optional features that your vendor may supply depending on your particular hardware configuration.
A full description of these tables is in section 5 of the ACPI 3.0 specification.
You should be reading the acpi-devel mailing list at, the linux-pm mailing list at, and, unfortunately, the linux kernel mailing list at. You can also have a look at linux-pm-devel at, which is much lower traffic. That ought to about cover the reading material. You can also monitor the bug reports at for the very latest news.
Linux on Laptops () entries for specific laptops often contain ACPI related configuration information. This is a great place to start.
TuxMobil () collects Linux installation reports which also have great information.
Ubuntu has a good list of test results for suspend for various laptops at.
If you are looking for a fix for your laptop's DSDT, please check the ACPI4Linux DSDT repository at. If you don't see it there, and you add fixes yourself, please add the new DSDT to the repository so others can use it.
In no particular order, here are some HOWTOs I have found helpful.
Emma Jane Hogbin's ACPI HOWTO (August 2004), at
Gentoo Forum -- HOWTO: Fix Common ACPI Problems (DSDT, ECDT, etc.) (February 2004), at
ThinkWiki -- How to make ACPI work (September 2005), at
SuseWiki -- Suspend NVidia HOWTO (September 2005), at
Richard Black's Linux ACPI Howto (February 2004), at
Powersave Documentation (June 2005), at a
Battery Powered Linux Mini-HOWTO (July 2003), at
Gentoo's Power Management Guide (June 2005), at
The ACPI4Linux Wiki (September 2005), at
The Software Suspend 2 HOWTO (July 2005), at
The Software Suspend 2 Wiki (October 2005), at
In no particular order, here are some papers I've found useful:
Takanori Watanabe, ACPI implementation on FreeBSD, at
Pramode C.E., Dissecting the ACPI Button Driver in Kernel 2.6, at
Dominik Brodowski, Current Trends in Linux Kernel Power Management, at
Srivatsa Vaddagiri, Power Management in Linux-Based Systems, at
Len Brown, July 2004, The State of ACPI in the Linux Kernel, at
The main source for official documentation is. They have the most recent specification, ACPI 3.0, available at. Microsoft has class specifications for devices at which describe each class of device does in a given power state -- which parts of the device are powered off, and what functionality it has in the given state. Intel's ACPI page at has good information too.
If you spend much time looking at the driver, you are going to want the PCI specifications, but you can't just download them. Check the PCI SIG website at to get them. Fortunately, chapter 12 of the Linux Device Drivers book version 3 at can get you through some of the code. A good deal of Linux-specific information about PCI devices and drivers is covered in David A Rusling's The Linux Kernel at, although it was written eight years ago. You can also look at /usr/src/linux/include/linux/pci.h for a list of every register and bit that Linux knows about in the PCI configuration space.
You may want the VESA BIOS extension specs at too if you read through the vbetool or ACPI video code.
[FIXME put some info here]
You can build in a number of kernel-based cpu frequency managers. Each of these has a different policy for what frequencies it sets the CPU to under which conditions.
To build in support for the "performance" CPU frequency manager, select CPU_FREQ_GOV_PERFORMANCE. Under this manager, the CPU frequency is set to the maximum possible at all times.
To build in support for the "powersave" CPU frequency manager, select. CPU_FREQ_GOV_POWERSAVE. Under this manager, the CPU frequency is set to the minimum possible.
To build in support for the user to control CPU frequency directly, via an entry in sysfs, select CPU_FREQ_GOV_USERSPACE. Most userspace applications that control CPU frequency such as cpuspeed or powernowd require this.
To build in support for the "ondemand" policy CPU frequency manager, select CPU_FREQ_GOV_ONDEMAND. Under this manager, the CPU frequency is changed depending on usage. Your CPU should be able to make very fast frequency changes for this manager to be effective.
To build in support for the "conservative" policy CPU frequency manager, select CPU_FREQ_GOV_CONSERVATIVE. Under this manager, the CPU frequency is changed depending on usage. However, it changes speed more slowly than the "ondemand" manager. This is a better manager to use when your CPU has a higher latency for switching frequencies, as laptop CPUs often do.
Of course there's no reason you should have to choose just one of these; at least one userspace application for frequency management expects you to have built in both the "performance" and "powersave" managers, and it switches between them depending on the load.
Once you have built in the managers you want, you must also set the default frequency manager; choose one of CPU_FREQ_DEFAULT_GOV_PERFORMANCE or CPU_FREQ_DEFAULT_GOV_USERSPACE which sets the default CPU frequency manager to the "performance" or "userspace" manager, respectively. Currently these are the only defaults supported, but you can always change the manager after boot.
Once you enable CONFIG_CPU_FREQ, you can choose a CPU frequency driver. Only certain drivers have an ACPI interface option; those are the only ones discussed here.
If you have a mobile AMD K7 (AMD Mobile Athlon/Duron), you should select CONFIG_X86_POWERNOW_K7 and CONFIG_X86_POWERNOW_K7_ACPI. If you have an AMD K8 (AMD Opteron/Athlon64), you should select CONFIG_X86_POWERNOW_K8 and CONFIG_X86_POWERNOW_K8_ACPI. If you have the Centrino chipset (Intel Pentium M), you should select CONFIG_X86_SPEEDSTEP_CENTRINO and CONFIG_X86_SPEEDSTEP_CENTRINO_ACPI.
If you have none of these, you can select CONFIG_X86_ACPI_CPUFREQ to build in the generic ACPI P-states driver. You can only use this if your system supports CPU performance states; in particular, your CPU must support the ACPI _PSS method. If it does not, you'll get an error when you try to load the module or initialize the driver. Most ACPI 2.0 compliant platforms should support this.
Now that you have some cpu frequency managers and the appropriate driver built into your kernel, you'll probably want a userspace application that you can configure to change the CPU frequency depending on your needs. It might regulate frequency only when you're not on AC, or it might step through various frequencies depending on load, or it might switch between max and min performance. There are a number of such applications, which include cpudyn, cpufreq (formerly cpuspeed), powernowd, and cpufreq-applet. A discussion of how to build, configure and run these is beyond the scope of this document. Many Linux distributions supply them as packages, however, with some reasonable default configuration.
If you want to change your CPU frequency manually, you can write the new frequency, in kHz, into /sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed. This means that if you want 800MHz, you do echo 800000 > /sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed. Don't worry; if you forget and put 800, the driver will find the lowest supported frequency for you and use that instead. You can check those supported frequencies by looking at /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies.
Turn on these configuration options for base ACPI support:
turns on power management
turns on ACPI
If you build into your kernel both APM and ACPI, and an ACPI-compliant BIOS is found, ACPI will be used and the APM-related functions will be disabled. So it's safe to enable both, if you are concerned that your system might not support ACPI.
Turn on these options for specific functionality:
Plug and Play devices
If you have plug and play devices, setting this option will enable the use of ACPI to detect and allocate resources for those devices rather than using the PnPBIOS. In almost all cases it's safe to enable this.
Suspend-to-RAM:
enable suspend to RAM
suspend to disk:
enables suspend to disk
sets the partition to be used for suspend to disk
Control over various devices:
Allows you to be notified when you switch to or from using an adapter as your system's power source, so that you can specify an action to take
Allows you to retrieve information about your battery, including how much capacity it has left, and be notified when battery charge drops below a certain level, so that you can specify an action to take
Allows you to be notified the sleep or power button is pressed or you close your laptop lid, so that you can specify an action to take
Allows you to control brightness, set which video display you use, get the EDID (extended display identification data) from a video display, and set which video adapter will be POSTed at next boot if you have more than one video device.
Allows you to turn your fans on or off or check their status
Allows the kernel to put your CPU in a lower power state when it's idle; allows you to throttle the cpu by forcing the cpu to be idle in a percentage of its total clock cycles, when you are actually doing computation and you don't want to run the cpu at full load; allows you to limit CPU cycle usage when CPU temperature is too hot; required for system thermal management described below (CONFIG_ACPI_THERMAL). You should really set this item, even if thermal management is the only feature that gets used.
Unless you have a very good reason, set this. Most modern systems have temperature sensing, and when the temperature of certain chipsets or the CPU reaches a critical point, the system shuts down, or other actions can be taken, such as turning on additional coolers. This requires CONFIG_ACPI_PROCESSOR.
This driver adds a CPUFreq driver which utilizes the ACPI Processor Performance States. To use this, you must have earlier set CONFIG_CPU_FREQ. It has the advantage of allowing you later to link CPU throttling limits to changes in CPU frequency, but it has the disadvantage of being slower in comparison to hardware-specific drivers. But newer BIOSes will conform to ACPI 3.0 which uses MSRs instead of IO ports to change states, and then this driver will kick *ss. There is a patch in the works to take care of these new features. [FIXME test and see if centrino really is slower to change freq than p-state.]
Don't use this; it's deprecated. It creates the entry /proc/acpi/processor/../performance, but you should use the sys entries /sys/devices/system/cpu/.../cpufreq/ instead.
Specific laptop extras:
If you have an ASUS laptop with ACPI supported, say yes to get support for the extra keys, control over the notification LEDs, and for some laptops, backlight and brightness control.
If you have an IBM Thinkpad with ACPI supported, say yes to get support for hotkeys, Bluetooth enable/disable, video display switching, UltraBay eject, docking and undocking, and several other features. An up to date list of these features is available in Documentation/ibm-acpi.txt.
If you have a Toshiba laptop which has no BIOS menu settings and no APM support, you probably want this option. The Toshiba Libretto is one of these laptops. This driver will give you access to some Toshiba-specific features that are only now being integrated into the generic ACPI driver. Those include turning on/off the fan, switching the video display device, brightness control, and hotkey support. [FIXME What about so-called development plans from June 2005? More about how there is an "experimental" toshiba driver now with more features.]
Misc:
New, lets you map a hotkey to a specific ACPI event which acpid can handle. This driver is useful because vendors do not have standard event numbers mapped to hotkeys, and this driver lets you convert vendor numbers to a standardized list. Note that you must use the boot parameter acpi_generic_hotkey to enable this driver even after building it into the kernel.
If you set this option in your kernel, and your BIOS is before the year specified, ACPI will be disabled by default. Some distributions default this to 2001. If you are building a kernel to be used on many systems such as a kernel for a Linux distribution, this is a useful option.
Debugging/fixing broken implementations
Don't use this right away unless you know in advance that your laptop has a broken DSDT and that you need to compile in a fixed one. See ACPI on Linux laptops for lists of laptops with their DSDT fixes, and DSDT editing for a discussion of DSDT tables.
If you need to compile n a custom DSDT (see previous option), you must enable this option and give the full pathname to the DSDT file, compiled into AML code. See DSDT editing for how to compile DSDT tables.
If you are trying to debug problems with the ACPI subsystem, this will produce some useful debugging messages in your log.
memory (NUMA)
SRAT and SLIT tables are defined if you set this. These tables permit the system to determine which memory modules ought to be assigned to which nodes. [FIXME get a better description.] If you have a system which has NUMA enabled, set this option.
Hotpluggable memory and cpu
FIXME
FIXME
FIXME
If you have an SMP box with a hotpluggable CPU, and you need to be able to swap in a new CPU on failure, set this.
DSDT (Differentiated System Description Table) options To get these, you must choose STANDALONE under "Generic Driver Options".
Allows you to use your own edited and fixed DSDT in case your BIOS has a broken one. See DSDT editing for more information on this.
Specify the full path to the file that contains your fixed DSDT, so the build system can read the file and build the contents right into the kernel
Don't enable this, because it's deprecated:
Creates the entry /proc/acpi/sleep, which can be used to put the system into various suspend states, but this is deprecated in favor of the sysfs entry /sys/power/state.
If you built your kernel with acpi disabled, you can use this option to force its use.
If you built your kernel with ACPI enabled, you can use this option to turn it off (in case you'd rather use APM, it interferes with something else, or it's just plain broken).
Enable ACPI only to the degree needed to support hyperthreading. If you don't want to use most of the ACPI driver, but you want hyperthreading working, use this option so that the ACPI tables will be used for virtual processor discovery.
Be anal about syntax and method requirements in ACPI tables provided by the vendor; if you turn this on, you can find potential problems with your DSDT that may not show up by other means.
If this boot parameter is passed, upon wake from suspend, the kernel will try to initialize your video adapter by calling code at c000:0003h. In practice, this code may no longer be available after power on, so your system may crash. But for some people, this is the only way to get suspend to RAM to work. Use with caution.
Upon wake from suspend, the kernel will set the video adapter mode to the mode it was in before suspend, using the VESA BIOS mode set call (0x4f02). Use this if your system can get back to VGA text mode from suspend, i.e. it suspends ok from a text console, but doesn't work from X. This could crash your system so use with caution.
On some systems that require acpi_sleep=s3_bios, the system will be left in VGA text mode and so you'll need to do s3_mode as well.
Set ACPI System Control Interrupt trigger mode; it's very unlikely that you'll need this, as SCI handling has been stable for some time. However, if you have a prerelease BIOS, and you see messages in your log about unrecognized SCIs, try using one of these settings. [If someone who has to use this option would contact me, I'll add a better description.]
ACPI will balance active IRQs to minimize sharing. This is the default in APIC mode.
ACPI will not move active IRQs around (the opposite of acpi_irq_balance). This is the default in PIC mode.
If you have set acpi_irq_balance, you have to reserve some IRQs for for use by PCI or else ACPI may use them all; list them here. Format: <irq>,<irq>...
If you have set acpi_irq_balance, you have to reserve some IRQs for for use by ISA or else ACPI may use them all; list them here. Don't do this unless you have ISA devices. Format: <irq>,<irq>...
By default, the _OSI method in ACPI will tell the BIOS that we are running Microsoft Windows NT. But if you use this option with an empty parameter, it disables the _OSI method. (What does the BIOS do then?)
By default, the _OSI method in ACPI will tell the BIOS that we are running Microsoft Windows NT. But if you specify a name here, that OS name will be reported to the BIOS instead. This may enable or disable some methods in your DSDT depending on the OS string you choose.
If you see errors in your log which include things likethen try setting this option. It forces serialization of AML methods in case a method creates namespace objects, fails to complete cleanly, and leaves its debris around; this may allow us to track down the specific problem.
This option is specific to certain versions of the nForce2 BIOS which map IRQ0 to pin 2 and result in the timer being XT-PIC instead of IO-APIC-edge. This isn't really an ACPI issue but it's called acpi_skip_timer_override so it's in this document. See kernel bug 1203 at for more info.
Format: <int> ; Turn on or off debugging of a or several acpi debug layers. Each bit of the <int> indicates a separate layer. Starting from the rightmost bit, you can turn on debugging for the layers: UTILITIES, HARDWARE, EVENTS, TABLES, NAMESPACE, PARSER, DISPATCHER, EXECUTER, RESOURCES, CA_DEBUGGER, OS_SERVICES, CA_DISASSEMBLER, COMPILER, and TOOLS. If you don't do this at boot time you can still enable this by writing to /proc/acpi/debug_layer.
Format: <int> ; Turn on or off debugging of a or several acpi debug levels. Each bit of the <int> indicates a separate level. Starting from the rightmost bit, you can turn on debugging for messages logged at the level: ERROR, WARN, INIT, DEBUG_OBJECT, INFO, INIT_NAMES, PARSE, LOAD, DISPATCH, EXEC, NAMES, OPREGION, BFIELD, TABLES, VALUES, OBJECTS, RESOURCES, USER_REQUESTS, PACKAGE, ALLOCATIONS, FUNCTIONS, OPTIMIZATIONS, MUTEX, THREADS, IO, INTERRUPTS, AML_DISASSEMBLE, VERBOSE_INFO, FULL_TABLES, and EVENTS. If you don't do this at boot time you can still enable this by writing to /proc/acpi/debug_level.
use burst mode instead of polling mode for embedded controller; this mode is better in the long run than polling mode but not ready for prime time yet. Use it, however, if you see problems with button failure or battery status failure or other ACPI events just disappearing and not being handled; see kernel bug 3851 at for more information.
There is a generic hotkey driver which will let you map hotkey codes to specific acpi methods. It's not at all user friendly. Nonetheless, it may be useful for you if your laptop has hotkeys that use the ACPI interface. If you compile in the generic hotkey driver, using CONFIG_ACPI_HOTKEY, you must use this boot option for the driver to be enabled.
Some laptops have specific hotkey drivers for their setups; see the CONFIG options above for the list. If you set this option and you have compiled in both the generic hotkey driver and a specific driver for one of those laptops, only the generic hotkey driver will be used.
Workaround failure due to BIOS lacking ECDT; use this if you see errors in your log early on about the battery, adapter or the embedded controller. Setting this option lets the kernel ignore the missing ECDT, and come back to complete initialization of those devices later when it has pulled more complete information from the DSDT.
If your system seems not to be generating ACPI events, try setting this option. Here's the explanation, taken right from the kernel code:
Wake and Run-Time GPES are expected to be separate. We disable wake-GPEs at run-time to prevent spurious interrupts. However, if a system exists that shares Wake and Run-time events on the same GPE this flag is available to tell Linux to keep the wake-time GPEs enabled at run-time.
Do not use ACPI for IRQ routing. ACPI looks at _PRT packages to figure out which interrupt goes with which PCI interrupt link device and then looks up the resources that device uses. Instead, use the PCI IRQ routing table. If your kernel hangs during boot, you may have serious IRQ problems; try this option.
Do IRQ routing for all PCI devices. Each device should call pci_enable_device(), which will do this IRQ routing, but some drivers may be broken and not call it, so this option makes sure it gets called for each device outside of the driver. If you have problems with a particular device, try this option. Someday this option should go away. I wonder about proprietary drivers though... Maybe this option is here to stay.
Try this option if you are having trouble with PNP devices under ACPI; this will disable use of PNPACPI and will use PNPBIOS instead.
Limit processor to maximum C-state; if you enabled CONFIG_ACPI_PROCESSOR so that the CPU is placed in different power states when it is idle, you may want this. Various IBM Thinkpad systems emit a high-pitched whine when the CPU enters C3 or C4, so passing C2 as a parameter will prevent that. See ThinkWiki at to check your specific model.
If you don't want to lose the ability to use these lower power states, you can try adjusting your timer speed instead: set your default timer speed to HZ_100 (CONFIG_HZ_100).
If you know that your system should support C3 or C4 and a look at /sys/module/processor/parameters/max_cstate shows that it's set lower, you can try to increase it. Some BIOSes are blacklisted from these lower power states in the kernel. As of this writing, those are the IBM ThinkPad R40e, the Medion 41700, and the Clevo 5600D. Set max_cstate=9 to override this limit.
Most acpi hooks have not been moved over from the /proc filesystem. There are a few exceptions: entries related to cpu power states, cpu frequency, a device or system's power state, and the ACPI namespace tree. Also, hotpluggable devices may be controllable via a /sys entry.
Every device with an entry in /sys, including buses, has an entry which concludes in power/state. Some such entries on my system areIf you cat one of these, you will see the current power state of the device. See Power states for more on power states.
/sys/power/state controls the power state for the whole system, from S0-S5. If you cat this, you see what types of system sleep are supported. Right now, the kernel supports standby S1), mem (S3) and disk (S4). If you echo one of these states into /sys/power/state, the system will try to enter that sleep state. For example, echo disk > /sys/power/state will do suspend to disk (i.e. hibernation) which is the S4 sleep state. This assumes you have built hibernation support into your kernel, of course.
If you have devices which are hot-pluggable, you will see /sys/firmware/acpi/eject and you can echo the name of the device -- as seen from the ACPI namespace, unfortunately -- into this file and the kernel will prepare the device so that the user can then swap it out. The name will probably start "\_SB." and then you can append the actual name of the device. Look in your DSDT for devices with the EJ0 method. I'd have better information but my system has no hot-swappable devices. Sorry!
/sys/module/processor/parameters/max_cstate contains the lowest power state your CPU can enter. If you know your CPU should support C3 or C4 but you only see C2 listed here, your BIOS may be blacklisted. See Boot parameters reference for processor.max_cstate settings to override the blacklist.
CPU frequency entries can be found under /sys/devices/system/cpu/cpu*/cpufreq/, assuming you built in support for CPU frequency management. You can find some details in the CPU_FREQ reference although only ACPI-related information is covered there.
Various IBM Thinkpad systems emit a high-pitched whine when the CPU enters C3 or C4, so echoing '2' into /sys/module/processor/parameters/max_cstate will prevent that. But see Boot parameters reference for more about that problem.
/sys/firmware/acpi/namespace/ACPI shows the ACPI device namespace in tree form. If it's not clear to you from the name what a given device is, you can find it in your DSDT and grab the HID (Hardware ID) associated with it, and look it up in this list: If the _HID isn't listed there, it may be in the ACPI 3.0 specs. For example, in my DSDT, I seeIf I look up PNP0C01 in the list, I find: "PNP0C01 System Board".
Many /proc entries have not made it over to sysfs yet. Those that have are listed as deprecated here so you can avoid using them. You'll find all the entries under /proc/acpi. These include access to your DSDT and FADT; the ACPI event queue; battery info; CPU power and throttling state info; info on various buttons, video display info; and much more.
/proc/alarm
If you have an RTC (Real Time Clock) that supports an alarm, an entry that lets you set that alarm shows up here. To set the alarm, write to the file, using the following format:Once the alarm is set, the RTC will generate a hardware wake event when the system is in a sleep state. It's required to work from S1-S3 and optional for S4. You can tell if your system supports RTC wake from S4 by running this little script. It looks at the flags in the FADT for you; there doesn't seem to be a /proc or /sys interface that exposes this.
info
If you read the info file, it will print the version number of [FIXME]. For example:This is the same version that ACPI gives you in your log:
dsdt
This is the binary form of your DSDT; more details about that table are available in the section DSDT editing.
fadt
This is the binary form of your FADT, or Fixed ACPI Description Table. This table contains ACPI registers and a pointer to your DSDT. Check section What are all these ACPI tables? for a (very short) overview of some of the ACPI tables. is
event
This is where ACPI events are written so that userspace applications can process them. If acpid is running, it will read the events and when you try to cat them, the file will be empty. If you have no daemon running to process events, you can cat this file to look at them, and they will be in the same format as in /var/log/acpid. See Acpid events for more information.
embedded_controller
Embedded controllers are usually used to manage or communicate with smart batteries and smart battery chargers. If you have a smart battery, you'll probably also have an embedded controller, and it will show up here. It may be listed as /proc/acpi/embedded_controller/EC0, and in that directory, you'll have the file info. If you read that file, you can find out driver-level specifics. Some sample output is here:If your embedded controller has the _GLK method then you should see "use global lock: yes". If your controller supports the _GPE method (which it is supposed to do), then you'll have a reserved GPE bit for events, and that bit will be listed under "gpe bit".
battery
If you're using a laptop, you should have an entry /proc/acpi/battery for your battery. Often this will be called BAT0 or something similar. Underneath that directory, you'll have entries alarm, info, and state.
alarm describes at what capacity your battery will generate a [FIXME] event. Some batteries don't support alarms; in that case you'll see "unknown" instead of a value. If your battery supports an alarm, you can set the alarm by writing a number to "alarm", which will be the cutoff point in mAh; once the battery reaches that capacity or lower, it will generate a notify event and the OS will stuff the event into /proc/acpi/event where acpid can pick it up and allow you, the user, to respond. See The acpid event handling daemon for information on processing these events. You can set this number higher than the manufacturer default, but not lower. See below the description of "design capacity warning".
If your battery doesn't support alarms, the ACPI specification requires the OS to poll the battery to check its remaining capacity. It appears that Linux does not yet do this. In this case, it's best to run a user application that can check your battery status and take appropriate action.
info describes various capabilities of your battery. Here's a breakdown using a sample listing:
present: yes or no, depending on whether you have a battery inserted or not
design capacity: 7200 mAh -- your battery's capacity in milliamp-hours. My battery will produce 7.2 amps for 1 hour.
last full capacity: 7191 mAh -- your battery's capacity when it was last fully charged. This is likely to be a bit lower than the design capacity (i.e. the capacity when the battery came out of the factory).
battery technology: rechargeable, non-rechargeable, or unknown. Know anyone using a non-rechargeable battery? If your battery reports that it is non-rechargeable, you probably have problems with the ACPI driver; time to visit the kernel bugs list at (check the ACPI component).
design voltage: 11100 mV -- voltage of the battery when new
design capacity warning: 720 mAh - When the battery capacity crosses this point, it generates a notify event -- whether it is charging, and capacity just got greater than this value, or draining, and capacity is running low. Linux will pass that event on to /proc/acpi/event where acpid can pick it up. See The acpid event handling daemon for information on processing these events.
If your battery supports _BTP, you'll have the alarm entry described earlier, which allows you to set this number. Otherwise, it's set at a default value.
design capacity low: 218 mAh - how much energy needed to transition the system to a sleep state. If battery capacity gets to this point, Linux will put the system into some sleep state [FIXME which one, how?].
capacity granularity 1: 72 mAh -- As the ACPI spec says, "battery capacity granularity between low and warning in [mAh] or [mWh]. That is, this is the smallest increment in capacity that the battery is capable of measuring."
capacity granularity 2: 72 mAh -- Same as above, for warning to Full, except that this number can be different than capacity granularity 1 because in some systems, the granularity accuracy may change depending on the battery level.
model number: DELL C54475
serial number: 1768
battery type: LION
OEM info: Sanyo
state describes the current battery state. From a sample listing:
present: yes or no
capacity state: ok or critical; critical means that the batteries are drained. If you are on battery power only, Linux should be shutting down your system right now. :-)
charging state: charged, charging, discharging, charging/discharging
present rate: 1 mA (or other value) or unknown
remaining capacity: 7200 mAh (or other value) or unknown
present voltage: 12441 mV (or other value) or unknown
button
This is where sleep, power and lid controls are described. Let's look at each of these.
You'll have an entry under this directory for your power button, something like PBTN. The button will have the entry info, which you can look at to see if your power button is a CM (Control Method) type button, or an FF (Fixed Feature) type button. For more information on the distinction, read the ACPI specification; see Specifications for the link.
You'll have an entry under this directory for your sleep button, something like SBTN. The button will have the entry info, which you can look at to see if your sleep button is a CM (Control Method) type button, or an FF (Fixed Feature) type button. For more information on the distinction, read the ACPI specification; see Specifications for the link. If you don't have a separate sleep button, there will be an entry here anyways and your button will be classed as CM type.
You'll have an entry under this directory for your laptop lid button, something like LID. The button will have the entry info, which will tell you that you have a "Lid Switch". There are no other types defined at this writing. There will also be an entry state, which will either tell you that the lid is "open" or "closed". If you're thinking that this doesn't give you much new information, realize that this entry isn't meant for you; it's meant for acpid-related scripts or user applications to check and take appropriate action when they are notified of an ACPI lid event.
fan
For each fan, you'll have an entry in /proc/acpi/fan, called FAN or something similar. Under this entry, you'll have the file state which lets you see whether the fan is on or off by reading it. It also lets you write the fan state by echoing a number between 0 and 3, inclusive, to the file. State 0 corresponds to device power state D0, and so on. If you have variable speed fans that allow this, that's how to keep them quiet during low load times and cooling well during high load times. You'll have to experiment to see what RPM each of these states gives you, if you have other software that lets you monitor fan speed. Often, D0 is full on and D3 is off.
power_resource
You should also see the directory /proc/acpi/power_resource. Power resources are supposed to be things like power planes, i.e. sources that devices rely on and that can be turned off when all devices using them are turned off. Having said that, I don't know any specific objects that get classified as power resources, although some systems list power fans under this category.
Under this directory you'll have an entry for every resource with a file state underneath it. You can read this file to see if your resource is on or off. There's a bit more information included: the system level, which is the lowest system sleep level that the OS can put the system in and still keep this power resource on; the order, which lets the OS know which order to turn on or off all resources at a given system sleep state; and the reference count, which is for internal bookkeeping.
For each cpu, you'll have an entry in /proc/acpi/processor, CPU0-CPUn, and for each CPU you'll have the following entries:
0, unless you have a multiprocessor system, in which case, it'll be the number of the particular CPU.
CPU number by a different scheme. ACPI gets its cpu numbering via the MADT, which may result in a different numbering than the processor id.
This must be yes in SMP systems for C3 usage (to maintain cache coherency); if you don't have it and your system is SMP, C3 and lower power states will be unavailable to you.
If yes, the CPU can be placed into a state of type C2 or C3. This is not the same as being in states C2 or C3! See below for discussion of power state *types*.
If yes, the CPU supports some throttling states; see {FIXME} for a discussion of how these work.
It would be nice if this entry had some use. But it's actually set whenever throttling control is set. There ya go. [FIXME doublecheck]
If your cpu supports throttling states, you can see the highest throttling state that your cpu is currently permitted to enter. See What are throttling/performance state limits and how do I use them? for more information on throttling states.
In addition to throttling states and performance states, each CPU supports different power states; see Power states for more about this. The power file shows you the current power state, the maximum state that the system will allow the CPU to enter (the state where it uses the lowest amount of power), [FIXME], and a list of all states the CPU actually supports. In the supported power states list, the type field refers to the sort of preparation that the OS must do in order to place the CPU in that power state. So for example, in the listing below, both power states C3 and C4 require the OS to disable bus master arbitration before entering the chosen power state; that's the preparation the OS needs for the "C3 type".One other thing you should pay attention to in this listing is the usage field. This indicates how many times the CPU has been placed in this state (including from the very same state). Unless you are always doing very computationally intensive work, your listing should look something like the list above, i.e. your CPU should spend most of its time in the state with the lowest power usage, here C4. This is true even with cpu frequency management enabled. Your CPU should be idle most of the time and it should spend most of the time in the deepest idle state available. If that is not happening, you should check your kernel configuration and possibly report it as a bug.
The throttling entry shows you how many throttling states your CPU supports, which state your CPU is currently in, and how much of the time your CPU is forced idle for each state.See CPU throttling for more on throttling.
/proc/acpi/sleep is deprecated; use /sys/power/state instead.
thermal_zone
If your system supports thermal management, you'll have entries in /proc/acpi/thermal_zone. For each CPU and for any other devices your system can monitor and control via ACPI, you'll have an entry that begins THM or something similar. The entries for each of these include:
This entry describes the cooling mode currently in use. This can be one of active, passive, or critical. These are described in more detail in the Thermal management section. If your platform supports it, you can set the cooling mode to active by echoing 0 to this file, or passive, by echoing 1 to this file.
This shows the state of the thermal zone: either one of the cooling modes, if it is currently activated, i.e. critical, passive, active[0] - active[9], or ok if no cooling mode is in use.
This shows the trip points you have set for the various cooling methods your system supports. If your system only supports the mandatory critical trip point, then that's all you'll see, as on my system:If other methods are supported, you'll see trip points for those also, as in the example below:
The values for tc1 and tc2 are used to compute the optimal processor throttling state to keep the thermal zone temperature down below the passive cooling limit, and tsp is how often to sample the temperature while doing this adjustment. These values are fixed by the vendor and are provided here so that folks who are interested in the nitty-gritty can do the computation and see if the hardware behavior makes sense. See /usr/src/linux/drivers/thermal.c, function acpi_thermal_passive(), for more information.
This shows how often the temperature is checked, in seconds. By default, Linux sets this to whatever your platform implements via the _TZP method; if this method doesn't exist, then it's disabled. That means that by default, temperature polling is turned off on a lot of platforms. Fortunately, you can enable it by echoing a number to the file, where the number is how often to poll in seconds.
This shows the current temperature in Celsius of the thermal zone.
For each video adapter, you'll have an entry under /proc/acpi/video that starts with VID. You should have the following subentries:
[FIXME]
[FIXME]
[FIXME]
[FIXME]
[FIXME]
For each VID entry, you'll have entries describing displays. My system supports a variety of displays so I have the following entries: CRT, DVI, LCD, and TV. For each display you have these entries:
This lets you change the brightness of your LCD. You must use one of the supported brightness levels, which you can obtain by reading the brightness file. Some platforms don't support this.
Show extended display identification data for the display; this includes identifying information, hfreq, vfreq, resolution, and supported video modes. Some platforms don't support this. If you have one that does, I'd love to get the output so folks can have a sample in this document.
device_id: 0x0110 type: UNKNOWN known by bios: no
This lets you activate/inactivate the display. echo 0x80000001 > /proc/video/VID/*/state turns on the display, and echo 0x80000000 > /proc/video/VID/*/state turns it off. These esoteric numbers come from the ACPI specs; bits 1-29 are zero, and if you want to do actual switching and not just cacheing the change, you set bit 31 and clear bit 30. Bit 0 is set to activate the device and cleared to inactivate it.
If you cat the file, you'll see something likeThe value for state also comes straight from the ACPI specs: bits 5-31 are zero, and the meaningful bits are as follows: bit 4 [optional]: set if device is attached, bit 3: set if device is not defective, bit 2: set if output is ready to switch, bit 1: output is activated, and bit 0: output connector exists now. Given this, we can decipher 0x1f as 11111 = attached, not defective, ready to switch, activated, connector exists now.
wakeup
The entry wakeup has a list of which devices can change the power state of the system, and whether or not that change is enabled.
So in the list below, if your system is in S3 (suspend to RAM), and you open the lid, the system will wake to S0. If your system is in S4 and you press the power button, the system will wake to S0. The other wake events are disabled.
Retrieve a given instance of a table by specifying the number of the instance. For example, acpidump | ./acpixtract SSDT 3 > ssdt3 | http://www.columbia.edu/~ariel/acpi/acpi_howto.html | crawl-002 | refinedweb | 23,507 | 70.33 |
In the quick tour analysis you created a Beta executable by
compiling the code in the BetaMiniUser package.
When you issued the command:
workdir> BetaMiniApp snippet.tcl
>
> ev beg -nev 3
> ev cont -nev 37
> exit
main()
Framework/AppMain.cc.
The Framework allows four types of processes to occur:
The framework passes data from module to module. Each module uses
the data to perform one well-defined task. There are many types of modules.
There are general-purpose modules that perform tasks like reconstruction,
and special-function modules exist; these are input modules
and output modules to control the input and output of data
and filter modules to control subsequent data processing.
In addition to the "ready made" modules, users can, and will
need to, write or modify their own analysis modules. User-defined modules
are made in a user's private test release. In the QuickTour analysis,
a user-defined module (the NTrkExample.cc and .hh files) was placed in the
BetaMiniUser package directory. In this directory there are already some
example and template module files.
Writing or modifying a user analysis module involves writing
or modifying C++ code. If this is unfamiliar, don't worry. This topic will
be covered with example exercises in
Booking
a New Histogram as an Example of Editing Code.
A path is an ordered list of modules and sequences. As they are created,
paths are strung together to form the main execution path.
This execution path starts at the active input module and
terminates at the active output module. Between the two is
everything related to an analysis, from (for example)
the data source, particle identification and reconstruction setups to
the analysis proper, and finally to the ntuple/database/file
output of results.
Each module, sequence, or path can be in one of two states: enabled
(the default) or disabled. Only enabled modules, sequences and paths
are seen by the framework and executed.
The execution path at the top of this figure shows
what happens for every event. The execution path begins
with the input module and terminates with the output module, both of
which have to be enabled and active. All enabled paths are executed.
The next level down in the figure shows that the individual path B (for
example) consists of several sequences and some individual modules.
Finally, the bottom part of the figure shows that sequence 1 (for
example) is in turn constructed out of modules.
You can see why it important to make sure that modules that you want to
execute are appended and enabled. Modules α, χ and
δ are connected in a sequence but the middle module has not been enabled,
so the framework ignores it. Also, the user-defined MyModule at the bottom has been
compiled successfully, but it hasn't been included in a sequence or path, so the
framework never sees it. Now, if this was your plan, then that is fine. For example,
if module χ is buggy (though it compiled) you may disable it
on purpose. On the other hand, if you expected module χ or MyModule to be
executed, then you are in trouble, because it won't be.
AppUserBuild*.cc
Once the Framework has a list of module objects to work with,
Tcl scripts and commands can be used to create
and define the framework's sequences and execution path. In the
QuickTour analysis the snippet.tcl script file was executed in the Framework
by passing the tcl script as an argument to the BetaMiniApp executable.
workdir> BetaMiniApp snippet.tcl
The framework will not work unless each module
has the uniform structure of the class AppModule. The class AppModule
and interface definition file is located in
$BFROOT/dist/releases/analysis-30/Framework/AppModule.cc
$BFROOT/dist/releases/analysis-30/Framework/AppModule.cc
An analysis module, inheriting from AppModule, must provide
the following methods:
beginJob (
AbsEvent *
)
event ( AbsEvent * )
endJob ( AbsEvent * )
beginRun(AbsEvent *)
endRun(AbsEvent *)
beginJob(AbsEvent *)
endJob(AbsEvent
*)
A job is basically an entire Framework
session. In the Quicktour analysis, the Job began when we
ran the Beta executable (BetaMiniApp), and ended when we typed
exit at the Framework prompt. The beginJob()
member function is executed once (at the very beginning of a job) Similarly,
endJob() is executed once at the end.
exit
beginJob()
endJob()
The event() method is where analysis code goes. This
is executed once for each event in a run.
event()
The above figure shows the order of execution in a job. A job
begins with a call to the beginJob() of each module,
starting with the active input module and ending with the active
output module. Then event() is called for each module,
and then endJob(). (Filter modules may cause some paths
to be skipped.)
For example, in the interactive job in the Quicktour, the
beginJob() method is initiated when you type the "ev beg"
("events begin") command.
As an example, imagine an analysis job run over 20,000
events. The user begins with the ev beg -nev 10000 command,
which causes the code beginRun() to be executed for the input and
output modules. Then the events are processed, meaning that event()
gets executed 10000 times. Then the user decides to modify the controlling tcl so as
to change some analysis parameters before the remaining 10000 events are
processed. (For example, maybe something happened to the detector at event 10001
so that different parameters are needed.) Then the user continues with ev
cont -nev 10000, causing the event() member function to be
called again 10000 times. Finally, when the controlling tcl exits,
the endjob() method cleans up.
ev beg -nev 10000
beginRun()
ev
cont -nev 10000
event()
exits
endjob()
There are two common ways of using Tcl to interface with the
Framework. One is through a script. Also you can enter one command at a
time from a Framework prompt (">"), entered with a carriage return (that is, by
pressing "enter" after each command).
We make use of a few standard conventions when expressing Tcl
command syntax. Anything contained inside square brackets: '[ ]' is optional.
This takes two forms. mod[ule] indicates that the entire word
need not be typed. It is as legal and proper to issue mod as
it is to issue module as a command. Also,
[<argument2>] implies that the extra argument is optional.
Names written <like this> are argument names
for which you will enter the appropriate value.
In addition to the standard Tcl commands,
the Framework has the following BaBar specific commands that can be displayed
at the '>' prompt in any application:
mod[ule]
mod
module
<like this>
echo <arg1> [<arg2>
... ]
Here is a complete list of general
commands. These can also be displayed by typing "help"
at the '>' prompt in a Framework application.
ev[ents] beg[in] [-nev <nev>]
ev[ents] cont[inue] [-nev <nev>]
events help
mod[ule]
mod[ule] disable <mod1/all> [<mod2>
..]
mod[ule] enable <mod1/all> [<mod2>
..]
mod[ule] in[put] <mod>
mod[ule] out[put] <mod>
module help
Issuing the module talk command transfers command
input to the specified module.
>module talk MyModule MyModule>
MyModule>
This is a very time-saving and useful feature. It is the
main subject of
Framework Continued.
> mod talk KanEventInput
KanEventInput> input add /store/SP/R14/001237/200309/14.3.1c/SP_001237_000533
Here is a comprehensive list of the
input commands.
A useful command, in the input module, that you might like
to use is described in the QuickTour. Basically it skips a specified number
of events - useful if you are bored with running over the same 40 events in
the Quicktour! You can skip, say 2000, events with:
module talk KanEventInput
first set 2001
exit
ev beg ...
ev cont ...
...EventInput>
Here is a comprehensive list of the
output commands.
seq[uence]
The first step in defining a sequence is to create it. Once
a sequence is created modules need to be added to it. An example
(from BetaMiniUser/MyDstarMicroAnalysis.tcl) is as follows:
sequence create MyDstarSequence
sequence append MyDstarSequence MyDstarAnalysis
path
path list
>path list
You may recognize the output of path list from the
Quicktour. That's because this command was included in MyMiniAnalysis.tcl,
so the first part of the output to the screen was just the output of the
path list command.
Here is a comprehensive list of
path commands.
action disable <act1/all> [<act2>
..]
action enable <act1/all> [<act2>
..]
action list
Here is a comprehensive list of
actioncommands.
action
Here is a comprehensive list
of config commands.
config
Tcl scripts are files with names having a '.tcl' suffix.
Much of the syntax for these files is the same as the command line use. Each
line of the file may contain either a comment, a command, or some general
language constructs such as an if statement. Comment lines are indicated
by a pound character: '#'.
You should be aware that an initial tcl file may, and often
does, source many secondary scripts.
When the Beta executable was run in the quick tour analysis,
a tickle file was passed as an argument. Recall the command:
workdir> BetaMiniApp snippet.tcl
The job passes from the two setup tcl files,
snippet.tcl and MyMiniAnalysis.tcl, to
the main physics analysis file, btaMini.tcl. Here is
an annotated version of MyMiniAnalysis.tcl, with comments
in blue.
snippet.tcl
MyMiniAnalysis.tcl
Related documents:
doc
Last modification: 13 June 2005
Last significant update: 24 Oct 2002 | http://www.slac.stanford.edu/BFROOT/www/doc/workbook_kiwi/framework1/framework1.html | CC-MAIN-2017-30 | refinedweb | 1,560 | 56.86 |
a test of restructured text in zwiki - this is a copy of .
Sending XHTML as text/html Considered Harmful
Author: Ian Hickson <ian@hixie.ch> (Comments welcome.) late 2004, it is still just as relevant as when it was originally written.
Note that this document compares XHTML 1.0 compliant to appendix C to HTML 4.01, because that is the only variant of XHTML that may be sent as text/html.:
- Authors write XHTML that makes assumptions that are only valid for tag soup or HTML4 UAs?, and not XHTML UAs?, and send it as text/html. (The common assumptions are listed below.)
- Authors find everything works fine.
- Time passes.
- Author decides to send the same content as application/xhtml+xml, because it is, after all, XHTML.
- Author finds site breaks horribly. (See below for a list of reasons why.)
-:
-
<disabled script> and <style> elements in XHTML sent as text/html have to be escaped using ridiculously complicated strings.
This is because in XHTML, <disabled script> and <style> elements are #PCDATA blocks, not #CDATA blocks, and therefore <!-- and --> really _are_ comments tags, and are not ignored by the XHTML parser. To escape script in an XHTML document which may be handled as either HTML4 or XHTML, you have to use:
- <disabled script<!--//--><![CDATA[//><!--
-
...
//--><!]]><disabled /script>
To embed CSS in an XHTML document which may be handled as either HTML4 or XHTML, you have to use:
/]]>/--></style>
Yes, it's pretty ridiculous. If documents _aren't_ escaped like this, then the contents of <disabled script> and <style> elements get dropped on the floor when parsed as true XHTML.
(This is all assuming you want your pages to work with older browsers as well as XHTML browsers. If you only care about XHTML and HTML4 browsers, you can make it a bit simpler.)
-
A CSS stylesheet written for an HTML4 document is interpreted slightly differently in an XHTML context (e.g. the <body> element is not magical in XHTML, tag names must be written in lowercase in XHTML). Thus documents change rendering when parsed as XHTML.
-
A DOM-based script written for an HTML4 document has subtly different semantics in an XHTML context (e.g. element names are case insensitive and returned in uppercase in HTML4, case sensitive and always lowercase in XHTML; you have to use the namespace-aware methods in XHTML, but not in HTML4). BUT, if you send your documents as text/html, then they will use the HTML4 semantics DESPITE being XHTML! Thus, scripts are highly likely to break when the document is parsed as XHTML.
-
Scripts that use document.write() will not work in XHTML contexts. (You have to use DOM Core methods.)
-.
-
XHTML documents that use the "/>" notation, as in "<link />" have very different semantics when parsed as HTML4. So if there was to be a fully compliant HTML4 UA, it would be quite correct to show ">" characters all over the page.
For more details on this see the third bullet point in the section entitled "The Myth of "HTML-compatible XHTML 1.0 documents".
COPY AND PASTE
The worst problem, and the main reason (I suspect) for most of the REALLY invalid XHTML pages out there, is that authors who have no clue about XHTML simply copy and pasted their DOCTYPE from another document. So even if you write valid XHTML, by using XHTML, you are likely to encourage authors who do not know enough to write valid XHTML to claim to do so.
Why trying to use XHTML and then sending it as text/html is bad
These are not likely to be problems for authors who regularly validate their pages, but other authors will run into these problems.
-
Documents sent as text/html are handled as tag soup [1]? by most UAs?.
This is the key. If you send XHTML as text/html, as far as browsers are concerned, you are just sending them Tag Soup. It doesn't matter if it validates, they are just going to be treating it the same was as plain old HTML 3.2 or random HTML garbage.
Since most authors only check their documents using one or two UAs?, rather than using a validator, this means that authors are not checking for validity, and thus most documents that claim to be XHTML on the web now are invalid.
- See, for example, this study:
-
...but if you don't believe it, feel free to do your own. In any random sample of documents that appear to claim to be XHTML, the overwhelming majority of documents are invalid.
Therefore the main advantage of using XHTML, that errors are caught early because it _has_ to be valid, is lost if the document is then sent as text/html. (Yes, I said _most_ authors. If you are one of the few authors who understands how to avoid the issues raised in this document and does validate all their markup, then this document probably does not apply to you -- see Appendix B.)
-. (SGML is over a decade older than XML and the tools have existed for years.)
-
HTML 4.01 contains everything that XHTML 1.0 contains, so there is little reason to use XHTML in the real world. It appears the main reason is simply "jumping on the bandwagon" of using the latest and (perceived) greatest thing.
The Myth of "HTML-compatible XHTML 1.0 documents"
RFC 2854 spec refers to "a profile of use of XHTML which is compatible with HTML 4.01". There is no such thing. Documents that follow the guidelines in appendix C are not valid HTML 4.01 documents. They just happen to be close enough that tag soup parsers are able to handle them just like most of the other pages on the Web.
The simplest examples of this are:
-
The "/>" empty tag syntax actually has totally different meaning in HTML4. (It's the SHORTTAG minimisation feature known as NET, if I recall the name correctly.) Specifically, the XHTML
<p> Hello <br /> World </p>
...is, if interpreted as HTML4, exactly equivalent to:
<p> Hello <br>> World </p>
...and should really be rendered as:
Hello > World
-
Script and style elements cannot have their contents hidden from legacy UAs?. The following XHTML:
<style type="text/css"> <!-- /* hide from old browsers */
p { color: red; }
--> </style>
...is exactly equivalent to the following HTML4:
<style type="text/css">
</style>
...because comments are not ignored in XHTML <style> blocks.
-
The "xmlns" attribute is invalid HTML4.
-
The XHTML DOCTYPEs? are not valid HTML4 DOCTYPEs?.
Using XHTML and sending it as text/html is effectively the same, from an HTML4 point of view, as writing tag soup (see "Why UAs? can't handle XHTML sent as text/html as XML" below).
- Note: This is covered by HTMLWG issue XHTML-1.0/6232:
-;expression=appendix%20c;user=guest
Why UAs? can't handle XHTML sent as text/html as XML
-
Documents sent as text/html are handled as tag soup by most UAs?. This means that authors are not checking for validity, and thus most XHTML documents on the web now are invalid. A conforming XML UA would thus be unable to show as many documents as current UAs?, and would therefore never get enough marketshare to be relevant.
-
It is impossible to reliably autodetect XHTML when sent as text/html. This is why UAs? could not ever treat text/html documents as XML, even if they did not care about not being usable (see the first point in this section).
- You can't sniff for the five characters "<?xml" because:
-.)
- You can't trigger off the "<html xmlns" string because it might be there but hidden in a comment (you'd need a complete XML parser to step past comments, PIs?, internal subsets, etc).>
-
Even if you could detect XHTML, what do you do with a document that is not well formed (such as the example above)? If you fall back on HTML4, then there is no advantage to using an XML processor, and you might as well always treat it as HTML4.
-
- The HTML working group said that UAs? should not do this:
-
The advantages of XHTML
When sent as application/xhtml+xml, XHTML has several advantages:
- XHTML content will be able to be mixed-and-matched with content from other well-known namespaces (in particular, MathML?). This is the main advantage for content authors.
- UAs? will immediately catch well-formedness errors
- Tools interacting with XHTML documents are guaranteed a well-formed document.
- XHTML content can be parsed with a simpler parser than tag soup can, and a _much_ simpler parser than SGML can.
However, none of these apply when an XHTML document is sent as text/html, and since authors feel their pages should be readable on the most popular Web browser, which does not support application/xhtml+xml, there is basically no point in using XHTML at the moment.
Conclusion
There are few advantages to using XHTML if you are sending the content as text/html, and many disadvantages.!).
(Advanced authors should also see appendix B.)
Further Reading
I wrote another document on a related matter: people wanting UAs? to treat XHTML documents sent as text/html as XML and not tag soup.
Henri Sivonen wrote a similar document asking what is the point of XHTML:
There are also many mailing list posts on this matter, e.g. on www-talk. The following post summarises some issues relating to using text/html for XHTML content containing XML extensions:
Some people have run into the problems this document mentions, for example:
There are also some interesting points made in other posts, for example:
Or this post, near the end of the thread:
Appendix A: application/xhtml+xml
See:
Appendix C: Acknowledgements
Thanks to Nick Boalch for the abstract. Thanks to Dan Connolly for pedantry that has improved the quality of this document. Thanks to Ted Shaneyfelt and many others for suggesting improvements to the text.
Appendix D: Footnotes
[1]? The term "handled as tag soup" refers to the fact that UAs? typically are very lenient in their error handling, and do not support any of the "advanced" SGML features. For example, browsers treat the string "<br/>" as "<br>" and not "<br>>", the latter being what HTML4/SGML says they should do. Similarly, real world UAs? have no problem dealing with content such as "<b> foo <i> bar </b> baz </i>" even though according to the HTML4 spec that is meaningless. | https://zwiki.org/FrontPage/SendingXHTMLAsTextHtmlConsideredHarmful | CC-MAIN-2021-25 | refinedweb | 1,741 | 73.07 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.