text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringlengths
9
15
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
The last several yeas the University of New Hampshire has put on a “Hi Tech” day for area high school students. Between 150 and 200 high school students come to campus to see demonstrations of and to try their hand at some interesting and powerful software. They see tools like Windows Robotics Studio, Flash, Greenfoot, networking hardware, and more. The last two years I have run a hands on lab using XNA to create a game. This year I volunteered to show students how easy it is to create a game for the Windows Phone 7. Sounds easy enough. Well I did only have 40 minutes to help the students create a working game. I needed a very simple game that would demonstrate the essential parts of a game program. I decided to create a version of a Whack a Mole style game. The game is pretty simple – boxes displaying an object appear on the screen for the user to “hit” and make disappear. This can be done with a minimum amount of code but we still cover the most important methods of a game program: The program I came up with is not the best program in the world and in fact has lots of room for improvement. It is, however, simple to understand and easy to implement. What follows here is the step by step code for creating this simple demo program. (You can get a Word version of this document, a copy of code snippets for all the code used, and the images I used in this example at (zip file) ). Now that we have the images we need it is time to start writing some code. We need several variables: Our code might look something like this: Texture2D aFire, bFire, xButton; Rectangle aRec, bRec, xRec; Boolean aShow, bShow; Random r; int cycleCount, howOften; These lines go in the top of the class right below the lines: public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch. Our) spriteBatch.Draw(aFire, aRec, Color.AliceBlue); if (bShow) spriteBatch.Draw(bFire, bRec, Color.AliceBlue);: We check for touching the X button or flames by checking touch points against the rectangles that define the locations of the objects. The status of the TouchPanel tells us where it was touched. Our code may look something like this: TouchCollection touches = TouchPanel.GetState(); foreach (TouchLocation t in touches) Rectangle touchRec = new Rectangle((int)t.Position.X, (int)t.Position.Y, 1, 1); if (touchRec.Intersects(xRec)) this.Exit(); if (touchRec.Intersects(aRec) && aShow) aShow = false; if (touchRec.Intersects(bRec) && bShow) bShow = false; }: int shouldShow = r.Next(1, 100); cycleCount++; if (cycleCount > howOften) if (shouldShow < 60) { aShow = true; aRec.X = r.Next(100, 700); aRec.Y = r.Next(10, 400); } if (shouldShow > 50). What next? Well some things are obvious: Visit the App Hub at for more Windows Phone development resources. Be sure you have the software you need to develop XNA Programs for Widows Phone 4.
http://blogs.msdn.com/b/alfredth/archive/2011/03/18/whack-something-game-for-windows-phone-7.aspx
CC-MAIN-2015-11
refinedweb
493
74.19
Learn how to include Bootstrap in your project using Webpack 3. Install bootstrap as a Node.js module using npm. Import Bootstrap’s JavaScript by adding this line to your app’s entry point (usually index.js or app.js): import 'bootstrap'; Alternatively, you may import plugins individually as needed: import 'bootstrap/js/dist/util'; import 'bootstrap/js/dist/dropdown'; ... Bootstrap is dependent on jQuery and Popper, these are defined as peerDependencies, this means that you will have to make sure to add both of them to your package.json using npm install --save jquery popper.js. Notice that if you chose to import plugins individually, you must also install exports-loader To enjoy the full potential of Bootstrap Bootstrap: @import "custom"; @import "~bootstrap/scss/bootstrap"; For Bootstrap }] }, ... Alternatively, you may use Bootstrap’s ready-to-use css by simply adding this line to your project’s entry point: import 'bootstrap/dist/css/bootstrap.min.css'; In this case you may use your existing rule for css without any special modifications to webpack config except you don’t need sass-loader just style-loader and css-loader. ... module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] } ... © 2011–2018 Twitter, Inc. © 2011–2018 The Bootstrap Authors Code licensed under the MIT License. Documentation licensed under the Creative Commons Attribution License v3.0.
http://docs.w3cub.com/bootstrap~4/getting-started/webpack/
CC-MAIN-2018-39
refinedweb
221
51.14
Client-Server SDK for Matrix Project description Matrix Client SDK for Python This is a Matrix client-server SDK for Python 2.7 and 3.4+ Community discussion on usage of this SDK and development of this SDK can be found at #matrix-python-sdk:matrix.org. Documentation can be found at Installation Stable release Install with pip from pypi. This will install all necessary dependencies as well. pip install matrix_client Development version Install using setup.py in root project directory. This will also install all needed dependencies. git clone cd matrix-python-sdk python setup.py install E2E development The Olm bindings are not yet hosted on PyPI. Hence it it necessary to pass --process-dependency-links when installing with pip, in order to fetch them from their Git repository. For example replace python setup.py install in the above instructions by pip install --process-dependency-links .[e2e]. Usage The SDK provides 2 layers of interaction. The low-level layer just wraps the raw HTTP API calls. The high-level layer wraps the low-level layer and provides an object model to perform actions on. Client: from matrix_client.client import MatrixClient client = MatrixClient("") # New user token = client.register_with_password(username="foobar", password="monkey") # Existing user token = client.login_with_password(username="foobar", password="monkey") room = client.create_room("my_room_alias") room.send_text("Hello!") API: from matrix_client.api import MatrixHttpApi matrix = MatrixHttpApi("", token="some_token") response = matrix.send_message("!roomid:matrix.org", "Hello!") Structure The SDK is split into two modules: api and client. API This contains the raw HTTP API calls and has minimal business logic. You can set the access token (token) to use for requests as well as set a custom transaction ID (txn_id) which will be incremented for each request. Client This encapsulates the API module and provides object models such as Room. Samples A collection of samples are included, written in Python 3. You can either install the SDK, or run the sample like this: PYTHONPATH=. python samples/samplename.py Building the Documentation The documentation can be built by installing sphinx and sphinx_rtd_theme. Simple run make inside docs which will list the avaliable output formats. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/matrix-client-harmonyqt/0.4.0.dev0/
CC-MAIN-2021-39
refinedweb
382
52.26
Why Enumerate a Type? Here's the older approach of simulating enumerations: class Bread { static final int wholewheat = 0; static final int ninegrain = 1; static final int rye = 2; static final int french = 3; } You would then declare an int variable and let it hold values from the Bread class, e.g. int todaysLoaf = Bread.rye; Drawbacks of using ints to enumerate Using final ints to represent values in an enumeration has at least three drawbacks. All the compiler tools (debugger, linker, run-time, etc.) still regard the variables as ints. They are ints. If you ask for the value of todaysLoaf, it will be 2, not "rye". The programmer has to do the mapping back and forth mentally. The variables aren't typesafe. There's nothing to stop todaysLoaf getting assigned a value of 99 that doesn't correspond to any Bread value. What happens next depends on how well the rest of your code is written, but the best case is that some routine notices pretty quickly and throws an exception. The worst case is that your computer-controlled bakery tries to bake "type 99" bread causing an expensive sticky mess. Use of integer constants makes code "brittle" (easily subject to breakage). The constants get compiled into every class that use them. If you update the class where the constants are defined, you must go and find all the users of that class, and recompile them against the new definitions. If you miss one, the code will run but be subject to subtle bugs. How enums solve these issues Enumerated types were introduced with JDK 1.5 to address these limitations. Variables of enumerated types Are displayed to the programmer or user as Strings, not numbers Can only hold values defined in the type Do not require clients to be recompiled when the enumeration changes Enumerated types are written using a similar syntax to class declarations, and you should think of them as being a specialized sort of class. An enumerated type definition can go in a file of its own, or in a file with other classes. A public enumeration must be in a file of its own with the name matching the enumeration name. You might create an enumerated type to represent some bread flavors. It would be defined like this: enum Bread { wholewheat, ninegrain, rye, french } That lets you declare variables of type Bread in the usual way: Bread todaysLoaf; You can assign an enum value to a variable of Bread type like this: todaysLoaf = Bread.rye; All the language tools know about the symbolic names. If you print out a Bread variable, you get the string value, not whatever numeric constant underlies it internally. System.out.println("bread choice is: " + todaysLoaf); This results in output of: bread choice is: rye How enums are implemented Under the covers, enum constants are static final objects declared (by the compiler) in their enum class. An enum class can have constructors, methods, and data. Enum variables are merely pointers to one of the static final enum constant objects. You'll understand enums better if you know that the compiler treats them approximately the same way as if it had seen this source code: class Bread extends Enum { // constructor public Bread(String name, int position) { super(name, position); } public static final Bread wholewheat = new Bread("wholewheat",0); public static final Bread ninegrain = new Bread("ninegrain", 1); public static final Bread rye = new Bread("rye", 2); public static final Bread french = new Bread("french", 3); // more stuff here } This is an approximation because the parent class, java.lang.Enum, uses a generic parameter, and we cover generics later. Bringing generics into the definition of Enum was an unnecessary complication aimed at improving the type-safety of enums. The work could and should have been moved into the compiler. The previous code should give you a good idea of how enums are represented. Namespaces in Java and in enumerations Namespace isn't a term that occurs in the Java Language Specification. Instead, it's a compiler term meaning "place where a group of names are organized as a whole." Some older languages only have one global namespace that holds the names of all methods and variables. Along with each name, the compiler stores information about what type it is, and other details. Java has many namespaces. All the members in a class form a namespace. All the variables in a method form a namespace. A package forms a namespace. Even a local block inside a method forms a namespace. A compiler will look for an identifier in the namespace that most closely encloses it. If not found, it will look in successively wider namespaces until it finds the first occurrence of the correct identifier. You won't confuse Java if you give the same name to a method, to a data field, and to a label. It puts them in different namespaces. When the compiler is looking for a method name, it doesn't bother looking in the field namespace. Each enumeration has its own namespace, so it is perfectly valid for enumeration values to overlap with other enums or other variables, like this: enum Fruit { peach, orange, grapefruit, durian } enum WarmColor { peach, red, orange } Some more Java terminology: the enumeration values apple, red, peach, plum and orange are known as enum constants. The enumeration types Fruit and WarmColor are enum types. Enum constants make software more reliable Here's an amazing thing: the constants that represent the enumeration values are not compiled into other classes that use the enumeration. Instead, each enum constant (like Bread.rye previously) is left as a symbolic reference that will be linked in at run-time, just like a field or method reference. If you compile a class that uses Bread.rye, and then later add some other bread flavors at the beginning of the enumeration (pumpernickel and oatmeal), Bread.rye will now have a different numeric value. But you do not need to recompile any classes that use the enumeration. Even better, if you remove an enum constant that is actually being used by some other class (and you forget to recompile the class where it's used), the run-time library will issue an informative error message as soon as you use the now-removed name. This is a significant boost to making Java software more reliable.
http://www.informit.com/articles/article.aspx?p=349047&seqNum=3
CC-MAIN-2019-51
refinedweb
1,064
62.27
Introduction to the QML Language Q (see the Javascript Guide) before diving deeper into QML. It's also helpful to have a basic understanding of other web technologies like HTML and CSS, but it's not required. Basic QML Syntax QML looks like this: import QtQuick 1.0 Rectangle { width: 200 height: 200 color: "blue" Image { source: "pics/logo.png" anchors.centerIn: parent } } Here we create. In the above example, we can see the Image objectQuick module, which contains all of the standard QML Elements. Without this import statement, the Rectangle and Image elements would not be available.. Object Identifiers Each object can be given a special id value that allows the object to be identified and referred to by other objects. For example, below we have two Text objects. The first Text object has an id value of "text1". The second Text object can now set its own text property value to be the same as that of the first object, by referring to text1.text: import QtQuick 1.0 Row { Text { id: text1 text: "Hello World" } Text { text: text1.text } } An object can be referred to by its id from anywhere within the component in which it is declared. Therefore, an id value must always be unique within a single component. The id value is a special value for a QML object and should not be thought of as an ordinary object property; for example, it is not possible to access text1.id in the above example. Once an object is created, its id cannot be changed. Note that an id must begin with a lower-case letter or an underscore, and cannot contain characters other than letters, numbers and underscores. Expressions JavaScript expressions can be used to assign property values. For example: Item { width: 100 * 3 height: 50 + 22 } These expressions can include references to other objects and properties, in which case a binding is established: when the value of the expression changes, the property to which the expression is assigned is automatically updated to the new value. For example: Item { width: 300 height: 300 Rectangle { width: parent.width - 50 height: 100 color: "yellow" } } Here, the Rectangle object's width property is set relative to the width of its parent. Whenever the parent's width changes, the width of the Rectangle is automatically updated. Properties Basic Property Types QML supports properties of many types (see QML Basic Types). The basic types include int, real, bool, string and color. Item { x: 10.5 // a 'real' property state: "details" // a 'string' property focus: true // a 'bool' property // ... } QML properties are what is known as type-safe. That is, they only allow you to assign a value that matches the property type. For example, the x property of item is a real, and if you try to assign a string to it you will get an error. Item { x: "hello" // illegal! } Note that with the exception of Attached Properties, properties always begin with a lowercase letter. Property Change Notifications When a property changes value, it can send a signal to notify others of this change. To receive these signals, simply create a signal handler named with an on<Property>Changed syntax. For example, the Rectangle element has width and color properties. Below, we have a Rectangle object that has defined two signal handlers, onWidthChanged and onColorChanged, which will automaticallly be called whenever these properties are modified: Rectangle { width: 100; height: 100 onWidthChanged: console.log("Width has changed to:", width) onColorChanged: console.log("Color has changed to:", color) } Signal handlers are explained further below. List properties List properties look like this: Item { children: [ Image {}, Text {} ] } The list is enclosed in square brackets, with a comma separating the list elements. In cases where you are only assigning a single item to a list, you can omit the square brackets: Image { children: Rectangle {} } Items in the list can be accessed by index. See the list type documentation for more details about list properties and their available operations. Default Properties. Grouped Properties. Attached Properties Some objects attach properties to another object. Attached Properties are of the form Type.property where Type is the type of the element that attaches property. For example, the ListView element attaches the ListView.isCurrentItem property to each delegate it creates: Component { id: myDelegate Text { text: "Hello" color: ListView.isCurrentItem ? "red" : "blue" } } ListView { delegate: myDelegate } Another example of attached properties is the Keys element which attaches properties for handling key presses to any visual Item, for example: Item { focus: true Keys.onSelectPressed: console.log("Selected") } Signal Handlers Signal handlers allow JavaScript code to be executed in response to an event. For example, the MouseArea element has an onClicked handler that can be used to respond to a mouse click. Below, we use this handler to print a message whenever the mouse is clicked: Item { width: 100; height: 100 MouseArea { anchors.fill: parent onClicked: { console.log("mouse button clicked") } } } All signal handlers begin with "on". Some signal handlers include an optional parameter. For example the MouseArea onPressed signal handler has a mouse parameter that contains information about the mouse press. This parameter can be referred to in the JavaScript code, as below: MouseArea { acceptedButtons: Qt.LeftButton | Qt.RightButton onPressed: { if (mouse.button == Qt.RightButton) console.log("Right mouse button pressed") } }.
http://doc.qt.io/qt-4.8/qdeclarativeintroduction.html
CC-MAIN-2016-18
refinedweb
879
56.76
Go to advanced search gordon77 wrote: ↑Sun Jan 20, 2019 3:29 pm try this... saves 2 files called message1.txt and message2.txt, which are loaded at the start Code: Select all import datetime; ts = datetime.datetime.now().timestamp() print(ts) gordon77 wrote: ↑Sun Jan 20, 2019 10:43 am To change Count1 to GPIO 4.. Remember to move the wired input to GPIO4 ! gordon77 wrote: ↑Sat Jan 19, 2019 5:19 pm Click on IO#- or IO#+ to choose a GPIO pin Then you can set GPIO to Input/Output/Count1/Count2 by clicking on I/O and you can set High/Low or None by clicking on H/L then press save. gordon77 wrote: ↑Thu Jan 17, 2019 5:28 pm Will it just display the settings, not allow the user to set them? gordon77 wrote: ↑Thu Jan 17, 2019 1:06 pm what choices of configuration are you looking for, just GPIO # Number ? gordon77 wrote: ↑Thu Jan 17, 2019 11:30 am Can you explain "I am trying to make GUI for pin configuration after IOT project labels " more ?
https://www.raspberrypi.org/forums/search.php?author_id=261227&sr=posts
CC-MAIN-2020-24
refinedweb
183
80.11
Introducing the Nashorn JavaScript Engine Free JavaScript Book! Write powerful, clean and maintainable JavaScript. RRP $11.95 Nashorn is a new JavaScript engine developed in the Java programming language by Oracle, released with Java 8. Nashorn’s goal is to implement a lightweight high-performance JavaScript runtime in Java with a native JVM. By making use of Nashorn, the developer can embed JavaScript in a Java application and also invoke Java methods and classes from the JavaScript code. Why Leave Rhino? Rhino is the predecessor of Nashorn. It began as a project in 1997 at NetScape and got released in 1998. There have been 16 years since the release of Rhino, and that JavaScript engine has lived its days. So the Java guys decided to have some fun by developing a new JavaScript engine from scratch instead of rewriting the existing one. This gave birth to Nashorn (fun fact: nashorn means rhino in German). Almost everyone here has been using JavaScript in the browser, and some have been using it on the server (like Node.js), but Nashorn is developed for another purpose. By using Nashorn the developer can perform the magic of: - Running JavaScript as native Desktop code. - Using JavaScript for shell scripting. - Call Java classes and methods from JavaScript code. The Goals of Nashorn When Nashorn was designed, the developers decided a set of goals for it: - It should be based on ECMAScript-262 Edition 5.1 language specification, and must pass the ECMAScript-262 compliance tests. - It should support the javax.script (JSR 223) API. - It should allow invoking Java from JavaScript and vice-versa. - It should define a command-line tool, jjsfor evaluating JavaScript code in “shebang” scripts (that normally start with #!/bin/sh), here documents, and edit strings. - Its performance should be significantly better than Rhino. - It should have no security risks. Furthermore, no one decided that Nashorn will not include debugging and not support CSS and JavaScript libraries/frameworks. This means Nashorn can be implemented in a browser without being a nightmare. JavaScript in a (nut)Shell In order to use JavaScript in the shell by using Nashorn’s jjs tool, you should first install the JDK8, which you can download for free. To test its installation, execute: >_ javac -version # it should echo # java version "1.8.x" jjs -version # it should echo # nashorn 1.8.x jjs> If you face any problems with the first or the second command, try adding JDK in the path Now you can use JavaScript as a shell script. Check out this simple example: jjs> var a = 1 jjs> var b = 4 jjs> print (a+b) 5 jjs> As you may have already figured out, you don’t have to write the code into the jjs shell. You can write the code into a JavaScript source file, and then call it from the shell. Consider the following JavaScript code: var isPrime = function(num) { if (isNaN(num) || !isFinite(num) || num < 2) return false; var m = Math.sqrt(num); for (var i = 2;i <= m; i++) if (num % i === 0) return false; return true; } var numbers = [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; for (var i = 0; i < numbers.length; i++) { if (isPrime(numbers[i])) print(numbers[i] + " is prime"); else print(numbers[i] + " is not prime"); } Assuming the code is on a file called prime.js, we can run it in the shell, by executing: >_ jjs prime.js 2 is prime 3 is prime 4 is not prime 5 is prime 6 is not prime 7 is prime 8 is not prime 9 is not prime 10 is not prime This may remind you of Python code or bash scripting, but it is JavaScript. And to make it more bash-like, Nashorn gives the arguments variable to extract the command line arguments. Consider this example: if (arguments.length === 0) print("No command-line arguments."); else { print("Called with these command-line arguments:"); for each (cli_arg in arguments) { print(cli_arg); } } Running it will give this output (arguments go after --): >_ jjs cliargs.js No command-line arguments. >_ jjs cliargs.js -- a b "c d e" Called with these command-line arguments: a b c d e Also, JavaScript can use Java classes and methods. See this example of a multithreaded JavaScript code: var Thread = Java.type("java.lang.Thread"); var Runnable = Java.type('java.lang.Runnable'); var Run1 = Java.extend(Runnable, { run: function() { print("One thread"); print("One thread"); } }); new Thread(function() { print("Another thread"); print("Another thread"); print("Another thread"); }).start() new Thread(new Run1()).start(); And the output would be: Another thread Another thread One thread One thread Another thread You can tell by the output that the code is multithreaded. By using Java.type("java.lang.Thread"); we can call Java classes inside the JavaScript code. Nashorn allows even going in the other direction, calling JavaScript code inside Java code. package j2js.example; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) { ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn"); try { nashorn.eval("print('Am I Java or JavaScript?')"); } catch (ScriptException e) { e.printStackTrace(); } } } This example just prints the Am I Java or JavaScript? question on line 14, but this is the simplest example of JavaScript code into Java. One can read the whole source code from the JavaScript file, using Java methods, and then pass that code as a String parameter to the eval() method. This would make the JavaScript code to execute inside Java. Conclusion Nowadays JavaScript is everywhere! You may use it for client-side applications, server-side applications, and better yet, sometimes for both client and server. You may use it for mobile applications or to set up a small IoT. And now, with Nashorn, you may use it as a powerful shell-like scripting language, by taking advantage of the simplicity of JavaScript and the rich API of Java. Learn valuable skills with a practical introduction to Python programming! Give yourself more options and write higher quality CSS with CSS Optimization Basics.
https://www.sitepoint.com/introducing-nashorn-javascript-engine/
CC-MAIN-2020-29
refinedweb
1,015
66.84
I read about pointer to pointers on tutorialsPoint. I had a little test myself. I want to slice a string by space so that every words (include the punctuation) are treated as a token and the tokens are returned line by line. Here is the code: #include <stdio.h> #include <string.h> #include <stdlib.h> char** split(const char* s) { int i = 0, j = 0; char** word = malloc(strlen(s)+1); * word = malloc(strlen(s)+1); while (*s != '\0') { if (*s == ' ') { i++; } else { word[i][j] = *s; j++; } i++; s++; } return word; //free(word); //with or without this i get the same outcome. } int main(void) { char** words = split("He said 'hello' to me!"); int i = 0; while (words[i] != NULL) { puts(words[i]); free(words[i]); i += 1; } free(words); } printf valgrind He said 'hello' to me! First, I will comment on your attempt: Here: return word; free(word); free won't be executed! You see anything that lies after the return statement, doesn't execute! Moreover, the space allocated dynamically with malloc() is wrong, check about how we do that in my 2D dynamic array, or/and read the example below. You see, without having allocated the sufficient, you were accessing out of bound memory, which would cause Undefined Behavior, but you are lucky to get a segmentation fault, which alerted you! :) I won't debug your code, since it's a wonderful chance to practice, but if you want ask more. Here is how I would do it, it's a simpler approach, but if you get that, then you will be able to work on your own attempt! :) #include <stdio.h> #include <string.h> #include <stdlib.h> // We return the pointer char **get(int N, int M) // Allocate the array */ { // TODO: Check if allocation succeeded. (check for NULL pointer) int i; char** table; table = malloc(N*sizeof(char *)); for(i = 0 ; i < N ; i++) table[i] = malloc( M*sizeof(char) ); return table; } void free2Darray(char** p, int N) { int i; for(i = 0 ; i < N ; i++) free(p[i]); free(p); } void zeroFill(char** p, int N, int M) { int i, j; for(i = 0 ; i < N ; i++) for(j = 0 ; j < M ; j++) p[i][j] = 0; } void print(char** p, int N, int M) { int i; for(i = 0 ; i < N ; i++) if(strlen(p[i]) != 0) printf("array[%d] = %s\n", i, p[i]); } void split(const char* s, char** words) { int i = 0, word_idx = 0, char_idx = 0; while(s[i] != '\0') { if(s[i] != ' ') { words[word_idx][char_idx++] = s[i]; } else { word_idx++; char_idx = 0; } ++i; } } int main(void) { char** words = get(10, 15); // 10 words, 14 chars max (+1 for n$ zeroFill(words, 10, 15); split("He said 'hello' to me!", words); print(words, 10, 15); free2Darray(words, 10); return 0; } Output: C02QT2UBFVH6-lm:~ gsamaras$ nano main.c C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall main.c C02QT2UBFVH6-lm:~ gsamaras$ ./a.out array[0] = He array[1] = said array[2] = 'hello' array[3] = to array[4] = me! The explanation: split(). Now, let me explain a bit more the split() function: Actually your attempt was pretty good, so you probably know already what I am doing: word_idxhelps me remember which word I am filling up now, and which character of that word with char_idx. elsecase), I have to advance to the next word (no need to NULL-terminate the string I filled up before, since I have zero initialized my 2D array), by incrementing word_idxby 1. I also set char_idxto 0, so that I can start filling up the new word from position 0.
https://codedump.io/share/ZIinpGPUwZWd/1/how-to-use-pointer-to-pointer-to-slice-string
CC-MAIN-2018-05
refinedweb
598
71.55
Calling a Dialog Box From an SDI Introduction A Single Document Interface (SDI) is the type of application that presents a frame-based window equipped with a title bar, a menu, and thick borders. In most cases the one-frame window is enough to support the application. The advantage of creating an SDI application is the full support of the Document/View architecture. To provide support and various options to the frame, you can add other dependent windows such as dialog boxes. When such a dialog box is needed, you can provide a menu item that the user would use to display the dialog box. For example, if you create an SDI using the wizard, it would be equipped with an About Box and the main menu would allow the user to open that dialog box. In the same way, you can add as many dialog boxes as you judge necessary to your SDI application and provide a way for the user to display them. To display a dialog from an SDI, the easiest and most usual way consists of creating a menu item on the main menu. When implementing the event of the menu item, as normally done in C++, in the source file of the class that would call it, include the header file of the dialog box. In the event that calls the dialog box, first declare a variable based on the name of the class of the dialog box. Then call the CDialog::DoModal() method of the dialog box that is being called. Practical Learning: Calling a Dialog Box From an SDI // SDI1View.cpp : implementation of the CSDI1View class // #include "stdafx.h" #include "SDI1.h" #include "SDI1Doc.h" #include "SDI1View.h" #include ".\sdi1view.h" #include "DependentDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif . . . No Change // CSDI1View message handlers void CSDI1View::OnToolsDependents() { // TODO: Add your command handler code here CDependentDlg Dlg; Dlg.DoModal(); }
http://www.functionx.com/visualc/howto/calldlgfromsdi.htm
CC-MAIN-2016-22
refinedweb
316
63.8
On Wed, Apr 03, 2013 at 10:04:20AM +0000, Purcareata Bogdan-B43198 wrote: > Hello, > > I am doing some research on [subject] and I would like to find out some information regarding various scenarios. I've studied the official documentation at [1] and some of the mailing list archives. The configurations I have in mind are somewhat inspired by what the sf LXC package offers in terms of networking. > > What I've tested so far and works: > - Shared networking - all host interfaces are present in the container if no <interface> tag has been specified in the domain configuration. I'm assuming this is because the container is started in the same network namespace like the host. Is it possible to make only a subset of these interfaces visible inside the container? Yes, if no <interface> is listed, we do not enable network namespaces. You can force network namespaces by setting <features> <privnet/> </features> which will mean all you get is a loopback device. If you need to make a subset of host interfaces visible, you'd need to use <privnet/> and then the (not yet implemented) <hostdev> mode you describe at the end. > - Bridge to LAN - connecting a domain interface to a host bridge; > - Direct attachment through a Macvtap device - all 3 modes (vepa, bridge and private) work as expected, "passthrough" requires some capabilities in the physical device (SRIOV), which I don't have - assuming I have a device with this capability, is this configuration supported by (implemented in) the libvirt_lxc driver? You don't need SRIOV for. It just requires a simple API call to move the host NIC to the containers' namespace Daniel -- |: -o- :| |: -o- :| |: -o- :| |: -o- :|
https://www.redhat.com/archives/libvir-list/2013-April/msg00233.html
CC-MAIN-2015-22
refinedweb
279
57.1
Revision history for HTML::Mason. ** denotes an incompatible change 1.51 May 8, 2013 [ DISTRIBUTION ] - Fix hardcoded version [DOCS] - Add HTML::Mason::FAQ, from old masonhq.com website 1.50 Jul 11, 2012 [ DISTRIBUTION ] - Switch to Dist::Zilla - Eliminate HTML docs from distribution, available on web - Move live Apache tests to author-only 1.49 Feb 27, 2012 [ DOCS ] - Fixed misspellings in docs. RT #74676. Reported by Salvatore Bonaccorso. 1.48 Feb 3, 2012 [ BUG FIXES ] - Calling a subcomponent from inside an anonymous component (created via $interp->make_component) caused an uninitialized value warning. Reported by Javier Amor Garcia. 1.47 Oct 21, 2011 [ BUG FIXES ] - Silenced an uninitalized value warning from ApacheHandler with newer versions of Perl. RT #61900. [. 1.29_02 June 22, 2005 [ ENHANCEMENTS ] - ** Support for mod_perl-2.00 (mod_perl-1.99 is no longer supported because of API changes in 2.0RC5). - Mason recovers more gracefully from an empty or corrupted object file. Task id #579. [. 1.29_01 January 25, 2005 [. [. - Added [ ENHANCEMENTS ] - Added "REQUEST:" as a component specifier for method comp calls, similar to "SELF:" and "PARENT:". "REQUEST:" is short-hand for $m->request_comp. Suggested by Manuel Capinha, among others. - Added $m->call_self. This was present in Mason pre-1.10, and has been added back per Jon Swartz's request. - Added $comp->attributes, similar to $comp->methods. This just returns attributes for a given component object. It doesn't return attributes inherited from a parent. Suggested by Matti Makitalo. [ BUG FIXES ] - ** When $m->cache_self was used for a component with a filter block, the output would be cached _before_ filtering, and filtered every time it was retrieved from the cache. This has been fixed, and the documentation now specifies that the filtered output is cached. - Fixed failure of 12-taint.t #7 on Win32 boxes. Reported by Randy Kobes. - Without HTML::Entities installed, 13-errors.t #7 failed. Reported by Sam Kington. - $m->file did not handle relative paths properly when called from a subcomponent or method. Reported by Chris Hutchinson. - If $m->abort was called in the shared block of a component that had a filter, then a fatal error occured. Reported by Chris Pudney. - Mason was not cooperating with Apache::Filter, and attempts to filter Mason's output did not work. Fixing this also requires Apache::Filter 1.021, if you are using Apache::Request to handling incoming arguments. Reported by by Manuel Capinha. - Mason assumed that if Scalar::Util loaded without errors, it had a weaken() subroutine. However, Scalar::Util provides a pure Perl implementation that does not include this subroutine. Now we check for this subroutine explicitly. Reported by Autrijus Tang. - Some code constructs, such as qw() lists, would end up being turned into invalid code during component compilation. Reported by Robert Landrum. - Subclassing a subclass of HTML::Mason::Request broke when the class between HTML::Mason::Request and your own class called alter_superclass. - Under mod_perl 2.0, when ApacheHandler could't resolve a filename to a component, it would die instead of returning a not found status. [ INCOMPATIBLE CHANGES ] - ** Removed the long deprecated and undocumented $comp->parent_comp method. Use $comp->owner instead., 2002 -, 2000 - Fixed small 0.8 bugs with automatic header sending. Headers are now sent for blank pages and are not sent on an error status code. - Fixed bug with default system log file. (submitted by Renzo Toma) - Eliminated memory leak introduced in 0.8 for a few Linux platforms. (submitted by Renzo Toma and Pascal Eeftinck) - Fixed bug with component paths displaying two leading slashes. - Fixed $comp->source_file when multiple comp roots declared. - Fixed $m->decline in mod_perl mode. - Removed legacy dhandler code from ApacheHandler. - Replaced $r->filename with $r->finfo in ApacheHandler. (submitted by Dennis Watson) - Added dynamic virtual server configuration example to Admin.pod. (submitted by Caleb Crome) 0.8 January 23, 2000 - New integrated request API. $m replaces $REQ as the global variable containing the current request object. All mc_ commands have been incorporated into $m methods: mc_comp becomes $m->comp, mc_file becomes $m->file, etc. The old commands still work for now. - The utility bin/convert0.8.pl converts existing components to use the new request API. - Autohandler methods have been renamed: from mc_auto_next to $m->call_next and mc_auto_comp to $m->fetch_next. This is in preparation for a more general component inheritance system. convert0.8.pl handles this change. - Can now specify multiple component roots in the spirit of @INC. (suggested by Ewan Edwards and others) - Simplified HTTP header behavior. Headers are sent at the end of the request (in batch mode) or just before the first non-whitespace output (in stream mode). suppress_http_header no longer needed. - New organization of Component class into subclasses Component::FileBased and Component::Subcomponent. No outward change. - Updated object file format. Mason should generally auto-detect and recompile old object files, but may not catch everything. Try removing your object directory if errors persist. - ** mc_suppress_http_header command still exists but does nothing. In most cases this should not cause a problem. The only incompatibility is if you have used mc_suppress_http_header to suppress headers completely (i.e. you don't want Mason to send headers at all); in this case pass auto_send_headers=>0 to ApacheHandler. - Output mode parameter was moved from ah->output_mode to interp->out_mode, to make it independent of mod_perl. ah->output_mode still works. - New in-memory code cache keeps track of component usage, and discards the most infrequently used components as needed. You can specify the cache size with interp->max_code_cache_size. - ** Eliminated the now unnecessary interp->code_cache_mode. - ** Eliminated the "source references" optimization, a common source of bugs, no longer needed with the new code cache. - Allow arguments to be accessed via @_ as in regular subroutines; no longer required to be in hash form. (suggested by Ken Williams) - Added $m->scomp, which returns the output of the component call instead of printing it. This is a cleaner replacement for the STORE parameter, which still works but is no longer officially documented. - Added $m->flush_buffer, which forces the buffer to be sent to the client when in batch mode. - Added $m->caller_args, which returns the argument list for any point in the stack. (suggested by Lee Semel) - Added $m->decline, which passes control to the next dhandler. (suggested by Chuck O'Donnell) - Augmented $m->cache_self to cache return values as well as output. (suggested by Jon Frisby) - Changed data cache filenames from colon-separated to url-encode style for Win32 compatibility. (submitted by Ken Williams) - Added improved, separate session_handler.pl for session handling. - ** mc_comp_source no longer works for non-existent components. - ** Removed mc_date legacy command. - Many new test scripts. - Added warnings about using Mason with mod_perl DSO. - Added more site configuration examples to Admin.pod. - Split object parameter methods (interp->comp_root, etc.) into read/write and read-only as appropriate. - Fixed request stack corruption when die() or error from one component is caught by another component's eval. - Fixed doc_root / comp_root mismatch on case-insensitive O/S. (reported by John Arnold) - Fixed "directory not absolute" warning on "/" (reported by Joe Edmonds) - Fixed reload file scanning mechanism (submitted by Brian Holmes) - Added use_data_dumper_xs Config.pm item, which checks whether Data::Dumper::Dumpxs is available. (reported by Pelle Johnsen) - Added "code examples" section to README 0.72 October 15, 1999 - Eliminated long-standing infinite-block bug when POSTing to a non-existent URL - Fixed "keys" cache action which never worked as documented (submitted by Scott Straley) - Fixed source references on Win32 platforms by using text mode when reading object file (submitted by Michael Shulman) - Fixed various methods in FakeApache - Remove final slash from system paths (component root, etc.) and check that those paths are absolute - Fixed all-text subcomponents, by bypassing the pure-text optimization - Quoted all hash strings in object file to reduce "Ambiguous use of ..." warnings (suggested by Paul Schilling) - Replaced */* with default-handler as recommended way to bypass Mason (suggested by Dirk Koopman) - Removed defunct pure text section in Administrators Guide (reported by Michael Shulman) 0.71 September 14, 1999 - Logic of top_level_predicate was reversed in 0.7; fixed. (reported by Tom Hughes, Eric Hammond) - mc_suppress_http_header(0) was broken in 0.7; fixed. (reported by Michael Alan Dorman) - Fixed bug in parser section that determines whether % is at the beginning of a line. (reported by Tom Hughes) - Parser no longer inadvertently accepts argument names with whitespace. (reported by Phillip Gwyn) 0.7 September 1, 1999 - Improved core implementation with two new classes, HTML::Mason::Request and HTML::Mason::Component. Code is now cleaner and more scalable, and the new APIs give developers control and introspection over Mason's inner workings. - Added documentation to accommodate new classes: created Request.pod and Component.pod, and moved component developer's guide (previously at Components.pod) to Devel.pod to avoid confusion. - Object files have changed significantly (they now return a component object). Pre-0.7 object files will be detected and automatically updated, unless you are running in reload file mode in which case you are responsible for generating new object files. - New <%def> section defines a subcomponent embedded inside a larger component. This allows repeated code and HTML to be modularized without affecting the global component namespace. - <%args> section now accommodates optional comments for declarations - Improved Perl translation of <%args> section (submitted by Ken Williams) - Autohandler and dhandler file names are now configurable - Dhandlers, which formerly worked only in mod_perl mode, now work in stand-alone mode as well - Interp::exec is now re-entrant with all request specific information having been moved to Request class. - ** Reworked Parser API. parse is now called make_component, has a simplified set of options, and returns a component object directly. make is now called make_dirs. - Source references now read from the object file, cleaner for a variety of reasons. Preprocess and postprocess now work with source references. - Removed obsolete and undocumented Interp::vars and mc_var functions - Simplified chown/getpwuid usage in handler.pl (submitted by Randal Schwartz) 0.6.2 August 20, 1999 - Fixed problem with shared data cache locks over NFS (submitted by Tom Hughes) - Fixed mc_auto_comp, which never really worked as documented - Fixed preloading for directories (submitted by Dennis Watson) - Added back Utils::get_lock, which is used by content management 0.6.1 July 27, 1999 - Added warnings to convert-0.6.pl about occasional erroneous component call syntax conversions (reported by Oleg Bartunov) - Fixed conversion of <% mc_comp("/foo/$bar") %> (reported by Oleg Bartunov) - Fixed cache access under high concurrencies (reported by Oleg Bartunov) - Fixed uppercase <%PERL>, broken in 0.6 (reported by Daniel L. Jones) - Fixed mc_suppress_http_header(0), broken in 0.6 (reported by Jim Mortko) 0.6 July 16, 1999 - New <& &> tag provides a more convenient way to call components inside HTML. mc_comp still works. - The "perl_" prefix has been eliminated from section names: now simply use <%init>, <%cleanup>, <%args>, etc. The old names still work. - The utility bin/convert0.6.pl converts existing components to use the above new syntax. - New autohandler feature finally provides an easy way to specify a common template or behavior for a directory. An autohandler is invoked just before any top-level components in its directory begins executing. It can display header/footers, apply a filtering function, set up globals, etc. A good complement to dhandlers. - New <%once> section contains code that will be executed once when a component is loaded. It is useful for defining persistent variables and named subroutines. - New <%filter> section and mc_call_self command allow you to arbitrarily filter the output of the current component. - New <%text> section allows you to turn off Mason processing for a particular section of text. - Implemented first installation test suite! [modus] - HEAD optimization: we now automatically abort after headers are sent on a HEAD request. - New Parser make() utility traverses a tree of components, compiling any out-of-date components into object files and reporting errors. - New mc_comp_source command returns the source filename of this or any component. - mc_file now uses current component path by default for relative paths if no static_file_root defined (suggested by John Landahl) - Various previewer interface improvements - Removed link tags in pods documentation due to 5.004 problems - Took out previewer stub from Mason.pm to eliminate "subroutine redefined" warning - Updated makeconfig.pl to prefer GDBM_File, to avoid a bug in Berkeley DB 1.x - Cleaned and sped up interp hooks facility - Stopped substituting control characters for section strings in Parser [modus] - Fixed mc_cache 'expire' bug (reported by Aaron Ross) - Changed ignore_warnings default to ignore "subroutine redefined" warnings to make <%once> more useful - Removed defunct Safe code from Parser and defunct ALLOW_HANDLERS code from Interp - Added index file to htdocs/ 0.5.1 June 10, 1999 - Removed leftover "use File::Recurse" in ApacheHandler.pm [modus] - Added empty test target to FAQ Makefile, required on certain architectures [modus] 0.5 June 3, 1999 -] - New preprocess and postprocess Parser options allow you to apply auomatic modifications to components, before or after they are compiled into code. (submitted by Philip Gwyn) - New in_package Parser option allows components to live in any package. (submitted by Philip Gwyn) - Added documentation about using globals in components, and some new facilities: Parser option 'allow_globals' and Interp method 'set_global'. - Documented how to save persistent user information with Apache::Session [modus] - ** Changed behavior of reload_file mode to read directly from object files. If you use reload files, you're now responsible for creating object files. [mschmick] - Reduced number of file stats when loading components [mschmick] - New apache_status_title ApacheHandler option makes it possible to use Mason's perl-status page with multiple ApacheHandler objects. (submitted by Philip Gwyn) - Upgraded FakeApache/debug files to work with mod_perl 1.19 - New sections in Component Developer's Guide explain how debug files work and some caveats about when they don't. -(), which allows you to compile components outside of a Interp environment. - New mc_cache actions 'expire' and 'keys' help you peer into data cache files and expire selected', which prevents multiple processes from recomputing an expire cache value at the same time. January 06, November 25, August 21, July 22, 1998 - Original version; created by h2xs 1.18
https://metacpan.org/changes/release/JSWARTZ/HTML-Mason-1.51
CC-MAIN-2015-11
refinedweb
2,344
50.94
Module::Install::API - Command Reference for Module::Install Module::Install has lots of commands scattered in the extensions. Several common commands are described in the main Module::Install's pod, but you usually need to know more to do what you want. This API document lists and describes all the public supported commands, grouped by the nature or importance of them. If you are a module author and want to use Module::Install in your distributions, this is the document you should consult. If you are a user (or a contributor) of distributions that use Module::Install, you may also want to check Module::Install::FAQ where you'll find some common glitches you may encounter. Note that commands not listed here should be deemed private utility commands for the Module::Install developers, or unsupported commands with various reasons (some are experimental and half-baked, some are broken (by design or by implementation), some are simply deprecated, and so on). You may find some of them are used rather widely, but their use is discouraged. You have been warned. Most of these are also described in the main Module::Install's pod. Basically, (almost) all you have to know is the all_from command that tries to extract all the necessary basic meta data from a module file, but you can also specify one by one what is not written in the module and can't be extracted (you usually want to write these specific commands before all_from() not to be warned by the lack of information). all_from 'lib/Foo/Bar.pm'; all_from command takes a module file path, and will try to extract meta data from the module including a distribution name, a module version, the minimum required perl version for the module, authors information, a license, a short description of the module. See the following commands for the extraction detail. name 'Foo-Bar'; name_from 'lib/Foo/Bar.pm'; name commmand takes a distribution name. It usually differs slightly from a module name (a module name is separated by double colons; a distribution name is separated by hyphens). Just replacing all the double colons of your main module with hyphens would be enough for you. name_from takes a module file path, and looks for the topmost package declaration to extract a module name, and then converts it to a distribution name. You may optionally set module_name to specify a main module name (if you choose other naming scheme for your distribution). This value is directly passed to ExtUtils::MakeMaker in the backend as a NAME attribute (Module::Install usually creates this from the distribution name set by name or name_from). abstract 'a short description of the distribution'; abstract_from 'lib/Foo/Bar.pm'; abstract command takes a string to describe what that module/distribution is for. abstract_from takes a module file path and looks for a string that follows the module's name and a hyphen to separate in the NAME section of the pod. The value set by abstract or abstract_from is passed to ExtUtils::MakeMaker as an ABSTRACT attribute. version '0.01'; version_from 'lib/Foo/Bar.pm'; version command takes a version string for the distribution. version_from takes a module file path, and looks for the $VERSION of the module. The value set by version or version_from is passed to ExtUtils::MakeMaker as a VERSION attribute. version_from (and all_from) also sets a VERSION_FROM attribute to check version integrity of the distribution. perl_version '5.008'; perl_version_from 'lib/Foo/Bar.pm'; perl_version command takes a minimum required perl version for the distribution. perl_version_from takes a module file path, and looks for a use <perl_version> (or require <perl_version>) statement (note that now Module::Install only supports perl 5.005 and newer). The value set by perl_version or perl_version_from is passed to ExtUtils::MakeMaker as a MIN_PERL_VERSION attribute (if applicable). author 'John Doe <john.doe at cpan.org>'; author_from 'lib/Foo/Bar.pm'; author command takes a string to describe author(s). You can set multiple authors with one author command, or with multiple authors (you can also use authors alias if you prefer). author_from takes a module file path, and looks for an AUTHOR (or AUTHORS) section in the pod (and also license/copyright sections if it can't find any author(s) section) to extract an author. The value set by author or author_from is concatenated and passed to ExtUtils::MakeMaker as an AUTHOR attribute. license 'perl'; license_from 'lib/Foo/Bar.pm'; license command takes an abbreviated license name including perl, artistic, apache, (l)gpl, bsd, mit, mozilla, open_source, and so on. If you don't (want to) specify a particular license, it will be unknown. license_from takes a module file path, and looks for a LICENSE (or LICENCE) section in the pod (and also COPYRIGHT section if it can't find any) to extract a license. The value set by license or license_from is passed to ExtUtils::MakeMaker as an LICENSE attribute (if applicable). You are also reminded that if the distribution is intended to be uploaded to the CPAN, it must be an OSI-approved open source license. Commercial software is not permitted on the CPAN. Most of these are described in the main pod, too. requires 'Foo::Bar'; requires 'Foo::Baz' => '1.00'; requires command takes a module name on which your distribution depends, and its minimum required version if any. You may add arbitrary numbers of requires. You even can add multiple numbers of dependencies on the same module with different required versions (which will be sorted out later, though). Note that this dependency is on the basis of a module, not of a distribution. This usually doesn't matter, and you just need to call for a module you really need (then you'll get the whole distribution it belongs to), but sometimes you may need to call for all the modules that the required module implicitly requires. The values set by requires are passed to ExtUtils::MakeMaker as a PREREQ_PM attribute. build_requires 'ExtUtils::Foo::Bar'; build_requires 'ExtUtils::Foo::Baz' => '1.00'; test_requires 'Test::Foo::Bar'; test_requires 'Test::Foo::Baz' => '1.00'; build_requires command also takes a module name and a minimum required version if any. The difference from the requires command is that build_requires is to call for modules you'll require while building the distribution, or in the tests, and that in theory are not required at run-time. This distinction is more for other system package managers than for the CPAN, from where you usually want to install everything for future reuse (unless you are too lazy to test distributions). As of this writing, test_requires is just an alias for build_requires, but this may change in the future. The values set by build_requires and test_requires are passed to ExtUtils::MakeMaker as a BUILD_REQUIRES attribute, which may fall back to PREREQ_PM if your ExtUtils::MakeMaker is not new enough. configure_requires 'ExtUtils::Foo::Bar'; configure_requires 'ExtUtils::Foo::Baz' => '1.00'; configure_requires command also takes a module name and a minimum required version if any. The difference from the requires command is that configure_requires is to call for modules you'll require to run perl Makefile.PL. This attribute only makes sense for the latest CPAN toolchains that parse META.yml before running perl Makefile.PL. The values set by configure_requires are passed to ExtUtils::MakeMaker as a CONFIGURE_REQUIRES attribute, which may fall back to PREREQ_PM if your ExtUtils::MakeMaker is not new enough. recommends 'ExtUtils::Foo::Bar'; recommends 'ExtUtils::Foo::Baz' => '1.00'; recommends command also takes a module name and a minimum required version if any. As of this writing, recommends is purely advisory, only written in the META.yml. Recommended modules will not usually be installed by the current CPAN toolchains (other system package managers may possibly prompt you to install them). feature( 'share directory support', -default => 1, 'File::ShareDir' => '1.00', ); features( 'JSON support', [ -default => 0, 'JSON' => '2.00', 'JSON::XS' => '2.00', ], 'YAML support', [ 'YAML' => '0', ], ); feature command takes a string to describe what the feature is for, and an array of (optional) modules and their recommended versions if any. features command takes an array of a description and an array of modules. As of this writing, both feature and features work only when auto_install (see below) is set. These are used to allow distribution users to choose what they install along with the distribution. This may be useful if the distribution has lots of optional features that may not work on all the platforms, or that require too many modules for average users. However, prompting users also hinders automated installation or smoke testing, and is considered a bad practice (giving sane default values is much preferred). Though featured modules are optional and can be chosen during the installation, the chosen modules are treated the same as the ones set by requires command. (They are not listed in the recommends section in the META.yml). This may change in the future. You can add -default => [01] in an array of required modules in the feature(s), to set a default value for the prompt. These are the commands to write actual meta files. use inc::Module::Install; all_from 'lib/Foo/Bar.pm'; WriteAll; WriteAll command is usually the last command in the Makefile.PL. It can take several attributes, but you usually don't need to care unless you want to write a Makefile for an Inline-based module. This writes Makefile, META.yml, and MYMETA.yml (or MYMETA.json) if you set an experimental environmental variable X_MYMETA. use inc::Module::Install; requires 'Foo::Baz'; # a la Module::Install WriteMakefile( # a la ExtUtils::MakeMaker NAME => 'Foo::Bar', VERSION_FROM => 'lib/Foo/Bar.pm', ); If you're familiar with ExtUtils::MakeMaker and generally want to stick to its way, you can. Use as much Module::Install's magic as you want, and then fall back to the good and old way. It just works. write_mymeta_yaml; write_mymeta_json; write_mymeta_yaml command and write_mymeta_json command are to write MYMETA.yml and MYMETA.json respectively, which are new enhancement for the CPAN toolchains that eventually will allow toolchain modules to know what modules are required without parsing Makefile etc. These are mainly for internal use (in the WriteAll command) but you can explicitly write these commands in your Makefile.PL. makemaker_args( PREREQ_FATAL => 1, dist => { PREOP => 'pod2text lib/Foo/Bar.pm > README' }, ); makemaker_args command is used in WriteMakefile command, and takes any attributes ExtUtils::MakeMaker understands. See ExtUtils::MakeMaker for the available attributes. preamble "# my preamble\n"; postamble qq{my_done ::\n\t\$(PERL) -e "print qq/done\\n/"\n}; preamble and postamble commands take a string to be embedded in the Makefile. You can add custom targets with this. See appropriate manuals to learn how to write Makefile. These are to set test files. tests 't/*.t t/*/*.t'; tests command takes a string to specify test files. You can use wildcard characters, and if you want to run tests under several directories, concatenates the specs with white spaces. If you haven't set tests by any means (with explicit tests command, or extensions like Module::Install::AuthorTests or Module::Install::ExtraTests), and if you have an xt directory, Module::Install silently adds those tests under the xt directory when you are in the author mode, or you are doing release testing (with RELEASE_TESTING environmental variable). The value set by tests is passed to ExtUtils::MakeMaker as a test attribute. tests_recursive; tests_recursive('t'); tests_recursive command may take a directory, and looks for test files under it recursively. As of this writing, you can't use this command with other test related commands. installdirs 'site'; installdirs command takes a directory type, and changes a directory to install modules and so on, though you usually don't need to use this. The value set by installdirs is passed to ExtUtils::MakeMaker as an INSTALLDIRS attribute. install_as_core; # = installdirs 'perl'; install_as_cpan; # = installdirs 'site'; install_as_site; # = installdirs 'site'; install_as_vendor; # = installdirs 'vendor'; install_as_* commands are aliases of the corresponding commands shown in the comments above. These are to install files other than the ones under the lib directory. install_script('foo'); install_script('script/foo'); install_script command takes a script file name, and installs it into a script directory for your Perl installation. If your script is in a script directory, you can omit the script/ part. The value set by install_script is passed to ExtUtils::MakeMaker as an EXE_FILES attribute. install_share; install_share('templates'); install_share('dist', 'templates'); install_share('module', 'My::WebApp', 'share'); install_share command may take a directory type (either dist or module), a module name if necessary, and a directory ( share by default), and installs files under the directory into a share directory for the type, which is usually in a directory your perl is installed in (but this may not be true if you're using local::lib and the likes). You can access these shared files via File::ShareDir's dist_file or module_file according to the type. Note also that a shared directory is usually read-only. You can't use this as a private temporary directory. auto_install; The auto_install command is used to allow users to install dependencies of a local project when you run make after <perl Makefile.PL>. In the past this was the only sane way to pull extra dependencies without installing the actual module, although now there are some alternatives (which however do not completely replace auto_install). For example you can use cpan . (with newer CPAN) or cpanm --installdeps . (with App::cpanminus). auto_install also enables feature(s) commands to choose what you install (keep in mind that using feature() in CPAN distributions is generally considered a bad practice). Module::Install 0.96 and above installs distributions in the subdirectories by default as ExtUtils::MakeMaker does. You also can specify what to install one by one. build_subdirs 'win32' if $^O eq 'MSWin32'; build_subdirs command takes subdirectories where projects you want to install are in. The values set by build_subdirs are passed to ExtUtils::MakeMaker as a DIR attribute. These are to provide optional meta data mainly used by the PAUSE indexer and the CPAN search site. See also the META-spec page () for details. no_index file => 'lib/My/Test/Module.pm'; no_index directory => 'templates'; no_index package => 'Test::Foo::Bar'; no_index namespace => 'Test::Foo::Bar'; no_index command takes a hash to describe what should be excluded from the PAUSE index etc. Module::Install provides several no_index directories by default, including inc, (x)t, test, example(s), demo. resources license => "", homepage => "", bugtracker => "", repository => "", MailingList => ""; resources command takes a hash that contains various URLs for the related resources. Keys in lower-case are reserved. These resources are written in the META.yml. homepage ''; bugtracker ''; repository ''; homepage, bugtracker, and repository commands take a URL for the corresponding resource. There are several commands to bundle modules/distributions in your distribution, but they are still broken in general. Don't use them for now. libs '-lz'; libs [qw/-lz -Llibs/]; cc_lib_paths 'libs'; cc_lib_links qw/z iconv/; libs command takes a string, or an array reference of strings to be passed to ExtUtils::MakeMaker as a LIBS attribute. cc_lib_paths and cc_lib_links are its alternatives, both of which take an array of strings. cc_lib_paths is for upper-cased -L (directories), and cc_lib_links is for lower-cased -l (libraries). inc '-I. -Iinclude'; cc_inc_paths qw/. include/; inc command takes a string to be passed to ExtUtils::MakeMaker as an INC attribute. cc_inc_paths is its alternative, and takes an array of directories. cc_optimize_flags '-O2'; cc_optimize_flags takes a string to be passed to ExtUtils::MakeMaker as an OPTIMIZE attribute. ppport; ppport command is used to bundle ppport.h to a distribution. requires_external_cc; requires_external_cc command checks if the user has a working compiler listed in the Config, and exits the Makefile.PL if none is found. exit 0 unless can_cc; can_cc command tells if the use has a working compiler or not. clean_files '*.o Foo-*'; realclean_files '*.o Foo-*'; clean_files command takes a string or an array of strings, concatenates them with spaces, and passes the result to ExtUtils::MakeMaker as a clean attribute. realclean_files does the same for a realclean attribute. if (can_use('Some::Module', '0.05')) { Some::Module::do_something(); } can_use command takes a module name, and optionally a version, and checks if the module (with the version if appropriate) is installed or not. if (can_run('svn')) { # do something with the C<svn> binary } can_run command takes a executable path, and checks if the executable is available or not. requires_external_bin 'svn'; requires_external_bin command takes a executable path, and exits the Makefile.PL if none is available. Kenichi Ishigaki <[email protected]> This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/dist/Module-Install/lib/Module/Install/API.pod
CC-MAIN-2016-44
refinedweb
2,777
55.95
◕ A new product. Popular Google Pages: ◕ This article is regarding What is a Member Function in C++? Last updated on: 12th December 2016. ◕ Let an example first. #include <iostream> using namespace std; char state = 'T'; int main() { cout << "Displaying char constant using Member Function, cout.put(): " << endl; cout.put(state); return 0; } The output of this program is: Displaying char constant using Member Function, cout.put(): T - Here cout.put() is a Member Function. - A Member Function belongs to a class and it describes a method to manipulating the class data. Here ostream class has a put() Member Function that is designed to output character constant such as 'T'. Here put() is the class Member Function and cout is the class object. - We can use a Member Function only with a particular object of that class. Here the cout is that object. - To use a class Member Function with an object, we need a period (. full stop) to combine the object name with the function name. This period is called the Membership Operator. Example: In this cout.put() Member Function we used a period sign as the membership operator. - The cout.put() Member Function is an alternative of the << operator to display a character constant. So why we need cout.put()? - Because cout.put() was used in the old version of the C++ for displaying char constant such as 'A', 'B' etc. Related articles: ◕ Bits & Bytes ◕ Integer Type in C++ ◕ Rules for Variable Names ◕ Variable in C++ ◕ Fundamental Data Types & Compound Data Types Popular Google Pages: Top of the page
http://riyabutu.com/c-plus-plus/what-is-member-function.php
CC-MAIN-2017-51
refinedweb
260
68.87
Re-Ment Disney Donuts miniature blind packet "Disney Donuts" Miniature Packet from Re-Ment import from Japan highly detailed miniature set with 15 Disney donuts: donuts with Mickey Mouse, Minnie Mouse, Donald Duck, Winnie-the-Pooh, Daisy Duck, Goofy and many more This is a blind packet, that means it is a surprise what theme you will get and we cannot tell what is inside either! Each theme includes one miniature theme. If you want to have the complete set, please order 15 pieces! You will get every item one time only and no item twice, incl. the original box. content: 1 of the 15 themes packet height: 9.6cm (3.8"), width: 7.3cm (2.9") miniature items: about 4cm (1.6") The packet is the same on the outside, but different on the inside very good quality super cute design perfect for your miniature collection, for the doll house, Barbie, Blythe, Pullip and more
http://www.modes4u.com/en/kawaii/p5533_Re-Ment-Disney-Donuts-miniature-blind-packet.html
CC-MAIN-2015-40
refinedweb
156
71.85
Let me explain the objective first. Let’s say I have 1000 images each with an associated quality score [in range of 0-10]. Now, I am trying to perform the image quality assessment using CNN with regression(in pytorch). I have divided the images into equal size patches. Now, I have created a CNN network in order to perform the linear regression. Following is the code: class MultiLabelNN(nn.Module): class MultiLabelNN(nn.Module): def __init__(self): super(MultiLabelNN, self).__init__() self.conv1 = nn.Conv2d(1, 32, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(32, 64, 5) self.fc1 = nn.Linear(3200,1024) self.fc2 = nn.Linear(1024, 512) self.fc3 = nn.Linear(512, 1) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.pool(x) x = self.conv2(x) x = F.relu(x) x = x.view(-1, 3200) x = self.fc1(x) x = F.relu(x) x = self.fc2(x) x = F.relu(x) x = self.fc3(x) return x While running this code of network I am getting following error input and target shapes do not match: input [400 x 1], target [200 x 1] the target shape is [200x1] is because I have taken the batch size of 200. I found the solution that if I change “self.fc1 = nn.Linear(3200,1024)” and “x = x.view(-1, 3200)” here from 3200 to 6400 my code runs without any error. Similarly, It will throw an error input and target shapes do not match: input [100 x 1], target [200 x 1] if I put 12800 instead of 6400 Now my doubt is that I am not able to understand the reason behind this. If I am giving 200 images as input to my network then why the input shape is getting affected while changing the parameters when I move from convolutional layer to fully connected layer. I hope I have clearly mentioned my doubt. Even though If anybody has any doubt please ask me. It will be a great help. Thanks in advance.
https://discuss.pytorch.org/t/linear-regression-with-cnn-using-pytorch-input-and-target-shapes-do-not-match-input-400-x-1-target-200-x-1/25178
CC-MAIN-2018-39
refinedweb
346
71.1
This post will show how to create a Student Enrollment Application using MYSQL DB with Hibernate ORM in a REST based Jersey2 Spring environment. This is a simple application that aims to collect the input details from the user during signup, save the details in the MYSQL DB and authenticate the same during login. 1. Create Java Web Application Project using Maven Template To begin with, from the command line, create a Java Maven project with the template of jersey-quickstart-webapp by providing appropriate values for GroupId, Artifact Id, Version and Package for the project. Import the project into the IDE using File->Import->Existing Maven Projects, select Root Directory where the Project is created (ideally the name of the Project or ArtifactId) and click on Finish. The sample web application directory structure is shown below with a standard deployment descriptor web.xml and Maven pom.xml 2. Update pom.xml To make the above Maven Java Web Application project support the Hibernate ORM and Jersey Container in Spring framework, add the following dependencies to the existing pom.xml - jstl and servlet-api (for Javax Servlet Support) - jersey-container-servlet, jersey-media-moxy, jersey-spring3, jersey-server and jersey-mvc-jsp (for Jersey Support) - spring-core, spring-context, spring-web and spring-webmvc(for Spring Support) - junit (for JUnit Support) - commons-lang3 (for standard Java Welcome file. - The Context Config Location. - A ContextLoaderLister and RequestContextListener to integrate spring with the web application. - A Spring Jersey Web Servlet. Specify the location of the provider packages, enable the JSON POJO Mapping Feature, provide the path where the JSP files for the project are stored to the JSP TemplateBasePath and enable the JSP MVC Feature. In this sample, a configuration file named applicationConfig.xml is created under src/main/resources folder and the JSP files are placed under WEB-INF/jsp folder in the project layout. - A servlet-mapping to map the servlet created in the above step that should be invoked when the client specifies the url matching the url pattern. 4. Create persistence.xml Create a file named persistence.xml under the folder src/main/resources/META-INF folder in the project to define the persistence unit required by JPA. Add the following to the persistence.xml to define a persistence unit named punit. 5. Create the Spring Configuration File As defined in the web.xml, create a file named applicationContext, mvc and tx namespaces. The applicationContext.xml will be as shown below After enabling the required namespaces, include the following (in between the <beans> and </beans> tags) to indicate that the application is annotation driven, base package for context component scan applicationContext.xml 6. Create JSP Files for Student Signup/Login Create a folder named “jsp” under WEB-INF (This is where the jsp files will be created as indicated in the web.xml for the JSP TemplateBasePath). app folder of this application can be found at 7. Create packages for Resource, Service, Repository and Model tier classes Create packages each for the Jersey Resource, Service, Repository and Model classes under the src/main/java folder. A sample snapshot of the project after the package creation is as shown below:. Annotate the classes with @Component to be picked by the Context-Component Scan of the Jersey-Spring framework. Also annotate the classes with @XmlRootElement to indicate the XML Element. A reference link to the files for the Model classes can be found at. 10.. 11. Create class for Resource Tier Create a Resource tier POJO class named StudentResource.java inside the package com.github.elizabetht.resource. This is where a REST API is implemented for each of the operation performed from the front end. 12. dataSource bean in applicationContext.xml Once the studentEnrollment DB Schema is created, create a table named student inside the DB Schema using the CREATE TABLE statement as follows:. 14. Clone or Download code If using git, clone a copy of this project here: In case of not using git, download the project as ZIP or tar.gz file here:
http://elizabetht.github.io/blog/2013/12/13/student-enrollment-using-jersey-rest-with-spring/
CC-MAIN-2017-09
refinedweb
675
54.42
Overview: - Mutable objects are Python objects that can be changed. - Immutable objects are Python objects that cannot be changed. - The difference originates from the fact the reflection of how various types of objects are actually represented in computer memory. - Be aware of these differences to avoid surprising bugs in your programs. Introduction To be proficient a Python programmer must master a number of skills. Among those is an understanding of the notion of mutable vs immutable objects. This is an important subject, as without attention to it programmers can create unexpected and subtle bugs in their programs. As described above, at its most basic mutable objects can be changed, and immutable objects cannot be changed. This is a simple description, but for a proper understanding, we need a little context. Let’s explore this in the context of the Python data types. Mutable vs. Immutable Data Types The first place a programmer is likely to encounter mutable vs. immutable objects is with the Python data types. Here are the most common data types programmers initially encounter, and whether they are mutable or immutable (this is not a complete list; Python does have a few other data types): Let’s experiment with a few of these in the Python shell and observe their mutability/immutability. First let’s experiment with the list, which should be mutable. We’ll start by creating a list: >>> our_list1 = ['spam', 'eggs'] Now let’s try changing the list using a slicing assignment: >>> our_list1[0] = 'toast' Now let’s view our list and see if it has changed: >>> our_list1 ['toast', 'eggs'] Indeed, it has. Now let’s experiment with integers, which should be immutable. We’ll start by assigning an integer to our variable: >>> our_int1 = 3 >>> our_int1 3 Now let’s try changing it: >>> our_int1 = 42 >>> our_int1 42 It changed. If you’ve already worked with Python this should not surprise you. So in what sense is an integer immutable? What’s going on here? What do the Python language designers mean they claim integers are immutable? It turns out the two cases are actually different. - In the case of the list, the variable still contains the original list but the list was modified. - In the case of the integer, the original integer was completely removed and replaced with a new integer. While this may seem intuitive in this example, it’s not always quite so clear as we’ll see later. Many of us start out understanding variables as containers for data. The reality, where data is stored in memory, is a little more complicated. The Python id() function will help us understand that. Looking Under the Hood: the id() Function The common understanding of variables as containers for data is not quite right. In reality variables contain references to where the data stored, rather than the actual data itself. Every object or data in Python has an identifier integer value, and the id() function will show us that identifier (id). In fact, that id is the (virtualized) memory location where that data is stored. Let’s try our previous examples and use the id() function to see what is happening in memory 🛑 Note: be aware that if you try this yourself your memory locations will be different. >>> our_list1 = ['spam', 'eggs'] >>> id(our_list1) 139946630082696 So there’s a list at memory location 139946630082696. Now let’s change the list using a slicing assignment: >>> our_list1[0] = 'toast' >>> our_list1 ['toast', 'eggs'] >>> id(our_list1) 139946630082696 The memory location referenced by our_list1 is still 139946630082696. The same list is still there, it’s just been modified. Now let’s repeat our integer experiment, again using the id() function to see what is happening in memory: >>> our_int1 = 3 >>> our_int1 3 >>> id(our_int1) 9079072 So integer 3 is stored at memory location 9079072. Now let’s try to change it: >>> our_int1 = 42 >>> our_int1 42 >>> id(our_int1) 9080320 So our_int1 has not removed the integer 3 from memory location 9079072 and replaced it with integer 42 at location 9079072. Instead it is referencing an entirely new memory location. Memory location 9079072 was not changed, it was entirely replaced with memory location 9080320. The original object, the integer 3, still remains at location 9079072. Depending on the specific type of object, if it is no longer used it will eventually be removed from memory entirely by Python’s garbage collection process. We won’t go into that level of detail in this article – thankfully Python takes care of this for us and we don’t need to worry about it. We’ve learned lists can be modified. So here’s a little puzzle for you. Let’s try modifying our list variable in a different way: >>> our_list1 = ['spam', 'eggs'] >>> id(our_list1) 139946630082696 >>> our_list1 = ['toast', 'eggs'] >>> our_list1 ['toast', 'eggs'] >>> id(our_list1) What do you think the id will be? Let’s see the answer: >>> id(our_list1) 139946629319240 Woah, a new id! Python has not modified the original list, it has replaced it with a brand new one. So lists can be modified, if something like assigning elements is done, but if instead a list is assigned to the variable, the old list is replaced with a new one. Remember: What happens to a list, whether being modified or replaced, depends on what you do with it. However if ever you are unsure what is happening, you can always use the id() function to figure it out. Mutable vs. Immutable Objects So we’ve explored mutability in Python for data types. However, this notion applies to more than just data types – it applies to all objects in Python. And as you may have heard, EVERYTHING in Python is an object! The topic of objects, classes, and object-oriented programming is vast, and beyond the scope of this article. You can start with an introduction to Python object-orientation in this blog tutorial: Some objects are mutable, and some are immutable. One notable case is programmer-created classes and objects — these are in general mutable. Modifying a “Copy” of a Mutable Object What happens if we want to copy one variable to another so that we can modify the copy: normal_wear = ['hat', 'coat'] rain_wear = normal_wear Our rainy weather wear is the same as our normal wear, but we want to modify our rainy wear to add an umbrella. Before we do, let’s use id() to examine this more closely: >>> id(normal_wear) 139946629319112 >>> id(rain_wear) 139946629319112 So the copy appears to actually be the same object as the original. Let’s try modifying the copy: >>> rain_wear.append('umbrella') >>> rain_wear ['hat', 'coat', 'umbrella'] >>> normal_wear ['hat', 'coat', 'umbrella'] So what we learned from id() is true, our “copy” is actually the same object as the original, and modifying the “copy” modifies the original. So watch out for this! Python does provide a solution for this through the copy module. We won’t examine that here, but just be aware of this issue, and know that a solution is available. 💡 Note: immutable objects behave almost the same. When an immutable value is copied to a second variable, both actually refer to the same object. The difference for the immutable case is that when the second variable is modified it gets a brand new object instead of modifying the original. Bug Risk, and Power: Mutable Objects in Functions If you’re not careful, the problem we saw in the last section, modifying a “copy” of a variable, can happen when writing a function. Suppose we had written a function to perform the change from the last section. Let’s write a short program dressForRain.py which includes such a function: def prepForRain(outdoor_wear): outdoor_wear.append('umbrella') rain_outdoor_wear = outdoor_wear return rain_outdoor_wear normal_wear = ['hat', 'coat'] print('Here is our normal wear:', normal_wear) rain_wear = prepForRain(normal_wear) print('Here is our rain wear:', rain_wear) print('What happened to our normal wear?:', normal_wear) We know that the data is passed into the function, and the new processed value is returned to the main program. We also know that the variable created within the function, the parameter outdoor_wear, is destroyed when the function is finished. Ideally this isolates the internal operation of the function from the main program. Let’s see the actual results from the program (A Linux implementation is shown. A Windows implementation will be the same, but with a different prompt): $ python dressForRain.py Here is our normal wear: ['hat', 'coat'] Here is our rain wear: ['hat', 'coat', 'umbrella'] What happened to our normal wear?: ['hat', 'coat', 'umbrella'] Since variables normal_wear and outdoor_wear both point to the same mutable object, normal_wear is modified when outdoor_wear is appended, which you might not have intended, resulting in a potential bug in your program. Had these variables been pointing to an immutable object such as a tuple this would not have happened. Note, however, tuples do not support append, and a concatenation operation would have to be done instead. Though we have shown some risk using lists in a function, there is also power as well. Functions can be used to modify lists directly, and since the original list is modified directly, no return statement would be needed to return a value back to the main program. Tuple Mutable(?) ‘Gotcha’ Here is one last, perhaps surprising, behavior to note. We’ve mentioned that tuples are immutable. Let’s explore this a little further with the following tuple: >>> some_tuple = ('yadda', [1, 2]) Let’s try modifying this by adding 3 to the list it contains: >>> some_tuple[1].append(3) What do you think happens? Let’s see: >>> some_tuple ('yadda', [1, 2, 3]) Did our tuple change? No it did not. It still contains the same list – it is the list within the tuple that has changed. You can try the id() function on the list portion of the tuple to confirm it’s the same list. Why Bother with Mutable vs. Immutable? This mutable/immutable situation may seem a bit complicated. Why did the Python designers do this? Wouldn’t it have been simpler to make all objects mutable, or all objects immutable? Both mutable and immutable properties have advantages and disadvantages, so it comes down to design preferences. Advantage: For instance, one major performance advantage of using immutable instead of mutable data types is that a potentially large number of variables can refer to a single immutable object without risking problems arising from overshadowing or aliasing. If the object would be mutable, each variable would have to refer to a copy of the same object which would incur much higher memory overhead. These choices are affected by how objects are typically used, and these choices affect language and program performance. Language designers take these factors into account when making those choices. Be aware that other languages address the mutable/immutable topic as well, but they do not all implement these properties in the same way. We will not go into more detail on this in this article. Your appreciation of these choices will develop in the future as you gain more experience with programming. Conclusion - We have noted that Python makes some of its objects mutable and some immutable. - We have explored what this means, and what some of the practical consequences of this are. - We have noted how this is a consequence of how objects are stored in memory, and - We have introduced Python’s id()function as a way to better follow this memory use. High-level programming languages are an ever-advancing effort to make programming easier, freeing programmers to produce great software without having to grapple with the minute details as the computer sees it. Being aware of how mutable and immutable objects are handled in memory is one case where a bit more awareness of the details of the computer will reap rewards. Keep these details in mind and ensure your programs perform at their best.
https://blog.finxter.com/mutable-vs-immutable-objects-in-python/
CC-MAIN-2022-21
refinedweb
1,974
62.27
MATLAB Newsgroup. "shome" wrote in message <[email protected]>... >. I may be completely off base here, but my understanding is that MATLAB doesn't "come" with a c compiler. It uses the c compiler you have (already) installed on your computer (with the "mex -setup" command). "shome" wrote in message <[email protected]>... > > Hello.c: > > #include <math.h> > #include <matrix.h> > #include <mex.h> Try changing the above includes to: #include <math.h> #include "mex.h" James Tursa "someone" wrote in message <[email protected]>... > > I may be completely off base here, but my understanding is that MATLAB doesn't "come" with a c compiler. It uses the c compiler you have (already) installed on your computer (with the "mex -setup" command). 32-bit MATLAB typically ships with the lcc compiler (a C compiler). I don't think 64-bit MATLAB ships with any compiler (although I don't have 64-bit MATLAB myself to check this)..
http://www.mathworks.com/matlabcentral/newsreader/view_thread/326294
CC-MAIN-2015-18
refinedweb
166
61.43
How to Set up Apache Kafka on Databricks This topic explains how to set up Apache Kafka on AWS EC2 machines and connect them with Databricks. Following are the high level steps that are required to create a Kafka cluster and connect from Databricks notebooks. In this topic: Step 1: Create a new VPC in AWS When creating the new VPC, set the new VPC CIDR range different than the Databricks VPC CIDR range. For example: Databricks VPC vpc-7f4c0d18has CIDR IP range 10.205.0.0/16 New VPC vpc-8eb1faf7has CIDR IP range 10.10.0.0/16 Create a new internet gateway and attach it to the route table of the new VPC. This allows you to ssh into the EC2 machines that you launch under this VPC. Create a new internet gateway. Attach it to VPC vpc-8eb1faf7. Step 2: Launch the EC2 instance in the new VPC Launch the EC2 instance inside the new VPC vpc-8eb1faf7 created in Step 1. Step 3: Install Kafka and ZooKeeper on the new EC2 instance SSH into the machine with the key pair. ssh -i keypair.pem [email protected] Download Kafka and extract the archive. wget tar -zxf kafka_2.12-0.10.2.1.tgz Start the ZooKeeper process. cd kafka_2.12-0.10.2.1 bin/zookeeper-server-start.sh config/zookeeper.properties Edit the config/server.propertiesfile and set 10.10.143.166as the private IP of the EC2 node. advertised.listeners=PLAINTEXT:/10.10.143.166:9092 Start the Kafka broker. cd kafka_2.12-0.10.2.1 bin/kafka-server-start.sh config/server.properties Step 4: Peer two VPCs Create a new peering connection. Add the peering connection into the route tables of your Databricks VPC and new Kafka VPC created in Step 1. In the Kafka VPC, go to the route table and add the route to the Databricks VPC. In the Databricks VPC, go to the route table and add the route to the Kafka VPC. For details on VPC peering, refer to VPC Peering. Step 5: Access the Kafka broker from a notebook Verify you can reach the EC2 instance running the Kafka broker with telnet. Create a new topic in the Kafka broker. SSH to the Kafka broker. ssh -i keypair.pem [email protected] Create a topic from the command line. bin/kafka-console-producer.sh --broker-list localhost:9092 --topic wordcount < LICENSE Read data in a notebook. import org.apache.spark.sql.functions._ val kafka = spark.readStream .format("kafka") .option("kafka.bootstrap.servers", "10.10.143.166:9092") .option("subscribe", "wordcount") .option("startingOffsets", "earliest") display(kafka) Example Kafka byte steam
https://docs.databricks.com/user-guide/faq/kafka-setup.html
CC-MAIN-2019-22
refinedweb
465
68.36
Murphy's Law states that: - "Anything that can possibly go wrong, does." - "Everything that can possibly go wrong will go wrong." - "If anything can go wrong, it will." - "If there is any way to do it wrong, he will." When software goes wrong, the MOST IMPORTANT thing to do is to FIND the ERROR MESSAGE, which can give you clues of what went wrong. If things were running fine until the lightning strikes, ask yourself what have you CHANGED! Search this document with your Error Message; or simple google your error message. Stack Trace Most of the times, the error message consists of tens of lines of so-called stack trace of method invocation. That is, method A called method B, which called method C, and so on, until method Z encountered an error and threw an Exception or an Error. It is important to: - Get to the first line of the error message to read the description, and - Look for the line number of YOUR PROGEAM that triggered the error. For example, this error message (stack trace) has 40 over lines: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure <== First line with error description The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the.SQLError.createCommunicationsException(SQLError.java:1116) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2333) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2370) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:792) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java.ConnectionImpl.getInstance(ConnectionImpl.java:381) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305) at java.sql.DriverManager.getConnection(DriverManager.java:579) at java.sql.DriverManager.getConnection(DriverManager.java:221) at MySQLJdbcTestJDK7.main(MySQLJdbcTestJDK7.java:7) <== Your program's line number here (line 7) Caused by: java.net.ConnectException: Connection refused: connect <== First line of another related error at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69):241) at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:257) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:294) ... 15 more JDK Common Errors JDK Installation Errors SYMPTOM: Cannot compile Java program from the CMD shell (e.g., "javac Hello.java" does not work!) ERROR MESSAGE: 'javac' is not recognized as an internal or external command, operable program or batch file. PROBABLE CAUSES: The PATH environment variable, which maintains a list of search paths for executable programs (including "javac.exe"), does not include JDK's bin directory. POSSIBLE SOLUTIONS: 1) Start a CMD shell (click "Start" button ⇒ "run..." ⇒ enter "cmd") and issue a path command: prompt> path PATH=....... 2) Check if it includes your JDK's "bin" directory. For example, suppose that your JDK is installed in "c:\program files\java\jdk1.7.0", then PATH should include "c:\program files\java\jdk1.7.0\bin". Otherwise, include JDK's bin directory in the PATH environment variable. Read "Step 3 of How to install JDK". SYMPTOM: Can compile but cannot run Java program from the CMD shell (e.g., "java Hello" does not work!) ERROR MESSAGE (JDK 1.7): Error: Could not find or load main class Hello ERROR MESSAGE (Pre JDK 1.7): Exception in thread "main" java.lang.NoClassDefFoundError: Hello PROBABLE CAUSES: 1) The Java class (in this example, Hello.class) is NOT in the current directory. 2) The CLASSPATH environment variable is set, but does not include the current directory ".". POSSIBLE SOLUTIONS: 1) Issue a "dir" command to list the contents of the current directory. Check that it contains the Java class to be run (e.g., Hello.class). You need to compile the source program (".java") to get the class file (".class"). 2) If the Java class is present in the current directory, issue a "set classpath" command to check its settings: prompt> set classpath CLASSPATH=....... If you receive the message "Environment variable CLASSPATH not defined" and your program is correct, I can't help you here. Otherwise, if the CLASSPATH is defined, for beginner, I suggest that you remove the CLASSPATH environment variable. From "Control Panel" ⇒ System ⇒ (Vista only) Advanced system settings ⇒ Switch to "Advanced" tab ⇒ Environment Variables ⇒ System variables (and also User variables) ⇒ Select variable "CLASSPATH" ⇒ Delete (Delete from both the System variables and User variables) 3) (For Advanced Users Only) If CLASSPATH is not set, it is defaulted to the current directory. However, if CLASSPATH is set, the current directory is NOT implicitly included. You can include the current directory (denoted by a single dot ".") in front of the existing class-paths. Read "Java Applications and Environment Variable" for more discussion on CLASSPATH. SYMPTOM: Can compile but cannot run the Hello-world program (e.g., "java Hello" does not work!) ERROR MESSAGE (JDK 1.7): Error: Main method not found in class Hello. POSSIBLE SOLUTIONS: Check whether there is a main() method in your program, and the signature of your main() as shown in the error message. SYMPTOM: Cannot compile Java program ERROR MESSAGE (JDK 1.7): Could not find or load main class com.sun.tools.javac.Main POSSIBLE SOLUTIONS: You did not install JDK and JRE correctly. If you are a novice, re-install JDK (Read "How to install JDK" again) 1. Un-install JDK and JRE (via control panel ⇒ "Program and Features"...) 2. Download the JDK (with JRE) and re-install. Use the default directories for JDK and JRE. That is, simply click Simply click "next"..."next"... to install JDK in "C:\Program Files\java\jdk1.7.0_0x" and JRE in "C:\Program Files\java\jre7". DO NOT change the installed directories! 3. Update the PATH environment variable. SYMPTOM: Cannot run the downloaded JDK Installer. Double-click the installer but nothing happens! POSSIBLE SOLUTIONS: There seems to be a bug in JDK 1.7 u2 onwards, that affects only some computers. Download and install JDK 1.7 u1 or below. Java Native Library (JNI) Errors ERROR MESSAGE: SEVERE: java.lang.UnsatisfiedLinkError: no xxx in java.library.path PROBABLE CAUSES: Your program uses a native library from a 3rd-party API (such as JOGL), which cannot be located in the native library search paths. POSSIBLE SOLUTION: A Java Native Library (JNI) contains non-Java library codes (in filetype of ".dll" in Windows, ".so" in Linux, ".jnilib" in MacOS). For example, JOGL's "jogl_xxx.dll", "gluegen-rt.dll". These dll's are needed for proper operations. The directory path of native libraries must be included in Java system's property "java.library.path". The "java.library.path" usually mirrors the Envrionment Variable PATH. You can list the entries by issuing: System.out.println(System.getProperty("java.library.path")); To include a directory in "java.library.path", you can use VM command-line option -Djava.library.path=pathname For JRE: > java -Djava.library.path=d:\bin\jogl2.0\lib myjoglapp For Eclipse, the VM command-line option can be set in "Run Configuration..." ⇒ "Arguments" ⇒ "VM Arguments". Alternatively, you can create a User library and specifying the native library (Refer to "Eclipse How-To") For NetBeans, the VM command-line option can be set in "Set Configuration" ⇒ "Customize..." ⇒ "Run" ⇒ "VM options". MySQL Installation Common Errors Starting the MySQL Server after Installation First of all, check if you have already started an instance of MySQL Server: - For Windows, start the "Task Manager", select "Processes" and look for " mysqld" processes. "End" all the " mysqld" processes. - For Mac, start the "Activity Monitor", select "All Processes" and look for " mysqld" processes. "Kill" all the " mysqld" processes. - For Ubuntu, start the "System Monitor" and look for " mysqld" processes. "Kill" all the " mysqld" processes. SYMPTOM: Cannot start MySQL server after installation ERROR MESSAGE: [ERROR] Can't find message file 'x:\xxxxx\share\english\errmsg.sys' PROBABLE CAUSES: Error in "basedir" option in the configuration file "my.ini". POSSIBLE SOLUTIONS: 1. Take note of your MySQL installed directory, e.g., d:\myproject\mysql. 2. Goto the MySQL installed directory, and check if "my.ini" (for Windows) or "my.cnf" (for Mac and Ubuntu) exists. 3. For Windows, if you use NotePad, ensure that you save the configuration file as "my.ini", instead of "my.ini.txt". "my.ini.txt" has file type of "Text Document". "my.ini" has file type of "Configuration Settings". "Save As..." the file again by enclosing the filename "my.ini" with a pair of double quotes. 4. Check the "basedir" and "datadir" options in "my.ini". Make sure that that path corresponds to your MySQL installed directory. Use Unix-style forward slash '/' as the directory separator, instead of Windows-style back slash '\'. SYMPTOM: Cannot start MySQL server after installation ERROR MESSAGE: [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it. ......... [ERROR] Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist PROBABLE CAUSES: Error in "datadir" option in the configuration file "my.ini". POSSIBLE SOLUTIONS: Check that "datadir" selects the "data" sub-directory of your MySQL installed directory, e.g., datadir=d:/myproject/mysql/data SYMPTOM: MySQL Server runs on TCP port 3306 (the MySQL default port number) instead of 8888 that was configured. PROBABLE CAUSES: MySQL Server was not started with your customized "my.ini". POSSIBLE SOLUTIONS: 1. Take note of your MySQL installed directory, e.g., d:\myproject\mysql. 2. Goto the MySQL installed directory, and check if "my.ini" exists. SYMPTOM: Cannot start MySQL server. ERROR MESSAGE: InnoDB: Operating system error number 32 in a file operation. InnoDB: The error means that another program is using InnoDB's files. InnoDB: This might be a backup or antivirus software or another instance of MySQL. InnoDB: Please close it to get rid of this error. PROBABLE CAUSES: You have already started an instance of MySQL. POSSIBLE SOLUTIONS: Shutdown the previously-started MySQL. You may use "Task Manager" to cancel the "process" called "mysqld". [The proper way is to use "mysqladmin" to do a normal shutdown.] Starting the "mysql" Client SYMPTOM: Cannot start mysql client ERROR MESSAGE: ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061) PROBABLE CAUSES: 1. MySQL Server is NOT started, or 2. The client was connecting to the wrong port number POSSIBLE SOLUTIONS: 1. Check to make sure that the MySQL server has been started. Note down the server's port number from the server's console. 2. Check "my.ini", make sure that you have a [client] section with port=xxxx. 3. Run a client with command "mysql -u root --port=xxxx" to specify the server's port number manually. SYMPTOM: Cannot start mysql client ERROR MESSAGE: error 2005 (hy000) unknown mysql server host 'localhost' (2) PROBABLE CAUSES: Somehow your localhost is not bind to 127.0.0.1 POSSIBLE SOLUTIONS: 1. Try "ping localhost" to check if "localhost" exists. 2. If not, check "C:\Windows\System32\drivers\etc\hosts" file. There should be an entry: 127.0.0.1 localhost Remove all the other localhost entries, if any. Using the "mysql" Client ERROR MESSAGE: ERROR 1046 (3D000): No database selected PROBABLE CAUSES: The default database is not set POSSIBLE SOLUTIONS: 1) Issue command "use database" to set the default database, or 2) Use the fully-qualified name in the form of "databaseName.tableName". ERROR MESSAGE: ERROR 1005 (HY000): Can't create table '....' (errno: 150) PROBABLE CAUSES: A foreign key references a parent table's column which is not indexed. Create index for that column in the parent table. Tomcat Installation Common Errors Starting Tomcat after Installation SYMPTOM: Cannot start Tomcat after installation. The Tomcat console flashed and disappeared. POSSIBLE SOLUTIONS: 1. Run the script "configtest.bat" (for Windows) or "./configtest.sh" (for Mac/Linux) to check configuration files ("server.xml", "web.xml", "content.xml"). 2. Check the Tomcat's log files, located at "<TOMCAT_HOME>\logs". The "catalina.{yyyy-mm-dd}.log" shows the Tomcat's startup messages. 3. Start the tomcat in the debugging mode by running "catalina debug" (or ./catalina.sh debug) and type "run" in the "jdb" prompt. Look for the error messages. 4. Check if you have already started a copy of Tomcat. For Windows, start Task Manager, Tomcat run as a "process" named "java.exe". Kill it. For Mac/Linux, issue "ps -ef | grep tomcat" to locate the Tomcat process. Note the process ID (pid), and kill the process via "kill -9 pid". 5. Check the JDK Extension directory, remove the out-dated "servlet-api.jar", if any. SYMPTOM: Cannot start Tomcat ERROR MESSAGE: SEVERE: StandardServer.await: create[localhost:8005] java.net.BindException: Address already in use: JVM_Bind POSSIBLE SOLUTIONS: 1. Another Tomcat instance has been started. Kill it. For Windows, start Task Manager, Tomcat run as a "process" named "java.exe". Kill it. For Mac/Linux, issue "ps -ef | grep tomcat" to locate the Tomcat process. Note the process ID (pid), and kill the process via "kill -9 pid". 2. Another application is running on the Tomcat's port number. Change the Tomcat's port number in "server.xml". You can issue command "netstat -an" to check the status of all the ports. SYMPTOM: Cannot start Tomcat after installation ERROR MESSAGE: 1. Neither the JAVA_HOME nor the JRE_HOME environment variable is defined At least one of these environment variable is needed to run this program 2. JRE_HOME environment variable is not defined POSSIBLE SOLUTIONS: 1. Check if JAVA_HOME is properly defined, via command "set JAVA_HOME" (for Windows) or "echo $JAVA_HOME" (for Mac/Linux). Check the spelling carefully. 2. Define environment variable JAVA_HOME according to "Step 2: Create an Environment Variable JAVA_HOME". SYMPTOM: Cannoat start Tomcat start after installation ERROR MESSAGE: java.lang.NoSuchMethodError: javax.servlet.ServletContext.getSessionCookieConfig() Ljavax/servlet/SessionCookieConfig; PROBABLE CAUSES: This is a new method in Servlets 3.0 (which Tomcat 7 supports). There is a Servlets 2.x API is your CLASSPATH or JDK's extension directory. POSSIBLE SOLUTIONS: Check your CLASSPATH. Remove servlet-api.jar from JDK's extension directory if any. Accessing Tomcat Server Common Error Messages: - (Firefox) Unable to Connect; (IE) Internet Explorer cannot display the webpage; (Chrome) Oops! Google Chrome could not connect to xxxx. - Error 404 File Not Found. - Error 500 Internal Server Error. - Error 505: GET (or POST) method not supported: Check you servlet to make sure that you have defined a doGet()(or doPost()) method. Read "How to debug" section of "How to install Tomcat". JDBC Programming Common Errors JDBC on MySQL SYMPTOM: Can compile the JDBC program but Runtime Error ERROR MESSAGE: (Windows) No suitable driver found (Mac/Linux) NullPointerException PROBABLE CAUSES: MySQL JDBC Driver Connector/J was NOT (properly) installed. POSSIBLE SOLUTION: 1. Read "Install MySQL JDBC Driver" again, again and again... 2. Make sure that you copy the driver to the JDK's Extension directory. 3. You may the following command to run your JDBC program: > java -cp .;path-to\mysql-connector-java-5.1.xx-bin.jar JdbcClassName 4. For Tomcat, you may place the driver JAR-file in Tomcat's "lib" directory. SYMPTOM: Can compile the JDBC program but Runtime Error ERROR MESSAGE: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure PROBABLE CAUSES: 1. MySQL Server is NOT started, or 2. The program was connecting to a wrong TCP port number or wrong hostname (or IP address) in your database-URL jdbc:mysql://localhost:port/studentdb. POSSIBLE SOLUTION: 1. Make sure that server has been started. Note down the server's port number from the server's console. 2. Check the database-URL's hostname and port number: jdbc:mysql://localhost:port/studentdb 3. Run a MySQL client, issue command "status" to confirm the server's TCP port number. 4. Run a mysql client, use "mysql -u root -p --port=xxxx" to specify the port number to confirm the server's port number. SYMPTOM: Can compile the JDBC program but Runtime Error ERROR MESSAGE: java.sql.SQLException: Access denied for user 'username'@'localhost' (using password: YES) PROBABLE CAUSES: Wrong username or password in statement: DriverManager.getConnection(databaseURL, username, password). POSSIBLE SOLUTION: Obvious! SYMPTOM: Can compile the JDBC program but Runtime Error ERROR MESSAGE: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'xxxx' PROBABLE CAUSES: DriverManager.getConnection("jdbc:mysql://localhost:8888/xxxx", user, password) specifies a database that does not exist in the server. POSSIBLE SOLUTION: Create the database using a client, before running the Java program. SYMPTOM: Can compile the JDBC program but Runtime Error ERROR MESSAGE: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'xxxx.xxxx' doesn't exist PROBABLE CAUSES: The SQL statement references a non-existence table. POSSIBLE SOLUTION: Check your SQL statement and the database tables. SYMPTOM: Can compile the JDBC program but Runtime Error ERROR MESSAGE: java.sql.SQLException: Column 'xxx' not found. PROBABLE CAUSES: The method ResultSet.getXxx(columnName) cannot locate the requested columnName in the ResultSet. POSSIBLE SOLUTION: Make sure that the column 'xxx' is included in the SELECT statement, so that it is included in the ResultSet. SYMPTOM: Can compile the JDBC program but Runtime Error ERROR MESSAGE: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near .... at line x PROBABLE CAUSES: Syntax error in your SQL statement. POSSIBLE SOLUTION: Obvious! SYMPTOM: Logical error in comparing floating point numbers for equality. For example, "SELECT * FROM class101 WHERE gpa = 4.4" yields empty set although there is a record with gpa=4.4. PROBABLE CAUSES: "gpa" has the type of FLOAT. Floating point numbers are not stored "accurately". POSSIBLE SOLUTION: Do not compare two floating point number for equality. Instead, specify a range, e.g., "gpa > 3.9 AND gpa < 4.1" SYMPTOM (NetBeans): I got this strange error running JDBC program on NetBeans. ERROR MESSAGE: The DriverManager.getConnection() method throws: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '??' at line 1 POSSIBLE SOLUTION: The NetBeans project was using "UTF-16" as the default charset. Hence, it communicates with MySQL server using "UTF-16" character set. The problem solved by setting the default charset to an ASCII compatible charset such as "Latin-1" or "UTF-8" (Right-click on the project ⇒ Properties ⇒ Encoding) JDBC on MS Access SYMPTOM (Access 2007): Can compile the JDBC program but Runtime Error ERROR MESSAGE: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified. PROBABLE CAUSES: No such Data Source (ODBC) name in method DriverManager.getConnection("jdbc:odbc:ODBCName"); POSSIBLE SOLUTION: Check your ODBC configuration (under control panel ⇒ ODBC). SYMPTOM (Access 2007): Can compile the JDBC program but Runtime Error ERROR MESSAGE: java.sql.SQLException: [Microsoft][ODBC Driver Manager] No data found PROBABLE CAUSES: The ODBCName in method DriverManager.getConnection("jdbc:odbc:ODBCName") does not SELECT a database. POSSIBLE SOLUTION: Check your ODBC configuration (under control panel ⇒ ODBC). SYMPTOM (Access 2007): Can compile the JDBC program but Runtime Error ERROR MESSAGE: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] The Microsoft Office Access database engine cannot find the input table or query 'xxx'. Make sure it exists and that its name is spelled correctly. PROBABLE CAUSES: The SQL statement references a non-existence table. POSSIBLE SOLUTION: Check your SQL statement and the database tables. SYMPTOM (Access 2007): Can compile the JDBC program but Runtime Error ERROR MESSAGE: java.sql.SQLException: Column not found. PROBABLE CAUSES: The method ResultSet.getXxx(columnName) cannot locate the requested columnName in the ResultSet. POSSIBLE SOLUTION: Make sure that the column is included in the SELECT statement, so that it is included in the ResultSet. SYMPTOM (Access 2007): Can compile the JDBC program but Runtime Error ERROR MESSAGE: [Microsoft][ODBC Microsoft Access Driver] Syntax error in FROM clause. [Microsoft][ODBC Microsoft Access Driver] Too few parameters. .... PROBABLE CAUSES: Syntax error in the SQL statement. POSSIBLE SOLUTION: Obvious! SYMPTOM (Access 2007): Can compile the JDBC program but Runtime Error ERROR MESSAGE: [Microsoft][ODBC Microsoft Access Driver] SQL General Error. PROBABLE CAUSES: This message is not clear, but most likly caused by inserting a record with duplicate primary key. SYMPTOM (Access 2007): Can compile the JDBC program but Runtime Error ERROR MESSAGE: [Microsoft][ODBC Microsoft Access Driver] The number of fields are not the same as the .... PROBABLE CAUSES: In the INSERT INTO tableName VALUES (...), you should have the same number of values as the number of columns. Java Servlet Common Errors SYMPTOM: Cannot compile Java Servlet ERROR MESSAGE: class xxxx is public, should be declared in a file named xxxx.java CAUSES/SOLUTION: In Java, the filename must be the same as the classname with extension of ".java". For example, the class "HelloServlet" must be saved as "HelloServlet.java" - case-sensitive! SYMPTOM: Cannot compile Java Servlet ERROR MESSAGE: package javax.servlet does not exist CAUSES/SOLUTION: The Java Servlet library is missing. Read "Step 6(a) Install Servlet API Library" again, again and again.... NetBeans Common Errors SYMPTOM: Cannot display chinese characters and other Unicode characters in the NetBeans editor ERROR MESSAGE: Chinese characters displayed as boxes or question marks in the NetBeans editor CAUSES/SOLUTION: 1. Check the character set. Right-click on the project ⇒ Property ⇒ "Source" node ⇒ "Encoding" ⇒ Choose "UTF-8" or the desired Unicode charater sets. 2. You also need to choose a font type that displays chinese or Unicode characters, such as "Monospace". In "Tools" menu ⇒ Options ⇒ Fonts & Colors ⇒ Syntax ⇒ default. If one font does not work, try another. C++ with GCC Compiler SYMPTOM: Cannot compile ERROR MESSAGE: error: 'string' does not name a type CAUSES/SOLUTION: missing "using namespace std;" SYMPTOM: Cannot compile ERROR MESSAGE: error: iostream: No such file or directory CAUSES/SOLUTION: The file is incorrectly saved as ".c" instead of ".cpp"
http://www3.ntu.edu.sg/home/ehchua/programming/howto/ErrorMessages.html
CC-MAIN-2016-18
refinedweb
3,637
52.15
Heuristic distribution of weighted items to bins (either a fixed number of bins or a fixed number of volume per bin). Data may be in form of list, dictionary, list of tuples or csv-file. Project description This package contains greedy algorithms to solve two typical bin packing problems, (i) sorting items into a constant number of bins, (ii) sorting items into a low number of bins of constant size. Here’s a usage example >>> import binpacking >>> >>> b = { 'a': 10, 'b': 10, 'c':11, 'd':1, 'e': 2,'f':7 } >>> bins = binpacking.to_constant_bin_number(b,4) # 4 being the number of bins >>> print("===== dict\n",b,"\n",bins) ===== dict {'a': 10, 'b': 10, 'c': 11, 'd': 1, 'e': 2, 'f': 7} [{'c': 11}, {'b': 10}, {'a': 10}, {'f': 7, 'e': 2, 'd': 1}] >>> >>> b = list(b.values()) >>> bins = binpacking.to_constant_volume(b,11) # 11 being the bin volume >>> print("===== list\n",b,"\n",bins) ===== list [10, 10, 11, 1, 2, 7] [[11], [10], [10], [7, 2, 1]] Consider you have a list of items, each carrying a weight w_i. Typical questions are - How can we distribute the items to a minimum number of bins N of equal volume V? - How can we distribute the items to exactly N bins where each carries items that sum up to approximately equal weight? Problems like this can easily occur in modern computing. Assume you have to run computations where a lot of files of different sizes have to be loaded into the memory. However, you only have a machine with 8GB of RAM. How should you bind the files such that you have to run your program a minimum amount of times? This is equivalent to solving problem 1. What about problem 2? Say you have to run a large number of computations. For each of the jobs you know the time it will probably take to finish. However, you only have a CPU with 4 cores. How should you distribute the jobs to the 4 cores such that they will all finish at approximately the same time? The package provides the command line tool “binpacking” using which one can easily bin pack csv-files containing a column that can be identified with a weight. To see the usage enter $ binpacking -h Usage: binpacking [options] Options: -h, --help show this help message and exit -f FILEPATH, --filepath=FILEPATH path to the csv-file to be bin-packed -V V_MAX, --volume=V_MAX maximum volume per bin (constant volume algorithm will be used) -N N_BIN, --n-bin=N_BIN number of bins (constant bin number algorithm will be used) -c WEIGHT_COLUMN, --weight-column=WEIGHT_COLUMN integer (or string) giving the column number (or column name in header) where the weight is stored -H, --has-header parse this option if there is a header in the csv-file -d DELIM, --delimiter=DELIM delimiter in the csv-file (use "tab" for tabs) -q QUOTECHAR, --quotechar=QUOTECHAR quotecharacter in the csv-file -l LOWER_BOUND, --lower-bound=LOWER_BOUND weights below this bound will not be considered -u UPPER_BOUND, --upper-bound=UPPER_BOUND weights exceeding this bound will not be considered Install $ pip install binpacking Examples In the repository’s directory cd examples/ binpacking -f hamlet_word_count.csv -V 2000 -H -c count -l 10 -u 1000 binpacking -f hamlet_word_count.csv -N 4 -H -c count in Python import binpacking b = { 'a': 10, 'b': 10, 'c':11, 'd':1, 'e': 2,'f':7 } bins = binpacking.to_constant_bin_number(b,4) print("===== dict\n",b,"\n",bins) b = list(b.values()) bins = binpacking.to_constant_volume(b,11) print("===== list\n",b,"\n",bins) Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/binpacking/1.4.2/
CC-MAIN-2021-31
refinedweb
622
59.03
Python library for parsing the most common Steam file formats. Project description Python library for parsing the most common Steam file formats. The library has a familiar JSON-like interface: load() / loads() for loading the data, and dump() / dumps() for saving the data back to the file. Format support Quickstart steamfiles requires Python 3.3+ Install the latest stable version: pip install steamfiles Import a module for your desired format: # Use one of these, or all at once! from steamfiles import acf from steamfiles import appinfo from steamfiles import manifest Easily load data, modify it and dump back: with open('appinfo.vdf', 'rb') as f: data = appinfo.load(f) # Calculate the total size of all apps. total_size = sum(app['size'] for app in data.values()) print(total_size) # Downgrade a change number for all apps. for app in data.values(): app['change_number'] -= 1 with open('new_appinfo.vdf', 'wb') as f: appinfo.dump(data, f) Caution: all formats are parsed into dict by default, so the order of data is very likely not the same. As I’m not sure how Steam and related tools deal with rearranged data, pass an OrderedDict class to the wrapper parameter if you plan to write data back and use it later: from collection import OrderedDict data = acf.load(f, wrapper=OrderedDict) # works with other formats as well Documentation More in progress… TODO - [✓] ACF support - [✓] appinfo.vdf support (Binary VDF) - [✓] Manifest support - [?] packageinfo.vdf (Another binary VDF) - [?] UserGameStats (achievements) - [?] Text VDF files (are they actually ACF?) 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/steamfiles/
CC-MAIN-2018-26
refinedweb
277
59.19
Introduction Node.js by building a simple Express API. The Features of H2. Size and Performance and Encryption. Other Useful Features. Description of the API and General Diagram two files. The first one will have the Express app that will answer all REST API requests. All endpoints we described in the definition above will be added to this file. The second file will have the persistence, functions to access the database to execute the CRUD operations, using the JDBC package. Database Schema To store the Exoplanet resource to an H2 database we should write the basic CRUD functions first. Let's start with the creation of the database. We use the JDBC package to access databases through JDBC: var JDBC = require('jdbc'); var jinst = require('jdbc/lib/jinst'); if (!jinst.isJvmCreated()) { jinst.addOption("-Xrs"); jinst.setupClasspath(['../h2-1.4.200.jar']); } var h2 = new JDBC({ url: 'jdbc:h2:tcp://localhost:5234/exoplanets;database_to_lower=true', drivername: 'org.h2.Driver', properties: { user : 'SA', password: '' } }); var h2Init = false; function getH2(callback) { if (!h2Init) h2.initialize((err) => { h2Init = true; callback(err) }); return callback(null); }; function queryDB(sql, callback) { h2.reserve((err, connobj) => { connobj.conn.createStatement((err, statement) => { if(callback) { statement.executeQuery(sql, (err, result) => h2.release(connobj, (err) => callback(result))); } else { statement.executeUpdate(sql, (err) => h2.release(connobj, (err) => { if(err) console.log(err) })); } }); }); }; module.exports = { initialize: function(callback) { getH2((err) => { queryDB("CREATE TABLE IF NOT EXISTS exoplanets (" + " id INT PRIMARY KEY AUTO_INCREMENT," + " name VARCHAR NOT NULL," + " year_discovered SIGNED," + " light_years FLOAT," + " mass FLOAT," + " link VARCHAR)" ); }); }, The initialize() function is simple enough because of the helper functions written beforehand. It creates the exoplanets table if it doesn't exist already. This function should be executed before our API starts receiving requests. We'll see later where to do that with Express. The h2 object gets configured with the connection string and credentials to access the database server. It is simpler for this example, but there is room for improvement regarding security. We could save our credentials elsewhere, like environment variables for example. Also, we needed to add the path to the H2 jar file on the method jinst.setupClasspath(). This is because the JDBC package needs a driver to connect to H2, org.h2.Driver. The JDBC connection string ends in /exoplanets;database_to_lower=true. This means that when connecting for the first time a database called exoplanets will be created. Also, the table and column names will be saved in lowercase. This will simplify the API so no conversion of property names will be needed. The queryDB() function uses the JDBC library methods to access the database. First, it needs to reserve() a connection to the database. The next steps are to createStatement() and then executeQuery() if a result is expected, or executeUpdate() otherwise. The connection is always released. All functions above may return an error. To simplify this example all errors are left unchecked, but on a real project we should check them. The getH2() function returns an object that represents the database. It will create that object only once, using the same mechanism Singleton classes use to return only one instance always. Let's now validate user data and allow them to perform CRUD operations. CRUD Database Functions Let's make the required functions to allow this app to perform CRUD operations on exoplanets. We'll add them to module.exports so that we can reference them from other files easily and create a persistence.js helper module that we can use: module.exports = { getAll: function(callback) { getH2((err) => queryDB("SELECT * FROM exoplanets", (result) => { result.toObjArray((err, results) => callback(results)) })); }, get: function(id, callback) { getH2((err) => queryDB(`SELECT * FROM exoplanets WHERE id = ${id}`, (result) => { result.toObjArray((err, results) => { return (results.length > 0) ? callback(results[0]) : callback(null); }) })); }, create: function(exoplanet) { getH2((err) => { columns = Object.keys(exoplanet).join(); Object.keys(exoplanet).forEach((key) => exoplanet[key] = `'${exoplanet[key]}'`); values = Object.values(exoplanet).join(); queryDB(`INSERT INTO exoplanets (${columns}) VALUES(${values})`); }); }, update: function(id, exoplanet) { getH2((err) => { keyValues = [] Object.keys(exoplanet).forEach((key) => keyValues.push(`${key} = '${exoplanet[key]}'`)); queryDB(`UPDATE exoplanets SET ${keyValues.join()} WHERE id = ${id}`); }); }, delete: function(id) { getH2((err) => queryDB(`DELETE FROM exoplanets WHERE id = ${id}`)); }, }; Both get() and getAll() functions query the database to return one or more exoplanets. The API will return them directly to the API client. All functions are mainly SQL queries, but create() and update() deserve more explanation. The INSERT SQL statement can receive column and values separated, in the form INSERT INTO table (column1Name) VALUES ('column1Value'). We can use the join() method to generate one string of columns separated by commas, and do something similar to join all values we want in the create() function. The UPDATE SQL statement is a bit more complex. Its form is UPDATE table SET column1Name = 'column1Value'. So we need to create a new array in the update() function to store the values in this format and join() them later. Let's save all database functions on its own file, persistence.js, so we can add some context when we call the functions in the API file, like this: const persistence = require('./persistence'); persistence.getAll(); Joi Schema As a rule of thumb, we should always validate what a user sends before using it, for example when the user attempts to create a resource. Some packages make this task easy. We'll use Joi to accomplish validation. First, we need to define a schema of our resource, a definition of properties and their types. It reminds us of the SQL CREATE statement we defined before: const Joi = require('joi'); const exoplanetSchema = Joi.object({ id: Joi.number(), name: Joi.string().required(), year_discovered: Joi.number(), light_years: Joi.number(), mass: Joi.number(), link: Joi.string().uri() }) options({ stripUnknown: true }); Each type will enforce some validation. For example, the link property needs to look like a URI, and the name is required(). Later we can validate a resource by using the exoplanetSchema.validate(theObject) method. This method will return an object with an error property with validation errors if there were any, and a value property with the processed object. We will use this validation when creating and updating an object. To add robustness to our API, it would be nice to ignore and discard any extra property not included in our schema. This is achieved in the definition above by setting the stripUnknown option to true. REST API with Express We'll use the Express package to create our REST API. And as we've just seen, we'll also use Joi to validate resources. Let's set up a regular Express server: const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json()); The app variable is our API, empty for now. Express allows extending its functionality through the use of middleware, functions that can modify the requests and responses of our API. In this case, we are using two middlewares. First, cors() will allow other browser applications to call our API. This includes the Swagger Editor we may use to test our API later. If you'd like to read more about Handling CORS with Node.js and Express, we've got you covered. Second, we add the express.json() middleware to enable parsing of JSON objects in the body of requests. Let's now add a few endpoints to the API. We'll start with put(), as they use the Joi validation explained in the last section: app.post('/exoplanets', (req, res) => { delete req.body.id; const { error, value } = exoplanetSchema.validate(req.body); if(error) res.status(405).send(error.details[0].message); persistence.create(value); res.status(201); }); app.put('/exoplanets/:id', (req, res) => { delete req.body.id; const { error, value } = exoplanetSchema.validate(req.body); if(error) { res.status(405).send(error.details[0].message); } persistence.get(req.params.id, (result) => { if(result) { persistence.update(req.params.id, value); res.status(201); } else { res.status(404); } }); }); Express supports one function per HTTP verb, so in this case, so we have put() as two functions. In both functions, the resource is validated first, and any error is returned to the API client. To keep this code simple, only the first validation error is returned in that case. put() also checks if the resource exists by attempting to get it from the database. It will update the resource only if it exists. With the put() functions that require validation out of the way, let's handle the get() methods when users would like to take a look at the exoplanets, as well as the delete() function used to remove an exoplanet from the database: app.get('/exoplanets', (req, res) => persistence.getAll((result) => res.send(result))); app.get('/exoplanets/:id', (req, res) => { persistence.get(req.params.id, (result) => { if(result) res.send(result); else res.status(404); }); }); app.delete('/exoplanets/:id', (req, res) => { persistence.get(req.params.id, (result) => { if(result) { persistence.delete(req.params.id); res; } else { res.status(404); } }); }); Having defined all endpoints, let's set up the port on which the application will listen for requests on: app.listen(5000, () => { persistence.initialize(); console.log("Exoplanets API listening at") }); The callback above will be called only once when starting the server, so it's the perfect place to initialize() the database. Conclusion H2 is a useful database server, performant and easy to use. Although it's a Java package, it also runs as a standalone server, so we can use it in Node.js with the JDBC package. In this tutorial, we defined first a simple CRUD to illustrate how to access the database, and which functions are available. After that, we defined a REST API with Express. This helped us to have a more complete idea on how to receive resources and save them to H2. Although several concepts were omitted for the sake of brevity, like authentication and paging, this tutorial is a good reference to start using H2 in our Express projects.
https://stackabuse.com/integrating-h2-with-node-express/
CC-MAIN-2021-10
refinedweb
1,659
51.55
I am fairly new to Circuit python. I am trying to make an IMU logger which would log IMU data (accelerations and rotation rates) onto a Micro SD card at 1 Khz. Board - Adafruit stm32f405 Feather IMU - MPU6050 Card - Strontium 16gb class 10 Micro SD card The issue i am facing is that the board logs for a few lines onto the SD card but after the first few lines the code crashes. My code is pasted below. Kindly help out with letting me know what i am doing wrong? If possible, please guide me to the right resources for getting it right. Code: Select all import board import digitalio import sdioio import storage import time import board import adafruit_mpu6050 led = digitalio.DigitalInOut(board.LED) led.direction = digitalio.Direction.OUTPUT i2c = board.I2C() # uses board.SCL and board.SDA mpu = adafruit_mpu6050.MPU6050(i2c) sdcard = sdioio.SDCard( clock=board.SDIO_CLOCK, command=board.SDIO_COMMAND, data=board.SDIO_DATA, frequency=25000000) vfs = storage.VfsFat(sdcard) storage.mount(vfs, "/sd") with open("/sd/test.txt", "w") as f: f.write("Printing values :\n" ) a = 0 while True: a += 1 with open("/sd/test.txt", "a") as f: led.value = True acc = mpu.acceleration gyr = mpu.gyro f.write( str(a) + " = " + str(acc)+ " " + str(gyr)+ "\n") led.value = False time.sleep (0.001)
https://forums.adafruit.com/viewtopic.php?f=60&p=936559&sid=dcd8f9bac4da15f1a3c4ed5e103f5af2
CC-MAIN-2022-40
refinedweb
217
62.95
I know that a question very similar has been asked before, "using namespace" in c++ headers, but mine is when its inside of a namespace. namespace foo { using namespace std; // what does this do? class Bar { ... } } Does this do exactly the same thing as the other question says and just include that using statement everywhere? Does it only do it in that namespace? Does it only do it in that header? There are two differences: usingwill only apply to code inside the foonamespace. But that means all foocode that sees this header, so you probably still don't want to do it. foo::stdexists, the nested usingstatement will favor it over ::std.
http://m.dlxedu.com/m/askdetail/3/0297ae9914051158745bb3656c0d90a1.html
CC-MAIN-2018-22
refinedweb
112
74.39
Sooner or later when you’re building your mobile application you’ll probably want to fire an event in one component of your application and have that event handled or acted upon in another component. In native iOS development you would probably handle this scenario either using the NSNotification class or the Delegate pattern. The former is loosely coupled and allows multiple listeners, the latter is more tightly coupled and allows just a single listener (I think). In Android development you can use Listeners or perhaps use an event bus architecture such as EventBus or Oto. In an Ionic 2 application we have an Events system which allows you to subscribe to events in one component that have been published in another component. Like the NSNotifcation class in iOS this is a loosely coupled architecture and allows multiple listeners i.e component 1 can publish an event and components 2 and 3 can subscribe to it. It’s incredibly simple to use. In both the publishing and subscribing events you need to inject the Event class i.e : import {Events} from ‘ionic-angular‘; In the component you wish to fire the event from simply publish it like this: this.events.publish(‘myEvent‘); and in the component you want to act on the event you subscribe to it i.e: this.events.subscribe(‘myEvent’,() => { // do something }); The event can also take an object as a parameter e.g let myParam = { name: “Bruce”, age: 100 } this.events.publish(‘myEvent‘,myParam); To handle this in the subscriber you would do something like: this.events.subscribe(‘myEvent’,(object) => { // do something with object }); To read more about Events in Ionic 2 see the documentation here and also have a look at the excellent Conference app that the Ionic team have created and are constantly updating as they add new features to the framework. In the Conference app, app.js subscribes to the login event fired by the UserData component.. This works very well and is really a nice feature but only in very simple and specific cases. I’ve found that using this across components (which I believe is the intent) within lifecycle hooks to be close to impossible (I only say “close” because I believe I may be overlooking something obvious, otherwise it is currently impossible.) Would you happen to have an example of unsubscribing from an event within a lifecycle hook such as ‘onPageWillLeave’? Hi. I don’t think I have tried that. Perhaps I’ll give it a go and see if I have the same issues you do. Thanks for reading. Using unsubscribe(topic, handler) you can unsubscribe from the given topic in your lifecycle hook. Your handler will no longer receive events published to this topic. Hi, Interesting read. Would like to know how to handle multiple events that can occur simultaneously. E.g say there is notification event that may come when the app is not on. And there is a login event that may be triggered as soon as the app is opened. Thus clicking on a notification will trigger both the events Thanks in advance Dhaval Shah What is the Ionic life cycle life cycle method of a component to unsubscribe the event. ?
https://ionicallyspeaking.com/2016/03/05/publishing-and-subscribing-to-events-in-ionic-2/
CC-MAIN-2018-51
refinedweb
536
62.78
WebSockets as a communication technology wins increasing importance. In the SAMPLES namespace, you find a nice example for running a WebSocket Server. There is also a useful example for a Browser Client. JavaScript does most of the work. in almost every browser. e. g JavaScript has excellent and verified libraries to support what you need. And there is the engine to run it without a browser: Node.js And Caché, IRIS, Ensemble have meanwhile a well-established interface module ready. So I took a closer look after managing to get the correct versions together. Once the WsockDemo.js was assembled and tested you launch it over CPIPE or $ZF(....) You provide control information from the server and get back the result to the server. If you are used to JavaScript there are no big surprises. The major difference to accept and understand is that yo operate in an almost total asynchronous environment and callback methods and their interaction are probably the most important difference to traditional programming. I have placed the example on Open Exchange with more docs as an invitation to break out (for most developers) of your traditional environment and find something new and useful. I have to admit that this was my first exercise into Node.js and I'm far from taking the best and most advanced solution. But the result in relation to the effort was convincing.
https://community.intersystems.com/post/client-websockets-based-nodejs
CC-MAIN-2019-18
refinedweb
232
58.69
User talk:Ixo From OLPC Please feel welcome to leave comments here. Feedback is always welcomed and appreicated. Some of my notes left on other pages: - My own random notes edited from XO laptop. - Target_Audience - centralizing ideas about target audiences. - Hardware Ideas -> Ergo Survey, Evaluation, and review - Browse: Browser Identification String -> needs update ! - sugar-control-panel --> Activity GUI ideas ? - Calculate --> Gallery of Examples - Region Volunteer --> Bellingham, Whatcom County, Washington State. We could use some help welcoming new users here :-) Also, with userboxen. Sj talk 17:49, 29. Calculate Activity I don't have any examples. When I first got my G1G1 I tested the Boolean functions (see my notes on the Calculate talk page). I tried to use the calculator and was confused because I couldn't find any documentation of what it actually does (especially the window on the right). I am quite pleased to find that it does plot! There are also questions as to whether this activity can work with the Pippy activity, somehow. The people who can best help here are, unfortunately, those who don't have laptops -- the teachers in the schools. I know my kids did a lot of work with plotting when they were in high school. Simple X-Y plotting probably happens in 5-6th grade here in the US (I'm in New England, down the street from Dartmouth College). Right now I'm working on the Measure/Oscilloscope activity, trying to prevent people from electrocuting themselves. If I come up with anything I'll let you know. (I've posted some things on the wikipedia website about division by zero -- see the talk page there near the bottom). That seems to be a topic that gets people going. Bill Wvbailey 12:18, 31 December 2007 (EST) - Thanks for the feedback. I just recently tried the 'Distance' Activity with another person on a jabber server I was visiting. For some reason, the measurement didn't work over very long distances. *heh Heh*. I'll look for some good examples of division by zero for ya too. :) --ixo 12:16, 1 January 2008 (EST) reset / restore factory (build 650) image defaults - FYI, there is a method of restoring to factory defaults. (build 650). --ixo 06:33, 6 January 2008 (EST) wiki cleanup Status page updated at Wiki cleanup - we should do a marathon some weekend. Mchua 00:21, 23 January 2008 (EST) - Yes. Definitely, I´m in Costa Rica currently, be back about Feb 4th. Which weekend would be best for you? --ixo (Jan 29th 2008) rename Hello Ixo, I've renamed your account here, which carries all of your subpages with it. --Sj talk 09:19, 4 February 2008 (EST) - Perfect. Thanks! --ixo 11:25, 4 February 2008 (EST) nice work... On the cleanup and the new News. I'd still like to see relevant daily notes, as well -- there are so many small things going on. I'll point you to a draft if I work one up tonight. --Sj talk 18:55, 5 February 2008 (EST) in reply to OOppsss... 'Zine .. MoS No worries. Thanks, I just am an avid wikipedian and pour over the Help: pages on the MediaWiki page. Be glad you arn't as addicted to wiki as I am that you have time to memorize the wikisyntax. Just to make sure, are you DDM, or the other ia{"i",""}n? ffm 20:00, 5 February 2008 (EST) weekly zine : OLPC Europe section Chris Hager, of OLPC Austria, has been working on articles about OLPC Europe -- how about adding an OLPC Europe correspondent for the 'zine? --Sj talk 16:15, 7 February 2008 (EST) I see your Monty Python sketch and raise you a possible draft of an article: Talk:Weekly zine/0/i18n Adricnet 02:23, 9 February 2008 (EST) Draft up See what you think of the link list / notes and your stuff that I commented out? This works better over IRC, heh. Adricnet 03:03, 9 February 2008 (EST) Whoa, go Bellingham! The grassroots group page looks AMAZING. there's also Regional community groups which we need to find some way to integrate with Grassroots (and I also need to figure out how to do the same with University chapters). It's not super-sustainable for all groups to list themselves in all categories... maybe make some "tags" (categories) for groups that we can put on the grassroots page and template, for easy sorting? plus some kind of map thing, "where are grassroots groups?" Mchua 04:45, 10 February 2008 (EST) Vid Yes, that was Kent Quirk. At least one of their sons (Lincoln) can be seen in the same clip (next to Kent in the back of the classroom, working). I usually look less sleep deprived and talk much more quickly; I'd slowed down considerably there because my high speech rate combined with my tech vocab and deaf accent usually renders me unintelligible to people, and I'd never been on camera before. So... uh... yes. Mchua 14:51, 10 February 2008 (EST) Linux Commands (Category:Linux_Programs) No problem :) --Chief Mike 07:42, 21 February 2008 (EST) - I was thinking of a subcategory under Linux Programs if you're planning to add any more. OLPC Logos Your request is timely. Within the next week, several variations on the official XO logo will be made public for non-official use. You should find them on either the Logos or Badges pages of the wiki. - Eben G1G1 / Peru activities? Try not to get hot under the collar... what's going on? --Sj talk 11:54, 24 March 2008 (EDT) mop and bucket Dear Ixo, You are now an admin... after a delay! Please use your new tools wisely and conservatively, and make use of the OLPC: namespace where appropriate. Cheers, --Sj talk 16:00, 24 April 2008 (EDT) design gang proposal I've posted a proposal for image upload file structure and categorization. OLPC:Design_gang/proposed_file_structure AuntiMame 14:45, 14 September 2008 (UTC)
http://wiki.laptop.org/go/User_talk:Ixo
CC-MAIN-2017-04
refinedweb
1,000
73.68
Python 2.6 introduced the str.format() method for formatting strings which provides a much more flexible alternative to the older modulo (%) based string formatting. But which one performs better? Let's test it out by repeating a simple string format a million times with each method and timing the execution. [1] str.format vs. (%) modulo from timeit import timeit def test_modulo(): 'Don\'t %s, I\'m the %s.' % ('worry', 'Doctor') def test_format(): 'Don\'t {0}, I\'m the {1}.'.format('worry', 'Doctor') timeit(stmt=test_modulo, number=1000000) # 0.31221508979797363 timeit(stmt=test_format, number=1000000) # 0.5489029884338379 Hmmm, the modulo operator is almost twice as fast as str.format() in these simple examples. In cases where you don't require the flexibility of str.format() and simply want sheer perfomance... Modulo has got to be the way to go... But according to PEP-3101, str.format() is intended to replace the modulo operator... Let's hope that doesn't happen anytime soon. Template strings For completeness, Python also supports string templates (introduced in Python 2.4). Let's put that to the test. from string import Template s = Template('Don\'t $what, I\'m the $who.') def test_template(): s.substitute(what='worry', who='Doctor') timeit(stmt=test_template, number=1000000) # 6.010946035385132 Ouch! Update: 5/12/2017: Python 3.6 introduced f-strings which provide a new method of string formatting. Let's see how f-strings perform... from timeit import timeit def test_fstring(): a, b = 'worry', 'Doctor' f'Don\'t {a}, I\'m the {b}.' timeit(stmt=test_fstring, number=1000000) # 0.276932206004858 Well, there we have it... f-strings combine the elegance of .format(), yet is slightly faster than the modulo operator. Big thanks to @StopSpazzing for pointing this out.
https://tomatohater.com/2013/08/30/python-performance-string-formatting/
CC-MAIN-2020-16
refinedweb
290
63.46
Details Description This would allow the very common useful idiom found in Ruby: variable ||= value Currently we have to write code like this in Groovy: def myMap = [:] if (condition) (myMap[someLongNameObject.getKeyId()] = myMap[someLongNameObject.getKeyId()] ?: []) << someNewValue Also, if getKeyId() is costly or shouldn't get called more than once for some reason, we would have to write it like: def myMap = [:] if (condition) { def key = someLongNameObject.getKeyId() (myMap[key] = myMap[key] ?: []) << someNewValue } When it could be simplified as this: if (condition) (myMap[someLongNameObject.getKeyId()] ?:= []) << someNewValue Issue Links - is related to GROOVY-5306 Add "a ?= 2" support: should be expanded to "a = a == null ? 2 : a" Activity The problem is that usually it is not "a = a ?: 2", but "someLongInstanceName.anotherLongInstancePropertyName = someLongInstanceName.anotherLongInstancePropertyName ?: 2". See what I mean? I don't know if this is relevant in this case but def myMap = [:].withDefault {[]} would get rid of that lengthy construct with colon and questionmark: if (condition) myMap[someLongNameObject.getKeyId()] << someNewValue Which is actually shorter and a lot more readable than the funky syntax proposed here. def myMap = [:].withDefault {[]} if (condition) myMap[someLongNameObject.getKeyId()] << someNewValue Yes, this helps for this case, but I miss the "?:=" construction in several other cases as well. Mathias, please take a look at the other example in a prior comment. note that in another thread in the grails forum, we decided to swap "?:=" with "?=" I actually like the idea of a ?= operator. It's less about typing and more about readability. It's the difference between saying "assign 100 to params.max unless params.max is already set" params.max = params.max ?: 100 and "params.max should default to 100" params.max ?= 100 The only argument against that I've heard is that it adds complexity without any gain. I think there is substantial gain. Could you please take a look at this again as it has a different semantic from the other '?=' feature request? I'm concerned about consistency with the "?:" operator. Well... That's a whole new story now I have no idea if Guillaume and others will see the benefit but still. It does make the code more readable... And it's only 2 chars long which doesn't hurt my eyes... I gave this a vote for the form params.max ?= 100 which reads as "should default to". Rodrigo, can you link to the other ?= issue? I don't know if there is some special formatting tag for this, so I'll just paste the link: Cedric, Guillaume and myself find all don't like this approach. While we want to be able to make Groovy programs we don't want it to become too much like Perl. the step from a=a?:2 to a=a?a:2 is small, but from a?:=2 to a=a?:2 I think is too much. Maybe with a different syntax - in another jira entry
http://jira.codehaus.org/browse/GROOVY-5291
crawl-003
refinedweb
480
69.38
Blog about technology, media and other interesting tidbitsAdd Visual XPath: Put $(ItemPath) in the Arguments text box Step 2: Map a shortcut key to this external tool Goto Tools->CustomizePress. Nice work. I had a very simple tool to do XPath queries previously and this is a much better way of doing it. We had some very large financial XML documents and navigating to the link and having the XPath statement there and ready to copy is great. Wouldn't mind if you got rid of the msg boxes popping up tho and placed the 'TODO's in the Help menu option or something. Would be interested in the next versions. [email protected] Well done. I saw Scott Watermasysk's post on your nice utility. If you're interested in seing a different approach to illustrating XPath query results, have a look at my website. I'm highlighting the hits directly in the XML. Thank's for this realy useful tool Nauman! I have spread the word about this application to my coworkers. I agree with Emil. A nice feature to Visual XPath would be if the node matching an expresseion was highlighted Yes, there are two approaches to see the result. The first one is to highlight the matching nodes and the other is what I have taken. I selected the latter approach based on my own requirements because I wanted to see the results only. There seems to be a problem with XML docs that have multiple namespaces. I used an RSS xml file as a test, and Visual XPath included "def:" for the default namespace for each node that was in the default. However, executing the query resuls in no matches. But if I simply remove "def" from the XPath everyhing works fine.
http://weblogs.asp.net/nleghari/archive/2003/12/03/40842.aspx
crawl-002
refinedweb
297
72.97
Opened 10 years ago Last modified 12 months ago #1396 enhancement new callLater(0) does not guarantee relative ordering of calls Description Attachments (2) Change History (33) comment:1 Changed 10 years ago by jknight comment:2 Changed 10 years ago by glyph I disagree. callLater is not callAtExactly - call queueing should be done with other mechanisms, and perhaps triggered by callLater. As I mentioned previously, we don't deal with the user setting the system clock so at worst calling this a "guarantee" is incorrect. Also, even providing the naive version of this guarantee may preclude implementing more a more efficient callLater at some point. comment:3 Changed 10 years ago by glyph See #1398 for more information. comment:4 Changed 10 years ago by jknight Ideally, we should use a timing source that isn't adjustable, but I don't think we have one. callLater is certainly not callAtTime. It is, however, a call queuing function. Ordering should most definitely be deterministic. Having the user set system time should not cause all timeouts to fire immediately. However, that's a separate issue. The only part I'm concerned with is that the clock moving backwards should also not violate ordering. comment:5 Changed 10 years ago by glyph I think that the bug here is that the documentation does not include the title of this issue. Guaranteeing relative ordering of calls is not realistically possible for a timed-call mechanism. Doing it more often is probably good, so I'm not saying that changing the win32er implementation to work around its super-low-precision timer is a bad idea, but saying we provide a guarantee is a ton of work. Consider a system with a lot of clock wobble that syncs the time every hour from NTP; there are LOTS of opportunities for time() to go backwards in time, and it's not clear what the right thing to do is, unless time is always measured from the beginning of the last reactor tick - and that's bad because events often do take non trivial amounts of wall-clock time to process. People who need deterministic ordering should NOT use callLater. That's simply not what it's for. comment:6 Changed 10 years ago by exarkun clock_gettime(CLOCK_MONOTONIC) is supposed to be non-adjustable. I don't think we should use it though. I think the current behavior of callLater() is perfectly reasonable. The documentation should be improved, but the code should be left alone for now. comment:7 Changed 10 years ago by jknight Your "consider" example is flawed. That is not how NTP is used. It instead adjusts a slew factor, causing time to go faster or slower than the hardware clock. That's not to say that the clock will never be changed, of course. Guaranteeing relative ordering *is* realistically possible, unless you see a reason why the code on my branch should not work. comment:8 Changed 10 years ago by exarkun It's relatively common to have NTP used incorrectly, where ntpdate is run once an hour or once a day, causing the system clock to jump. comment:9 Changed 10 years ago by glyph That's why I said "a lot of clock wobble". From the NTP documentation: ." The code on your branch doesn't work because in order to achieve a relatively subtle change in semantics for callLater(N,...) callLater(N,...) which is of dubious utility (the issue that spawned this discussion has since been resolved by other means, and I think, to warner's satisfaction) you want to change the semantics of Platform.seconds() to mean something almost completely different than what it currently does. Currently, if a Twisted process is started and then the clock is changed, callLater calls started before the time is adjusted might be delayed for an unreasonable amount of time, or run sooner than they expected to be. With your proposed change, if a Twisted process is started and the clock is changed, some of those behaviors will likely be fixed (although I note that in the absence of an external point of reference, your fix is only heuristically correct), but application code has no opportunity to make the time correct on its own, since platform.seconds now be reporting a random value. (In other words, "you have no chance to survive, or make your time (correct)." Hee hee.) The application code might be calling time.time() itself in this case, but why should it? Twisted's Platform.seconds is advertised as more portable, and is (was) supposed to return a semantically equivalent value. Perhaps the right thing to do here is to apply the time-going-backwards detection from this patch and simply to provide a hook for the reactor to alert application code that it may have gone backwards in time? Being set forwards is something that application code can detect on its own, if it cares about real-time scheduling. comment:10 Changed 10 years ago by glyph Ugh. Please forget I used the word "real-time" there. I mean "accurate wall-clock". comment:11 Changed 10 years ago by jknight Yes, ntpdate does that, but that generally runs once at system boot time. The ntp daemon does not do that. I've never seen a system that installs a cron job with ntpdate rather than ntp, but maybe I've not looked hard enough. Okay, so instead, I'd like to introduce platform.realSeconds(), which returns a value which may or may not have anything to do with the epoch, and which is guaranteed monotonic and strictly increasing. The reactor timers should use this. It should ideally use clock_gettime if available, otherwise use the heuristics on top of gettimeofday. callLater *should not* be affected by real time changes, if it's possible to avoid, as it has nothing to do with real time, but rather elapsed time intervals. That it may be affected by real time is an implementation deficiency, not a feature. And finally: before I broke it, callLater *did* guarantee ordering. There's really no reason to think it should not behave the way warner expected it to, and if both that and the misbehavior upon time-setting can be fixed with one change, all the better. comment:12 Changed 10 years ago by glyph > I'd like to introduce platform.realSeconds() Hmm. OK, that doesn't sound like a bad plan. Naming's important though, and I'd like to be careful to avoid putting "real" anywhere near the word "time", especially since it's got a heuristic that makes it not-real in many cases. Can we call it "monotonicSeconds" or something? (Perhaps we should also rename the other one 'secondsFromEpoch' and deprecate just 'seconds', to stress the distinction.) Re-jigger your branch and I'll re-review? That reminds me; if we're going to use clock_gettime and add our own time interface, we might want to add a primitive interface to the reactor that uses integer milliseconds. I still occasionally get grief from DirectX developers that they have to force the FPU back into double precision mode so that Twisted will work :) comment:13 Changed 10 years ago by exarkun <> Regarding milliseconds, clock_gettime returns a timespec, which consists of a time_t representing seconds and a long representing nanoseconds. Resolution is variable, but queryable. On my system (x86, P4, Linux 2.6.12) it is 0.999848 milliseconds. comment:14 Changed 10 years ago by jknight Branch seems good, please review. I changed the reactor-internal APIs to use integer nanoseconds rather than floats, as well. One somewhat suspect bit of API is DelayedCall.getTime(), which cannot return a truly accurate trigger time, since DelayedCalls are defined in terms of an increment of time, rather than an absolute time. Of additional note is that I changed distutils.build_extension to allow failures to build C modules, and not abort the build process. comment:15 Changed 10 years ago by jknight Oh, I guess I should mention: svn diff -r15485:HEAD svn://svn.twistedmatrix.com/svn/Twisted/branches/ callLater-1396 comment:16 Changed 10 years ago by exarkun A few trivial points to start off (this does not represent a comprehensive review): twisted/python/runtime.py: _posix_clock is being imported by a relative name. It should be imported as "twisted.python._posix_clock" instead. staticmethod() was being used on Platform to prevent the creation of bound methods. While time.time is a builtin function, and builtin functions aren't descriptors, I am pretty sure these are both implementation details. It'd be nice to at least preserve the level of safety that was in this code before. 1000000000 and 10000000 could stand to be lifted out and replaced with symbolic constants. Was 0.01s selected for any particular reason (ie, does some common operation result in adjustments by increments slightly smaller or greater than that), or does it just work well in practice? twisted/internet/{base,task}.py, twisted/test/{test_task,test_internet}.py: Again, 10 ** 9 and should be a symbolic constant, preferably one imported from someplace else. twisted/python/_posix_clock.c: We don't have a coding standard for C written down anyplace, but if we did I imagine it would say things about trailing whitespace and tabs. ;) Also, I would hope it would also recommend {} around all blocks, even where they are not necessary. Branch mostly looks good, but I doubt my head has fully absorbed the various implications yet, particularly wrt DelayedCall. comment:17 Changed 10 years ago by jknight As I understand it, best practice is for C modules to be imported with a relative name, so that they can be moved to the toplevel when building a zip or what have you without any code changes. 1000000000 could be replaced with a variable like "TENTOTHENINTH" or "NANOSECONDSPERSECOND" but that's pretty much just what it means..the interface is defined to return nanoseconds, not 'symbolic-constant's-per-second. 0.01s is a value I just made up. The constraints are that it must be larger than the most number of times you can call monotonicTicks without the system clock increasing, and must be smaller than you "care" to lose if the clock moves backwards. comment:18 Changed 9 years ago by zooko - Cc zooko added So what needs to be done to make this branch ready to be reviewed to be merged into trunk? comment:19 Changed 9 years ago by exarkun Merged this forward to callLater-1396-2 and resolved the copious conflicts (most of which made little sense, someone should write a better merge algorithm). _posix_clock.c also no longer compiles for me :/ _XOPEN_REALTIME doesn't seem to be defined. The man page suggests _POSIX_TIMERS and _POSIX_MONOTONIC_CLOCK might be more appropriate to check for, but I haven't dug very deeply and I'm sure there are plenty of subtle differences between these (doing a probe is probably a better idea though). comment:20 Changed 9 years ago by jknight I think unistd.h might need to be included first. If not, can you do a: getconf _XOPEN_REALTIME in a shell? And if that returns 1, grep all your header files for _XOPEN_REALTIME being defined? comment:21 Changed 9 years ago by exarkun getconf returns 1, _XOPEN_REALTIME is defined as 1 in posix_opt.h, which is included by unistd.h. comment:22 Changed 8 years ago by therve - Owner changed from jknight to therve comment:23 Changed 8 years ago by therve - Branch set to branches/callLater-1396-3 comment:24 Changed 8 years ago by zooko Here's a version of this patch against current trunk. Changed 8 years ago by zooko comment:25 Changed 8 years ago by zooko Ah, and here is a version that actually builds on my Mac OS X system. Changed 8 years ago by zooko comment:26 follow-up: ↓ 27 Changed 8 years ago by zooko: comment:27 in reply to: ↑ 26 Changed 8 years ago by glyph: This sets off alarm bells for me. Why would this patch stop timing out his jobs? This doesn't sound like "hooray we fixed a bug", it sounds like "oh no, we made certain timed events stop firing when they should". comment:28 Changed 8 years ago by zooko The jobs were timing out after only a few seconds, because the gettimeofday() had jumped more than 1200 seconds. That's my theory anyway. Make sense? I think this might be hooray we fixed the bug. By the way, along the way I found some discussions on the libevent mailing list about situations which called for CLOCK_MONOTONIC: comment:29 Changed 8 years ago by zooko Oh, my informant informs me that the 1200-second timeouts are still going off spuriously (long before 1200 actual seconds have passed). He is checking to see whether the build of Twisted actually built the posix_clock module... comment:30 Changed 5 years ago by <automation> - Owner therve deleted comment:31 Changed 12 months ago by adiroiban As as #7776 I am cleaning the code of todo tests looks like there is not much progress on this for reference, here is the removed text def testCallLaterOrder(self): l = [] l2 = [] def f(x): l.append(x) def f2(x): l2.append(x) def done(): self.assertEqual(l, range(20)) def done2(): self.assertEqual(l2, range(10)) for n in range(10): reactor.callLater(0, f, n) for n in range(10): reactor.callLater(0, f, n+10) reactor.callLater(0.1, f2, n) reactor.callLater(0, done) reactor.callLater(0.1, done2) d = Deferred() reactor.callLater(0.2, d.callback, None) return d testCallLaterOrder.todo = "See bug 1396" testCallLaterOrder.skip = "Trial bug, todo doesn't work! See bug 1397" def testCallLaterOrder2(self): # This time destroy the clock resolution so that it fails reliably # even on systems that don't have a crappy clock resolution. def seconds(): return int(time.time()) base_original = base.seconds runtime_original = runtime.seconds base.seconds = seconds runtime.seconds = seconds def cleanup(x): runtime.seconds = runtime_original base.seconds = base_original return x return maybeDeferred(self.testCallLaterOrder).addBoth(cleanup) testCallLaterOrder2.todo = "See bug 1396" testCallLaterOrder2.skip = "Trial bug, todo doesn't work! See bug 1397"
http://twistedmatrix.com/trac/ticket/1396
CC-MAIN-2016-07
refinedweb
2,372
63.59
Since we're linking to /categories/:slug from our list of categories inside CategoryList component, we need to create pages for each of them at build time. This is where we will hook into a special Gatsby API at build time to do this. Let's first create the template for our category page. Inside the src directory, create a new folder templates. Here create a file CategoryPage.js and add the following: import React from 'react'; import { graphql } from 'gatsby'; import ProductList from '../components/ProductList'; export default function CategoryPage({ data: { category } }) { const { products } = category; return ( <React.Fragment> <h1>{category.name}</h1> <ProductList products={products} /> </React.Fragment> ); } You'll notice we're not exporting a pageQuery, yet. Let's now export a pageQuery, but this time it will look a little different. Since this is a "template", it should be used when visiting /categories/:slug. With Gatsby, we must pass some "context" to the template when building it. This context is available to the GraphQL query as variables, so we can use write a query that uses that variable to fetch the page. In this case we will use the id of each category nodes to fetch from the Gatsby built Chec nodes. export const pageQuery = graphql` query CategoryPageQuery($id: String!) { category: checCategory(id: { eq: $id }) { id name products { name permalink ...PriceInfo } } } `; As it stands, this file does nothing itself. So let's put it to action! Inside the root of your project, create the file gatsby-node.js. We need to hook into the createPages Gatsby API. Update gatsby-node.js to include the following: exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions; const { data: { allChecCategory }, } = await graphql(` { allChecCategory { nodes { id slug } } } `); allChecCategory.nodes.forEach(({ id, slug }) => createPage({ path: `/categories/${slug}`, component: require.resolve(`./src/templates/CategoryPage.js`), context: { id, }, }) ); }; Inside the createPages function we're running a GraphQL query to get all of our categories, and for each of those, using the createPage action, and providing it the required path, component, and context. Discussion (0)
https://dev.to/notrab/create-individual-category-pages-2f7g
CC-MAIN-2021-21
refinedweb
337
50.12
Introducing Pandas Objects At the very basic level, Pandas objects can be thought of as enhanced versions of NumPy structured arrays in which the rows and columns are identified with labels rather than simple integer indices. As we will see during the course of this chapter, Pandas provides a host of useful tools, methods, and functionality on top of the basic data structures, but nearly everything that follows will require an understanding of what these structures are. Thus, before we go any further, let's introduce these three fundamental Pandas data structures: the Series, DataFrame, and Index. We will start our code sessions with the standard NumPy and Pandas imports: import numpy as np import pandas as pd data = pd.Series([0.25, 0.5, 0.75, 1.0]) data 0 0.25 1 0.50 2 0.75 3 1.00 dtype: float64 As we see in the output, the Series wraps both a sequence of values and a sequence of indices, which we can access with the values and index attributes. The values are simply a familiar NumPy array: data.values array([ 0.25, 0.5 , 0.75, 1. ]) The index is an array-like object of type pd.Index, which we'll discuss in more detail momentarily. data.index RangeIndex(start=0, stop=4, step=1) Like with a NumPy array, data can be accessed by the associated index via the familiar Python square-bracket notation: data[1] 0.5 data[1:3] 1 0.50 2 0.75 dtype: float64 As we will see, though, the Pandas Series is much more general and flexible than the one-dimensional NumPy array that it emulates. a 0.25 b 0.50 c 0.75 d 1.00 dtype: float64 And the item access works as expected: data['b'] 0.5 We can even use non-contiguous or non-sequential indices: data = pd.Series([0.25, 0.5, 0.75, 1.0], index=[2, 5, 3, 7]) data 2 0.25 5 0.50 3 0.75 7 1.00 dtype: float64 data[5] 0.5 Series as specialized dictionary¶ In this way, you can think of a Pandas Series a bit like a specialization of a Python dictionary. A dictionary is a structure that maps arbitrary keys to a set of arbitrary values, and a Series is a structure-dictionary California 38332521 Florida 19552860 Illinois 12882135 New York 19651127 Texas 26448193 dtype: int64 By default, a Series will be created where the index is drawn from the sorted keys. From here, typical dictionary-style item access can be performed: population['California'] 38332521 Unlike a dictionary, though, the Series also supports array-style operations such as slicing: population['California':'Illinois'] California 38332521 Florida 19552860 Illinois 12882135 dtype: int64 Constructing Series objects¶]) 0 2 1 4 2 6 dtype: int64 data can be a scalar, which is repeated to fill the specified index: pd.Series(5, index=[100, 200, 300]) 100 5 200 5 300 5 dtype: int64 data can be a dictionary, in which index defaults to the sorted dictionary keys: pd.Series({2:'a', 1:'b', 3:'c'}) 1 b 2 a 3 c dtype: object In each case, the index can be explicitly set if a different result is preferred: pd.Series({2:'a', 1:'b', 3:'c'}, index=[3, 2]) 3 c 2 a dtype: object Notice that in this case, the Series is populated only with the explicitly identified keys.. DataFrame as a generalized NumPy array¶ discussed in the previous section: area_dict = {'California': 423967, 'Texas': 695662, 'New York': 141297, 'Florida': 170312, 'Illinois': 149995} area = pd.Series(area_dict) area California 423967 Florida 170312 Illinois 149995 New York 141297 Texas 695662 dtype: int64 Now that we have this along with the population Series from before, we can use a dictionary to construct a single two-dimensional object containing this information: states = pd.DataFrame({'population': population, 'area': area}) states Like the Series object, the DataFrame has an index attribute that gives access to the index labels: states.index Index(['California', 'Florida', 'Illinois', 'New York', 'Texas'], dtype='object') Additionally, the DataFrame has a columns attribute, which is an Index object holding the column labels: states.columns Index(['area', 'population'], dtype='object') Thus the DataFrame can be thought of as a generalization of a two-dimensional NumPy array, where both the rows and columns have a generalized index for accessing the data. DataFrame as specialized dictionary¶ Similarly, we can also think of a DataFrame as a specialization of a dictionary. Where a dictionary maps a key to a value, a DataFrame maps a column name to a Series of column data. For example, asking for the 'area' attribute returns the Series object containing the areas we saw earlier: states['area'] California 423967 Florida 170312 Illinois 149995 New York 141297 Texas 695662 Name: area, dtype: int64 Data Indexing and Selection. pd.DataFrame(population, columns=['population'])}]) pd.DataFrame({'population': population, 'area': area}) pd.DataFrame(np.random.rand(3, 2), columns=['foo', 'bar'], index=['a', 'b', 'c']) From a NumPy structured array¶ We covered structured arrays in Structured Data: NumPy's Structured Arrays. A Pandas DataFrame operates much like a structured array, and can be created directly from one: A = np.zeros(3, dtype=[('A', 'i8'), ('B', 'f8')]) A array([(0, 0.0), (0, 0.0), (0, 0.0)], dtype=[('A', '<i8'), ('B', '<f8')]) pd.DataFrame(A) The Pandas Index Object¶ We have seen here that both the Series and DataFrame objects contain an explicit index that lets you reference and modify data. This Index object is an interesting structure in itself, and it can be thought of either as an immutable array or as an ordered set (technically a multi-set, as Index objects may contain repeated values). Those views have some interesting consequences in the operations available on Index objects. As a simple example, let's construct an Index from a list of integers: ind = pd.Index([2, 3, 5, 7, 11]) ind Int64Index([2, 3, 5, 7, 11], dtype='int64') ind[1] 3 ind[::2] Int64Index([2, 5, 11], dtype='int64') Index objects also have many of the attributes familiar from NumPy arrays: print(ind.size, ind.shape, ind.ndim, ind.dtype) 5 (5,) 1 int64 One difference between Index objects and NumPy arrays is that indices are immutable–that is, they cannot be modified via the normal means: ind[1] = 0 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-34-40e631c82e8a> in <module>() ----> 1 ind[1] = 0 /Users/jakevdp/anaconda/lib/python3.5/site-packages/pandas/indexes/base.py in __setitem__(self, key, value) 1243 1244 def __setitem__(self, key, value): -> 1245 raise TypeError("Index does not support mutable operations") 1246 1247 def __getitem__(self, key): TypeError: Index does not support mutable operations This immutability makes it safer to share indices between multiple DataFrames and arrays, without the potential for side effects from inadvertent index modification. Index as ordered set¶ Pandas objects are designed to facilitate operations such as joins across datasets, which depend on many aspects of set arithmetic. The Index object follows many of the conventions used by Python's built-in set data structure, so that unions, intersections, differences, and other combinations can be computed in a familiar way: indA = pd.Index([1, 3, 5, 7, 9]) indB = pd.Index([2, 3, 5, 7, 11]) indA & indB # intersection Int64Index([3, 5, 7], dtype='int64') indA | indB # union Int64Index([1, 2, 3, 5, 7, 9, 11], dtype='int64') indA ^ indB # symmetric difference Int64Index([1, 2, 9, 11], dtype='int64') These operations may also be accessed via object methods, for example indA.intersection(indB).
https://jakevdp.github.io/PythonDataScienceHandbook/03.01-introducing-pandas-objects.html
CC-MAIN-2019-18
refinedweb
1,266
52.7
C++ cout~text~ if (int<=)can someone just paste what everything would look like with the fixes? please C++ cout~text~ if (int<=)soooo what would that look like, i tried it and what i did didnt work C++ cout~text~ if (int<=)i know but i want it to say that anytime health is <=0 C++ cout~text~ if (int<=)well this is the program so i dont think that would work #include <iostream> using namespace std;... C++ cout~text~ if (int<=)i want it to say sorry you have died if health is equal to or less than 0 and close the program. so ... This user does not accept Private Messages
http://www.cplusplus.com/user/SloshyFob/
CC-MAIN-2017-17
refinedweb
113
79.13
New firmware release v1.13.0.b1 (Sigfox and LoRa coexistency on the LoPy4) Hello, This release is mainly about support for the LoPy4. The change log is as follows: - esp32: Add LoPy4 support with LoRa and Sigfox on the SX1276 - esp32: Save the downlink ack flag as part of the LoRaWAN NVRAM parameters. - esp32: Only bootstrap the 32KHz RTC clock if enabled with an external crystal. Solves GPIO issues when using both P19 and P20. - esp32: Fix os.uname() crash on the FiPy. Cheers, Daniel @daniel @Xykon I also updated to the latest version but sigfox is not working. Do you have any idea what could be the reason? Is it bricked? Also, in the device information at Sigfox backend "Radio Configurations" seems wrong. ( I am in Japan): Modem manufacturer: PYCOM_device_maker Modem name: SiPy-14 Modem version: S I P Y 1.0 R Radio Configurations: RC1 Thanks @livius, just downgraded to 1.12.0.b1 using the same link you provided. @daniel it is still same, no message is going to sigfox backend. Can be it antenna issue? @denial How can I revert back to 1.12.0.b1 ? I guess the updater always installs the latest one. @pymiom 1.12.0.b1 also has Sigfox. Have you tried a different USB cable? There are a lot of weird issues which are caused by faulty cables... @daniel do you have any ideas about the reboots of the fipy? I still have yet to downgrade, but need the Sigfox functionally and concerned it may not be in the version I downgrade to. Cheers! @naveen seems correct. Are you able to revert the firmware back to the previous release? As far as we can test Sigfox is still working OK with this version, but maybe in your case there's a problem. It would be great if you can revert to the 1.12.0.b1 release and test again. Thanks. Cheers, Daniel '@daniel I got this output: Hello Naveen, The only way to know if the device is transmitting is with a Spectrum Analyzer, but I don't think you could have damaged the radio. Please read the Sigfox ID and PAC from the device and tell me what you get: from network import Sigfox import socket import binascii sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ3) print(binascii.hexlify(sigfox.id())) print(binascii.hexlify(sigfox.pac())) Cheers, Daniel @daniel As you suggested, I clicked on the "Disengage the sequence number" option for the registered FiPy device in the SigFox backend but the FiPy still does not send message. How can I know if the SigFox chip is okay and working? Is there any way to debug whether the messages are being sent? - Xykon administrators last edited by Xykon UPDATE: [LINK NO LONGER AVAILABLE] @naveen please go to the Sigfox back-end portal, click on your device (the FiPy in question) and, find the option to "Disengage the sequence number" and click on it. The try sending messages again. The failed update might have messed up the NVM of the device causing a a corruption of the sequence numbers. I tried with another USB cable which I used before and it worked! But the other problem is still there, fipy is not sending message to sigfox anymore. Why? @Xykon I do not use any expansion board. I use usb serial adapter with breadboard (in fact, I made one using mkr1000). I have updated last firmware twice (few days ago) using this setup successfully. All wires are connected correctly and I always hit reset button before upgrade. Nothing is connected to FiPy except TX/RX, VIN/GND (with GND and G23 connected using jumper). Also, when I run "screen" command on MacOs and hit reset button it says "Waiting for download...", so I think serial connection is working. I guess for some reason it is not able to read memory. I am not able to erase firmware using esptool, too. Otherwise everything is working with the existing firmware (the last one). I also tried to do safe boot by connecting P12 to 3v3 with all possible ways but the firmware stays same. And the main thing is SigFox stopped sending messages, before I was able to send 21 messages so far and I believe Sigfox coverage is pretty good where I live (near Tokyo). - Xykon administrators last edited by @naveen Do you use a Pytrack / Pysense or Expansion Board 2.0? The most important thing is to make sure that no other program is using the serial port when you try the firmware upgrade. Unfortunately I don't have a way of checking this in the app. For Pytrack / Pysense: Please make sure you have the latest firmware loaded. For Expansion Board2: Please make sure you press the reset button before every use of the firmware update or esp-tool. Can you please post the output you see on the serial port when pressing the reset button with the firmware jumper wire attached? I am not able to update using the GUI updater for MacOS. It always fails. I tried to update using pycom-fwtool-cli but I am getting following error message: Connecting..... Uploading stub... Exception: read failed: [Errno 6] Device not configured, on line 197 Then I tried esptool.py read_mac and it says: A fatal error occurred: Failed to read target memory The FiPy's BLE and Wifi still works but now it stops sending message to SigFox (before it worked very well). I am not sure if it is related to the update failure. UPDATE: I also updated esptool to the latest version and run "esptool.py read_mac" but it stucks at "Uploading stub..." : esptool.py v2.2 Connecting.... Detecting chip type... ESP32 Chip is ESP32D0WDQ6 (revision 1) Uploading stub... HI,! This post is deleted!
https://forum.pycom.io/topic/2421/new-firmware-release-v1-13-0-b1-sigfox-and-lora-coexistency-on-the-lopy4
CC-MAIN-2021-31
refinedweb
969
74.39
Hierarchical Datasets Updates As a part of a session that I’m suppose to deliver on March, I’m going to explain the datasets enhancements that came along with Visual Studio 2008. In particularly, I’m going to explain what is the TableAdapterManager and how it is going to help you with hierarchical datasets updates. The post is going to explain that subject as well. The TableAdapterManager Class When you create a new typed-dataset in Visual Studio 2008 by default a class by the name TableAdapterManager is generated. The main purpose of the class is to enable the functionality to save data in related data tables. The TableAdapterManager uses the relations between the data tables in order to determine in which order to perform a set of CRUD operations without violating any foreign-key constraints. This behavior is called hierarchical update. This new behavior is suppose to free the developers from the plumbing of building CRUD scenarios by themselves when using datasets. The hierarchical update behavior is best suited to Master-Details forms. As a backward compatibility a new property with the name Hierarchical Update was added to the typed-dataset. That property is by default True but in datasets that were added to projects that were created in earlier versions of Visual Studio the Hierarchical Update property is set to False. How to Perform Hierarchical Datasets Updates The following example is going to use the typed-dataset that is generated from the following database schema: Lets generate the dataset. I’ve created a class library that is called DataAccessLayer. In that library I generated a new typed-dataset with the name SchoolDataSet. Then, I dragged the Course and Department tables to the designer. The following image shows the outcome of the operations I described: As you can see in the image I put the mouse pointer on the new Hierarchical Update property. If you don’t want to use that feature change the property to False. The following class provide a method to update Courses and Departments in hierarchical update: public class DataProvider { public void UpdateCoursesAndDepartments(SchoolDataSet ds) { TableAdapterManager manager = new TableAdapterManager(); manager.CourseTableAdapter = new CourseTableAdapter(); manager.DepartmentTableAdapter = new DepartmentTableAdapter(); manager.UpdateAll(ds); } } In order to use hierarchical update we need to create a new TableAdapterManager and insert the relevant table adapters that will participate in the update. The reason for that is obvious. If we have a lot of data tables in the dataset that don’t participate in the update, why should we build adapters for them? it will be a waist of memory. After building the adapters all we have to do is to call the UpdateAll method that perform the hierarchical update. Simple as that. Summary Lets sum up, Visual Studio 2008 brought with it some enhancements for the datasets world. One enhancement is the hierarchical update feature that enables to update a set of data tables that relate to one another without the need to indicate the order of operations. I showed how to use the TableAdapterManager which is the base for the hierarchical update behavior. תודה רבה Hi Shlomo, With pleasure. תודה אחלה של פוסט Thanks Rotem.
http://blogs.microsoft.co.il/gilf/2009/01/23/hierarchical-datasets-updates/
CC-MAIN-2016-36
refinedweb
525
54.83
... Nokogiri version 1.8.3 has been released! TL;DR: This is a feature and bugfix release. There's also a commit reverted in the vendored upstream libxml2 that the Nokogiri maintainers feel introduced unnecessary security risk involving sanitizing HTML attributes. You're encouraged to read the release notes and the related documents if you're curious or want to evaluate whether you should upgrade. The release is being made from NYC, at the twelfth and final GORUCO. Here is a really old version of a browser game i wrote in PHP(1). Please don't share the link as I'm very limited in resources. This is the type of browser game I'm trying to create. It is an open source version of Batllemail, a now defunct game written by Paul Gouge. Players would pick 6 attacks and 6 blocks and then the challenge would be sent to the opponent. After the opponent does the same if he accepts the challenge, bother users are treated to a Kung-Fu style cinematic played out based on what both players choose(2)(3). I know you guys might be bias, but i still want your opinions. Hi, all. "For reasons," I need to set up a telnet-like service -- and, yeah, it needs to be on port 23. In the Unix world, ports < 1024 require root privs to open, but I don't want my server running with root privs for reasons that should be obvious. Using the base Eventmachine example, I'm wondering if someone could show me how to do this? I see that there's a "set_effective_user(username)" method on the object, but I don't see how to use that on the object since instantiating it seems to execute it, and it's too late to do it afterward... People, I have been using RCM for many years and although it is the best current option for my needs, there are still some changes / enhancements I would make if I could - but it is written in PHP and there is no way I am going to put any effort into learning that. Hi Folks, Just came across the question regarding what are the different design patterns used in ActiveRecord library, As of I know ORM is one of the design pattern used, Is there any other design pattern used in ActiveRecord library? Is there some reason that ruby-doc.org presents the merge method in the example block for update method ? <a href="" title=""></a> thank you, -az Hello Ruby Friends! I was reviewing Ruby docs and re-learned that a Hash can be created from what appears to be a list of strings with the requirement that there is even number. I try it in irb: irb(main):004:0> Hash["stringA1", "stringA2", "stringB1", "stringB2"] => {"stringA1"=>"stringA2", "stringB1"=>"stringB2"} Yet when I try to automate it with a variable I see that the argument of list appears to be unacceptable. In irb: irb(main):007:0> s = ["stringA1", "stringA2", "stringB1", "stringB2"] => ["stringA1", "stringA2", "stringB1", "stringB2"] irb(main):008:0> Hash[s] (irb):8: warni Hi! Hello,. I. using the sportdb machinery (gems, command line tools and build scripts in ruby) I've put together a [new free public domain dataset for the (football) world cup in Russia 2018 [1]. Forgive me if this is off topic, but since Ruby and Heroku (and Rails and ...) use GH ... I'm really upset about the acquisition of GitHub by The Company That Shall Not Be Named. Clearly I have a bias. I have been a happy little coder, thinking about Github with warm fuzzy thoughts about all the great innovative work going on and my little miniscule contribution to that. Now the site is associated with what I consider to be one of the worst companies of all time. Honestly I feel blindsided and betrayed. Your mileage may vary ? I can't ask this question on the Discourse forum because I installed the Bitnami stack into my Docker container and the Docker people won't answer questions if you don't use their container - so I thought there might be some Rubyists who have had some experience with Discourse or at least might be interested enough to help me debug this problem (I am assuming it is Ruby-related). I have the container working fine here: <a href="" title=""></a> BUT . . emails aren't working . Well, okay, feel free to comment on my Ruby. There's room for improvement. I have been playing at some code for a while and decided to make it actually "work" today. That means prioritizing a very few processes and pushing back on scope creep. We are pleased to announce the release of Ruby 2.6.0-preview2. Ruby 2.6.0-preview2 is the first preview toward Ruby 2.6.0. This preview2 is released earlier than usual because it includes an important new feature, JIT. ## JIT Ruby 2.6 introduces an initial implementation of JIT (Just-in-time) compiler. cod e. See also: https:// I am completely new to ruby though I have several years experience in programming. My question is why following code's class X can directly refer to state (for defining method block) without any include or require keyword? And how can I access to state method value (in class X) after those state blocks are initialized (so I can observe values gets defined or executed in that block)? Unsubscribe: <mailto:[email protected]?subject=unsubscribe> <> rasn1 0.6.2 has been released. * bugs: <> * doc: <> RASN1 is a pure ruby ASN.1 library. RASN1 helps to create ASN.1 parsers and encoders. Changes: ### 0.6.2 / 2018-05-28 * Add Types::UtcTime and Types::GeneralizedTime I installed ruby-2.4.4 from the default tarball on a RHEL5 system to /tmp/ruby24. I want to install gems manually to /tmp/ruby24p (I want all gems in a separate directory). The JRuby community is pleased to announce the release of JRuby 9.2. Good evening everyone, I am pleased to announce that I have released ruby-xz 1.0.0 today after several years of stallment. ruby-xz provides Ruby bindings for the liblzma[1] library, the C library behind the compression programme xz(1). It can thus be used to create or unpack XZ-compressed tarballs if used together with the minitar[2] RubyGem. Intended as a foot-in-the-door patch to start using URCU in a similar fashion to GMP (both are LGPL). Only working with the slow "bp" (bulletproof) Userspace-RCU implementation, for now. Hi there, I'm looking for feedback on <a href="" title=""></a> and <a href="" title=""></a>. Sorry I haven't committed to Ruby before and am not sure of the best way to go about getting more feedback other than emailing this listserv. Please let me know if there's a better way to go about getting feedback on these. Thanks! As I was investigating the performance of Eric Wong's Sleepy GC patches ( <a href="" title=""></a>) I saw some regression in early April Ruby head-of-master. I mentioned that I'd seen it, and Koichi suggested I email Ruby Core. The speed regression I saw was pretty small, and I re-ran the benchmarks to make sure. A large parallel run of Discourse can have very noisy data. I've added a new free (online) book to the Yuki & Moto Press Bookshelf [1]. Let's welcome: Programming Blockchains Step-by-Step from Scratch (Zero) in Ruby. Starting with Crypto Hashes... Hi, all. I've got a file with some things like this: radio frames^M<83>?<9B>v64 (The "?" is a \x3f) Needless to say, Ruby barfs all over that. There are also *other* invalid strings in the file. (Thanks, Framemaker.) Now, I know I can use #scrub to make the file palatable, but what I *really* want to do is to take the "<83>?<9B>", and swap it with a \u2022 (unicode bullet), and then use #scrub on the rest of the invalid stuff. But I can't figure out how to do that; I admit I get out of my depth when dealing with encodings.. flay version 2.12.0 has been released! * code: <> * rdoc: <> Flay analyzes code for structural similarities. Differences in literal values, variable, class, method names, whitespace, programming style, braces vs do/end, etc are all ignored. Making this totally rad. ### 2.12.0 / 2018-04-29 * 1 minor enhancement: * Switched node filtering to happen before processing to avoid subtrees getting processed.? Hi, To host RoR application, what do i need in memory/cpu/storage ? Does a VPS with 2GB MEMORY/ 2cpu 3.0 GHz / 30 GB storage enough ? In the way running nginx+unicorn+postgresql Thank's! Cédric. Qo 0.3.0 is now out, and comes with a shiny new way to do pattern matching: <a href="" title=""></a> name_longer_than_three = -> person { person.name.size > 3 } people_with_truncated_names = people.map(&Qo.match { |m| m.when(name_longer_than_three) { |person| Person.new(person.name[0..2], person.age) } m.else(&:itself) }) # And standalone like a case:Qo.match(people.first) { |m| m.when(age: 10..19) { |person| "#{person.name} is a teen that's #{person.age} years old" } m.else { |person| "#{person.name} is #{person.age} years old" } } A bit more Scala inspired, and defini Hi Ruby core committers, Cookpad Inc. supports Ruby committers who can attend "Ruby Committers vs the World" session at this RubyKaigi2018. I've been writing a few more advanced articles on how base concepts of Ruby can be utilized to emulate features of more functionally oriented languages. The JRuby community is pleased to announce the release of JRuby 9.1.17.0 JRuby 9.1.x is our current major version of JRuby. It is expected to be compatible with Ruby 2.3.x and stay in sync with C Ruby.. Back again with new toys after playing with Rambda in Javascript again, and wanting to keep a few of the features for later. <a href="" title=""></a> Introducing Xf, or Transform Functions. The idea behind this one was to emulate lenses from functional languages in Ruby in a pragmatic way with a bit of a Ruby twist. Deal with a lot of JSON and transforming it? Have no idea where the key is, or even if it's in the same place? Xf is great with that, give it a shot! Was tempted to add some of this to Qo, but the concerns were fairly seperate. Enjoy! - baweaver What do you advice for a Unix/Windows administrator who wish to create awesome web applications using Rails framework ? What skills do we need in Ruby language to be able to survive in Rails ? Do we need to master CSS, HTML, Javascript ? Do we need to master Git ? Which database to choose ? PostgreySQL, MySQL or Sqlite? MongoDB ? Thank you very much for your replies! Cheers, Cédric What's the primary toolkit/framework for machine learning with ruby? Just like python's scikit-learn. I searched and found this link, <a href="" title=""></a> It seems there are too many options to choose. Thanks for any suggestion. I just saw one developer do this in his code : private if some_condition? def first_method end I was wondering how the private method works. How does it figure out which methods to mark private ? It would be nice if someone could explain this or point me to appropriate resources on the web. - bitsapien Added a feature for pattern matching with right hand assignment using a guarded block implementation. Hello, I'm working with an established financial technology employer that is looking to hire a permanent web developer with significant client side experience to join their New York office. Consequently, I had hoped that some members of this mailing list may like to discuss further off-list using "JamesBTobin (at) Gmail (dot) Com". Kind regards, James Hello. Ruby what kind of evaluation do you have ?, according to I have a strict evaluation, since in the following code in the variable the addition and subtraction are evaluated. #ruby 2.3.1 a = 3 + 2 b = 10-5 c = (a + b) / (a-b) puts "hello world!" Hi, I have two arrays of hashes : "----- table name == EMessages <--------------> ID == ID" ---------arr1 ----target----------------- [{"ID"=>"11562", "EmailType"=>"2", "ContentKey"=>"1113", "ExtraKey1"=>"1", "CreationDate"=>"2009-07-06 09:36:01.303", "EmailSent"=>nil}, {"ID"=>"11574", "EmailType"=>"2", "ContentKey"=>"8833", "ExtraKey1"=>"0", "CreationDate"=>"2009-07-06 11:38:52.613", "EmailSent"=>nil}] ---------arr2 ----source----------------- [{"ID"=>11562, "EmailType"=>2, "ContentKey"=>"1113", "ExtraKey1"=>"1", "CreationDate"=>2009-07-06 09:36:01 -0400, "EmailSent"=>nil}, {"ID"= First release of Qo, short for Query Object. I'm trying to understand ruby more from an implementers perspective in the hopes that I can one day contribute a patch. My first step into this arena is learning how the unary & operator works, although I can't find out where in the ruby source this is implemented. Also, does anyone have any tips on finding where in the ruby source these kinds of things are implemented? Hello list, currently i'm trying to build a little application with Ruby and Gtk+ (See [1]). I have such files: bin/latex_curriculum_vitae: =========================== #!/usr/bin/env ruby require 'gtk3' require 'fileutils' # Require all ruby files in the application folder recursively application_root_path = File.expand_path(__dir__) Dir[File.join(application_root_path, '..', 'application', '**', '*.rb')].each { |file| require file } # Define the source & target files of the glib-compile-resources command resource_xml = File.join(application_root_path, '..', 'resources', 'gresources.xml' I'd like to introduce a library I've been working on for the past months. * code: <> * rdoc: <> It's an http library, which supports both HTTP/2 and HTTP/1 requests over the same simple API. Its high-level API and some features are directly inspired from both the HTTP.rb and python requests. The main differentiator to other libraries is that it allows multiple concurrent requests in the same thread.. It appears that Golang has Race Detector, a tool to detect race conditions -- <a href="" title=""></a> Does anyone know of anything similar for Ruby? Or, any advice at all for testing that my code is threadsafe? (Detail: I'm writing a connection pool. This is for Ruby, not Rails. I think I have a workable approach, but I'm not sure how best to write the tests...) Hi Rubyists, First version of cancancan-neo4j <> for neo4j graph database is released. It will help with authorisation using cancan. Rules can be defined as can :read, Article, author: { name: 'Chunky' } Thanks, A Rubyist. packetgen 2.5.0 has been released. * bugs: <> * doc: <> PacketGen provides simple ways to generate, send and capture network packets. Known protocols are: Ethernet, Dot11, Dot1x, ARP, IP, IPv6, GRE, ICMP, IGMP, ICMPv6, MLD, MLDv2, OSPFv2, OSPFv3, UDP, TCP, SNMP, ESP, DNS, IKE, EAP, BOOTP, DHCP, TFTP and HTTP. ### 2.5.0 / 2018-04-02 * Add support for MLDv2, OSPFv2 and OSPFv3 protocols * Freeze all string literals to be ready for ruby3 * Refactor Hello rubyists, I'm done with some basic ruby. What should be my next step?. Thank you !.
http://www.devheads.net/development/ruby
CC-MAIN-2018-26
refinedweb
2,524
65.93
CodePlexProject Hosting for Open Source Software Documentation NumPy and SciPy for .Net The Python NumPy and SciPy packages have been ported to run under IronPython, Microsoft’s Python implementation for .NET. These packages implement a fast and flexible multi-dimensional array package (NumPy) and a large collection of scientific and numerical algorithms built on top of the array (SciPy). Both packages consist of a heavily optimized native core implementation of the algorithms and a custom .NET interface for integrating the packages into IronPython.. This release represents an early version of the architecture for the NumPy 2.0 release where there is a common, platform-independent core and multiple interface layers (currently CPython and IronPython/.NET). This version attempts to maintain full compatibility with earlier versions of NumPy, and in general this goal has been achieved. However, some inconsistencies were necessarily as a result of the port and the re-architecting of the NumPy core. See ‘What You Should Know’ below regarding this release. The first part of this document provides a quick overview of the capabilities of NumPy and SciPy for those unfamiliar with the packages. These examples attempt to highlight a range of capabilities of these packages but are by no means complete. Please see and for the complete documentation. The second part of the document describes the known limitations, incompatibilities, and future work for these packages. NumPy and SciPy are bundled as pre-built “eggs” common to Python software distributions. The files include the Python source code and pre-built binary images in an easy-to-install package. For download and installation instructions please see. NumPy is the fundamental package needed for scientific computing with Python. It contains among other things: Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. This allows NumPy to seamlessly and speedily integrate with a wide variety of data formats. This section provides a brief tour of some of the capabilities of NumPy, particularly the array functionality. Getting Started All of the following examples assume that IronPython (2.7rc1 or later) and NumPy for .NET have been installed and the packages loaded into python (“import numpy as np”). Please see for instructions on downloading and installing NumPy. The NumPy package takes full advantage of the flexibility and expressiveness of the Python range syntax to provide powerful indexing capabilities. When a NumPy array is indexed, the package typically returns a view into the original data and avoids copying it. This allows the selection of subsets of data to be performed very quickly, and modifications to be made using the much clearer syntax of the subset. The following example creates a 10x10 2-d array and selects one row and one column from it. Both the row and col variables are views into the array so when col[2] is set to a new value, the original array is modified: x = np.arange(100).reshape((10,10)) # Now have a 10x10 array row = x[3] # Y is [30..39], view not copy col = x[:,3] # Z is [3, 13, ... 39], not a copy col[2] = 42 print "x[2, 3] = %d" % x[2, 3] # x[2,3] has been modified Note, too, in the first line that the array is originally created as a 1-d, 100-element array and then a new shape is applied. NumPy provides powerful capabilities to “look at” the same data array in multiple ways as will be shown in later examples. Continuing the same example, the entire column can be modified. Now that the 3rd column in the array has been modified: col += 100 # Modify third column of X print "x = %s" % z # 0, 1, 2, 103, 4, 5, ... # 10, 11, 12, 113, 14, 15, ... NumPy fully supports the Python range syntax of start:step:increment. Using this syntax, we can select every third element of the array starting with the second: x = np.arange(100) y = x[1::3] Again, this is simply a view into the original array so modifications to this array are reflected in the original. The view makes it much easier to operate on the selected subset of data. For example, if we wanted to multiply every third element by 2: y = x[1::3] for i in range(len(y)): y[i] *= 2 Or more simply: x[1::3] *= 2 There are two advantages to this approach. First, it avoids the off-by-one class of errors common in for-next loops in C by using the array indexing syntax. Second, in the single-line version, iteration over the array is performed in native code, making it the fastest version, too. Going further, NumPy supports the use of ‘mask arrays’ as array indices. Mask arrays are arrays of Boolean values and when used as an array index, NumPy selects elements where the mask is true. For example: x = np.arange(100) y = (x % 3) == 0 # y is bool array w/ true where (x%3 == 0) z = x[y] # z is elements of X where Y is true. In the second line, the result of applying the double equal operator to the result of the modulus operator is a Boolean array indicating each index where (x%3) is 0. Using ‘y’ as an index into ‘x’ produces an array containing only the values that are even multiples of 3 (z). In this case it is important to note that ‘z’ is a copy of x because there is no way to simply adjust the number of dimensions and strides to make a new view of ‘x’ since the mask array can be an arbitrary pattern. In this case, changes to ‘z’ will not be reflected in ‘x’. A slightly more complex example uses fancy indexing to extract the subset of values that are perfect squares and passes the result as a C# function which can access it through the IEnumerable interface: x = np.arange(100) y = np.sqrt(x) MyCSharpClass.DoSomething(x[y == np.trunc(y)]) C vs. Fortran Ordering and Interoperability By default NumPy stores the data using a memory layout common to the C language (most rapidly changing index last) vs the standard Fortran memory layout (more rapidly changing index first). However, NumPy supports arrays with both layouts transparently and makes it simple to convert between the two. Selecting Fortran memory layout makes it easier to integrate with legacy Fortran code: # 10x10 2d array of ints, convert to Fortran order, floats x = np.arange(100).reshape((10,10)) y = np.array(x, dtype=np.float32, order='Fortran') # Pass IntPtr of array data to C# object MyCSharpFortWrapr.DoSomething(y.UnsafeAddress) Record arrays and Type Conversions Record arrays are a variation on indexing in that they allow each element of the array to consist of multiple fields of different types. For example, the following array contains 10 elements consisting of a string, an integer, and a floating point value: x = np.zeros(10, dtype=('S,i,f')) Array fields can be accessed using the string ‘f0’, ‘f1’, … ‘fN’ or the fields can be explicitly named: x = np.zeros(10, dtype=[('name', 'S'), ('quantity', 'i'), ('weight', 'f')]) Accessing each row of the record array returns the fields as a tuple: name, qty, weight = np[0] Alternately, each field can be accessed as a column and extracted into an array. For example, the weighted average weight of the inventory items: avgWeight = np.sum(x['quantity'] * x['weight']) / np.sum(x['quantity']) And similar to indexing earlier, referencing fields of an array produces a view so modifications to the view are reflected in the original. The weights can all be converted to from kg to lbs like this: x['weight'] *= 2.206 One of the particularly powerful uses of record arrays is the ability to apply the record structure to an existing memory layout, such as one read from a file. Say we have a binary file that is a simple dump of an array of the following structure: struct { float latitude; float longitude; int16 elevation; int16 surfaceType; }; This file can be quickly loaded into a NumPy array for processing. For example: x = np.fromfile('data.dat', dtype=[('lat', 'f4'), ('lng', 'f4'),('elev', 'i2'), ('surface', 'i2')]) maxElev = np.max(x['elev']) Further, it is not uncommon to find data written using a machine architecture different than the current one, such as big- vs little-endian. By default NumPy uses the native machine format but can be instructed to use big-endian with the greater-than symbol prefix (>) or little-endian with the less-than symbol prefix (<). The following code reads the above data file assuming it was written on a big-endian machine and extracts a copy of the elevation data into native-format 32-bit integers: x = np.fromfile('data.dat', dtype=[('lat', '>f4'), ('lng', '>f4'), ('elev', '>i2'), ('surface', '>i2')]) elev = np.array(x['elev'], dtype='i4') # 'elev' is now a copy As mentioned before, selecting a field out of an array produces a view so writes to the view are reflected back to the original. This is true even if the byte format is non-native; the byte swaps are handled transparently: x['elev'][2] = 1500 Signal Processing, Linear Algebra, and Other Packages A full description of the FFT, linear algebra (linalg), and other packages provided by NumPy are beyond the scope of this document and the reader is referred to for complete documentation. However, a final short example will demonstrate how some of the above concepts can be combined with these packages. The FFTPack module provides a range of fast Fourier transforms that operate on NumPy arrays. The following example reads data from a hypothetical data file containing signal data. The data is stored as a 32-bit int plus two 16-bit ints all in big-endian format. The following code extracts the middle value and performs a basic, 1-d FFT transform on it. To make it useful without the hypothetical file, it also generates some synthetic data. SciPy Overview SciPy (pronounced "Sigh Pie") is large Python library. NumPy and SciPy are easy to use, but powerful enough to be depended upon by some of the world's leading scientists and engineers. A full description of the SciPy library can be found at. Here is a brief look at some of the SciPy modules available on IronPython: import numpy as np import numpy.fft as fft x = np.fromfile('signal.dat', dtype=('>i4,>i2,>i2')) # Copy, convert to native floats, rescale sig = np.array(x['f1'], dtype=np.float32) / 32768 # Alternate: since no file is provided, we can make up some data: data = [math.sin(np.pi / 8 * i) for i in range(320)] noise = [np.random.rand() * 0.02 for i in range(320)] sig = np.array(data, dtype='f') sig += np.array(noise) f = fft.fft(sig) print "Strongest frequency = %d n" % np.argmax(np.abs(f)) What You Should Know Some SciPy packages have not been ported yet - Many of the most important SciPy packages have been ported to IronPython but some packages are still in-progress. The following packages are included in this release: stats, special, linalg, fftpack, constants, and misc. The remaining packages are in-progress and will be added as the ports are completed and passing regression tests. Memory corruption in chararray package - In the NumPy chararray package (numpy.char), there is a memory corruption issue that has not yet been tracked down. This does not impact arrays of strings in general, just the numpy.char package and surfaces in a couple of that package’s regression tests. ‘Bytes’ type is not recognized as a string type - In CPython strings can be both unicode and ASCII. However, in .NET all strings are unicode and the bytes type is represented as a byte[] type, which does not implement the string interface. In most cases everything works as expected, but occasionally an error will be reported. In this case, it is necessary to manually convert to either a bytes or string type as needed. Because of this issue, numpy.compat.asbytes() in IronPython returns a string type instead of a bytes type. numpy.fromfile does not support file handles - In CPython numpy.fromfile accepts both file names (strings) and file handles. Because IronPython file handles are implemented as .NET streams and the NumPy file reading code is in the (native) core, these streams can not be passed into the NumPy core. For now, only file names are accepted. numpy.fromstring only support text strings - The CPython version of numpy.fromstring supports both text and binary strings. Because .NET strings are unicode, only text strings are currently supported. Pickling from transposed and dis-continuous arrays is not implemented - This functionality has not yet been implemented. numpy._dotblas CBlas library has not yet been ported - This module must still be ported. The SciPy linear algebra package scipy.linalg can be used instead. ndarray.resize() can not check for multiple references - IronPython uses a garbage collector instead of reference counting so there is no way for the resize function to check to see whether there are multiple references to the underlying data. Using resize() on an array referenced by other objects is illegal and can cause memory issues. This function should only be used on a new copy of an array or avoided. The __array_struct__ and __array_interface__ attributes are not implemented - These attributes provide methods for other objects to present an array interface to NumPy. If external classes implement these interfaces it will not cause a problem, but the NumPy array on IronPython does not currently implement these interfaces. This breaks some regression tests in both NumPy and SciPy. Buffer Support is weakly implemented - The current version of IronPython does not implement a full version of the buffer protocol in CPython. NumPy provides and implements the interface IExtBufferProtocol, but this is not a standard part of IronPython. Long double type is not supported - The .NET platform does not have support a long double type so it has not been implemented in this release. [would you like to help port NumPy/SciPy to Mono? Let’s talk!] Last edited Jul 17, 2014 at 5:05 PM by Ptools, version 9
https://pytools.codeplex.com/wikipage?title=NumPy%20and%20SciPy%20for%20.Net&version=9
CC-MAIN-2016-07
refinedweb
2,368
54.73
XML Schemas enable document designers to specify the allowed structure and content of an XML document. <oXygen/> provides a powerful and expressive Schema Diagram mode for editing XML Schemas. The structure of the diagram is intuitive and easy to use. The XML Schema diagram helps both. The Palette view enhances even further the usability of the XML Schema diagram builder by allowing you to drag components from this helper view and drop them into the Design page. The Outline view for XML Schema presents the XML schema components from the current schema and from the included and imported schemas. All the global components can be sorted by name and grouped by type, location and namespace. If you need to find a component, you can search for it by typing its name into the outliner filter text field. The Outline view is drag and drop enabled,. The Attributes View provides an easy way to edit attributes for all XML Schema components. You can choose valid values from a list or you can specify your own values. If an attribute has an invalid value it will be highlighted in the table so you can easily spot the error and fix it. Using the Facets View you can easily check the existing facets of the current simple type (including the default facets), edit values or add patterns and enumerations. If a facet has an invalid value it will be highlighted in the table. You can ensure the XML Schema you develop complies with the W3C standard by using one of the validation engines distributed with <oXygen/>: Xerces or Saxon-EE validator. <oXygen/> can also be configured to use an external XML Schema validator. <oXygen/> provides the support for defining the main module of a complex XML Schema, thus allowing correct validation of a module in the context of the larger schema structure. When an editing action introduces an error the XML Schema validator signals it by painting in the diagram the border of the component containing the error with red. .
http://www.oxygenxml.com/xml_developer/xml_schema_diagram_editor.html
CC-MAIN-2014-15
refinedweb
337
60.95
StrLConnector (sfi.StrLConnector)¶ - class sfi. StrLConnector(*argv)¶ This class facilitates access to Stata’s strL datatype. The allowed values for the variable index var and the observation index obs are -nvar <= var < nvar and -nobs <= obs < nobs Here nvar is the number of variables defined in the dataset currently loaded in Stata or in the specified frame, which is returned by getVarCount(). nobs is the number of observations defined in the dataset currently loaded in Stata or in the specified frame, which is returned by getObsTotal(). Negative values for var and obs are allowed and are interpreted in the usual way for Python indexing. var can be specified either as the variable name or index. Note that passing the variable index will be more efficient because looking up the index for the specified variable name is avoided. There are two ways to create a StrLConnectorinstance: StrLConnector(var, obs) Creates a StrLConnectorand connects it to a specific strL in the Stata dataset; see Data. - var : int or str Variable to access. - obs : int Observation to access. A ValueError can be raised if StrLConnector(frame, var, obs) Creates a StrLConnectorand connects it to a specific strL in the specified Frame. A ValueError can be raised if Method Summary Attributes Method Detail Examples¶ In this section, we will show you how to access Stata’s strL datatype in two ways: - Write to strL variables in Python. - Read from strL variables in Python. We will use Stata to generate a PNG file for the purpose of this illustration. Then, we will use Python to store the PNG file into a dataset. Lastly, we will demonstrate how to read the PNG image from the dataset and store it into a new file. To begin, we generate a scatterplot and save it as sc1.png. . sysuse auto, clear . scatter mpg price . graph export sc1.png, replace . clear In the Python script that follows, strlex1.py, we create a dataset with one variable named mystrl with one observation. Next, we create an instance of the StrLConnector class sc, which is connected to the first observation of strL. The next step is to allocate the proper size for the data that we need to store in our strL. We do this by specifying the size of our image file in the allocateStrL() method. Then, we use a loop to read the contents of the image file in 2,048 byte chunks, writing each chunk to our strL in Stata. from sfi import Data, StrLConnector, SFIToolkit import sys import os #create a new dataset with one strL variable #mystrl and one observation Data.addVarStrL("mystrl") Data.setObsTotal(1) mpv = Data.getVarIndex("mystrl") obs = 0 #create an instance of StrLConnector sc = StrLConnector(mpv, obs) filename = sys.argv[1] flen = os.path.getsize(filename) #allocate the strL variable Data.allocateStrL(sc, flen, True) #read the image file and store the contents #in the strL variable chunk_size = 2048 with open(filename, "rb") as fin: b = fin.read(chunk_size) while b: Data.writeBytes(sc, b) b = fin.read(chunk_size) sc.close() SFIToolkit.displayln(filename + " stored in dataset") Now that we have shown how to add binary data from an image file and store it into a strL, we can reverse the process by reading the data from a strL and storing it on disk. In the Python script that follows, strlex2.py, we create an instance of the StrLConnector class sc to connect to the previously stored strL data. Remember that we stored sc1.png in our strL. We read the data in our strL using 2,048 byte chunks with readBytes(), writing each of those chunks into a new image file named sc2.png. from sfi import Data, StrLConnector, SFIToolkit import sys filename = sys.argv[1] #create an instance of StrLConnector #to connect to the strL variable var = Data.getVarIndex("mystrl") obs = 0 sc = StrLConnector(var, obs) #read the image file from the strL variable and #store the contents in a new image file chunk_size = 2048 with open(filename, "wb") as fout: b = Data.readBytes(sc, chunk_size) while b: fout.write(b) b = Data.readBytes(sc, chunk_size) sc.close() SFIToolkit.displayln(filename + " retrieved from dataset") Using Stata, we execute both Python scripts. Next, we checksum both the original image file and the file produced by reading the data from Stata, to confirm that they are equivalent. . python script strlex1.py, args(sc1.png) sc1.png stored in dataset . python script strlex2.py, args(sc2.png) sc2.png retrieved from dataset . checksum sc1.png Checksum for sc1.png = 1777154237, size = 37386 . checksum sc2.png Checksum for sc2.png = 1777154237, size = 37386
https://www.stata.com/python/api17/StrLConnector.html
CC-MAIN-2022-40
refinedweb
768
67.15
XQuery Functions against the xml Data Type SQL Server 2014 This topic and its subtopics describe the functions you can use when specifying XQuery against the xml data type. For the W3C specifications, see. The XQuery functions belong to the namespace. The W3C specifications use the "fn:" namespace prefix to describe these functions. You do not have to specify the "fn:" namespace prefix explicitly when you are using the functions. Because of this and to improve readability, the namespace prefixes are generally not used in this documentation. The following table lists the XQuery functions that are supported against the xmldata type. Concepts Other Resources Show:
http://msdn.microsoft.com/en-us/library/ms189254(v=sql.120).aspx
CC-MAIN-2014-35
refinedweb
105
58.18
Introduction ; Introduction Applet is java program that can be embedded into HTML pages. Java applets.... In this example you will see, how to write an applet program. Java source of applet... into the first program or Applet. destroy() method: The destroy() method how to execute jsp and servlets with eclipse how to execute jsp and servlets with eclipse hi kindly tell me how to execute jsp or servlets with the help of eclipse with some small program execute dos commands execute dos commands how to execute dos commands using a java program Introduction to Struts 2 Framework Introduction to Struts 2 Framework - Video tutorial of Struts 2 In this video... the basics of Struts 2 framework. We will explain you how you can create your first... Introduction. In this session I will explain you the basics of Struts 2 framework how to execute jsp and servlets with eclipse how to execute jsp and servlets with eclipse hi kindly tell me how to execute jsp or servlets with the help of eclipse with some small program.../hibernate/hibernate4/hibernate4ExampleEclipse.shtml Going through this link you may understand how how to execute a unix shell script from a java program how to execute a unix shell script from a java program well , i am... the script name from a java code .once you execute this java program... solution . could anyone please give a sample code as of how to do this... what i am Struts 2 Introduction to Struts 2 This section provides you a quick introduction to Struts 2 framework..., JSP API 2.0 and Java 5. Video Tutorial - Introduction to Struts File Upload Example Struts File Upload Example In this tutorial you will learn how to use Struts to write... and deploy the application go to Struts\strutstutorial directory and type ant Introduction Introduction  ... Hibernate and Struts. Hibernate and Struts are popular open source tools. You can download Hibernate from and Struts How to execute shellscript in Javascript How to execute shellscript in Javascript Hello Can anyone please explain me how to execute shellscript in Javascript Thanks Introduction to java arrays Introduction to java arrays  ... of Arrays in Java Programming language. You will learn how the Array class... manageable format. Program data is stored in the variables and takes the  How can java programs execute automatically when it connects to network How can java programs execute automatically when it connects to network Good Day dears... How can java programs execute automatically when it connects to network. Thanks in Advance friends Shackir How can i Test Struts File Upload and Save directory of server. In this tutorial you will learn how to use Struts... Upload</html:link> <br> Example shows you how to Upload File with Struts... the application go to Struts\strutstutorial directory and type ant on the command prompt struct program - Struts Struct program I am using the weblogic 8.1 as application server. I pasted the struts. jar file in the lib folder. when i execute program.do always gives the unavailable service exception. please help me where execute a PHP script using command line execute a PHP script using command line How can I execute a PHP... Line Interface) program and provide the PHP script file name as the command line... the CLI program. Be aware that if your PHP script was written for the Web CGI unable to execute the examples unable to execute the examples unable to execute the examples given for struts,ejb,or spring tutorials.Please help I am a beginner Struts - Struts ******************************************************************** package strutsTutorial; import... strutsTutorial; import javax.servlet.http.HttpServletRequest; import... UserRegistrationAction extends Action { public ActionForward execute (ActionMapping mapping Execute the java program using one processor Execute the java program using one processor Write a program... in dual core computer a) Execute the program using one processor b) Execute the program using more than one processor execute shellscript in javascript execute shellscript in javascript Hello Can anyone please help me how to execute a shellscript in javascript struts - Struts struts how to handle multiple submit buttons in a single jsp page of a struts application Hi friend, Code to help in solving... execute() { if ("Submit".equals(buttonName)) { doSubmit how to execute this code - JSP-Servlet how to execute this code hi guys can any help me in executing this bank application, i need to use any database plz tell me step-to-step procedure for executing this,i need to create J2EE Tutorial - Introduction J2EE Tutorial - Introduction  ..., JAX and Struts ..as well as hands on experience in Application servers...; begin with what Javabean is and also see how beans can be used Program compiles but won't execute - Java Beginners Program compiles but won't execute I have to write a program... so far for the Employee class(it compiles but does not execute); public class... written which again compiles but does not execute; public class Driver how to compile and run struts application - Struts how to compile and run struts application how to compile and run struts program(ex :actionform,actionclass) from command line or in editplus 3 Struts DynaActionForm ; In this tutorial you will learn how to create Struts DynaActionForm. We will recreate our address form with Struts DynaActionForm... To build and deploy the application go to Struts\strutstutorial directory Detailed introduction to Struts 2 Architecture Detailed introduction to Struts 2 Architecture Struts 2 Framework Architecture In the previous section we learned... components of Struts 2 framework. How Struts 2 Framework works? Suppose you Introduction To Application for the readers who wants to know how a shopping cart application can be written in struts...Introduction To Application The shopping cart application allows customer to view and brows catalogs of the products which is being sail online Introduction to Ajax. Introduction to Ajax. Ajax : Asynchronous JavaScript and XML Ajax...;Server Side Scripting. Ajax examples: How to change value of div using Ajax in struts. Ajax validation in struts validation not work properly - Struts Struts validation not work properly hi... i have a problem with my struts validation framework. i using struts 1.0... i have 2 page which... { public ActionForward execute( ActionMapping mapping, ActionForm form Struts Struts how to learn struts Introduction to Action interface Introduction To Struts Action Interface The Action interface contains the a single method execute(). The business logic of the action is executed within... public String execute() throws Exception { setMessage(getText Struts Struts How to retrive data from database by using Struts how to execute the below servlet with html page how to execute the below servlet with html page //vallidate user n pwd by validservlet package active; import javax.servlet.*; import java.io.*; import java.sql.*; public class validservlet extends GenericServlet STRUTS STRUTS Request context in struts? SendRedirect () and forward how to configure in struts-config.xml Execute database query by using sql tag of JSTL SQL library how to execute sql query. To execute sql query we have used a sql tag <sql...Execute database query by using sql tag of JSTL SQL library... to create application that execute sql query given by user using JSTL SQL Library HTML . Introduction to HTML Here, we will introduce... idea about the DHTML and how it can be made to work on your site without pages..., we will introduce you to the idea of Forms and how they are used in HTML. You how to execute a file in java at regular time intrevals automattically how to execute a file in java at regular time intrevals automattically how to execute a file in java at time retrievals automatically Struts Articles security principle and discuss how Struts can be leveraged to address... are familiar with the Struts framework in the servlet environment how to use... includes support beyond the servlet Struts framework. In Part 1, we talked about How can I execute a PHP script using command line? How can I execute a PHP script using command line? How can I execute a PHP script using command line please send me a program that clearly shows the use of struts with jsp Introduction to the JSP Java Server Pages source code. Introduction to JSP Java Server Pages or JSP... the requests. Introduction to the JSP tags... introduction to JSP Declaratives JSP Declaratives begins with <%! and ends %> 1 Tutorial and example programs In this tutorial you will learn how to use Struts program to upload... and struts2 Introduction to the Apache Struts This lesson is an introduction to the Struts and its architecture Struts Books components How to get started with Struts and build your own... Edition maps out how to use the Jakarta Struts framework, so you can solve...-the business logic at the core of the program. The Jakarta Struts Framework is one Java Execute Jar file operating system or platform. To execute a JAR file, one must have Java..., you can attach it along with any libraries the program uses. To Run your .jar file type java -jar [Jar file Name] in the command prompt. To execute struts-netbeans - Framework struts-netbeans hai friends please provide some help "how to execute struts programs in netbeans IDE?" is requires any software or any supporting files to execute this. thanks friends in advance LookupDispatchAction Example ;Struts File Upload</html:link> <br> Example demonstrates how... the Example To build and deploy the application go to Struts\Strutstutorial directory... Struts LookupDispatchAction Example   Struts LookupDispatchAction Example ; To build and deploy the application go to Struts\Strutstutorial directory... Struts LookupDispatchAction Example Struts LookupDispatch Action How to execute mysql query based on checkboxes values in java swing application. How to execute mysql query based on checkboxes values in java swing application. Hello Sir, I have a java swing application and i have to execute query based on selection of checkboxes.Means I have to to execute JDBC Execute Statement JDBC Execute Statement JDBC Execute Statement is used to execute SQL Statement, The Execute... a database. In this Tutorial, the code illustrates an example from JDBC Execute JDBC Execute Update Example JDBC Execute Update Example JDBC Execute Update query is used to modify or return you an integer value specify... a simple example from JDBC Execute update Example. In this Tutorial we want Introduction to Interceptor Introduction to Interceptor Interceptors are one of the most powerful features of struts2.2.1. the introduction of interceptors into struts2.2.1...- The ServletDispatcher initializes The ActionProxy to call the execute() method Struts Dispatch Action Example Struts Dispatch Action Example Struts Dispatch Action... with the struts framework. The org.apache.struts.actions.DispatchAction struts struts how to handle exception handling in struts reatime projects? can u plz send me one example how to deal with exception? can u plz send me how to develop our own exception handling An introduction to spring framework SPRING Framework... AN INTRODUCTION... Framework. Other popular framewoks like Struts, Tapestry, JSF etc., are very good web... that instructs Spring on where and how to apply aspects. 4. Spring DAO: The Spring's JDBC Software Foundation. Struts in Action is a comprehensive introduction to the Struts... the Struts architecture and control flow, as well as how to extend framework... for a practical book that "shows you how to do it", then Struts Kick Start is for you - Struts be done in Struts program? Hi Friend, 1)Java Beans are reusable software...Java 1)What is the use of formbeans? 2)what happens if we write try block then return and finally? Which block statements will execute? Please Struts MappingDispatchAction Example the application go to Struts\Strutstutorial directory and type ant on the command... Struts MappingDispatchAction Example Struts MappingDispatch Struts MappingDispatchAction Example the application go to Struts\Strutstutorial directory and type ant... Struts MappingDispatchAction Example Struts MappingDispatch Action errors in struts struts - Struts struts How to use back button in struts Introduction To Math Class In Java Introduction To Math Class In Java In this tutorial we will read about... : Here I am giving a simple example which will demonstrate you how to use the above mentioned function in your program. In this example I will create a Java Java Introduction . How to Program in Java What is Programming... about what is Java, how it is used, its features, its purpose and about Java tools.... The program written in Java is first compiled in byte code by Java compiler Introduction to PreResultListener Introduction To PreResultListener PreResultListener is an interface...;/html> login.jsp <%@ taglib prefix="s" uri="/struts...="s" uri="/struts-tags" %><HTML> <HEAD> < 2 datetimepicker Example Struts 2 datetimepicker Example In this section we will show you how to develop datetimepicker in struts 2. Struts 2... Here is the output of the program In this section we have studied how Tiles Result Example in Struts 2.2.1 Tiles Result Example In Struts Tiles is a view layer which allows separate... Here</font> </div> menu.jsp <%@taglib uri="/struts...; <a href=" How to Program in Java This tutorial tells you how to program in Java? As a beginner you must know... program) for more details on "How to Program in Java?". Create simple... if there is no error in source code. Step 4: Execute the program. This is the final step Forward - Struts Forward Hi how to get the return value of execute() in Action class. we will write return mapping.findForward("success"); how to get the value of forward. Is there any method to get the which forward is executing PHP Introduction The quick introduction to the PHP programming language PHP is server... program is simple text file with the .php or .php5 extensions. You can use... for the MySQL database. MySQL is most used database with the PHP program. You can use struts - Struts struts get records in Tabular format How do i get result in tabular format using JSP in struts Introduction to XML Introduction to XML An xml file consists of various elements. This section presents you a brief introduction to key terminologies used in relation to xml... Difficult to manipulate by program code Unable to describe structures Not easy
http://www.roseindia.net/tutorialhelp/comment/58537
CC-MAIN-2014-23
refinedweb
2,339
56.25
Paper Mario: The Thousand-Year Door: Completion Guide by jamescom1 Version: 2.02 | Updated: 2005-03-11 | Original File Paper Mario: The Thousand-Year Door Only for the Nintendo GameCube Completion Guide, version 2.02 By jamescom1 There probably are errors, so don't hesitate to e-mail corrections to me. This is a guide that lists stuff (Star Pieces, Badges, other items) that you find in each area. This isn't meant to be a walkthrough. I don't list any items (such as keys) required to advance through the game. NOTE: The Checklist lists the item and how to get it. The Checklist Summary lists only the item. (Don't worry; the Table of Contents just LOOKS big.) Table of Contents Line Number -------------------------------- ----------- Checklist Summary ........................................................ 132 Chapter 1 170 Chapter 2 228 Chapter 3 260 Chapter 4 278 Chapter 5 319 Chapter 6 347 Chapter 7 385 Chapter 8 429 The Checklist ............................................................ 456 Rogueport 508 Rogueport Sewers 597 Chapter 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748 Petal Meadows 748 Petalburg 782 Path to Shhwonk Fortress 802 Shhwonk Fortress 833 Hooktail Castle 842 Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 927 Boggly Woods 927 The Great Tree 975 Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1068 Glitzville 1068 Glitz Pit 1096 Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1135 Twilight Town 1135 Twilight Trail 1169 Creepy Steeple 1214 Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1291 Keelhaul Key 1291 Pirate's Grotto 1369 Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1450 The Excess Express 1450 Riverside Station 1487 Poshley Heights 1534 Poshley Sanctum 1565 Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1582 Path to Fahr Outpost 1582 Fahr Outpost 1608 The Moon 1632 X-Naut Fortress 1663 Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1717 Palace of Shadow 1717 Pit of 100 Trials ........................................................ 1809 Summary 1835 Bonetail 2397 Trouble Center ........................................................... 2420 Pianta Parlor ............................................................ 2481 Prizes 2494 Slots 2538 Plane Game 2564 Paper Game 2599 Tube Game 2619 Boat Game 2658 Lahla 2679 Super Luigi RPG: Legend of the Marvelous Compass ........................ 2738 After Chapter 1 . . . . . . . . . . . . . . . . . . . . . . . . . 2759 Waffle Kingdom Letter 2769 After Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . . 2798 Rumblebump Volcano 2805 Blooey 2832 After Chapter 3 . . . . . . . . . . . . . . . . . . . . . . . . . 2843 Plumpbelly Village 2851 Jerry 2879 After Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . 2889 Circuit Break Island 2896 Torque 2928 After Chapter 5 . . . . . . . . . . . . . . . . . . . . . . . . . 2937 Jazzafrazz Town 2945 Hayzee 2974 After Chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . 2982 Rapturous Ruins 2990 Screamy 3018 After Chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . 3024 Hatesong Tower 3033 Blooey 3072 After Chapter 8 . . . . . . . . . . . . . . . . . . . . . . . . . 3080 Super Luigi Book 3087 The Legend of Rogueport .................................................. 3102 The Fearsome Demon 3111 The Crystal Stars 3121 Dragons and Dungeons 3128 The Hero Who Arose 3137 The Wise Goomba 3146 The Stalwart Koopa 3153 The Four Heroes 3163 The Duel With the Demon 3171 The Demon Sealed Within 3181 The Demon's Curse 3191 The Great Tree and Punies 3201 The Boo Heroine's Last Days 3210 The Pirate King Cortez 3215 The Toad Hero's Final Days 3223 All Becomes Legend 3231 The Magical Map 3241 Tips ..................................................................... 3251 Efficient ways to make money 3255 Efficient ways to win piantas 3296 Fast ways to earn Star Points 3319 Amazy Dayzee 3348 Good recipes to make (with Cookbook) 3388 Good recipes to make (without Cookbook) 3510 Danger Mario 3575 Yoshi Colors 3626 The Lovely Howz of Badges 3686 Version & Contact ........................................................ 3739 Credits 3768 Legal 3783 END OF FILE ______________________________________________________________ 3797 =============================================================================== CHECKLIST SUMMARY ------------------------------------------------------------------------------- Rogueport Star Pieces: 18 ****************** Shine Sprites: 5 ***** Badges: 2 ** Double Dip HP Drain Items: (none) Other: Trouble Center backdoor Rogueport Sewers Star Pieces: 13 ************* Shine Sprites: 8 ******** Badges: 9 ********* Damage Dodge Defend Plus Defend Plus P Flower Saver P FP Plus Happy Heart P Pretty Lucky Soft Stomp Spike Shield Items: Fire Flower Mushroom Other: A cracked column blocking the path Chet Rippo (switch stats) Merlee (helpful "curses") Merluvlee (locates Star Pieces/Shine Sprites) Petal Meadows Chapter 1 Star Pieces: 2 ** "CASTLE AND DRAGON" Shine Sprites: 0 Badges: 2 ** Close Call Happy Heart Items: Fire Flower Horsetail (infinite) Mushroom Mushroom Mystery Other: Coin Block Petalburg Star Pieces: 2 ** Shine Sprites: 0 Badges: 1 * Mega Rush P Items: Turtley Leaf (infinite) Path to Shhwonk Fortress Star Pieces: 1 * Shine Sprites: 0 Badges: 0 (none) Items: Fire Flower Inn Coupon POW Block POW Block Shhwonk Fortress Star Pieces: 0 Shine Sprites: 0 Badges: 1 * Multibounce Items: (none) Hooktail Castle Star Pieces: 5 ***** Shine Sprites: 3 *** Badges: 5 ***** Attack FX B (see Trouble Center) Attack FX R HP Plus Last Stand P Power Bounce Items: Honey Syrup Life Shroom Mushroom Other: Up Arrow Boggly Woods Chapter 2 Star Pieces: 4 **** "THE GREAT BOGGLY TREE" Shine Sprites: 1 * Badges: 3 *** P-Down, D-Up P Quake Hammer Super Appeal P Items: Honey Syrup Inn Coupon Sleepy Sheep Volt Shroom The Great Tree Star Pieces: 6 ****** Shine Sprites: 4 **** Badges: 4 **** Charge Damage Dodge P FP Plus Shrink Stomp Items: Dizzy Dial Mushroom Mushroom (infinite) Mystic Egg (infinite) Power Punch Thunder Rage Ultra Shroom Other: Hidden shop Glitzville Chapter 3 Star Pieces: 5 ***** "OF GLITZ AND GLORY" Shine Sprites: 1 * Badges: 1 * Power Plus P Items: Inn Coupon Glitz Pit Star Pieces: 5 ***** Shine Sprites: 1 * Badges: 3 *** Last Stand Charge P HP Plus P Items: Ice Storm Twilight Town Chapter 4 Star Pieces: 3 *** "FOR PIGS THE BELL TOLLS" Shine Sprites: 0 Badges: 1 * Defend Plus Items: Boo's Sheet Inn Coupon Jammin' Jelly Life Shroom Peachy Peach (infinite) Shooting Star Twilight Trail Star Pieces: 2 ** Shine Sprites: 1 * Badges: 1 * Hammer Throw Items: Earth Quake Super Shroom Other: Coin Blocks Creepy Steeple Star Pieces: 5 ***** Shine Sprites: 3 *** Badges: 5 ***** Flower Saver Ice Smash Lucky Start Power Plus Tornado Jump Items: Golden Leaf (infinite) Mr. Softener Ultra Shroom Other: Coin Block Cookbook Keelhaul Key Chapter 5 Star Pieces: 6 ****** "KEY TO PIRATES" Shine Sprites: 2 ** Badges: 2 ** Ice Power Head Rattle Items: Coconut (infinite) Courage Shell Inn Coupon Jammin' Jelly Keel Mango (infinite) Mini Mr. Mini Spite Pouch Thunder Rage Whacka Bump (x8) Other: Coin Block Pirate's Grotto Star Pieces: 4 **** Shine Sprites: 5 ***** Badges: 2 ** P-Down, D-Up Defend Plus P Items: Ruin Powder The Excess Express Chapter 6 Star Pieces: 5 ***** "3 DAYS OF EXCESS" Shine Sprites: 2 ** Badges: 0 (none) Items: Dried Shroom Mushroom Other: 30 coins Riverside Station Star Pieces: 1 * Shine Sprites: 2 ** Badges: 3 *** P-Up, D-Down HP Plus Close Call P Items: Dried Shroom Thunder Rage Poshley Heights Star Pieces: 4 **** Shine Sprites: 1 * Badges: 1 * HP Drain P Items: Inn Coupon Poshley Sanctum Star Pieces: 0 Shine Sprites: 1 * Badges: 1 * L Emblem Items: (none) Path to Fahr Outpost Chapter 7 Star Pieces: 3 *** "MARIO SHOOTS THE MOON" Shine Sprites: 1 * Badges: 2 * Double Dip P HP Plus P Items: (none) Fahr Outpost Star Pieces: 3 *** Shine Sprites: 1 * Badges: 0 (none) Items: Inn Coupon Space Food (infinite) The Moon Star Pieces: 1 * Shine Sprites: 0 Badges: 0 (none) Items: Courage Shell Ruin Powder Stopwatch Volt Shroom X-Naut Fortress Star Pieces: 2 ** Shine Sprites: 0 Badges: 2 ** Feeling Fine Feeling Fine P Items: HP Drain Sleepy Sheep Super Shroom Ultra Shroom Other: Cog 8-bit Mario Palace of Shadow Chapter 8 Star Pieces: 0 "THE THOUSAND-YEAR DOOR" Shine Sprites: 0 Badges: 2 ** All or Nothing P-Up, D-Down P Items: Boo's Sheet Jammin' Jelly Jammin' Jelly Jammin' Jelly Life Shroom Life Shroom Life Shroom Point Swap Repel Cape Shooting Star Shooting Star Shooting Star Stopwatch Thunder Rage Ultra Shroom Ultra Shroom Ultra Shroom =============================================================================== THE CHECKLIST ------------------------------------------------------------------------------- It's hard to outline every single room of some places, especially if they are non-linear such as Rogueport Sewers. So, not only are my directions slightly confusing, but also my locations may not coincide with Ms. Mowz's ability to sniff out item locations. I just thought I'd let you know... Things I mention: Blocks containing items Coin Blocks Invisible blocks Star Pieces Badges Shine Sprites Things I skip: Coins hidden in bushes Required items (such as keys) On the very left side are symbols for what is at that location. __ /_/ Star Piece _ (_) Badge + Shine Sprite ! Item, Other (coins, special items, secrets) I list any requirements to the left of the description of the location. [ SUPER BOOTS ] = Use Super Jump to flip over a hidden panel [ ULTRA BOOTS ] = Use Spring Jump to jump sky-high [ SUPER HAMMER ] = Spin the hammer to break giant yellow blocks [ ULTRA HAMMER ] = Use the hammer to break small and giant gray blocks [ PLANE MODE ] = Change into Plane Mode to fly across chasms [ PAPER MODE ] = Change into Paper Mode to fit between narrow bars [ TUBE MODE ] = Change into Tube Mode to fit in small spaces [ BOAT MODE ] = Change into Boat Mode to sail across water In addition, you may also need the ability of a partner; I list that as well. To reiterate, when you see [ SUPER BOOTS ], you know to use the Spin Jump to flip the hidden panel. Then I won't say there's a hidden panel at that spot because [ SUPER BOOTS ] implies that there is a hidden panel. /-------------/------------------------------- / ROGUEPORT / -------------------------------/-------------/ 18 Star Pieces, 2 Badges, 5 Shine Sprites -- Rogueport Harbor -- __ /_/ [ SUPER BOOTS ] Star Piece near the stairs _ (_) [ BOAT MODE ] HP Drain badge in a chest. On the right side of this area is a Boat Panel. Use Boat Mode to sail to a hidden alcove on the left side, where the badge awaits. __ /_/ [ BOAT MODE ] Star Piece behind some barrels near the HP Drain badge -- Rogueport Square (also called Rogueport Plaza) -- __ /_/ [ SUPER BOOTS ] Star Piece near the entrance from Rogueport Harbor __ /_/ Along the right wall, there's a couple of brown boxes and barrels. A Star Piece is behind them. __ /_/ On top of Zess T.'s house is a Star Piece. It's on the rear part of the roof. __ /_/ [ SUPER BOOTS ] Behind Zess T.'s house is a Star Piece. __ /_/ Behind the inn is a door to a house that has a Star Piece inside. -- Rogueport East Side -- __ /_/ Star Piece behind Prof. Frankly's house. There are a few crates tucked away in an alley back there. On top of them is a Star Piece. __ /_/ [ SUPER BOOTS ] Star Piece right in front of Prof. Frankly's house __ /_/ [ YOSHI ] A Star Piece is behind the chimney on top of Admiral Bobbery's house. His house is between Prof. Frankly's house and the Trouble Center. + There's a Shine Sprite in the back room of Admiral Bobbery's house. + [ YOSHI ] A Shine Sprite is on top of Ishnail's hangout. Ishnail is the leader of the Robbos. __ /_/ [ PAPER MODE ] Right next to Ishnail's front door is a couple of crates and a barrel. Hiding among them is a Star Piece. + [ YOSHI ] Across the stream from Ishnail's place is a Shine Sprite. __ /_/ [ SUPER BOOTS ] On top of Garf's house is a hidden panel with a Star [ YOSHI ] Piece. Garf's house is on the right side of this area. _ (_) [ BOAT MODE ] Double Dip badge in the water in front of the Trouble Center. To get there, use the Boat Panel near Ishnail's house, and sail to the chest with the badge. ! [ FLURRIE ] There's a secret entrance on the rear side of the Trouble Center. Use Flurrie to uncover the back door. -- Rogueport West Side -- __ /_/ As soon as you enter from the right side, walk down. A Star Piece is hiding behind the short wall. __ /_/ There is a Star Piece behind the tall green pipe near the fountain. __ /_/ [ SUPER BOOTS ] Star Piece right in front of the Pianta Parlor __ /_/ All the way on the left side is a gray...trashcan, or something. Check behind it for a Star Piece. + [ BOBBERY ] Shine Sprite behind a cracked wall next to the shop on the left side of west Rogueport + [ TUBE MODE ] Go into the house on the right side of this area (it has green wallpaper inside). In the corner on the second floor is a small space where Mario can fit with Tube Mode. A Shine Sprite is behind there. -- Rogueport Station -- __ /_/ A Star Piece is hiding right behind the pipe that leads to the blimp. __ /_/ [ SUPER BOOTS ] Star Piece on the train platform all the way to the left /--------------------/---------------------------- / ROGUEPORT SEWERS / ---------------------------/--------------------/ 13 Star Pieces, 9 Badges, 8 Shine Sprites // The first room is down the pipe that's in front of Prof. Frankly's house. // There are four pipes in this room. ! [ BOBBERY ] Chet Rippo is in the background. To get there, have Bobbery blow up the cracked wall that's in the left side of the room. The pipe behind it will lead to Chet Rippo. __ /_/ [ SUPER BOOTS ] Star Piece in front of the moving platform ! [ PAPER MODE ] Merlee is in a house in the background. To get there, go down the rightmost pipe in this room. // Go through the doorway on the right side of the room. // In this room, there's a lot of water and a Boat Panel. // A pipe to Petal Meadows is in this room. + [ BOAT MODE ] Shine Sprite on the right side of the room. Use Boat Mode. _ (_) [ ULTRA BOOTS ] Defend Plus P badge in a chest. Use Spring Jump to grab [ BOBBERY ] the bar, then go left and bomb the wall to get the badge. __ /_/ [ ULTRA BOOTS ] Star Piece in a house in the background. Use Spring Jump to grab the bar, then go right until you reach the end, where a pipe will take you into the background. // Return to the first room. Go down the pipe to the left of the moving // platform. In this room, there's some water flowing at the bottom. ! Mushroom inside a yellow question block ! Fire Flower inside a yellow question block _ (_) [ PAPER MODE ] Spike Shield badge in a chest inside a booby-trapped room. [ VIVIAN ] Use Paper Mode to get to the doorway behind the bars. Use Vivian to get through the spike-filled room. // Go through the door on the left side. // In this room are pipes leading to the Great Tree and Petalburg. + [ SUPER HAMMER ] Shine Sprite on a high ledge. You have to get rid of the huge yellow block using the Super Hammer, first. // Return to the previous room, and take the pipe down. // In this room, there's a staircase leading up to an Airplane Panel. _ (_) [ FLURRIE ] Happy Heart P badge in a chest underneath the stairs. __ /_/ Star Piece alongside the green pipe. (If you have yet to destroy the giant yellow block, the Star Piece is between that and the green pipe.) _ (_) Pretty Lucky badge in an invisible block. Here's the easy way to find it. Walk to the small crack in the wall next to the bars. Then walk straight down until you hit the wall, then jump up. __ /_/ [ SUPER BOOTS ] Star Piece past the doorway in the top-right corner. It's right in front of the black chest. // Use Paper Mode to go through the bars blocking the door. // In this room is a pipe leading to Boggly Woods. _ (_) Damage Dodge badge on a high ledge on the left side of the room. In the hidden passageway, walk left instead of right to walk through a secret passageway that leads to the badge. __ /_/ [ SUPER BOOTS ] Star Piece in the right room near the pipe // Return to the previous room. Go through the doorway on the left side of that room. You are now in the same room as the Thousand-Year Door. + [ PAPER MODE ] Shine Sprite on a high ledge on the left side of the room __ /_/ [ SUPER BOOTS ] Star Piece near the bottom-middle of the room // Go through the doorway on the left side of the room. // In this room is the entrance to the Pit of 100 Trials. __ /_/ Star Piece behind the stairs // Return to the first room. Go through the doorway on the left side. // In this room is an underground town-like area. ! Merluvlee inside the rightmost building. She can tell you the locations of any remaining Star Pieces or Shine Sprites. ! [ BOBBERY ] There's a big column that has fallen over, blocking the path. Have Bobbery blow up the cracked column to open up the path. __ /_/ Star Piece behind a pedestal in the upper-left corner _ (_) Soft Stomp badge in a chest in the water in the lower-left corner __ /_/ Star Piece among the fallen columns in the lower-right corner __ /_/ Star Piece behind a pedestal in the upper-right corner + [ ULTRA BOOTS ] Shine Sprite above the pedestal in the upper-right corner. Use Spring Jump in the upper-middle part of the room to grab the bar overhead, then head to your right. __ /_/ [ SUPER BOOTS ] Star Piece in the second house from the left (this is Herb T's cola bar). // Go through the doorway on the left side of the room. // In this room are the pipes to Twilight Town and Fahr Outpost. __ /_/ Star Piece in the corner of the L-shaped wall in the middle of the room __ /_/ [ YOSHI ] Star Piece in the background. Jump into the green pipe on the left side of the room, and jump across the platforms. + Shine Sprite on a ledge on the left side of the room _ (_) [ ULTRA BOOTS ] Flower Saver P badge in a chest. On the left side of the room is a red X on the floor. Use Spring Jump there. // Go down through the pipe in the right half of the room. // In this room, there is water flowing near the bottom. ! Slow Shroom inside a yellow question block ! Gradual Syrup inside a yellow question block ! [ FLURRIE ] There's a hidden pipe. Use Flurrie to uncover the pipe. // There's a pipe leading down to the Pit of 100 Trials entrance. // To the left of that pipe is a hidden passageway leading to a Boat Panel. // Use the Boat Panel on the left side of the room and sail to the right. // In the room you finally end up in, there are a whole bunch of Spanias. + Shine Sprite + Shine Sprite again + [ ULTRA BOOTS ] Shine Sprite high in the air _ (_) [ YOSHI ] Defend Plus badge on a high ledge. Use Yoshi to get on the [ KOOPS ] moving platform, then use Koops to retrieve the badge. // Sail back to the previous room. Go through the doorway to the right. // In this room are pipes leading to Poshley Heights and Keelhaul Key. _ (_) [ ULTRA HAMMER ] FP Plus badge in a chest. You have to get rid of the huge gray block using the Ultra Hammer, first. /-----------------/----------------------------- / PETAL MEADOWS / Chapter 1 -----------------------------/-----------------/ 2 Star Pieces, 2 Badges -- first area with a castle in the background -- __ /_/ Star Piece up in the leftmost tree. Hit the tree with your hammer. ! Mushroom in the second tree from the left ! Mushroom inside a yellow question block -- next area with patches of yellow flowers and a tall green pipe -- _ (_) Close Call badge inside a red question block _ (_) [ KOOPS ] Happy Heart badge way up in the air. Use Koops to retrieve it. ! Coin Block. Hit the brown block quickly to gain up to ten coins. ! Horsetail found by whacking the rightmost blue-striped pole. Can be obtained infinite times by reentering the area. -- final area with a bridge over the river -- __ /_/ Star Piece in the background. Go down green pipe and walk right. ! Mystery in a bush to the right of the bridge ! Fire Flower inside a yellow question block /-------------/------------------------------- / PETALBURG / Chapter 1 -------------------------------/-------------/ 2 Star Pieces, 1 Badge -- west Petalburg -- __ /_/ [ SUPER BOOTS ] Star Piece in front of the Bub-ulb -- east Petalburg -- ! Turtley Leaf in bushes in Mayor Kroop's front yard. Can be obtained infinite times by reentering the area. _ (_) [ PAPER MODE ] Mega Rush P badge behind a fence by Mayor Kroop's house. __ /_/ [ SUPER BOOTS ] Star Piece near the flowers in the lower-right corner /----------------------------/------------------------ / PATH TO SHHWONK FORTRESS / Chapter 1 -----------------------/----------------------------/ 1 Star Piece -- path between Petalburg and the blue-colored building -- __ /_/ Star Piece in the leftmost bush ! POW Block inside a yellow question block -- inside the blue-colored building -- (no items) -- path between the blue-colored building and the red-colored building -- ! POW Block in a bush on the right side of the area -- inside the red-colored building -- (no items) -- path between the red-colored building and the main Shhwonk Fortress -- ! Fire Flower inside a yellow question block ! Inn Coupon near yellow question block, partially obscured by a short wall /--------------------/---------------------------- / SHHWONK FORTRESS / Chapter 1 ---------------------------/--------------------/ 1 Badge _ (_) Multibounce badge inside a red question block /-------------------/---------------------------- / HOOKTAIL CASTLE / Chapter 1 ----------------------------/-------------------/ 5 Star Pieces, 5 Badges, 3 Shine Sprites // Right outside the castle, with the broken bridge. _ (_) [ KOOPS ] HP Plus badge under the bridge. Use Koops to retrieve it. // The first room inside Hooktail Castle. _ (_) Power Bounce badge inside a red question block // The next room has bars in the back and a letter from Kolorado's father. __ /_/ [ PAPER MODE ] Star Piece behind the bars on the left side of the room [ SUPER BOOTS ] // The next room has yellow and small purple blocks. + Shine Sprite out in the open __ /_/ [ KOOPS ] Star Piece. Ride the purple block upward and go right. __ /_/ [ KOOPS ] Star Piece. Ride the yellow block upward and jump to the left. NOTE: An alternate way is to proceed until you get to the area where you jump out a window. Fall down one of the gaps instead of jumping out the window to land on the ledge with this Star Piece. // The next room has a big green block. (no items) // Take the door to the right. This room has a red switch that opens bars. _ (_) [ PAPER MODE ] Attack FX R badge behind some bars // Go right, past the black chest, into the room that had the falling ceiling. ! [ BOBBERY ] The Up Arrow is past the cracked wall in the room that had the falling ceiling. Have Bobbery blow up the cracked wall. // Go back to the room with the big green block, ride it upward, and go through // the door to the left. __ /_/ Star Piece. After jumping out the window, walk to the right. // Keep going left, through the door, to a room with another big green block. ! Life Shroom underneath left platform after riding big green block up. Jump down from above to reach the Life Shroom. You can also use Koops to snatch it while riding the block upward. // At the top of the room, go through the door on the left. ! Mushroom inside a chest ! Honey Syrup inside a chest + Shine Sprite near the Mushroom and Honey Syrup // Go to the right, past two doors. Use the yellow block to reach the ceiling. __ /_/ Star Piece near the ceiling in the rear to the right // Use Plane Mode to reach the platform to the right, and go through the door. _ (_) Last Stand P badge. Drop the big yellow block, and jump down to nab the badge. // (If you went for the badge, then you'll have to get back to the top again.) + Shine Sprite right before the door that takes you outside to the top of the castle // Inside Hooktail's room _ (_) [ FLURRIE ] Attack FX B badge where Hooktail used to be. After clearing Chapter 4, go to the Trouble Center and accept the "Elusive badge!" trouble from "???". Return to Hooktail's room, and use Flurrie to blow at the middle of the room. /----------------/------------------------------ End of Chapter 1 / BOGGLY WOODS / Chapter 2 -----------------------------/----------------/ 4 Star Pieces, 3 Badges, 1 Shine Sprite -- first screen with Save Block, where you come out of Rogueport Sewers -- (no items) -- next screen to the right -- ! Sleepy Sheep in the leftmost tree ! Honey Syrup partially hidden by a circle of flowers next to a tree -- next screen to the right, where the Great Tree is in the background -- ! Inn Coupon in some grass to the right of the pipe that warps you into the background -- next screen to the right, with the Airplane Panel -- _ (_) P-Down D-Up P badge inside an invisible block over the tree stumps. Jump around the middle of the row of tree stumps to hit the hidden block. __ /_/ Star Piece on the left side of the screen on top of the tree stumps + [ KOOPS ] Shine Sprite high in the air to the left of the Airplane Panel _ (_) Quake Hammer badge inside a red question block -- next screen to the right, where Flurrie's house is in the background -- __ /_/ Star Piece in one of the trees on the left side of the area. Use your hammer to knock it down. ! Volt Shroom behind the fence near the Recovery Block __ /_/ Star Piece behind the fence to the left of the pipe -- inside Flurrie's house -- _ (_) Super Appeal P badge in a chest inside Flurrie's room __ /_/ [ SUPER BOOTS ] Star Piece inside Flurrie's room /------------------/----------------------------- / THE GREAT TREE / Chapter 2 ----------------------------/------------------/ 6 Star Pieces, 4 Badges, 4 Shine Sprites // Right outside the Great Tree, has a couple of small waterfalls on the sides. _ (_) FP Plus badge on the right side of the area, hidden by some falling water // The first room inside the Great Tree, with the Recovery and Save Blocks. ! Mystic Egg from Petuni. Play her Stump Petuni game and let her win. Ask her "Mario likes which person the most?", and she'll give you an egg. Can be obtained infinite times by leaving the Boggly Woods area and coming back. Appears here only after completing Chapter 2. // Go up the pipe. This room has a pedestal with a "10" on it. __ /_/ [ SUPER BOOTS ] Star Piece on the right side of the room // Go up the next pipe. ! Power Punch in the bush in the lower-right corner of the room // Go all the way up to the top level, where the cells are. __ /_/ [ SUPER BOOTS ] Star Piece inside the blue cell // Go in the room to the left of the cells ! Ultra Shroom in a chest ! Mushroom from a Jabbi baby. Behind a bush on the left side of the room is a hiding Jabbi baby. Talk to it to receive a Mushroom. Can be obtained infinite times by leaving the Boggly Woods area and coming back. Appears here only after completing Chapter 2. // Return to the first room. Go into the room to the right. // This room has bubbles that float upwards. + Shine Sprite in the bottom-right corner of the room ! Thunder Rage in a bush in the bottom-right part of the room // Next room down the pipe + [ FLURRIE ] Shine Sprite over a large platform. Blow away the object [ PLANE MODE ] covering the Airplane Panel, then fly to the Shine Sprite. // Next room down the pipe; this room has a zigzag-like path _ (_) Damage Dodge P badge in a red question block. Shoot out Koops under the red block to hit a hidden coin block, with which you can reach the badge. __ /_/ Star Piece hidden in one of the bushes at the bottom of the room ! [ FLURRIE ] At the bottom of the room on the left side, use Flurrie to uncover the hidden shop in the Great Tree. // Room to the left of Crump's cage trap __ /_/ Star Piece hiding behind a pipe // Room right under Crump's cage trap __ /_/ Star Piece behind the pipe // From the room where you got the Super Boots, go out, then go down the hole. _ (_) Charge badge to the left of where you fell + Shine Sprite near where you fell // Two rooms where the top room drained water into the bottom room _ (_) Shrink Stomp badge in a chest after draining the top room ! Dizzy Dial on the other side of the stairs near the Shrink Stomp + Shine Sprite in the bottom room; step on the lilies to reach // The last room with the Save Block and Recovery Block before the room where // the Crystal Star's held. ! Mushroom in one of the bushes // In the room where the Crystal Star's held, take the pipe on the right side. // You'll emerge in a small room. __ /_/ Star Piece in one of the bushes /--------------/------------------------------- End of Chapter 2 / GLITZVILLE / Chapter 3 ------------------------------/--------------/ 5 Star Pieces, 1 Badge, 1 Shine Sprite -- main area of Glitzville, outside the Glitz Pit -- + Shine Sprite near the front doors to the Glitz Pit. Swing your hammer under the Shine Sprite to hit a hidden block. Jump on top of the block to reach the Shine Sprite. ! Inn Coupon next to the red sign in front of the Fresh Juice Shop _ (_) Power Plus P badge in a chest on top of the Fresh Juice Shop __ /_/ Star Piece under the Rawk Hawk poster on top of the Fresh Juice Shop. Use Koops to retrieve it. __ /_/ Star Piece behind the bar inside the Fresh Juice Shop __ /_/ Star Piece behind the phone booth in the lower-left corner of the area __ /_/ Star Piece behind the green plants right in front of the Glitz Pit doors __ /_/ [ SUPER BOOTS ] Star Piece near the southern end of the area /-------------/------------------------------- / GLITZ PIT / Chapter 3 -------------------------------/-------------/ 5 Star Pieces, 3 Badges, 1 Shine Sprite -- the main lobby area -- __ /_/ [ SUPER BOOTS ] Star Piece near the bottom-left poster -- the long and narrow backstage corridor behind the Glitz Pit -- _ (_) Last Stand badge inside a large hollow blue box -- the red major-league locker room -- ! Ice Storm next to the row of lockers on the left side -- the storage room next to Grubba's office -- __ /_/ [ SUPER BOOTS ] Star Piece in the middle of the floor _ (_) Charge P badge among the crates on the right side + Shine Sprite in the attic above the storage room _ (_) HP Plus P badge in the attic above the storage room -- the room to the right on the second floor of the storage room -- __ /_/ Star Piece among the boxes along the right wall -- Grubba's office -- __ /_/ Star Piece behind the potted plant in the lower-left corner __ /_/ Star Piece inside one of the desk drawers /-----------------/----------------------------- End of Chapter 3 / TWILIGHT TOWN / Chapter 4 -----------------------------/-----------------/ 3 Star Pieces, 1 Badge -- west side of town -- __ /_/ Star Piece hidden around the corner of the leftmost house __ /_/ Star Piece in a bush at the bottom of the screen ! Peachy Peach in the inn. Each time you sleep at the inn, you'll find a Peachy Peach to your left when you wake up. -- east side of town -- ! Shooting Star from the person in the house on the left side. Give her an item, and she'll give you a Shooting Star before turning into a pig. Must be done before defeating Doopliss for the first time. _ (_) Defend Plus badge in a chest inside Twilight Shop's storage room ! Inn Coupon hidden behind the sign inside Twilight Shop ! Life Shroom inside Twilight Shop's storage room ! Boo's Sheet inside Twilight Shop's storage room ! Jammin' Jelly inside Twilight Shop's storage room __ /_/ Star Piece hidden behind the barrels near the lower-left corner /------------------/----------------------------- / TWILIGHT TRAIL / Chapter 4 ----------------------------/------------------/ 2 Star Pieces, 1 Badge, 1 Shine Sprite -- first screen with the brown shed -- ! Coin Block inside the brown shed -- next screen -- ! A single coin inside a yellow question block ! Super Shroom inside an invisible block. Jump on top of the previously mentioned block, and jump up to make the Super Shroom appear. ! Coin Block on the right side of the area. Hit the brown block quickly to gain ten coins. -- next screen where you have to use Tube Mode to pass the fallen tree -- __ /_/ Star Piece right next to the fallen tree __ /_/ Star Piece behind the green pipe -- entering the woods -- ! Coin Block; hit the brown block quickly to gain ten coins ! Earth Quake in a yellow question block -- the next screen with a large tree on the left side -- _ (_) Hammer Throw in a red question block -- the next screen with a large boulder in the way -- ! Invisible Coin Block to the left of the boulder (a tree in the foreground is kind of in front of it) + Shine Sprite to the right of the boulder. A tree in the foreground is completely covering it, so you may have to jump around a little. /------------------/----------------------------- / CREEPY STEEPLE / Chapter 4 ----------------------------/------------------/ 5 Star Pieces, 5 Badges, 3 Shine Sprites // Outside Creepy Steeple. There's a well near the gate. __ /_/ Star Piece just past the gate to the left ! Invisible Coin Block in the middle of the steps leading to the front door // The main room of Creepy Steeple. _ (_) [ SUPER HAMMER ] Lucky Start badge dropped by the Atomic Boo. After you free the Boos, they appear in this room. Spin your hammer to hit the Boos as they materialize around you. This will trigger the fight with Atomic Boo. // From the main room, use Tube Mode to go under the wall near the front door. + Shine Sprite _ (_) Ice Smash badge in the left chest ! Cookbook in the right chest __ /_/ Star Piece among the junk in the back // Back in the main room, push the star statue right, and go down the hole. _ (_) [ FLURRIE ] Flower Saver badge inside a hidden room. Have Flurrie blow on the rear wall to reveal a secret passageway. Go in the hidden passageway, and walk to the right to claim the badge. // Go left through the door. ! Ultra Shroom held by a Boo. Open the box, and 200 Boos should come out. // Return to the main room, and go through the door on the far wall. ! Golden Leaf up in a tree. There's a place in the fence where you can go through the fence with Paper Mode. Follow the path to the right. Hit the brown tree to obtain a Golden Leaf. Can be obtained infinite times by reentering the area. // Go to the room that has the stairs that can be moved by hitting the switches in the adjacent rooms. __ /_/ [ SUPER BOOTS ] Star Piece in the middle-right part of the room // Go back outside Creepy Steeple, and jump down the well near the gate. + Shine Sprite on the left side // Go to the right to the next room where several Buzzy Beetles are _ (_) Tornado Jump badge inside a red question block // Go right, under the gate using Vivian's Veil, and through the door. + Shine Sprite again // Go right using Tube Mode, then go down the hole. // You should be behind some windows. __ /_/ Star Piece behind the windows on the right side // Use Tube Mode and go to the left, into the room with the parrot. __ /_/ [ SUPER BOOTS ] Star Piece in the lower-right corner ! Mr. Softener inside a chest _ (_) Power Plus badge inside a chest /----------------/------------------------------ End of Chapter 4 / KEELHAUL KEY / Chapter 5 -----------------------------/----------------/ 6 Star Pieces, 2 Badges, 2 Shine Sprites -- first screen, right next to the sea on the west side of the island -- ! Whacka Bump from Whacka. Hit Whacka with your hammer to receive it. You can get only eight Whacka Bumps. __ /_/ [ SUPER BOOTS ] Star Piece a little to the north of the exit on the right -- next screen to the right, with the inn and the shop -- __ /_/ Star Piece in the water in the lower-left corner of the area __ /_/ Star Piece behind the brown rocks near the exit to the right -- next screen to the right, the beginning of the jungle -- ! Keel Mango in a tree on the left side of the area (hit with hammer). Can be obtained infinite times by reentering the area. Appears here only after completing Chapter 5. __ /_/ Star Piece in the bush at the left side of the area _ (_) Head Rattle badge in a red question block ! Courage Shell in a yellow question block near the red question block -- next screen to the right -- ! Mini Mr. Mini in a bush at the bottom of the area ! Coin in a yellow question block ! Invisible Coin Block above the previous yellow question block. Quickly hit the brown block repeatedly to gain ten coins. __ /_/ Star Piece at the bottom of the area to the right of the yellow question block. It's somewhat obstructed from view by a branch in the foreground. + [ YOSHI ] Shine Sprite in the upper-left corner of the area to the left of the yellow question block containing the Thunder Rage ! Thunder Rage in a yellow question block at the top of the area ! Jammin' Jelly in an invisible block. A little to the south of the yellow block with the Thunder Rage is a hidden block with Jammin' Jelly. It's a little bit off the edge, though, so you have to walk to the edge and spin your hammer to hit the invisible block. Bobbery's explosion works, too. NOTE: If you have no idea what I'm talking about, then it's a lot easier to get it after getting the Ultra Boots. Simply get on top of the yellow block in the center of the area (the one where you have to use Yoshi to get to it), and perform a Spring Jump. You'll go straight up into the Jammin' Jelly. -- next screen to the right, with the bridge over the water -- ! Inn Coupon behind a bush on the left side of the area ! [ YOSHI ] Coconut in a tree on an island in the background. Get to the pipe under the bridge using Yoshi. Can be obtained infinite times by reentering the area. _ (_) [ PAPER MODE ] Ice Power badge under the right side of the bridge. Use Paper Mode to slip through the bridge. + Shine Sprite on the right side of the screen hidden by a tree's leaves. -- last screen to the right, with the two rocks with blue and red mustaches -- ! Spite Pouch in the last bush right before the water __ /_/ Star Piece hidden behind a rock in the foreground /-------------------/---------------------------- / PIRATE'S GROTTO / Chapter 5 ----------------------------/-------------------/ 4 Star Pieces, 2 Badges, 5 Shine Sprites // The first room. ! Ruin Powder in the lower-left corner behind a barrel // The next room to the right, with a long fall down and some jump platforms. (no items) // The next room to the right, with spikes that pop out from the floor. + Shine Sprite over the tip of the floating boat near the left side of the room. Partially hidden by the stalactites in the foreground. __ /_/ Star Piece out in the open // The next room to the right, with a long wooden bridge over the water. (no items) // The next room to the right, with a large waterfall in the background. (no items) // The next room to the right, with some winding steps upward and a small // waterfall in the very back. + Shine Sprite at the top of the steps. From the right, use Koops to hit a hidden block underneath the Shine Sprite. // The next room to the left, with a small stream that seems to be distinctly marked for some reason. There's also a Boat Panel here. __ /_/ [ SUPER BOOTS ] Star Piece in the upper-right corner of the room _ (_) [ BOAT MODE ] Defend Plus P badge in a chest. Use Boat Mode, and go into the hole to the right. Then sail into the small waterfall. There's a secret area behind it that contains the badge. // The next room to the left, which looks like some sort of storeroom. // Use Koops or Bobbery to activate the switch from afar. + Shine Sprite on top of the barrels along the left wall __ /_/ Star Piece inside a hollow barrel near the Shine Sprite // Return to the room with some winding steps upward and a small waterfall in // the very back. Go through the door on the right at the bottom of the room. // This room is a very small room. __ /_/ [ SUPER BOOTS ] Star Piece in the middle of this small room // Proceed onward. The next room has waves rolling in the water. The room // also features spikes that come out of the wall. + [ KOOPS ] Shine Sprite to the right of the spikes // Go through the doorway to the left. This room has some flotsam. + Shine Sprite on the right side of the room. There is an invisible coin block underneath the Shine Sprite that you can hit with your hammer. // The next room to the left is pretty much just a long corridor. (no items) // The next room to the left has a couple of Boat Panels and an abandoned ship // where a black chest is. (no items) // Inside the abandoned ship _ (_) P-Down, D-Up badge behind the black chest /----------------------/--------------------------- End of Chapter 5 / THE EXCESS EXPRESS / Chapter 6 --------------------------/----------------------/ 5 Star Pieces, 2 Shine Sprites -- The orange and brown passenger car, containing rooms 003, 004, and 005 -- __ /_/ [ SUPER BOOTS ] Star Piece in the bottom-left corner of room 004 + Shine Sprite on the left side of room 005 ! Dried Shroom inside the drawer in room 005 -- The green and brown passenger car, containing rooms 001 and 002 -- ! 30 coins from Toodles. Return her Gold Ring to her to receive the coins. -- The engineer's car at the front of the train -- __ /_/ [ SUPER BOOTS ] Star Piece near the Save Block -- The dining car, which includes a shop -- __ /_/ Star Piece from Chef Shimi. Return his Galley Pot to him to receive it. __ /_/ Star Piece from the waitress. Return her Shell Earrings to receive it. -- The blue and brown passenger car, containing rooms 006, 007, and 008 -- __ /_/ Star Piece inside the drawer in room 008 + Shine Sprite from Bub. Bring him the engineer's Autograph to receive it. ! Mushroom from the conductor. Return his Blanket to him to receive it. /---------------------/--------------------------- / RIVERSIDE STATION / Chapter 6 ---------------------------/---------------------/ 1 Star Piece, 3 Badges, 2 Shine Sprites // The first room, with the elevator. _ (_) [ ULTRA BOOTS ] Close Call P badge on a high ledge. Use Spring Jump to knock it down. // The next room to the right. (no items) // Go through the door at the top of the room. // This room has a lot of spinning gears. __ /_/ Star Piece behind a last gear all the way on the right side of the room // Return to the previous room, then go through the door on the right. // This will lead you outside. ! Thunder Rage in an invisible block. Along the way, there should be a lone yellow block on the ground. Jump on top of it, then jump up. + Shine Sprite out in the open _ (_) HP Plus badge in a small alcove. In the stairs near the top door is a hole. Roll in there with Tube Mode to reach the badge. // Go through the door at the bottom-left. This room is a garbage dump with a maze just for Mario in Tube Mode. _ (_) P-Up, D-Down badge inside the maze ! Dried Shroom in one of the garbage bins // At the bottom is another door. Through that door is an abandoned office. (no items) // One more room to the left. This is the records room. + [ KOOPS ] Shine Sprite near the top of the stairs. Use Koops to get it. /-------------------/---------------------------- / POSHLEY HEIGHTS / Chapter 6 ----------------------------/-------------------/ 4 Star Pieces, 1 Badge, 1 Shine Sprite -- the first area, nearest to the Excess Express train -- _ (_) [ PAPER MODE ] HP Drain P badge in a chest. Inside Goldbob's house (the house on the left), you will find a slight discoloration on the wall. Use Paper Mode there to enter a secret room. __ /_/ Star Piece behind a lawn chair to the left of Goldbob's house __ /_/ [ SUPER BOOTS ] Star Piece in the center of the area near the Save Block __ /_/ Star Piece hidden in some shrubbery. To the right of Toodle's house (the house on the right) is some shrubbery. There's a crack in there; walk in there, and go up to snag the hidden Star Piece. -- the next area, which has a hotel -- ! Inn Coupon behind the vendor that sells Fresh Pasta __ /_/ Star Piece behind the shrubbery to the left of the house -- the last area, where Poshley Sanctum is -- + [ ULTRA BOOTS ] Shine Sprite high in the air. Use Spring Jump to get. /-------------------/---------------------------- / POSHLEY SANCTUM / Chapter 6 ----------------------------/-------------------/ 1 Badge, 1 Shine Sprite -- the "real" Poshley Sanctum -- (no items) -- the Poshley Sanctum inside the painting -- + Shine Sprite on a high ledge on the left side _ (_) L Emblem badge on a high ledge on the left side /------------------------/-------------------------- End of Chapter 6 / PATH TO FAHR OUTPOST / Chapter 7 -------------------------/------------------------/ 3 Star Pieces, 2 Badges, 1 Shine Sprite -- first screen, just coming out of the blue pipe -- __ /_/ [ SUPER BOOTS ] Star Piece to the left of the blue pipe _ (_) Double Dip P badge in an invisible block. It's directly in front of the rightmost tree. -- next screen to the right -- + Shine Sprite hidden behind a tree near the left side of the area __ /_/ Star Piece partially hidden by a tiny dead bush -- last screen to the right -- _ (_) HP Plus P badge inside a red question block __ /_/ Star Piece hidden by the wall in the foreground near the right side /----------------/------------------------------ / FAHR OUTPOST / Chapter 7 -----------------------------/----------------/ 3 Star Pieces, 1 Shine Sprite -- left half of Fahr Outpost -- __ /_/ Star Piece hidden by a wall near the bottom-left side of the area -- right half of Fahr Outpost -- ! Inn Coupon next to the steps in front of the inn ! Space Food in the inn. Each time you sleep at the inn, you'll find Space Food to your left when you wake up. __ /_/ [ SUPER BOOTS ] Star Piece a little to the left of the cannon monument __ /_/ Star Piece inside the rightmost house + Shine Sprite out in the open on the right side of the area /------------/-------------------------------- / THE MOON / Chapter 7 -------------------------------/------------/ 1 Star Piece NOTE: After completing Chapter 7, the moon will become inaccessible until after you beat the final boss, so get the Star Piece before you leave. -- first screen, with the Save Block -- ! [ BOBBERY ] Stopwatch in cracked boulder in top-left part of area -- next screen to the right -- ! [ BOBBERY ] Volt Shroom in cracked rock in middle of area -- next screen to the right, contains the X-Naut fortress in the background -- __ /_/ Star Piece hidden behind a small rock in middle of area -- next screen to the right -- ! [ BOBBERY ] Ruin Powder in cracked rock in right part of area -- next screen to the right -- ! [ BOBBERY ] Courage Shell in cracked rock in bottom part of area /-------------------/---------------------------- / X-NAUT FORTRESS / Chapter 7 ----------------------------/-------------------/ 2 Star Pieces, 2 Badges NOTE: After completing Chapter 7, the X-Naut Fortress will become inaccessible until after you beat the final boss, so get the items before you leave. -- Level 1, the top floor -- ! Super Shroom inside a yellow question block in the rightmost room -- Sublevel 1 -- _ (_) Feeling Fine badge in leftmost room (requires the Cog) _ (_) Feeling Fine P badge in leftmost room (requires the Cog) __ /_/ Star Piece in leftmost room (requires the Cog) -- Sublevel 2 -- ! Sleepy Sheep in yellow question block in leftmost room __ /_/ [ SPRING JUMP ] Star Piece; in one of the rooms, you can Spring Jump into the ceiling. A Star Piece is all the way to the left. ! [ SPRING JUMP ] Cog item; in one of the rooms, you can Spring Jump into [ PAPER MODE ] the ceiling. If you fall down the second hole from the [ KOOPS ] left, you will drop on top of a computer near the Cog. ! [ SPRING JUMP ] 8-bit Mario! In one of the rooms, you can Spring Jump [ PAPER MODE ] into the ceiling. If you fall down the rightmost hole, you'll drop into a room where you'll emerge with "8-bit" graphics! Take a look at your Mario and Party menus; even your Map has 8-bit Mario on it. Also, you can equip the L Emblem and/or the W Emblem badges to change colors. Leave the room to return to normal. -- Sublevel 3 -- ! HP Drain in yellow question block in leftmost room -- X-Naut factory (to the right of Sublevel 3) -- ! Ultra Shroom in the background all the way on the left side -- Sublevel 4 -- (no items) /--------------------/---------------------------- End of Chapter 7 / PALACE OF SHADOW / Chapter 8 ---------------------------/--------------------/ 2 Badges // Entering the first room of the Palace of Shadow (no items) // A bridge-like staircase over water ! Stopwatch near the left door. As soon as you walk in, walk up. // A winding path downward ! Shooting Star inside a yellow question block // A corridor filled with spike traps _ (_) All or Nothing badge inside a red question block // A bridge over water with bars of fire in the way ! Boo's Sheet in an invisible block. In the middle of the room is a couple of fire bars spinning around one spot. Stand on that spot and jump up. // A large room (no items) // Another winding path downward ! Ultra Shroom inside a yellow question block // Another large room ! A single coin inside a yellow question block _ (_) P-Up, D-Down P badge in a red question block ! Jammin' Jelly inside a yellow question block // Fast forward to Gloomtail's room, after defeating Gloomtail. Note that once // you use the eight Palace Keys inside the tower containing the eight riddles, // Gloomtail's room becomes inaccessible, so get these two items beforehand. ! [ BOBBERY ] Ultra Shroom inside a yellow question block. On the right wall of Gloomtail's room is a crack. Blow up the wall there to uncover a secret room with the Ultra Shroom inside. ! [ BOBBERY ] Jammin' Jelly inside a yellow question block to the right of the yellow question block containing the Ultra Shroom. // Now fast forward to the part after solving the eight riddles and defeating // Beldam, Marilyn, and Freak...I mean, Doopliss. The corridors that // originally lead to Gloomtail have now been reconfigured, so it is the // last (platforming) test before the final boss(es). ! [ SPRING JUMP ] Thunder Rage inside a yellow question block in the first hallway. Use Spring Jump to hit it. You can also use Koops to hit it. ! Repel Cape inside a yellow question block ! Shooting Star inside a chest ! [ SPRING JUMP ] Life Shroom inside a yellow question block. Again, you can use either Spring Jump or Koops to hit the block. ! Life Shroom inside a yellow question block over the spinning wheel ! A single Coin inside a yellow question block ! Point Swap inside an invisible block above the block with the single Coin ! [ PLANE MODE ] Life Shroom on top of a high pedestal. Use Plane Mode and drop when you're over the Life Shroom. ! [ PLANE MODE ] Shooting Star to the right of the Life Shroom. Use Plane Mode and drop when you're over the Life Shroom. If you're on the pedestal where the Life Shroom was, then you can also use Yoshi to hover to the right. // The room RIGHT BEFORE the showdown with the final boss. ! Ultra Shroom in a chest. Use it wisely. ! Jammin' Jelly in a chest. Use it wisely. =============================================================================== PIT OF 100 TRIALS ------------------------------------------------------------------------------- The Pit of 100 Trials is a sidequest that is accessible after you get cursed with Paper Mode in Hooktail Castle. The entrance to the Pit of 100 Trials is in the room to the left of the Thousand-Year Door. Every set of ten floors has certain enemies that you will fight randomly. At every tenth floor is an exit pipe (which leads to the entrance) and a prize. Level 10 = BADGE: Sleepy Stomp (put an enemy to sleep) Level 20 = BADGE: Fire Drive (fire damage that pierces defense) Level 30 = BADGE: Zap Tap (electrifies Mario) Level 40 = BADGE: Pity Flower (may recover 1 FP when hit) Level 50 = ITEM: Strange Sack (doubles inventory space) Level 60 = BADGE: Double Dip (Mario can use two items in one turn) Level 70 = BADGE: Double Dip P (partner can use two items in one turn) Level 80 = BADGE: Bump Attack (defeat low-level enemies automatically) Level 90 = BADGE: Lucky Day (increases evasion) Level 100 = BADGE: Return Postage (counters direct attackers) A very powerful boss guards Level 100 and the Return Postage badge, so beware. _____________________________________________________________________________ / \ | Pit of 100 Trials: An Abstract | | | | LEVEL ENEMY NAME : STATS REWARD | |-----------------------------------------------------------------------------| | LEVEL Dull Bones : 1 HP, 2 Atk, 1 Def | | 1-9 Fuzzy : 3 HP, 1 Atk, 0 Def | | Gloomba : 7 HP, 3 Atk, 0 Def | | Spania : 3 HP, 1 Atk, 0 Def | | Spinia : 3 HP, 1 Atk, 0 Def | |.............................................. Sleepy Stomp badge = LEVEL 10 | | LEVEL Cleft : 2 HP, 2 Atk, 2 Def | | 11-19 Dark Puff : 3 HP, 2 Atk, 0 Def | | Paragloomba : 7 HP, 3 Atk, 0 Def | | Pider : 5 HP, 2 Atk, 0 Def | | Pokey : 4 HP, 3 Atk, 0 Def | |................................................ Fire Drive badge = LEVEL 20 | | LEVEL Bandit : 5 HP, 2 Atk, 0 Def | | 21-29 Bob-omb : 4 HP, 2 Atk, 1 Def | | Boo : 7 HP, 3 Atk, 0 Def | | Lakitu : 5 HP, 3 Atk, 0 Def | | Spiky Gloomba : 7 HP, 4 Atk, 0 Def | | Spiny : 3 HP, 3 Atk, 3 Def | |................................................... Zap Tap badge = LEVEL 30 | | LEVEL Dark Koopa : 8 HP, 4 Atk, 2 Def | | 31-39 Flower Fuzzy : 6 HP, 3 Atk, 0 Def | | Hyper Cleft : 4 HP, 3 Atk, 3 Def | | Parabuzzy : 5 HP, 3 Atk, 4 Def | | Shady Koopa : 8 HP, 3 Atk, 1 Def | |............................................... Pity Flower badge = LEVEL 40 | | LEVEL Bulky Bob-omb : 6 HP, 4 Atk, 2 Def | | 41-49 Dark Paratroopa : 8 HP, 4 Atk, 2 Def | | Lava Bubble : 6 HP, 4 Atk, 0 Def | | Poison Pokey : 8 HP, 4 Atk, 0 Def | | Spiky Parabuzzy : 5 HP, 3 Atk, 4 Def | |.................................................... Strange Sack = LEVEL 50 | | LEVEL Badge Bandit : 12 HP, 5 Atk, 0 Def | | 51-59 Dark Boo : 8 HP, 5 Atk, 0 Def | | Ice Puff : 9 HP, 4 Atk, 0 Def | | Moon Cleft : 6 HP, 5 Atk, 5 Def | | Red Chomp : 6 HP, 5 Atk, 3 Def | |................................................ Double Dip badge = LEVEL 60 | | LEVEL Dark Craw : 20 HP, 6 Atk, 0 Def | | 61-69 Dark Lakitu : 13 HP, 5 Atk, 0 Def | | Dark Wizzerd : 10 HP, 5 Atk, 2 Def | | Dry Bones : 8 HP, 5 Atk, 2 Def | | Frost Piranha : 10 HP, 5 Atk, 0 Def | | Sky-Blue Spiny : 6 HP, 6 Atk, 4 Def | |.............................................. Double Dip P badge = LEVEL 70 | | LEVEL Chain-Chomp : 7 HP, 6 Atk, 5 Def | | 71-79 Dark Koopatrol : 25 HP, 5 Atk, 2 Def | | Phantom Ember : 10 HP, 5 Atk, 0 Def | | Swoopula : 9 HP, 4 Atk, 0 Def | | Wizzerd : 10 HP, 6 Atk, 3 Def | |............................................... Bump Attack badge = LEVEL 80 | | LEVEL Arantula : 16 HP, 7 Atk, 0 Def | | 81-89 Dark Bristle : 8 HP, 8 Atk, 4 Def | | Piranha Plant : 15 HP, 9 Atk, 0 Def | | Spunia : 12 HP, 7 Atk, 2 Def | |................................................. Lucky Day badge = LEVEL 90 | | LEVEL Amazy Dayzee : 20 HP, 20 Atk, 1 Def | | 91-99 Bob-ulk : 10 HP, 4 Atk, 2 Def | | Elite Wizzerd : 12 HP, 8 Atk, 5 Def | | Poison Puff : 15 HP, 8 Atk, 0 Def | | Swampire : 20 HP, 6 Atk, 0 Def | |.............................................................................| | LEVEL Bonetail : 200 HP, 8 Atk, 2 Def Return Postage badge | | 100 | \_____________________________________________________________________________/ Charlieton appears randomly every ten floors. He sells HP/FP restoring items as well as attack items, but his prices grow steeper the farther down you go. I list enemy names and stats on the left side. I show excerpts of Goombella's tattles on the right side (because I'm too lazy to come up with my own words; she probably describes enemies better than I ever will, anyway...). /--------------------\ | LEVELS 1 THROUGH 9 | \--------------------/ Dull Bones "Sort of a skeleton thing. It was a Koopa Troopa...once. HP: 1 X These creeps throw bones to attack. Oh, and they build Atk: 2 ++ reinforcements, too! Attacks that can strike multiple Def: 1 = Dull Bones at once are the most effective." Fuzzy "Those things suck up your HP and use it to replenish HP: 3 XXX their own! Isn't that the worst? Anyway, guard against Atk: 1 + them by pressing A the MOMENT they release you." Def: 0 Gloomba "It's stronger than a normal Goomba, so be careful." HP: 7 XXXXXXX Atk: 3 +++ Def: 0 Spania "A Spinia with spikes on its head. You oughta watch out HP: 3 XXX for the spikes on its head, but otherwise, just whale on Atk: 1 + it." Def: 0 Spinia "A totally weird creature made of thin, papery boards. Its HP: 3 XXX attacks are super-swift, but it should be pretty easy." Atk: 1 + Def: 0 /----------\ | LEVEL 10 | \----------/ Sleepy Stomp (badge) "2 FP are required to use this attack, which can make enemies sleep if executed superbly." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 10 Recover 5 HP Super Shroom 30 Recover 10 HP Honey Syrup 10 Recover 5 FP Maple Syrup 40 Recover 10 FP Fire Flower 20 3 damage + burn all enemies Thunder Rage 40 5 damage all enemies /----------------------\ | LEVELS 11 THROUGH 19 | \----------------------/ Cleft "A rock-head jerk with spikes on his noggin. Fire doesn't HP: 2 XX hurt it, but other types of items are pretty effective, Atk: 2 ++ usually." Def: 2 == Dark Puff "It's basically a tiny, mean thunderhead. Sometimes it'll HP: 3 XXX charge itself with electricity. Don't touch it when it Atk: 2 ++ does! After it charges itself, it'll totally zap you with Def: 0 lightning." Paragloomba "It's a Gloomba with wings." HP: 7 XXXXXXX Atk: 3 +++ Def: 0 Pider "Besides its normal attacks, it might spit three web-wads HP: 5 XXXXX at you consecutively." Atk: 2 ++ Def: 0 Pokey "It's a cactus ghoul that's got nasty spines all over its HP: 4 XXXX body. Pokeys attack by lobbing parts of their bodies and Atk: 3 +++ by charging at you... They can even call friends in for Def: 0 help, so be quick about taking them out." /----------\ | LEVEL 20 | \----------/ Fire Drive (badge) "5 FP are required to use this attack, which assaults all ground enemies and burns them as well." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 15 Recover 5 HP Super Shroom 45 Recover 10 HP Honey Syrup 15 Recover 5 FP Maple Syrup 60 Recover 10 FP Fire Flower 30 3 damage + burn all enemies Thunder Rage 60 5 damage all enemies /----------------------\ | LEVELS 21 THROUGH 29 | \----------------------/ Bandit "This scumbag tries to bump you and grab coins. If you HP: 5 XXXXX time your guard well when he attacks, he won't be able to Atk: 2 ++ steal anything. If a Bandit steals coins from you, defeat Def: 0 him before he flees to get your coins back." Bob-omb "It attacks by blowing itself up. A Bob-omb will get HP: 4 XXXX totally mad if you damage it. When it gets mad, it'll Atk: 2 ++ charge and explode on its next turn. THAT attack... Def: 1 = really hurts. Oh, and if it's mad, it'll blow up at the slightest contact. So don't attack directly! Attack it from a step away with a hammer or hit it with something hard, like a shell." Boo "It's everyone's favorite ghost. ...Well, most everyone... HP: 7 XXXXXXX It's nothing to write home about on the Attack side, but Atk: 3 +++ it can turn invisible. If it turns invisible, we won't be Def: 0 able to hit it, so beat it while you can see it." Lakitu "It's a member of the Koopa clan that rides on clouds. It HP: 5 XXXXX attacks by throwing Spiny Eggs. If you stomp on it when Atk: 2 ++ it's holding up a Spiny Egg, you'll take damage, so DON'T Def: 0 do it! Spiny Eggs slowly hatch into Spinies, so beat the Lakitu before fighting the Spinies." Spiky Gloomba "It's a Spiky Goomba that likes dark places. I'm sure you HP: 7 XXXXXXX know this, but try not to jump on the spike." Atk: 4 ++++ Def: 0 Spiny "Basically a spike-covered Koopa. These things have such HP: 3 XXX high Defense that you can't even hurt them when they roll Atk: 3 +++ up. So, when they go back to normal, do all the damage Def: 3 === you can, and do it quickly! If you flip them over, their Defense drops to 0. THAT'S the time to take them out." /----------\ | LEVEL 30 | \----------/ Zap Tap (badge) "Do damage to enemies that touch Mario in battle." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 20 Recover 5 HP Super Shroom 60 Recover 10 HP Honey Syrup 20 Recover 5 FP Maple Syrup 80 Recover 10 FP Fire Flower 40 3 damage + burn all enemies Thunder Rage 80 5 damage all enemies /----------------------\ | LEVELS 31 THROUGH 39 | \----------------------/ Dark Koopa "It's a bit tougher than a regular Koopa, so you won't be HP: 8 XXXXXXXX able to beat it easily. But, it DOES have the same Atk: 4 ++++ weakness as a regular Koopa. Flip it over and it's Def: 2 == helpless." Flower Fuzzy "This thing attack by boinging in and sucking out FP. Once HP: 6 XXXXXX it charges up its own FP, it uses magical attacks. Better Atk: 3 +++ beat it before it does." Def: 0 Hyper Cleft "It's basically a Cleft that uses charged-up moves. When HP: 4 XXXX it charges up, its Attack power rises to 9. Couple its Atk: 3 +++ rock-hardness with its ability to charge up... and things Def: 3 === get scary. If you're confident, you may wanna try doing Superguards to send its attacks back..." Parabuzzy "A Buzzy Beetle with wings. Fire and explosions seem to HP: 5 XXXXX have no effect, so don't bother, OK? If you flip it over, Atk: 3 +++ its Defense goes down to 0, so jump on it first." Def: 4 ==== Shady Koopa "It's yet another member of the Koopa family tree. The HP: 8 XXXXXXXX difference between them and other Koopas? They can attack Atk: 3 +++ from their backs! And, when they flip back up, their Def: 1 = Attack gets boosted and they go totally ape!" /----------\ | LEVEL 40 | \----------/ Pity Flower (badge) "When Mario takes damage, occasionally recover 1 FP." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 25 Recover 5 HP Super Shroom 75 Recover 10 HP Honey Syrup 25 Recover 5 FP Maple Syrup 100 Recover 10 FP Fire Flower 50 3 damage + burn all enemies Thunder Rage 100 5 damage all enemies /----------------------\ | LEVELS 41 THROUGH 49 | \----------------------/ Bulky Bob-omb "I think it's like other Bob-ombs...but it's huge! It's HP: 6 XXXXXX weird... It never attacks, but once its fuse is lit, Atk: 2 ++ it'll blow up on its own eventually. I don't mind it Def: 1 = taking itself out of the battle, but that explosion hurts us, too! Oh, and when it powers up, that Attack power is 8, so watch out! Fire and explosions light its fuse, so I guess setting it off early is one strategy..." Dark Paratroopa "It's strong, but otherwise just like other Paratroopas. HP: 8 XXXXXXXX It's airborne, so try to ground it first." Atk: 4 ++++ Def: 2 == Lava Bubble "It's a flame spirit. Its HP and Attack power may be HP: 6 XXXXXX different from an Ember's, but otherwise it's the same. Atk: 4 ++++ Since it is made of fire, try not to touch it, 'cause Def: 0 it'll burn you. Apparently it's vulnerable to explosions and ice attacks. Oh, and if you get hit by a flame attack, you might catch fire, so guard well." Poison Pokey "As you probably guessed, it's a poisonous Pokey. If you HP: 8 XXXXXXXX get poisoned, your HP will slowly drain, so you may want Atk: 4 ++++ to avoid that. I'm sure you can see this but they have Def: 0 spines all over, so DON'T touch them." Spiky Parabuzzy "It's a Buzzy with a spike and wings. Fire and explosions HP: 5 XXXXX don't work on Buzzies, in case you've forgotten. Atk: 3 +++ ...And this one flies in the air AND has a spike. Def: 4 ==== What a total pain." /----------\ | LEVEL 50 | \----------/ Strange Sack (item) "An item that lets you carry up to 20 items." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 30 Recover 5 HP Super Shroom 90 Recover 10 HP Honey Syrup 30 Recover 5 FP Maple Syrup 120 Recover 10 FP Fire Flower 60 3 damage + burn all enemies Thunder Rage 120 5 damage all enemies /----------------------\ | LEVELS 51 THROUGH 59 | \----------------------/ Badge Bandit "He's a Bandit who'll go after your badges. He has high HP: 12 XXXXXXXXXX Attack power and HP. He sometimes steals a badge when he XX tackles you, so use your Guard carefully." Atk: 5 +++++ Def: 0 Dark Boo "Its HP and Attack are high, but they're just like HP: 8 XXXXXXXX ordinary Boos otherwise. So, just attack it like a Atk: 5 +++++ normal Boo. Get it before it turns invisible! Def: 0 Ice Puff "It's a mean snow cloud that appears in cold areas. It HP: 9 XXXXXXXXX swoops down and uses cold breath to attack. That cold Atk: 4 ++++ breath can freeze us, so try to avoid it. Also, if we Def: 0 touch it when it's storing cold energy, we'll get hurt. They're vulnerable to fire, so let's try that, maybe." Moon Cleft "It's your basic cleft living on the moon. Defense is HP: 6 XXXXXX high, as usual... and fire attacks don't work against it. Atk: 5 +++++ If you can turn it over with an explosion, though, its Def: 5 ===== Defense goes down to 0. Red Chomp "It's a rabid, red, biting, chewing, chomping fool! Its HP HP: 6 XXXXXX is pretty low, though, so items and special moves might Atk: 5 +++++ just work..." Def: 3 === /----------\ | LEVEL 60 | \----------/ Double Dip (badge) "Wear this to become able to use two items during Mario's turn in battle. This move requires 4 FP." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 35 Recover 5 HP Super Shroom 105 Recover 10 HP Honey Syrup 35 Recover 5 FP Maple Syrup 140 Recover 10 FP Fire Flower 70 3 damage + burn all enemies Thunder Rage 140 5 damage all enemies /----------------------\ | LEVELS 61 THROUGH 69 | \----------------------/ Dark Craw "Wow, that's some serious Attack power. You don't wanna HP: 20 XXXXXXXXXX jump on it if its spear is pointing up. 'Cause that... XXXXXXXXXX would hurt." Atk: 6 ++++++ Def: 0 Dark Lakitu "It rides a rain cloud. It attacks by throwing pipes at HP: 13 XXXXXXXXXX you. If it's holding up a pipe when you jump on it, XXX you'll get hurt. And sometimes the pipes it throws turn Atk: 5 +++++ into Sky-Blue Spinies. If you only attack the Spinies, Def: 0 you'll never win, so go after the Dark Lakitu!" Dark Wizzerd "It's a part-machine, part-organic, centuries-old thing. HP: 10 XXXXXXXXXX It uses magic to attack and to alter your condition, so Atk: 5 +++++ stay on guard. If there's only one left, it'll multiply Def: 2 == itself to confuse you." Dry Bones "It's a former Koopa whose spirit animates its bones. When HP: 8 XXXXXXXX its HP goes down to 0, it collapses into a pile, but Atk: 5 +++++ it'll eventually rise again. Fire and explosions will put Def: 2 == a permanent end to it getting back up, though. A Dry Bones will sometimes build friends if it feels it's outnumbered. If you don't take them all out close together, they'll just keep coming back." Frost Piranha "It's a cool customer with strong ice powers. Its biting HP: 10 XXXXXXXXXX attack sometimes freezes us, so try to immobilize it Atk: 5 +++++ first. It's weak against fire attacks, too, so use them Def: 0 as well." Sky-Blue Spiny "It appeared from a pipe thrown by the Dark Lakitu. It'll HP: 6 XXXXXX totally charge at you! Sometimes it balls up to defend Atk: 6 ++++++ and store energy for an attack. If you can, beat it and Def: 4 ==== any buddies it may have with a special attack." /----------\ | LEVEL 70 | \----------/ Double Dip P (badge) "Wear this to allow your partner to use two items in one turn in battle. This move requires 4 FP." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 40 Recover 5 HP Super Shroom 120 Recover 10 HP Honey Syrup 40 Recover 5 FP Maple Syrup 160 Recover 10 FP Fire Flower 80 3 damage + burn all enemies Thunder Rage 160 5 damage all enemies /----------------------\ | LEVELS 71 THROUGH 79 | \----------------------/ Chain-Chomp "It's body is hard, so most attacks won't do much. Plus, HP: 7 XXXXXXX you can't damage it with fire and ice attacks. You can Atk: 6 ++++++ freeze it, though. Luckily, it has low HP, so you could Def: 5 ===== take it down with a special move or an item." Dark Koopatrol "These guys just totally ooze toughness, don'tcha think? HP: 25 XXXXXXXXXX After it charges up power, its next attack will be XXXXXXXXXX devastating. Try to survive it." XXXXX Atk: 5 +++++ Def: 2 == Phantom Ember "It's an angry spirit born of hatred and confusion. If it HP: 10 XXXXXXXXXX attacks you with spirit flames, you'll catch on fire." Atk: 5 +++++ Def: 0 Swoopula "An airborne, bloodsucking, batlike thing. As if losing HP HP: 9 XXXXXXXXX wasn't bad enough, this little creep adds yours to its Atk: 4 ++++ own!" Def: 0 Wizzerd "It's a part-machine, part-organic, centuries-old thing. HP: 10 XXXXXXXXXX It uses magic to attack, heal, and alter your condition, Atk: 6 ++++++ so stay on guard." Def: 3 === /----------\ | LEVEL 80 | \----------/ Bump Attack (badge) "Bump into weak foes to defeat them without battling." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 45 Recover 5 HP Super Shroom 135 Recover 10 HP Honey Syrup 45 Recover 5 FP Maple Syrup 180 Recover 10 FP Fire Flower 90 3 damage + burn all enemies Thunder Rage 180 5 damage all enemies /----------------------\ | LEVELS 81 THROUGH 89 | \----------------------/ Arantula "It's a spiderlike creature that lives deep underground. HP: 16 XXXXXXXXXX It'll spit web-wads at you. Sometimes it even attacks several times in a row." Atk: 7 +++++++ Def: 0 Dark Bristle "It's an ancient creature made of rock. You can't jump on HP: 8 XXXXXXXX it because of its spikes, and you can't approach due to Atk: 8 ++++++++ its spears. AND its Defense is high. You'd better take it Def: 4 ==== out with special attacks or items." Piranha Plant "I think this is the strongest type of them all. It's HP: 15 XXXXXXXXXX Attack power is absurdly high... It may look like a XXXXX normal Piranha Plant, but don't be fooled! Atk: 9 +++++++++ It's super-tough!" Def: 0 Spunia "Its body is made up of springy discs. It may not look HP: 12 XXXXXXXXXX like much, but it's pretty tough." XX Atk: 7 +++++++ Def: 2 == /----------\ | LEVEL 90 | \----------/ Lucky Day (badge) "When Mario's attacked, cause enemies to miss more often." Charlieton Item Cost What it does ------------- ---- ------------ Mushroom 50 Reoover 5 HP Super Shroom 150 Recover 10 HP Honey Syrup 50 Recover 5 FP Maple Syrup 200 Recover 10 FP Fire Flower 100 3 damage + burn all enemies Thunder Rage 200 5 damage all enemies /----------------------\ | LEVELS 91 THROUGH 99 | \----------------------/ Amazy Dayzee "This mystical Dayzee is like, the rarest thing ever. HP: 20 XXXXXXXXXX Since it has such high HP and runs away really quickly, XXXXXXXXXX it's almost impossible to beat. Plus, its lullaby has Atk: 20 ++++++++++ massive Attack power." ++++++++++ Def: 1 = Bob-ulk "It won't attack, but once its fuse is lit, it'll explode HP: 10 XXXXXXXXXX after a while. So the problem is...how to beat it before Atk: 4 ++++ it goes off. I mean, its bomb attack has a power of 16! Def: 2 == That's no joke. Seriously, watch out for that. Or you could just set it off early with fire or explosions." Elite Wizzerd "This is the top of the heap for half-machine organisms. HP: 12 XXXXXXXXXX You can probably guess this, but it uses various magic XX moves in battle. And, if it's alone, it'll create Atk: 8 ++++++++ illusions of itself. It has no real weakness. So just Def: 5 ===== use whatever you've got to beet it, OK?" Poison Puff "Basically just a puff of poisonous air. Its poison-gas HP: 15 XXXXXXXXXX attack is 10! These things charge you, but they also save XXXXX up toxins and poison you with them. Plus, you can't touch Atk: 8 ++++++++ them when they're saving up toxins or you'll get hurt." Def: 0 Swampire "It's a feared health-sucker that hides in the darkness. HP: 20 XXXXXXXXXX It sucks health from its prey to add to its own HP. If XXXXXXXXXX you let it feast on you, its HP will get really high." Atk: 6 ++++++ Def: 0 /-----------\ | LEVEL 100 | \-----------/ Bonetail HP: 200 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Atk: 8 ++++++++ Def: 2 == Goombella: "He has various breaths that might confuse us or put us to sleep. When his HP gets low, he'll recover...or reanimate, as the case may be. He's probably stronger than the last boss, seriously!" Reward: Return Postage (badge) "Make direct-attackers take 1/2 the damage they do." The Return Postage badge is like a permanent Spite Pouch, if you are familiar with that item. Many players seem to find the badge useless and a worthless prize for clearing the difficult Pit of 100 Trials. If nothing else, you can always sell the badge to the Lovely Howz of Badges for 500 coins. =============================================================================== TROUBLE CENTER ------------------------------------------------------------------------------- The Trouble Center is a place in east Rogueport where Mario can solve troubles and possibly receive a reward in return. More troubles are accessible after completing every chapter. _____________________________________________________________________________ / \ | Trouble Center: An Abstract | | | | TROUBLED THE TROUBLE YOUR REWARD | |-----------------------------------------------------------------------------| | NEW GAME | | Garf Need a key! 20 coins | | McGoomba Safe delivery... 20 coins | | Arfur Price adjustment. 20 coins | | Goomther Find this guy! 20 coins | | Mousimillian Hit me, please! A small money-making tip | | Bomberto I'm hungry! 11 coins | | AFTER CHAPTER 1 | | Koopook Try to find me! Special Card | | Mayor Kroop Listen to me! Turtley Leaf | | Plenn T. Order me an item! Ultra Shroom | | AFTER CHAPTER 2 | | Puni Elder Emergency Shroom! 60 coins | | Lahla Play with me! 10 piantas | | Pine T. Jr. Help my daddy! Silver Card | | AFTER CHAPTER 3 | | Jolene Help wanted! 30 coins | | Merlee Heartful Cake recipe... 30 coins | | Bub-ulber The food I want. Dried Bouquet | | AFTER CHAPTER 4 | | ??? Elusive badge! Attack FX B badge, new partner | | Mayor Dour Newsletter... 30 coins | | Zess T. Seeking legendary book! Honey Shroom, can cook 2 items | | AFTER CHAPTER 5 | | Eve Tell that person... Meteor Meal | | Goom Goom Looking for a gal! Couple's Cake | | AFTER CHAPTER 6 | | Frankie Important thing! Gold Card | | Chef Shimi Get these ingredients! 40 coins | | Toodles I must have that book. Platinum Card | | Businessman Security code... can buy Hot Sauce | | AFTER CHAPTER 7 | | Goldbob Delivery, please! 64 coins | | Gob I can't speak! 20 coins | | Toadia I wanna meet Luigi! Choco Cake | | AFTER CHAPTER 8 | | Doe T. Roust these cads! 20 coins | | Bub Help me make up. 3 coins | | Swob Erase that graffiti! Snow Bunny | \_____________________________________________________________________________/ NOTE: It seems like Frankie's trouble isn't available until after Chapter 6. Too bad; it kind of breaks the rhythm (three troubles per chapter). It also stops you from utilizing Danger Mario until after Chapter 6. =============================================================================== PIANTA PARLOR ------------------------------------------------------------------------------- The Pianta Parlor is a game center in west Rogueport. There, you can play minigames that you have unlocked with certain cards that you acquire from some of the troubles at the Trouble Center. The Pianta Parlor uses tokens called pianta coins, or simply piantas. You can win piantas from minigames, and you can trade in your own coins for piantas. (The conversion rate is 3 coins for 1 pianta.) Piantas can be used only at the Pianta Parlor. You can trade piantas for various prizes. PRIZES: ________________________________ ____________________________________________ \ / This shows prizes sorted by the | This column shows items and badges sorted order in which they're unlocked. | alphabetically, the cost in piantas, and | the cost in coins (3 coins = 1 pianta). AVAILABLE FROM BEGINNING: | Cake Mix = 6 piantas | THE COMPLETE LIST OF PRIZES Super Shroom = 10 piantas | SORTED ALPHABETICALLY: Super Appeal = 34 piantas | Refund = 34 piantas | ITEMS: COST <-- COIN UNLOCKED WITH SPECIAL CARD: | (the Plane Game minigame) | Cake Mix = 6 piantas = 18 coins Maple Syrup = 14 piantas | Gold Bar x 3 = 234 piantas = 702 coins Power Jump = 34 piantas | Jammin' Jelly = 67 piantas = 201 coins HP Plus = 100 piantas | Maple Syrup = 14 piantas = 42 coins FP Plus = 100 piantas | Super Shroom = 10 piantas = 30 coins UNLOCKED WITH SILVER CARD: | Ultra Shroom = 67 piantas = 201 coins (the Paper Game minigame) | Power Smash = 34 piantas | BADGES: COST <-- COIN Multibounce = 50 piantas | HP Plus P = 200 piantas | FP Plus = 100 piantas = 300 coins Gold Bar x 3 = 234 piantas | Hammer Throw = 50 piantas = 150 coins UNLOCKED WITH GOLD CARD: | HP Plus = 100 piantas = 300 coins (the Tube Game minigame) | HP Plus P = 200 piantas = 600 coins Power Rush = 34 piantas | Money Money = 234 piantas = 702 coins Power Rush P = 34 piantas | Multibounce = 50 piantas = 150 coins Hammer Throw = 50 piantas | Power Jump = 34 piantas = 102 coins Tornado Jump = 67 piantas | Power Rush = 34 piantas = 102 coins UNLOCKED WITH PLATINUM CARD: | Power Rush P = 34 piantas = 102 coins (the Boat Game minigame) | Power Smash = 34 piantas = 102 coins Quake Hammer = 67 piantas | Quake Hammer = 67 piantas = 201 coins Ultra Shroom = 67 piantas | Refund = 34 piantas = 102 coins Jammin' Jelly = 67 piantas | Super Appeal = 34 piantas = 102 coins Money Money = 234 piantas | Tornado Jump = 67 piantas = 201 coins ________________________________/ \____________________________________________ You obtain the different Member's Cards by solving specific troubles: Special Card = Koopook's trouble (available after Chapter 1) Silver Card = Pine T. Jr.'s trouble (available after Chapter 2) Gold Card = Frankie's trouble (available after Chapter 6) Platinum Card = Toodles's trouble (available after Chapter 6) --++< Slots >++-- If you are able to get 7's even remotely consistently, then the slots will easily give you all the piantas you'll need. It costs only one pianta for one play. Line up three matching symbols, and you win piantas. Payoff: 3 faces = 3 piantas 3 stars = 15 piantas 3 sevens = 100 piantas The good news is that the slots don't seem to be rigged, so it all comes down to your skill. Of course, the bad news is that you'll need a lot of practice; the sevens won't come to you that easily. You need sharp eyes and a quick thumb. Luckily, the sevens are on red, which stand out from the green and the blue that the faces and stars are on, making the sevens easier to distinguish. When it begins, you'll see the three slots spinning. You'll see the A button above the first slot. You can stop the slots in any order by pressing left or right, but usually you stop them left to right. Get a feel for the timing of the seven passing by. Press the A button just before the seven passes by, and hopefully it'll stop on the seven. Note that the timing for each slot is slightly different. That's because the right slot spins faster than the left slot. --++< Plane Game >++-- Here, you can hone your awesome flying skills to your heart's content while getting some piantas along the way. Theoretically, you could get more piantas here than in the other minigames, but it'll require a little more work. Not only that, but also this minigame is so short, you could probably play this twice in the time it takes you to play one of the other minigames once. In this minigame, you are in Plane Mode flying through the air to see how far you can fly. There are signposts at regular intervals that say 100, 200, 300, and so forth. Every 30 you go equals one pianta (so the 300 sign marks 10 piantas). Flashing bonus platforms move along the ground. If you land on one of those, you double the number of piantas you gained in the current play. Penalty platforms remain stationary on the ground and say -5, -10, -15, and so on. Landing on one of those usually means you lose all the piantas you gained in the current play. Also, a few piantas float in the sky. Touching one of them adds one pianta to your current play and is also affected by any bonus or penalty you get. Finally, pressing the A or B button makes you fall to the ground right where you are. You can use that to help you land on the bonus panels if you can time it correctly. When you are flying in the air, you'll want to keep tapping left so you don't lose too much altitude. It's kind of hard to describe; you'll have to develop your own rhythm for it. If you're going for piantas, then you'll want to go for the bonus platform moving around the 300 sign. Get any piantas that are conveniently in your way as you head toward that bonus platform. The bonus platform is usually in the foreground or the background, so you have to hit it while it's switching from one to the other. With practice and luck, you'll be able to land on it. You can use the A or B button to fall down where you are, but remember that the bonus platforms keep moving even while you're falling. Why does it not say anywhere what the distance is measured in? I'm guessing maybe meters, but... --++< Paper Game >++-- If you're playing games to win piantas, then this game is a good one (probably the best one because it's very easy and consistent: 20 piantas for 1st place). This is a race between you and 700 other characters; no elapsed time is kept. There are giant fans on both sides of the track that periodically activate. The idea is to use Paper Mode to avoid getting blown off the track. If you fall off, then you win nothing. If you get 1st place, you get 15 piantas plus 5 bonus piantas, always. Forget about 2nd place or anything else besides 1st place. It's incredibly easy to win 1st place. You may see some other characters in the Paper Game as well. Luigi is usually there often (isn't he supposed to be kicking butt in the Waffle Kingdom?). I've also seen Koopie Koo and Wonky there. (Man, I was hoping for a Puni...) If Mario got Paper Mode from the "curse" of the black chest, then how did everyone else get the power of Paper Mode?... --++< Tube Game >++-- The Tube Game is essentially an obstacle course for Mario's Tube Mode. When the race starts, go right. Jump over the bars on the ground, and move around the posts. Follow the 180-degree curve, and then slow down just enough so you can jump up the steps without hitting the sides of the steps. Charge through the hollow building, then look ahead for the moving platforms. If you rushed through the course without stopping, then the platform to Mario's left should be there for you to get on. If it's just leaving, then you can try to jump to it; otherwise, wait for the next platform. While on the platform, if you want to save some time, you can jump off the platform to the other side (make sure you get a rolling start, first). Once on the other side, roll down the steep decline to another 180-degree curve. After the turn, some more bars await you. Do short hops with the B button (to avoid hitting the high bars). Get past the tilted track, and cross the finish line. Incidentally, if you fall off the track after crossing the finish line, then you'll "magically" jump back onto the track. It won't subtract from your Technical Bonus, either. With practice, it's possible to finish consistently with 2:17 or 2:18 left on the clock. That's 14 piantas right there. Combined with the Technical Bonus, you'll get 19 piantas, which is very comparable to the Paper Game in terms of winnings, especially if you can also pick up one or two piantas from the track. Results: Time Remaining: Ignore the fractions of a second for this calculation. For every two seconds above 1:50, you are awarded one pianta. So 1:51 or 1:52 will award one pianta, 1:53 or 1:54 will award two piantas, 1:59 or 2:00 will award five piantas, and so on. 1:50 fall off the course, one pianta will be taken away from your Technical Bonus. --++< Boat Game >++-- This minigame is kind of a pain to navigate. The first half of the course has floating barrels to avoid (though nothing happens if you touch them), and the second half has moving whirlpools to dodge. The whirlpools come in big and small varieties. The small whirlpools push you away from them, and the big whirlpools sink you. Reach the finish line within the two-minute time limit. Results: Time Remaining: Ignore the fractions of a second for this calculation. For every two seconds above 1:15, you are awarded one pianta. So 1:16 or 1:17 will award one pianta, 1:18 or 1:19 will award two piantas, 1:24 or 1:25 will award five piantas, and so on. 1:15 sail into a whirlpool, big or small, one pianta will be taken away from your Technical Bonus. --++< Lahla >++-- Lahla is the Boo working behind the counter. You can use Paper Mode to get to Lahla directly. Get first place in the various minigames, and she'll tell you various tidbits of her personal life. WITH ZERO FIRST PLACES: Oh, my! Customers aren't allowed back here! What?!? You want to learn a little more about me? Well, I'm in charge of the parlor center, silly! I know all there is to know about this place, so if you have a question, just ask! ...You were hoping for more personal information? Uhhh... Ugh! Fine! Whatever... I'm eighteen. My favorite food is Honey Shrooms. The rest is a secret. If you get a high score in one of the mini-games, maybe I'll tell you more... WITH ONE FIRST PLACE: Oh, my! Customers aren't allowed back here! What?!? You got a high score in one of the mini-games? Ugh! Fine! Whatever... Um... My sister Peeka works in the shop next door, and we get along REALLY well! We go shopping together whenever we get a day off. So much FUN, shopping! Peeka likes jewelry and bags and things, but those don't interest me at all. I guess maybe I could use a little more flair in my outfits, though... OK! That's enough. Maybe I'll tell you more if you get another high score. WITH TWO FIRST PLACES: Oh, my! Customers aren't allowed back here! What?!? You got another high score? Ugh! Fine! Whatever... Um... I really love sweets, so I ask Zess T. to bake stuff for me all the time. Ooh, and I love nothing better than a nice, sweet cake, but... Lately I've been feeling a little chunky, though... So I'm on a diet. But hey! That's a secret! Seriously! Don't tell Peeka! But that's all for now. Maybe I'll tell you more about me if you get another high score, all right? WITH THREE FIRST PLACES: Oh, my! Customers aren't allowed back here! What?!? You got another high score? Ugh! Fine! Whatever... Um... The other day a customer named Arfur asked me out to dinner. But I said no... I mean, I don't even know him, right? Still, I wonder if he really likes me... I just don't get it, though. What could he like about me? I mean, really... OK, that's all for now. How embarrassing. Maybe I'll tell you more about me if you get another high score, all right? WITH ALL FOUR FIRST PLACES: Oh, my! Customers aren't allowed back here! What?!? You got another high score? Ugh! Fine! Whatever... Um... My dream is to have my own place someday. I just wanna be surrounded by cakes and cute stuff all the time... And then I'd get all the people I like to hang out here... It'd be sooo great! So, I've gotta work hard now to make my dream come true. But I kind of like being a parlor kitty, too, tee-hee! OK, that's all for now! I feel silly talking about this kind of stuff. And, Mario... I hope you're not spending all your time trying to talk to little old me. Because I'm sure there are other things you're supposed to be doing, right? =============================================================================== SUPER LUIGI RPG: LEGEND OF THE MARVELOUS COMPASS ------------------------------------------------------------------------------- It seems that Luigi has his own adventure while Mario's out. After Chapter 1, Luigi will appear in Rogueport, where you can ask him about his adventure. After every chapter, he'll be in another spot in Rogueport, just waiting to tell you the next chapter in his adventure. It's a pretty good read; just use your imagination. By the way, Luigi's adventure is recorded as a multiple-volume novel and sold in the shop in Rogueport. The writing style of that novel has a more serious and emotional feeling to it. The novel is virtually stripped of humor, but it's mostly the same recounting of Luigi's adventure. I'm not going to type that novel here; buy it for yourself in Rogueport! As an incentive, the first volume of the novel contains a recipe. Everything below is Luigi speaking to Mario, unless it says [Addendum], then the paragraph is Luigi's partner talking to Mario. ~~{ AFTER CHAPTER 1 }~~ Well, hey, big brother! Fancy meeting you here! What a co-inky-dink! Eh? Who, me? Well, Bro, I'm on an adventure. I have to rescue Princess Eclair of the Waffle Kingdom. Yeah, it's a bad scene, all right. She's been kidnapped by the evil Chestnut King. If you gotta know, I met with some Waffle Kingdom cabinet members the other day. It was pretty crazy, Bro. Wanna hear what happened? It's a pretty long story... "Waffle Kingdom Letter" Well, like I said, it's a really long story, but here goes...affler fables... When it activated, the entire thing lit right up, indicating the deep south... It was pointing me toward Rumblebump Volcano on the Pudding Continent! So yeah, here I am! I'm sailing out of Rogueport for Rumblebump Volcano. It's probably gonna be pretty dangerous, but... I gotta rescue that princess! ~~{ AFTER CHAPTER 2 }~~ Well, I went to Rumblebump Volcano and got myself a Marvelous Compass piece! It was an incredible quest! There was danger, and all sorts of adventuring! It was pretty nutso, Bro. Wanna hear what happened? It's a pretty long story... "Rumblebump Volcano" Well, like I said, it's a really long story, but here goes... Rumblebump... [Addendum by Blooey, the Blooper]! ~~{ AFTER CHAPTER 3 }~~ Well, I got my second piece of the Marvelous Compass at Plumpbelly Village recently! Hoo, boy! I really got my hands dirty on that one, I'll tell you what! It was pretty wild, Bro. Wanna hear what happened? It's a pretty long story... "Plumpbelly Village" Well, like I said, it's a really long story, but here goes... its save! [Addendum by Jerry, the Bob-omb] Hi, I guess. I'm Jerry. I'm a Bob-omb from Plumpbelly Village. Nice meeting you. Sorry I sound so down, but you would be too if you saw Luigi dressed as a bride.. ~~{ AFTER CHAPTER 4 }~~ Well, I headed to Circuit Break Island and got me a Marvelous Compass piece! You wouldn't believe it, Bro! Talk about thrills, chills, and spills! It was pretty nuts, Bro. Wanna hear what happened? It's a pretty long story... "Circuit Break Island" Well, like I said, it's a really long story, but here goes... racetrack,. I was in reverse! The Big Green 01 went rocketing backwards with me yelling... I crashed into the wall behind me hard enough to cut me off midscream. In one fell swoop I dropped into last place and wrecked my racing machine... But it wasn't all bad news: all the other karts crashed because of my maneuver... Once I got in gear and took off, I was the only car left! I won by a country mile, Bro! Rogueport. And that's what's been up with me. [Addendum by Torque, the Buzzy Beetle]! ~~{ AFTER CHAPTER 5 }~~ Well, I got another piece of that Marvelous Compass! At Jazzafrazz Town, this time. Bro, I'm telling you, I turned adventuring into an art form on THAT little quest! Hoo! It was pretty nutty, Bro. Wanna hear what happened? It's a pretty long story... "Jazzafrazz Town" Well, like I said, it's a really long story, but here goes...! In the end, our musical was the talk Rogueport, and here I am, another leg of my adventure completed! [Addendum by Hayzee, the Dayzee] I'm Hayzee! And I must say, Luigi is a great actor, one of the finest I've seen! After this adventure, we're going on tour to appear on stages everywhere! I'm going to be known as "The Red Miracle"! And, of course, Luigi will be grass! ~~{ AFTER CHAPTER 6 }~~ Well, guess what I found in Rapturous Ruins, Bro? Yup! A Marvelous Compass piece! This part of my adventure was actually sort of sad, if you wanna know the truth. It was pretty insane, Bro. Wanna hear what happened? It's a pretty long story... "Rapturous Ruins" Well, like I said, it's a really long story, but here goes... learned. To prevent a repeat of their fate, Cranberry broke the compass into seven parts. He hid six and kept one, putting himself to sleep until a worthy hero woke him. Rogueport after that. I'm making my final preparations for my final battle now. I'm a little nervous, Bro. But that's what I've been up to, anyway! [Addendum by Screamy] ...I'm Screamy. I wonder what future is plotted for us by he who holds the compass... For I must deliver something... ~~{ AFTER CHAPTER 7 }~~ Let's see, adventures... Oh, of course! Me, I'm done questing for now. Yup! I scaled Hatesong Tower the other day and rescued the fair Princess Eclair! That's one adventure I'm never gonna forget. Nope, it was just tooooo exciting! It was just bonkers, Bro. Wanna hear what happened? It's a pretty long story... "Hatesong Tower" Well, like I said, it's a really long story, and this part is just crazy, but here goes.... The door to the tower swung slowly openHHHHWHAAAAACK! The ocean winds raged against the tower windows! With that sound as my call to battle, I advanced with no mercy in my heart! And then.............................................. And then.............................................. .................................................................. .................................................................. .................................................................. .................................................................. I beat him. I defeated the Chestnut King. An even worse beast came next, a nightmare thing...but I beat it, too. ........................... I rescued Princess Eclair. It was all over. And then I came back to Rogue... [Addendum by Blooey, the Blooper] Hey! You! Remember me? It's me, Blooey! Maaaan, that last battle was hairy! You have no idea! I was burnt to a crisp, but I was actually kinda relieved, if you can believe that! But if you want the whole story, you should just ask Luigi here! Wahahaha! ~~{ AFTER CHAPTER 8 }~~ I've been catching a breather here, you know, reflecting back on all my adventures. It's been a long road, Bro. Wanna hear what happened? It's a pretty long story... "Super Luigi Book" Rogueport... It's set a new record for consecutive weeks at number one on the best-seller list!!! Rogueport. How about you snag a copy, Bro? =============================================================================== THE LEGEND OF ROGUEPORT ------------------------------------------------------------------------------- On top of Merlon's house is a guy named Grifty who imparts the tales passed around the streets of Rogueport. The tales explain the ancient city beneath Rogueport, the reason the city was destroyed, the Crystal Stars, the black chests, and the Magical Map. Every chapter, he reveals more of the legend. "The Fearsome Demon" Ages ago, a city flourished here in peace and splendor. ...But it was destroyed in a single day by a demon form. "The Crystal Stars". "Dragons and Dungeons"... "The Hero Who Arose" his strength and honor to defend his people. And he became a hero to all, despite his odd voice. "The Wise Goomba" There was a wise Goomba from Boggly Woods gifted in knowledge of the world. When beasts rose to take the woods, this knowledge helped the people fight them. And this Goomba, who knew the way that every monster would attack... She began to think of a way to banish all monsters from the land... "The Stalwart Koopa" A Koopa who traveled the world alone learned of the darkness covering the land... He went alone wherever evil dwelt, and banished it with shell and sheer bravado. The monsters grew to fear this scar-riddled Koopa who thwarted them at every turn. But the brave Koopa was finally taken in a trap set for him by the monsters. But then, a Boo who fought with the monsters came and used her magic to free him. The brave Koopa's spirit had melted the heart of the cold Boo lass... "The Four Heroes" The Boo used her powerful magic to learn more about the evil they faced... "We cannot destroy this darkness alone," she decided, her face a grim mask. "We need the Toad hero of Petal Meadows and the wise Goomba of Boggly Woods." The Boo's magic drew the four heroes together to send the demon from the world. And so, the four heroes finally set out for the Palace of Shadow... "The Duel With the Demon" The power of the world-devouring demon was greater than any could imagine... But the wise Goomba soon realized that this was the power of the Crystal Stars... She thought of a way to take the stars and use them against the demon. She told the other heroes her plan and set it in motion, banishing their fears. The Boo's magic and the Toad's strength created a gap in the demon's defenses... At that moment, the brave Koopa seized the stars... And succeeded in badly damaging the demon... "The Demon Sealed Within" But even the brave Koopa's stroke was not enough to end the demon's reign... The wise Goomba thought of another use for the Crystal Stars in that dire hour... She suggested sealing the demon forever with the Crystal Stars. All agreed. The heroes matched their strengths with the power of the Crystal Stars... And they successfully sealed the demon's soul within the deepest part of the palace. Together, they made it so that only all seven stars could break the seal... "The Demon's Curse" The four heroes thought they had sealed away the demon and all of its powers... But the demon used a tiny opening before the seal was complete to curse them all. While holding the Crystal Stars, they'd feel nothing, but when they let them go... A black box would appear to seal their souls within. The four heroes traveled the world, scattering the stars so the seal would remain. But the last four stars each carried the curse, which claimed each hero... "The Great Tree and Punies" The hiding places of many of the Crystal Stars have now faded into legend. But some say that the wise Goomba hid one in the Great Tree. At that time, many monsters wandered in the nearby Boggly Woods. The tiny Punies were always tormented by their fierce appetites, it was said. Pitying them, the Goomba hollowed out the Great Tree for the Punies to live in. The Punies were so grateful that they swore to protect the Crystal Star there... "The Boo Heroine's Last Days" Once the Boo heroine hid her star in a steeple, she was trapped in the nearby town... Some say the Crystal Star lies in that steeple still... "The Pirate King Cortez" The Koopa hero went to a southern isle to hide his star where none would find it. But the Koopa was so tired from his journey that the pirate Cortez stole it easily. In that very instant, the brave Koopa was trapped in an inescapable chest. But Cortez did not realize the power of the star and lost it among his treasures... "The Toad Hero's Final Days" The strong Toad held his star and continued his arduous journey. But eventually the miles took their toll upon him, and he collapsed. A traveling healer happened by and saved his life... But the Toad knew his fate was to be trapped in the box when the star was gone... So he asked this healer to hide the star in a secret place known to no one... "All Becomes Legend" After the demon was sealed within the Palace of Shadow... Many refused to come near that place of terror. But as the years passed, entire generations forgot... And the penniless and the immoral began to congregate in this once- barren place... This place soon became a populous harbor, the town of Rogueport... And some even began to say that the underground city held a legendary treasure. But they were unaware that the demon slept beneath them still... "The Magical Map" The heroes knew that the seal might not last forever... And they sought to make the Crystal Stars available to one who might need them... So, before going to their individual dooms, they made a map to all the stars. And to prevent an evil force from misusing this map... They placed it in a box that could only be opened by the pure of heart. =============================================================================== TIPS ------------------------------------------------------------------------------- ***** Efficient ways to make money ***** The most efficient way to get money (at least in the long run) is to buy Money Money badges from the Pianta Parlor. It costs 234 piantas for one, which equals 702 coins if you use the pianta changer. It's money well-spent in my opinion since you'll receive more coins per battle. (You'll receive even more coins if you equip more Money Money badges.) Trust me; equip a Money Money badge or two, fight some higher-level enemies, and see the money pour in. My favorite place to rake in the money is the path right outside Fahr Outpost for its easy access to an inn if battles go bad (and because I like snow places). Unfortunately, the Money Money badge is not for sale until after Chapter 6. Another excellent long-term investment is Lumpy, the Ratooey who appears in Rogueport Harbor until Chapter 3 is completed. He asks for your coins to fund his quest for oil. You can give him 100, 200, or up to 300 coins. Come back here after Chapter 6, and he'll return your investment approximately threefold: 100-coin investment --> 300-coin return 200-coin investment --> 600-coin return 300-coin investment --> 999-coin return (no joke!) A different way to get some decent cash is to trounce. You will receive 20 coins every time you defeat Rawk Hawk. The fight with Rawk Hawk is quite easy; Rawk Hawk has the same stats as when you first fought him in Chapter 3, but Mario grows stronger with all the new moves, items, and badges he gets in each chapter. So this really is a painless way to make some money. If you need immediate gratification, then you can try selling an Ultra Shroom or Jammin' Jelly for 100 coins. You can always buy another one in Rogueport Sewers for 200 coins, which really isn't that much if you have a Money Money badge or two as stated above; plus, you can cook Zess Deluxes (+40 HP/FP) for only 40 coins each. You can also sell badges to the Lovely Howz of Badges for some quick money. Sell the badges that you probably won't use anytime in the near future. For example, the Attack FX badges sell for 50 coins each. The Return Postage badge sells for 500 coins! You can always buy back the badges later if you wish (at twice the price you sold them for, however). ***** Efficient ways to win piantas ***** In my opinion, the best way to win piantas is to play the slots. Just learn the timing for the 7's; it's really not that hard (it takes a lot of practice, though). It costs 1 pianta for 1 play, and three 7's give you 100 piantas. (Of course, I'm probably alone on this opinion...) There are two other ways to get piantas consistently. One way is to play the Paper Game. The Paper Game awards 20 piantas for 1st place every single time, and it's very easy to win 1st place. As for the other minigames, they're not as consistent as the Paper Game, but they could give more than 20 piantas. In the Tube Game, you can win around 18-22 piantas with practice (depends on how many piantas you pick up from the track), so it's a good game to play if you get bored of the Paper Game. The Plane Game could be the most profitable minigame since it's so short, provided that you are able to land on the bonus platforms frequently. I do not recommend the Boat Game... The other way to get piantas is the pianta changer, of course. If you have extra money flowing out of your pockets, and you don't feel like playing any Pianta Parlor games, then you may consider dumping your money into the pianta changer. The exchange rate is 3 coins for 1 pianta. ***** Fast ways to earn Star Points ***** The maximum level that Mario can reach is 99, so if your goal is to max out Mario's level, then you have a long road ahead of you... There are two ways to earn mass Star Points. One way is to look for the Amazy Dayzee, which looks like a golden, sparkling Crazee Dayzee. At level 30, you'll gain over 30 Star Points for defeating one Amazy Dayzee. You can read more about Amazy Dayzees in the following section. Another good way is to go through the Pit of 100 Trials. Lots of enemies in floors 81-89 give decent Star Points. The enemies in floors 91-99 give you a lot of Star Points, and you should meet at least one Amazy Dayzee there, probably more than one. Plus, the fact that you have to go through 90 floors worth of enemies ensures that you'll get at least 90 Star Points... Note that, even with the Amazy Dayzee, there is no "fast" way for Mario to level up all the way to 99. I recommend using Danger Mario to help you get through battles more quickly. A slightly less fast way to get Star Points is to fight. Rawk Hawk gives you decent experience for a "normal" battle; you even get 20 coins per battle as well. Past level 30, however, he, too, starts giving 1 Star Point. ***** Amazy Dayzee ***** Amazy Dayzee's stats: HP = 20 Attack = 20 Defense = 1 Amazy Dayzees look similar to Crazee Dayzees, except Amazy Dayzees are golden and sparkly. They also give a ton of Star Points. At level 30, you'll gain nearly 40 Star Points for defeating one Amazy Dayzee (more Star Points than most bosses give you). They also have an Attack of 20 and tend to run away in the first turn, so be prepared to take it out in one turn if you fight one. There are several different ways to deal with the Amazy Dayzee: -- Have Mario use Art Attack. It is possible to defeat it with one Art Attack, but if it's still alive after that, then finish it off with your partner. -- Have Mario use Supernova, then have your partner use an attack that hits all enemies such as Shell Slam, Stampede, Fiery Jinx, or Bob-ombast. -- Equip some badges that boost Attack, have Mario use Power Bounce, then have Goombella use Multibonk. Alternatively, you can have Goombella use Rally Wink after Mario's Power Bounce, and then have Mario use Power Bounce again. -- Use the Double Dip and Double Dip P badges to hit it with four Thunder Bolts or four Thunder Rages. -- You can try to inflict a status effect (immobilize it, freeze it, or put it to sleep), and if it fails, run away and reenter the battle (see below). If you wish to exit a battle from an Amazy Dayzee (perhaps to heal or to swap badges), then you can run away without worry; the Amazy Dayzee will still be there if you fight the same enemy again (but do not leave the immediate area). Amazy Dayzees can be found at Twilight Trail. Get into battles with Crazee Dayzees, and you'll randomly find Amazy Dayzees (a very small chance). Apparently, you have a slightly greater chance of finding Amazy Dayzees if you're carrying a Golden Leaf with you (how convenient that Creepy Steeple is right next to Twilight Trail). Amazy Dayzees also appear in the Pit of 100 Trials; unfortunately, they appear all the way at the bottom: levels 91-99. ***** Good recipes to make (with Cookbook) ***** -- Jelly Ultra -- Effects: Recover 50 HP and 50 FP Total Cost: 0-400 coins Ingredients: Ultra Shroom (200 coins in Rogueport Sewers, 67 piantas, or 201 coins, in the Pianta Parlor) Jammin' Jelly (200 coins in Rogueport Sewers, 67 piantas, or 201 coins, in the Pianta Parlor) First Available: After giving the Cookbook to Zess T. after Chapter 4 Notes: The most powerful healing item, unless you count the Life Shroom's reviving power. It is extremely expensive to make, though. -- Zess Deluxe -- Effects: Recover 40 HP and 40 FP Total Cost: 40 coins Ingredients: Life Shroom (40 coins in Twilight Town) Horsetail (Petal Meadows) 2 Turtley Leaves (Petalburg, in the bushes in Mayor Kroop's yard) First Available: After giving the Cookbook to Zess T. after Chapter 4 Notes: My favorite recipe, and a lot more cost-effective than Jelly Ultras. -- Zess Cookie -- Effects: Recover 15 HP and 15 FP Total Cost: 0-33 coins Ingredients: Cake Mix (6 piantas, or 18 coins, in the Pianta Parlor) Mystic Egg (win from Petuni in The Great Tree) OR Gradual Syrup (15 coins in Rogueport Sewers) OR Maple Syrup First Available: After giving the Cookbook to Zess T. after Chapter 4 Notes: This is a nice and easy recipe to cook after getting the Cookbook. -- Honey Candy -- Effects: Recover 20 FP Total Cost: 3-23 coins Ingredients: Cake Mix (6 piantas, or 18 coins, in the Pianta Parlor) Honey Syrup (5 coins in Rogueport, 3 coins in Keelhaul Key) First Available: After giving the Cookbook to Zess T. after Chapter 4 Notes: If you don't want to make Zess Tea (since you'd need Golden Leaves), then Honey Candy is the way to go, though you'll need some coins. -- Healthy Salad -- Effects: Recover 15 FP, cure poison Total Cost: 0 coins Ingredients: Turtley Leaf (Petalburg, in the bushes in Mayor Kroop's yard) Horsetail (Petal Meadows) First Available: After giving the Cookbook to Zess T. after Chapter 4 Notes: If you don't want to make Zess Tea (since you'd need Golden Leaves), and you don't want to have to pay coins to make Honey Candy, then Healthy Salad is for you. It also cures poison, which can be useful. -- Zess Dynamite -- Effects: 7 damage to all enemies Total Cost: 10-20 coins Ingredients: Mystic Egg (win from Petuni in The Great Tree) Coconut (Keelhaul Key) 2 Fire Flowers (10 coins in Rogueport, 5 coins in Keelhaul Key) First Available: After Chapter 6 Notes: An alternative to Thunder Rage/Shooting Star, and it does more damage. First, mix the Mystic Egg and a Fire Flower to make an Egg Bomb. Then, mix the Coconut and a Fire Flower to make a Coconut Bomb. Finally, mix the Egg Bomb and the Coconut Bomb to make Zess Dynamite. -- Trial Stew -- Effects: Reduce the user's HP to 1, and reduce FP to 0. Total Cost: 26-45 coins Ingredients: Ice Storm (15 coins in The Great Tree/Keelhaul Key, 6 coins in Fahr Outpost) Point Swap (5 coins in Glitzville) Slow Shroom (15 coins in Rogueport Sewers) Golden Leaf (Creepy Steeple) Horsetail (Petal Meadows) OR Fire Flower (10 coins in Rogueport, 5 coins in Keelhaul Key) First Available: After giving the Cookbook to Zess T. after Chapter 4 Notes: This is an advanced item that requires great care on the player's part. It instantly puts the user in Peril, where Mega Rush or Mega Rush P badges can drastically boost the Attack power of the one in Peril. Use an FP-restoring item after eating Trial Stew. To cook this recipe, first mix the Ice Storm and Golden Leaf together to make a Snow Bunny. Second, cook the Horsetail or the Fire Flower to make some Spicy Soup. Third, mix the Snow Bunny and Spicy Soup to create a Couple's Cake. Fourth, mix a Slow Shroom with a Point Swap to make a Poison Shroom. Lastly, mix the Couple's Cake and Poison Shroom to create Trial Stew. It's a bit of a hassle to create, but the effects can be very potent. ++ Honorable Mentions ++ -- Zess Frappe -- Effects: Recover 20 FP (not 20 HP like the game says) Ingredients: Ice Storm (15 coins in The Great Tree/Keelhaul Key, 6 coins in Fahr Outpost) Maple Syrup (20 coins in Twilight Town/Fahr Outpost, 15 coins in the Excess Express, 14 piantas, or 42 coins, in the Pianta Parlor) Notes: It's good to make if you happen to have an Ice Storm and Maple Syrup. Otherwise, it's more expensive to create than Honey Candy. Plus, the typo in the description could confuse the player. That's a stupid reason, I know, but it could happen... -- Heartful Cake -- Effects: Recover 20 FP, softens the user (Defense down) Ingredients: Cake Mix (6 piantas, or 18 coins, in the Pianta Parlor) Ruin Powder (15 coins in Fahr Outpost) Notes: It's good to make if you happen to have Ruin Powder. Otherwise, just stick with Honey Candy. Defense down may sound bad, but Defense cannot be less than 0, so it's safe to eat if the user's Defense is already 0. -- Fire Pop -- Effects: Recover 20 FP Ingredients: Cake Mix (6 piantas, or 18 coins, in the Pianta Parlor) Fire Flower (10 coins in Rogueport, 5 coins in Keelhaul Key) Notes: It's good to make if you happen to get a Fire Flower in your travels; otherwise, just stick with Honey Candy. -- Electro Pop -- Effects: Recover 15 FP Ingredients: Cake Mix (6 piantas, or 18 coins, in the Pianta Parlor) Volt Shroom (10 coins in Rogueport) Notes: It's good to make if you happen to get a Volt Shroom in your travels; otherwise, just stick with Honey Candy. ***** Good recipes to make (without Cookbook) ***** Zess T. won't cook anything until you give her a Contact Lens. Unfortunately, the Contact Lens is not available until after Chapter 1. -- Shroom Fry -- Effects: Recover 6 HP and 2 FP Total Cost: 5 coins Ingredients: Mushroom (5 coins in Rogueport) First Available: After giving the Contact Lens to Zess T. after Chapter 1 Notes: Mushrooms heal 5 HP and no FP, so you should always cook Mushrooms. Volt Shrooms also work, so cook those if you're not going to use them. -- Koopa Tea -- Effects: Recover 7 FP Total Cost: No cost Ingredients: Turtley Leaf (Petalburg, in the bushes in Mayor Kroop's yard) First Available: After giving the Contact Lens to Zess T. after Chapter 1 Notes: 7 FP is better than Honey Syrup's 5 FP, and Turtley Leaves are free. -- Spicy Soup -- Effects: Recover 4 HP and 4 FP Total Cost: 10 coins Ingredients: Fire Flower (10 coins in Rogueport) First Available: After giving the Contact Lens to Zess T. after Chapter 1 Notes: Useful if you don't need Fire Flower's attack power. -- Shroom Roast -- Effects: Recover 15 HP and 5 FP Total Cost: 15 coins Ingredients: Slow Shroom (15 coins in Rogueport Sewers) First Available: After giving the Contact Lens to Zess T. after Chapter 1 Notes: More expensive but can be useful if you need the extra healing power. -- Mousse Cake -- Effects: Recover 15 FP Total Cost: 0-18 coins Ingredients: Cake Mix (6 piantas, or 18 coins, in the Pianta Parlor) First Available: After giving the Contact Lens to Zess T. after Chapter 1 Notes: More expensive but can be useful if you need the extra healing power. -- Fried Egg -- Effects: Recover 10 HP Total Cost: No cost Ingredients: Mystic Egg (win from Petuni in The Great Tree) First Available: After Chapter 2 Notes: Same recovery as a Super Shroom, and Mystic Eggs are free. -- Zess Tea -- Effects: Recover 20 FP Total Cost: No cost Ingredients: Golden Leaf (Creepy Steeple) First Available: After Chapter 4 Notes: It is a very good recovery item, even after getting the Cookbook, although it is a bit cumbersome to walk all the way to Creepy Steeple. ++ Honorable Mentions ++ -- Fresh Juice -- Effects: Recover 5 FP, cure poison Ingredients: Honey Syrup (5 coins in Rogueport) Notes: It's the same as Honey Syrup, except it can also cure poison status. There are no poisonous enemies before you get the Cookbook, though... ***** Danger Mario ***** "Danger Mario" is a specific setup for Mario that involves equipping a lot of Power Rush badges while perpetually keeping his HP at 5. The idea is to kill all your enemies in one turn, thereby keeping your HP safe. It is considered "cheating" by some players because Mario's Attack power can go as high as the player wishes (the damage caps at 99, though). This isn't a glitch, either; it's a valid, legitimate setup within the game. I don't know if I'd call it cheating, but it certainly is cheap, so don't use it in your first playthrough. The complete setup for Danger Mario is not available until after Chapter 6. The setup will be much easier to do if you do not raise Mario's HP at all whenever Mario levels up. First of all, you have to keep Mario's HP at 5 or lower at all times. To do this, you are going to lower his Max HP to 5. Go down the pipe in front of Professor Frankly's house to enter Rogueport Sewers. To the left is a cracked wall. Have Bobbery blow up the cracked wall to uncover a pipe. This pipe leads to Chet Rippo, a magician who can alter your stats. Have him lower Mario's Max HP to 5. It costs 39 coins for every level transfer, so it's much easier if you did not level up Mario's HP a lot, if at all. Next, you need the Power Rush badges themselves. Solve Frankie's trouble in the Trouble Center to obtain the Gold Card. Take the Gold Card to the Pianta Parlor. You'll unlock the Tube Game and items for sale, including the Power Rush badge. Now just buy as many Power Rush badges as you want. That's all. They cost 34 piantas each (or 102 coins if you use the pianta changer). Finally, you get to set up your badges. Go to your badge screen. Equip your Power Rush badges. Five should take care of a lot of enemies, and ten should kill almost everything. Equip the Multibounce badge to take care of all the regular enemies in one turn, and equip the Power Bounce badge to kill bosses. Also, equip the Spike Shield badge to protect against spiked enemies and the Ice Power badge to protect against fire enemies. Optionally, you can wear the Flower Saver and FP Drain badges so you never have to worry about FP again. Flower Saver drops Multibounce's FP consumption to 1, and FP Drain gives you 1 FP every time you attack; therefore, your FP never goes down. Power Bounce will still cost 2 FP, but that's only for bosses, or you can equip a second Flower Saver. Of course, this setup isn't flawless. Multibounce will not hit enemies that hang from the ceiling. For this, you can use Quake Hammer to hit them. If there are also enemies floating in the air, then you can use Goombella's Rally Wink to give Mario a chance to use Multibounce. If you're still worried about Mario getting hit, you can wear defensive and evasive badges. Last Stand and Close Call will help since Mario is always in Danger. P-Down, D-Up increases his Defense by 1, and his Attack is so high that a decrease in Attack will not matter. HP Drain will recover his HP by 1 every time he attacks, and his Attack is so high that the decrease in Attack will not matter. ***** Yoshi Colors ***** It is possible to determine the color that your Yoshi is going to be. It must be done while you're in Chapter 3. The color is based on elapsed time, from the time you get the egg to the time you lose to the Iron Clefts with the egg. See, at any given time, the Yoshi is a certain color for a specific duration. Color Lasts for And becomes ------ ----------- ----------- Green 6 minutes Red Red 3 minutes Blue Blue 2 minutes Orange Orange 4 minutes Pink Pink 3 minutes Black Black 1 minute White White 0.5 minute Green Or, a more flowchart-like diagram (read from left to right): Green Red Blue Orange Pink Black White / \ / \ / \ / \ / \ / \ / \ | +6 min. +3 min. +2 min. +4 min. +3 min. +1 min. | | | ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< +0.5 min. <- Once the Yoshi egg hatches, the color is permanent, so do the following steps in Chapter 3 before the egg hatches. 1. Fight your way up the ranks until you are rank 11 (your next fight will be the Iron Clefts). If you have yet to get the Yoshi egg, then get it now. 2. Save in the Save Block outside your locker room. 3. Lose to the Iron Clefts and see what color your Yoshi turns out to be. 4. Reset the game, and reload your file. 5. Now that you know the current color, you just have to wait underneath the Save Block for a certain amount of time while the Yoshi changes colors inside the egg. Use the chart to add up the number of minutes you ought to wait. Be careful not to wait too long, though. For example, if you know you have orange, and you want black, then you have to wait a maximum of 7 minutes. I say maximum because if your Yoshi was at the end of the orange phase, then you'd have to wait only 3 or 4 minutes; 7 minutes would cycle back to green. Therefore, do not overestimate your wait time. You can use the Play Time clock on Mario's Menu screen to count the number of minutes that pass by. 6. Once you think you've waited long enough, save your game. 7. Now quickly lose to the Iron Clefts, and see what color you get. If it's the one you wanted, then great! If not, then try again from step 4. Sorry, I probably made this sound a lot more confusing than it actually is. ***** The Lovely Howz of Badges ***** The Lovely Howz of Badges is a badge shop where you can buy and sell badges. The shop becomes available after Professor Frankly gives you your first badge. The badges on display on the counter are 70% of the regular cost. The badges rotate every time you leave and reenter Rogueport, so there are always five of the available badges that are on sale. | AVAILABLE | | | | | Badge Name | | Regular | | Special | | | | | | Cost | | Deal | FROM BEGINNING FP Drain 100 coins 70 coins Happy Flower 150 coins 105 coins Last Stand 50 coins 35 coins Last Stand P 50 coins 35 coins Piercing Blow 75 coins 52 coins Power Jump 50 coins 35 coins Simplifier 50 coins 35 coins Super Appeal 50 coins 35 coins Unsimplifier 50 coins 35 coins AFTER CHAPTER 1 Close Call 100 coins 70 coins Close Call P 100 coins 70 coins Sleepy Stomp 75 coins 52 coins AFTER CHAPTER 2 First Attack 100 coins 70 coins Power Rush 50 coins 35 coins Pretty Lucky P 150 coins 105 coins AFTER CHAPTER 3 Ice Smash 75 coins 52 coins Power Rush P 50 coins 35 coins Shrink Stomp 75 coins 52 coins AFTER CHAPTER 4 Damage Dodge 150 coins 105 coins Head Rattle 100 coins 70 coins Soft Stomp 75 coins 52 coins AFTER CHAPTER 5 Damage Dodge P 150 coins 105 coins Fire Drive 100 coins 70 coins Super Appeal P 50 coins 35 coins AFTER CHAPTER 6 Attack FX P 100 coins 70 coins (No kidding; there are Simplifier 50 coins 35 coins <-- 2 Simplifier badges and Unsimplifier 50 coins 35 coins <-- 2 Unsimplifier badges.) I don't know if there are more badges after Chapter 7; I'll have to check that out when I get there. =============================================================================== VERSION & CONTACT ------------------------------------------------------------------------------- E-mail: [email protected] Version 1.0 - February 9, 2005 Whew, I finished the checklist. Hopefully, I have not missed anything. Originally, I was just going to do the checklist, but then I decided to add the Pit of 100 Trials, Trouble Center, and Pianta Parlor sections. I'll have to include tips and strategies for those sections next version. Version 2.0 - March 4, 2005 Added a whole bunch of stuff. Entire new sections were put in. It also crossed my mind that it may be easier to get the Jammin' Jelly in Keelhaul Key by spinning your hammer. Finally, thanks to "Turtlebirdnl" for telling me that Space Food appears in the Fahr Outpost inn, and "Glenn Tore Fingarson Dalby" for pointing out two errors in my checklist (one in Rogueport Sewers and one in Petalburg). I can't believe I made such lame mistakes... Oh, and I still need to do the Pit of 100 Trials and Trouble Center sections. Version 2.01 - March 6, 2005 Added Rawk Hawk in the Tips section as a good source for coins and possibly experience. Version 2.02 - March 11, 2005 Shoot, I had completely forgotten about 8-bit Mario in the X-Naut Fortress. That's added to the Checklist now. =============================================================================== CREDITS ------------------------------------------------------------------------------- God, without whom everything is meaningless. My family who always takes such good care of me. Nintendo for making such an awesome game. Nintendo again for making such an addictive theme song. "blaiken used peck" for posting that a Golden Leaf attracts Amazy Dayzees. "Turtlebirdnl" for telling me that Space Food appears in the Fahr Outpost inn. "Glenn Tore Fingarson Dalby" for correcting two checklist location errors. =============================================================================== James Akasaka. (^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^) (.............................. ~ END OF FILE ~ ..............................)
http://www.gamefaqs.com/gamecube/920182-paper-mario-the-thousand-year-door/faqs/35249
CC-MAIN-2015-11
refinedweb
21,532
80.62
Please confirm that you want to add Introduction to C Programming for the Raspberry Pi to your Wishlist.. Get to know the instructor for this course and an overview of the course. In this lesson, you'll learn what hardware is used in this course. In this lesson, you'll learn what Operation System and Software is used in this course. In this lesson, we will do the whole process from writing the code, compiling, running and debugging the program from the command line. In this lesson, we will use the IDE Geany to write, compile and debug the code and run the program. In this lesson, we will start with the installation and configuration of the IDE Netbeans. We will connect Netbeans to the Raspberry Pi, write code, compile the code and run the program. What do you need to make C programs that run on the Raspberry Pi? In this lesson, I will talk about what we are doing in this section. In this lesson, we'll look at the building blocks of a C Program to answer the question, what are C Programs are made of. In this lesson, you'll learn how to write text on the screen and how to read user input from the keyboard. Which statement can print \n on the screen? In this lesson, you'll learn, how to add comments to the Source Code. In this lesson, you'll learn how to declare and use variables. In this lesson, you'll learn, what different kind of mathematical operations are used in the C language. #include <studio.h> int main() { int i = 100, j = 9, k; i = i/10; k = i - j; printf("%d - %d = %d\n" , i, j, k); return 0; } In this lesson, you'll learn, how to use the datatype char that is used for declaring characters and strings. In this lesson, you'll learn, how to declare and use constants in your program. In this lesson, you'll learn about the different types of arrays, how to declare and use them. In this lesson, you'll get an overview over the different kind of conditions that are used in C. In this lesson, we'll make a countdown program to demonstrate the advantage of the fflush() function. Using fflush(stdout) from the stdio.h we are able to flush the named stream, stdout in this case. In this lesson, you'll learn, how pointers are declared and used in a C program. In this lesson, we'll make use of pointers to declare files. You'll also learn, how to create, open, close, read and write to files. #include<stdio.h> int main () { FILE *fp; fp = fopen("source.txt", "r"); return 0; } In this lesson, you'll learn, how the system function can be used to call extern programs from your C program. Learn how to write your own functions. In this tutorial you'll learn how to setup the library wiringPi. The library is needed to get access to the GPIO pins on the Raspberry Pi. In this lesson, we will use the library wiringPi to do our first physical project, the Blinking LED. Adding 2 Led's to the countdown program We'll take the countdown program we did earlier as a starting point. This means that you need to load this code into your IDE to work from there. In this lesson, we will light up a LED after pressing a button. In this lesson, we'll create a program that counts every time we press a button. In this lesson, will will let the buzzer make a sound after pressing a button. (Door Bell) In this lesson, we will first test the tilt sensor with a LED, than replace the LED with a buzzer to make ourself a prototype of a bicycle alarm. In this lesson, we will read the humidity and temperature from the DHT11 sensor and print the value on the screen. In this lesson, we will gradually increase and decrease the luminance of an LED with PWM (Pulse-width modulation) technology, which looks like breathing. In this lesson, we will take pictures with the RaspiCam using the system() function. The system() function let us use the pre-installed camera programs raspistill (picture taking) and raspivid (video taking). Add a text to the Source Code that prints on the screen 5 seconds before the camera starts to take (a) picture(s). Hint: to pause 5 seconds, you can use: delay(5000); The program takes only a picture after the Button has pressed. Hint: Take the inspiration from the Source Code "Control LED by Button". In this lesson, we'll write a test program for the PIR sensor. The LED goes on after the PIR sensor has been triggered. In this lesson, we'll combine code from the PIR sensor getting started lessen and the adding a LED to it. Make the code from the lesson "PIR sensor - Getting started" available in an editor or IDE, so that you can take this code as starting point. Configuration of the I2C Interface. Project example: BMP180, Getting the Barometer sensor up and running. Distance measurement In this lesson, we'll write a program to measure the distance and print the result in cm and inch. This code is a very good base for all kind of projects where you wanna use an ultrasonic sensor. In this lesson, we'll will prepare the Linux system (Raspbian) to be able to send Emails. After that, we can send text emails, attached files or both. In this lesson, we'll setup a project with a Button and the Raspicam. The press of the Button (Door Bell) will trigger the camera to take a picture. After the picture has been taken, it will be send to a pre-defined Email address from out of our C Code. In this summary, I will give you some recommendations for going further in C development. Installation of MonoDevelop on the Raspberry Pi In this lesson, we'll take several Arduino example sketches and convert them into C code for the Raspberry Pi..
https://www.udemy.com/introduction-to-c-programming-for-the-raspberry-pi/
CC-MAIN-2017-17
refinedweb
1,020
80.31
Solution to a chatterbox FAQ: what modules required are shipped with Perl? Which are already on the system? This cli script sits at the corner of my desk awaiting the next time I am looking up Perl modules at search.cpan.org. Finding the module I am interested in, I examine its directory (like: ) ... there are a number of files listed, including Makefile.PL (or Build.PL), MANIFEST, README, and ...META.yml. I context-click on the META.yml file and click "Copy Link Location" to put the URL pointing to the META.yml file on the system clipboard. Then I run the snippet below to quickly get the overview of this module's prerequisites. #!/usr/bin/env perl # Last modified: 10 Oct 2006 at 12:02 PM EDT # Author: Soren Andersen <intrepid -AT- perlmonk *dot* org> # $Id$ use strict; use warnings; use YAML qw/ Load Dump LoadFile /; use LWP::Simple; use POSIX qw(isatty); sub coremod { "" }; sub hr; sub dimmer; sub find_longest_keystring; sub mtest; sub testyml { my $metayml_uri = (shift(@_) || ' +META.yml'); my $docu; if( $docu = get $metayml_uri ) { return $docu } die "Could not retrieve '$metayml_uri'. Network troubles? Bad URI? +"; } ## And now a brief interlude of presentational trivia, not very intere +sting my $screenW = $ENV{COLUMNS} || 42; my $unxterm = isatty(*STDOUT) && $^O !~/MSWin32/ ? 1 : 0; if ($unxterm) { require Term::ANSIColor and import Term::ANSIColor ('colored'); #print colored("Using Term::ANSIColor", 'dark white'), "\n"; } ## done with interlude, back to main show my $metadoc = testyml (shift(@ARGV) || undef); my $modmeta = Load( $metadoc ); if( $modmeta->{requires} ) { my ($k,$v); my $fmtlen; my %reqrs = %{ my($mkl,@hash) = find_longest_keystring($modmeta->{requires}); $fmtlen = $mkl || 28; my $rh = {@hash}; }; if (eval "use Module::CoreList; 1" and not $@) { no warnings ('redefine','once'); sub coremod { my($pm) = @_; my $presence_in_core = $Module::CoreList::version{$]}{$pm} +; return "\n" unless defined $presence_in_core; my $pmv; $pmv = $presence_in_core == 0 ? "without a VERSION number" : "version $presence_in_core"; my $prn = Module::CoreList->first_release($pm); my $note = <<" ELEPHANT"; CORE: $pm was first included in the core Perl distribution at Perl r +elease $prn The present Perl system shipped with $pm $pmv ELEPHANT return $note; } } print hr; printf <<" YODOWN" %-${fmtlen}s %s %s%s YODOWN => ($k,($v eq '0'? 'any version':"at version $v") , mtest($k), coremo +d($k)) while ($k,$v) = each %reqrs; print hr; } else # there are no prerequisite modules or pragmata listed { print "No requires for $modmeta->{name}\n"; } sub mtest { my $installed_version; my $wherep; my $modname = shift(); my $modlibp = $modname; $modlibp =~ s{ :: } {/}xg; $modlibp .= '.pm'; my $can_req = eval "use $modname; 1;"; if ($can_req and not $@) { no strict 'refs'; $wherep = $INC{ $modlibp }; $installed_version = (${$modname.'::VERSION'}) || 0; } else { return colored(sprintf( "%-32s is not installed"=> $modname) , 'cyan') if ($unxterm); return sprintf( "%-32s is not installed"=> $modname) } if ($unxterm) { colored( sprintf('%-32s v%4s found as %s' => ($modname , $installed_version , $wherep)) , 'magenta' ); } else { sprintf('%-32s v%-4s found as %s' => ($modname , $installed_version , $wherep)) } } sub find_longest_keystring { my %rethash = %{ shift() }; return () unless 1 * @{[ %rethash ]}; delete $rethash{'perl'}; my $l_maxed_at = 0; for (keys(%rethash)) { $l_maxed_at = length() > $l_maxed_at ? length() : $l_maxed_at } return ( $l_maxed_at, %rethash ); } sub hr { my $decor = $unxterm ? dimmer("-" x $screenW) : ("-" x $screenW); $decor . "\n"; } sub dimmer { colored( shift() , 'dark white' ); } __END__ =head1 NAME METAreqWeb =head1 SYNOPSIS ./METAreqWeb [ < +.16/META.yml> ] =cut. • another intruder with the mooring in the heart of the Perl On on Oct 10, 2006, grinder wrote:. Nice code, but, I hate to break it to you, but you're using the wrong web site. If you used Randy Kobes's site, you'd already have it on the page: YAML-AppConfig @ kobes Glad I could provide some inspiration. I'd be very interested in seeing a Bookmarklet, indeed, for CPAN module information! Very cool. ;-) I do have to make a correction, however, for the benefit of those that cannot read the code. Listing the modules required by a chosen CPAN module is only 1/3 of the functionality of the solution shown above. The other 2/3 are: Changing websites to Kobe or CPANTS isn't going to accomplish the latter 2/3 of the functionality of the code above (nor answer the FAQ chatterbox question, "How can I tell whether I have that module already?", that prompted this contribution. The latter 2 operations are fundamentally local in nature and nothing short of a complex client-side scripting project is going to make that info available in the http user agent (browser). Boy, I did a good job of moderating my tone in this response and not displaying my disappointment over receiving such a careless, clueless comment / evaluation / feedback ... didn't I. grinder usually does better. Soren A / somian / perlspinr / Intrepid -- I was managing with a humbler self made version. This one is great! I appreciate your putting of both versions (local and CPAN's) at the same column. Tron Wargames Hackers (boo!) The Net Antitrust (gahhh!) Electric dreams (yikes!) Office Space Jurassic Park 2001: A Space Odyssey None of the above, please specify Results (107 votes), past polls
http://www.perlmonks.org/?node_id=577441
CC-MAIN-2014-35
refinedweb
820
60.85
Print paths in a binary tree We learned various kind of traversals of a binary tree like inorder, preorder and postorder. Paths in a binary tree problem require traversal of a binary tree too like every other problem on a binary tree. Given a binary tree, print all paths in that binary tree What is a path in a binary tree? A path is a collection of nodes from the root to any leaf of the tree. By definition, a leaf node is a node which does not have left or right child. For example, one of the paths in the binary tree below is 10,7,9. Paths in a binary tree: thoughts It is clear from the problem statement that we have to start with root and go all the way to leaf nodes. Question is do we need to start with root from each access each path in binary tree? Well, no. Paths have common nodes in them. Once we reach the end of a path (leaf node), we just move upwards one node at a time and explore other paths from the parent node. Once all paths are explored, we go one level again and explore all paths from there. This is a typical postorder traversal of a binary tree, we finish the paths in the left subtree of a node before exploring paths on the right subtree We process the root before going into left or right subtree to check if it is the leaf node. We add the current node into the path till now. Once we have explored left and right subtree, Let’s take an example and see how does it work. Below is the tree for each we have to print all the paths in it. First of all our list of paths is empty. We have to create a current path, we start from the root node which is the node(10). Add node(10) to the current path. As node(10) is not a leaf node, we move towards the left subtree. node(7) is added to the current path. Also, it is not a leaf node either, so we again go down the left subtree. node(8) is added to the current path and this time, it is a leaf node. We put the entire path into the list of paths or print the entire path based on how we want the output. At this point, we take out node(8) from the current path and move up to node(7). As we have traversed the left subtree node(7) we will traverse right subtree of the node(7). node(9) is added now to the current path. It is also a leaf node, so again, put the path in the list of paths. node(9) is moved out of the current path. Now, left and right subtrees of node(7) have been traversed, we remove node(7) from the current path too. At this point, we have only one node in the current path which is the node(10) We have already traversed the left subtree of it. So, we will start traversing the right subtree, next we will visit node(15) and add it to the current path. node(15) is not a leaf node, so we move down the left subtree. node(18) is added to the current path. node(18) is a leaf node too. So, add the entire path to the list of paths. Remove node(18) from the current path. We go next to the right subtree of node(15) node(19) node(19) is also a leaf node, so the path is added to the list of paths. Now, the left and right subtrees of node(15) node(10) Print paths in a binary tree: implementation package com.company.BST; import java.util.ArrayList; /** * Created by sangar on 21.10.18. */ public class PrintPathInBST { public void printPath(BinarySearchTree tree){ ArrayList<TreeNode> path = new ArrayList<>(); this.printPathRecursive(tree.getRoot(), path); } private void printPathRecursive(TreeNode root, ArrayList<TreeNode> path){ if(root == null) return; path.add(root); //If node is leaf node if(root.getLeft() == null && root.getRight() == null){ path.forEach(node -> System.out.print(" " + node.getValue())); path.remove(path.size()-1); System.out.println(); return; } /*Not a leaf node, add this node to path and continue traverse */ printPathRecursive(root.getLeft(),path); printPathRecursive(root.getRight(), path); //Remove the root node from the path path.remove(path.size()-1); } } Test cases(); } } Tree node definition package com.company.BST; /** * Created by sangar on 21.10.18. */ public class TreeNode<T> { private T value; private TreeNode left; private TreeNode right; public TreeNode(T value) { this.value = value; this.left = null; this.right = null; } public T getValue(){ return this.value; } public TreeNode getRight(){ return this.right; } public TreeNode getLeft(){ return this.left; } public void setValue(T value){ this.value = value; } public void setRight(TreeNode node){ this.right = node; } public void setLeft(TreeNode node){ this.left = node; } } Complexity of above algorithm to print all paths in a binary tree is O(n). Please share if there is something wrong or missing. If you are preparing for Amazon, Microsoft or Google interviews, please signup for interview material for free.
https://algorithmsandme.com/tag/print-all-paths-in-binary-search-tree/
CC-MAIN-2019-18
refinedweb
869
75.3
. Many cracking tools are available for free that use some techniques like a brute force to crack a user password. This type of tool tries every sequence of characters and tries to crack the password. So to prevent this type of attack, we shall not choose a password that is of short length or can be easily guessed. While creating a password, we need to follow the below rules. - The password length must be atleast 8 characters. - The password should contain a mixture of both uppercase and lowercase characters. - The password should contain a mixture of digits and letters. - The password should contain at least one special character. Creating a password generator using Python In this tutorial, we will learn how to create a password generator using python. This password generator can be used to generate strong passwords based on the rules mentioned above. To follow this tutorial, it is assumed that you have a basic knowledge of python. It is recommended to execute all the code block yourself for better understanding. Then, you can use an IDE like the open-source VS code or PyCharm for writing your code. Writing the code Let us build our password generator. First, our password generator must ask the user to enter the length of the password. Next, we need to select random characters from the mixture of uppercase, lowercase, digits, and special characters. The random characters will be combined to form a string. This string will be our required password. So, we will display it to the user in the console. To build our program, we first need to import the required libraries into our python program. To build the password generator, we will require two libraries. The first one is the string module. The string module has built-in attributes that store all the uppercase letters, lowercase letters, digits, and special characters. The second module that we will use is the random module. The random module has built-in functions that will provide randomness to our password generator. Our program will use the random module to select random characters for the password from a set of characters. So, let us import the required modules into our code. import string import random After importing the required libraries, we will convert the ascii_uppercase, ascii_lowercase, punctuations attributes of the string module into a list. Next, we will use the list comprehension of python to create a list of numbers from 0-9. See the below code for an illustration. uppercase_letters = list(string.ascii_uppercase) lowercase_letters = list(string.ascii_lowercase) punctuations = list(string.punctuation) digits = [str(i) for i in range(10)] After converting the string into a list, we need to create an empty list and extend it with the list of uppercase, lowercase, punctuation characters, and the digits that we have created. See the below code for an illustration. characters = [] characters.extend(lowercase_letters) characters.extend(uppercase_letters) characters.extend(punctuations) Next, we use the input() function of python to prompt the user to enter the length of the password. After taking the length from the user, we will use the choice() function of the random module to choose random characters from the list of characters. Then, we use the join() method of the string to join the characters and convert them into a string. See the below code for illustration. length = int(input('Enter the length of the password : ')) password = ''.join(random.choice(characters) for _ in range(length)) print(password) In the above code, we use the choice() function of the random module to generate a random string of characters. This random string of characters will be our required password which can’t be cracked easily. Final Code No, let us merge our codes to build our final password generator program. See the below code for an illustration. You can copy the code by clicking the copy button present in the top menu of the below code block. import string import random uppercase_letters = list(string.ascii_uppercase) lowercase_letters = list(string.ascii_lowercase) punctuations = list(string.punctuation) characters = [] characters.extend(lowercase_letters) characters.extend(uppercase_letters) characters.extend(punctuations) length = int(input('Enter the length of the password : ')) password = ''.join(random.choice(characters) for _ in range(length)) print(password) The above code will prompt a user to enter the length of the password and then generate a strong password of the required length. On running the above code, we will get the output as shown in the below image. Conclusion In this tutorial, we have seen how we can use the string module and the random module of python to build a strong password generator. You may also want to see our step-by-step guide on generating QR codes in python.
https://www.codeunderscored.com/how-to-create-a-password-generator-using-python/
CC-MAIN-2022-21
refinedweb
783
57.37
#include <qvaluevector.h> QValueVector is a Qt implementation of an STL-like vector container. It can be used in your application if the standard vector is not available for your target platforms. QValueVector is part of the Qt Template Library. QValueVector<T> defines a template instance to create a vector of values that all have the class T. QValueVector does not store pointers to the members of the vector; it holds a copy of every member. QValueVector is said to be value based; in contrast, QPtrList and QDict are pointer based. QValueVector contains and manages a collection of objects of type T and provides random access iterators that allow the contained objects to be addressed. QValueVector owns the contained elements. For more relaxed ownership semantics, see QPtrCollection and friends, which are pointer-based containers. QValueVector: for example, all classes derived from QObject and thus all classes that implement widgets. Only values can be used in a QValueVector. To qualify as a value the class must provide: Note that C++ defaults to field-by-field assignment operators and copy constructors if no explicit version is supplied. In many cases this is sufficient. QValueVector uses an STL-like syntax to manipulate and address the objects it contains. See this document for more information.ValueVector<int> vec1; // an empty vector vec1[10] = 4; // WARNING: undefined, probably a crash QValueVector<QString> vec2(25); // initialize with 25 elements vec2[10] = "Dave"; // OK Whenever inserting, removing or referencing elements in a vector, always make sure you are referring to valid positions. For example: void func( QValueVector<int>& vec ) { if ( vec.size() > 10 ) { vec[9] = 99; // OK } }; The iterators provided by vector are random access iterators, therefore you can use them with many generic algorithms, for example, algorithms provided by the STL or the QTL. Another way to find an element in the vector is by using the std::find() or qFind() algorithms. For example: QValueVector<int> vec; ... QValueVector<int>::const_iterator it = qFind( vec.begin(), vec.end(), 3 ); if ( it != vector.end() ) // 'it' points to the found element It is safe to have multiple iterators on the vector at the same time. Since QValueVector<int> vec( 3 ); vec.push_back( 1 ); vec.push_back( 2 ); vec.push_back( 3 ); ... if ( !vec.empty() ) { // OK: modify the first element int& i = vec.front(); i = 18; } ... QValueVector<double> dvec; double d = dvec.back(); // undefined behavior Because QValueVector manages memory dynamically, it is recommended that you contruct a vector with an initial size. Inserting and removing elements happens fastest when: By creating a QValueVector is shared implicitly, which means it can be copied in constant time. If multiple QValueVector instances share the same data and one needs to modify its contents, this modifying instance makes a copy and modifies its private copy; it thus does not affect the other instances. This is often called "copy on write". If a Q. Vectors can be also sorted with various STL algorithms , or it can be sorted using the Qt Template Library. For example with qHeapSort(): Example: QValueVector<int> v( 4 ); v.push_back( 5 ); v.push_back( 8 ); v.push_back( 3 ); v.push_back( 4 ); qHeapSort( v ); QValueVector stores its elements in contiguous memory. This means that you can use a QValueVector in any situation that requires an array. See also Qt Template Library Classes, Implicitly and Explicitly Shared Classes, and Non-GUI Classes. This operation costs O(1) time because QValueVector is implicitly shared. The first modification to the vector does takes O(n) time, because the elements must be copied. See also push_back() and insert(). Returns a const reference to the element with index i. If ok is non-null, and the index i is out of range, *ok is set to FALSE and the returned reference is undefined. If the index i is within the range of the vector, and ok is non-null, *ok is set to TRUE and the returned reference is well defined. See also empty() and front(). Returns a const reference to the last element in the vector. If there is no last element, this function has undefined behavior. See also empty() and front(). Returns a const iterator pointing to the beginning of the vector. If the vector is empty(), the returned iterator will equal end(). This function is provided for STL compatibility. It is equivalent to isEmpty(). Returns a const iterator pointing behind the last element of the vector. Removes all elements from first up to but not including last and returns the position of the next element. See also empty() and last(). See also empty() and back(). Returns a const reference to the first element in the vector. If there is no first element, this function has undefined behavior. See also empty() and back(). Inserts n copies of x immediately before position x. See also empty() and first(). All iterators of the current vector become invalidated by this operation. The cost of such an assignment is O(1) since QValueVector is implicitly shared. Assigns v to this vector and returns a reference to this vector. All iterators of the current vector become invalidated by this operation. The cost of this assignment is O(n) since v is copied. Returns TRUE if each element in this vector equals each corresponding element in x; otherwise returns FALSE. Returns a const reference to the element at index i. If i is out of range, this function has undefined behavior. This function is provided for STL compatibility. This function is provided for STL compatibility. It is equivalent to append(). This function is provided for STL compatibility. It is equivalent to count(). See also empty().
http://www.linuxmanpages.com/man3/QValueVector.3qt.php
crawl-003
refinedweb
930
60.11
Glow QML Type Generates a halo like glow around the source item. More... Properties - cached : alias - color : alias - radius : alias - samples : alias - source : alias - spread : alias - transparentBorder : alias Detailed Description The Glow effect blurs the alpha channel of the source and colorizes it with color and places it behind the source, resulting in a halo or glow around the object. The quality of the blurred edge can be controlled using samples and radius and the strenght of the glow can be changed using spread. The glow is created by blurring the image live using a gaussian blur. Performing blur live is a costly operation. Fullscreen gaussian blur with even a moderate number of samples will only run at 60 fps on highend graphics hardware. Example The following example shows how to apply the effect. import QtQuick 2.0 import QtGraphicalEffects 1.0 Item { width: 300 height: 300 Rectangle { anchors.fill: parent color: "black" } Image { id: butterfly source: "images/butterfly.png" sourceSize: Qt.size(parent.width, parent.height) smooth: true visible: false } Glow { anchors.fill: butterfly radius: 8 samples: 17 color: "white" source: butterfly } }". Radius defines the softness of the glow. A larger radius causes the edges of the glow to appear more blurry. Depending on the radius value, value of the samples should be set to sufficiently large to ensure the visual quality. The ideal blur is acheived by selecting samples and radius such that samples = 1 + radius * 2, such as: By default, the property is set to floor(samples/2). This property defines how many samples are taken per pixel when edge softening blur calculation is done. Larger value produces better quality, but is slower to render. Ideally, this value should be twice as large as the highest required radius value plus one, such as: By default, the property is set to 9. This property is not intended to be animated. Changing this property will cause the underlying OpenGL shaders to be recompiled. This property defines the source item that is going to be used as source for the generated glow. Note: It is not supported to let the effect include itself, for instance by setting source to the effect's parent. This property defines how large part of the glow color is strenghtened near the source edges. The values range from 0.0 to 1.0. By default, the property is set to 0.5. This property determines whether or not the effect has a transparent border. When set to true, the exterior of the item is padded with a transparent edge, making sampling outside the source texture use transparency instead of the edge pixels. Without this property, an image which has opaque edges will not get a blurred edge. By default, the property is set to true. Set it to false if the source already has a transparent edge to make the blurring a tiny bit faster. In the snippet below, the Rectangle on the left has transparent borders and has blurred edges, whereas the Rectangle on the right does not. import QtQuick 2.0 import QtGraphicalEffects 1.0 Rectangle { width: 180 height: 100 Row { anchors.centerIn: parent spacing: 16 Rectangle { id: normalRect width: 60 height: 60 color: "black" radius: 10 layer.enabled: true layer.effect: Glow { samples: 15 color: "blue" transparentBorder: false } } Rectangle { id: transparentBorderRect width: 60 height: 60 color: "black" radius: 10 layer.enabled: true layer.effect: Glow { samples: 15 color: "blue" transparentBorder: true } } } } >>IMAGE.
https://doc.qt.io/archives/qt-5.6/qml-qtgraphicaleffects-glow.html
CC-MAIN-2022-05
refinedweb
570
67.04
It Seemed Like A Good Idea At The Time: PyMongo's "use_greenlets" The road to hell is paved with good intentions. This is the second of a four-part series on regrettable decisions we made when we designed PyMongo. This winter we're preparing PyMongo 3.0, and we have an opportunity to make big changes. I'm putting our regrettable designs to rest, and writing their epitaphs as I go. Last week I wrote about the first regrettable decision, "start_request". Today I'll tell you the story of the second: PyMongo and Gevent. The Invention Of "use_greenlets" As I described in last week's article, I committed my first big changes to connection pooling in PyMongo in March 2012. Once I'd improved PyMongo's connection pool for multi-threaded applications, my boss Bernie asked me to improve PyMongo's compatibility with Gevent. The main problem was, PyMongo wanted to reserve a socket for each thread, but Gevent uses greenlets in place of threads. I didn't know Gevent well, but I forged ahead. I added a "use_greenlets" option to PyMongo; if True, PyMongo reserved a socket for each greenlet. I made a separate connection pool class called GreenletPool: it shared most of its code with the standard Pool, but instead of using a threadlocal to associate sockets with threads, it used a simple dict to associate sockets with greenlets. A weakref callback ensured that the greenlet's socket was reclaimed when the greenlet died. Half A Feature The "use_greenlet" option and the GreenletPool didn't add too much complexity to PyMongo. But my error was this: I only gave Gevent users half a feature. My "improvement" was as practical as adding half a wheel to a bicycle. At the time, I clearly described my half-feature in PyMongo's documentation: Using Gevent Without Threads Typically when using Gevent, you will run from gevent import monkey; monkey.patch_all()early in your program's execution. From then on, all thread-related Python functions will act on greenlets instead of threads, and PyMongo will treat greenlets as if they were threads transparently. Each greenlet will use a socket exclusively by default. Using Gevent With Threads If you need to use standard Python threads in the same process as Gevent and greenlets, you can run only monkey.patch_socket(), and create a Connection instance with use_greenlets=True. The Connection will use a special greenlet-aware connection pool that allocates a socket for each greenlet, ensuring consistent reads in Gevent. ReplicaSetConnection with use_greenlets=Truewill also use a greenlet-aware pool. Additionally, it will use a background greenlet instead of a background thread to monitor the state of the replica set. Hah! In my commit message, I claimed I'd "improved Gevent compatibility." What exactly did I mean? I meant you could use PyMongo after calling Gevent's patch_socket() without having to call patch_thread(). But who would do that? What conceivable use case had I enabled? After all, once you've called patch_socket(), regular multi-threaded networking code doesn't work. So I had not allowed you to mix Gevent and non-Gevent code in one application. Update: Peter Hansen explained to me exactly what I was missing, and I've written a followup article in response. What was I thinking? Maybe I thought "use_greenlets" worked around a bug in Gevent's threadlocals, but Gevent fixed that bug two years prior, so that's not the answer. I suppose "use_greenlets" allowed you to use PyMongo with multiple Gevent loops, one loop per OS thread. Gevent does support this pattern, but I'm uncertain how useful it is since the Global Interpreter Lock prevents OS threads from running Python code concurrently. I'd written some clever code that was probably useless, and I greatly confused Gevent users about how they should use PyMongo. Youthful Indiscretion It's been three years since I added "use_greenlets". The company was so young then. We were called 10gen, and we were housed on Fifth Avenue in Manhattan, above a nail salon. The office was cramped and every seat was taken. There was no place to talk: my future boss Steve Francia interviewed me walking around Union Square. Eliot Horowitz and I negotiated my salary in the stairwell. The hardwood floors were bent and squeaky. The first day I came to work I wore motorcycle boots, and the racket they made on those bad floors made me so self-conscious I never wore them to work again. When I sat down, my chair rolled downhill from my desk and bumped into Meghan Gill behind me. The company was young and so was I. When Bernie asked me to improve PyMongo's compatibility with Gevent, I should've thought much harder about what that meant. Instead of the half-feature I wrote, I should have given you either a whole feature or no feature. The whole feature would have allowed you to use PyMongo with Gevent and no monkey-patching at all, provided that you set "use_greenlets". If "use_greenlets" was set to True, PyMongo would associate sockets with greenlets instead of threads, and it would use Gevent's socket implementation instead of the standard library's. This would allow Gevent to properly suspend the current greenlet while awaiting network I/O, but you could still mix Gevent and non-Gevent code in one application. The Death Of "use_greenlets" But even better than the whole feature is no feature. So that is what I have implemented for PyMongo 3.0: in the next major release, PyMongo will have no Gevent-specific code at all. PyMongo will work with Gevent's monkey.patch_all() just like any other Python library does, and use_greenlets is gone. In our continuous integration server we'll test Gevent and, if practical, other monkey-patching frameworks like Eventlet and Greenhouse, to make sure they work with PyMongo. But we won't privilege Gevent over the other frameworks, nor distort PyMongo's design for the sake of a half-feature no one can use. Post-Mortem The lesson here is obvious: gather requirements. It's harder for an open source author to gather requirements than it is for a commercial software vendor, but it's far from impossible. Gevent has a mailing list, after all. At the time it didn't occur to me to discuss with Gevent users what they wanted from PyMongo. Nowadays I'd know better. Especially when I'm not scratching my own itch, when I'm integrating with a library I don't use, I need to define rigorously what need I'm filling. Otherwise I'm meeting you in a foreign country with a ship full of the wrong goods for trade. The same challenge presents itself to me now with Motor, my async driver for MongoDB. So far Motor has only worked with Tornado, an async framework I've used and know well. But I'm going to start integrating Motor with asyncio and, eventually, Twisted, and I need to be awfully careful about gathering requirements. One technique I'll use is eating my own hamster food: Before I release the version of Motor that supports asyncio, I'll port Motor-Blog, the software that runs this site, from Tornado to asyncio. That way there will be at least one real-world application that uses Motor and asyncio before I release the new version. The next installment in "It Seemed Like A Good Idea At The Time" is PyMongo's "copy_database".
https://emptysqua.re/blog/it-seemed-like-a-good-idea-at-the-time-pymongo-use-greenlets/
CC-MAIN-2019-18
refinedweb
1,247
63.8
FWIW, I just pushed a change to cordova-build.xml that let me do the following: - git clone flex-asjs - cd flex-asjs - git checkout develop - mvn clean install - cd examples/flexjs/MobileStocks - mvn clean install - ant -f ../../../cordova-build.xml I didn't get any rat errors. There were some warnings on the GCC compile on the last step. Then: - ant -f ../../../cordova-build.xml run.android And it showed up on my android phone. The run.android took several minutes to do a final build before installing on the device. HTH, -Alex On 10/21/16, 4:45 PM, "[email protected] on behalf of Carlos Rovira" <[email protected] on behalf of [email protected]> wrote: >> What I don't know how to do is replicate what cordova_build.xml does in >> Maven. That's where we could use Chris or other Maven experts. >> >> >Yes mavenizing a simple project is not a problem (my MDL project and the >example are proof that is easy thank to Chris's work in preparing the >entire project. I think as well we need Chris only in something new that >is >not implemented yet. > > >> Carlos, what was your setup when you tried the Ant script? Were you >> working from the repo, or some other configuration? >> > >I has the repo synchronized with source tree, and as you guys make some >changes I pull to my local and rebuild 0.8.0-snapshot with maven and >continue working. Now for MobileStock: if try to build with maven it arise >that many files are without license (see rat.txt). That's easy to solve, >just check the rat file and see what files are and add license. But this >told me that no maven build was considered. > > > >> >> Thanks, >> -Alex >> >> On 10/21/16, 1:03 PM, "[email protected] on behalf of OmPrakash >>Muppirala" >> <[email protected] on behalf of [email protected]> wrote: >> >> >Chris, >> > >> >Can you please take this opportunity to create a wiki page on how to >> >create >> >a pom.xml or in other words - how to mavenize a project? It seems >>like we >> >are going to have more of this and obviously you dont want all this >>work >> >ending up on yourself. >> > >> >Thanks, >> >Om >> > >> >On Fri, Oct 21, 2016 at 1:01 PM, Christofer Dutz >> ><[email protected]> >> >wrote: >> > >> >> Hi Carlos, >> >> >> >> Thanks for that positive feedback. Ist incredibly nice to hear that >>:-) >> >> >> >> Usually as soon as I detect a new example not building with Maven, I >>add >> >> the missing poms. So if there us anything missing, just drop a nite >>and >> >> I'll take care of it. >> >> >> >> Chris >> >> >> >> >> >> >> >> Von meinem Samsung Galaxy Smartphone gesendet. >> >> >> >> >> >> -------- Ursprüngliche Nachricht -------- >> >> Von: Carlos Rovira <[email protected]> >> >> Datum: 21.10.16 21:30 (GMT+01:00) >> >> An: [email protected] >> >> Betreff: [FlexJS] Maveninze MobileStocks (was [FlexJS] Mobile Apps) >> >> >> >> Maybe Chris could help with that. He's the man that makes the "maven >> >>magic" >> >> >> >> One think to notice here. My laptop was recently reinstaled from zero >> >>with >> >> macOS Sierra. >> >> I used Homebrew and it was amazingly simple to configure the dev >> >> environment and I even no need to >> >> start adding environment variable (no JAVA_HOME, no M2_HOME, >> >>no...nothing) >> >> thanks to use maven as build tool >> >> >> >> Now trying to build MobileStocks with Ant is starting to complain >>"that >> >> FALCON_HOME doesn't exist", and then willl be come another... >> >> >> >> Evidently I must now to configure that, but I want to expose the >> >> incredible,amazing easy environment that is now FlexJS thanks to the >> >> mavenization. >> >> If we decided (If I remember well) to make maven as the official >>tool, >> >>we >> >> should try to make all project maven aware, so people coming does not >> >>have >> >> any problem with some parts build with ant and others with maven. >> >> >> >> just my opinion >> >> >> >> Thanks >> >> >> >> >> >> 2016-10-21 20:13 GMT+02:00 Alex Harui <[email protected]>: >> >> >> >> > We could probably make cordova-build.xml work with Maven output in >>the >> >> > target folder instead of bin-debug. But yes, I don't think Peter >>or I >> >> > understand how to use Maven with Cordova, so the last piece will >>still >> >> > require Ant until some other volunteer steps up. >> >> > >> >> > -Alex >> >> > >> >> > On 10/21/16, 11:00 AM, "Peter Ent" <[email protected]> wrote: >> >> > >> >> > >I used maven on a very complex project a number of years ago and >> >>don't >> >> > >really remember much about it. I can try to piece together a pom >>file >> >> > >using another example, but I would have no idea how to do >>something >> >>like >> >> > >the cordova-build.xml file. >> >> > > >> >> > >‹peter >> >> > > >> >> > >On 10/21/16, 12:16 PM, "[email protected] on behalf of >>Carlos >> >> > >Rovira" <[email protected] on behalf of >> >> > >[email protected]> wrote: >> >> > > >> >> > >>One final note, I'm building all with maven. I didn't try maven >>as >> >>you >> >> > >>posted ANT build instructions. >> >> > >>Are maven pom configured to work. It would be very handy >> >> > >>thanks! >> >> > >> >> >> > >>2016-10-21 18:12 GMT+02:00 Carlos Rovira < >> >> [email protected] >> >> > >: >> >> > >> >> >> > >>> Hi Peter, >> >> > >>> >> >> > >>> congrats for reaching the milestone. I'm trying but finding >>some >> >> > >>>problems: >> >> > >>> >> >> > >>> (Prerequisites: I'm on Mac and want to try iOS version, I >>already >> >>has >> >> > >>> Xcode installed. I don't have FB anymore. I installed Cordova >>vía >> >> > >>>NPM...all >> >> > >>> ok) >> >> > >>> >> >> > >>> *I run from MobileStocks folder, but ant told me that there's >>no >> >> > >>> bin/je-debug folder. Checking wiki url you gave I created >>manually >> >> > >>> bin/debug. finaly I get ANT BUILD SUCCESSFUL (maybe ant should >> >>create >> >> > >>>bin >> >> > >>> and js-debug folders?) >> >> > >>> >> >> > >>> * Then for your instructions I use "run.ios"...this is a file >>(I >> >> don't >> >> > >>> find any). I'm stuck there. >> >> > >>> >> >> > >>> For getting styling you mention, there's 2 approach, one to use >> >>what >> >> we >> >> > >>> have and try to style ( I think this is limited), the second is >> >>use >> >> > >>>some >> >> > >>> good library out there like MDL, BootStrap, or others. I'm on >>the >> >> works >> >> > >>>as >> >> > >>> you already know with MDL. Right now I'm doing components in >>the >> >> "mdl" >> >> > >>> namespace, but this is not the ideal scenario, since it would >>be >> >> great >> >> > >>>to >> >> > >>> get a MDL style in a js:Button without the need to change it to >> >> > >>>mdl:Button, >> >> > >>> only applying styles. >> >> > >>> >> >> > >>> I'm finding some more few things: >> >> > >>> >> >> > >>> * CSS styles already in place are very cumbersome and I think >>we >> >> would >> >> > >>> need to work on a clean separation to avoid mixing and >>generating >> >> side >> >> > >>> effect. Alex propose in other thread some compiler options to >> >>avoid >> >> > >>>include >> >> > >>> CSS...maybe this is a nice option. >> >> > >>> * classNames and typeNames are part of the problems, but only >>due >> >>to >> >> > >>>the >> >> > >>> before mentioned point. If we can compile without already set >> >>styles >> >> > >>>this >> >> > >>> could solve the problem. >> >> > >>> * With MDL I'm inserting classNames inside class components, >>what >> >>I >> >> > >>>don't >> >> > >>> like since is a clear mixing of AS3 code declaration with CSS >> >>styles. >> >> > >>> * from the experience I'm getting with MDL (and suppose that >>other >> >> > >>> libraries like bootstrap will be the same), those good looking >> >>styles >> >> > >>>are >> >> > >>> dependent from a concrete way of implementing the html tags and >> >>use >> >> of >> >> > >>>html >> >> > >>> class. Maybe a component need to create a surrounding div and >>then >> >> nest >> >> > >>>a >> >> > >>> span, and this maybe is not what our HTML implementation does. >>I >> >> think >> >> > >>>a >> >> > >>> right approach should be to use the HTML swc and be able to >>change >> >> the >> >> > >>> output to match what a concrete style demands. >> >> > >>> >> >> > >>> For example, I'm making a Card component (and btw learning how >> >>flexjs >> >> > >>> framework works): >> >> > >>> >> >> > >>> >> >> > >>> This could be some kind of a Panel...but is not a Panel, so >>better >> >> > >>>create >> >> > >>> a Card component, but if you see the structure, is completely >> >>made to >> >> > >>>use >> >> > >>> the MDL style... >> >> > >>> >> >> > >>> looking at the MobileStocks code, it seems, the approach is the >> >>first >> >> > >>>one, >> >> > >>> since is all made with FlexJS comps. In that scenario, I think >>we >> >> need >> >> > >>>as >> >> > >>> well a way to not be bloated with CSS styles that we don't know >> >>where >> >> > >>>came >> >> > >>> from. and start from a clean state. >> >> > >>> >> >> > >>> I think this is something like a prerequisite in order to be >>able >> >>to >> >> > >>>work >> >> > >>> in some kind of styling. >> >> > >>> >> >> > >>> Hope I could first build MobileStocks and try on my iPhone to >>get >> >>a >> >> > >>>look >> >> > >>> at what we are talking about. >> >> > >>> >> >> > >>> Thanks >> >> > >>> >> >> > >>> Carlos >> >> > >>> >> >> > >>> >> >> > >>> >> >> > >>> >> >> > >>> 2016-10-21 15:53 GMT+02:00 Peter Ent <[email protected]>: >> >> > >>> >> >> > >>>> Hi, >> >> > >>>> >> >> > >>>> We've been working on an improved FlexJS mobile app: >> >>MobileStocks. >> >> It >> >> > >>>>is >> >> > >>>> in the FlexJS examples directory. This example runs on both >> >>Android >> >> > >>>>and iOS >> >> > >>>> devices and is a version of MobileTrader, offering just two >> >>views. >> >> The >> >> > >>>> first view allows you to enter a stock symbol and a number of >> >> shares. >> >> > >>>>It >> >> > >>>> then puts that information into a DataGrid and a chart, >> >>monitoring >> >> the >> >> > >>>> change in prices and updating the grid and chart. The second >>view >> >> > >>>>allows >> >> > >>>> you to enter a symbol and watch it in a similar fashion. >> >> MobileStocks >> >> > >>>>uses >> >> > >>>> the FlexJS Storage project to retain the list of stocks >>between >> >> > >>>>sessions. >> >> > >>>> >> >> > >>>> MobileStocks uses Apache Cordova, making the app run on both >>iOS >> >>and >> >> > >>>> Android from a single code base. Cordova integration is >>handled >> >>by >> >> the >> >> > >>>> FlexJS Mobile project as well as the Storage project. >> >> > >>>> >> >> > >>>> Building and running the app is pretty simple and you can do >>it >> >>from >> >> > >>>>the >> >> > >>>> command line or from Flash Builder. If you want to use the >> >>command >> >> > >>>>line, >> >> > >>>> pull down the source and run ANT to build the js-debug >>directory. >> >> Then >> >> > >>>>run >> >> > >>>> "ant -f ../../../cordova-build.xml" to create the Apache >>Cordova >> >> > >>>> sub-project. Once that has done, connect your Android device >>to >> >>your >> >> > >>>> computer and run "ant -f ../../../cordova-build.xml >>run.android" >> >> which >> >> > >>>>will >> >> > >>>> download a little more and then install and run the app on >>your >> >> > >>>>device. >> >> > >>>> iOS users can do the same thing (use "run.ios") which will >>launch >> >> the >> >> > >>>> device simulator; you also need to have Xcode installed. >> >> > >>>> >> >> > >>>> You can run this example easily from Flash Builder by >>following >> >>the >> >> > >>>> instructions on the FlexJS wiki [1] and use the launch >> >> configurations >> >> > >>>>to >> >> > >>>> build and run the app. >> >> > >>>> >> >> > >>>> The example has shown us a couple of things. >> >> > >>>> >> >> > >>>> * We needed to make more beads to handle different types >>of >> >>data >> >> > >>>> providers in the pay-as-you-go world of FlexJS; this keeps the >> >>app >> >> as >> >> > >>>>small >> >> > >>>> as possible. >> >> > >>>> * We needed to add additional layouts that were more >> >>responsive >> >> to >> >> > >>>> resizing. >> >> > >>>> * We needed to fix a couple of bugs as well. >> >> > >>>> >> >> > >>>> Please give this a try if you can. The next step for the app >> >>would >> >> be >> >> > >>>> some nice styling. This my "developer's eye" which is just >> >>minimal, >> >> so >> >> > >>>> contribute some updates to that, if you can. >> >> > >>>> >> >> > >>>> [1]? >> >> > >>>> pageId=63406558 >> >> > >>>> >> >> > >>>> Regards, >> >> > >>>> Peter Ent >> >> > >>>> Adobe Systems/Apache Flex Project >> >> > >>>> >> >> > >>> >> >> > >>> >> >> > >>> >> >> > >>> -- >> >> > >>> >> >> > >>>.
http://mail-archives.apache.org/mod_mbox/flex-dev/201610.mbox/%3CD430450C.7828E%[email protected]%3E
CC-MAIN-2017-43
refinedweb
1,777
73.98
This action might not be possible to undo. Are you sure you want to continue? BHAGAVAD GITA By SRI SWAMI SIVANANDA Sri Swami Sivananda Founder of The Divine Life Society SERVE, LOVE, GIVE, PURIFY, MEDITATE, REALIZE So Says Sri Swami Sivananda A DIVINE LIFE SOCIETY PUBLICATION World Wide Web (WWW) Edition: 2000 WWW site: This WWW reprint is for free distribution © The Divine Life Trust Society Published By THE DIVINE LIFE SOCIETY P.O. SHIVANANDANAGAR—249 192 Distt. Tehri-Garhwal, Uttar Pradesh, Himalayas, India. Sri Swami Sivananda wants us to study daily at least one discourse of the scripture. Each discourse has been preceded by a short summary giving the substance of that discourse in a nutshell. It guides the lives of people all over the world. We are extremely grateful to Sri Swami Chidananda. so that its great lessons are ever fresh in our memory. Divine Life Society Shivanandanagar Rishikesh. iv .PUBLISHERS’ NOTE The Bhagavad Gita is one of the world-scriptures today. Mahatma Gandhi regarded it as the “Mother”. for his Foreword and assistance in the preparation of some of the summaries. to whom the children (humanity) turned when in distress.P. the World-President of the Divine Life Society. U. . . . 1 Prayer to the Guru . . . . . . . . . . . . . The Yoga of the Division of the Threefold Faith . . . 7 1. . . . . . 60 8. . . . . . . . . . . . . . . The Yoga of Distinction Between The Field & the Knower of the Field . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Yoga of the Division of the Three Gunas . . . . . . . . . . . . . . . . . . . . . .CONTENTS Publishers’ Note. . . . . . . . . . . . . 51 7. . . . 16 3. . . . . The Yoga of Renunciation of Action . . . . . . . . . . . . 115 17. . . . . . . . . . . Sankhya Yoga . . . . . . . . . . . . . . . . xvii Prayer to Vyasa . . . . . . . . . . . . . . . . . . . . . . . . . . . The Yoga of Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Yoga of the Divine Glories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 4. . . . . . . . . . . . . . . . . . . 124 v . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The Yoga of Liberation by Renunciation . . . . . . . . . . 84 12. The Yoga of Meditation . . . . . . . . . . . . . 65 9. . . . . . . The Yoga of the Despondency of Arjuna . . . . . . . . . . . . . . . . . . . . . . . . 71 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 13. . . . . . . . . . . . . . . . . 3 Gita Dhyanam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Prayer to Lord Krishna. iv Foreword . . . . . . . . . . . . . . . . . The Yoga of the Supreme Spirit . . . . . . . The Yoga of Devotion . . . . . . . . . . . . . . . . . . . 110 16. . . . . . . . . . . . . . . . . . . . . . . . . The Yoga of the Vision of the Cosmic Form. . . . . . . . . . . . . . . . . The Yoga of the Imperishable Brahman. . . . . . . . . . . . . . . . . . . . . . . . . . . The Yoga of Wisdom and Realisation . . . . . . . . . . . . . 77 11. . . . . . . . . . . . . . . . . . . . . 105 15. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 18. . . . . . . The Yoga of the Division Between the Divine and the Demoniacal . . . . . . . . . . . . . . . . . . . . . . . . . . The Yoga of Wisdom . . . . . . . . . . . . . . . . . . . . . . . . . . The Yoga of the Kingly Science & the Kingly Secret. . . . . vi Preface . . . . . . . . . . . 99 14. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Gita Mahatmya. . . . . . . . . . . . . . . . . . . . . . . vii Introduction . . . . . . . . . . . . . 9 2. he can just pass by without being perturbed. Swami Chidananda 10th July. I assure him of this. nor is it just a book of “religious teachings”. I commend this wonderful gift of God unto every man and woman. It transcends the bounds of any particular religion or race. The mystery of man. suffering. This holy scripture is not just an “old scripture”. fear. nor even a Hindu holy book. renewed strength and triumph. The Bhagavad Gita is a message addressed to each and every human individual to help him or her to solve the vexing problem of overcoming the present and progressing towards a bright future. perhaps. His life will become new from that moment.FOREWORD The modern man in this present decade of the second half of the 20th century is greatly in need of an effective guide to light. towards his or her supreme blessedness and highest welfare. But everything else that is of a purely philosophical. Therefore. the drama of the ascent of man from a state of utter dejection. Within its eighteen chapters is revealed a human drama. love and hate. fear and anxiety.—all these he can grasp and assimilate fully. sorrow and total breakdown and hopelessness to a state of perfect understanding. All clouds will vanish. Such things as seem to be particularly Hindu and therefore. of pain. It enables man to liberate himself from all limiting factors and reach a state of perfect balance. 1968 (Guru Purnima) vi . as also the path to perdition. The workings of your mind—the real problem to your welfare and happiness—how to overcome it. the secret of self-mastery and the way to peace amidst your daily activities and duties—all these and more you will find in this great treasure. not in reading but in what he takes from it. what the path to blessedness is. psychological. He will be wonderfully enriched and supremely blessed. This is the Gita. unhappiness and complication. Light will fill the heart and mind. is explained as perhaps nowhere else. He is groping. and is actually divine wisdom addressed to mankind for all times. complete freedom from grief. not acceptable to him as a person of another faith. this world and God. what course to adopt and how to move towards a better state of things. He sees only problems everywhere and no solutions are to be found anywhere. He does not know which way to turn. The Bhagavad Gita contains words of wisdom and practical teachings that contain the answers to the above-mentioned condition of the present-day individual. his life is filled with restlessness. To the Western reader I would suggest that he carefully reads through the entire book once. Then he should commence it a second time. Upon the second reading he should adopt the method of selectivity. in order to help human beings face and solve the ever-present problems of birth and death. Each discourse holds for you an invaluable new lesson and imparts a new understanding of yourself in a marvellous way. This is the experience of everyone in this world. inner stability and mental peace. It is yours by which to enrich your life. clarity. bondage. ethical and psychical nature. Those who are self-controlled and who are endowed with faith can reap the full benefit of the Gita. and expounded the rare secrets of Yoga. It is an ocean of knowledge. wisdom. namely. together with a wonderfully woven synthesis of these three. vii . spiritual upliftment and Self-realisation. It is full of divine splendour and grandeur. It is the essence of the soul-elevating Upanishads. Vedanta and action. Peace. sublime and soul-stirring spiritual truths. It is a book for eternity. Vedanta. It is a wonderful book with sublime thoughts and practical instructions on Yoga. It is a fountain of bliss. which is the science of the Soul. It comprises eighteen discourses of a total of 701 Sanskrit verses. Brahman. It is a marvellous book. In this unique book you will find an unbiased exposition of the philosophy of action. during the course of His most instructive and interesting talk with Arjuna. It was the day on which the scripture was revealed to the world by Sanjaya. The Gita is a rare and splendid flower that wafts its sweet aroma throughout the world. narrated in the Bhishma Parva of the Mahabharata. It brings peace and solace to souls that are afflicted by the three fires of mortal existence. It expounds very lucidly the cardinal principles or the fundamentals of the Hindu religion and Hindu Dharma. Param Padam and Gita are all synonymous terms. It is an inexhaustible spiritual treasure. The world is under a great debt of gratitude to Bhagavan Vyasa who presented this Song Celestial to humanity for the guidance of their daily conduct of life. A considerable volume of material has been compressed within these verses. All the teachings of Lord Krishna were subsequently recorded as the Song Celestial or Srimad Bhagavad Gita by Bhagavan Vyasa for the benefit of humanity at large. In all the spiritual literature of the world there is no book so elevating and inspiring as the Gita. revealed profound. On the battlefield of Kurukshetra. It is a universal scripture applicable to people of all temperaments and for all times. devotion. Bhakti and Karma. devotion and knowledge. Nirvana. profound in thought and sublime in heights of vision. It can be one’s constant companion of life. afflictions caused by one’s own body. You can milk anything from it. It is the wish-fulfilling gem. The Gita contains the divine nectar. It is your great guide. with life like that of a mushroom.PREFACE The Srimad Bhagavad Gita is a dialogue between Lord Krishna and Arjuna. Sri Krishna. The Gita is the cream of the Vedas. It is a vade-mecum for all. bliss. those caused by beings around one.. and those caused by the gods. It is not a catch-penny book. tree and cow. The Gita is a boundless ocean of nectar. It is the source of all wisdom. It is your supreme teacher. It is the immortal celestial fruit of the Upanishadic tree. creed. There are numerous commentaries on the Gita at the present time. It is one of the most authoritative books of the Hindu religion. There is nothing more to be attained beyond this. Sri Ramanuja and Sri Madhava dived into it and gave accounts of their interpretation and established their own philosophy. and a man of reason by that of Sri Shankara. This milk is the Bhagavad Gita. perfection and peace for all human beings. Just as the dark unfathomed depths of the ocean contain most precious pearls. You will have to dive deep into its depths with a sincere attitude of reverence and faith. so also the Bhagavad Gita contains spiritual gems of incalculable value. You will find here a solution for all your doubts. This sacred scripture is like the great Manasarovar lake for monks. Glory to Krishna. age or country. everlasting peace and perennial joy. Sri Krishna is their milker. It is the immortal song of the Soul. The more you study it with devotion and faith. It solves not only Arjuna’s problems and doubts. the whole of it is transformed into gold. It is a standard book on Yoga for all mankind. Arjuna is the calf who first tasted that milk of wisdom of the Self. universal and sublime. If the philosopher’s stone touches a piece of iron even at one point. The language is as simple as could be. A man of devotional temperament will be attracted by Sri Sridhara’s commentary. Even a man who has an elementary knowledge of Sanskrit can go through the book. which bespeaks of the glory of life. The instructions given by Sri Krishna are for the whole world. The Bhagavad Gita is a unique book for all ages. you will doubtless be transmuted into divinity. entitled Gita Rahasya. but also the world’s problems and those of every individual. sect. penetrative insight and clear. Sri Shankara. the joy of Devaki! He who drinks the nectar of the Gita through purification of the heart and regular meditation. A busy man with an active temperament will be greatly benefited by the commentary of Sri Gangadhar Lokamanya Tilak. Only then will you be able to collect its spiritual pearls and comprehend its infinitely profound and subtle teachings. renunciates and thirsting aspirants to sport in. They do not belong to any cult. The Gita is like an ocean. They are meant for the people of the whole world. The study of the Gita alone is sufficient for daily Swadhyaya (scriptural study). Anyone can do the same and bring out the most precious pearls of divine knowledge and give their own interpretation. if you live in the spirit of even one verse of the Gita. right thinking. Even so. attains immortality. eternal bliss. the more you will acquire deeper knowledge. the friend of the cowherds of Gokula. All your miseries will come to an end and you will attain the highest goal of life—immortality and eternal peace. Glory to the Gita! Glory to the Lord of the Gita! The teachings of the Gita are broad. It is the ocean of bliss in which seekers of Truth swim with joy and ecstasy. Based on the soul-elevating Upanishads—the ancient wisdom of seers and saints—the Gita prescribes methods which are within the reach of all. viii . salvation.If all the Upanishads should represent cows. milked by the divine Cowherd for the benefit of all humanity. freedom. A volume can be written on each verse. It has a message of solace. In the Gita the word “Avyaktam” sometimes refers to primordial Nature and sometimes to the Absolute Para Brahman also. In the Hatha Yogic texts it is stated: “At the junction of the rivers Yamuna and Ganga there is a young virgin”. Lord Krishna speaks from different levels of consciousness. Good commentaries written by realised sages will also be of immense help to you. Worldly-minded individuals. mind. which helps and guides them in the attainment of supreme bliss. You will be like the man who brought a horse to one who asked for saindava while taking food. the charioteer. The battle of the Mahabharata is still raging within. you should study it under a qualified teacher. one who is established in the Absolute. cannot grasp the essential teachings of the Gita. This itself proves clearly that God exists. senses. will the truths contained therein be revealed unto you like a fruit on the palm of your hand. the body is the chariot. the help of a teacher is necessary if you wish to know the right significance of the verses. without the help of a Guru. They will realise that there is a close connection between the verses in all the chapters. however intellectual they may be. mental impressions. It was given over five thousand years ago by Lord Krishna to Arjuna. Ignorance is Dhritarashtra. you will not be able to understand the proper meaning of the verses of the Gita. the senses are the five horses. and that one can attain perfection or liberation only by realising God. So. There is a great deal of repetition. that He is an embodiment of knowledge. None but the Lord Himself can bring out such a marvellous and unprecedented book which gives peace to its readers. and which has survived up to the present time. lust.The Bhagavad Gita is a gospel for the whole world. likes and dislikes. egoism. They are best calculated to create a deep and indelible impression in the mind of the aspirant. Such ignorant people say: “There is no intimate connection between the verses.” If they study the book with reverence and faith under a qualified teacher all their doubts would vanish. the indweller of your heart is Lord Krishna. In the Kathopanishad the term “brick” is used to denote the gods. greed. Therefore. The world is one huge battlefield. Only when studied with great and intense faith. The word saindava means salt as well as horse! ix . They are thrown in a disorderly manner. The real Kurukshetra is within you. cravings. They cavil and carp at the teachings. The esoteric meaning of this is that there is the Sushumna Nadi between the Ida and the Pingala. single-minded devotion and purity. pride and hypocrisy are your dire enemies. jealousy. the individual soul is Arjuna. It is meant for the generality of mankind. Guide For Study As the Gita contains subtle and profound teachings. Repetitions in the Gita and the Upanishads are useful repetitions. They enter into unnecessary discussions and useless debates. He learns the methods of controlling the senses and the mind and practising concentration and meditation. the nature of the middle term “Art”. the emotional and the rational. He is then given knowledge of the Field and the Knower of the Field. constantly perform action which is duty. will. which establishes the identity of the individual soul with the Supreme Soul. for. Arjuna experiences the magnificent Cosmic Vision and understands the glorious nature of a liberated being. Only then can you rejoice in the Self. Lord x . This may be achieved by doing one’s prescribed duties of life. It harmonises most wonderfully the philosophy of action. Arjuna is coached by Krishna for the attainment of knowledge of the Self in the spiritual university. Even so.Harmony in the Gita Man is a composite of three fundamental factors. Just as a student is coached in a university. Lord Krishna says to Arjuna: “Therefore. Only then will it move smoothly and reach the destination safely and quickly. feeling and cognition. The concluding six discourses treat of the path of knowledge. This is called the Tat-pada. the nature of “That”. The central teaching of the Gita is the attainment of the final beatitude of life—perfection or eternal freedom. sing the song of Soham. namely. Arjuna had various kinds of doubts. devotion and knowledge. Hence. One Yoga is as efficacious as the other. His knowledge is completed by an explanation of the divine attributes. Arjuna then learns the technique of Karma Yoga and renunciation of the fruits of actions. open his eyes and give him strength and courage. the heart of Lord Buddha and the hand of King Janaka. the three Gunas and the Purushottama. the three kinds of faith and the essence of the Yoga of renunciation. the nature of “Thou”. The three horses of this body-chariot—action. Each one is intimately or vitally connected with its precedent. All three must be harmoniously blended if you wish to attain perfection. illustrative of the three terms of the Mahavakya of the Sama Veda—“Tat Twam Asi—That Thou Art”. The Gita is divided into three sections. without attachment. man verily reaches the Supreme”. Lord Krishna’s opening remarks in the second discourse. that is. emotion and intellect—should work in perfect harmony. The Bhagavad Gita formulates the theories of the three paths without creating any conflict among them. There are three kinds of temperament—the active. In accordance with this view. be in tune with the Infinite. it is called the Asi-pada. the first six discourses deal with the path of action or Karma Yoga. This is followed by a description of the various manifestations of the Lord in order to prepare him for the vision of the Cosmic Form. The next six discourses explain the path of devotion. by performing action without attachment. It is called the Twam-pada. there are three Yogas—Jnana Yoga for a person of enquiry and rational temperament. Arjuna became very despondent. The eighteen discourses are not woven in a discordant manner. and Karma Yoga for a person of action. Bhakti Yoga for the emotional temperament. hear the soundless voice of the Soul and enjoy the sweet music of the eternal Self. which bespeak of the immortality of the soul. You should have the head of Sri Shankara. mental. mind and world. the Truth which is transcendental. Now you will not be bound by your actions since the idea of doership has been destroyed by the attainment of knowledge of the Self. you can rest in your true essential nature as Existence-Knowledge-Bliss Absolute and still be active in the affairs of the world. The sages of ancient times attained this mysterious and most marvellous state through the eye of intuition or the divine third eye. This is the keynote of the Gita. Real religion is the attainment of this transcendental. Behind the dynamic rotating electrons. music. motionless something. namely. Intellect is finite and cold. Arjuna placed his foot on the highest rung. which has neither a beginning. undying.Krishna cleared them one by one. You can ascend the summit of the hill of knowledge through science. supreme. analysis. Thus. This is the indirect method. undecaying Essence through constant and intense meditation. electrons. which is neither subtle nor gross. I will act according to Thy word”. The goal of science is to discover the one ultimate Truth which is the substratum of the atoms. immortal Soul which is the substratum of this body. Eventually. attained the supreme knowledge of the Self and exclaimed in joy: “O my Lord! my delusion has been destroyed. They then explained the things of this world in the light of their intuitive knowledge of the Self. A Vedantin is the real scientist. I am firm. the more I am puzzled. True life is identification with this Supreme Soul. art. The Two Ways The seers of the Upanishads emphatically declare that the real man is the all-pervading. etc. Nature. the food. motion and all physical and mental phenomena and laws of Nature by means of enquiry. which is behind the five sheaths. which has neither parts nor limbs. xi . present and future. intellectual and bliss sheaths. This is the direct method of Self-realisation. which exists in the past. or something beyond the intellect and the world”. vital. there is the static. Our Western scientists will grope in utter darkness if their purpose is only to invent some things for our physical convenience. You can become a liberated sage by annihilating the ego and the currents of likes and dislikes. observation. the body. by annihilating desires and cravings and destroying their residual potencies. middle nor end. Behind these changing phenomena there is the unchanging noumenon. He pushed Arjuna up the ladder of Yoga from one rung to the next. the unseen governor or hidden proprietor of this house. I have attained knowledge through Thy Grace. energy. The scientist who in the past proclaimed that there was nothing beyond this world now proclaims: “The more I know of phenomena. Real life is life in the eternal Soul. All my doubts have now vanished in toto. Only his mode of approach to the Truth is different. molecules. investigation and study of these laws in operation. The goal of life is to directly cognise or realise this self-luminous Self which is hidden in this body as fire is hidden in wood or as butter in milk. This Self is the inner ruler. From the effect you go to the cause and ultimately reach the causeless Cause or Para Brahman. Essence of the Gita The Gita again and again emphasises that one should cultivate an attitude of non-attachment or detachment. It urges repeatedly that an individual should live in the world like water on a lotus leaf. Therefore.2.Reconciliation of the Paths In the Vishnu Purana. All Deities are one. Detachment is born of Sattwa. Failures are not stumbling-blocks but steppingstones to success. “Therefore. You may stumble like a baby who is just learning to walk. In another place He praises Raja Yoga: “The Yogi is thought to be superior to the ascetics and even superior to men of knowledge. selfishness and passion and brings with it death. offering them to Brahman and abandoning attachment.22. In the Shiva Purana. It was not meant for Arjuna alone. O Arjuna. O Arjuna!”—VI. “He who does actions. In the Devi Bhagavatam. But. be thou a Yogi. In one place He praises Jnana Yoga: “Noble indeed are all these. Think of the Self constantly. he is established in Me alone as the supreme goal”—VII. steadfast in mind. In yet another place Lord Krishna praises the path of Bhakti Yoga: “The highest Purusha. or vice versa.19. detachment is wisdom and brings with it freedom. Lord Shiva is immensely praised whilst Lord Vishnu is secondary. without attachment do thou always perform action which should be done.10. for. The practice of detachment is a rigorous discipline. for his love is pure and divine. if you think deeply. they are different aspects of the Lord. the latter a divine one. Krishna praises each Yoga in order to create interest in the aspirant in his particular path. but I deem the wise man as My very Self. he is also superior to men of action. is not tainted by sin as a lotus leaf by water”—V. Attachment to the Lord is a potent antidote to annihilate all worldly attachments. The former is a demoniacal attribute. there is no room for any confusion. Attachment is due to infatuation. for. Abide in your centre. It is the offspring of the quality of Rajas. The Gita is a book for the people of the world at large. xii . the Divine Mother is given prominence above Lord Shiva and Lord Vishnu. but you will have to rise up again with a cheerful heart. He who has no attachments can really love others. Try to dwell always in your own Self. It is simply absurd to believe that Shiva is inferior to Vishnu. is attainable by unswerving devotion to Him alone within whom all beings dwell and by whom all this is pervaded!”—VIII. Attachment is born of ignorance. by performing action without attachment man reaches the Supreme”—III. Then all attachments will die automatically. Lord Krishna praises Karma Yoga: “The Yoga of action is superior to the renunciation of action”—V.18.46. A beginner is confused when he comes across these seemingly contradictory verses. All this is done in order to create in the aspirant intense and unswerving faith in his favourite Deity. In the same manner. Each Yoga is as efficacious as the other. Bhagavan Vishnu is highly eulogised and a secondary place is given to Lord Shiva. in one place in the Gita. who have no desire for enjoyments and whose impurities have been destroyed. “Therefore. Then they quote the Gita in support of their evil actions: “Weapons cut It not.17. Therefore. Recently someone wrote a criticism in the newspaper: “The Gita is not a sacred book at all. nor is he bound (by the action)”—XVIII. those who have not been purged of their faults and impurities would either disbelieve or misbelieve it. neither of them knows. Lord Krishna asked Arjuna to kill even his dear relations and preceptors”. It teaches violence. He is like Virochana who received spiritual instructions from Prajapati and took the body as being the Self on account of his perverted intellect. May the Lord grant them a subtle and pure intellect. Wonderful philosophy indeed! Devils can also quote scriptures. The teachings of the Gita can only be understood if you approach it with a reverential attitude of mind and with intense faith. Discipline and purification of the mind and the senses are the prerequisites for aspirants on the path of God-realisation. stand up and obtain fame.33. wind dries It not”—II. though he slays these people. These people are the followers of the Virochana school. The Upanishads declare: “To that high-souled man whose devotion to his preceptor is as great as that to the Lord. He slays not nor is He slain”—II. dispassion. They cannot hope to understand the teachings of the Gita as their wisdom has been destroyed by illusion and they have embraced the nature of demons. Verily by Me have they been already slain.23. be thou a mere instrument. “He who is free from the egoistic notion. They are evil-doing. knowledge as inculcated arises only in him who has purified himself by austerity. He is obviously a follower of the philosophy of the flesh. deluded and the vilest of men. and meditating upon their significance. whose intellect is untainted (by good or evil). control of the mind and senses. he slayeth not. performed either in this or in a previous birth.In Defence Some people study the Gita in order to find loopholes and criticise the teachings contained in it. water wets It not. Even when the nature of God is explained. For this reason an aspirant is expected to possess the qualifications of keen discrimination. Some people catch fish in the Ganges river to satisfy their palate. the secrets explained here become illumined”. O Arjuna!”—XI. and aversion to worldly attractions. He has read the Gita not to gain spiritual knowledge but to attack it. as was the case with Indra and Virochana. It is clear that this critic obviously has no real knowledge or understanding of the Gita. Conquer the enemies and enjoy the unrivalled kingdom. He cannot comprehend the depths of the Gita philosophy as his mind is callous and impervious to the reception of its truths.19. The answer to his criticism lies in a proper understanding of the following verses: “He who takes the Self to be the slayer and he who thinks He is slain. before he can practise the threefold Sadhana of hearing the scriptures. so also the instructions of a sage penetrate and settle down only in the hearts of aspirants whose minds are calm. fire burns It not. xiii . Just as coloured dye stands out more clearly only when the original material is pure white. reflecting upon them. You have to frequently make cross references before you get the right answer. Ramananda and the Gopis who could understand the secret of the Rasa Lila. He was not an Avatara or Incarnation. xiv . “Entering into demoniacal wombs and deluded birth after birth. clad in human form. He can do anything. Solutions to Conflicting Verses A critic says: “In the Gita. but see its connection with the previous and succeeding verses of the same discourse as well as of all the other discourses. not attaining Me. by standing on its hood? Did He not multiply Himself as countless Krishnas for the satisfaction of the Gopis? Who were the Gopis? Were they not God-intoxicated beings who saw Krishna alone everywhere. III. He was a passionate cowherd who lustfully played with the Gopis”. they thus fall. The Lord gave Arjuna the divine eye of intuition. they verily are possessed of the deceitful nature of demons and undivine beings”—IX. of vain knowledge and senseless. the Unmanifest. Chaitanya. When studying the Gita you should not confine the meaning to one verse exclusively. Mira.19-20. as having manifestation.inner spiritual strength and right understanding to comprehend the teachings of the Gita in their proper light and live in their spirit! Some ignorant people say: “Lord Krishna was not God. Did He not play miracles when He was a boy? Did He not show that He was the Avatara of Lord Hari? Did He not show His Cosmic Form to His mother when He was only a baby? Did He not subdue the serpent. “Empty of hopes. They were above body-consciousness.11-12. “These cruel haters—the worst among men in the world—I hurl these evil-doers into the womb of demons only”. Some thoughtless people begin to entertain a doubt and say: “How could the Gita have been taught to Arjuna on the battlefield in such a short time? It could not.. ‘Even a wise man acts in accordance with his own nature. it is said. not knowing My higher Being as the great Lord of all beings”. even in themselves? The sound of the flute would throw them in a state of ecstasy or holy communion.24. Our nature can be subdued by Sadhana. It was all a revelation to Arjuna. The Gopis only are qualified for this divine sport. what can restraint do?’ What then is the use of our attempt at controlling the senses and the mind when our nature is so powerful and overwhelming? How can our Sadhana overcome it?” In the very next verse. beings follow their nature. into a condition lower than that”-XVI. Lord Krishna distinctly advises us to control likes and dislikes. O Arjuna. Kaliya. “Fools disregard Me. of vain actions. immutable and most excellent form”—VII. Just listen to the fate of such people who cavil and carp at the Lord: “The foolish think of Me. His Grace can make the dumb man eloquent and the cripple a climber of mountains. Sukadeva.33.” This is wrong. knowing not My higher. draws to itself the five senses with the mind for the sixth. The Lord has also said that “one’s own duty is good”. to revolve as if mounted on a machine!’ Is man then a perfect slave? Is he like a straw tossed about here and there? Has he not any free will to act?” Krishna tries His best to persuade Arjuna to do his duty. excels. The power of Maya is invincible to even wise men. self-contented and self-satisfied. Yet another critic says: “In XV. Sattwa. xv . The wise too are affected by the three Gunas when they are not actually in the state of Samadhi. Even the residual good tendencies in the wise men work in accordance with the qualities of their nature. then how much more difficult it would be for worldly men to conquer it! For them. the natural duties can never be forsaken. by His illusive power. Of what avail is their effort to control the senses. One’s duty should in no case be ignored. namely. causing all beings. Brahman alone exists. But they have no attachment to the body and other objects of enjoyment and. The doctrine of non-dualism is quite correct.Those who disregard the Lord’s commandment: “Renouncing all actions in Me. having become a living soul in the world of life. ever steadfast and devoted to the One. with the mind centred in the Self free from hope and egoism and from mental fever. will not derive any benefit by such renunciation. So He speaks of Arjuna’s utter helplessness. therefore. Rajas and Tamas. So. Understand things in their proper light. the wise. for I am exceedingly dear to the wise and he is dear to Me”. As long as one is not free from ignorance. They are ever serene. is the director of the individual soul. How can we say that it is identical with Brahman? The doctrine of Advaita is therefore wrong”. do thou fight”.7. Being under the sway of one’s nature. are not affected mentally. The truth is that the individual soul and Brahman are one in essence. They do not long for objects not attained nor weep over things lost. In VII. and who sit quiet. He wants to extract work from him. the Lord says: “Of them. Advaita philosophy can be grasped only by a microscopic few. abiding in Nature’. XVIII. ‘The Lord dwells in the hearts of all beings. From the absolute point of view there is neither the individual soul nor Self-realisation. He speaks of other philosophical doctrines in different places to suit different kinds of aspirants. Lord Krishna says. All these schools eventually reach the Advaitic goal of oneness. the inner ruler. It is quite clear that the individual soul is a part of Brahman. and Lord Krishna wanted him to do just that. let him not lower himself.17. The Lord. qualified monism and pure monism are different rungs in the ladder of realisation. the Absolute. the Lord says: ‘An eternal portion of Myself.61. The Lord gives instructions according to the aspirant’s qualification. renunciation of work without attainment of knowledge is undesirable. O Arjuna. Krishna preaches about right exertion: “Let a man lift himself by his own Self alone. Here He speaks of identity. or what can restraint do in their case? These worldly men cannot escape the clutches of likes and dislikes. In VI. Arjuna’s duty as a Kshatriya was to fight. Non-dualism is the highest realisation. for this self is the friend of oneself and this self alone is the enemy of oneself”.5. They will be caught in the clutches of Maya. Another objector says: “In the Gita. Dualism. one is bound to one’s duty. renouncing their own duty. Radheshyam or Sitaram. Sri Shankara. Float high the unique banner of peace. nay. Sri Swami Visvananda. Study of the Gita must be made compulsory in all schools and colleges of India. Sri Swami Vishnudevananda. Sri Hastamalakacharya. Lord Rama. Bhagavan Vyasa. of the whole world. Put on the marvellous coat of arms of discrimination. Only that system of education wherein moral and spiritual training are imparted along with secular knowledge can be deemed sound. who placed the Gita before men of this world to attain liberation! May His blessings be upon you all! May the Gita be your centre. Lord Subramanya. Shivoham. Sri Saraswathi. sensible and perfect. Hold the magnificent torch of faith. Sri Jnana Dev.Epilogue India is held in high esteem by the Westerners on account of the Gita. Blow the conch of courage. Shanti! Swami Sivananda 4th July. Sita Devi. My silent adorations to Lord Ganesh. Sing the immortal song of Soham. and all the Brahma Vidya Gurus and commentators on the Gita. Sri Padmapadacharya. through whose Grace and blessings alone I was able to write this commentary! May their blessings be upon you all! Glory. glory to the Gita! Glory to Lord Krishna. Wear the magnificent shield of dispassion. 1942 xvi . Shanti. Gandhiji once visited one of the biggest libraries in London and asked the librarian which book was issued most frequently. Kill the enemies of ignorance and egoism and enter the illimitable kingdom of God. It must become a textbook for students of schools and colleges. Sri Sureshvaracharya. March boldly with the band of Pranava. It should find a very important place in every scheme of education. The librarian said that it was the Gita. practical. All aspirants should try to get the whole eighteen discourses by heart. It is very popular throughout the world. This can be achieved through daily study over a period of about one year at a rate of two verses a day.. Sri Totakacharya. including Draupadi. Sri Krishna. because of his age. thinking that Arjuna was foolish. Having successfully completed these thirteen years of exile. who. They both found Krishna resting on a couch in His palace. Madri had twins. Hence the Pandavas decided to live separately. the Pandavas decided upon war and tried to establish their rightful claim on the kingdom by overcoming the Kauravas. gave the first choice to Arjuna. Sakuni. Kunti got a boon through her sincere service of a wise sage in her younger age. sharing half of their kingdom. as per the terms of the agreement. and then Duryodhana sitting on a chair. Duryodhana. the Pandavas. Yudhisthira. Arjuna. even though Krishna warned that He would remain a witness. after which they had to live incognito for another year. Arjuna said. and Pandu was married to Kunti and Madri. Kindly fulfil my desire in this war. Duryodhana and Arjuna. through the celestial physicians called Asvini-Devatas. Pandu passed away and his sons. When Krishna asked Arjuna why he chose Him when He was not for taking up arms. The Pandavas and Kauravas grew up together. expressed his desire to have the Lord with him. bound by the vow of not participating in battle and not taking up arms. but due to the braveness and intelligence of the former. and also because of His sight of Arjuna first. whereby all his wealth and possessions. according to the prevailing custom. Dhritarashtra married Gandhari. Krishna asked Arjuna to fulfil his desire by selecting Him unarmed or His powerful army called Narayani Sena. including Draupadi. After enquiry of their welfare and the purpose of their visit. Duryodhana went in and occupied a seat at the head of the couch while Arjuna stood near the feet of the Lord. During this period the kingdom was to be ruled by the wicked Duryodhana. neglecting the powerful Narayani Sena. Lord Krishna. The moment Sri Krishna opened His eyes. the Pandavas. due to which he was not permitted to unite with his wife. who was a devotee of Sri Krishna. Duryodhana. the chief of the Kauravas. with the cunning advice of his uncle. untraced by the Kauravas. were sent to Dwaraka to seek the help of the Yadava hero. should repair to the forest for twelve years in exile. approached the Kauravas for their share of the kingdom. from the side of the Kauravas and Pandavas respectively. in the battle.INTRODUCTION Dhritarashtra and Pandu were brothers. Nakula and Sahadeva. facing many obstacles and dangers instigated by the Kauravas. According to the advice of Mother Kunti and with the inspiration of Lord Krishna. Finally it was settled that the Pandavas.” xvii . namely. Dhritarashtra had a hundred and one children by his wife Gandhari. Bhima and Arjuna from Yama. flatly refused to part with as much land as could be covered by the point of a needle. were all brought up by Dhritarashtra along with his sons known as Kauravas. “O Lord! You have the power to destroy all the forces by a mere sight. King Pandu was cursed for a sin while hunting. wealth and glory displayed during the Rajasuya Yajna aroused deep jealousy and greed in the mind of Duryodhana. invited Yudhisthira to a game of dice and fraudulently defeated him. Why then should I prefer that worthless army? I have for a long time been cherishing a desire in my heart that you should act as my charioteer. and she begot three children. He naturally saw Arjuna first. The Pandavas’ pomp. with great delight. expressed his wish for the powerful army to help his side in the battle. the Kauravas were unable to tolerate them. were lost. however. Vayu and Indra respectively. when the great warrior Bhishma was thrown down from his chariot by Arjuna. and the Kaurava chief. No weapon will touch his body nor will he feel tired. When both sides were prepared to commence the battle.The Lord. But then. failed to control them. and whether it is reduced to actual action or appears only in thought. Here commences the Bhagavad Gita.” The Kaurava king replied. King Dhritarashtra. but I should like to hear all the details of the battle. privately or in public. Lord Krishna Himself went once to Hastinapura as the emissary of the Pandavas and tried to prevent the war. due to his attachment to his sons. it will not remain hidden from his view. He will come to know everything. Whatever happens in the course of the war.” Then the sage conferred the gift of divine vision on Sanjaya. “Sanjaya will describe to you all the incidents of the war. at which Krishna showed His Supreme Form (Viswarupa). during the day or during the night. decided to meet the powerful Pandavas in war. Whether an incident takes place before his eyes or behind his back.” After the ten days of continued war between the Pandavas and the Kauravas. who is ever the most devoted lover of His devotees. In agony the king asks Sanjaya to narrate the full details of the previous ten days war. xviii . Duryodhana. accepted his request with pleasure. with vain hope. Sanjaya announces the news to Dhritarashtra. from the very beginning. “O Chief of the Brahmarishis! I have no desire to see with my own eyes this slaughter of my family. he will directly see. under the guidance of Sakuni. the egoistic Duryodhana refused to agree to the peace mission and tried to imprison Lord Krishna. hear or otherwise come to know. the trusty counsellor of the king. exactly as it happens. “If you wish to see this terrible carnage with your own eyes I can give you the gift of vision. and thus Krishna became the charioteer of Arjuna in the battle of the Mahabharata. the sage Veda Vyasa approached blind Dhritarashtra and said. in all detail as it happened. and told the king. After the return of Duryodhana and Arjuna from Dwaraka. Even the blind Dhritarashtra saw it by the Lord’s Grace. Guru is the preserver (Vishnu). Nandagopakumaaraaya govindaaya namo namah. the Guru’s word is the root of Mantra. Guru is the destroyer (Maheshvara). Dhyaanamoolam gurormoortih poojaamoolam guroh padam. To that Guru we prostrate. PRAYER TO LORD KRISHNA Krishnaaya vaasudevaaya devakeenandanaaya cha. Salutations unto thee. the Guru’s feet are the root of worship. the Guru’s Grace is the root of liberation. Guru is the creator (Brahma). I bow again and again to Lord Krishna. Kindly explain. The Guru’s form is the root of meditation. Thou art my best teacher. Mantramoolam gurorvaakyam mokshamoolam guroh kripaa. the darling of Nandagopa. son of Vasudeva. Yena twayaa bhaaratatailapoornah prajwaalito jnaanamayah pradeepah. Thou hast a soft corner for me in Thy heart. Give me easy lessons. Teach me now the mysteries of Thy divine play and the secrets of Vedanta.PRAYER TO VYASA Namostu te vyaasa visaalabuddhe phullaaravindaa yatapatranetra. Thou sayest in the Gita: “I am the author of Vedanta and the knower of the Vedas”. O Krishna! Thou art my sweet companion now. a Brahma Jnani who was always absorbed in Brahman. O Vyasa. of a Yogi who is established in the highest Superconscious State. Guru is verily the Supreme Absolute. the protector of cows. filled with the oil of the Mahabharata. and of a Jnani firmly established in the state of oneness or Brahman? What is the real difference between 1 . of broad intellect and with eyes large like the petals of a full-blown lotus. by whom the lamp of divine knowledge. the delighter of Devaki. Guruh saakshaat param brahma tasmai shree gurave namah. teach the Bhagavata to King Parikshit? What are the differences in the experiences of a Bhakta who enjoys union with God. Explain to me the intricate details of Vedanta. has been lighted! PRAYER TO THE GURU Gururbrahmaa gururvishnurgururdevo maheshwarah. why did Sukadev. I prostrate again and again before Thee. accept my humble prayer! Guide me. enlighten. Protect me. and the substance of my physical. the life of my life. and the Lord of my life-breath! I cannot hide anything from Thee. innermost prayer. my Lord. O Thou supreme world-teacher! I cannot bear any longer. O Lord of my breath! O all-pervading Lord of the universe. the mind of our mind. knowledge and purity. Thee alone I adore. O Krishna. between the perishable Person. Thou art the unseen seer. Listen. Do not be cruel. listen. Thou art the purifier of the fallen. O Prabhu! I am pining. the unknown knower. the illuminator of my intellect and senses. I am melting. You can play on the flute. Thou art the friend of the afflicted. I trust Thee alone.PRAYER TO LORD KRISHNA liberation while living and disembodied liberation. my Lord. the imperishable Person and the Supreme Person? Let me be frank with Thee. the divine love of my heart. Thou art one who raises the downtrodden. because Thou art the indweller of my heart. Thou art my friend now. this life and this worldly existence. Pray. Remove the obstacles on my spiritual path. Let us eat sugar-candy and butter together. the unheard hearer. the miseries of this physical body. Meet me quickly. O ocean of mercy and love! Elevate. Remove the veil of ignorance. Give us light. the very soul of my soul. the breath of our breath. Thou art the basis of all names and forms. on Thee alone I meditate in Thee alone I take sole refuge. I shall sing and dance. Thou art my sole refuge. mental and causal bodies. the ear of our ear. the unthought thinker. O magnificent Lord of love and compassion! O fountain-head of bliss and knowledge! Thou art the eye of our eye. Let me hear it directly from Thy lips once more. deliver us from temptation. because Thou directly witnesseth all the thoughts that emanate from my mind. Lift me from the mire of worldliness. I recognise Thee alone as the mighty ruler of this universe and the inner controller of my three bodies. Let us sing. Teach me the Gita. I have no fear of Thee. O Thou invisible One! O adorable and Supreme One! Thou penetratest and permeatest this vast universe from the unlimited space down to the tiny blade of grass at my feet. Treat me like Arjuna. 2 . Thee alone I worship. guide and protect me. Enlighten me. the witness of my mind. listen to my fervent. between the transcendent state and the state beyond it. the sweet mystic music of my heart. Thou art the apple of my eye. the soul of our soul. even for a second. The Earth said: 1. Geetaayaah pustakam yatra yatra paathah pravartate. and where the Gita is read. O Lord? Sri Vishnuruvaacha: Praarabdham bhujyamaano hi geetaabhyaasaratah sadaa. 3. 3 . Gopalas. divine serpents. Gopikas (friends and devotees of Lord Krishna). Uddhava and others (dwell here). sages. Mahaapaapaadipaapaani geetaadhyaanam karoti chet. Kwachit sparsham na kurvanti nalineedalam ambuvat. Sarve devaashcha rishayo yoginahpannagaashcha ye. even so sins do not taint him who is regular in the recitation of the Gita. Gopaalaa gopikaa vaapi naaradoddhava paarshadaih. 5. dwell in that place where the Gita is kept. Yogins. Lord Vishnu said: 2. one who is regular in the study of the Gita becomes free. All the gods. O Bhagavan. like Prayag and other places. Praarabdham bhujyamaanasya katham bhavati he prabho. Sahaayo jaayate sheeghram yatra geetaa pravartate. Tatra sarvaani teerthaani prayaagaadeeni tatra vai. Narada. Yatra geetaavichaarashcha pathanam paathanam shrutam. Though engaged in the performance of worldly duties. Tatraaham nishchitam prithvi nivasaami sadaiva hi. Sa muktah sa sukhee loke karmanaa nopalipyate. Just as the water stains not the lotus leaf. He is not bound by Karma. 4. All the sacred centres of pilgrimage. the Supreme Lord! How can unflinching devotion arise in him who is immersed in his Prarabdha Karmas (worldly life).BHAGAVAD GITA G. He is the happy man in this world. Hence it is a universal scripture suited for people of all temperaments and for all ages. the all-knowing. He who recites the eighteen chapters of the Bhagavad Gita daily. Vedatrayee paraanandaa tatwaarthajnaanasamyutaa. 7. It is full of supreme bliss. There is no doubt about this. he attains the benefit of giving a cow as a gift. It was spoken by the blessed Lord Krishna. and the Gita is My best abode. the Eternal. Help comes quickly where the Gita is recited and. Tadaa godaanajam punyam labhate naatra samshayah. taught and contemplated upon! Geetaashraye’ham tishthaami geetaa me chottamam griham. and who recites one-sixth of it attains the merit of performing a Soma sacrifice (a kind of ritual). O Earth. 4 . 11. through His own mouth. I protect the three worlds with the knowledge of the Gita. I ever dwell where it is read. with a pure and unshaken mind. Jnaanasiddhim sa labhate tato yaati param padam. Geetaajnaanam upaashritya treen Uokaan paalayaamyaham. Geetaa me paramaa vidyaa brahmaroopaa na samshayah. to Arjuna. Ekaadhyaayam tu yo nityam pathate bhaktisamyutah. If a complete reading is not possible. Shadamsham japamaanastu somayaagaphalam labhet. I take refuge in the Gita. Ardhamaatraaksharaa nityaa swaanirvaachyapadaatmikaa. 8. 10. It contains the essence of the Vedas—the knowledge of the Reality. Paathe’asamarthah sampoornam tato’rdham paathamaacharet. and reaches the highest state or supreme goal. 9. which is doubtless of the form of Brahman. COMMENTARY: The Gita contains the cream of the Vedas and Upanishads. He who recites one-third part of it achieves the merit of a bath in the sacred river Ganges. Rudralokam avaapnoti gano bhootwaa vasecchiram. the ineffable splendour of the Self. 12. even if only half is read. The Gita is My highest science. Chidaanandena krishnena proktaa swamukhato’rjuna. heard. Yoashtaadasha japen nityam naro nishchalamaanasah.GITA MAHATMYA 6. Tribhaagam pathamaanastu gangaasnaanaphalam labhet. attains perfection in knowledge. the Ardhamatra (of the Pranava Om). a dying man comes back to life again as a human being. goes to the kingdom of God and rejoices with Lord Vishnu. Uttering the word Gita at the time of death. 20. O Earth. taking refuge in the Gita. Sa yaati narataam yaavanmanwantaram vasundhare. three. In this world. Dwautreenekam tadardhamvaa shlokaanaam yah pathennarah. having performed many virtuous actions. Adhyaayam shlokapaadam vaa nityam yah pathate narah. Jeevanmuktah sa vijneyo dehaante paramam padam. Geetaayaah pathanam kritwaa maahaatmyam naiva yah pathet. He who meditates on the meaning of the Gita. By repeated study of the Gita. two verses or even one or half of it.BHAGAVAD GITA 13. five. Geetaam aashritya bahavo bhoobhujo janakaadayah. 14. Nirdhootakalmashaa loke geetaa yaataah param padam. seven.448. Geetaabhyaasam punah kritwaa labhate muktim uttamaam. Geetaartham dhyaayate nityam kritwaa karmaani bhoorishah. Geetaayaah shloka dashakam sapta pancha chatushtayam. Vaikuntham samavaapnoti vishnunaa saha modate. he attains liberation. He who repeats ten. four. Though full of sins. purified of all sins. COMMENTARY: A Jivanmukta is one who has attained liberation while living. If one reads a discourse or even a part of a verse daily he. a person attains liberation. 19. Vrithaa paatho bhavet tasya shrama eva hyudaahritah. 15-16.000 years. Geetaapaathasamaayukto mrito maanushataam vrajet. 18. Accustomed to the daily study of the Gita.000 years). retains a human body till the end of a Manvantara (71 Mahayugas or 308. 17. Such an individual should be considered a true Jivanmukta. one who is ever intent on hearing the meaning of the Gita. That person who reads one discourse with supreme faith and devotion attains to the world of Rudra and. Chandralokam avaapnoti varshaanaam ayutam dhruvam. 5 . having become a Gana (an attendant of Lord Shiva). attains the region of the moon and lives there for 10. lives there for many years. Geetetyucchaarasamyukto mriyamaano gatim labhet. many kings like Janaka and others reached the highest state or goal. Geetaarthashravanaasakto mahaapaapayuto’pi vaa. attains the supreme goal after death. Om Shanti. and the fruits mentioned therein will be obtained. and reaches the state which is otherwise very difficult to be attained. Etanmaahaatmyasamyuktam geetaabhyaasam karoti yah. loses the benefit thereby. and the effort alone remains. Shanti. One who studies the Gita. COMMENTARY: This is to test and confirm the faith of the reader in the Bhagavad Gita. This greatness or “Glory of the Gita”. attains the fruits mentioned above. Sa tatphalamavaapnoti durlabhaam gatim aapnuyaat. as narrated by me. Suta Uvaacha: Maahaatmyam etad geetaayaah mayaa proktam sanaatanam. which is eternal. Suta said: 23. 22. together with this “Glory of the Gita”. Thus ends the “Glory of the Gita” contained in the Varaha Purana. which is not a mere philosophical book but the word of God and should therefore be studied with great faith and devotion. He who fails to read this “Glory of the Gita” after having read the Gita. should be read at the end of the study of the Gita. Iti srivaraahapuraane srigeetaamaahaatmyam sampoornam. Shanti! 6 .GITA MAHATMYA 21. Geetaante cha pathedyastu yaduktam tatphalam labhet. The Gita Mahatmya generates this devotion in one’s heart. BHAGAVAD GITA.. 2.. 3.. 4.. 5.. 7 GITA DHYANAM.. 8..! 8 BHAGAVAD GITA Iheld.; 9 “Drishtaketu. “The strong Yudhamanyu and the brave Uttamaujas. Chekitana and the valiant king of Kasi. Having seen the army of the Pandavas drawn up in battle array. “Thyself and Bhishma. Dhrishtaketush chekitaanah kaashiraajashcha veeryavaan. Virata and Drupada. Asvatthama. 3. Anye cha bahavah shooraa madarthe tyaktajeevitaah. Asmaakam tu vishishtaa ye taan nibodha dwijottama. this mighty army of the sons of Pandu. the names of those who are the most distinguished amongst ourselves. arrayed by the son of Drupada. mighty archers. “Here are heroes. Naanaashastrapraharanaah sarve yuddhavishaaradaah. O Teacher. 4. Yuyudhaano viraatashcha drupadashcha mahaarathah. and Kuntibhoja and Saibya. King Duryodhana then approached his teacher (Drona) and spoke these words: Pashyaitaam paanduputraanaam aachaarya mahateem chamoom. “Know also. all of great chariots (great heroes). and Karna and Kripa.THE YOGA OF THE DESPONDENCY OF ARJUNA Aachaaryam upasamgamya raajaa vachanam abraveet. “Behold. 10 . Purujit. Yudhaamanyushcha vikraanta uttamaujaashcha veeryavaan. 6. O best among the twice-born. Saubhadro draupadeyaashcha sarva eva mahaarathaah. 7. Purujit kuntibhojashcha shaibyashcha narapungavah. equal in battle to Bhima and Arjuna. Bhavaan bheeshmashcha karnashcha kripashcha samitinjayah. thy wise disciple! Atra shooraa maheshwaasaa bheemaarjunasamaa yudhi. 5. Vikarna. 8. and Jayadratha. and the sons of Draupadi. Ashwatthaamaa vikarnashcha saumadattis tathaiva cha. the victorious in war. Naayakaah mama sainyasya samjnaartham taan braveemi te. Yuyudhana. of the great car (mighty warriors). the son of Arjuna). the son of Subhadra (Abhimanyu. Sanjaya said: 2. Vyoodhaam drupadaputrena tava shishyena dheemataa. the best of men. the leaders of my army! These I name to thee for thy information. the son of Somadatta. Maadhavah paandavashchaiva divyau shankhau pradadhmatuh. blew the “Anantavijaya”. 14. Aparyaaptam tad asmaakam balam bheeshmaabhirakshitam. 11 . 16. blew their divine conches. blew the great conch. Nakulah sahadevashcha sughoshamanipushpakau. the son of Kunti. the doer of terrible deeds. His glorious grandsire (Bhishma). and Sahadeva and Nakula blew the “Manipushpaka” and “Sughosha” conches. and Bhima. seated in their magnificent chariot yoked with white horses. tabors. 10. Yudhisthira. conches and kettle-drums. Paanchajanyam hrisheekesho devadattam dhananjayah. “Therefore. do ye all. armed with various weapons and missiles. 12. 15. is sufficient. Bheeshmam evaabhirakshantu bhavantah sarva eva hi. marshalled by Bhima. the eldest of the Kauravas. Then (following Bhishma). in order to cheer Duryodhana. Kaashyashcha parameshwaasah shikhandee cha mahaarathah. Tasya sanjanayan harsham kuruvriddhah pitaamahah. Ayaneshu cha sarveshu yathaabhaagam avasthitaah. Paryaaptam twidam eteshaam balam bheemaabhirakshitam. Paundram dadhmau mahaashankham bheemakarmaa vrikodarah. stationed in your respective positions in the several divisions of the army. Sahasaivaabhyahanyanta sa shabdastumulo’bhavat. protect Bhishma alone”. whereas their army. drums and cow-horns blared forth quite suddenly (from the side of the Kauravas). “Paundra”. Tatah shvetair hayair yukte mahati syandane sthitau. Then also. 11. now roared like a lion and blew his conch. “This army of ours marshalled by Bhishma is insufficient. “And also many other heroes who have given up their lives for my sake. Tatah shankhaashcha bheryashcha panavaanakagomukhaah. Hrishikesa blew the “Panchajanya” and Arjuna blew the “Devadatta”. and the son of Pandu (Arjuna). all well skilled in battle. and the sound was tremendous.BHAGAVAD GITA 9. Simhanaadam vinadyocchaih shankham dadhmau prataapavaan. Madhava (Krishna). Anantavijayam raajaa kunteeputro yudhishthirah. 13. Dhristadyumna and Virata and Satyaki. For I desire to observe those who are assembled here to fight. Arjuna said: 21-22. place my chariot. 18. 19. Nabhashcha prithiveem chaiva tumulo vyanunaadayan. the mighty-armed. Drupada and the sons of Draupadi. seeing all the people of Dhritarashtra’s party standing arrayed and the discharge of weapons about to begin. took up his bow and said the following to Krishna. desirous to fight. and know with whom I must fight when the battle begins. Dhaartaraashtrasya durbuddher yuddhe priyachikeershavah. Hrisheekesham tadaa vaakyamidamaaha maheepate. O Lord of the Earth! Arjuna Uvaacha: Senayor ubhayormadhye ratham sthaapaya me’chyuta. Saubhadrashcha mahaabaahuh shankhaan dadhmuh prithak prithak. 17. Sanjaya Uvaacha: Evamukto hrisheekesho gudaakeshena bhaarata. Pravritte shastrasampaate dhanurudyamya paandavah. Atha vyavasthitaan drishtwaa dhaartaraashtraan kapidhwajah. whose ensign was that of a monkey. the mighty car-warrior. 23. O Lord of the Earth. all blew their respective conches! Sa ghosho dhaartaraashtraanaam hridayaani vyadaarayat. and the son of Subhadra. Sikhandi.THE YOGA OF THE DESPONDENCY OF ARJUNA Dhrishtadyumno viraatashcha saatyakishchaaparaajitah. Yaavad etaan nireekshe’ham yoddhukaamaan avasthitaan. the son of Pandu. In the middle of the two armies. an excellent archer. making both heaven and earth resound. the unconquered. The king of Kasi. Yotsyamaanaan avekshe’ham ya ete’tra samaagataah. the evil-minded. Senayor ubhayormadhye sthaapayitwaa rathottamam. Then. Arjuna. 20. Drupado draupadeyaashcha sarvashah prithiveepate. Sanjaya said: 12 . The tumultuous sound rent the hearts of Dhritarashtra’s party. O Krishna. so that I may behold those who stand here. Kair mayaa saha yoddhavyam asmin ranasamudyame. wishing to please in battle Duryodhana. Being thus addressed by Arjuna. Na cha shreyo’nupashyaami hatwaa swajanam aahave. (He saw) fathers-in-law and friends also in both armies. teachers. Seedanti mama gaatraani mukham cha parishushyati. 27. Then Arjuna beheld there stationed. Seeing these. The (bow) “Gandiva” slips from my hand and my skin burns all over. behold now all these Kurus gathered together!” Tatraapashyat sthitaan paarthah pitrin atha pitaamahaan. 31. too. O Dhritarashtra. my kinsmen. And I see adverse omens. Vepathushcha shareere me romaharshashcha jaayate. sons. 13 . Uvaacha paartha pashyaitaan samavetaan kuroon iti. Lord Krishna. grandfathers and fathers. In front of Bhishma and Drona and all the rulers of the earth. Shvashuraan suhridashchaiva senayorubhayorapi. brothers. 30. Arjuna said: 28. my mind is reeling. 26. as it were. My limbs fail and my mouth is parched up. Arjuna Uvaacha: Drishtwemam swajanam krishna yuyutsum samupasthitam. 25. 29.BHAGAVAD GITA 24. eager to fight. my body quivers and my hairs stand on end! Gaandeevam sramsate hastaat twak chaiva paridahyate. said: “O Arjuna. Na cha shaknomyavasthaatum bhramateeva cha me manah. Nimittaani cha pashyaami vipareetaani keshava. Kripayaa parayaa’vishto visheedannidam abraveet. Bheeshmadronapramukhatah sarveshaam cha maheekshitaam. arrayed. spoke thus sorrowfully. having stationed that best of chariots. grandsons and friends. filled with deep pity. The son of Kunti—Arjuna—seeing all these kinsmen standing arrayed. O Kesava! I do not see any good in killing my kinsmen in battle. maternal uncles. Taan sameekshya sa kaunteyah sarvaan bandhoon avasthitaan. in the midst of the two armies. O Krishna. Aachaaryaan maatulaan bhraatrun putraan pautraan sakheemstathaa. I am unable even to stand. O Madhava (Krishna)? Yadyapyete na pashyanti lobhopahatachetasah. with intelligence overpowered by greed. enjoyments and pleasures. For I desire neither victory. 14 . 36. Teachers. see no evil in the destruction of families. Aachaaryaah pitarah putraastathaiva cha pitaamahaah. Those for whose sake we desire kingdoms. Therefore. Kulakshayakritam dosham mitradrohe cha paatakam. O Krishna. 37. sons and also grandfathers. Paapam evaashrayed asmaan hatwaitaan aatataayinah. stand here in battle. our relatives. fathers-in-law. we should not kill the sons of Dhritarashtra. O Krishna. O Janardana? Only sin will accrue by killing these felons. These I do not wish to kill. Maatulaah shwashuraah pautraah shyaalaah sambandhinas tathaa. 33. 35. Kulakshayakritam dosham prapashyadbhir janaardana. 34. brothers-in-law and relatives. nor pleasures nor kingdoms! Of what avail is a dominion to us. what pleasure can be ours. 32. Katham na jneyam asmaabhih paapaad asmaan nivartitum. grandsons. 38. how can we be happy by killing our own people. Swajanam hi katham hatwaa sukhinah syaama maadhava. for. and no sin in hostility to friends. Kim no raajyena govinda kim bhogair jeevitena vaa. By killing these sons of Dhritarashtra. though they kill me. Though they. leave alone killing them for the sake of the earth! Nihatya dhaartaraashtraan nah kaa preetih syaaj janaardana. even for the sake of dominion over the three worlds. O Krishna. or pleasures or even life? Yeshaam arthe kaangkshitam no raajyam bhogaah sukhaani cha.THE YOGA OF THE DESPONDENCY OF ARJUNA Na kaangkshe vijayam krishna na cha raajyam sukhaani cha. Ta ime’vasthitaa yuddhe praanaamstyaktwaa dhanaani cha. having renounced life and wealth. maternal uncles. Api trailokya raajyasya hetoh kim nu maheekrite. fathers.— Etaan na hantum icchaami ghnato’pi madhusoodana. Tasmaan naarhaa vayam hantum dhaartaraashtraan swabaandhavaan. COMMENTARY: Dharma pertains to the duties and ceremonies practised by the family in accordance with scriptural injunctions. Dharme nashte kulam kritsnam adharmo’bhibhavatyuta. Why should not we. Yadraajya sukhalobhena hantum swajanam udyataah. for their forefathers fall. 15 . the immemorial religious rites of that family perish. Narake’niyatam vaaso bhavateetyanushushruma. who clearly see evil in the destruction of a family. impiety overcomes the whole family. O Varsneya (descendant of Vrishni). Adharmaabhibhavaat krishna pradushyanti kulastriyah. O Janardana. O Krishna. 44. Utsannakuladharmaanaam manushyaanaam janaardana. By these evil deeds of the destroyers of the family. 42. 45. which cause confusion of castes. deprived of the offerings of rice-ball and water. Confusion of castes leads to hell the slayers of the family. women becoming corrupted. Kulakshaye pranashyanti kuladharmaah sanaatanaah. Patanti pitaro hyeshaam luptapindodakakriyaah. We have heard. the women of the family become corrupt and. 43. Utsaadyante jaatidharmaah kuladharmaashcha shaashwataah. that inevitable is the dwelling for an unknown period in hell for those men in whose families the religious practices have been destroyed! Aho bata mahat paapam kartum vyavasitaa vayam. learn to turn away from this sin.BHAGAVAD GITA 39. Streeshu dushtaasu vaarshneya jaayate varnasankarah. In the destruction of a family. the eternal religious rites of the caste and the family are destroyed. there arises intermingling of castes! Sankaro narakaayaiva kulaghnaanaam kulasya cha. 41. Doshair etaih kulaghnaanaam varnasankarakaarakaih. on the destruction of spirituality. By prevalence of impiety. O Janardana (Krishna)? COMMENTARY: Ignorance of the law is no excuse and wanton sinful conduct is a crime unworthy of knowledgeable people. Alas! We are involved in a great sin in that we are prepared to kill our kinsmen through greed for the pleasures of a kingdom. 40. Visrijya sasharam chaapam shokasamvignamaanasah. Arjuna. 46. Lord Krishna rebukes him for his dejection. The Lord takes pity on him and proceeds to enlighten him by various means. He explains to Arjuna the imperishable nature of the Atman. As It transcends the five elements. heat and cold. The senses carry the sensations through the nerves to the mind. namely. the scripture of Yoga. The Atman never dies. with weapons in hand. casting away his bow and arrow. Thus in the Upanishads of the glorious Bhagavad Gita. earth. the science of the Eternal. due to contact of objects with the senses. ends the first discourse entitled: “The Yoga Of the Despondency of Arjuna” II SANKHYA YOGA Summary of Second Discourse Sanjaya explains the condition of Arjuna. After failing to convince Sri Krishna through his seemingly wise thoughts. If the sons of Dhritarashtra. It cannot be cut. Everyone experiences conditions like pleasure and pain. air and ether. One should 16 . which was due to Moha or attachment.THE YOGA OF THE DESPONDENCY OF ARJUNA Yadi maam aprateekaaram ashastram shastrapaanayah. that would be better for me. for which there is no past. burnt or dried. who was agitated due to attachment and fear. water. the dialogue between Sri Krishna and Arjuna. therefore Arjuna should not grieve. It is unchanging and eternal. seeking His guidance to get over the conflict of his mind. fire. Arjuna realises his helplessness and surrenders himself completely to the Lord. Dhaartaraashtraa rane hanyus tanme kshemataram bhavet. unresisting and unarmed. Sanjaya Uvaacha: Evamuktwaa’rjunah sankhye rathopastha upaavishat. Having thus spoken in the midst of the battlefield. present and future.yaayah. should slay me in battle. and exhorts him to fight. Sanjaya said: 47. Sanjaya said: 1. having achieved a stable mind. free from desire for acquisition of kingdom or preservation of it. Lord Krishna turns to the performance of action without expectation of fruit. The various qualities of a Sthitaprajna (a stable-minded person) are described by the Lord. people will be justified in condemning such action as unworthy of a warrior. He will take things as they come. Since he is content within. having realised the Self. one does not lose consciousness of one’s identity with Brahman. Even at the end of life. Krishna asserts that only one who has the capacity to be balanced in pleasure and pain alike is fit for immortality. Such a person. Visheedantam idam vaakyam uvaacha madhusoodanah. Krishna advises Arjuna to fight. He is unmoved and lives a life of eternal peace. spoke these words. He will neither hug the world nor hate it. when one departs from this body. The senses are powerful and draw the mind outwards. The consciousness of the Atman and abandonment of desires are simultaneous experiences. like the tortoise which withdraws all its limbs within. He will not be affected by adversity and will have no fear or anger. Having taught Arjuna the immortal nature of the Atman. like gain and loss. remains steadfast even though all sense-objects come to him. pleasure and pain. that inevitably manifest during action. One should therefore turn one’s gaze within and realise God who resides in the heart. 17 . Sri Bhagavaan Uvaacha: Kutastwaa kashmalam idam vishame samupasthitam. with eyes full of tears and agitated. Krishna goes on to tell Arjuna that if he refuses to fight and flees from the battle. The man of stable mind will have perfect control of the senses. calmly enduring the pairs of opposites like heat and cold. The Yogi.BHAGAVAD GITA be able to withdraw the senses from objects. he is entirely free from desires. Anaaryajushtam aswargyam akeertikaram arjuna. He should perform all action with a balanced mind. These are in the hands of the Lord. Krishna concludes that the eternal Brahmic state frees one from delusion forever. Sanjaya Uvaacha: Tam tathaa kripayaavishtam ashrupoornaakulekshanam. will have no desires at all. victory and defeat. Krishna tells him. A man should not concern himself about the fruit of the action. and will not have any likes and dislikes. Arjuna is eager to know the characteristics of a man who has a stable mind. To him who was thus overcome with pity and who was despondent. Krishna or Madhusudana (the destroyer of Madhu). Better it is. my mind is confused as to duty. But if I kill them. Stand up. and which will close the gates of heaven upon thee. I am Thy disciple. Na hi prapashyaami mamaapanudyaad 18 . disgraceful. this dejection which is unworthy of thee.SANKHYA YOGA The Blessed Lord said: 2. Yaan eva hatwaa na jijeevishaamas Te’vasthitaah pramukhe dhaartaraashtraah. O destroyer of enemies? Guroon ahatwaa hi mahaanubhaavaan Shreyo bhoktum bhaikshyam apeeha loke. Kshudram hridaya daurbalyam tyaktwottishtha parantapa. son of Pritha! It does not befit thee. 3. Whence is this perilous strait come upon thee. stand facing us. who are fit to be worshipped. Even the sons of Dhritarashtra. in this world to accept alms than to slay the most noble teachers. indeed.. My heart is overpowered by the taint of pity. after slaying whom we do not wish to live. O Arjuna. shall I fight in battle with arrows against Bhishma and Drona. Hatwaarthakaamaamstu guroon ihaiva Bhunjeeya bhogaan rudhirapradigdhaan. Instruct me who has taken refuge in Thee. How. Yacchreyah syaan nishchitam broohi tanme Shishyaste’ham shaadhi maam twaam prapannam. 5. Yield not to impotence. Cast off this mean weakness of the heart. 6. O Madhusudana. Na chaitad vidmah kataran no gareeyo Yadwaa jayema yadi vaa no jayeyuh. I can hardly tell which will be better: that we should conquer them or they should conquer us. 7. Ishubhih pratiyotsyaami poojaarhaavarisoodana. Arjuna said: 4. I ask Thee: tell me decisively what is good for me. O Arjuna? Klaibyam maa sma gamah paartha naitat twayyupapadyate. even in this world all my enjoyments of wealth and desires will be stained with (their) blood. spoke these words! Sri Bhagavaan Uvaacha: Ashochyaan anvashochastwam prajnaavaadaamshcha bhaashase.BHAGAVAD GITA Yacchokam ucchoshanam indriyaanaam. Tathaa dehaantara praaptir dheeras tatra na muhyati. 8. the firm man does not grieve thereat. the destroyer of foes.” and became silent. O Bharata. Sanjaya said: 9. Aagamaapaayino’nityaas taamstitikshaswa bhaarata. Dehino’smin yathaa dehe kaumaaram yauvanam jaraa. Having spoken thus to Hrishikesa (Lord of the senses). yet thou speakest words of wisdom. said to Krishna: “I will not fight. Na twevaaham jaatu naasam na twam neme janaadhipaah. 19 . The Blessed Lord said: 11. To him who was despondent in the midst of the two armies. The wise grieve neither for the living nor for the dead. I do not see that it would remove this sorrow that burns up my senses even if I should attain prosperous and unrivalled dominion on earth or lordship over the gods. 13. Sanjaya Uvaacha: Evam uktwaa hrisheekesham gudaakeshah parantapah. nor verily shall we ever cease to be hereafter. Gataasoon agataasoomshcha naanushochanti panditaah. 10. 12. youth and old age. Just as in this body the embodied (soul) passes into childhood. Nor at any time indeed was I not. so also does he pass into another body. Thou hast grieved for those that should not be grieved for. Arjuna (the conqueror of sleep). Na chaiva na bhavishyaamah sarve vayam atah param. Tam uvaacha hrisheekeshah prahasanniva bhaarata. nor these rulers of men. as if smiling. Avaapya bhoomaavasapatnam riddham Raajyam suraanaam api chaadhipatyam. Senayor ubhayor madhye visheedantam idam vachah. Na yotsya iti govindam uktwaa tooshneem babhoova ha. Sri Krishna. Maatraasparshaastu kaunteya sheetoshnasukhaduhkhadaah. O Arjuna! Yam hi na vyathayantyete purusham purusharshabha. 17. It is the only Reality. He who takes the Self to be the slayer and he who thinks He is slain. This phenomenal world of names and forms is ever changing. The unreal hath no being. Therefore. by whom all this is pervaded. which cause heat and cold and pleasure and pain. if the bodies and all other objects perish. there is no non-being of the Real. Names and forms are subject to decay and death. endure them bravely. Know That to be indestructible. neither of them knows. the truth about both has been seen by the knowers of the Truth (or the seers of the Essence). all-pervading Self ever exists. The contacts of the senses with the objects. fight. None can cause the destruction of That. O Arjuna! Ya enam vetti hantaaram yashchainam manyate hatam. the Imperishable. 18. He slays not nor is He slain. COMMENTARY: The Self pervades all objects like ether. which is eternal. Vinaasham avyayasyaasya na kashchit kartum arhati. Similarly. have a beginning and an end. O chief among men. Even if the pot is broken. is fit for attaining immortality! Naasato vidyate bhaavo naabhaavo vidyate satah. Na jaayate mriyate vaa kadaachin Naayam bhootwaa bhavitaa vaa na bhooyah. Anaashino’prameyasya tasmaad yudhyaswa bhaarata. 19. indestructible and immeasurable. 15. The Atman or the eternal. Ubhau tau na vijaaneeto naayam hanti na hanyate. Avinaashi tu tad viddhi yena sarvam idam tatam. It is the living Truth. That firm man whom surely these afflict not. COMMENTARY: What is changing must always be unreal. What is constant or permanent must always be real. Samaduhkha sukham dheeram so’mritatwaaya kalpate. to whom pleasure and pain are the same. O son of Kunti. Ajo nityah shaashwato’yam puraano 20 .SANKHYA YOGA 14. the eternal Self that pervades them cannot be destroyed. Ubhayorapi drishto’ntastwanayos tattwadarshibhih. These bodies of the embodied Self. are said to have an end. 16. they are impermanent. Hence they are unreal or impermanent. Antavanta ime dehaa nityasyoktaah shareerinah. the ether that is within and without it cannot be destroyed. O Arjuna. Nityah sarvagatah sthaanur achalo’yam sanaatanah. water wets It not. This (Self) is said to be unmanifested. stable. how can that man slay. Weapons cut It not. Just as a man casts off worn-out clothes and puts on new ones. 23. This Self cannot be cut. O mighty-armed. Avyakto’yam achintyo’yam avikaaryo’yam uchyate. eternal. unthinkable and unchangeable. even then. Tathaa shareeraani vihaaya jeernaa Nyanyaani samyaati navaani dehee. COMMENTARY: The Self is partless. 24. Atha chainam nityajaatam nityam vaa manyase mritam. 25. 22. 20. Whosoever knows Him to be indestructible. changeless and ancient. ancient and immovable. He again ceases not to be. Nainam cchindanti shastraani nainam dahati paavakah. 21. wind cannot dry It. all-pervading. Vedaavinaashinam nityam ya enam ajam avyayam. It is infinite and extremely subtle. 26. after having been. fire burns It not. so also the embodied Self casts off worn-out bodies and enters others that are new. He is not killed when the body is killed. wind dries It not. knowing This to be such. Therefore. It is eternal. even if thou thinkest of It as being constantly born and dying. But. So the sword cannot cut It. Na chainam kledayantyaapo na shoshayati maarutah. eternal. or cause to be slain? Vaasaamsi jeernaani yathaa vihaaya Navaani grihnaati naro’paraani. Acchedyo’yam adaahyo’yam akledyo’shoshya eva cha. thou shouldst not grieve! 21 . fire cannot burn It. thou shouldst not grieve. wetted nor dried up. unborn and inexhaustible. Katham sa purushah paartha kam ghaatayati hanti kam. He is not born nor does He ever die.BHAGAVAD GITA Na hanyate hanyamaane shareere. burnt. Tasmaad evam viditwainam naanushochitum arhasi. Unborn. Tathaapi twam mahaabaaho naivam shochitum arhasi. O Arjuna. over the inevitable thou shouldst not grieve. 28. for there is nothing higher for a Kshatriya than a righteous war. another hears of It as a wonder. 27. certain is death for the born and certain is birth for the dead. hears and speaks of the Self is a wonderful man. Tasmaat sarvaani bhootaani na twam shochitum arhasi. For. none understands It at all. Swadharmam api chaavekshya na vikampitum arhasi. 31. yet. thou shouldst not grieve for any creature. another speaks of It as a wonder. O Arjuna! Therefore. having regard to thy own duty. Tasmaad aparihaarye’rthe na twam shochitum arhasi. and unmanifested again in their end! What is there to grieve about? COMMENTARY: The physical body is a combination of the five elements. Therefore. Avyaktaadeeni bhootaani vyaktamadhyaani bhaarata. one should not grieve. 22 . the Indweller in the body of everyone. having heard. manifested in their middle state. One sees This (the Self) as a wonder. Beings are unmanifested in their beginning. is always indestructible. therefore. He is one among many thousands. It is perceived by the physical eye only after the five elements have entered into such combination. After death the body disintegrates and all the five elements return to their source. Dharmyaaddhi yuddhaacchreyo’nyat kshatriyasya na vidyate. thou shouldst not waver. This is the law of Nature. Further. Such a man is very rare. Jaatasya hi dhruvo mrityur dhruvam janma mritasya cha. Aashcharyavacchainam anyah shrinoti Shrutwaapyenam veda na chaiva kashchit. He who understands the nature of the body and human relationships based upon it will not grieve. It can be perceived only in the middle state. Aashcharyavat pashyati kashchid enam Aashcharyavad vadati tathaiva chaanyah. the Self is very hard to understand. This. 30. 29. The body cannot be perceived now. Avyakta nidhanaanyeva tatra kaa paridevanaa.SANKHYA YOGA COMMENTARY: Birth is inevitable to what is dead and death is inevitable to what is born. Dehee nityam avadhyo’yam dehe sarvasya bhaarata. Therefore. COMMENTARY: The verse may also be interpreted in this manner: he that sees. Yadricchayaa chopapannam swargadwaaram apaavritam. 34. 33. 36. too. will recount thy everlasting dishonour. Atha chettwam imam dharmyam samgraamam na karishyasi. then. thou wilt enjoy the earth. 32. thou wilt obtain heaven. 23 . stand up. Thy enemies also. resolved to fight! Sukhaduhkhe same kritwaa laabhaalaabhau jayaajayau. Happy are the Kshatriyas. Avaachyavaadaamshcha bahoon vadishyanti tavaahitaah. People. 35. O son of Kunti. dishonour is worse than death. Akeertim chaapi bhootaani kathayishyanti te’vyayaam. therefore. will speak many abusive words. Tasmaad uttishtha kaunteya yuddhaaya kritanishchayah. and to one who has been honoured. Sambhaavitasya chaakeertir maranaad atirichyate. Tato yuddhaaya yujyaswa naivam paapamavaapsyasi. Sukhinah kshatriyaah paartha labhante yuddham eedrisham. But.BHAGAVAD GITA COMMENTARY: To a Kshatriya (one born in the warrior or ruling class) nothing is more welcome than a righteous war. and thou wilt be lightly held by them who have thought much of thee. Bhayaad ranaad uparatam mamsyante twaam mahaarathaah. 37. Tatah swadharmam keertim cha hitwaa paapam avaapsyasi. victorious. Nindantastava saamarthyam tato duhkhataram nu kim. O Arjuna. cavilling at thy power. if thou wilt not fight in this righteous war. Yeshaam cha twam bahumato bhootwaa yaasyasi laaghavam. What is more painful than this! Hato vaa praapsyasi swargam jitwaa vaa bhokshyase maheem. thou shalt incur sin. The great car-warriors will think that thou hast withdrawn from the battle through fear. who are called upon to fight in such a battle that comes of itself as an open door to heaven! COMMENTARY: The scriptures declare that if a warrior dies for a righteous cause on the battlefield he at once ascends to heaven. having abandoned thine duty and fame. Slain. COMMENTARY: This is the Yoga of equanimity or the doctrine of poise in action. O Arjuna. Full of desires. If a person performs actions with the above mental attitude. having heaven as their goal. Having made pleasure and pain. Kaamaatmaanah swargaparaa janmakarmaphalapradaam. Eshaa te’bhihitaa saankhye buddhir yoge twimaam shrinu. Buddhyaa yukto yayaa paartha karma bandham prahaasyasi. there is a single one-pointed determination! Many-branched and endless are the thoughts of the irresolute. Now listen to wisdom concerning Yoga. is wisdom concerning Sankhya. 24 . Kriyaavisheshabahulaam bhogaishwaryagatim prati. Vyavasaayaatmikaa buddhir ekeha kurunandana. 42. In this there is no loss of effort. They extol these actions and rewards unduly. endowed with which. 40. Even a little of this knowledge (even a little practice of this Yoga) protects one from great fear. thou shalt cast off the bonds of action! Nehaabhikramanaasho’sti pratyavaayo na vidyate. Yaam imaam pushpitaam vaacham pravadantyavipashchitah. and prescribe various specific actions for the attainment of pleasure and power. 39. 41. they utter speech which promises birth as the reward of one’s actions. 43.SANKHYA YOGA 38. nor is there any harm (the production of contrary results or transgression). thus thou shalt not incur sin. saying: “There is nothing else!” COMMENTARY: Unwise people who lack discrimination place great stress upon the Karma Kanda or ritualistic portion of the Vedas which lays down specific rules for specific actions for the attainment of specific fruit. Swalpam apyasya dharmasya traayate mahato bhayaat. Bahushaakhaa hyanantaashcha buddhayo’vyavasaayinaam. Flowery speech is uttered by the unwise. Vedavaadarataah paartha naanyad asteeti vaadinah. victory and defeat the same. engage thou in battle for the sake of battle. who take pleasure in the eulogising words of the Vedas. he will not reap the fruits of such actions. This which has been taught to thee. COMMENTARY: In Karma Yoga (selfless action) even a little effort brings immediate purification of the heart. O Arjuna. gain and loss. Purification of the heart leads to fearlessness. O joy of the Kurus. Bhogaishwarya prasaktaanaam tayaapahritachetasaam. Here. be thou above these three attributes. Yaavaanartha udapaane sarvatah samplutodake. 45. The pairs of opposites are pleasure and pain. nor let thy attachment be to inaction. you get purification of heart and ultimately knowledge of the Self. honour and dishonour. abandoning attachment and balanced in success and failure! Evenness of mind is called Yoga. harmony). 46. Nature is made up of three Gunas—Sattwa (purity. O Arjuna! Free yourself from the pairs of opposites and ever remain in the quality of Sattwa (goodness). 48. mean that the Vedas are useless. COMMENTARY: Actions done with expectation of its rewards bring bondage. praise and censure. whose minds are drawn away by such teaching. O Arjuna. darkness). and be established in the Self. Rajas (passion. Siddhyasiddhyoh samo bhootwaa samatwam yoga uchyate. To the Brahmana who has known the Self. The Vedas deal with the three attributes (of Nature). This does not. motion). light. freed from the thought of acquisition and preservation.BHAGAVAD GITA Vyavasaayaatmikaa buddhih samaadhau na vidheeyate. Nirdwandwo nityasatwastho niryogakshema aatmavaan. 47. 25 . being steadfast in Yoga. victory and defeat. COMMENTARY: Only for a sage who has realised the Self are the Vedas of no use. Perform action. Yogasthah kuru karmaani sangam tyaktwaa dhananjaya. Buddhau sharanamanwiccha kripanaah phalahetavah. all the Vedas are of as much use as is a reservoir of water in a place where there is a flood. Taavaan sarveshu vedeshu braahmanasya vijaanatah. 44. If you do not thirst for them. and Tamas (inertia. heat and cold. Thy right is to work only. Doorena hyavaram karma buddhiyogaad dhananjaya. because he is in possession of knowledge of the Self. Traigunyavishayaa vedaa nistraigunyo bhavaarjuna. however. They are useful for neophytes or aspirants who have just started on the spiritual path. but never with its fruits. gain and loss. It is substance as well as quality. let not the fruits of actions be thy motive. that determinate faculty is not manifest that is steadily bent on meditation and Samadhi (the state of Superconsciousness). Karmanyevaadhikaaraste maa phaleshu kadaachana. COMMENTARY: Guna means attribute or quality. restlessness. For those who are much attached to pleasure and to power. Maa karmaphalahetur bhoor maa te sango’stwakarmani. If actions are done for the sake of God. Karmajam buddhiyuktaa hi phalam tyaktwaa maneeshinah. When thy intellect crosses beyond the mire of delusion. COMMENTARY: The mire of delusion is identification of the Self with the body and mind. possessed of knowledge. then thou shalt attain to indifference as to what has been heard and what has yet to be heard. The former leads to bondage. 52.SANKHYA YOGA 49. 51. Yadaa te mohakalilam buddhir vyatitarishyati. Sthitadheeh kim prabhaasheta kimaaseeta vrajeta kim. O Arjuna! Seek thou refuge in wisdom. COMMENTARY: Actions which are of a binding nature lose that nature when performed with equanimity of mind. then thou shalt attain Self-realisation. one casts off in this life both good and evil deeds. devote thyself to Yoga. shall stand immovable and steady in the Self. Tasmaad yogaaya yujyaswa yogah karmasu kaushalam. and is the cause of birth and death. go to the place which is beyond all evil. therefore. When thy intellect. 50. having abandoned the fruits of their actions. and being freed from the fetters of birth. Arjuna said: 26 . Far lower than the Yoga of wisdom is action. Arjuna Uvaacha: Sthitaprajnasya kaa bhaashaa samaadhisthasya keshava. 53. Yoga is skill in action. wretched are they whose motive is the fruit. Samaadhaavachalaa buddhistadaa yogam avaapsyasi. Actions performed by one who expects their fruits are far inferior to the Yoga of wisdom wherein the seeker does not seek the fruits. Janmabandha vinirmuktaah padam gacchantyanaamayam. Buddhiyukto jahaateeha ubhe sukrita dushkrite. The wise. COMMENTARY: Clinging to the fruits of actions is the cause of rebirth. Tadaa gantaasi nirvedam shrotavyasya shrutasya cha. perplexed by what thou hast heard. Endowed with wisdom (evenness of mind). without desire for the fruits. Man has to take a body to enjoy them. Shrutivipratipannaa te yadaa sthaasyati nishchalaa. one is released from the bonds of birth and death and attains to immortal bliss. COMMENTARY: Actions done with evenness of mind is the Yoga of wisdom. When. Duhkheshwanudwignamanaah sukheshu vigatasprihah. but his longing also turns away on seeing the Supreme. fear and anger. Naabhinandati na dweshti tasya prajnaa pratishthitaa. O Arjuna. Indriyaani pramaatheeni haranti prasabham manah. leaving the longing (behind). who neither rejoices nor hates.BHAGAVAD GITA 54. When a man completely casts off. like the tortoise which withdraws its limbs on all sides. then his wisdom becomes steady. Yadaa samharate chaayam kurmo’ngaaneeva sarvashah. then is he said to be one of steady wisdom! COMMENTARY: All the pleasures of the world are worthless to an illumined sage who is ever content in the immortal Self. He who is everywhere without attachment. The turbulent senses. O Arjuna. What. Yah sarvatraanabhisnehas tattat praapya shubhaashubham. The Blessed Lord said: 55. The objects of the senses turn away from the abstinent man. He whose mind is not shaken by adversity. on meeting with anything good or bad. Veetaraagabhayakrodhah sthitadheer munir uchyate. Indriyaaneendriyaarthebhyas tasya prajnaa pratishthitaa. 56. who does not hanker after pleasures.. Vishayaa vinivartante niraahaarasya dehinah Rasavarjam raso’pyasya param drishtwaa nivartate. 58. all the desires of the mind and is satisfied in the Self by the Self. and who is free from attachment. is called a sage of steady wisdom. Yatato hyapi kaunteya purushasya vipashchitah. do violently carry away the mind of a wise man though he be striving (to control them)! 27 . O Krishna. 59. 60. Aatmanyevaatmanaa tushtah sthitaprajnastadochyate. he withdraws his senses from the sense-objects. his wisdom is fixed. 57. 62. Naasti buddhir ayuktasya na chaayuktasya bhaavanaa. 65. 66. moving amongst objects with the senses under restraint. his wisdom is steady whose senses are under control. intent on Me. 61. Raagadwesha viyuktaistu vishayaanindriyaishcharan. for the intellect of the tranquil-minded soon becomes steady. 63. Tadasya harati prajnaam vaayur naavam ivaambhasi. Tasmaad yasya mahaabaaho nigriheetaani sarvashah. 28 . When a man thinks of the objects. how can there be happiness? Indriyaanaam hi charataam yanmano’nuvidheeyate. Aatmavashyair vidheyaatmaa prasaadamadhigacchati. from the destruction of discrimination he perishes. In that peace all pains are destroyed. Na chaabhaavayatah shaantir ashaantasya kutah sukham.SANKHYA YOGA Taani sarvaani samyamya yukta aaseeta matparah. 67. But the self-controlled man. attains to peace. COMMENTARY: When peace is attained all miseries end. 64. Smritibhramshaad buddhinaasho buddhinaashaat pranashyati. carries away his discrimination as the wind (carries away) a boat on the waters. attachment to them arises. Sangaat sanjaayate kaamah kaamaat krodho’bhijaayate. Prasaade sarvaduhkhaanaam haanir asyopajaayate. from loss of memory the destruction of discrimination. Krodhaad bhavati sammohah sammohaat smriti vibhramah. Dhyaayato vishayaan pumsah sangas teshupajaayate. from desire anger arises. and to the unsteady no meditation is possible. and free from attraction and repulsion. from delusion the loss of memory. From anger comes delusion. Having restrained them all he should sit steadfast. and to the un-meditative there can be no peace. and to the man who has no peace. Vashe hi yasyendriyaani tasya prajnaa pratishthitaa. from attachment desire is born. Prasannachetaso hyaashu buddhih paryavatishthate. There is no knowledge of the Self to the unsteady. For the mind which follows in the wake of the wandering senses. He experiences sense-objects. the science of the Eternal. 69. He is unconscious of worldly phenomena. which. Being established therein. That which is night to all beings. 71. He attains peace into whom all desires enter as waters enter the ocean. Aapooryamaanam achalapratishtham Samudram aapah pravishanti yadwat.. This is the Brahmic seat (eternal state). 70. The ordinary man is unconscious of his real nature. without the sense of mine and without egoism. Nirmamo nirahankaarah sa shaantim adhigacchati. ends the second discourse entitled: “The Sankhya Yoga” 29 . abandoning all desires. the dialogue between Sri Krishna and Arjuna. none is deluded. this is day to him. 68. when all beings are awake. Therefore.BHAGAVAD GITA Indriyaaneendriyaarthebhyas tasya prajnaa pratishthitaa. Vihaaya kaamaan yah sarvaan pumaamshcharati nihsprihah. The man attains peace. So life in the Self is like night to him. this is day to him. remains unmoved. who. even at the end of life one attains to oneness with Brahman. this is like night to him. Tadwat kaamaa yam pravishanti sarve Sa shaantim aapnoti na kaamakaami. O son of Pritha! Attaining to this. Sthitwaasyaamantakaale’pi brahmanirvaanamricchati. filled from all sides. but not the man who is full of desires. COMMENTARY: The sage lives in the Self. the scripture of Yoga. 72. that is night for the sage who sees. then the self-controlled man is awake. moves about without longing. Eshaa braahmee sthitih paartha nainaam praapya vimuhyati. Yasyaam jaagrati bhootaani saa nishaa pashyato muneh. O mighty-armed Arjuna. his knowledge is steady whose senses are completely restrained from sense-objects! Yaanishaa sarvabhootaanaam tasyaam jaagarti samyamee. The Atman is beyond these three qualities and their functions. Sri Krishna quotes the example of Janaka.THE YOGA OF ACTION III THE YOGA OF ACTION Summary of Third Discourse In order to remove Moha or attachment. Arjuna raises the question as to why man commits such actions that cloud his mind and drag him downwards. Sri Krishna explains to Arjuna. light and freedom. The Lord tells Arjuna that each one should do his duty according to his nature. He can be ever absorbed in the calm and immutable Self. But to perform action for the good of the world and for the education of the masses is no doubt superior. Only when knowledge of this fact dawns in man does he attain perfection. If it be thought by Thee that knowledge is superior to action. O Kesava. Prakriti or Nature is made up of the three qualities—Rajas. Therefore. action is necessary not only for one who has attained perfection but also for one who is striving for perfection. Tamas and Sattwa. Arjuna said: 1. Sri Krishna taught him the imperishable nature of the Atman. Sri Krishna clears this doubt by telling him that although one has realised oneness with the Eternal. why then. Desire is the root cause of all evil actions. one has to perform action through the force of Prakriti or Nature. who continued to rule his kingdom even after attaining God-realisation. dost Thou ask me to engage in this terrible action? 30 . which was the sole cause of Arjuna’s delusion. as it were. by force. and thus commit wrong actions. as he has attained everything that has to be attained. A doubt therefore arises in Arjuna’s mind as to the necessity of engaging in action even after one has attained this state. He emphasises that perfection is attained not by ceasing to engage in action but by doing all actions as a divine offering. the great sage-king of India. and that doing duty that is suited to one’s nature in the right spirit of detachment will lead to perfection. then the divine power manifests in its full glory and one enjoys peace. Arjuna Uvaacha Jyaayasee chet karmanaste mataa buddhir janaardana. The man of God-vision. If desire is removed. need not engage in action. the realisation of which would grant him the freedom of the Eternal. Tat kim karmani ghore maam niyojayasi keshava. Sri Krishna answers that it is desire that impels man to lose his discrimination and understanding. O Krishna. bliss. imbued with a spirit of non-attachment and sacrifice. my understanding. He must possess knowledge of the Self. he excels! 31 . Tadekam vada nishchitya yena shreyo’ham aapnuyaam. But whosoever. Verily none can ever remain for even a moment without performing action. The Blessed Lord said: 3. Karmendriyaih karmayogam asaktah sa vishishyate.—the path of knowledge of the Sankhyas and the path of action of the Yogis! Na karmanaam anaarambhaan naishkarmyam purusho’shnute. Yastwindriyaani manasaa niyamyaarabhate’rjuna. he. is called a hypocrite. COMMENTARY: Even if a man abandons action. In this world there is a twofold path. of deluded understanding. for.BHAGAVAD GITA Vyaamishreneva vaakyena buddhim mohayaseeva me. Na hi kashchit kshanamapi jaatu tishthatyakarmakrit. merely by renouncing action. COMMENTARY: The ignorant man is driven to action helplessly by the actions of the Gunas—Rajas. Sri Bhagavaan Uvaacha: Loke’smin dwividhaa nishthaa puraa proktaa mayaanagha. Not by the non-performance of actions does man reach actionlessness. tell me that one way for certain by which I may attain bliss. engages himself in Karma Yoga with the organs of action. therefore. O Arjuna. 7. his mind may be active. Na cha sannyasanaad eva siddhim samadhigacchati. One cannot reach perfection or freedom from action or knowledge of the Self. Jnaanayogena saankhyaanaam karmayogena yoginaam. everyone is made to act helplessly indeed by the qualities born of Nature. 5. without attachment. O sinless one. sits thinking of the sense-objects in mind. Indriyaarthaan vimoodhaatmaa mithyaachaarah sa uchyate. controlling the senses by the mind. as I said before. 6. as it were. With these apparently perplexing words Thou confusest. Karmendriyaani samyamya ya aaste manasaa smaran. Kaaryate hyavashah karma sarvah prakritijair gunaih. Tamas and Sattwa. 2. restraining the organs of action. nor by mere renunciation does he attain to perfection. He who. 4. 13. ye shall attain to the highest good. 12. and may the gods nourish you. who eat of the remnants of the sacrifice. will give you the desired objects. Tair dattaan apradaayaibhyo yo bhungkte stena eva sah. 11. Devaan bhaavayataanena te devaa bhaavayantu vah. 10. Do thou perform thy bounden duty. do thou. 9. having in the beginning of creation created mankind together with sacrifice. Anena prasavishyadhwam esha vo’stvishtakaamadhuk. His heart is purified by performing actions for the sake of the Lord. Sahayajnaah prajaah srishtwaa purovaacha prajaapatih. nourished by the sacrifice. The gods. he who enjoys the objects given by the gods without offering (in return) to them. Shareerayaatraapi cha te na prasiddhyed akarmanah. Tadartham karma kaunteya muktasangah samaachara. The Creator. 8. Annaad bhavanti bhootaani parjanyaad anna sambhavah. he is not bound. verily eat sin. Ishtaan bhogaan hi vo devaa daasyante yajnabhaavitaah. The world is bound by actions other than those performed for the sake of sacrifice. Parasparam bhaavayantah shreyah param avaapsyatha. are freed from all sins. Yajnaarthaat karmano’nyatra loko’yam karmabandhanah. therefore. is verily a thief. however good or glorious they may be. free from attachment! COMMENTARY: If anyone does actions for the sake of the Lord. Where this spirit of unselfishness does not govern the action. perform action for that sake (for sacrifice) alone. O son of Kunti. The righteous. thus nourishing one another. for action is superior to inaction and even the maintenance of the body would not be possible for thee by inaction. said: “By this shall ye propagate. let this be the milch cow of your desires (the cow which yields the desired objects)”. but those sinful ones who cook food (only) for their own sake. With this do ye nourish the gods. So. Yajnaad bhavati parjanyo yajnah karma samudbhavah. 32 .THE YOGA OF ACTION Niyatam kuru karma twam karma jyaayo hyakarmanah. such actions bind one to worldliness. Bhunjate te twagham paapaa ye pachantyaatma kaaranaat. Yajnashishtaashinah santo muchyante sarva kilbishaih. who is satisfied in the Self. COMMENTARY: The sage who rejoices in his own Self does not gain anything by doing any action. 16. From food come forth beings.BHAGAVAD GITA 14. even with a view to the protection of the masses thou shouldst perform action. Yastwaatmaratir eva syaad aatmatriptashcha maanavah. do thou always perform action which should be done. but who indulges only in sensual pleasures. To him no real purpose is served by engaging in any action. by performing action without attachment man reaches the Supreme. 20. without attachment. Lokasangraham evaapi sampashyan kartum arhasi. O Arjuna! COMMENTARY: He who does not follow the wheel by studying the Vedas and performing the sacrifices prescribed therein. 17. and Brahma proceeds from the Imperishable. rejoicing in the senses. Karma brahmodbhavam viddhi brahmaakshara samudbhavam. Karmanaiva hi samsiddhim aasthitaa janakaadayah. 18. Therefore. he lives in vain. lives in vain. and from rain food is produced. He who does not follow the wheel thus set revolving. But for that man who rejoices only in the Self. 19. Aghaayur indriyaaraamo mogham paartha sa jeevati. He does not lose anything by being inactive. verily there is nothing to do. 33 . He wastes his life. Tasmaat sarvagatam brahma nityam yajne pratishthitam. from sacrifice arises rain. No evil can touch him as a result of inaction. for. and sacrifice is born of action. For him there is no interest whatsoever in what is done or what is not done. 15. Therefore. the all-pervading (Brahma) ever rests in sacrifice. Naiva tasya kritenaartho naakriteneha kashchana. Na chaasya sarvabhooteshu kashchidartha vyapaashrayah. Janaka and others attained perfection verily by action only. who is content in the Self alone. Asakto hyaacharan karma param aapnoti poorushah. nor does he depend on any being for any object. Aatmanyeva cha santushtas tasya kaaryam na vidyate. Evam pravartitam chakram naanuvartayateeha yah. Tasmaad asaktah satatam kaaryam karma samaachara. who is of sinful life. Know thou that action comes from Brahma. 27. For. 25.THE YOGA OF ACTION Yadyad aacharati shreshthas tattadevetaro janah. O Bharata (Arjuna). O Arjuna! Utseedeyur ime lokaa na kuryaam karma ched aham. that the world follows. that should be done by Me. 22. 24. Saktaah karmanyavidwaamso yathaa kurvanti bhaarata. wishing the welfare of the world! Na buddhibhedam janayed ajnaanaam karmasanginaam. Sa yat pramaanam kurute lokas tad anuvartate. mind. O Arjuna. Naanavaaptam avaaptavyam varta eva cha karmani. Joshayet sarva karmaani vidwaan yuktah samaacharan. whatever he sets up as the standard. COMMENTARY: Prakriti or Nature is that state in which the three Gunas exist in a state of equilibrium. Ahamkaaravimoodhaatmaa kartaaham iti manyate. He whose mind is deluded by egoism thinks: “I am the doer”. creation begins and the body. All actions are wrought in all cases by the qualities of Nature only. I should be the author of confusion of castes and destruction of these beings. that other men also do. nor is there anything unattained that should be attained. Let no wise man unsettle the minds of ignorant people who are attached to action. Sankarasya cha kartaa syaam upahanyaam imaah prajaah. 21. There is nothing in the three worlds. Prakriteh kriyamaanaani gunaih karmaani sarvashah. yet I engage Myself in action! Yadi hyaham na varteyam jaatu karmanyatandritah. As the ignorant men act from attachment to action. he should engage them in all actions. Mama vartmaanuvartante manushyaah paartha sarvashah. Kuryaad vidwaam stathaa saktash chikeershur lokasangraham. When this equilibrium is disturbed. The man who is deluded by egoism identifies the Self with the body. Na me paarthaasti kartavyam trishu lokeshu kinchana. men would in every way follow My path. unwearied. Whatsoever a great man does. should I not ever engage Myself in action. senses and mind are formed. himself fulfilling them with devotion. the 34 . 23. 26. so should the wise act without attachment. These worlds would perish if I did not perform action. Prakriter gunasammoodhaah sajjante gunakarmasu. 31. knowing that the Gunas as senses move amidst the Gunas as the sense-objects. about the divisions of the qualities and their functions. Sadrisham cheshtate swasyaah prakriter jnaanavaan api. beings will follow nature. Gunaa guneshu vartanta iti matwaa na sajjate. what can restraint do? COMMENTARY: Only the ignorant man comes under the sway of his natural propensities. A man of perfect knowledge should not unsettle the foolish one of imperfect knowledge. they too are freed from actions. Taan akritsnavido mandaan kritsnavin na vichaalayet. Shraddhaavanto’nasooyanto muchyante te’pi karmabhih. In reality the Gunas of nature perform all actions. But those who carp at My teaching and do not practise it. 32. Those deluded by the qualities of Nature are attached to the functions of the qualities. know them to be doomed to destruction. free from hope and egoism. and ascribes to the Self all the attributes of the body and the senses. and from (mental) fever. 28. deluded in all knowledge and devoid of discrimination. Renouncing all actions in Me. Mayi sarvaani karmaani sannyasyaadhyaatma chetasaa. Prakritim yaanti bhootaani nigrahah kim karishyati. Even a wise man acts in accordance with his own nature.BHAGAVAD GITA life-force and the senses. Sarvajnaanavimoodhaam staan viddhi nashtaan achetasah. Those men who constantly practise this teaching of Mine with faith and without cavilling. But he who knows the truth. The seeker after Truth who is endowed with the ‘Four Means’ and who constantly 35 . COMMENTARY: Surrender all actions to Me with the thought: “I perform all actions for the sake of the Lord only. Ye twetad abhyasooyanto naanutishthanti me matam. 29. with the mind centred in the Self. Niraasheer nirmamo bhootwaa yudhyaswa vigatajwarah. 33. Tattwavittu mahaabaaho gunakarma vibhaagayoh.” Ye me matam idam nityam anutishthanti maanavaah. O mighty-armed Arjuna. 30. do thou fight. is not attached. like love and hate. wisdom is enveloped by this constant enemy of the wise in the form of desire. O Arjuna. 38. can easily control Nature if he rises above the sway of the pairs of opposites. Mahaashano mahaapaapmaa viddhyenam iha vairinam. But impelled by what does man commit sin. Shreyaan swadharmo vigunah paradharmaat swanushthitaat. Arjuna Uvaacha: Atha kena prayukto’yam paapam charati poorushah. As fire is enveloped by smoke. constrained. It is desire. Arjuna said: 36. as it were. 36 . so is this enveloped by that. Better is death in one’s own duty. Yatholbenaavrito garbhas tathaa tenedam aavritam. Anicchann api vaarshneya balaad iva niyojitah. which is unappeasable as fire! Indriyaani mano buddhir asyaadhishthaanam uchyate. know this as the foe here (in this world). Kaamaroopena kaunteya dushpoorenaanalena cha. the duty of another is fraught with fear. 35. let none come under their sway. Aavritam jnaanam etena jnaanino nityavairinaa. etc. for they are his foes. O Varshneya (Krishna). Swadharme nidhanam shreyah paradharmo bhayaavahah. Better is one’s own duty. as a mirror by dust. 34. Dhoomenaavriyate vahnir yathaadarsho malena cha. 39. The Blessed Lord said: 37. than the duty of another well discharged. though against his wishes. though devoid of merit. all-sinful and all-devouring. Indriyasyendriyasyaarthe raagadweshau vyavasthitau. Attachment and aversion for the objects of the senses abide in the senses. Tayor na vasham aagacchet tau hyasya paripanthinau. it is anger born of the quality of Rajas. and as an embryo by the amnion. by force? Sri Bhagavaan Uvaacha: Kaama esha krodha esha rajoguna samudbhavah.THE YOGA OF ACTION practises meditation. Therefore.. But a man of discrimination and dispassion. the enemy in the form of desire. through these it deludes the embodied by veiling his wisdom. 40. who does constant and intense Sadhana. and one who is superior even to the intellect is He—the Self. the science of the Eternal. superior to the mind is the intellect. 42. hard to conquer! COMMENTARY: Restrain the lower self by the higher Self. 43. Manasastu paraa buddhir yo buddheh paratastu sah. Paapmaanam prajahi hyenam jnaana vijnaana naashanam. controlling the senses first. 41. They say that the senses are superior (to the body). superior to the senses is the mind. slay thou. ends the third discourse entitled: “The Yoga of Action” 37 . the dialogue between Sri Krishna and Arjuna. Thus. O mighty-armed Arjuna. the scripture of Yoga. Subdue the lower mind by the higher mind. Jahi shatrum mahaabaaho kaamaroopam duraasadam.BHAGAVAD GITA Etair vimohayatyesha jnaanam aavritya dehinam. The senses. It is difficult to conquer desire because it is of a highly complex and incomprehensible nature. do thou kill this sinful thing (desire). knowing Him who is superior to the intellect and restraining the self by the Self. Tasmaat twam indriyaanyaadau niyamya bharatarshabha. can conquer it quite easily. mind and intellect are said to be its seat. O best of the Bharatas (Arjuna). Evam buddheh param buddhwaa samstabhyaatmaanam aatmanaa. the destroyer of knowledge and realisation! Indriyaani paraanyaahur indriyebhyah param manah. but if the mind is active with the idea of doership and egoism. When knowledge of the Self dawns. On the other hand. according to Sri Krishna. whatever path they may use to approach Him. The Lord accepts the devotion of all. it is inaction in action. God Himself manifests in the heart of the Guru and instructs the disciple. He attains immortality. Through the practice of these sacrifices the mind is purified and led Godward. Such a union can only be achieved when one is free from attachment. Here also there must be the spirit of non-attachment to the fruits of actions. Hence we see the appearance of the great saviours of the world. just as fuel is burnt by fire. order and harmony. though engaged physically in intense action. What is the secret of Yogic action? This the Lord proceeds to explain to Arjuna. exist in his own Self and also in God. They lose their potency. in order to raise man and take him to the Supreme. one who has realised the Truth. all actions with their results are burnt by the fire of that knowledge. The aspirant should approach such a sage in a spirit of humility and devotion.THE YOGA OF WISDOM IV THE YOGA OF WISDOM Summary of Fourth Discourse Lord Krishna declares that He is born from age to age. then it is action in inaction. from the Creator down to a blade of grass. actions are no actions. Various kinds of sacrifices are performed by those engaged in the path to God. Faith is therefore the most important qualification for a spiritual aspirant. fear and anger. if the idea of agency is absent. the Lord manifests Himself to destroy these adverse forces and to establish peace. When there is no idea of egoism. Arjuna is given the most heartening assurance that divine wisdom liberates even the most sinful. The liberated man is free from attachment and is always calm and serene though engaged in ceaseless action. if one feels that Prakriti does everything. Divine wisdom. Having understood the Truth from the Guru by direct intuitive experience the aspirant is no longer deluded by ignorance. The doubting mind is always led 38 . One who has true union with the Lord is not subject to rebirth. Even though one is not engaged in action. In order to attain divine wisdom one must have supreme faith and devotion. being thoroughly purified by right knowledge. He cognises through internal experience or intuition that all beings. Whenever there is a prevalence of unrighteousness and the world is ruled by the forces of darkness. should be sought at the feet of a liberated Guru. The liberated aspirant directly beholds the Self in all beings and all beings in the Self. He is unaffected by the pairs of opposites like joy and grief. when there is no desire for the fruits of one’s actions. success and failure. handed down thus in regular succession. I taught this imperishable Yoga to Vivasvan. Bhakto’si me sakhaa cheti rahasyam hyetad uttamam. The Blessed Lord said: 1. 2. the royal sages knew. one’s doubts are rent asunder and divine knowledge manifests itself within. 39 . 3. Faith ultimately confers divine knowledge. COMMENTARY: This ancient Yoga consists of profound and subtle teachings. Vivaswaan manave praaha manur ikshwaakave’braveet. it is the supreme secret. Manu proclaimed it to Ikshvaku. Sa kaaleneha mahataa yogo nashtah parantapa. then true knowledge dawns within and one attains liberation and freedom from all weaknesses and sins. That same ancient Yoga has been today taught to thee by Me. When one has achieved complete self-mastery and self-control. O Parantapa (burner of foes)! COMMENTARY: The royal sages were kings who at the same time possessed divine knowledge. has been lost here. The Lord concludes by emphasising that the soul that doubts goes to destruction. Evam paramparaa praaptam imam raajarshayo viduh. Sa evaayam mayaa te’dya yogah proktah puraatanah. in the scriptures and in the words of the preceptor. This. which removes ignorance once and for all. Hence it is the supreme secret which the Lord reveals to Arjuna. by a long lapse of time. It cannot grant one supreme peace and freedom. when one has intense faith and devotion.BHAGAVAD GITA astray from the right path. Sri Bhagavaan Uvaacha: Imam vivaswate yogam proktavaan aham avyayam. Mere intellectual knowledge does not lead to liberation. By following the instructions of the Guru and through sincere service. he told it to Manu. Arjuna Uvaacha: Aparam bhavato janma param janma vivaswatah. one cannot make any headway on the spiritual path. This Yoga. for. It is doubt that prevents one from engaging in spiritual Sadhana and realising the highest knowledge and bliss. Spiritual progress then goes on at a rapid pace. Without faith in oneself. They learnt this Yoga. thou art My devotee and friend. Abhyutthaanam adharmasya tadaatmaanam srijaamyaham. Later on was Thy birth. and though I am the Lord of all beings. O Arjuna. Whenever there is a decline of righteousness. Paritraanaaya saadhoonaam vinaashaaya cha dushkritaam. O Arjuna! I know them all but thou knowest not. For the protection of the good. ruling over My own Nature. 6. Prakritim swaam adhishthaaya sambhavaamyaatmamaayayaa. Taanyaham veda sarvaani na twam vettha parantapa. Tyaktwa deham punarjanma naiti maameti so’rjuna. Though I am unborn and of imperishable nature. He who thus knows in true light My divine birth and action. Yadaa yadaa hi dharmasya glaanir bhavati bhaarata. I am born in every age. how am I to understand that Thou didst teach this Yoga in the beginning? Sri Bhagavaan Uvaacha: Bahooni me vyateetaani janmaani tava chaarjuna. 7. Bahavo jnaana tapasaa pootaa madbhaavam aagataah. that which drags him into worldliness is unrighteousness. That which helps a man to attain liberation is Dharma. as well as of thine. O Parantapa! Ajo’pi sannavyayaatmaa bhootaanaam eeshwaro’pi san.THE YOGA OF WISDOM Katham etadvijaaneeyaam twam aadau proktavaan iti. 9. O Arjuna! Veetaraagabhayakrodhaa manmayaa maam upaashritaah. Dharma samsthaapanaarthaaya sambhavaami yuge yuge. 40 . Many births of Mine have passed. then I manifest Myself! COMMENTARY: That which elevates a man and helps him to reach the goal of life and attain knowledge is Dharma (righteousness). he comes to Me. that which makes him irreligious is Adharma or unrighteousness. and prior to it was the birth of Vivasvan (the Sun). I am born by My own Maya. 8. Arjuna said: 4. Janma karma cha me divyam evam yo vetti tattwatah. for the destruction of the wicked. and for the establishment of righteousness. The Blessed Lord said: 5. yet. after having abandoned the body is not born again. and rise of unrighteousness. Vaisya and Sudra. Tamas predominates and Rajas is subordinate to the quality of Tamas. He possesses serenity. Actions do not taint Me. In a Brahmana. protection of cattle and trade. 41 . many have attained to My Being. Rajas predominates. Sattwa predominates. purified by the fire of knowledge. Rajas predominates and Tamas is subordinate to Rajas. This division is according to the Guna and Karma. He renders service to the other three castes. Tasya kartaaram api maam viddhyakartaaram avyayam. taking refuge in Me. COMMENTARY: The four castes are Brahmana. He possesses prowess. The fourfold caste has been created by Me according to the differentiation of Guna and Karma. In a Sudra. self-restraint. Kshipram hi maanushe loke siddhir bhavati karmajaa. Both Guna and Karma determine the caste of a man. even so do I reward them. nor have I a desire for the fruits of actions. splendour. Na maam karmaani limpanti na me karmaphale sprihaa.BHAGAVAD GITA 10. 14. purity. Chaaturvarnyam mayaa srishtam gunakarma vibhaagashah. He who knows Me thus is not bound by actions. Kuru karmaiva tasmaat twam poorvaih poorvataram kritam. Guna is quality. fear and anger. In whatever way men approach Me. My path do men tread in all ways. Ye yathaa maam prapadyante taamstathaiva bhajaamyaham. Mama vartmaanuvartante manushyaah paartha sarvashah. In a Vaisya. know Me as the non-doer and immutable. dexterity. 13. O Arjuna! Kaangkshantah karmanaam siddhim yajanta iha devataah. generosity and rulership. Human temperaments and tendencies vary according to the Gunas. Those who long for success in action in this world sacrifice to the gods. though I am the author thereof. Kshatriya. firmness. Iti maam yo’bhijaanaati karmabhir na sa badhyate. 12. 11. straightforwardness and devotion. absorbed in Me. In a Kshatriya. Evam jnaatwaa kritam karma poorvair api mumukshubhih. because success is quickly attained by men through action. He does the duty of ploughing. Freed from attachment. Karma is the kind of work. he incurs no sin. Having known this. Karmanyabhipravritto’pi naiva kinchit karoti sah. the world of birth and death). he does not do anything though engaged in activity. Karmanyakarma yah pashyed akarmani cha karma yah. For. He whose undertakings are all devoid of desires and (selfish) purposes. 16. verily the true nature of action (enjoined by the scriptures) should be known. action is no action at all. Jnaanaagni dagdhakarmaanam tam aahuh panditam budhaah. he is ever doing actions. COMMENTARY: It is the idea of agency. I shall teach thee such action (the nature of action and inaction). But if a man sits quietly. Having abandoned attachment to the fruit of the action.—him the wise call a sage. depending on nothing. Sa buddhimaan manushyeshu sa yuktah kritsnakarmakrit. by knowing which thou shalt be liberated from the evil (of Samsara. Karmano hyapi boddhavyam boddhavyam cha vikarmanah. therefore. and of inaction. also (that) of forbidden (or unlawful) action. It does not bind one to worldliness. Kim karma kim akarmeti kavayo’pyatra mohitaah. 17. the ancient seekers after freedom also performed actions. doing mere bodily action. ever content. 18. do thou perform actions as did the ancients in days of yore. This is referred to as action in inaction. he is wise among men.THE YOGA OF WISDOM 15. hard to understand is the nature (path) of action. having abandoned all greed. Niraasheer yatachittaatmaa tyaktasarvaparigrahah. Akarmanashcha boddhavyam gahanaa karmano gatih. Therefore. Tyaktwaa karmaphalaasangam nityatripto niraashrayah. What is action? What is inaction? As to this even the wise are confused. thinking of actions and that he is their doer. the idea of “I am the doer” that binds man to worldliness. 19. 42 . 21. This is inaction in action. Yasya sarve samaarambhaah kaamasankalpa varjitaah. Shaareeram kevalam karma kurvannaapnoti kilbisham. If this idea vanishes. 20. He who seeth inaction in action and action in inaction. Tat te karma pravakshyaami yajjnaatwaa mokshyase’shubhaat. Without hope and with the mind and the self controlled. he is a Yogi and performer of all actions. and whose actions have been burnt by the fire of knowledge. who is liberated. Yajnaayaacharatah karma samagram pravileeyate. others offer sound and various objects of the senses as sacrifice in the fire of the senses. Samah siddhaavasiddhau cha kritwaapi na nibadhyate. Daivam evaapare yajnam yoginah paryupaasate. 43 . Content with what comes to him without effort. wherein the idea of Brahman is substituted for the ideas of the instrument and other accessories of action. Some again offer hearing and other senses as sacrifice in the fire of restraint.BHAGAVAD GITA Yadricchaalaabhasantushto dwandwaateeto vimatsarah. Some Yogis perform sacrifice to the gods alone. Aatmasamyamayogaagnau juhwati jnaanadeepite. 23. Shrotraadeeneendriyaanyanye samyamaagnishu juhwati. Sarvaaneendriya karmaani praanakarmaani chaapare. Brahman is the oblation. the idea of action itself and its results. 22. while the ascetics of self-restraint and rigid vows offer study of scriptures and knowledge as sacrifice. 28. free from the pairs of opposites and envy. the whole action is dissolved. he is not bound. 24. Brahmaiva tena gantavyam brahmakarmasamaadhinaa. Some again offer wealth. By having such an idea the whole action melts away. 25. Others again sacrifice all the functions of the senses and those of the breath (vital energy or Prana) in the fire of the Yoga of self-restraint kindled by knowledge. by Brahman is the oblation poured into the fire of Brahman. Brahman is the melted butter (ghee). Shabdaadeen vishayaananya indriyaagnishu juhwati. whose mind is established in knowledge. 27. Brahmaagnaavapare yajnam yajnenaivopajuhwati. To one who is devoid of attachment. Brahmaarpanam brahmahavirbrahmaagnau brahmanaa hutam. even-minded in success and failure. Swaadhyaayajnaana yajnaashcha yatayah samshitavrataah. though acting. Gatasangasya muktasya jnaanaavasthitachetasah. Dravyayajnaas tapoyajnaa yogayajnaastathaapare. who works for the sake of sacrifice (for the sake of God). while others (who have realised the Self) offer the Self as sacrifice by the Self in the fire of Brahman alone. Brahman verily shall be reached by him who always sees Brahman in action. COMMENTARY: This is wisdom-sacrifice. 26. austerity and Yoga as sacrifice. He who does not perform any of these is not fit even for this miserable world. This world is not for the man who does not perform sacrifice. the wise who have realised the Truth will instruct thee in (that) knowledge. Karmajaan viddhi taan sarvaan evam jnaatwaa vimokshyase. Yajnashishtaamritabhujo yaanti brahma sanaatanam. Thus. Know them all as born of action. 44 .THE YOGA OF WISDOM Apaane juhwati praanam praane’paanam tathaa’pare. which are like nectar. Shreyaan dravyamayaadyajnaaj jnaanayajnah parantapa. 31. Yajjnaatwaa na punarmoham evam yaasyasi paandava. all these are knowers of sacrifice. O Arjuna? COMMENTARY: They go to the eternal Brahman after attaining knowledge of the Self through purification of the mind by performing the above sacrifices. 29. 34. Others who regulate their diet offer life-breaths in life-breaths. some practise exhalation. Apare niyataahaaraah praanaan praaneshu juhwati. Those who eat the remnants of the sacrifice. O Arjuna. Sarve’pyete yajnavido yajnakshapita kalmashaah. Know that by long prostration. how then can he have the other. various kinds of sacrifices are spread out before Brahman (literally at the mouth or face of Brahman). culminate in knowledge! Tadviddhi pranipaatena pariprashnena sevayaa. Praanaapaana gatee ruddhwaa praanaayaamaparaayanaah. go to the eternal Brahman. Upadekshyanti te jnaanam jnaaninas tattwadarshinah. thou shalt be liberated. Naayam loko’styayajnasya kuto’nyah kurusattama. and the incoming in the outgoing. How then can he hope to get a better world than this? Evam bahuvidhaa yajnaa vitataa brahmano mukhe. Superior is wisdom-sacrifice to sacrifice with objects. by question and by service. 32. Others offer as sacrifice the outgoing breath in the incoming. solely absorbed in the restraint of the breath. This is Pranayama. Sarvam karmaakhilam paartha jnaane parisamaapyate. COMMENTARY: Some Yogis practise inhalation. restraining the courses of the outgoing and the incoming breaths. 33. O Parantapa! All actions in their entirety. whose sins are all destroyed by sacrifice. and some retention of breath. and knowing thus. 30. 38. O Arjuna. As the blazing fire reduces fuel to ashes. Aatmavantam na karmaani nibadhnanti dhananjaya. Ajnashchaashraddhadhaanashcha samshayaatmaa vinashyati. and by that thou shalt see all beings in thy Self and also in Me! Api chedasi paapebhyah sarvebhyah paapakrittamah. obtains (this) knowledge. The man who is full of faith. Cchittwainam samshayam yogam aatishthottishtha bhaarata. yet thou shalt verily cross all sins by the raft of knowledge. the faithless. whose doubts are rent asunder by knowledge. Even if thou art the most sinful of all sinners. 39. thou shalt not. Sarvam jnaanaplavenaiva vrijinam santarishyasi. He who is perfected in Yoga finds it in the Self in time. having obtained the knowledge. Knowing that. 36. again become deluded like this. who is devoted to it. there is neither this world nor the other nor happiness for the doubting. O Arjuna. The ignorant. and. and who is self-possessed. 40. 37.BHAGAVAD GITA Yena bhootaanyasheshena drakshyasyaatmanyatho mayi. 41. O Arjuna! Tasmaad ajnaanasambhootam hritstham jnaanaasinaatmanah. Yogasannyasta karmaanam jnaanasamcchinnasamshayam. He who has renounced actions by Yoga. he goes at once to the supreme peace. COMMENTARY: One can overcome sin through Self-knowledge. 45 . the doubting self proceeds to destruction. Jnaanam labdhvaa paraam shaantim achirenaadhigacchati. Shraddhaavaan labhate jnaanam tatparah samyatendriyah. Verily there is no purifier in this world like knowledge. Yathaidhaamsi samiddho’gnir bhasmasaat kurute’rjuna. and who has subdued all the senses.—actions do not bind him. so does the fire of knowledge reduce all actions to ashes! Na hi jnaanena sadrisham pavitram iha vidyate. Tat swayam yogasamsiddhah kaalenaatmani vindati. 35. Naayam loko’sti na paro na sukham samshayaatmanah. Jnaanaagnih sarvakarmaani bhasmasaat kurute tathaa. Such a sage sees Brahman within and without—within as the static and transcendent Brahman. Therefore. he does not do anything. the scripture of Yoga. he is not born again. and without as the entire universe. He surrenders himself completely to the Divine Shakti. He is a spectator of everything. the dialogue between Sri Krishna and Arjuna. ends the fourth discourse entitled: “The Yoga of Wisdom” V THE YOGA OF RENUNCIATION OF ACTION Summary of Fifth Discourse In spite of Sri Krishna’s clear instructions. the path of action or the path of renunciation of action. Sri Krishna reminds Arjuna that desire is the main cause of pain and suffering. residing in thy heart. but the path of Karma Yoga is superior. He does not depend upon the senses for his satisfaction. The Karma Yogi who is aware of the Atman and who is constantly engaged in action knows that although the intellect. Arjuna still seems to be bewildered. ever remaining pure and unaffected.. They are impermanent. It is the cause of anger. The Lord says that both the paths lead to the highest goal of God-realisation. Krishna further asserts that perfection can be attained and one can be established in the Atman only after the mind has been purified through the performance of selfless action. mind and intellect by concentrating between the eyebrows and practising Pranayama. and take refuge in Yoga. He sees the one Self in all beings and creatures—in a cow. One who has achieved perfect 46 . Having completely rooted out all desires. mind and senses are active. with the sword of knowledge (of the Self) cut asunder the doubt of the self born of ignorance. The sage who has realised Brahman and is always absorbed in It does not have any rebirth. In both cases the final realisation of the Atman is the aim. He wants to know conclusively which is superior. On the other hand the enjoyments of the senses are generators of pain. Therefore. arise. and even in a dog and an outcaste. He dedicates all his actions to the Lord and thus abandons attachment. the science of the Eternal. an elephant. The Lord concludes by describing how to control the senses. attachments and the ego. Actually there is no real difference between the two. He is ever free from joy and grief and enjoys eternal peace and happiness. the aspirant should try to eradicate desire and anger if he is to reach the Supreme.THE YOGA OF WISDOM 42. Children. Renunciation of actions. 47 . Renunciation and the Yoga of action both lead to the highest bliss. ignorance. 3. he who is truly established in one obtains the fruits of both. some family quarrel or calamity or unemployment. Arjuna said: 1. not the wise. That place which is reached by the Sankhyas or the Jnanis is reached by the (Karma) Yogis. Physical renunciation of objects is no renunciation at all. he is easily set free from bondage! COMMENTARY: A man does not become a Sannyasin by merely giving up actions due to laziness. He should be known as a perpetual Sannyasin who neither hates nor desires. Yacchreya etayorekam tanme broohi sunishchitam. Arjuna Uvaacha: Sannyaasam karmanaam krishna punar yogam cha shamsasi. 5. Saankhyayogau prithagbaalaah pravadanti na panditaah. Tayostu karmasannyaasaat karmayogo vishishyate. Nirdwandwo hi mahaabaaho sukham bandhaat pramuchyate. Sri Bhagavaan Uvaacha: Sannyaasah karmayogashcha nihshreyasakaraa vubhau. O mighty-armed Arjuna. A true Sannyasin is one who has neither attachment nor aversion to anything. free from the pairs of opposites. The Blessed Lord said: 2. the Yoga of action is superior to the renunciation of action. He sees who sees knowledge and the performance of action (Karma Yoga) as one. Jneyah sa nityasannyaasi yo na dweshti na kaangkshati. What is wanted is the renunciation of egoism and desires. and again Yoga! Tell me conclusively which is the better of the two. speak of knowledge and the Yoga of action or the performance of action as though they are distinct and different. 4.BHAGAVAD GITA control of the outgoing senses and is freed from desire. O Krishna. Yatsaankhyaih praapyate sthaanam tad yogair api gamyate. anger and fear attains liberation and enjoys perfect peace. Thou praisest. for. Ekam apyaasthitah samyag ubhayor vindate phalam. but of the two. Ekam saankhyam cha yogam cha yah pashyati sa pashyati. 7. opening and closing the eyes—convinced that the senses move among the sense-objects. is hard to attain without Yoga. Brahmanyaadhaaya karmaani sangam tyaktwaa karoti yah. mind. He who performs actions. who has subdued his senses and who has realised his Self as the Self in all beings. Yuktah karmaphalam tyaktwaa shaantim aapnoti naishthikeem. 12. attains to the eternal peace. COMMENTARY: The liberated sage always remains as a witness of the activities of the senses as he identifies himself with the Self. 10. impelled by desire and attached to the fruit. Sarvabhootaatmabhootaatmaa kurvannapi na lipyate. sleeping. 6. Pralapan visrijan grihnan nunmishan nimishannapi. He who is devoted to the path of action. touching. Yogis. is bound. O mighty-armed Arjuna. is not tainted by sin as a lotus leaf by water. 9. whose mind is quite pure. having abandoned the fruit of action. having abandoned attachment. Yogayukto munir brahma na chirenaadhigacchati. Pashyan shrunvan sprishan jighran nashnan gacchan swapan shwasan. he is not tainted. breathing. offering them to Brahman and abandoning attachment. Kaayena manasaa buddhyaa kevalair indriyair api. Indriyaaneendriyaartheshu vartanta iti dhaarayan. intellect and also by the senses. Lipyate na sa paapena padmapatram ivaambhasaa. 48 . Ayuktah kaamakaarena phale sakto nibadhyate. going. for the purification of the self. Naiva kinchit karomeeti yukto manyeta tattwavit. 8. hearing. The united one (the well poised or the harmonised). smelling. though acting.THE YOGA OF RENUNCIATION OF ACTION Sannyaasastu mahaabaaho duhkham aaptuma yogatah. eating. letting go. perform actions only by the body. Speaking. But renunciation. the Yoga-harmonised sage proceeds quickly to Brahman! Yogayukto vishuddhaatmaa vijitaatmaa jitendriyah. seizing. who has conquered the self. Yoginah karma kurvanti sangam tyaktwaatmashuddhaye. “I do nothing at all”—thus will the harmonised knower of Truth think—seeing. 11. the non-united only (the unsteady or the unbalanced). BHAGAVAD GITA Sarvakarmaani manasaa sannyasyaaste sukham vashee. 15. Shuni chaiva shvapaake cha panditaah samadarshinah. neither acting nor causing others (body and senses) to act. 17. to those whose ignorance is destroyed by knowledge of the Self. it is Nature that acts. Neither agency nor actions does the Lord create for the world. established in That. Na karmaphala samyogam swabhaavas tu pravartate. Mentally renouncing all actions and self-controlled. Sthirabuddhir asammoodho brahmavid brahmani sthitah. on an elephant. and even on a dog and an outcaste. Tadbuddhayas tadaatmaanas tannishthaas tatparaayanaah. Naadatte kasyachit paapam na chaiva sukritam vibhuh. with That as their supreme goal. thereby beings are deluded. 18. they go whence there is no return. they are established in Brahman. Even here (in this world) birth (everything) is overcome by those whose minds rest in equality. the embodied one rests happily in the nine-gated city. Ihaiva tairjitah sargo yeshaam saamye sthitam manah. Nirdosham hi samam brahma tasmaad brahmani te sthitaah. Sages look with an equal eye on a Brahmin endowed with learning and humility. Teshaam aadityavaj jnaanam prakaashayati tatparam. The Lord accepts neither the demerit nor even the merit of any. Vidyaavinaya sampanne braahmane gavi hastini. like the sun. 14. nor union with the fruits of actions. Their intellect absorbed in That. knowledge is enveloped by ignorance. therefore. on a cow. knowledge reveals the Supreme (Brahman). Brahman is spotless indeed and equal. But. 16. Navadwaare pure dehee naiva kurvan na kaarayan. their sins dispelled by knowledge. 19. Jnaanena tu tad ajnaanam yeshaam naashitam aatmanah. their self being That. 13. Na kartritwam na karmaani lokasya srijati prabhuh. Gacchantyapunaraavrittim jnaana nirdhoota kalmashaah. Ajnaanenaavritam jnaanam tena muhyanti jantavah. Na prahrishyet priyam praapya nodwijet praapya chaapriyam. 49 . Sa yogee brahma nirvaanam brahmabhooto’dhigacchati. equalising the outgoing and incoming breaths moving within the nostrils. himself becoming Brahman. who have controlled their thoughts and who have realised the Self. The sages obtain absolute freedom or Moksha—they whose sins have been destroyed.THE YOGA OF RENUNCIATION OF ACTION 20. who are self-controlled. Resting in Brahman. 24. the knower of Brahman neither rejoiceth on obtaining what is pleasant nor grieveth on obtaining what is unpleasant. 50 . undeluded. for they have a beginning and an end. The enjoyments that are born of contacts are generators of pain only. such a Yogi attains absolute freedom or Moksha. he is a happy man. 27. 21. 25. Shutting out (all) external contacts and fixing the gaze between the eyebrows. who rejoices within. who is illumined within. 23. O Arjuna! The wise do not rejoice in them. Kaamakrodhaviyuktaanaam yateenaam yatachetasaam. the impulse born of desire and anger—he is a Yogi. while still here in this world to withstand. and intent on the welfare of all beings. with the self engaged in the meditation of Brahman he attains to the endless happiness. 26. before the liberation from the body. Yo’ntah sukho’ntaraaraamas tathaantarjyotir eva yah. Cchinnadwaidhaa yataatmaanah sarvabhootahite rataah. Absolute freedom (or Brahmic bliss) exists on all sides for those self-controlled ascetics who are free from desire and anger. Ye hi samsparshajaa bhogaa duhkhayonaya eva te. Labhante brahma nirvaanam rishayah ksheenakalmashaah. Baahyasparsheshwasaktaatmaa vindatyaatmani yat sukham. Abhito brahma nirvaanam vartate viditaatmanaam. whose dualities (perception of dualities or experience of the pairs of opposites) are torn asunder. Shaknoteehaiva yah sodhum praak shareera vimokshanaat. Sa brahma yoga yuktaatmaa sukham akshayam ashnute. with steady intellect. Praanaapaanau samau kritwaa naasaabhyantara chaarinau. With the self unattached to the external contacts he discovers happiness in the Self. 22. Aadyantavantah kaunteya na teshu ramate budhah. He who is ever happy within. Sparsaan kritwaa bahir baahyaamschakshus chaivaantare bhruvoh. Kaamakrodhodbhavam vegam sa yuktah sa sukhee narah. He who is able. He who knows Me as the enjoyer of sacrifices and austerities. With the senses. He sees inwardly that there is no difference between gold and stone. Vigatecchaabhaya krodho yah sadaa mukta eva sah. fear and anger—the sage is verily liberated for ever. the scripture of Yoga. mind and senses and is united with God. free from desire. can engage itself in constant meditation on the Atman. the mind and the intellect always controlled. He is perfectly harmonised. Therefore.. 29. between friends and enemies.BHAGAVAD GITA Yatendriya manobuddhir munir mokshaparaayanah. He should arrange his meditation seat properly and sit in a comfortable posture. Then the higher Self becomes one’s friend. between the righteous and the unrighteous. 28. having liberation as his supreme goal. attains to peace. which drives the soul into the field of action. none can realise permanent freedom and tranquillity of mind without renouncing desires. the science of the Eternal. mind and senses must be controlled by the power of the higher Self. sees God in all objects and beings. a mind free from desires. Sri Krishna proceeds to give various practical hints as to the practice of meditation. the great Lord of all the worlds and the friend of all beings. The lower self must be controlled by the higher Self. Desire gives rise to imagination or Sankalpa. Suhridam sarvabhootaanaam jnaatwaa maam shaantim ricchati. The aspirant should select a secluded spot where there is no likelihood of disturbance. performance of actions without an eye on their fruits brings about the purification of the mind. All the lower impulses of the body. Only a purified mind. He who has perfect control of the body. Bhoktaaram yajnatapasaam sarvaloka maheshwaram. not the actions themselves. neck and spine 51 . with the head. with more favourable conditions for Sadhana. Arjuna wishes to know the fate of the aspirant who fails to realise the Supreme in spite of his faith and sincerity. recreation. The conservation and transformation of the vital fluid into spiritual energy gives immense power of concentration. Sri Bhagavaan Uvaacha: Anaashritah karmaphalam kaaryam karma karoti yah. He does not relish any more the pleasures of the senses. The Blessed Lord said: 1. not he who is without fire and without action.THE YOGA OF MEDITATION erect but not tensed. to the men of book knowledge and the men of action. Na hyasannyastasankalpo yogee bhavati kashchana. as its very nature seems to be one of restlessness. Krishna tells him that the accumulated power of his Yogic practices will assure him a better birth in the future. Arjuna is doubtful whether it is at all possible to engage the mind steadily on the higher Self. He who performs his bounden duty without depending on the fruits of his actions—he is a Sannyasin and a Yogi. Living a life of such moderation. that there is no gain greater than the Self. Krishna concludes that the Yogi—one who has attained union with the Supreme Lord—is superior to the ascetics. The aspirant will then be compelled to carry on his Yogic practices with greater vigour and faith and will finally achieve God-realisation. The aspirant is advised to practise moderation in his daily habits—in eating. Sa sannyaasi cha yogee cha na niragnirna chaakriyah. Having thus attained perfect union with the Self. etc. the aspirant gradually transcends the senses and intellect and merges himself in the blissful Atman. Lord Krishna again emphasises that the concentration of the mind on the Atman should be like a steady flame in a windless place. Extremes are to be avoided as they hinder the practice of meditation. This ultimately leads to the vision of the Lord in all beings and creatures. He should fix his purified mind on the Atman by concentrating between the eyebrows or on the tip of the nose. He finds that the bliss of the Atman is incomparable. and gathering up all his forces and directing them towards meditation upon the Atman. as the latter have not transcended ignorance and merged in the Self. The practice of Brahmacharya is absolutely necessary if one is to succeed in meditation. Krishna assures him that the practice can succeed through Vairagya (dispassion) and constant effort. too. Yam sannyaasamiti praahuryogam tam viddhi paandava. Fearlessness. It is faith in the sustaining protection and Grace of God. the Yogi no more descends into ignorance or delusion. is an essential quality on the Godward path. sleeping. 52 . Jitaatmanah prashaantasya paramaatmaa samaahitah. 7. The self is the friend of the self for him who has conquered himself by the Self. for this self alone is the friend of oneself and this self alone is the enemy of oneself. Anaatmanastu shatrutwe vartetaatmaiva shatruvat. Saadhushwapi cha paapeshu samabuddhirvishishyate. The Supreme Self of him who is self-controlled and peaceful is balanced in cold and heat. 53 . inaction (quiescence) is said to be the means. but to the unconquered self. is said to have attained the state of Nirvikalpa Samadhi). Uddharedaatmanaatmaanam naatmaanamavasaadayet. 5. this self stands in the position of an enemy like the (external) foe. In order to encourage the practice of Karma Yoga it is stated here that it is Sannyasa. Yogaaroodhasya tasyaiva shamah kaaranamuchyate. a piece of stone and gold are the same. The Yogi who is satisfied with the knowledge and the wisdom (of the Self). O Arjuna. Suhrinmitraary udaaseena madhyastha dweshya bandhushu. then he is said to have attained to Yoga. and to whom a clod of earth. Bandhuraatmaa’tmanastasya yenaatmaivaatmanaa jitah. Let a man lift himself by his own Self alone. For a sage who wishes to attain to Yoga. Yuktah ityuchyate yogee samaloshtaashmakaanchanah. 8. 3. Do thou. no one verily becomes a Yogi who has not renounced thoughts! COMMENTARY: Lord Krishna eulogises Karma Yoga here because it is a means or a stepping stone to the Yoga of meditation. 4. Jnaana vijnaana triptaatmaa kootastho vijitendriyah. action is said to be the means. for the same sage who has attained to Yoga. Atmaiva hyaatmano bandhuraatmaiva ripuraatmanah. know Yoga to be that which they call renunciation. having renounced all thoughts. 6.BHAGAVAD GITA 2. When a man is not attached to the sense-objects or to actions. pleasure and pain. as also in honour and dishonour. who has conquered the senses. let him not lower himself. is said to be harmonised (that is. Aarurukshormuneryogam karma kaaranamuchyate. Sheetoshna sukha duhkheshu tathaa maanaapamaanayoh. Yadaa hi nendriyaartheshu na karmaswanushajjate. Sarvasankalpasannyaasee yogaaroodhas tadochyate. Shaantim nirvaanaparamaam matsamsthaamadhigacchati. remaining in solitude. the Yogi. let him sit. 11. made of a cloth. firm in the vow of a Brahmachari. Prashaantaatmaa vigatabheer brahmachaarivrate sthitah. 13. the righteous and the unrighteous. Naatyucchritam naatineecham chailaajinakushottaram. 14. excels. Verily Yoga is not possible for him who eats too much. attains to the peace abiding in Me. nor for him who sleeps too much. nor for him who is (always) awake. Naatyashnatastu yogo’sti nachaikaantamanashnatah.THE YOGA OF MEDITATION 9. Samprekshya naasikaagram swam dishashchaanavalokayan. enemies. Ekaakee yatachittaatmaa niraasheeraparigrahah. the hateful. O Arjuna! Yuktaahaaravihaarasya yuktacheshtasya karmasu. the relatives. the indifferent. with the mind and the body controlled. always keeping the mind balanced. Yogee yunjeeta satatamaatmaanam rahasi sthitah. Upavishyaasane yunjyaadyogamaatmavishuddhaye. neither too high nor too low. having established a firm seat of his own. Shuchau deshe pratishthaapya sthiramaasanamaatmanah. 54 . friends. 16. with the actions of the mind and the senses controlled. practise Yoga for the purification of the self. Let him firmly hold his body. thinking of Me and balanced in mind. without looking around. seated on the seat. fearless. There. Tatraikaagram manah kritwaa yatachittendriyakriyah. 15. Thus. He who is of the same mind to the good-hearted. 12. Samam kaayashirogreevam dhaarayannachalam sthirah. head and neck erect and perfectly still. In a clean spot. the neutral. Yunjannevam sadaa’tmaanam yogee niyatamaanasah. 10. Let the Yogi try constantly to keep the mind steady. and free from hope and greed. which culminates in liberation. alone. with the mind controlled. having controlled the mind. one over the other. having Me as his supreme goal. let him. a skin and kusha grass. Serene-minded. nor for him who does not eat at all. Manah samyamya macchitto yukta aaseeta matparah. having made the mind one-pointed. gazing at the tip of his nose. Na chaatiswapnasheelasya jaagrato naiva chaarjuna. who is moderate in sleep and wakefulness. 18. Yam labdhwaa chaaparam laabham manyate naadhikam tatah. As a lamp placed in a windless spot does not flicker—to such is compared the Yogi of controlled mind. 21. COMMENTARY: This is a beautiful simile which Yogis often quote when they talk of concentration or one-pointedness of mind. 17. wherein established. Yatra chaivaatmanaa’tmaanam pashyannaatmani tushyati.” COMMENTARY: Without union with the Self neither harmony nor balance nor Samadhi is possible. established wherein he never moves from the Reality. who is moderate in exertion in actions. 22.— Tam vidyaad duhkhasamyogaviyogam yogasamjnitam. Sukhamaatyantikam yattad buddhi graahyamateendriyam. he thinks there is no other gain superior to it. Yadaa viniyatam chittamaatmanyevaavatishthate. seeing the Self by the Self. Yogino yatachittasya yunjato yogamaatmanah.BHAGAVAD GITA Yuktaswapnaavabodhasya yogo bhavati duhkhahaa. Yasmin sthito na duhkhena gurunaapi vichaalyate. Yathaa deepo nivaatastho nengate sopamaa smritaa. Vetti yatra na chaivaayam sthitashchalati tattwatah. Sa nishchayena yoktavyo yogo’nirvinna chetasaa. attains to quietude. 20. he is not moved even by heavy sorrow. etc. he is satisfied in his own Self. free from longing for the objects of desire. and. practising Yoga in the Self (or absorbed in the Yoga of the Self). then it is said: “He is united. Yatroparamate chittam niruddham yogasevayaa. 55 . having obtained. restrained by the practice of Yoga. When the mind. Which.). 19. Nihsprihah sarvakaamebhyo yukta ityuchyate tadaa. Yoga becomes the destroyer of pain for him who is always moderate in eating and recreation (such as walking. When the perfectly controlled mind rests in the Self only. and when. When he (the Yogi) feels that infinite bliss which can be grasped by the (pure) intellect and which transcends the senses. Shanaih shanairuparamed buddhyaa dhritigriheetayaa. COMMENTARY: The mind is so diplomatic that it keeps certain desires for its secret gratification. Aatmasamstham manah kritwaa na kinchidapi chintayet. From whatever cause the restless. freed from sins. Supreme bliss verily comes to this Yogi whose mind is quite peaceful. he sees the same everywhere. always engaging the mind thus (in the practice of Yoga). from that let him restrain it and bring it under the control of the Self alone. Abandoning without reserve all the desires born of Sankalpa. 24. let him not think of anything. Upaiti shaantarajasam brahmabhootamakalmasham. and who is free from sin. Sankalpaprabhavaan kaamaan styaktwaa sarvaan asheshatah. The Yogi. the severance from union with pain. Tatastato niyamyaitad aatmanyeva vasham nayet.THE YOGA OF MEDITATION 23. and completely restraining the whole group of senses by the mind from all sides. 28. So one should completely abandon all desires without reservation. Sukhena brahmasamsparsham atyantam sukham ashnute. Eekshate yogayuktaatmaa sarvatra samadarshanah. Let that be known by the name of Yoga. whose passion is quieted. Prashaantamanasam hyenam yoginam sukhamuttamam. Little by little let him attain to quietude by the intellect held firmly. Sarvabhootasthamaatmaanam sarvabhootaani chaatmani. 56 . 27. 29. This Yoga should be practised with determination and with an undesponding mind. Tasyaaham na pranashyaami sa cha me na pranashyati. easily enjoys the infinite bliss of contact with Brahman (the Eternal). Yato yato nishcharati manashchanchalamasthiram. Yunjannevam sadaa’tmaanam yogee vigatakalmashah. unsteady mind wanders away. Yo maam pashyati sarvatra sarvam cha mayi pashyati. who has become Brahman. 26. 25. With the mind harmonised by Yoga he sees the Self abiding in all beings and all beings in the Self. having made the mind establish itself in the Self. Manasaivendriyagraamam viniyamya samantatah. The mind verily is restless. Arjuna said: 33. That is why the mind is even more difficult to control than to control the wind. O mighty-armed Arjuna. So it is always restless. I do not see its steady continuance. 34. he is regarded as the highest Yogi! Arjuna Uvaacha: Yo’yam yogastwayaa proktah saamyena madhusoodana. he does not become separated from Me nor do I become separated from him. Sukham vaa yadi vaa duhkham sa yogee paramo matah. Undoubtedly. Sarvabhootasthitam yo maam bhajatyekatwamaasthitah. Aatmaupamyena sarvatra samam pashyati yo’rjuna. It produces agitation in the body and in the senses. The Blessed Lord said: 35. turbulent. O Krishna! I deem it as difficult to control as to control the wind.—that Yogi abides in Me. He who. by practice and by dispassion it may be restrained! 57 . O Krishna. COMMENTARY: The mind ever changes its point of concentration from one object to another. Sarvathaa vartamaano’pi sa yogee mayi vartate. O Arjuna. be it pleasure or pain. 32. Etasyaaham na pashyaami chanchalatwaat sthitim sthiraam. being established in unity. strong and unyielding. Tasyaaham nigraham manye vaayoriva sudushkaram. because of restlessness (of the mind)! Chanchalam hi manah krishna pramaathi balavad dridham. This Yoga of equanimity taught by Thee. It is not only restless but also turbulent and impetuous. whatever may be his mode of living. through the likeness of the Self. 31. Sri Bhagavaan Uvaacha: Asamshayam mahaabaaho mano durnigraham chalam. sees equality everywhere. strong and obstinate.BHAGAVAD GITA 30. COMMENTARY: The Lord describes here the effect of oneness. He who. worships Me who dwells in all beings. the mind is difficult to control and restless. Abhyaasena tu kaunteya vairaagyena cha grihyate. but. He who sees Me everywhere and sees everything in Me. This doubt of mine. 41. Having attained to the worlds of the righteous and. The Blessed Lord said: 40. I think that Yoga is hard to be attained by one of uncontrolled self. Sri Bhagavaan Uvaacha: Paartha naiveha naamutra vinaashas tasya vidyate. what end does he meet. Athavaa yoginaameva kule bhavati dheemataam. Shucheenaam shreemataam gehe yogabhrashto’bhijaayate. O mighty-armed (Krishna). and whose mind wanders away from Yoga. O Arjuna. Fallen from both. ever comes to grief! Praapya punyakritaam lokaanushitwaa shaashwateeh samaah. nor in the next world is there destruction for him. verily. Nahi kalyaanakrit kashchid durgatim taata gacchati. deluded on the path of Brahman? Etanme samshayam krishna cchettumarhasyasheshatah. he who fell from Yoga is reborn in the house of the pure and wealthy. neither in this world. Apraapya yogasamsiddhim kaam gatim krishna gacchati. COMMENTARY: There is no better teacher than the Lord Himself as He is omniscient. does he not perish like a rent cloud. Twadanyah samshayasyaasya cchettaa na hyupapadyate. having failed to attain perfection in Yoga. Apratishtho mahaabaaho vimoodho brahmanah pathi. O Krishna? Kacchinnobhayavibhrashtash cchinnaabhramiva nashyati. but the self~controlled and striving one attains to it by the (proper) means. Etaddhi durlabhataram loke janma yadeedrisham. because it is not possible for any but Thee to dispel this doubt. Arjuna Uvaacha: Ayatih shraddhayopeto yogaacchalitamaanasah. do Thou completely dispel. none. Vashyaatmanaa tu yatataa shakyo’vaaptumupaayatah. supportless. He who is unable to control himself though he has the faith. Arjuna said: 37. 39. 36.THE YOGA OF MEDITATION Asamyataatmanaa yogo dushpraapa iti me matih. who does good. O Krishna. O My son. 38. 58 . having dwelt there for everlasting years.” VII THE YOGA OF WISDOM AND REALISATION Summary of Seventh Discourse Sri Krishna tells Arjuna that the supreme Godhead has to be realised realisation. The Lord has already given a clear description of the all-pervading static and infinite state of His. Now He. 60 BHAGAVAD GITA. 61 Whatever being (and objects) that are pure. 13. I am the intelligence of the intelligent. those who take refuge in Me alone cross over this illusion. Matta eveti taanviddhi na twaham teshu te mayi. I am the sapidity in water. Pranavah sarvavedeshu shabdah khe paurusham nrishu. Jeevanam sarvabhooteshu tapashchaasmi tapaswishu. O Arjuna! I am the light in the moon and the sun. Punyo gandhah prithivyaam cha tejashchaasmi vibhaavasau. They are in Me. 8. and in (all) beings. Verily this divine illusion of Mine made up of the qualities (of Nature) is difficult to cross over. 10. I alone am the cause of the universe. yet I am not in them. Tribhirgunamayair bhaavairebhih sarvamidam jagat. active and inert. and I am austerity in ascetics. Beejam maam sarvabhootaanaam viddhi paartha sanaatanam. I am the syllable Om in all the Vedas. I am the desire unopposed to Dharma. Na maam dushkritino moodhaah prapadyante naraadhamaah. Mohitam naabhijaanaati maamebhyah paramavyayam. Know Me. I am the strength devoid of desire and attachment. Buddhir buddhimataamasmi tejastejaswinaamaham. 11. Raso’hamapsu kaunteya prabhaasmi shashisooryayoh. as the eternal seed of all beings. and virility in men. 14. the life in all beings. O Arjuna! Ye chaiva saattvikaa bhaavaa raajasaastaamasaashcha ye. all this world does not know Me as distinct from them and immutable. Daivee hyeshaa gunamayee mama maayaa duratyayaa. the splendour of the splendid objects am I! Balam balavataam asmi kaamaraagavivarjitam. know that they proceed from Me. Dharmaaviruddho bhooteshu kaamo’smi bharatarshabha.THE YOGA OF WISDOM AND REALISATION COMMENTARY: There is no other cause of the universe but Me. sound in ether. Of the strong. 12. I am the sweet fragrance in earth and the brilliance in fire. O Arjuna. 9. Deluded by these Natures (states or things) composed of the three qualities of Nature. 62 . Maameva ye prapadyante maayaametaam taranti te. they whose knowledge is destroyed by illusion follow the ways of demons. 20. Of them. excels (is the best). I am exceedingly dear to the wise and he is dear to Me. and from it he obtains his desire. Priyo hi jnaanino’tyarthamaham sa cha mama priyah. the seeker of knowledge. go to other gods. 16. 17. such a great soul (Mahatma) is very hard to find. Sa tayaa shraddhayaa yuktastasyaaraadhanameehate. 63 . O Arjuna! They are the distressed. The evil-doers and the deluded. 21. Aarto jijnaasurartharthee jnaanee cha bharatarshabha. and the wise. Vaasudevah sarvamiti sa mahaatmaa sudurlabhah. the wise. who are the lowest of men. Labhate cha tatah kaamaan mayaiva vihitaan hi taan. 18. Udaaraah sarva evaite jnaanee twaatmaiva me matam. Chaturvidhaa bhajante maam janaah sukritino’rjuna. realising that all this is Vasudeva (the innermost Self). he is established in Me alone as the supreme goal. Endowed with that faith. for. 15. ever steadfast and devoted to the One. O lord of the Bharatas! Teshaam jnaanee nityayukta eka bhaktirvishishyate. he engages in the worship of that (form). Tam tam niyamamaasthaaya prakrityaa niyataah swayaa. 19. At the end of many births the wise man comes to Me. the seeker of wealth. 22. Tasya tasyaachalaam shraddhaam taameva vidadhaamyaham. these being verily ordained by Me (alone). Those whose wisdom has been rent away by this or that desire.BHAGAVAD GITA Maayayaapahritajnaanaa aasuram bhaavamaashritaah. do not seek Me. following this or that rite. for. Aasthitah sa hi yuktaatmaa maamevaanuttamaam gatim. Bahoonaam janmanaamante jnaanavaanmaam prapadyate. led by their own nature. steadfast in mind. but I deem the wise man as My very Self. Kaamaistaistairhritajnaanaah prapadyante’nyadevataah. Yo yo yaam yaam tanum bhaktah shraddhayaarchitum icchati. Four kinds of virtuous men worship Me. Whatsoever form any devotee desires to worship with faith—that (same) faith of his I make firm and unflinching. Noble indeed are all these. O Arjuna. Verily the reward (fruit) that accrues to those men of small intelligence is finite. Naaham prakaashah sarvasya yogamaayaasamaavritah. This deluded world does not know Me. Moodho’yam naabhijaanaati loko maamajamavyayam. but My devotees come to Me. Te brahma tadviduh kritsnam adhyaatmam karma chaakhilam. Prayaanakaale’pi cha maam te vidur yuktachetasah. immutable and most excellent nature. Saadhibhootaadhidaivam maam saadhiyajnam cha ye viduh. But those men of virtuous deeds whose sins have come to an end. Icchaadweshasamutthena dwandwamohena bhaarata. knowing not My higher. realise in full that Brahman. the present and the future. and who are freed from the delusion of the pairs of opposites.THE YOGA OF WISDOM AND REALISATION Antavattu phalam teshaam tadbhavatyalpamedhasaam. taking refuge in Me. Te dwandwamohanirmuktaa bhajante maam dridhavrataah. worship Me. I am not manifest to all (as I am). Those who strive for liberation from old age and death. Jaraamaranamokshaaya maamaashritya yatanti ye. 27. the whole knowledge of the Self and all action. O Bharata. 25. all beings are subject to delusion at birth. the unborn and imperishable. 26. O Parantapa! Yeshaam twantagatam paapam janaanaam punyakarmanaam. Vedaaham samateetaani vartamaanaani chaarjuna. Avyaktam vyaktimaapannam manyante maamabuddhayah. but no one knows Me. 23. Sarvabhootaani sammoham sarge yaanti parantapa. I know. as having manifestation. The foolish think of Me. Devaan devayajo yaanti madbhaktaa yaanti maamapi. By the delusion of the pairs of opposites arising from desire and aversion. steadfast in their vows. the Unmanifest. The worshippers of the gods go to them. 24. being veiled by the Yoga Maya. Param bhaavamajaananto mamaavyayamanuttamam. 29. 64 . the beings of the past. 28. Bhavishyaani cha bhootani maam tu veda na kashchana. regular meditation and continuous communion. if one can ever remain united with the Divine through deep devotion. That radiant. steadfast in mind. and what is the meaning that pertains to this spirit. places. Single-minded devotion of our heart is the means of attaining this highest blessed state. He wishes to know what is the Supreme Being. Even though there are auspicious and inauspicious circumstances of departing from the physical body and journeying forth. By always remaining in tune with the Lord through pure love. conditions and situations become auspicious and blessed. yet if one steadily abides in the Lord through firm devotion and faith. then these conditions do not matter. what is Karma or action that He refers to. the dialogue between Sri Krishna and Arjuna. Arjuna here asks Lord Krishna about the meaning of the different terms referred to by Him in the last two verses of the previous chapter. COMMENTARY: They who are steadfast in mind. the Adhidaiva (pertaining to the gods). everything is made auspicious. the elements and the centre of all things within this human body. This is the secret of invoking His Grace and attaining Him and becoming eternally free and blissful. the scripture of Yoga. 65 .—they are not affected by death. the science of the Eternal. who know Me as knowledge of elements on the physical plane. as knowledge of sacrifice in the realm of sacrifice. All beings. and Adhiyajna (pertaining to the sacrifice).BHAGAVAD GITA 30. come again and again into this created universe from the state of unmanifest being wherein they remained at the end of an age-cycle. including even the gods.. Those who know Me with the Adhibhuta (pertaining to the elements). as knowledge of gods on the celestial or mental plane. imperishable Divine Reality is the highest goal to be attained. But the Lord exists even beyond this unmanifest being. who have taken refuge in Me.. then all times. know Me even at the time of death. constant remembrance. He indwells this body as the centre of all things. senses must be well disciplined and gradually withdrawn from outside objects. art Thou to be known by the self-controlled one? COMMENTARY: In the last two verses of the seventh discourse. What is that Brahman? What is Adhyatma? What is action. prayer and offering to the gods with faith and devotion constitute actions that lead to blessedness. 2. Lord Krishna uses certain philosophical terms. By such steady practice daily the Lord is easily attained. O destroyer of Madhu (Krishna)? And how. Prakriti or Nature is the being pertaining to the elements. Thus departing. there is the Supreme Being—Brahman. is to constantly practise unbroken remembrance of the Lord at all times. Prayaanakaale cha katham jneyo’si niyataatmabhih. at the time of death.THE YOGA OF THE IMPERISHABLE BRAHMAN Beyond all things manifest and unmanifest. One must practise sense-control. O best among men? What is declared to be Adhibhuta? And what is Adhidaiva said to be? Adhiyajnah katham ko’tra dehe’smin madhusoodana. by uttering Om or any Divine Name. then he will be rooted in His remembrance even at the time of departing from this body at death. If one practises such steady remembrance through regular daily Sadhana. The secret of reaching the Divine Being and thus freeing oneself forever from birth and death and the pains and sufferings of this earth-life. Arjuna Uvaacha: Kim tadbrahma kim adhyaatmam kim karma purushottama. Arjuna said: 1. Who and how is Adhiyajna here in this body. Adhibhootam cha kim proktam adhidaivam kimuchyate. he will go beyond darkness and bondage and attain the realm of eternal blessedness. We are a spiritual being residing in this body and supported by the Silent Witness within—the Supreme Antaryamin. in all places and even amidst one’s daily activities. including even our own self (individual soul). So he proceeds to question the Lord. beyond these names and forms. Arjuna does not understand their meaning. The Blessed Lord said: 66 . Worship. The mind should be centred within upon God. and constantly meditating. His essential nature is called Self-knowledge. one goes to the Supreme Person. leaving the body. Mayyarpitamanobuddhir maamevaishyasyasamshayam. With the mind not moving towards any other thing. Brahman is the Imperishable. made steadfast by the method of habitual meditation. Adhiyajno’hamevaatra dehe dehabhritaam vara. the Resplendent. 7. Tam tamevaiti kaunteya sadaa tadbhaavabhaavitah. thou shalt doubtless come to Me alone. to that being only does he go. Adhibhuta (knowledge of the elements) pertains to My perishable Nature. the offering (to the gods) which causes existence and manifestation of beings and which also sustains them is called action. he attains My Being. goes forth remembering Me alone at the time of death. there is no doubt about this. thinking of any being. Adhibhootam ksharo bhaavah purushashchaadhidaivatam. 8.BHAGAVAD GITA 3. Sarvasya dhaataaram achintyaroopam Aadityavarnam tamasah parastaat. 67 . Whosoever at the end leaves the body. the Supreme. 6. 5. Paramam purusham divyam yaati paarthaanuchintayan. I alone am the Adhiyajna here in this body. 4. And whosoever. at all times remember Me only and fight. because of his constant thought of that being! COMMENTARY: The most prominent thought of one’s life occupies the mind at the time of death. O best among the embodied (men)! Antakaale cha maameva smaran muktwaa kalevaram. and the Purusha or soul is the Adhidaiva. Abhyaasayogayuktena chetasaa naanyagaaminaa. Therefore. O son of Kunti (Arjuna). With mind and intellect fixed (or absorbed) in Me. O Arjuna! Kavim puraanamanushaasitaaram Anoraneeyaamsam anusmaredyah. It determines the nature of the body to be attained in the next birth. Yah prayaati sa madbhaavam yaati naastyatra samshayah. Yam yam vaapi smaran bhaavam tyajatyante kalevaram. Tasmaat sarveshu kaaleshu maamanusmara yudhya cha. Sarvadwaaraani samyamya mano hridi nirudhya cha. Tasyaaham sulabhah paartha nityayuktasya yoginah. endowed with devotion and by the power of Yoga. Whosoever meditates on the Omniscient. Yadaksharam vedavido vadanti Vishanti yadyatayo veetaraagaah. 13. the ruler (of the whole world). Bhruvormadhye praanamaaveshya samyak Sa tam param purusham upaiti divyam. the Ancient. that which the self-controlled (ascetics) and passion-free enter. Having closed all the gates. 68 . Omityekaaksharam brahma vyaaharan maamanusmaran. Uttering the monosyllable Om—the Brahman—remembering Me always. confined the mind in the heart and fixed the life-breath in the head. the supporter of all. fixing the whole life-breath in the middle of the two eyebrows. he who departs thus. he reaches that resplendent Supreme Person. O Partha (Arjuna)! COMMENTARY: Constantly remembering the Lord throughout one’s life is the easiest way of attaining Him. 11. that desiring which celibacy is practised—that goal I will declare to thee in brief. attains to the supreme goal.THE YOGA OF THE IMPERISHABLE BRAHMAN 9. Naapnuvanti mahaatmaanah samsiddhim paramaam gataah. engaged in the practice of concentration. with unshaken mind. leaving the body. Maamupetya punarjanma duhkhaalayamashaashwatam. Prayaanakaale manasaachalena Bhaktyaa yukto yogabalena chaiva. Ananyachetaah satatam yo maam smarati nityashah. minuter than an atom. Yah prayaati tyajan deham sa yaati paramaam gatim. 12. Moordhnyaadhaayaatmanah praanamaasthito yogadhaaranaam. I am easily attainable by that ever-steadfast Yogi who constantly and daily remembers Me (for a long time). Yadicchanto brahmacharyam charanti Tatte padam samgrahena pravakshye. 14. not thinking of anything else (with a single or one-pointed mind). effulgent like the sun and beyond the darkness of ignorance. 10. of inconceivable form. That which is declared imperishable by those who know the Vedas. At the time of death. Maamupetya tu kaunteya punarjanma na vidyate. and the night. Those who know the day of Brahma. are subject to return again. (All) the worlds. Raatryaagame praleeyante tatraivaavyaktasamjnake. But verily there exists. It is not destroyed when all beings from Brahma down to a blade of grass are destroyed. Coming of the “night” is the commencement of dissolution. which is also of a thousand Yugas’ duration. Avyaktaadvyaktayah sarvaah prabhavantyaharaagame. COMMENTARY: Coming of the “day’ is the commencement of creation. Having attained Me these great souls do not again take birth (here). 17. Yam praapya na nivartante taddhaama paramam mama. 20. Yah sa sarveshu bhooteshu nashyatsu na vinashyati.BHAGAVAD GITA 15. 69 . helplessly. O son of Kunti. O Arjuna! But he who reaches Me. (into the unmanifested) at the coming of the night. 18. including the world of Brahma. is dissolved. has no rebirth! Sahasrayugaparyantam aharyad brahmano viduh. COMMENTARY: Another unmanifested Eternal refers to Para Brahman. and which is of quite a different nature. Raatrim yugasahasraantaam te’horaatravido janaah. Avyakto’kshara ityuktastamaahuh paramaam gatim. higher than the unmanifested. Aabrahmabhuvanaallokaah punaraavartino’rjuna. which is the place of pain and is non-eternal. O Arjuna. 16. Raatryaagame’vashah paartha prabhavatyaharaagame. they have reached the highest perfection (liberation). This same multitude of beings. born again and again. From the unmanifested all the manifested (worlds) proceed at the coming of the “day”. It is superior to Hiranyagarbha (the creative Intelligence) and the unmanifested Nature because It is their cause. which is of a duration of a thousand Yugas (ages). at the coming of the “night” they dissolve verily into that alone which is called the unmanifested. Bhootagraamah sa evaayam bhootwaa bhootwaa praleeyate. 19. and comes forth at the coming of the day! Parastasmaat tu bhaavo’nyo’vyakto’vyaktaatsanaatanah. they know day and night. another unmanifested Eternal who is not destroyed when all beings are destroyed. which is distinct from the unmanifested (primordial Nature). 24. night-time. Yatra kaale twanaavrittim aavrittim chaiva yoginah. The dark path is of the manes taken by those who perform sacrifices or charitable acts with the expectation of rewards. Purushah sa parah paartha bhaktyaa labhyastwananyayaa. O Arjuna. Dhoomo raatristathaa krishnah shanmaasaa dakshinaayanam. the dark fortnight or the six months of the southern path of the sun (the southern solstice). That is My highest abode (place or state). Tasmaat sarveshu kaaleshu yogayukto bhavaarjuna. O chief of the Bharatas. COMMENTARY: The bright path is the path to the gods taken by devotees. daytime. at all times be steadfast in Yoga. Attaining to the lunar light by smoke. O Arjuna. What is called the Unmanifested and the Imperishable. Tatra prayaataa gacchanti brahma brahmavido janaah. Naite sritee paartha jaanan yogee muhyati kashchana. Knowing these paths. Tatra chaandramasam jyotir yogee praapya nivartate. the bright fortnight. the Yogi returns. 23. is attainable by unswerving devotion to Him alone within whom all beings dwell and by whom all this is pervaded. Ekayaa yaatyanaavrittim anyayaa’vartate punah. the six months of the northern path of the sun (northern solstice)—departing then (by these).THE YOGA OF THE IMPERISHABLE BRAHMAN 21. That highest Purusha. no Yogi is deluded! Therefore. The bright and the dark paths of the world are verily thought to be eternal. Prayaataa yaanti tam kaalam vakshyaami bharatarshabha. Now I will tell thee. men who know Brahman go to Brahman. Fire. Shuklakrishne gatee hyete jagatah shaashwate mate. and by the other (the dark path) he returns. 25. 22. by the one (the bright path) a person goes not to return again. That they say is the highest goal (path). the times departing at which the Yogis will return or not return! Agnijyotirahah shuklah shanmaasaa uttaraayanam. Vedeshu yajneshu tapahsu chaiva Daaneshu yat punyaphalam pradishtam: 70 . 27. 26. Yasyaantahsthaani bhootaani yena sarvamidam tatam. They who reach It do not return (to this cycle of births and deaths). light. BHAGAVAD GITA 71 THE YOGA OF THE KINGLY SCIENCE & THE KINGLY SECRET. 72 BHAGAVAD GITA! 73 the friend. Jnaanayajnena chaapyanye yajanto maamupaasate. Others also.and Yajur Vedas. I am the medicinal herb and all the plants. worshipping Me by sacrifices. sacrificing with the wisdom-sacrifice.THE YOGA OF THE KINGLY SCIENCE & THE KINGLY SECRET Satatam keertayanto maam yatantashcha dridhavrataah. Te punyamaasaadya surendralokaMashnanti divyaan divi devabhogaan. Amritam chaiva mrityushcha sadasacchaahamarjuna. the foundation. O Arjuna! Traividyaa maam somapaah pootapaapaa Yajnairishtwaa swargatim praarthayante. striving. 14. the all-faced. they worship Me with devotion. Gatirbhartaa prabhuh saakshee nivaasah sharanam suhrit. Tapaamyahamaham varsham nigrihnaamyutsrijaami cha. (As the sun) I give heat. the mother. prostrating before Me. Pitaahamasya jagato maataa dhaataa pitaamahah. the (one) thing to be known. ever steadfast. I am the Kratu. the shelter. the drinkers of Soma. existence and non-existence. I am the Yajna. Always glorifying Me. I am also the ghee or melted butter. the abode. 74 . 19. 15. 16. the Lord. the dissolution. I am the Mantra. the support. the Sama. the witness. Prabhavah pralayah sthaanam nidhaanam beejamavyayam. they reach the holy world of the Lord of the gods and enjoy in heaven the divine pleasures of the gods. firm in vows. I am the fire. as one. and also the Rig-. and the grandfather. as distinct. Vedyam pavitramonkaara riksaama yajureva cha. the dispenser of the fruits of actions. I am the offering (food) to the manes. 17. I am the oblation. Ekatwena prithaktwena bahudhaa vishwatomukham. the purifier. I am the goal. Aham kraturaham yajnah swadhaa’hamahamaushadham. and as manifold. I am the father of this world. the origin. worship Me. 18. pray for the way to heaven. purified of all sins. 20. I withhold and send forth the rain. Namasyantashcha maam bhaktyaa nityayuktaa upaasate. Mantro’hamahamevaajyam ahamagniraham hutam. I am immortality and also death. The knowers of the three Vedas. the sacred monosyllable (Om). the treasure-house and the imperishable seed. endowed with faith. 22. COMMENTARY: When their accumulated merits are exhausted. they attain to the state of going and returning. Even those devotees who. to the manes go the ancestor-worshippers. 75 . thus abiding by the injunctions of the three (Vedas) and desiring (objects of) desires. Whoever offers Me with devotion and a pure mind (heart). of those ever united. Ananyaashchintayanto maam ye janaah paryupaasate. O Arjuna. worship Me only. 25. enter the world of mortals when their merits are exhausted.BHAGAVAD GITA Te tam bhuktwaa swargalokam vishaalam Ksheene punye martyalokam vishanti. Ye’pyanyadevataa bhaktaa yajante shraddhayaa’nvitaah. worship other gods. Na tu maamabhijaananti tattwenaatashchyavanti te. 26. I secure what is not already possessed and preserve what they already possess. a leaf. having enjoyed the vast heaven. They have no independence. 21. They. Patram pushpam phalam toyam yo me bhaktyaa prayacchati. Yattapasyasi kaunteya tatkurushva madarpanam. (For) I alone am the enjoyer and also the Lord of all sacrifices. a flower. The worshippers of the gods go to them. Evam trayeedharmamanuprapannaa Gataagatam kaamakaamaa labhante. but they do not know Me in essence (in reality). Te’pi maameva kaunteya yajantyavidhipoorvakam. 24. they come to this world again. My devotees come to Me. thinking of no other. to the Deities who preside over the elements go their worshippers. Teshaam nityaabhiyuktaanaam yogakshemam vahaamyaham. Tadaham bhaktyupahritamashnaami prayataatmanah. Bhutaani yaanti bhutejyaa yaanti madyaajino’pi maam. Yaanti devavrataa devaan pitreen yaanti pitrivrataah. but by the wrong method! Aham hi sarvayajnaanaam bhoktaa cha prabhureva cha. and hence they fall (return to this mortal world). To those men who worship Me alone. a fruit or a little water—I accept (this offering). Yatkaroshi yadashnaasi yajjuhoshi dadaasi yat. 23. Thus shalt thou be freed from the bonds of actions yielding good and evil fruits. for he has rightly resolved. to Me there is none hateful or dear. Kaunteya pratijaaneehi na me bhaktah pranashyati. thou shalt come unto Me. sacrifice unto Me. Api chet suduraachaaro bhajate maamananyabhaak. 76 . The same am I to all beings. O Arjuna. 34. 29. Maamevaishyasi yuktwaivamaatmaanam matparaayanah. 33. with the mind steadfast in the Yoga of renunciation. taking refuge in Me. whatever thou practiseth as austerity. he too should indeed be regarded as righteous. whatever thou offerest in sacrifice. Fix thy mind on Me. may be of sinful birth—women. O Arjuna. For. Manmanaa bhava madbhakto madyaajee maam namaskuru. Vaisyas as well as Sudras—attain the Supreme Goal! Kim punarbraahmanaah punyaa bhaktaa raajarshayastathaa. with devotion to none else. Saadhureva sa mantavyah samyagvyavasito hi sah. do it as an offering unto Me! Shubhaashubhaphalairevam mokshyase karmabandhanaih. O Arjuna. How much more easily then the holy Brahmins and devoted royal saints (attain the goal). 30. know thou for certain that My devotee is never destroyed! Maam hi paartha vyapaashritya ye’pi syuh paapayonayah. do thou worship Me.THE YOGA OF THE KINGLY SCIENCE & THE KINGLY SECRET 27. Soon he becomes righteous and attains to eternal peace. Sannyaasayogayuktaatmaa vimukto maamupaishyasi. Anityamasukham lokam imam praapya bhajaswa maam. bow down to Me. whatever thou givest. Ye bhajanti tu maam bhaktyaa mayi te teshu chaapyaham. whatever thou eatest. be devoted to Me. having thus united thy whole self with Me. but those who worship Me with devotion are in Me and I am also in them. 31. 28. Kshipram bhavati dharmaatmaa shashwacchaantim nigacchati. Whatever thou doest. having obtained this impermanent and unhappy world. thou shalt verily come unto Me. taking Me as the Supreme Goal. Striyo vaishyaastathaa shoodraaste’pi yaanti paraam gatim. Even if the most sinful worships Me. and liberated. Samo’ham sarvabhooteshu na me dweshyo’sti na priyah. who. 32. they also. The Blessed Lord said: 77 . truth. the scripture of Yoga. the dialogue between Sri Krishna and Arjuna. contentment. Then there will be a marvellous transformation. and how He upholds everything.. All sorrows and pains will vanish. In short. Sri Bhagavaan Uvaacha: Bhooya eva mahaabaaho shrinu me paramam vachah.. Yatte’ham preeyamaanaaya vakshyaami hitakaamyayaa. All these qualities—wisdom.—originate from Him. He will have the vision of God everywhere. The Lord describes His Divine glories. Arjuna accepts the descent of the Supreme in a human form. the science of the Eternal. The true devotees of the Lord are wholly absorbed in Him. His mind will be one with Him. etc. the discrimination that leads them from the unreal to the Real. Krishna emphatically declares that ignorance is destroyed and knowledge gained through Divine Grace alone. the Lord is the Almighty Power that creates. bringing within the range of Arjuna’s comprehension His limitless manifestations. He will for ever have his life and being in the Lord alone. They have completely surrendered to Him and through single-minded devotion they are granted the power of discrimination. He goes on to describe the various qualities that beings manifest according to their Karmas.BHAGAVAD GITA COMMENTARY: The whole being of a man should be surrendered to the Lord without reservation. sustains and destroys everything. but wishes to know from the Lord Himself His Cosmic powers by means of which He controls the diverse forces of the universe. and so He Himself comes forward to give him instructions without any request having been made by Arjuna. forgiveness. Ahamaadirhi devaanaam maharsheenaam cha sarvashah. Maharshayah sapta poorve chatwaaro manavastathaa. the ancient four and also the Manus. Madbhaavaa maanasaa jaataa yeshaam loka imaah prajaah. Etaam vibhootim yogam cha mama yo vetti tattwatah. O mighty-armed Arjuna. Sukham duhkham bhavo’bhaavo bhayam chaabhayameva cha. he is liberated from all sins. is undeluded. COMMENTARY: As the Supreme Being is the cause of all the worlds. austerity. 6. from them are these creatures born in this world. He is unborn. birth or existence. Na me viduh suraganaah prabhavam na maharshayah. Buddhir jnaanamasammohah kshamaa satyam damah shamah. He is the great Lord of all the worlds. He is beginningless. pain. beneficence. truth. equanimity. as the great Lord of the worlds. for. Neither the hosts of the gods nor the great sages know My origin. wisdom. 3. The seven great sages. for thy welfare! COMMENTARY: The all-compassionate Lord in His mercy wants to encourage Arjuna and cheer him up. so there is no source for His own existence. in every way I am the source of all the gods and the great sages. 78 . possessed of powers like Me (on account of their minds being fixed on Me). Ahimsaa samataa tushtistapo daanam yasho’yashah. ill-fame—(these) different kinds of qualities of beings arise from Me alone. among mortals. Bhavanti bhaavaa bhootaanaam matta eva prithagvidhaah. happiness. As He is the source of all the gods and the great sages. As He is beginningless. Asammoodhah sa martyeshu sarvapaapaih pramuchyate. he. calmness. Again.THE YOGA OF THE DIVINE GLORIES 1. fame. death or non-existence. were born of (My) mind. self-restraint. Intellect. 2. listen to My supreme word which I shall declare to thee who art beloved. So’vikampena yogena yujyate naatra samshayah. Yo maamajamanaadim cha vetti lokamaheshwaram. non-delusion. He who knows Me as unborn and beginningless. contentment. 5. Non-injury. fear and also fearlessness. 4. 11. the eternal. With their minds and lives entirely absorbed in Me. Kathayantashcha maam nityam tushyanti cha ramanti cha. the primeval God. Iti matwaa bhajante maam budhaa bhaavasamanvitaah. Arjuna said: 12. unborn and omnipresent. Out of mere compassion for them. Dadaami buddhiyogam tam yena maamupayaanti te. becomes established in the unshakeable Yoga. Purusham shaashvatam divyam aadidevamajam vibhum. the supreme abode (or the supreme light). Arjuna Uvaacha: Param brahma param dhaama pavitram paramam bhavaan. He who in truth knows these manifold manifestations of My Being and (this) Yoga-power of Mine. enlightening each other and always speaking of Me. Aham sarvasya prabhavo mattah sarvam pravartate. the supreme purifier. I am the source of all. obtain the Divine Grace. the wise. Devala and Vyasa. I. who are ever harmonious and self-abiding. 13. 8. as also the divine sage Narada. who adore Him with intense love. Asito devalo vyaasah swayam chaiva braveeshi me. understanding thus. worshipping Me with love. To them who are ever steadfast. Teshaam evaanukampaartham aham ajnaanajam tamah. destroy the darkness born of ignorance by the luminous lamp of knowledge. and now Thou Thyself sayest so to me. endowed with meditation. 9. Macchittaa madgatapraanaa bodhayantah parasparam. they are satisfied and delighted. I give the Yoga of discrimination by which they come to Me. 79 . so also Asita. 10. All the sages have thus declared Thee. Teshaam satatayuktaanaam bhajataam preetipoorvakam. COMMENTARY: The devotees who have dedicated themselves to the Lord. dwelling within their Self. from Me everything evolves. Thou art the Supreme Brahman. there is no doubt about it. worship Me.BHAGAVAD GITA 7. divine Person. who are ever devout. Aahustwaam rishayah sarve devarshirnaaradastathaa. Naashayaamyaatmabhaavastho jnaanadeepena bhaaswataa. ) Katham vidyaamaham yogimstwaam sadaa parichintayan.. seated in the hearts of all beings! I am the beginning. 20. of Thy divine glories by which Thou existeth. 18. (None else can do so. art Thou to be thought of by me? Vistarenaatmano yogam vibhootim cha janaardana. I believe all this that Thou sayest to me as true. the middle and also the end of all beings. Bhooyah kathaya triptirhi shrinvato naasti me’mritam. know Thee. O source and Lord of beings. Verily. Thou shouldst indeed tell. O Arjuna! There is no end to their detailed description. 14. Bhootabhaavana bhootesha devadeva jagatpate. COMMENTARY: The Lord’s divine glories are illimitable. Na hi te bhagavan vyaktim vidurdevaa na daanavaah. of Thy Yogic power and glory. 17. O blessed Lord. Ahamaadishcha madhyam cha bhootaanaamanta eva cha. Praadhaanyatah kurushreshtha naastyanto vistarasya me. 15. pervading all these worlds. O ruler of the world! Vaktum arhasyasheshena divyaa hyaatmavibhootayah. without reserve. Ahamaatmaa gudaakesha sarvabhootaashayasthitah. O Krishna. neither the gods nor the demons know Thy manifestation (origin)! Swayamevaatmanaatmaanam vettha twam purushottama. The Blessed Lord said: 19. O God of gods. O Yogin? In what aspects or things. now I will declare to thee My divine glories in their prominence. Yaabhir vibhootibhir lokaanimaamstwam vyaapya tishthasi. Thou Thyself knowest Thyself by Thyself. Keshu keshu cha bhaaveshu chintyo’si bhagavanmayaa. O blessed Lord.THE YOGA OF THE DIVINE GLORIES Sarvametadritam manye yanmaam vadasi keshava. 80 . 16. Very well. How shall I. O Supreme Person. Tell me again in detail. I am the Self. O Krishna! Verily. ever meditating. O Gudakesha. and I am intelligence among living beings. I am Marichi among the (seven or forty-nine) Maruts. among the Yakshas and Rakshasas. COMMENTARY: Repetition of the Mantra is regarded as the best of all Yajnas or sacrifices. know Me to be the chief. among Gandharvas I am Chitraratha. 25. Vasoonaam paavakashchaasmi meruh shikharinaamaham. among the household priests (of kings). among immovable things the Himalayas I am. Gandharvaanaam chitrarathah siddhaanaam kapilo munih. There is no loss or injury in this Yajna. 22. and among men. among words I am the monosyllable Om. among the senses I am the mind. he attains salvation by Japa alone”. Know Me as Ucchaisravas. among lakes I am the ocean! Maharsheenaam bhriguraham giraamasmyekamaksharam. 27. 26. I am Vasava among the gods. Indriyaanaam manashchaasmi bhootaanaamasmi chetanaa. O Arjuna. Yajnaanaam japayajno’smi sthaavaraanaam himaalayah. among the Rudras I am Shankara. Rudraanaam shankarashchaasmi vittesho yaksharakshasaam. Senaaneenaamaham skandah sarasaamasmi saagarah. Ashwatthah sarvavrikshaanaam devarsheenaam cha naaradah. among lordly elephants (I am) the Airavata. among the army generals I am Skanda. Among the Vedas I am the Sama Veda. among the luminaries. and among the (seven) mountains I am the Meru. the king. Brihaspati. Airaavatam gajendraanaam naraanaam cha naraadhipam. the Lord of wealth (Kubera). Ucchaihshravasamashwaanaam viddhi maamamritodbhavam. Purodhasaam cha mukhyam maam viddhipaartha brihaspatim. Among the (twelve) Adityas. among the Vasus I am Pavaka (fire). born of nectar among horses. among the perfected the sage Kapila. Mareechirmarutaamasmi nakshatraanaamaham shashee. among stars the moon am I. I am Vishnu. among sacrifices I am the sacrifice of silent repetition. among the divine sages I am Narada. And. Among the great sages I am Bhrigu. 81 . Vedaanaam saamavedo’smi devaanaam asmi vaasavah.BHAGAVAD GITA Aadityaanaamaham vishnur jyotishaam raviramshumaan. Manu says: “Whatever else the Brahmana may or may not do. the radiant sun. 23. And. 24. 21. Among the trees (I am) the peepul. I am Prahlad among the demons. Among the letters of the alphabet. And I am all-devouring death. Pavanah pavataamasmi raamah shastrabhritaamaham. 34. Prajanashchaasmi kandarpah sarpaanaamasmi vaasukih. prosperity. I am the dispenser (of the fruits of actions). 29. among serpents I am Vasuki. Aksharaanaamakaaro’smi dwandwah saamaasikasya cha. speech. among beasts I am their king. 30. among feminine qualities (I am) fame. 28. I am Ananta among the Nagas. Rama among the warriors am I. firmness and forgiveness. Prahlaadashchaasmi daityaanaam kaalah kalayataamaham. among cows I am the wish-fulfilling cow called Surabhi. intelligence. 82 . having faces in all directions. Pitreenaamaryamaa chaasmi yamah samyamataamaham. and Garuda among birds. 32. I am the progenitor. Brihatsaama tathaa saamnaam gaayatree cchandasaamaham. Mrigaanaam cha mrigendro’ham vainateyashcha pakshinaam. Maasaanaam maargasheersho’hamritoonaam kusumaakarah. Mrityuh sarvaharashchaaham udbhavashcha bhavishyataam. among the reckoners I am time. I am verily the inexhaustible or everlasting time. Adhyaatmavidyaa vidyaanaam vaadah pravadataamaham. memory. Ahamevaakshayah kaalo dhaataaham vishwatomukhah. the letter “A” I am. among the streams I am the Ganga. Among weapons I am the thunderbolt. I am Varuna among water-Deities. and prosperity of those who are to be prosperous. the god of love. the middle and also the end. I am Yama among the governors. Among the purifiers (or the speeders) I am the wind. and the dual among the compounds. Jhashaanaam makarashchaasmi srotasaamasmi jaahnavee. and I am logic among controversialists. the lion. And.THE YOGA OF THE DIVINE GLORIES Aayudhaanaamaham vajram dhenoonaamasmi kaamadhuk. Aryaman among the manes I am. 33. O Arjuna! Among the sciences I am the science of the Self. Anantashchaasmi naagaanaam varuno yaadasaamaham. 31. Among creations I am the beginning. Sargaanaamaadirantashcha madhyam chaivaaham arjuna. among the fishes I am the shark. Keertih shreervaakcha naareenaam smritirmedhaadhritih kshamaa. Tattadevaavagaccha twam mama tejom’shasambhavam. I am victory. O Arjuna. I am gambling. Among the punishers I am the sceptre. I am the Self of everything. COMMENTARY: Of the various methods of defrauding others. Dyootam cchalayataamasmi tejastejaswinaamaham. I am the splendour of the splendid. among seasons (I am) the flowery season. prosperous or powerful. among the months I am Margasirsa. Among the hymns also I am the Brihatsaman. among sages I am Vyasa. Dando damayataamasmi neetirasmi jigeeshataam. that know thou to be a manifestation of a part of My splendour. that can exist without Me. 37. And whatever is the seed of all beings. I am victory in the victorious. among metres Gayatri am I. I am effort in those who make that effort. There is no end to My divine glories. Maunam chaivaasmi guhyaanaam jnaanam jnaanavataamaham. 83 . Esha tooddeshatah prokto vibhootervistaro mayaa. Everything is of My nature. knowledge among knowers I am. 41. among poets I am Usana. Yachchaapi sarvabhootaanaam beejam tadahamarjuna. the poet. and also among secrets I am silence. Among Vrishnis I am Vasudeva. such as dice-play. 40. among those who seek victory I am statesmanship. COMMENTARY: I am the primeval seed from which all creation has come into existence. I am determination (of those who are determined). I am power in the powerful. whether moving or unmoving. I am the gambling of the fraudulent. I am the soul of everything. Muneenaamapyaham vyaasah kaveenaamushanaa kavih. that also am I. Jayo’smi vyavasaayo’smi sattwam sattwavataamaham. Nothing can exist without Me. O Arjuna! There is no being. 39.BHAGAVAD GITA 35. Whatever being there is that is glorious. Naanto’sti mama divyaanaam vibhooteenaam parantapa. but this is a brief statement by Me of the particulars of My divine glories! Yadyad vibhootimat sattwam shreemadoorjitameva vaa. 38. I am the seed of everything. I am the goodness of the good. Vrishneenaam vaasudevo’smi paandavaanaam dhananjayah. Gambling is My manifestation. 36. among the Pandavas I am Arjuna. Na tadasti vinaa yatsyaanmayaa bhootam charaacharam. Krishna reiterates that this vision cannot be had through any amount of austerities. His Will alone prevails in all things and actions. supporting this whole world by one part of Myself. study. He begs the Lord to assume once more His usual form.THE YOGA OF THE DIVINE GLORIES Athavaa bahunaitena kim jnaatena tavaarjuna. Arjuna Uvaacha: Madanugrahaaya paramam guhyamadhyaatmasamjnitam. Vishtabhyaahamidam kritsnamekaamshena sthito jagat. he being only an apparent cause of the destruction of his enemies. 42. But of what avail to thee is the knowledge of all these details. Supreme devotion is the only means by which one can have access to His grand vision. the science of the Eternal. Yattwayoktam vachastena moho’yam vigato mama. Arjuna further sees that the great cosmic drama is set in motion and controlled by the all-mighty power of the Lord. The Lord exhorts him to fight. Krishna grants him the divine sight by means of which Arjuna beholds the Lord as the vast Cosmic Manifestation. both good and bad. sacrifices or philanthrophic acts. the scripture of Yoga. In every direction Arjuna sees the Lord as the entire universe. 84 . All the created worlds. he is now ready to behold the Cosmic Vision. creatures and things stand revealed as the one gigantic body of the Lord. The vision is at once all-comprehensive and simultaneous. beings. Arjuna is unable to bear the pressure of the sudden expansion of consciousness and is filled with fear... gods. the dialogue between Sri Krishna and Arjuna. O Arjuna? I exist. My forms by the hundreds and thousands. Behold. do Thou. O lotus-eyed Lord. thinkest it possible for me to see it. behold many wonders never seen before. and also Thy inexhaustible greatness! Evametadyathaattha twamaatmaanam parameshwara. 7. the Vasus. Bhavaapyayau hi bhootaanaam shrutau vistarasho mayaa. Arjuna has an intense longing to have the wonderful Cosmic Vision. Now behold. 4.BHAGAVAD GITA Arjuna said: 1. in this. Drashtumicchaami te roopamaishwaram purushottama. Yogeshwara tato me twam darshayaatmaanamavyayam. O Arjuna. Bahoonyadrishtapoorvaani pashyaashcharyaani bhaarata. COMMENTARY: After hearing the glories of the Lord. Naanaavidhaani divyaani naanaavarnaakriteeni cha. then. O Supreme Person. the Rudras. Mama dehe gudaakesha yachchaanyad drashtumicchasi. I wish to see Thy Divine Form! Manyase yadi tacchakyam mayaa drashtumiti prabho. which Thou hast spoken out of compassion towards me my delusion is gone. 6. divine and of various colours and shapes! Pashyaadityaan vasoon rudraan ashwinau marutastathaa. O Arjuna! Ihaikastham jagatkritsnam pashyaadya sacharaacharam. 3. 2. Twattah kamalapatraaksha maahaatmyamapi chaavyayam. My body. the two Asvins and also the Maruts. of different sorts. O Arjuna. If Thou. O Lord. (Now). Behold the Adityas. The Blessed Lord said: 5. as Thou hast thus described Thyself. O Lord of the Yogis. show me Thy imperishable Self! Sri Bhagavaan Uvaacha: Pashya me paartha roopaani shatasho’tha sahasrashah. The origin and the destruction of beings verily have been heard by me in detail from Thee. By this explanation of the highest secret concerning the Self. the whole universe centred in the one—including the moving and the unmoving—and whatever else thou desirest to see! 85 . O Supreme Lord. with its many groups. Pranamya shirasaa devam kritaanjalirabhaashata. I give thee the divine eye. 86 . endless. Hari (Krishna). Divi sooryasahasrasya bhavedyugapadutthitaa. behold My lordly Yoga. that would be the splendour of that mighty Being (great soul). 10. If the splendour of a thousand suns were to blaze out at once (simultaneously) in the sky. It should not be confused with seeing through the physical eye or through the mind. Having thus spoken. Sarvaashcharyamayam devam anantam vishwatomukham. Arjuna then saw the whole universe resting in the one. the great Lord of Yoga. There. showed to Arjuna His supreme form as the Lord! Anekavaktra nayanam anekaadbhuta darshanam. thine own eyes. in the body of the God of gods. Divyam dadaami te chakshuh pashya me yogamaishwaram. Anekadivyaabharanam divyaanekodyataayudham. Wearing divine garlands and apparel. anointed with divine unguents. Sanjaya said: 9. 8. Divyamaalyaambaradharam divyagandhaanulepanam. It is an inner divine experience attained through intense devotion and concentration. with numerous wonderful sights. But thou art not able to behold Me with these. Tatraikastham jagatkritsnam pravibhaktamanekadhaa. with numerous divine weapons uplifted (such a form He showed). Sanjaya Uvaacha: Evamuktwaa tato raajan mahaayogeshwaro harih. COMMENTARY: No fleshy eye can behold Me in My Cosmic Form. One can see Me only through the eye of intuition or the divine eye. 13. Apashyaddevadevasya shareere paandavastadaa. resplendent (Being). Darshayaamaasa paarthaaya paramam roopamaishwaram. With numerous mouths and eyes. with numerous divine ornaments. with faces on all sides. 12. Tatah sa vismayaavishto hrishtaromaa dhananjayah. Yadi bhaah sadrishee saa syaadbhaasastasya mahaatmanah. 11. the all-wonderful.THE YOGA OF THE VISION OF THE COSMIC FORM Na tu maam shakyase drashtum anenaiva swachakshushaa. O king. Arjuna. 17. filled with wonder and with hair standing on end. Thou art the ancient Person. Arjuna Uvaacha: Pashyaami devaamstava deva dehe Sarvaamstathaa bhootavisheshasanghaan. very hard to look at. 87 . 18. Naantam na madhyam na punastavaadim Pashyaami vishweshwara vishwaroopa. Thou art the imperishable protector of the eternal Dharma. I see Thee of boundless form on every side. Twamavyayah shaashwatadharmagoptaa Sanaatanastwam purusho mato me. Thou art the Imperishable.BHAGAVAD GITA 14. Thou art the great treasure-house of this universe. with many arms. Pashyaami twaam deeptahutaashavaktram Swatejasaa vishwamidam tapantam. worthy of being known. blazing all round like burning fire and the sun. Pashyaami twaam durnireekshyam samantaad Deeptaanalaarkadyutimaprameyam. Then. stomachs. O Cosmic Form! Kireetinam gadinam chakrinam cha. I deem. O Lord of the universe. Anaadimadhyaantamanantaveeryam Anantabaahum shashisooryanetram. a mass of radiance shining everywhere. O God. I see Thee with the diadem. Arjuna said: 15. neither the end nor the middle nor also the beginning do I see. the Lord. all the sages and the celestial serpents! Anekabaahoodaravaktranetram Pashyaami twaam sarvato’nantaroopam. Tejoraashim sarvato deeptimantam. seated on the lotus. and immeasurable. the club and the discus. the Supreme Being. I behold all the gods. Brahmaanameesham kamalaasanasthaMrisheemshcha sarvaanuragaamshcha divyaan. in Thy body. Twamaksharam paramam veditavyam Twamasya vishwasya param nidhaanam. 16. Brahma. bowed down his head to the Lord and spoke with joined palms. mouths and eyes. and hosts of various classes of beings. Thy wonderful and terrible form. 22. the manes and hosts of celestial singers. Drishtwaa hi twaam pravyathitaantaraatmaa Dhritim na vindaami shamam cha vishno. Vasus. Gandharvayakshaasurasiddhasanghaa Veekshante twaam vismitaashchaiva sarve. 20. infinite in power. the three worlds are trembling with fear. demons and the perfected ones. Sadhyas. the two Asvins. and fearful with many teeth. thighs and feet. Dyaavaaprithivyoridamantaram hi Vyaaptam twayaikena dishashcha sarvaah. some extol Thee in fear with joined palms: “May it be well. 88 . Having beheld Thy immeasurable form with many mouths and eyes. middle or end. into Thee enter these hosts of gods. bands of great sages and perfected ones praise Thee with complete hymns. the burning fire Thy mouth. Bahoodaram bahudamshtraakaraalam Drishtwaa lokaah pravyathitaastathaa’ham. The Rudras.THE YOGA OF THE VISION OF THE COSMIC FORM 19. 23. Swasteetyuktwaa maharshisiddhasanghaah Stuvanti twaam stutibhih pushkalaabhih. heating the entire universe with Thy radiance. Drishtwaa’dbhutam roopamugram tavedam Lokatrayam pravyathitam mahaatman. Verily. The space between the earth and the heaven and all the quarters are filled by Thee alone. with many stomachs. of endless arms. Rudraadityaa vasavo ye cha saadhyaa Vishwe’shvinau marutashchoshmapaashcha.” Saying thus. I see Thee without beginning. Yakshas. Adityas. Maruts. with many arms. the sun and the moon being Thy eyes. 21. Roopam mahat te bahuvaktranetram Mahaabaaho bahubaahoorupaadam. O great-souled Being! Amee hi twaam surasanghaah vishanti Kechid bheetaah praanjalayo grinanti. O mighty-armed. having seen this. Visvedevas. are all looking at Thee in great astonishment. the worlds are terrified and so am I! Nabhahsprisham deeptamanekavarnam Vyaattaananam deeptavishaalanetram. fiery eyes. shining in many colours. Bhishma. On seeing Thee (the Cosmic Form) touching the sky. Yathaa nadeenaam bahavo’mbuvegaah Samudramevaabhimukhaah dravanti. 27. O Lord of the gods! O abode of the universe! Amee cha twaam dhritaraashtrasya putraah Sarve sahaivaavanipaalasanghaih. Having seen Thy mouths. so why should he worry about the inevitable. Drona and Karna. COMMENTARY: Arjuna sees all the warriors. 26. Verily. blazing like the fires of cosmic dissolution.BHAGAVAD GITA 24. I know not the four quarters. All the sons of Dhritarashtra with the hosts of kings of the earth. Disho na jaane na labhe cha sharma Praseeda devesha jagannivaasa. 89 . Bheeshmo dronah sootaputrastathaa’sau Sahaasmadeeyairapi yodhamukhyaih. He knows now that the Lord has already destroyed them. Have mercy. I am terrified at heart and find neither courage nor peace. Yathaa pradeeptam jwalanam patangaa Vishanti naashaaya samriddhavegaah. with the chief among all our warriors. O Vishnu! Damshtraakaraalaani cha te mukhaani Drishtwaiva kaalaanalasannibhaani. even so these heroes of the world of men enter Thy flaming mouths. with their heads crushed to powder. with mouths wide open. 28. Kechidwilagnaa dashanaantareshu Sandrishyante choornitairuttamaangaih. Tathaiva naashaaya vishanti lokaas Tavaapi vaktraani samriddhavegaah. Tathaa tavaamee naralokaveeraah Vishanti vaktraanyabhivijwalanti. 25. fearful with teeth. Vaktraani te twaramaanaa vishanti Damshtraakaraalaani bhayaanakaani. nor do I find peace. whom he did not wish to kill. They hurriedly enter into Thy mouths with terrible teeth and fearful to behold. rushing to death. with large. just as many torrents of rivers flow towards the ocean. Some are found sticking in the gaps between the teeth. who Thou art. Mayaa hataamstwam jahi maa vyathishthaa Yudhyaswa jetaasi rane sapatnaan. Vijnaatumicchaami bhavantamaadyam Na hi prajaanaami tava pravrittim. Karna and all the other courageous warriors—these have already been slain by Me. 33. Mayaivaite nihataah poorvameva Nimittamaatram bhava savyasaachin. The Blessed Lord said: 32. Thou lickest up. 34. so fierce in form. Verily. O Vishnu! Aakhyaahi me ko bhavaanugraroopo Namo’stu te devavara praseeda. Sri Bhagavaan Uvaacha: Kaalo’smi lokakshayakrit pravriddho Lokaan samaahartumiha pravrittah. O Arjuna! Dronam cha bheeshmam cha jayadratham cha Karnam tathaa’nyaanapi yodhaveeraan. Tell me. be not distressed with fear. they have already been slain by Me. fight and thou shalt conquer thy enemies in battle. I desire to know Thee. Thy fierce rays. Salutations to Thee. none of the warriors arrayed in the hostile armies shall live. Bhishma. are burning. I know not indeed Thy doing. Drona. Tasmaat twam uttishtha yasho labhaswa Jitwaa shatroon bhungkshwa raajyam samriddham. do thou kill. Jayadratha. Even without thee. the original Being. I am the mighty world-destroying Time. As moths hurriedly rush into a blazing fire for (their own) destruction. O God Supreme! Have mercy. Conquer the enemies and enjoy the unrivalled kingdom.THE YOGA OF THE VISION OF THE COSMIC FORM 29. Lelihyase grasamaanah samantaal Lokaan samagraan vadanair jwaladbhih. devouring all the worlds on every side with Thy flaming mouths. so also these creatures hurriedly rush into Thy mouths for (their own) destruction. stand up and obtain fame. Therefore. filling the whole world with radiance. Tejobhiraapoorya jagatsamagram Bhaasastavograah pratapanti vishno. 30. Rite’pi twaam na bhavishyanti sarve Ye’wasthitaah pratyaneekeshu yodhaah. 31. 90 . be thou a mere instrument. now engaged in destroying the worlds. Vettaasi vedyam cha param cha dhaama Twayaa tatam vishwamanantaroopa. COMMENTARY: The Lord is Mahatma. 38.BHAGAVAD GITA Sanjaya Uvaacha: Etacchrutwaa vachanam keshavasya Kritaanjalirvepamaanah kireetee. Rakshaamsi bheetaani disho dravanti Sarve namasyanti cha siddhasanghaah. O great soul. overwhelmed with fear. love and delight. Arjuna Uvaacha: Sthaane hrisheekesha tava prakeertyaa Jagat prahrishyatyanurajyate cha. By Thee is the universe pervaded. so He is the proper object of worship. Arjuna said: 36. the non-being and That which is the supreme (that which is beyond the Being and non-being). 37. Ananta devesha jagannivaasa Twamaksharam sadasattatparam yat. the supreme refuge of this universe. the primal cause even of (Brahma) the creator. trembling. And why should they not. bowing down. demons fly in fear to all quarters and the hosts of the perfected ones bow to Thee! Kasmaachcha te na nameran mahaatman Gareeyase brahmano’pyaadikartre. Having heard that speech of Lord Krishna. again addressed Krishna. O Being of infinite forms! Vaayuryamo’gnirvarunah shashaankah 91 . Thou art the primal God. He is greater than all else. bow to Thee who art greater (than all else). It is meet. O Krishna. prostrating himself. O Infinite Being! O Lord of the gods! O abode of the universe! Thou art the imperishable. that the world delights and rejoices in Thy praise. Twamaadidevah purushah puraanas Twamasya vishwasya param nidhaanam. Sanjaya said: 35. in a choked voice. the knowable and the supreme abode. He is the imperishable. Namaskritwaa bhooya evaaha krishnam Sagadgadam bheetabheetah pranamya. the knower. the Being. the crowned one (Arjuna). the ancient Purusha. with joined palms. salutations unto Thee. pervadest all. the creator. sitting or at meals. salutations unto Thee! Namah purastaadatha prishthataste Namo’stu te sarvata eva sarva. 43. Namo namaste’stu sahasrakritwah Punashcha bhooyo’pi namo namaste. Thou art Vayu. to forgive! Pitaasi lokasya charaacharasya Twamasya poojyashcha gururgareeyaan. Thou art the greatest Guru. or in company—that I implore Thee. reposing. 41. wherefore Thou art all. Anantaveeryaamitavikramastwam Sarvam samaapnoshi tato’si sarvah. In whatever way I may have insulted Thee for the sake of fun while at play. O Achyuta. Agni. the moon. O Being of unequalled power? Tasmaatpranamya pranidhaaya kaayam Prasaadaye twaamahameeshameedyam.THE YOGA OF THE VISION OF THE COSMIC FORM Prajaapatistwam prapitaamahashcha. Ajaanataa mahimaanam tavedam Mayaa pramaadaat pranayena vaapi. a thousand times. unmoving and moving. 42. Yama. addressing Thee as O Krishna! O Yadava! O Friend! regarding Thee merely as a friend. Na twatsamo’styabhyadhikah kuto’nyo Lokatraye’pyapratimaprabhaava. how then can there be another superior to Thee in the three worlds. Varuna. Eko’thavaapyachyuta tatsamaksham Tatkshaamaye twaamaham aprameyam. Thou art the Father of this world. Thy greatness. (for) none there exists who is equal to Thee. Salutations. Yachchaavahaasaartham asatkrito’si Vihaarashayyaasanabhojaneshu. and again salutations. Piteva putrasya sakheva sakhyuh Priyah priyaayaarhasi deva sodhum. Sakheti matwaa prasabham yaduktam He krishna he yaadava he sakheti. Thou art to be adored by this world. 40. immeasurable one. 92 . when alone (with Thee). Whatever I have presumptuously uttered from love or carelessness. Salutations to Thee from front and from behind! Salutations to Thee on every side! O All! Thou infinite in power and prowess. and the great-grandfather. 39. unknowing of this. bearing a mace. Evam roopah shakya aham nriloke Drashtum twadanyena karupraveera. and infinite. this Cosmic Form of Mine has never been seen before by anyone other than thyself. prostrating my body. Neither by the study of the Vedas and sacrifices. Tenaiva roopena chaturbhujena Sahasrabaaho bhava vishwamoorte. Show me that (previous) form only. I crave Thy forgiveness. crowned. Therefore. even so shouldst Thou forgive me. 48. having four arms. in Thy former form only. O God! Adrishtapoorvam hrishito’smi drishtwaa Bhayena cha pravyathitam mano me. Na vedayajnaadhyayanairna daanair Na cha kriyaabhirna tapobhirugraih. 46. Tejomayam vishwamanantamaadyam Yanme twadanyena na drishtapoorvam. nor by gifts. Vyapetabheeh preetamanaah punastwam Tadeva me roopamidam prapashya. O God of gods! O abode of the universe! Kireetinam gadinam chakrahastam Icchaami twaam drashtumaham tathaiva.BHAGAVAD GITA 44. with the discus in hand. O Arjuna. 93 . a friend his (dear) friend. can I be seen in this form in the world of men by any other than thyself. nor by rituals. and yet my mind is distressed with fear. The Blessed Lord said: 47. I am delighted. primeval. full of splendour. nor by severe austerities. O thousand-armed. 45. this Cosmic Form has graciously been shown to thee by Me by My own Yogic power. Cosmic Form (Being)! Sri Bhagavaan Uvaacha: Mayaa prasannena tavaarjunedam Roopam param darshitamaatmayogaat. O God! Have mercy. O adorable Lord! As a father forgives his son. a lover his beloved. O great hero of the Kurus (Arjuna)! Maa te vyathaa maa cha vimoodhabhaavo Drishtwaa roopam ghorameedringmamedam. having seen what has never been seen before. Tadeva me darshaya deva roopam Praseeda devesha jagannivaasa. I desire to see Thee as before. bowing down. Arjuna Uvaacha: Drishtwedam maanusham roopam tava saumyam janaardana. be known and seen in reality and also entered into. Idaaneemasmi samvrittah sachetaah prakritim gatah. and the great soul (Krishna). of this form. nor by austerity. The Blessed Lord said: 52. Nirvairah sarvabhooteshu yah sa maameti paandava. Having thus spoken to Arjuna. Even the gods are ever longing to behold it. But by single-minded devotion can I. Sanjaya Uvaacha: Ityarjunam vaasudevastathoktwaa Swakam roopam darshayaamaasa bhooyah. Having seen this Thy gentle human form. Jnaatum drashtum cha tattwena praveshtum cha parantapa. O Arjuna! Matkarmakrinmatparamo madbhaktah sangavarjitah. Arjuna said: 51. Naa ham vedairna tapasaa na daanena na chejyayaa. now I am composed and restored to my own nature! Sri Bhagavaan Uvaacha: Sudurdarshamidam roopam drishtavaanasi yanmama. O Krishna.THE YOGA OF THE VISION OF THE COSMIC FORM 49. Bhaktyaa twananyayaa shakyam aham evamvidho’rjuna. with thy fear entirely dispelled and with a gladdened heart. 53. Aashwaasayaamaasa cha bheetamenam Bhootwaa punah saumyavapurmahaatmaa. Very hard indeed it is to see this form of Mine which thou hast seen. 54. Neither by the Vedas. can I be seen in this form as thou hast seen Me (so easily). Be not afraid nor bewildered on seeing such a terrible form of Mine as this. Krishna again showed His own form. consoled him who was terrified (Arjuna). Devaa apyasya roopasya nityam darshanakaangkshinah. Shakya evamvidho drashtum drishtavaanasi maam yathaa. now behold again this former form of Mine. assuming His gentle form. nor by gift. Sanjaya said: 50. nor by sacrifice. 94 . whereby the aspirant meditates on the formless Brahman. He who practises this teaching attains supreme bliss and immortality. becoming completely one with Him. If this process of concentration is difficult he should dedicate all his actions to Him. the science of the Eternal. If this also is beyond his ability. He thus effects union with the Lord and attains not only His formless aspect but also the Lord as the manifest universe. He neither attaches himself to anything nor does he have any aversion to things. who is devoted to Me. The Lord goes on to describe the qualities that a true devotee possesses. who is free from attachment. He who does all actions for Me.o’dhyaayah Thus in the Upanishads of the glorious Bhagavad Gita. He should take complete refuge in Him. He has to have dispassion for the things of the world. the scripture of Yoga. remembers Him and chants His glories and Name. He has a balanced mind under all 95 . This verse contains the summary of the entire Gita philosophy. Such a one realises Him and enters into His Being. adores Him. is more difficult as he has to give up his attachment to the body from the very beginning. he comes to Me. In this path the aspirant worships God in His Cosmic Form of the Supreme Personality.BHAGAVAD GITA 55. O Arjuna! COMMENTARY: This is the essence of the whole teaching of the Gita. The devotee who surrenders himself to the Lord attains perfect peace. He develops a loving relationship with Him. he should offer all his actions to the Lord. who looks upon Me as the Supreme. abandoning the desire for their fruits. feeling that it is His power that activates everything. The path of knowledge. As often as the mind wanders it should be brought back to the Lord. How to practise devotion? Krishna asks Arjuna to fix his entire mind on Him. ends the eleventh discourse entitled: “The Yoga of the Vision of the Cosmic Form” XII THE YOGA OF DEVOTION Summary of Twelfth Discourse The twelfth discourse indicates that the path of devotion is easier than the path of knowledge. the dialogue between Sri Krishna and Arjuna. who bears enmity towards no creature. ever steadfast and endowed with supreme faith. thus worship Thee and those also who worship the Imperishable and the Unmanifested—which of them are better versed in Yoga? COMMENTARY: The twelfth discourse indicates that Bhakti Yoga is much easier than Jnana Yoga or the Yoga of knowledge. 96 . He sees equality everywhere. The Blessed Lord said: 2. Those who worship the imperishable. Shraddhayaa parayopetaaste me yuktatamaa mataah. Sarvatragamachintyam cha kootasthamachalam dhruvam. nor does he himself cause any agitation in others. Arjuna said: 1. fixing their minds on Me. these are the best in Yoga in My opinion. being untouched by sorrow. the unthinkable. Greater is their trouble whose minds are set on the Unmanifested. the omnipresent. Avyaktaa hi gatirduhkham dehavadbhiravaapyate. ever steadfast. Those devotees who. 3. the eternal and the immovable. Ye chaapyaksharamavyaktam teshaam ke yogavittamaah. fear. He is perfectly desireless and rejoices in the Lord within. worship Me. for the goal—the Unmanifested—is very difficult for the embodied to reach. 4. He is not agitated by the happenings of the world. Those who. Samniyamyendriyagraamam sarvatra samabuddhayah. Ye twaksharamanirdeshyamavyaktam paryupaasate. the indefinable. Arjuna Uvaacha: Evam satatayuktaa ye bhaktaastwaam paryupaasate. even-minded everywhere. Klesho’dhikatarasteshaam avyaktaasaktachetasaam. intent on the welfare of all beings—verily they also come unto Me. Sri Bhagavaan Uvaacha: Mayyaaveshya mano ye maam nityayuktaa upaasate. 5.THE YOGA OF DEVOTION circumstances. He is perfectly content as he has surrendered his entire being to the Lord. honour as also dishonour. Having restrained all the senses. Te praapnuvanti maameva sarvabhootahite rataah. the unmanifested. even by doing actions for My sake. Nivasishyasi mayyeva ata oordhwam na samshayah. meditating on Me with single-minded Yoga. 6. Shreyo hi jnaanamabhyaasaat jnaanaaddhyaanam vishishyate. then. 7. Their restless minds will not be able to get fixed on the attributeless Self. renounce the fruits of all actions with the self controlled.BHAGAVAD GITA COMMENTARY: The embodied—those who identify themselves with their bodies. taking refuge in union with Me. Better indeed is knowledge than practice. 97 . Dhyaanaat karmaphalatyaagas tyaagaacchaantir anantaram. 11. thy intellect in Me. Teshaamaham samuddhartaa mrityusamsaarasaagaraat. The imperishable Self is very hard to reach for those who are attached to their bodies. If thou art unable to practise even this Abhyasa Yoga. Ananyenaiva yogena maam dhyaayanta upaasate. O Arjuna. But to those who worship Me. thou shalt attain perfection. Abhyaasayogena tato maamicchaaptum dhananjaya. renouncing all actions in Me. be thou intent on doing actions for My sake. Sarvakarmaphalatyaagam tatah kuru yataatmavaan. 9. If thou art unable to fix thy mind steadily on Me. then by the Yoga of constant practice do thou seek to reach Me. If thou art unable to do even this. than knowledge meditation is better. Athaitadapyashakto’si kartum madyogamaashritah. Atha chittam samaadhaatum na shaknoshi mayi sthiram. 12. than meditation the renunciation of the fruits of actions. Bhavaami nachiraat paartha mayyaaveshitachetasaam. Ye tu sarvaani karmaani mayi sannyasya matparaah. Fix thy mind on Me only. 8. regarding Me as the supreme goal. verily I become ere long the saviour out of the ocean of the mortal Samsara! Mayyeva mana aadhatswa mayi buddhim niveshaya. To those whose minds are set on Me. peace immediately follows renunciation. 10. O Arjuna! Abhyaase’pyasamartho’si matkarmaparamo bhava. (then) thou shait no doubt live in Me alone hereafter. Madarthamapi karmaani kurvansiddhimavaapsyasi. and untroubled. 15. Shubhaashubhaparityaagee bhaktimaan yah sa me priyah. and who is freed from joy. Samah shatrau cha mitre cha tathaa maanaapamaanayoh. nor grieves. Further. is dear to Me. Sheetoshnasukhaduhkheshu samah sangavivarjitah. 18. 13. He who is the same to foe and friend. he. 17. with mind and intellect dedicated to Me. Harshaamarshabhayodwegairmukto yah sa cha me priyah. 98 . Yasmaannodwijate loko lokaannodwijate cha yah. content with anything. Mayyarpitamanobuddhiryo madbhaktah sa me priyah. possessed of firm conviction. He who neither rejoices. He who hates no creature. expert. self-controlled. is dear to Me. COMMENTARY: He does not rejoice when he attains desirable objects nor does he grieve when he parts with his cherished objects. Nirmamo nirahankaarah samaduhkhasukhah kshamee. Yona hrishyati na dweshti na shochati na kaangkshati. nor hates. and in honour and dishonour. and full of devotion—that man is dear to Me. Ever content. 19. he does not desire the unattained. Santushtah satatam yogee yataatmaa dridhanishchayah. He who is free from wants. He to whom censure and praise are equal. Tulyanindaastutirmaunee santushto yena kenachit: Aniketah sthiramatir bhaktimaan me priyo narah. unconcerned. who is free from attachment. pure. balanced in pleasure and pain. homeless. 16. and forgiving. and who is full of devotion. who is friendly and compassionate to all. renouncing all undertakings or commencements—he who is (thus) devoted to Me. Sarvaarambhaparityaagee yo madbhaktah sa me priyah.THE YOGA OF DEVOTION Adweshtaa sarvabhootaanaam maitrah karuna eva cha. nor desires. steady in meditation. 14. who is free from attachment and egoism. who is the same in cold and heat and in pleasure and pain. who is silent. is dear to Me. of a steady mind. renouncing good and evil. Anapekshah shuchirdaksha udaaseeno gatavyathah. He by whom the world is not agitated and who cannot be agitated by the world. My devotee. envy. fear and anxiety—he is dear to Me. Ye tu dharmyaamritamidam yathoktam paryupaasate. the mind. The Lord gives us a wonderfully revealing insight into the human individual. the scripture of Yoga. 20. The immortal Soul. the ego. is also described in a wonderful manner. are exceedingly dear to Me. sustainer. endowed with faith. Thus. the guide. most inspiring and most mystical portions of the Bhagavad Gita. They verily who follow this immortal Dharma (doctrine or law) as described above. This knowledge constitutes the main subject matter of all the scriptures and the highest philosophical works. Verily. the knowledge of which grants us immortality. is the main theme of this discourse. Lord Krishna explains the mystery of the individual soul dwelling within this mortal body. Next follows a wonderful summing-up of what constitutes true knowledge. This self is none other than That. the dialogue between Sri Krishna and Arjuna. ends the twelfth discourse entitled: “The Yoga of Devotion” XIII THE YOGA OF DISTINCTION BETWEEN THE FIELD & THE KNOWER OF THE FIELD Summary of Thirteenth Discourse In this discourse we have one of the most significant. The five elements. most illuminating. with its physical embodiment. the devotees. It pervades all. The knower of the Supreme Reality is instantly liberated. it is the one seer. the science of the Eternal. they. The Immortal Soul (yourself). It is the metaphysics of man. That Supreme Reality is the one universal Essence present everywhere. The supreme transcendental Spirit. it is the Supreme Being who has projected Himself and assumed the form of this Knower of the Field within this body. One who knows this mystery is not bound by activity 99 . experiencer and Lord of all. which is the eternal substratum beyond both.BHAGAVAD GITA Shraddhadhaanaah matparamaa bhaktaaste’teeva me priyaah. Then follows the declaration of the Supreme Soul. The blessed Lord tells us that the knowledge of the Field and the Knower of the Field is the true knowledge. unknown. It shines within the inmost chambers of our heart. This body is the Field. intellect and the ten organs. desire and aversion and such factors constitute the Field. regarding Me as their supreme goal. This highest and the best knowledge grants us divine wisdom and spiritual illumination that lead to divine beatitude. it is everything. dwelling in the body is the Knower of the Field. the witness. Indriyaani dashaikam cha pancha chendriyagocharaah. O Arjuna. Rishibhirbahudhaa geetam cchandobhirvividhaih prithak. 5. Sages have sung in many ways. Arjuna Uvaacha: Prakritim purusham chaiva kshetram kshetrajnameva cha. Do thou also know Me as the Knower of the Field in all fields. the Field and the Knower of the Field. Sri Bhagavaan Uvaacha: Idam shareeram kaunteya kshetramityabhidheeyate. Brahmasootrapadaishchaiva hetumadbhirvinishchitaih. knowledge and that which ought to be known. Sa cha yo yatprabhaavashcha tatsamaasena me shrinu. and also who He is and what His powers are—hear all that from Me in brief. Tat kshetram yaccha yaadrik cha yadvikaari yatashcha yat. 3. Mahaabhootaanyahankaaro buddhiravyaktameva cha. The Blessed Lord said: 2. by the sages. Etadveditumicchaami jnaanam jneyam cha keshava. that is. Krishna asks us to see and know the difference between the Field (body or Prakriti) and the Knower of the Field (Spirit or Purusha). he who knows it is called the Knower of the Field by those who know of them.THE YOGA OF DISTINCTION BETWEEN THE FIELD & THE KNOWER OF THE FIELD even in the midst of life. Kshetrajnam chaapi maam viddhi sarvakshetreshu bhaarata. I wish to learn about Nature (matter) and the Spirit (soul). what its modifications are and whence it is. Arjuna said: 1. is called the Field. This body. full of reasoning and decisive. 100 . O Arjuna! Knowledge of both the Field and the Knower of the Field is considered by Me to be the knowledge. and thus reach the Self. Kshetrakshetrajnayor jnaanam yattat jnaanam matam mama. Etadyo vetti tam praahuh kshetrajna iti tadvidah. 4. in various distinctive chants and also in the suggestive words indicative of the Absolute. What the Field is and of what nature. When we perceive this supreme Presence dwelling in all beings we cannot injure anyone. This is the teaching and the message of this illuminating discourse. sickness and pain. Icchaa dweshah sukham duhkham sanghaatashchetanaa dhritih. Indriyaartheshu vairaagyamanahankaara eva cha. pain. intellect and also unmanifested Nature. 9. Asaktiranabhishwangah putradaaragrihaadishu. The great elements. and the five objects of the senses. death. 12. 8. unpretentiousness. purity. water. egoism. tongue and nose). steadfastness. old age. taste and smell. air and ether are so called because they pervade all modifications of matter. Adhyaatma jnaana nityatwam tattwa jnaanaartha darshanam. also absence of egoism. 10. and constant even-mindedness on the attainment of the desirable and the undesirable. Desire. pleasure. home and the rest. fortitude and intelligence—the Field has thus been described briefly with its modifications. Humility. perception of the end of true knowledge—this is declared to be knowledge. Viviktadesha sevitwam aratir janasamsadi. wife. resort to solitary places. and the five organs of action (hand. the aggregate (the body). Amaanitwam adambhitwam ahimsaa kshaantiraarjavam. the ten senses and one. forgiveness. eyes. Janmamrityujaraavyaadhi duhkhadoshaanu darshanam. Aachaaryopaasanam shaucham sthairyamaatmavinigrahah. Etat kshetram samaasena savikaaramudaahritam. hatred. perception of (or reflection on) the evil in birth. and what is opposed to it is ignorance. COMMENTARY: Great elements: earth. anus and generative organ). service of the teacher. The five objects of the senses are sound. non-injury. Constancy in Self-knowledge. self-control. mouth. 7. distaste for the society of men. skin. 101 . 11. The one: this is the mind. The ten senses are: the five organs of knowledge (ears. feet. touch. Mayi chaananyayogena bhaktiravyabhichaarinee.BHAGAVAD GITA 6. form colour. Nityam cha samachittatwam ishtaanishtopapattishu. uprightness. Unswerving devotion unto Me by the Yoga of non-separation. Indifference to the objects of the senses. Etajjnaanamiti proktam ajnaanam yadato’nyathaa. fire. non-identification of the Self with son. Non-attachment... 15.. 16.. they go to the Supreme. and that the Knower of the Field is pure Consciousness. the Unmanifested. Hence all things created are subject to their influence and irresistible power. which hold the entire universe and all creatures under their sway. the material cause of being. perceive the distinction between the Field and its Knower. This Cosmic Nature is the primal source and origin of the entire creation and all things in it. the non-doer. the dialogue between Sri Krishna and Arjuna. the scripture of Yoga.BHAGAVAD GITA 34.—they attain the Supreme. They who. O Arjuna! Kshetrakshetrajnayor evam antaram jnaanachakshushaa. so also the Lord of the Field (the Supreme Self) illumines the whole Field. the doer. Therefore. namely. Without this knowledge one will be forever bound by sorrow. unchanging and infinite. and who also perceive the non-existence of Nature. ends the thirteenth discourse entitled: “The Yoga of the Distinction Between The Field and the Knower of the Field” XIV THE YOGA OF THE DIVISION OF THE THREE GUNAS Summary of Fourteenth Discourse Knowledge of the three cosmic qualities or Gunas. ignorance. changing and finite. Just as the one sun illumines the whole world. is of vital importance to each and everyone for their progress and happiness in life. through the eye of knowledge. Lord Krishna reveals that these three qualities compose the Cosmic Nature. one should acquire this precious knowledge. 105 . Bhootaprakritimoksham cha ye vidur yaanti te param. that the Field is insentient. 35.. COMMENTARY: They who know through the eye of intuition opened by meditation and the instructions of the Guru and the scriptures. The knowledge of these three Gunas. Rajas and Tamas is now given through this discourse. The individual soul also is bound to the body by these three qualities present in Cosmic Nature. Sattwa. and also the liberation from the Nature of being. In this knowledge we have the secret of success in worldly life as well as in spiritual life. the science of the Eternal. The Supreme Being brings about creation through the help of His Prakriti (Nature) endowed with these threefold qualities. The Blessed Lord said: 1. It is pure. is the birth of all beings! 106 . old age and sorrow. Mama yonirmahadbrahma tasmin garbham dadhaamyaham. 3. are neither born at the time of creation nor are they disturbed at the time of dissolution. although it is Sattwa that enables him to reach God. Lord Krishna teaches us this important subject in this discourse from the ninth to the eighteenth verse. and by holding it in check. wisdom and also illumination. O Arjuna. both secular as well as spiritual. COMMENTARY: In this verse it is knowledge of the Supreme Self that is eulogised by the Lord. I will again declare (to thee) that supreme knowledge. even this quality will bind him if he is attached to it. lethargy and delusion. the best of all knowledge. for. It brings about happiness. Yajjnaatwaa munayah sarve paraam siddhimito gataah. The second quality of Rajas gives rise to passion manifested by intense attachment and greed. death. and enjoys immortality. of course. wisely divert its power towards good kinds of activities. It causes sorrow and suffering. It arises due to ignorance and results in darkness. Then only can he maintain an unhampered and smooth progress in all activities of his life. They who. Sambhavah sarvabhootaanaam tato bhavati bhaarata. goes beyond all these qualities. 2. Sattwa should be carefully cultivated. The aspirant should know the symptoms and signs of their presence in his personality and acquire a knowledge of their subtle workings. Krishna asks us to diligently endeavour to cast out Tamas from our nature. My womb is the great Brahma. In reply to a question from Arjuna. termed Tamas. He declares that one who rises beyond all the three Gunas through spiritual practices. in that I place the germ. thence. having taken refuge in this knowledge. Sri Bhagavaan Uvaacha: Param bhooyah pravakshyaami jnaanaanaam jnaanamuttamam. He states that if one constantly worships Him with exclusive devotion one will attain the highest divine experience and supreme peace and blessedness. the blessed Lord describes the marks of one who has risen above the three Gunas. We should control and master Rajas. The third. having known which all the sages have gone to the supreme perfection after this life. becomes free from birth. developed and conserved in order to enable us to attain immortality. attain to unity with Me. is the worst of all.THE YOGA OF THE DIVISION OF THE THREE GUNAS The highest of the three qualities is Sattwa. Sarge’pi nopajaayante pralaye na vyathanti cha. Idam jnaanam upaashritya mama saadharmyam aagataah. The realised sage. Now Sattwa prevails. while Tamas. binds by attachment to knowledge and to happiness. Sometimes Sattwa predominates and at other times Rajas or Tamas predominates. O sinless one! Rajo raagaatmakam viddhi trishnaasangasamudbhavam. now Rajas. They are not constant. O Arjuna. 7. sleep and indolence! Sattwam sukhe sanjayati rajah karmani bhaarata. the great Brahma is their womb and I am the seed-giving father. Purity. Sattwa attaches to happiness. 4. Know thou Rajas to be of the nature of passion. the embodied one by attachment to action! Tamastwajnaanajam viddhi mohanam sarvadehinaam. and now Tamas. But know thou Tamas to be born of ignorance. it binds fast. Of these. One should analyse and stand as a witness of these three qualities. by heedlessness. Tannibadhnaati kaunteya karmasangena dehinam. Rajah sattwam tamashchaiva tamah sattwam rajastathaa. attaches to heedlessness only! Rajastamashchaabhibhooya sattwam bhavati bhaarata. Pramaadaalasyanidraabhis tannibadhnaati bhaarata. bind fast in the body. Whatever forms are produced. deluding all embodied beings. having overpowered Sattwa and Rajas! 107 .BHAGAVAD GITA Sarvayonishu kaunteya moortayah sambhavanti yaah. 8. it binds fast. O Arjuna. Sattwam rajastama iti gunaah prakriti sambhavaah. Sukhasangena badhnaati jnaanasangena chaanagha. Rajas to action. O Arjuna. having overpowered Rajas and Tamas. born of Nature. 6. Nibadhnanti mahaabaaho dehe dehinam avyayam. the indestructible! COMMENTARY: The three Gunas are present in all human beings. Jnaanamaavritya tu tamah pramaade sanjayatyuta. the source of thirst (for sensual enjoyment) and attachment. O Arjuna. O mighty-armed Arjuna. Taasaam brahma mahadyonir aham beejapradah pitaa. None is free from the operation of any one of the three qualities. 10. 5. Tatra sattwam nirmalatwaat prakaashakam anaamayam. shrouding knowledge. 9. having overpowered Sattwa and Tamas. in any womb whatsoever. which from its stainlessness is luminous and healthy. the embodied. passion and inertia—these qualities. O Arjuna. Sattwa. O Arjuna! Yadaa sattwe pravriddhe tu pralayam yaati dehabhrit. Rajasi pralayam gatwaa karmasangishu jaayate. 12. through every gate (sense) in this body. heedlessness and delusion—these arise when Tamas is predominant. 13. Rajasastu phalam duhkham ajnaanam tamasah phalam. the wisdom-light shines. inertness. is Sattwic and pure. and dying in Tamas. 17. he is born in the womb of the senseless. Pramaadamohau tamaso bhavato’jnaanameva cha. Greed. heedlessness and delusion arise from Tamas. then he attains to the spotless worlds of the knowers of the Highest. and ignorance also. Tadottamavidaam lokaan amalaan pratipadyate. the undertaking of actions. the fruit of Rajas is pain. then it may be known that Sattwa is predominant. he is born among those who are attached to action. and ignorance is the fruit of Tamas. If the embodied one meets with death when Sattwa has become predominant. activity. Rajasyetaani jaayante vivriddhe bharatarshabha. From Sattwa arises knowledge. longing—these arise when Rajas is predominant. 108 . 15. 14.THE YOGA OF THE DIVISION OF THE THREE GUNAS Sarvadwaareshu dehe’smin prakaasha upajaayate. Lobhah pravrittir aarambhah karmanaam ashamah sprihaa. Karmanah sukritasyaahuh saattwikam nirmalam phalam. 11. Sattwaat sanjaayate jnaanam rajaso lobha eva cha. The fruit of good action. Jaghanyagunavrittisthaa adho gacchanti taamasaah. O Arjuna! Aprakaasho’pravrittishcha pramaado moha eva cha. restlessness. Darkness. Oordhwam gacchanti sattwasthaa madhye tishthanti raajasaah. they say. Tathaa praleenastamasi moodhayonishu jaayate. and greed from Rajas. When. Tamasyetaani jaayante vivriddhe kurunandana. Jnaanam yadaa tadaa vidyaa dvivriddham sattwamityuta. 16. Meeting death in Rajas. and attains to immortality. O Arjuna. Arjuna Uvaacha: Kairlingais treen gunaanetaan ateeto bhavati prabho. Samaduhkhasukhah swasthah samaloshtaashmakaanchanah.—when they are present. he hates not. 109 . COMMENTARY: The seer knows that the Gunas alone are responsible for all actions and He is distinct from them. Those who are seated in Sattwa proceed upwards. is freed from birth. death. O Lord? What is his conduct and how does he go beyond these three qualities? Sri Bhagavaan Uvaacha: Prakaasham cha pravrittim cha mohameva cha paandava. 19. When the seer beholds no agent other than the Gunas. Gunaanetaanateetya treen dehee dehasamudbhavaan. Light. is self-centred and moves not. 23. Arjuna said: 21. activity and delusion. go downwards. He who. and who. What are the marks of him who has crossed over the three qualities. Gunaa vartanta ityeva yo’vatishthati nengate. and the Tamasic. he attains to My Being. abiding in the function of the lowest Guna. The Blessed Lord said: 22. Naanyam gunebhyah kartaaram yadaa drashtaanupashyati. 20. decay and pain. is not moved by the qualities. Gunebhyashcha param vetti madbhaavam so’dhigacchati. Janmamrityujaraaduhkhair vimukto’mritamashnute. knowing that the qualities are active. Kimaachaarah katham chaitaam streen gunaan ativartate. nor does he long for them when they are absent! Udaaseenavadaaseeno gunairyo na vichaalyate. the Rajasic dwell in the middle. Tulyapriyaapriyo dheeras tulyanindaatma samstutih. having crossed beyond these three Gunas out of which the body is evolved. seated like one unconcerned. knowing that which is higher than them. Na dweshti sampravrittaani na nivrittaani kaangkshati. The embodied one.BHAGAVAD GITA 18. to whom a clod of earth. the same to friend and foe. Here Lord Krishna tells us about the ultimate source of this visible phenomenal universe from which all things have come into being. 26. leaves. Sa gunaan samateetyaitaan brahmabhooyaaya kalpate. and whose spreading branches and foliage constitute all the things and factors that go to make up this 110 . crossing beyond the qualities. The same in honour and dishonour. Maanaapamaanayostulyas tulyo mitraaripakshayoh. Sarvaarambhaparityaagee gunaateetah sa uchyate. firm. Sri Krishna declares that the Supreme Being is the source of all existence. of everlasting Dharma and of absolute bliss. who dwells in the Self. he. and refers allegorically to this universe as being like an inverted tree whose roots are in Para Brahman. the scripture of Yoga. the same in censure and praise. the science of the Eternal. ends the fourteenth discourse entitled: “The Yoga of the Division Of the Three Gunas” XV THE YOGA OF THE SUPREME SPIRIT Summary of Fifteenth Discourse This discourse is entitled “Purushottama Yoga” or the “Yoga of the Supreme Person”. Shaashwatasya cha dharmasya sukhasyaikaantikasya cha. And he who serves Me with unswerving devotion. flowers and fruits which spring forth from the earth. Maam cha yo’vyabhichaarena bhaktiyogena sevate. the immortal and the immutable. just like a great tree with all its roots. to whom the dear and the unfriendly are alike.. is fit for becoming Brahman. abandoning all undertakings—he is said to have crossed the qualities. 25. stone and gold are alike. which itself supports the tree and in which it is rooted. the dialogue between Sri Krishna and Arjuna. branches.THE YOGA OF THE DIVISION OF THE THREE GUNAS 24. Alike in pleasure and pain. 27. For I am the abode of Brahman. trunk. twigs. Brahmano hi pratishthaa’ham amritasyaavyayasya cha. and below in the world of men stretch forth the roots. One who fully understands the nature of this Samsara-Tree goes beyond Maya. Below and above spread its branches. whose leaves are the metres or hymns. 111 . moon and fire. He is the inner witness of all beings. Thus. 2. Cchandaamsi yasya parnaani yastam veda sa vedavit. imperishable status. He is the effulgence inherent in the sun. apparent appearance without having actual reality. He Himself is the indwelling Oversoul beyond the self. originating action. and hence a marvellous. In verses four and five of this discourse the Lord tells us how one goes beyond this visible Samsara and attains the supreme. he who knows it is a knower of the Vedas. He is the resplendent Person who is beyond both this perishable phenomenal creation as well as the imperishable individual soul which is a part of His eternal essence. This is a very mysterious “Tree” which is very difficult to understand. having its root above and branches below. The Lord declares that it is a part of Himself that manifests here as the individual soul in each body. He is known in this world as well as in the Vedas as the Supreme Person. To be attached to it is to be caught in it. Adhashchordhwam prasritaastasya shaakhaah Gunapravriddhaa vishayapravaalaah. nourished by the Gunas. They (the wise) speak of the indestructible peepul tree. attaining which one does not have to return to this mortal world of pain and death. Adhashcha moolaanyanusantataani Karmaanubandheeni manushyaloke. Sri Bhagavaan Uvaacha: Oordhwamoolam adhahshaakham ashwattham praahuravyayam. sense-objects are its buds. He is the supreme Knower even beyond Vedic knowledge. The surest way of transcending this Samsara or worldly life is by wielding the excellent weapon of dispassion and non-attachment. Ashwatthamenam suviroodhamoolam Asangashastrena dridhena cchittwaa. He is present as the nourishing element in the earth. Lord Krishna also describes for us the wonderful mystery of His Presence in this universe and the supreme place He occupies in sustaining everything here. because He is beyond perishable matter and superior to the imperishable soul (enveloped in Maya). being a product of His inscrutable power of Maya.BHAGAVAD GITA creation of variegated phenomena. The Blessed Lord said: 1. Na roopamasyeha tathopalabhyate Naanto na chaadirna cha sampratishthaa. Tameva chaadyam purusham prapadye Yatah pravrittih prasritaa puraanee. the undeluded reach the eternal goal. victorious over the evil of attachment.). is Purusha. which consists of ceaselessly remembering the Supreme Being. Then that goal should be sought after. dwelling constantly in the Self. etc. Shareeram yadavaapnoti yacchaapyutkraamateeshwarah. 7. draws to (itself) the (five) senses with the mind for the sixth. Tatah padam tat parimaargitavyam Yasmin gataa na nivartanti bhooyah. When the Lord obtains a body and when He leaves it. Single-minded devotion. That which sleeps in this city of the body is the Purusha. Nirmaanamohaa jitasangadoshaa Adhyaatmanityaa vinivrittakaamaah. Its form is not perceived here as such. that is My supreme abode. Seek refuge in that Primeval Purusha whence streamed forth the ancient activity or energy. their desires having completely turned away. 112 .THE YOGA OF THE SUPREME SPIRIT 3. Neither doth the sun illumine there. abiding in Nature. whither having gone none returns again. nor its foundation nor resting place. Griheetwaitaani samyaati vaayurgandhaanivaashayaat. neither its end nor its origin. is the surest and most potent means of attaining Self-realisation. having cut asunder this firmly-rooted peepul tree with the strong axe of non-attachment. Adhishthaaya manashchaayam vishayaanupasevate. 6. 4. Na tadbhaasayate sooryo na shashaangko na paavakah. Free from pride and delusion. nor the fire. freed from the pairs of opposites known as pleasure and pain. Yadgatwaa na nivartante taddhaama paramam mama. 8. nor the moon. He takes these and goes (with them) as the wind takes the scents from their seats (flowers. Shrotram chakshuh sparshanam cha rasanam ghraanameva cha. COMMENTARY: That which fills the whole world with the form of Satchidananda. Dwandwairvimuktaah sukhaduhkhasamjnair Gacchantyamoodhaah padamavyayam tat. Manah shashthaaneendriyaani prakritisthaani karshati. 5. Mamaivaamsho jeevaloke jeevabhootah sanaatanah. An eternal portion of Myself having become a living soul in the world of life. having gone thither they return not. Dwaavimau purushau loke ksharashchaakshara eva cha. from Me are memory. Having become the fire Vaisvanara. 14. Vedaischa sarvairahameva vedyo Vedaantakrid vedavid eva chaaham. that which is in the moon and in the fire—know that light to be Mine. Vimoodhaa naanupashyanti pashyanti jnaanachakshushah. The deluded do not see Him who departs. the unrefined and unintelligent. and the knower of the Vedas am I. as well as the mind. 12. Praanaapaana samaayuktah pachaamyannam chaturvidham. associated with the Prana and Apana. Yatanto’pyakritaatmaano nainam pashyantyachetasah. see Him not. Yadaadityagatam tejo jagad bhaasayate’khilam. 15. 13. stays and enjoys. illumines the whole world. but. The Yogis striving (for perfection) behold Him dwelling in the Self. I abide in the body of living beings and. knowledge. Yatanto yoginashchainam pashyantyaatmanyavasthitam. Pushnaami chaushadheeh sarvaah somo bhootwaa rasaatmakah. he enjoys the objects of the senses. as well as their absence.BHAGAVAD GITA 9. and. I nourish all herbs. Aham vaishwaanaro bhootwaa praaninaam dehamaashritah. And. That light which residing in the sun. Gaam aavishya cha bhootaani dhaarayaamyaham ojasaa. I am indeed the author of the Vedanta. but they who possess the eye of knowledge behold Him. I am seated in the hearts of all. 113 . taste and smell. 10. even though striving. touch. I am verily that which has to be known by all the Vedas. 11. Ksharah sarvaani bhootaani kootastho’kshara uchyate. Sarvasya chaaham hridi sannivishto Mattah smritir jnaanam apohanam cha. digest the fourfold food. Utkraamantam sthitam vaapi bhunjaanam vaa gunaanvitam. the eye. Presiding over the ear. Permeating the earth I support all beings by (My) energy. Yacchandramasi yacchaagnau tattejo viddhi maamakam. having become the watery moon. THE YOGA OF THE SUPREME SPIRIT 16. this most secret science has been taught by Me. 20. Etadbuddhwaa buddhimaan syaat kritakrityashcha bhaarata. But distinct is the Supreme Purusha called the highest Self. Ato’smi loke vede cha prathitah purushottamah. knows Me thus as the highest Purusha. As I transcend the perishable and am even higher than the imperishable. 19. he. the perishable and the imperishable. the dialogue between Sri Krishna and Arjuna. O Arjuna! Hari Om Tat Sat Iti Srimad Bhagavadgeetaasoopanishatsu Brahmavidyaayaam Yogashaastre Sri Krishnaarjunasamvaade Purushottamayogo Naama Panchadasho’dhyaayah Thus in the Upanishads of the glorious Bhagavad Gita. Yasmaat ksharam ateeto’hamaksharaadapi chottamah. I am declared as the highest Purusha in the world and in the Vedas. the science of the Eternal. Two Purushas there are in this world. All beings are the perishable. He who. a man becomes wise. and the Kutastha is called the imperishable. Yo lokatrayamaavishya bibhartyavyaya ishwarah. Yo maamevam asammoodho jaanaati purushottamam. 17. O sinless one! On knowing this. ends the fifteenth discourse entitled: “The Yoga of the Supreme Spirit” 114 . undeluded. the indestructible Lord who. Uttamah purushastwanyah paramaatmetyudaahritah. worships Me with his whole being (heart). sustains them. O Arjuna! Iti guhyatamam shaastram idamuktam mayaa’nagha. Sa sarvavidbhajati maam sarvabhaavena bhaarata. knowing all. pervading the three worlds. the scripture of Yoga. Thus. and all his duties are accomplished. 18. The pure divine qualities are conducive to peace and liberation and the undivine qualities lead to bondage. Purity. Sri Bhagavaan Uvaacha: Abhayam sattwasamshuddhih jnaanayogavyavasthitih. One should therefore follow the injunctions of the sacred scriptures that wish his welfare and be guided in his actions by their noble teachings. 115 . and urges us to eradicate the latter and cultivate the divine qualities. Haughtiness. and to seekers in particular. and having no faith in God or a higher Reality beyond this visible world. good conduct and truth are indispensable to spiritual progress and even to an honourable life here. must eradicate vice and cultivate virtue. Therefore.BHAGAVAD GITA XVI THE YOGA OF THE DIVISION BETWEEN THE DIVINE AND THE DEMONIACAL Summary of Sixteenth Discourse This discourse is important and very instructive to all persons who wish to attain happiness. and sinks into darkness. The Blessed Lord said: 1. alms-giving. good conduct and truth. What kind of nature should one develop? What conduct must one follow? What way should one live and act if one must attain God and obtain divine bliss? These questions are answered with perfect clarity and very definitely. Listing two sets of qualities of opposite kinds. austerity and straightforwardness. desiring success. Lord Krishna brings out quite clearly and unmistakably here the intimate connection between ethics and spirituality. Fearlessness. steadfastness in Yoga and knowledge. who wish to attain success in their spiritual life. Released from these three qualities one can succeed in attaining salvation and reaching the highest goal. man degenerates into a two-legged beast of ugly character and cruel actions. a wise person. namely God. anger and greed. In this world three gates lead to hell—the gates of passion. sacrifice. prosperity and blessedness. Caught in countless desires and cravings. control of the senses. virtuous living. his life ultimately ends in misery and degradation. between a life of virtue and God-realisation and liberation. Daanam damashcha yajnashcha swaadhyaayastapa aarjavam. arrogance and egoism lead to this dire fate. the Lord classifies them as divine and demoniacal (undivine). Such a person becomes his own enemy and the destroyer of the happiness of others as well as his own. a slave of sensual enjoyments and beset by a thousand cares. study of scriptures. Ahimsaa satyamakrodhas tyaagah shaantirapaishunam. Thus the sacred scriptures teach wisely the right path of pure. Devoid of purity. purity of heart. Maa shuchah sampadam daiveem abhijaato’si paandava. Harmlessness. absence of crookedness. The demoniacal know not what to do and what to refrain from. 4. belong to one who is born in a demoniacal state. 2. without a (moral) basis. Daivo vistarashah proktah aasuram paartha me shrinu. 6. fortitude. Dwau bhootasargau loke’smin daiva aasura eva cha.THE YOGA OF THE DIVISION BETWEEN THE DIVINE AND THE DEMONIACAL Dayaa bhooteshvaloluptwam maardavam hreerachaapalam. The divine nature is deemed for liberation and the demoniacal for bondage. Sri Krishna assures him not to feel alarmed at this description of the demoniacal qualities as he is born with Sattwic tendencies leading towards salvation. what else?” 116 . neither purity nor right conduct nor truth is found in them. Asatyamapratishtham te jagadaahuraneeshwaram. the divine has been described at length. absence of anger. 3. absence of hatred. self-conceit. forgiveness. brought about by mutual union. Tejah kshamaa dhritih shauchamadroho naatimaanitaa. with lust for its cause. Ajnaanam chaabhijaatasya paartha sampadamaasureem. 7. harshness and also anger and ignorance. compassion towards beings. Vigour. without a God. Grieve not. O Arjuna! Dambho darpo’bhimaanashcha krodhah paarushyameva cha. truth. arrogance. 8. O Arjuna! Daivee sampadvimokshaaya nibandhaayaasuree mataa. O Arjuna. 5. absence of pride—these belong to one born in a divine state. gentleness. purity. of the demoniacal! Pravrittim cha nivrittim cha janaa na viduraasuraah. hear from Me. uncovetousness. There are two types of beings in this world—the divine and the demoniacal. Aparasparasambhootam kimanyat kaamahaitukam. Na shaucham naapi chaachaaro na satyam teshu vidyate. Bhavanti sampadam daiveem abhijaatasya bhaarata. peacefulness. O Arjuna. Hypocrisy. They say: “This universe is without truth. modesty. absence of fickleness. renunciation. for thou art born with divine properties! COMMENTARY: As Arjuna is dejected. regarding gratification of lust as their highest aim. 9.”—thus. and feeling sure that that is all. Eeshwaro’hamaham bhogee siddho’ham balavaan sukhee. Aashaapaashashatairbaddhaah kaamakrodhaparaayanaah. I enjoy.BHAGAVAD GITA Etaam drishtimavashtabhya nashtaatmaano’lpabuddhayah. Eehante kaamabhogaartha manyaayenaarthasanchayaan. Prasaktaah kaamabhogeshu patanti narake’shuchau. Chintaamaparimeyaam cha pralayaantaamupaashritaah. they work with impure resolves. Idamasteedamapi me bhavishyati punardhanam. holding evil ideas through delusion. 12. 117 . powerful and happy”. 15. deluded by ignorance. “I am rich and born in a noble family. I will rejoice. come forth as enemies of the world for its destruction. “This has been gained by me today. 14. Kaamopabhogaparamaa etaavaditi nishchitaah. Idamadya mayaa labdham imam praapsye manoratham. they strive to obtain by unlawful means hoards of wealth for sensual enjoyment. Giving themselves over to immeasurable cares ending only with death. this desire I shall obtain. this is mine and this wealth too shall be mine in future. given over to lust and anger. Who else is equal to me? I will sacrifice. 11.” Asau mayaa hatah shatrur hanishye chaaparaanapi. Holding this view. Kaamamaashritya dushpooram dambhamaanamadaanvitaah. “That enemy has been slain by me and others also I shall slay. Bound by a hundred ties of hope. pride and arrogance. I am perfect. Prabhavantyugrakarmaanah kshayaaya jagato’hitaah. I am the lord. Filled with insatiable desires. I will give (charity). full of hypocrisy. Aadhyo’bhijanavaanasmi ko’nyosti sadrisho mayaa. Yakshye daasyaami modishye ityajnaanavimohitaah. 10. 13. Anekachittavibhraantaah mohajaalasamaavritaah. Mohaadgriheetvaasadgraahaan pravartante’shuchivrataah. these ruined souls of small intellects and fierce deeds. they thus fall. the worst among men in the world. they fall into a foul hell. O Arjuna. through ostentation. Aatmasambhaavitaah stabdhaa dhanamaanamadaanvitaah. stubborn.THE YOGA OF THE DIVISION BETWEEN THE DIVINE AND THE DEMONIACAL 16. He hears the scriptures.—I hurl all these evil-doers for ever into the wombs of demons only. Kaamah krodhastathaa lobhas tasmaadetat trayam tyajet. destructive of the self—lust. He gets the company of sages. Aasureem yonimaapannaa moodhaa janmani janmani. addicted to the gratification of lust. 17. Yajante naamayajnaiste dambhenaavidhipoorvakam. He receives spiritual instructions and practises them. entangled in the snare of delusion. Taanaham dwishatah krooraan samsaareshu naraadhamaan. 19. Bewildered by many a fancy. Ahankaaram balam darpam kaamam krodham cha samshritaah. Given over to egoism. These cruel haters. anger. and greed. Yah shaastravidhimutsrijya vartate kaamakaaratah. Entering into demoniacal wombs and deluded birth after birth. filled with the intoxication and pride of wealth. lust and anger. one should abandon these three. Triple is the gate of this hell. the path to salvation is cleared for the aspirant. Na sa siddhimavaapnoti na sukham na paraam gatim. Maamapraapyaiva kaunteya tato yaantyadhamaam gatim. O Arjuna. 22. A man who is liberated from these three gates to darkness. meditates and attains Self-realisation. power. Maamaatmaparadeheshu pradwishanto’bhyasooyakaah. Aacharatyaatmanah shreyas tato yaati paraam gatim. 21. practises what is good for him and thus goes to the Supreme goal! COMMENTARY: When these three gates to hell are abandoned. 118 . not attaining Me. 20. Kshipaamyajasram ashubhaan aasureeshweva yonishu. reflects.—therefore. Self-conceited. into a condition still lower than that! Trividham narakasyedam dwaaram naashanamaatmanah. they perform sacrifices in name. these malicious people hate Me in their own bodies and those of others. Etairvimuktah kaunteya tamodwaaraistribhirnarah. 18. contrary to scriptural ordinances. which leads to liberation. haughtiness. Thus. charity. even though setting aside scriptural injunctions yet perform worship with faith?” The Lord replies and states that the faith of such men who ignore the injunctions of the scriptures could be either Sattwic. the scripture of Yoga. so develops the nature of the man. in all things like sacrifice. all these actions become barren and useless. as is the kind of faith. acts under the impulse of desire. They produce results in accordance with the quality of the doer’s faith. casting aside the ordinances of the scriptures. the science of the Eternal. contained in the last two verses therein (Verses 23 and 24). Tasmaat shaastram pramaanam te kaaryaakaaryavyavasthitau. Arjuna asks. attains neither perfection nor happiness nor the supreme goal. etc. Rajasic or Tamasic. let the scripture be the authority in determining what ought to be done and what ought not to be done. penance..BHAGAVAD GITA 23. And. worship.”. Therefore. Having known what is said in the ordinance of the scriptures. These acts done with right faith lead to supreme blessedness. the dialogue between Sri Krishna and Arjuna. 24. Jnaatwaa shaastravidhaanoktam karma kartumihaarhasi. “What about those who. Hari Om Tat Sat Iti Srimad Bhagavadgeetaasoopanishatsu Brahmavidyaayaam Yogashaastre Sri Krishnaarjunasamvaade Daivaasurasampadvibhaagayogo Naama Shodasho’dhyaayah Thus in the Upanishads of the glorious Bhagavad Gita. thou shouldst act here in this world. 119 . He who. these qualities become expressed in accordance with the kind of faith in which the person concerned is based. conversely. When done without any faith whatsoever. The theme of this discourse arises out of the question asked by Arjuna in Verse 1 with reference to the final and closing advice of Lord Krishna in the previous discourse. This would be in accordance with the basic nature of the person himself. 4. and the Tamasic (dark). the Rajasic (passionate). Shraddhaamayo’yam purusho yo yacchraddhah sa eva sah. 3. Dambhaahamkaarasamyuktaah kaamaraagabalaanvitaah. Threefold is the faith of the embodied. Pretaan bhootaganaamshchaanye yajante taamasaa janaah. Saattwikee raajasee chaiva taamasee cheti taam shrinu. perform sacrifice with faith. Maam chaivaantahshareerastham taanviddhyaasuranishchayaan. Sattwaanuroopaa sarvasya shraddhaa bhavati bhaarata. Arjuna said: 1. the others (the Tamasic or the deluded) worship the ghosts and the hosts of nature-spirits. O Krishna? Is it that of Sattwa.THE YOGA OF THE DIVISION OF THE THREEFOLD FAITH Arjuna Uvaacha: Ye shaastravidhimutsrijya yajante shraddhayaanvitaah. Yajante saattwikaa devaan yaksharakshaamsi raajasaah. the Rajasic or the passionate worship the Yakshas and the Rakshasas. which is inherent in their nature—the Sattwic (pure). 5. Karshayantah shareerastham bhootagraamamachetasah. Sri Bhagavaan Uvaacha: Trividhaa bhavati shraddhaa dehinaam saa swabhaavajaa. 6. Ashaastravihitam ghoram tapyante ye tapo janaah. Rajasic or Tamasic. O Arjuna! The man consists of his faith. Do thou hear of it. torturing all the elements in the body and Me also. The faith of each is in accordance with his nature. The Sattwic or pure men worship the gods. who dwells in the body. Those men who practise terrific austerities not enjoined by the scriptures. according to one’s inherent nature—Sattwic. so is he. as a man’s faith is. Rajas or Tamas? COMMENTARY: This discourse deals with the three kinds of faith. impelled by the force of lust and attachment. 120 . given to hypocrisy and egoism. Senseless. Those who. The Blessed Lord said: 2. setting aside the ordinances of the scriptures. what is their condition. Teshaam nishthaa tu kaa krishna sattwamaaho rajastamah.—know thou these to be of demoniacal resolves. The sacrifice which is offered. Foods which increase life. Yajnastapastathaa daanam teshaam bhedamimam shrinu. 121 . That which is stale. The foods that are bitter. Aahaaraah raajasasyeshtaa duhkhashokaamayapradaah. Rasyaah snigdhaah sthiraa hridyaa aahaaraah saattwikapriyaah. which are oleaginous and savoury. purity. Yashtavyameveti manah samaadhaaya sa saattwikah. as also sacrifice. putrid. Aayuh sattwabalaarogya sukha preetivi vardhanaah. O Arjuna. know thou that to be a Rajasic Yajna! Vidhiheenam asrishtaannam mantraheenam adakshinam. The food also which is dear to each is threefold. dry. Ucchishtamapi chaamedhyam bhojanam taamasapriyam. Abhisandhaaya tu phalam dambhaarthamapi chaiva yat. Katvamlalavanaatyushna teekshna rooksha vidaahinah. with a firm faith that to do so is a duty. 11. austerity and alms-giving. sour. substantial and agreeable.joy and cheerfulness. excessively hot. in which no food is distributed. Shraddhaavirahitam yajnam taamasam parichakshate.BHAGAVAD GITA Aahaarastwapi sarvasya trividho bhavati priyah. 12. 10. seeking a reward and for ostentation. Hear thou the distinction of these. That sacrifice which is offered by men without desire for reward as enjoined by the ordinance (scripture). health. which is devoid of Mantras and gifts. strength. Aphalaakaangkshibhiryajno vidhidrishto ya ijyate. saline. 7. rotten and impure refuse. 9. COMMENTARY: A man’s taste for a particular food is determined according to the Guna prevalent in him. 8. and which is devoid of faith. is the food liked by the Tamasic. Ijyate bharatashreshtha tam yajnam viddhi raajasam. are liked by the Rajasic and are productive of pain. are dear to the Sattwic people. tasteless. pungent and burning. is Sattwic (or pure). grief and disease. 13. They declare that sacrifice to be Tamasic which is contrary to the ordinances of the scriptures. Yaatayaamam gatarasam pooti paryushitam cha yat. 15. COMMENTARY: It is said in the Manu Smriti: “One should speak what is true. celibacy and non-injury—these are called the austerities of the body. with self-torture. knowing it to be a duty to give in a fit place and time to a worthy person. 16. one should speak what is pleasant. that gift is held to be Sattwic. Daatavyamiti yaddaanam deeyate’nupakaarine. or for the purpose of destroying another. Satkaaramaanapoojaartham tapo dambhena chaiva yat. Manahprasaadah saumyatwam maunamaatmavinigrahah. Kriyate tadiha proktam raajasam chalamadhruvam. The austerity which is practised out of a foolish notion. This is the ancient Dharma”. 18. Worship of the gods. Swaadhyaayaabhyasanam chaiva vaangmayam tapa uchyate. Bhaavasamshuddhirityetat tapo maanasamuchyate. That gift which is given to one who does nothing in return. pleasant and beneficial. Anudwegakaram vaakyam satyam priyahitam cha yat. nor what is pleasant if it is false. are called austerity of speech. is declared to be Tamasic. Brahmacharyamahimsaa cha shaareeram tapa uchyate. 14. The austerity which is practised with the object of gaining good reception. the practice of the study of the Vedas.THE YOGA OF THE DIVISION OF THE THREEFOLD FAITH Devadwijagurupraajna poojanam shauchamaarjavam. the teachers and the wise. self-control—this is called mental austerity. is here said to be Rajasic. This threefold austerity practised by steadfast men with the utmost faith. 20. Moodhagraahenaatmano yat peedayaa kriyate tapah. unstable and transitory. Serenity of mind. 122 . they call Sattwic. 19. Shraddhayaa parayaa taptam tapastattrividham naraih. good-heartedness. Aphalaakaangkshibhiryuktaih saattwikam parichakshate. honour and worship and with hypocrisy. desiring no reward. Parasyotsaadanaartham vaa tattaamasamudaahritam. one should not speak what is true if it is not pleasant. Speech which causes no excitement and is truthful. Deshe kaale cha paatre cha taddaanam saattwikam smritam. purity of nature. 17. To be an austerity speech should combine all the attributes mentioned in the above verse. the twice-born. purity. straightforwardness. is said to be Rajasic. This does not discourage the giving of alms to the poor. and so also. Adeshakaale yaddaanamapaatrebhyashcha deeyate. Asatkritamavajnaatam tattaamasamudaahritam. or looking for a reward. rogues. wealth that is distributed at an inauspicious time. Daanakriyaashcha vividhaah kriyante mokshakaangkshibhih. 26. where irreligious people and beggars assemble. Deeyate cha pariklishtam taddaanam raajasam smritam. Karma chaiva tadartheeyam sadityevaabhidheeyate. 25. The word Sat is used in the sense of reality and of goodness. that gift which is made with a view to receive something in return. 23. are the acts of sacrifice and austerity and the various acts of gift performed by the seekers of liberation. is declared to be Tamasic. women of evil reputation. And. the Vedas and the sacrifices. sacrifice and austerity as enjoined in the scriptures always begun by the students of Brahman. without aiming at the fruits. without respect or with insult. Uttering Tat. Prashaste karmani tathaa sacchabdah paartha yujyate. Tasmaadomityudaahritya yajnadaanatapahkriyaah. fools. Om tatsaditi nirdesho brahmanas trividhah smritah. Sadbhaave saadhubhaave cha sadityetatprayujyate. is distributed to gamblers. singers. Braahmanaastena vedaashcha yajnaashcha vihitaah puraa. it is used in the sense of an auspicious act! Yajne tapasi daane cha sthitih saditi chochyate. COMMENTARY: At the wrong place and time—at a place which is not holy. “Om Tat Sat”: this has been declared to be the triple designation of Brahman. The gift which is given at the wrong place and time to unworthy persons. By that were created formerly the Brahmanas. O Arjuna. 24. Tadityanabhisandhaaya phalam yajnatapah kriyaah. with the utterance of “Om” are the acts of gift. 22. 21. Pravartante vidhaanoktaah satatam brahmavaadinaam. Therefore. where wealth acquired through illegal means such as gambling and theft. or given reluctantly.BHAGAVAD GITA Yattu pratyupakaaraartham phalamuddishya vaa punah. 123 . It covers in brief numerous important points dealt with in the previous discourses. Steadfastness in sacrifice. personal gain. The drama of Arjuna’s utter despondency and breakdown is finally resolved in triumphant self-mastery. if one performs actions by renouncing egoism and attachment and surrendering all desire for selfish. which is the conclusion of the divine discourse of Lord Krishna. you obtain the Grace of the Lord and attain the eternal One. and whatever austerity is practised without faith. Ashraddhayaa hutam dattam tapastaptam kritam cha yat. O Arjuna! It is naught here or hereafter (after death). 28. Very clearly we are told that selfless and virtuous actions. the science of the Eternal.. Its central message emerges as an assurance that in and through the performance of one’s respective duties in life one can qualify for the highest liberation. the blessed Lord makes it clear to us that real Sannyasa or renunciation lies in renunciation of selfish actions. and actions conducive to the welfare of others should not be abandoned. Asadityuchyate paartha na cha tatpretya no iha. this discourse opens with a question by Arjuna asking what is true Sannyasa and true Tyaga (renunciation). You must engage yourself in performing such action but renouncing attachment and 124 . strength and bold resoluteness. given or performed. and even more in the renunciation of the desire or greed for the fruits of any action. austerity or charity done without being dedicated to the Lord will be of no avail to the doer in this earthly life here or in the life beyond hereafter. Significantly. Whatever is sacrificed. is also called Sat. is in many ways a summary of the foregoing portions of the Gita. By regarding the performance of your duties as worship offered to God. In reply to this important and crucial query.THE YOGA OF THE DIVISION OF THE THREEFOLD FAITH 27. the scripture of Yoga. it is called Asat. and also action in connection with these (or for the sake of the Supreme) is called Sat. austerity and gift. ends the seventeenth discourse entitled: “The Yoga of the Division of the Threefold Faith” XVIII THE YOGA OF LIBERATION BY RENUNCIATION Summary of Eighteenth Discourse The eighteenth discourse. Here you behold the ultimate result or effect of the Lord’s discourse to Arjuna. COMMENTARY: Whatever sacrifice. the dialogue between Sri Krishna and Arjuna. O best of the Bharatas. Hear from Me the conclusion or the final truth about this abandonment. glory and all blessedness will prevail. the essence or truth of renunciation. Arjuna said: 1. and such willing readiness to carry out the divine teachings. Sarvakarmaphalatyaagam praahustyaagam vichakshanaah. sacrifice and austerity should not be relinquished. 3. Karma does not accumulate and bind one who is thus established in such inner renunciation. has been declared to be of three kinds! Yajnadaanatapah karma na tyaajyam kaaryameva tat. Nishchayam shrinu me tatra tyaage bharatasattama. Some philosophers declare that all actions should be abandoned as an evil. verily. 125 . The Blessed Lord said: 2. there surely prosperity. as also of abandonment. while others declare that acts of gift. I desire to know severally. The sages understand Sannyas to be the renunciation of action with desire. victory. O slayer of Kesi! Sri Bhagavaan Uvaacha: Kaamyaanaam karmanaam nyaasam sannyaasam kavayoviduh. This is called Sattwic Tyaga. Tyaagasya cha hrisheekesha prithak keshinishoodana. the renunciation of egoism. The divine injunction is that God must be made the sole object of one’s life. selfishness and attachment in your activity is declared as true renunciation. This is the one way to your welfare here. the wise declare the abandonment of the fruits of all actions as Tyaga. Arjuna Uvaacha: Sannyaasasya mahaabaaho tattwamicchaami veditum. 4. We neither hate unpleasant action nor are we attached to pleasurable action. O best of men. Tyaago hi purushavyaaghra trividhah samprakeertitah. This is the heart of the Gita gospel. Now Sanjaya concludes his narrative by declaring that where there is such obedience as that of Arjuna. As it is not possible for you to renounce all action. The true and proper renunciation is giving up of selfishness and attachment while performing one’s legitimate duties. O Hrishikesa. abandonment. This is the central message in its teaching.BHAGAVAD GITA greed. Tyaajyam doshavadityeke karma praahurmaneeshinah. O mighty-armed. Yajnadaanatapah karma na tyaajyamiti chaapare. but should be performed. Sa kritwaa raajasam tyaagam naiva tyaagaphalam labhet. 8. 6. Verily. Acts of sacrifice. Sangam tyaktwaa phalam chaiva sa tyaagah saattwiko matah. 126 . 5. abandoning attachment and also the desire for reward. that renunciation is regarded as Sattwic! Na dweshtyakushalam karma kushale naanushajjate. he does not obtain the merit of renunciation by doing such Rajasic renunciation. 7. He who abandons action on account of the fear of bodily trouble (because it is painful).THE YOGA OF LIBERATION BY RENUNCIATION Yajno daanam tapashchaiva paavanaani maneeshinaam. but he who relinquishes the rewards of actions is verily called a man of renunciation. Verily. Niyatasya tu sannyaasah karmano nopapadyate. COMMENTARY: This is a summary of the doctrine of Karma Yoga already enunciated before. Then no action will bind you. Kartavyaaneeti me paartha nishchitam matamuttamam. 11. intelligent and with his doubts cut asunder. Yastu karmaphalatyaagi sa tyaageetyabhidheeyate. pervaded by purity. But even these actions should be performed leaving aside attachment and the desire for rewards. You will have to abandon the idea of agency and the fruits of actions. Tyaagee sattwasamaavishto medhaavee cchinnasamshayah. 10. the abandonment of the same from delusion is declared to be Tamasic. merely because it ought to be done. and your own nature. sacrifice. Duhkhamityeva yat karma kaayakleshabhayaat tyajet. does not hate a disagreeable work nor is he attached to an agreeable one. it is not possible for an embodied being to abandon actions entirely. gift and also austerity are the purifiers of the wise. the renunciation of obligatory action is improper. Na hi dehabhritaa shakyam tyaktum karmaanyasheshatah. Mohaattasya parityaagas taamasah parikeertitah. O Arjuna. Etaanyapi tu karmaani sangam tyaktwaa phalaani cha. Kaaryamityeva yatkarma niyatam kriyate’rjuna. O Arjuna! This is My certain and best conviction. The man of renunciation. will urge you to do actions. gift and austerity should not be abandoned. too. The defect in Karma is not in the action itself but in attachment and expectation of a reward. Whatever obligatory action is done. 9. COMMENTARY: Nature. looks upon his Self. 127 . but never to the abandoners. 15. Pashyatyakritabuddhitwaan na sa pashyati durmatih. the knowable and the knower form the threefold impulse to action. 13. he who. O mighty-armed Arjuna.BHAGAVAD GITA Anishtamishtam mishram cha trividham karmanah phalam. 17. Panchaitaani mahaabaaho kaaranaani nibodha me. The body. Prochyate gunasankhyaane yathaavacchrinu taanyapi. sees not. these five are its causes. 18. as declared in the Sankhya system for the accomplishment of all actions! Adhishthaanam tathaa kartaa karanam cha prithagvidham. though he slays these people. the organ. Vividhaashcha prithakcheshtaa daivam chaivaatra panchamam. 14. Yasya naahankrito bhaavo buddhiryasya na lipyate. owing to untrained understanding. He who is ever free from the egoistic notion. the fifth. Knowledge. nor is he bound (by the action). whether right or the reverse. Now. Whatever action a man performs by his body. as the agent. Tatraivam sati kartaaram aatmaanam kevalam tu yah. Jnaanam jneyam parijnaataa trividhaa karmachodanaa. 16. Jnaanam karma cha kartaa cha tridhaiva gunabhedatah. such being the case. Shareeravaangmanobhiryat karma praarabhate narah. the action and the agent form the threefold basis of action. he slayeth not. Nyaayyam vaa vipareetam vaa panchaite tasya hetavah. he of perverted intelligence. good and mixed—accrues after death to the non-abandoners. Learn from Me. the doer. whose intelligence is not tainted by (good or evil). the various senses. these five causes. Saankhye kritaante proktaani siddhaye sarvakarmanaam. Hatwaapi sa imaam llokaan na hanti na nibadhyate. The threefold fruit of action—evil. which is isolated. and the presiding Deity. Karanam karma karteti trividhah karmasangrahah. 12. Bhavatyatyaaginaam pretya na tu sannyaasinaam kwachit. the different functions of various sorts. speech and mind. also. Siddhyasiddhyor nirvikaarah kartaa saattwika uchyate. But that action which is done by one longing for the fulfilment of desires or gain. 24. That by which one sees the one indestructible Reality in all beings. Niyatam sangarahitam araagadweshatah kritam. 21. endowed with firmness and enthusiasm and unaffected by success or failure. Yattu kritsnavadekasmin kaarye saktamahaitukam. He who is free from attachment.THE YOGA OF LIBERATION BY RENUNCIATION 19. Muktasango’nahamvaadi dhrityutsaahasamanvitah. 20. injury and (one’s own) ability—that is declared to be Tamasic. Hear them also duly. and trivial—that is declared to be Tamasic (dark). 22. Yattu kaamepsunaa karma saahankaarena vaa punah. without regard to the consequences of loss. Sarvabhooteshu yenaikam bhaavamavyayameekshate. according to the distinction of the Gunas. without reason. not separate in all the separate beings—know thou that knowledge to be Sattwic (pure). Prithaktwena tu yajjnaanam naanaabhaavaan prithagvidhaan. Avibhaktam vibhakteshu tajjnaanam viddhi saattwikam. Aphalaprepsunaa karma yattat saattwikamuchyate. Mohaadaarabhyate karma yattat taamasamuchyate. non-egoistic. 128 . with egoism or with much effort—that is declared to be Rajasic. An action which is ordained. Atattwaarthavadalpam cha tattaamasamudaahritam. Knowledge. Anubandham kshayam himsaam anavekshya cha paurusham. which is done without love or hatred by one who is not desirous of any reward—that action is declared to be Sattwic. is called Sattwic. Vetti sarveshu bhooteshu tajjnaanam viddhi raajasam. Kriyate bahulaayaasam tadraajasamudaahritam. action and the actor are declared in the science of the Gunas (the Sankhya philosophy) to be of three kinds only. But that which clings to one single effect as if it were the whole. That action which is undertaken from delusion. which is free from attachment. 26. 25. But that knowledge which sees in all beings various entities of distinct kinds as different from one another—know thou that knowledge to be Rajasic (passionate). without foundation in Truth. 23. Vishaadee deerghasootree cha kartaa taamasa uchyate. 32. bondage and liberation—that intellect is Sattwic. is Rajasic! COMMENTARY: That which is ordained in the scriptures is Dharma. Passionate. Ayuktah praakritah stabdhah shatho naishkritiko’lasah. desiring to obtain the rewards of actions. proscrastinating—such an agent is called Tamasic. The unwavering firmness by which. greedy. 29. Unsteady. That which. Yogenaavyabhichaarinyaa dhritih saa paartha saattwikee. 31. through Yoga. O Arjuna. impure. lazy and Buddherbhedam dhriteshchaiva gunatastrividham shrinu. the functions of the mind. dejected. Harshashokaanvitah kartaa raajasah parikeertitah. is called Tamasic! Dhrityaa yayaa dhaarayate manah praanendriyakriyaah. Ayathaavat prajaanaati buddhih saa paartha raajasee. Adharmam dharmamiti yaa manyate tamasaavritaa. moved by joy and sorrow. Prochyamaanamasheshena prithaktwena dhananjaya. as I declare them fully and distinctly. and also what ought to be done and what ought not to be done—that intellect. That which knows the path of work and renunciation. vulgar. Hear thou the threefold division of the intellect and firmness according to the Gunas.BHAGAVAD GITA Raagee karmaphalaprepsur lubdho himsaatmako’shuchih. malicious. such an agent is said to be Rajasic. fear and fearlessness. views Adharma as Dharma and all things perverted—that intellect. Sarvaarthaan vipareetaamshcha buddhih saa paartha taamasee. 28. cruel. The Rajasic intellect is not able to distinguish between righteous and unrighteous actions. 33. 27. is Sattwic! 129 . cheating. unbending. O Arjuna. O Arjuna. enveloped in darkness. the life-force and the senses are restrained—that firmness. what ought to be done and what ought not to be done. Bandhammoksham cha yaa vetti buddhih saa paartha saattwikee. O Arjuna! Yayaa dharmamadharmam cha kaaryam chaakaaryameva cha. That by which one incorrectly understands Dharma and Adharma. 30. That which hurls you into the abyss of ignorance is Adharma. O Arjuna! Pravrittim cha nivrittim cha karyaakaarye bhayaabhaye. despair and also conceit—that firmness. arising from sleep. Parinaame vishamiva tatsukham raajasam smritam. Abhyaasaadramate yatra duhkhaantam cha nigacchati. Na vimunchati durmedhaa dhritih saa paartha taamasee. 39. Sattwam prakritijairmuktam yadebhih syaat tribhirgunaih. one holds fast to Dharma. Tatsukham saattwikam proktam aatmabuddhiprasaadajam. which is at first like nectar and in the end like poison—that is declared to be Rajasic. 37. enjoyment of pleasures and earning of wealth—that firmness. But that firmness. is Rajasic! Yayaa swapnam bhayam shokam vishaadam madameva cha. That pleasure which arises from the contact of the sense-organs with the objects. Braahmanakshatriyavishaam shoodraanaam cha parantapa. O Arjuna. born of the purity of one’s own mind due to Self-realisation. 36. That which is like poison at first but in the end like nectar—that pleasure is declared to be Sattwic. indolence and heedlessness—such a pleasure is declared to be Tamasic. is Tamasic! Sukham twidaaneem trividham shrinu me bharatarshabha. fear. by which. 40. O Arjuna. of the threefold pleasure. 34. Nidraalasyapramaadottham tattaamasamudaahritam. Yadagre chaanubandhe cha sukham mohanamaatmanah. Prasangena phalaakaangkshee dhritih saa paartha raajasee. Vishayendriya samyogaad yattadagre’mritopamam. 130 . That by which a stupid man does not abandon sleep. on account of attachment and desire for reward. That pleasure which at first and in the sequel is delusive of the self. O Arjuna. 35. O Arjuna. Na tadasti prithivyaam vaa divi deveshu vaa punah.THE YOGA OF LIBERATION BY RENUNCIATION Yayaa tu dharmakaamaarthaan dhrityaa dhaarayate’rjuna. There is no being on earth or again in heaven among the gods that is liberated from the three qualities born of Nature. grief. Karmaani pravibhaktaani swabhaavaprabhavairgunaih. in which one rejoices by practice and surely comes to the end of pain! Yattadagre vishamiva parinaame’mritopamam. Now hear from Me. 38. Swe swe karmanyabhiratah samsiddhim labhate narah. he becomes qualified for the dawn of Self-knowledge. devoted to his own duty. the duties are distributed according to the qualities born of their own nature! Shamo damastapah shaucham kshaantiraarjavameva cha. that is. worshipping Him with his own duty. hear now. 45. born of (their own) nature. Swakarmanaa tamabhyarchya siddhim vindati maanavah. 47. 46. Krishigaurakshyavaanijyam vaishyakarma swabhaavajam. Shreyaanswadharmo vigunah paradharmaat swanushthitaat. splendour. born of (their own) nature. How he attains perfection while being engaged in his own duty. Of Brahmanas. 43. O Arjuna. Agriculture. He from whom all the beings have evolved and by whom all this is pervaded. Jnaanam vijnaanam aastikyam brahmakarma swabhaavajam. Daanameeshwarabhaavashcha kshaatram karmaswabhaavajam. Yatah pravrittirbhootaanaam yena sarvamidam tatam. forgiveness and also uprightness. attains perfection. 42. dexterity and also not fleeing from battle. his heart gets purified and he goes to heaven. Serenity. Paricharyaatmakam karma shoodrasyaapi swabhaavajam. purity. Better is one’s own duty (though) destitute of merits. man attains perfection. Prowess. knowledge. 44. COMMENTARY: Man attains perfection by worshipping the Lord through the performance of his own duty. Kshatriyas and Vaishyas. born of (their own) nature. self-restraint. Shauryam tejo dhritirdaakshyam yuddhe chaapyapalaayanam. Each man. COMMENTARY: When a man does his duties rightly according to his order of life. Swabhaavaniyatam karma kurvannaapnoti kilbisham. cattle-rearing and trade are the duties of the Vaishya (merchant class). Swakarmaniratah siddhim yathaa vindati tacchrinu. as also the Sudras. 131 . firmness. than the duty of another well performed. austerity. He who does the duty ordained by his own nature incurs no sin. realisation and belief in God are the duties of the Brahmanas. born of (their own) nature. generosity and lordliness are the duties of Kshatriyas.BHAGAVAD GITA 41. and action consisting of service is the duty of the Sudra (servant class). Brahmabhootah prasannaatmaa na shochati na kaangkshati. Samaasenaiva kaunteya nishthaa jnaanasya yaa paraa. O Arjuna. Sarvaarambhaa hi doshena dhoomenaagnirivaavritaah. Dwelling in solitude. from whom desire has fled. relinquishing sound and other objects and abandoning both hatred and attraction.—he by renunciation attains the supreme state of freedom from action. controlling the self by firmness. Having abandoned egoism. all undertakings are enveloped by evil. as fire by smoke! Asaktabuddhih sarvatra jitaatmaa vigatasprihah. anger. though faulty. Viviktasevee laghwaashee yatavaakkaayamaanasah. 54. 52. strength. O Arjuna. for. he neither grieves nor desires. who has subdued his self. Dhyaanayogaparo nityam vairaagyam samupaashritah. Siddhim praapto yathaa brahma tathaapnoti nibodha me. Samah sarveshu bhooteshu madbhaktim labhate paraam. serene in the Self. Naishkarmyasiddhim paramaam sannyaasenaadhigacchati. that supreme state of knowledge. Becoming Brahman. Vimuchya nirmamah shaanto brahmabhooyaaya kalpate. 48. 132 . 53. Endowed with a pure intellect. Tato maam tattwato jnaatwaa vishate tadanantaram. he attains supreme devotion unto Me. arrogance. always engaged in concentration and meditation..—he is fit for becoming Brahman. 51. body and mind subdued. Learn from Me in brief. 49. taking refuge in dispassion. One should not abandon. Ahankaaram balam darpam kaamam krodham parigraham. desire. eating but little. He whose intellect is unattached everywhere. Bhaktyaa maamabhijaanaati yaavaanyashchaasmi tattwatah. how he who has attained perfection reaches Brahman. free from the notion of “mine” and peaceful.THE YOGA OF LIBERATION BY RENUNCIATION Sahajam karma kaunteya sadoshamapi na tyajet. 50. the duty to which one is born. with speech. the same to all beings. and covetousness. Eeshwarah sarvabhootaanaam hriddeshe’rjuna tishthati. 60. he forthwith enters into the Supreme. thou shalt by My Grace overcome all obstacles. Nature will compel thee. 59. by His illusive power. Doing all actions always. that which from delusion thou wishest not to do. Mentally renouncing all actions in Me. Bhraamayan sarvabhootaani yantraaroodhaani maayayaa. Kartum necchasi yanmohaat karishyasyavasho’pi tat. Atha chet twam ahankaaraan na shroshyasi vinangkshyasi. even that thou shalt do helplessly! COMMENTARY: Thou wilt be forced to fight because of thy nature. 56. indestructible state or abode. thou shalt perish. vain is this.BHAGAVAD GITA 55. 133 . Sarvakarmaanyapi sadaa kurvaano madvyapaashrayah. Fixing thy mind on Me. The Lord dwells in the hearts of all beings. bound by thy own Karma (action) born of thy own nature. and knowing Me in truth. having Me as the highest goal. but if from egoism thou wilt not hear Me. resorting to the Yoga of discrimination do thou ever fix thy mind on Me. Chetasaa sarvakarmaani mayi sannyasya matparah. O Arjuna. Yadahankaaram aashritya na yotsya iti manyase. filled with egoism. 58. 57.. If. O Arjuna. By devotion he knows Me in truth. Matprasaadaadavaapnoti shaashwatam padamavyayam. Mithyaisha vyavasaayaste prakritistwaam niyokshyati. causing all beings. thou thinkest: “I will not fight”. 61. Buddhiyogam upaashritya macchittah satatam bhava. Macchittah sarvadurgaani matprasaadaat tarishyasi. much against thy will. what and who I am. by My Grace he obtains the eternal. thy resolve. It will compel thee to fight. Swabhaavajena kaunteya nibaddhah swena karmanaa. taking refuge in Me. Fix thy mind on Me. Nor is there any among men who does dearer service to Me. 63. 67. Fly unto Him for refuge with all thy being. 65. most secret of all. truly do I promise unto thee. I will liberate thee from all sins. having reflected over it fully. then act thou as thou wishest. I will tell thee what is good. Na chaashushrooshave vaachyam na cha maam yo’bhyasooyati. grieve not. nor to one who does not render service. Idam te naatapaskaaya naabhaktaaya kadaachana. 134 . Hear thou again My supreme word. Vimrishyaitadasheshena yathecchasi tathaa kuru. bow down to Me. Abandoning all duties. Maamevaishyasi satyam te pratijaane priyo’si me. Sarvadharmaan parityajya maamekam sharanam vraja. Bhaktim mayi paraam kritwaa maamevaishyatyasamshayah. (for) thou art dear to Me. Aham twaa sarvapaapebhyo mokshayishyaami maa shuchah. Iti te jnaanamaakhyaatam guhyaad guhyataram mayaa. Thus has wisdom more secret than secrecy itself been declared unto thee by Me. 68. Sarvaguhyatamam bhooyah shrinu me paramam vachah. sacrifice to Me. O Arjuna! By His Grace thou shalt obtain supreme peace and the eternal abode. because thou art dearly beloved of Me. nor who does not desire to listen. This is never to be spoken by thee to one who is devoid of austerities. Ya imam paramam guhyam madbhakteshvabhidhaasyati. Bhavitaa na cha me tasmaadanyah priyataro bhuvi. Thou shalt come even to Me. 66. 64.THE YOGA OF LIBERATION BY RENUNCIATION 62. Na cha tasmaanmanushyeshu kashchinme priyakrittamah. 69. be devoted to Me. He who with supreme devotion to Me will teach this supreme secret to My devotees. shall doubtless come to Me. nor to one who cavils at Me. take refuge in Me alone. to one who is not devoted. nor shall there be another on earth dearer to Me than he. Ishto’si me dridhamiti tato vakshyaami te hitam. Manmanaa bhava madbhakto madyaajee maam namaskuru. In the present generation. such is My conviction. Kacchid ajnaanasammohah pranashtaste dhananjaya. Sthito’smi gata sandehah karishye vachanam tava. 135 . Through the Grace of Vyasa I have heard this supreme and most secret Yoga direct from Krishna.BHAGAVAD GITA COMMENTARY: He who hands down this Gita to My devotees does immense service to Me. shall attain to the happy worlds of those of righteous deeds. Adhyeshyate cha ya imam dharmyam samvaadamaavayoh. Kacchid etacchrutam paartha twayaikaagrena chetasaa. 70. Arjuna said: 73. So’pi muktah shubhaamllokaan praapnuyaat punyakarmanaam. He is extremely dear to Me. Destroyed is my delusion as I have gained my memory (knowledge) through Thy Grace. Yogam yogeshwaraat krishnaat saakshaat kathayatah swayam. And he who will study this sacred dialogue of ours. 72. Shraddhaavaan anasooyashcha shrinuyaadapi yo narah. nor shall there be in the future also. liberated. I will act according to Thy word. too. Samvaadam imam ashrausham adbhutam romaharshanam. with one-pointed mind? Has the delusion of thy ignorance been fully destroyed. Vyaasaprasaadaacchrutavaan etadguhyamaham param. O Dhananjaya? Arjuna Uvaacha: Nashto mohah smritirlabdhaa twatprasaadaanmayaachyuta. he. full of faith and free from malice. by him I shall have been worshipped by the sacrifice of wisdom. Sanjaya said: 74. Sanjaya Uvaacha: Ityaham vaasudevasya paarthasya cha mahaatmanah. my doubts are gone. which causes the hair to stand on end. The man also who hears this. O Arjuna. the Lord of Yoga Himself declaring it. 71. Has this been heard. 75. O Krishna! I am firm. Thus have I heard this wonderful dialogue between Krishna and the high-souled Arjuna. Jnaanayajnena tenaaham ishtah syaamiti me matih. there will be none dearer to Me in the world. the scripture of Yoga. happiness. Keshavaarjunayoh punyam hrishyaami cha muhurmuhuh. the science of the Eternal. Wherever there is Krishna. I rejoice again and again! Taccha samsmritya samsmritya roopamatyadbhutam hareh. the Lord of Yoga. wherever there is Arjuna. And remembering again and again also that most wonderful form of Hari. the archer. Vismayo me mahaan raajan hrishyaami cha punah punah. O King! And I rejoice again and again! Yatra yogeshwarah krishno yatra paartho dhanurdharah.THE YOGA OF LIBERATION BY RENUNCIATION Raajan samsmritya samsmritya samvaadam imam adbhutam. victory and firm policy. there are prosperity. 78. Tatra shreervijayo bhootirdhruvaa neetirmatirmama. ends the eighteenth discourse entitled: “The Yoga of Liberation by Renunciation” Om Shanti! Shanti! Shanti! 136 . 76.. 77. remembering this wonderful and holy dialogue between Krishna and Arjuna. the dialogue between Sri Krishna and Arjuna. great is my wonder. such is my conviction. O King.
https://www.scribd.com/doc/50954702/bhagavad-gita
CC-MAIN-2017-34
refinedweb
44,330
63.56
This projects is about an small easy to use seven segment display. The disdplay is controlled by a 8-bit shift register. Rev2 and higher displays are chainable, so you can get multi segment display. Beside the Hardware there is also a Software part in this project. This software part is shared with a very similar project ( #µ7 ), wich is very similar (shrunken down version of tny7's rev1) but to to differnt to handle it as the same project. Hardware There is nothing special about the Hardware: on the ISP header you have access to three IOs of the micro controller. These are connected to shift-register, which drives the Leds. The PCB should be small. So it can be used quick and easy. So I ended with this, after some hours of routing: The used seven segment displays have a very clever pin out (this pin out is also very conmen, so nothing special): The common ground pin are in the middle. You can mount the display on both sides of the PCB and only the order of the segments changes. This could be reversed in software. In the second revision two pin headers on both sides of the PCB got added. With these pin headers you can solder two (or more) PCBs together to get a two digit display. so you can create multiple digit displays. In revision 2.1 there is beside some minor changed an SMD solder jumper added. with this solder Jumper you can connect the common pins of the display to GND or Vcc. So common anode or common cathode display can be used. The library is also updated to use this option. Hardware files (eagle) are availible in the bitbucked reposetory. Software There is a working Arduino library available (see Bitbucket). With this you can control one or more displays. The plain C library is not ready yet. Using the Arduino Library To use the Arduino Library you have to include it first. Additionally you have to create an tiny7 object: #include <tiny7.h> tiny7 myTiny7;In your setup you have to use the function .begin() this is the prototype of the function: void begin(char inLength=1, // length of chain char inInvert=0, // display orientation char commonPin= T7_CC, // common cathode/anode char inSDO=127, // MOSI pin char inSCK=127, // SCK pin char inLatch=127); // MISO pin (used for the latch)None of the Parameters are needed if using only one tiny7, normal display mount, normal Arduino and common cathode display. So is could look like: myTiny7.begin(); //setup for one tiny7 The other parameters of begin can be used to use for additional configuration if needed. Now you can use your display by using the .print() function. For example like this: myTiny7.print("H");There is also an .printf() Function availible. This is very usefull for display values with an unit on bigger displays. For example you can do this: with this function call: myTiny7.printf("%d`C",21); More examples can be found in the library! Tested devices I did test test the library and the tiny7 with the following devices: - Arduino Nano with ATmega 328p - ESP8266 development board ( #ESP8266 (ESP-07/12) Dev Board ) - ATtiny 85 ( used as Trinket) - Arduino Mega2560 with ATmega 2560 It should work on all board which are using the Arduino IDE. The pins used by the tiny7 library can be changed in the .begin() function. Used Tools and Software Cadsoft, Egale 7.2 Freeware for circuit an PCB Jerome Lamy, egleUp for the 3D images (freeware) ImageMagick Studio LLC, ImageMagick used by eagleUp (open source, Apache 2.0) Trimble Navigation, SktechUp Make for the 3D images Arduino IDE Notepad++ v6.4.2 GIMP 2.8 Credits First I would like to thank to everyone who write comment, following this project or gave a skull. Specially @Stefan Lochbrunner who had the idea of dais chain multiple displays. I would also thanks @WooDWorkeR. With him I did have an inspired taslk about how to mechanical strengthen the connection between multiple displays. I am still thinking about which one would be the best. Hot Glue? Foame tape? soldering massive wires on it? or maybe some other? I do not know yet., but I like hot...Read more » [verified: no design files missing]
https://hackaday.io/project/6568-tiny7/discussion-31193
CC-MAIN-2019-43
refinedweb
715
75.3
Chatbots are the future of this generation and those are capable enough to understand what we say and to respond accordingly. Also, those can work as an assistant for us just like Google Assistant and Alexa. To work as an intelligent assistant, chatbots understand us and help us with our work by taking actions, but how do they do it. So, this what exactly you will learn in this blog and after completing this blog you will be able to make your bot do it for you. So, let’s get started and learn how to do it. Introduction In this blog, you will learn, - What packages are required to handle API? - How to call an API in python - How to call weather API in rasa chatbot. Firstly, let’s understand what is an API. API or Application Programming Interface is a software intermediary that allows two applications to communicate with each other. Whenever you are using an application like Facebook or Instagram or twitter to send instant messages or checking the weather on your smartphone, you’re using an API. In other words, your application is capable of taking action to help you instantly connect to your loved ones. Now, let’s understand how to use and call an API in python. You will use the package name “requests”, that is capable of handling the requests from any API. It fetches and updates the data with the GET/POST methods respectively. Installation So firstly you have to install the request package in your current rasa environment so that we can implement the calling of weather API in rasa chatbot. To install it enter the following command in the terminal: $ pip install requests This will install the requests package in the rasa environment and then you can call an API. In this blog you will use the weather API, to understand the concept. Code Here is the script for calling weather API with the name weather.py that will implement this task, weather.py import requests def Weather(city): api_address=' url = api_address + city json_data = requests.get(url).json() format_add = json_data['main'] print(format_add) return format_add To see it’s practical implementation check this, In this code above, you can see firstly requests module is imported. Then, we have created a function that takes an argument from the user as a “city” name to check the weather as per the city entered by the user. Inside the function, there is a variable with name api_address which holds the weather API in string format without the city name so that you can modify the API according to the city that the user wants to check for. After that here comes the main functionality of the requests module that you have installed here. When you have the complete API with the city name added to it, you can send a get request to this API to fetch the data in json format. To do that we used, json_data = requests.get(url).json() if JSON is a new term for you, then to understand it considers the data stored in a dictionary in python programming. JSON stores the data in the same way as the dictionary does. When you will have fetched the data from this API then you can slice the data that you require. In our case we will fetch the data with respect to key ‘main’, as the values corresponding to the weather will be stored here so we have used, format_add = json_data['main'] At last this will return the data with, return format_add So, this is the complete script for calling the weather API. Now, it’s time to integrate this script with rasa chatbot to call it from the actions file with respect to the city entered by the user. First of all, build a basic chatbot on your system to have a small conversation with the chatbot to ask for the weather via weather API. Build your Weather assistant If you are new to rasa chatbot and don’t know how to build one the click here and build your first chatbot in an easy way. But if you already know how to build one you can directly check this link and get the complete code to get started. Download Weather API Assistant Full Code When you have your basic weather assistant chatbot ready with you. Now you can understand how to call the function that you have created above to call an API in actions.py. To do that add this code to your actions.py file, from typing import Any, Text, Dict, List from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from weather import Weather class ActionHelloWorld(Action): def name(self) -> Text: return "action_weather_api" def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: city=tracker.latest_message['text'] temp=int(Weather(city)['temp']-273) dispatcher.utter_template("utter_temp", tracker,temp=temp) return [] Here, what exactly we are doing. Your chatbot is asking the user to enter the city name for which the user wants to check the weather by calling the weather API. When the user will enter the value your chatbot will be able to read this text and to further use this city name to find the weather of your city by calling the weather API, city=tracker.latest_message['text'] temp=int(Weather(city)['temp']-273) This will give you the temperature value of the entered city name and accordingly you can reply to the user with this value using, dispatcher.utter_template("utter_temp",tracker,temp=temp) This will call the utter_temp action from the domain file with the temperature value fetched by calling the weather API. Here, are the updated domain, nlu, and the stories file where you have to make the changes. nlu.md ## intent: weather - what's the weather - i want to know the weather of today - tell me the weather forcast - hows the weather today ## intent: city - Delhi - delhi - chandigarh - mohali - mumbai - jaipur domain.yml templates: utter_city: - text: "which city you want to check for?" utter_temp: - text: "Today's temperature is {temp} degree Celcius." actions: - utter_city - utter_temp - action_weather_api intents: - weather - city stories.md ## happy weather * greet - utter_greet * weather - utter_city * city - action_weather_api To see the practical implementation check this After these updations in the file, train the model and run rasa shell, $ rasa train && rasa shell –debug or $ rasa train && rasa x parallelly run the actions server in new terminal, $ rasa run actions If everything goes right then you will be able to see the output like this, Time to wrap up now. Hope you liked our content on How to integrate weather API. 😉
https://innovationyourself.com/calling-weather-api-in-rasa/
CC-MAIN-2022-21
refinedweb
1,108
59.43
/* * java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; /** * A Proxy stream which acts as expected, that is it passes the method * calls on to the proxied stream and doesn't change which methods are * being called. * <p> * It is an alternative base class to FilterInputStream * to increase reusability, because FilterInputStream changes the * methods being called, such as read(byte[]) to read(byte[], int, int). * See the protected methods for ways in which a subclass can easily decorate * a stream with custom pre-, post- or error processing functionality. * @version $Id: ProxyInputStream.java 1415850 2012-11-30 20:51:39Z ggregory $ public abstract class ProxyInputStream extends FilterInputStream { /** * Constructs a new ProxyInputStream. * * @param proxy the InputStream to delegate to */ public ProxyInputStream(final InputStream proxy) { super(proxy); // the proxy is stored in a protected superclass variable named 'in' } * Invokes the delegate's <code>read()</code> method. * @return the byte read or -1 if the end of stream * @throws IOException if an I/O error occurs @Override public int read() throws IOException { try { beforeRead(1); final int b = in.read(); afterRead(b != -1 ? 1 : -1); return b; } catch (final IOException e) { handleIOException(e); return -1; } * Invokes the delegate's <code>read(byte[])</code> method. * @param bts the buffer to read the bytes into * @return the number of bytes read or -1 if the end of stream public int read(final byte[] bts) throws IOException { beforeRead(bts != null ? bts.length : 0); final int n = in.read(bts); afterRead(n); return n; * Invokes the delegate's <code>read(byte[], int, int)</code> method. * @param off The start offset * @param len The number of bytes to read public int read(final byte[] bts, final int off, final int len) throws IOException { beforeRead(len); final int n = in.read(bts, off, len); * Invokes the delegate's <code>skip(long)</code> method. * @param ln the number of bytes to skip * @return the actual number of bytes skipped public long skip(final long ln) throws IOException { return in.skip(ln); return 0; * Invokes the delegate's <code>available()</code> method. * @return the number of available bytes public int available() throws IOException { return super.available(); * Invokes the delegate's <code>close()</code> method. public void close() throws IOException { in.close(); * Invokes the delegate's <code>mark(int)</code> method. * @param readlimit read ahead limit public synchronized void mark(final int readlimit) { in.mark(readlimit); * bytes that the caller wanted to read (1 for the {@link #read()} * method, buffer length for {@link #read(byte[])},. * @since 2.0 * @param n number of bytes that the caller asked to be read * @throws IOException if the pre-processing fails protected void beforeRead(final int n) throws IOException { * Invoked by the read methods after the proxied call has returned * successfully. The number of bytes returned to the caller (or -1 if * the end of stream was reached) is given as an argument. * Subclasses can override this method to add common post-processing * you want to add post-processing steps also to them. * @param n number of bytes; }
http://commons.apache.org/proper/commons-io/cobertura/org.apache.commons.io.input.ProxyInputStream.html
CC-MAIN-2013-20
refinedweb
503
55.24
Code. Collaborate. Organize. No Limits. Try it Today. Here’s an approach I've used a few times to consume similar APIs into an application. A gateway of sorts, if you will. I'll try and keep it as brief and simple as possible. Having a look at the sample code will help you along as well. I also assume that you know something about Reflection and Web services. Well (hypothetically, of course), imagine you get a third party payment solution that only accepts Visa cards. OK, you've implemented the Visa payment provider. Now, some of your customers would want to pay with MasterCard. And, you'd suspect that someone down the track would like to use Amex as well. You would be able to add every payment provider into your code as you need, but this will get messy very quickly. Whereas, loosely coupled API wrappers (proxy wrappers, in this example) in a “gateway” will allow you to add and remove payment providers as you please. Even add some business logic that will decide which provider is the cheapest for your users... So, if you'd implemented a “gateway” from the start, adding new payment providers through the duration of your application life is a breeze, well, a lot easier and cleaner at least. Here’s a quick example of creating an API gateway. I've used two web services in this example, but libraries can be plugged-in in a similar way. Looking at the image above, I'll briefly go though the entities of the solution. I'll be focusing mainly on the Gateway and API 1 and 2 entities. I am going to go through the gateway first and then the API wrappers, and after that, I'll explain how it all hooks up. The interface is the part that really gets the gateway together. As shown in the image above, the Gateway and API wrappers both implement the interface. So, let's whack one together. In my example, I created IGateway: IGateway public interface IGateway { bool ValidateUser(Userobj user); string GetUserAddress(Userobj user); } I'm using Reflection in the gateway to call the API wrappers. By implementing an interface, we'd know exactly what method to call, parameters to pass down, and what to expect in return. In this example, I want to validate a user and get his address. Now that we have defined what we need, we can define our interface. Let's add it to the gateway. public class Gateway: IGateway { IGateway proxy; public Gateway(String dllNamePath) { LoadIGhostAssembly(dllNamePath); } void LoadIGhostAssembly(String dllNamePath) { Assembly asm = Assembly.LoadFrom(dllNamePath); Type[] typesInAssembly = asm.GetTypes(); foreach(Type t in typesInAssembly) { if (t.GetInterface(typeof(IGateway).FullName) != null) { proxy = (IGateway)Activator.CreateInstance(t); } } } //IGateway Members public bool ValidateUser(Userobj user) { return proxy.ValidateUser(user); } public string GetUserAddress(Userobj user) { try { return proxy.GetUserAddress(user); } catch { return "Facility doesn't exist"; } } } LoadIGhostAssembly is where we get the correct API wrapper to call. My business logic will pass down the Visa or Mastercard library location, depending on which one you want to use. As shown in the diagram above, the API wrappers also implement the IGhost interface. We will instantiate the correct reference and create a direct mapping to the API wrapper's interface methods. LoadIGhostAssembly IGhost I've created a new library and added a class that implements my interface. Now, I will consume my desired web service (called WebServiceMasterCard and WebServiceVisa in the sample code), and match it to my interface methods. WebServiceMasterCard WebServiceVisa public class Proxy : Global.IGateway { #region IGateway Members public bool ValidateUser(Global.Userobj user) { try { ProxyWebServiceVisa.localhost.Service1 apiProxy = new ProxyWebServiceVisa.localhost.Service1(); return apiProxy.CheckUser(user.UserID); } catch { return false; } } public string GetUserAddress(Global.Userobj user) { ProxyWebServiceVisa.localhost.Service1 apiProxy = new ProxyWebServiceVisa.localhost.Service1(); return apiProxy.UserAddress(user.UserID, user.FirstName, user.LastName); } #endregion } Repeat this for every payment provider you want to add to your gateway. This is how I would call the gateway from my application: UserGateway.Gateway gateway = new UserGateway.Gateway("c:\\temp\\ProxyWebServiceMasterCard.dll"); gateway.ValidateUser(user) gateway.GetUserAddress(user) As you can see, I call the gateway and pass down the desired service I need. As long as all the API wrappers have implemented the proper interface, you can add as many as you wish, even take some out. I hardcoded the location of the library, but I usually add it to an XML, database or common directory, so the code wouldn't need to be recompiled every time I need to add a service to the gateway. Once you've specified the library you want to use, the gateway will create an instance of it by using Reflection, and with the method mapping, you can call any method you desire. And presto, create as many API wrappers as you wish, as long as they implement your interface and your gateway will recognise them. Update: This is also an example of the Proxy Pattern implementation, which I unknowingly implemented at the time of conception. Please look at Proxy Patterns for more details. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) stixoffire wrote:So all I really need I think for such system is to have a Payment provider for each API that I might use .. am I correct in my thinking ? Or do I just use one "provider" and an interface to the API's ? Is this what you are getting at ??? stixoffire wrote:I see you use reflection - I am not sure why and what that accomplishes for you ? I know reflection uses a lot more horsepower to run (performance). Johan "BJ" Vorster wrote:I assume you're in Aus or NZ. Johan "BJ" Vorster wrote:What sort of API has ANZ giving with the MIGS solution? Johan "BJ" Vorster wrote:Are you going to use more than one solution? Johan "BJ" Vorster wrote:Enjoy the hot weather Manu!! Johan "BJ" Vorster wrote:It's cold here! Johan "BJ" Vorster wrote:Rather then searching for MiGS, search for "payment solutions" or "online payment solutions providers". Johan "BJ" Vorster wrote:Have you thought about delivery service for your solution? Johan "BJ" Vorster wrote:it snowed here last night, so not the best place to be General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/30025/A-Simple-Gateway-Proxy-Pattern?msg=2788927
CC-MAIN-2014-23
refinedweb
1,080
57.57
(PHP 4 >= 4.0.5, PHP 5)preg_replace_callback -- Perform a regular expression search and replace using a callback The behavior of this function is almost identical to preg_replace(), except for the fact that instead of replacement parameter, one should specify a callback. pattern The pattern to search for. It can be either a string or an array with strings. callback A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. You'll often need the callback function for a preg_replace_callback() in just one place. In this case you can use create_function() to declare an anonymous function as callback within the call to preg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else. subject The string or an array with strings to search and replace. limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit). count If specified, this variable will be filled with the number of replacements done. preg_replace_callback() returns an array if the subject parameter is an array, or a string otherwise. If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.
http://idlebox.net/2007/apidocs/php-manual-20070505.zip/function.preg-replace-callback.html
CC-MAIN-2014-15
refinedweb
223
65.22
. 31 High 30 Power Fail 29 Inter-processor Interrupt 28 Clock 27 Profile/Synch 26 Device n … 5 CMCI 4 3 Device 1 2 DPC/Dispatch 1 APC 0 Passive. 3: kd> k= 91aeca40 91aec954 82b29431 91aeca40 82b2aef1 nt!MiFreePoolPages+0x42c. Hello Hi debuggers, this is Graham McIntyre again. These days I’m working more closely with hardware so I thought I’d share some hardware related debugging tips. I recently debugged an issue where a PCI-E storage device failed to work after hot swapping it from one slot to another slot on the system without rebooting. We determined the issue was due to the device not receiving interrupts once it was moved. So in the process I learned how line based interrupts are routed to a particular PCI slot. Interrupt routing is quite a hefty subject, but here’s one example of how to determine what the expected interrupt line is for a particular PCI-E slot using a live kernel debug. There are two ways the routing can be defined in the ACPI tables: Since APIC is much more common, I am focusing on method 1 for static routing. Though, it is legal to use Link Node routing with IOAPICs, it’s not common, so I am omitting how to parse that. This is also specifically for devices that use physical line based interrupts (LBI), not Message Signaled Interrupts (MSI). Here is the general method for determining the static routing IRQ for a particular device: Here’s the in-depth steps, along with an example: Step 1: Locate the devstack for the device, and determine its parent devices in the PCI hierarchy. To determine this, use !pcitree to dump the PCI hierarchy. Then locate your device by ven/dev ID. You could also use !devnode to dump the hierarchy. The way !pcitree shows the hierarchy may be a little confusing. When it encounters a PCI bridge, it dumps the child buses under the bridge. The indenting tells you what bus a device is on. A device is always indented one level from the entry of the parent bus. In my case, I know the device I'm interested in is VEN FEFE DEV 1550. kd> !pcitree Bus 0x0 (FDO Ext fffffa80053efe00) (d=0, f=0) 80863406 devext 0xfffffa80054d51b0 devstack 0xfffffa80054d5060 0600 Bridge/HOST to PCI (d=1, f=0) 80863408 devext 0xfffffa80054d9b70 devstack 0xfffffa80054d9a20 0604 Bridge/PCI to PCI Bus 0x1 (FDO Ext fffffa80054e8680) (d=0, f=0) 14e41639 devext 0xfffffa80051b91b0 devstack 0xfffffa80051b9060 0200 Network Controller/Ethernet (d=0, f=1) 14e41639 devext 0xfffffa80051ba1b0 devstack 0xfffffa80051ba060 0200 Network Controller/Ethernet (d=3, f=0) 8086340a devext 0xfffffa80054dab70 devstack 0xfffffa80054daa20 0604 Bridge/PCI to PCI Bus 0x2 (FDO Ext fffffa80054e9460) (d=0, f=0) 14e41639 devext 0xfffffa80051bcb70 devstack 0xfffffa80051bca20 0200 Network Controller/Ethernet (d=0, f=1) 14e41639 devext 0xfffffa80051cab70 devstack 0xfffffa80051caa20 0200 Network Controller/Ethernet (d=4, f=0) 8086340b devext 0xfffffa80054dbb70 devstack 0xfffffa80054dba20 0604 Bridge/PCI to PCI Bus 0x3 (FDO Ext fffffa80054ec190) (d=0, f=0) 10000079 devext 0xfffffa80051cd1b0 devstack 0xfffffa80051cd060 0104 Mass Storage Controller/RAID (d=5, f=0) 8086340c devext 0xfffffa80054dcb70 devstack 0xfffffa80054dca20 0604 Bridge/PCI to PCI Bus 0x4 (FDO Ext fffffa80054ede00) No devices have been enumerated on this bus. (d=6, f=0) 8086340d devext 0xfffffa80054ddb70 devstack 0xfffffa80054dda20 0604 Bridge/PCI to PCI Bus 0x5 (FDO Ext fffffa80054ee9c0) (d=7, f=0) 8086340e devext 0xfffffa80054deb70 devstack 0xfffffa80054dea20 0604 Bridge/PCI to PCI << Root Port Bus 0x6 (FDO Ext fffffa80054f1190) (d=0, f=0) abcd8632 devext 0xfffffa80051d91b0 devstack 0xfffffa80051d9060 0604 Bridge/PCI to PCI << Upstream switch port Bus 0x7 (FDO Ext fffffa80051cd850) (d=4, f=0) abcd8632 devext 0xfffffa80051d71b0 devstack 0xfffffa80051d7060 0604 Bridge/PCI to PCI Bus 0x8 (FDO Ext fffffa8006f44ac0) No devices have been enumerated on this bus. (d=5, f=0) abcd8632 devext 0xfffffa80058d6a10 devstack 0xfffffa80058d68c0 0604 Bridge/PCI to PCI Bus 0x9 (FDO Ext fffffa80051ba850) (d=6, f=0) abcd8632 devext 0xfffffa8007075b70 devstack 0xfffffa8007075a20 0604 Bridge/PCI to PCI << Parent PDO (Downstream Switch Port) Bus 0xa (FDO Ext fffffa8007312b60) (d=0, f=0) fefe1550 devext 0xfffffa8006f67b70 devstack 0xfffffa8006f67a20 0180 Mass Storage Controller/'Other' << Device (d=7, f=0) abcd8632 devext 0xfffffa80051e5b70 devstack 0xfffffa80051e5a20 0604 Bridge/PCI to PCI Bus 0xb (FDO Ext fffffa80052d2e00) (d=14, f=0) 8086342e devext 0xfffffa80054dfb70 devstack 0xfffffa80054dfa20 0800 Base System Device/Interrupt Controller (d=14, f=1) 80863422 devext 0xfffffa80054e0b70 devstack 0xfffffa80054e0a20 0800 Base System Device/Interrupt Controller (d=14, f=2) 80863423 devext 0xfffffa80054e1b70 devstack 0xfffffa80054e1a20 0800 Base System Device/Interrupt Controller (d=1a, f=0) 80862937 devext 0xfffffa80054e2b70 devstack 0xfffffa80054e2a20 0c03 Serial Bus Controller/USB (d=1a, f=1) 80862938 devext 0xfffffa80054e31b0 devstack 0xfffffa80054e3060 0c03 Serial Bus Controller/USB (d=1a, f=7) 8086293c devext 0xfffffa80054e3b70 devstack 0xfffffa80054e3a20 0c03 Serial Bus Controller/USB (d=1d, f=0) 80862934 devext 0xfffffa80054e41b0 devstack 0xfffffa80054e4060 0c03 Serial Bus Controller/USB (d=1d, f=1) 80862935 devext 0xfffffa80054e4b70 devstack 0xfffffa80054e4a20 0c03 Serial Bus Controller/USB (d=1d, f=7) 8086293a devext 0xfffffa80054e51b0 devstack 0xfffffa80054e5060 0c03 Serial Bus Controller/USB (d=1e, f=0) 8086244e devext 0xfffffa80054e5b70 devstack 0xfffffa80054e5a20 0604 Bridge/PCI to PCI Bus 0xc (FDO Ext fffffa80054f2e00) (d=3, f=0) 102b0532 devext 0xfffffa80051d51b0 devstack 0xfffffa80051d5060 0300 Display Controller/VGA (d=1f, f=0) 80862918 devext 0xfffffa80054e61b0 devstack 0xfffffa80054e6060 0601 Bridge/PCI to ISA (d=1f, f=2) 80862921 devext 0xfffffa80054e6b70 devstack 0xfffffa80054e6a20 0101 Mass Storage Controller/IDE Total PCI Root busses processed = 1 Total PCI Segments processed = 1 To recap the devices in the tree (Bus,Device,Function): (0,7,0) : Root Port, PCI-PCI Bridge (devstack 0xfffffa80054dea20) (6,0,0) : Upstream Switch Port (devstack 0xfffffa80051d9060) (7,6,0) : Downstream Switch Port (the PDO for the slot) (devstack 0xfffffa8007075a20) (a,0,0) : Device (devstack 0xfffffa8006f67a20) I scanned the output looking for my ven/dev ID, and found it at Bus A, Device 0, Function 0. Step 2: Determine which interrupt pin the device uses. For this step, you can use !pci to dump the PCI config space for the device. The output will show you the interrupt pin the device uses, labeled as IntPin. !pci 1 a 0 0 PCI Bus 10 00:0 FEFE:1550.01 Cmd[0007:imb...] Sts[0018:c....] Device SubID:1344:1008 Other mass storage controller cf8:800a0000 IntPin:1 IntLine:2e Rom:0 cis:0 cap:40 MEM[2]:df5fd000 MEM[3]:df5fc000 IO[4]:cff1 MEM[5]:df5fe000 So our IntPin is 1. Step 3: Walk the parent devices to find the closest PCI Routing Table (_PRT) which will describe the mapping of interrupt pin to IRQ. Now, we will traverse the parent PCI devnodes until we find a PCI bridge which has an associated ACPI object with a _PRT method. This may be the root port, or an integrated bridge. Example: First, we’ll swizzle the pin of the device itself (a,0,0). The IntPin is 1 so: IntPin = ((((1-1)+0) % 4) +1) << The Swizzled Pin is still IntPin 1 Next, I dumped the parent device (7,6,0), !devstack 0xfffffa8007075a20. It didn’t have an ACPI filter driver on the stack. So I need to swizzle the pin. IntPin = ((((1-1)+6) % 4) +1) << The Swizzled Pin is now 3 I now dump the next parent up, (6,0,0), !devstack 0xfffffa80051d9060. It also didn’t have an ACPI filter driver on the stack so I need to swizzle the pin again. IntPin = ((((3-1)+0) % 4) +1) << The Swizzled Pin is still 3 I am now at the root port. The first devstack which has a _PRT method in my case is the root port. kd> !devstack 0xfffffa80054dea20 !DevObj !DrvObj !DevExt ObjectName fffffa80054f1040 \Driver\pci fffffa80054f1190 fffffa80054e5800 \Driver\ACPI fffffa80051c1510 << Has an ACPI filter driver in the devstack > fffffa80054dea20 \Driver\pci fffffa80054deb70 NTPNP_PCI0006 !DevNode fffffa80054e1750 : DeviceInst is "PCI\VEN_8086&DEV_340E&SUBSYS_02351028&REV_13\3&33fd14ca&0&38" ServiceName is "pci" kd> !acpikd.acpiext fffffa80051c1510 ACPI!DEVICE_EXTENSION fffffa80051c1510 - 70000 DevObject fffffa80054e5800 PhysObject fffffa80054dea20 NextObject fffffa80054dea20 AcpiObject fffffa80052e3890 ParentExt fffffa80051c07d0 PnpState Started OldPnpState Stopped Dispatch fffff880011cbb50 RefCounts 4-Device 1-Irp 0-Hiber 0-Wake State D0 SxD Table S0->D0 S4->D3 S5->D3 Flags 0540100002000240 Types Filter Enumerated ValidPnP Caps PCIBus Props HasAddress Enabled AcpiPower Dump the namespace object. Use /s to display the subtree under this object and look for a _PRT method. kd> !amli dns /s fffffa80052e3890 ACPI Name Space: \_SB.PCI0.PEX7 (fffffa80052e3890) Device(PEX7) | Integer(_ADR:Value=0x0000000000070000[458752]) | Integer(_STA:Value=0x000000000000000f[15]) | Method(_PRT:Flags=0x0,CodeBuff=fffffa80052e3aa9,Len=144) << A _PRT method exists for this object Now, we have a swizzled IntPin value of 3, and a pointer to the _PRT method. We can move on to the next step. Step 4: Convert the pin number from PCI to ACPI numbering The !pci or !devext output, and subsequent swizzling will show pin numbering in PCI format where 1 = INTA. But the ACPI table uses 0 for INTA. So you need to subtract one from the PCI pin number to get the ACPI pin number. PCI pin number ACPI pin number INTA INTB INTC INTD Once you’ve converted to ACPI pin numbering, you have to dump the _PRT method to find the package which maps to that pin number. For my example since the PCI IntPin value is 3, which corresponds to INTC, the ACPI pin number is 2 Step 5: Parse the _PRT method to find the static routing table Now that we located the correct _PRT entry, we need to use the AMLI debugger extension to parse the method and find the static routing table. The command !amli u will unassemble an ACPI method kd> !amli u \_SB.PCI0.PEX7._PRT AMLI_DBGERR: Failed to get address of ACPI!gDebugger fffffa80052e3aa9 : If(LNot(PICF)) fffffa80052e3ab1 : { fffffa80052e3ab1 : | Name(P10B, Package(0x4) fffffa80052e3ab9 : | { fffffa80052e3ab9 : | | Package(0x4) fffffa80052e3abc : | | { fffffa80052e3abc : | | | 0xffff, fffffa80052e3abf : | | | 0x0, fffffa80052e3ac1 : | | | LK00, fffffa80052e3ac5 : | | | 0x0 fffffa80052e3ac7 : | | }, fffffa80052e3ac7 : | | Package(0x4) fffffa80052e3aca : | | { fffffa80052e3aca : | | | 0xffff, fffffa80052e3acd : | | | 0x1, fffffa80052e3acf : | | | LK01, fffffa80052e3ad3 : | | | 0x0 fffffa80052e3ad5 : | | }, fffffa80052e3ad5 : | | Package(0x4) fffffa80052e3ad8 : | | { fffffa80052e3ad8 : | | | 0xffff, fffffa80052e3adb : | | | 0x2, fffffa80052e3add : | | | LK02, fffffa80052e3ae1 : | | | 0x0 fffffa80052e3ae3 : | | }, fffffa80052e3ae3 : | | Package(0x4) fffffa80052e3ae6 : | | { fffffa80052e3ae6 : | | | 0xffff, fffffa80052e3ae9 : | | | 0x3, fffffa80052e3aeb : | | | LK03, fffffa80052e3aef : | | | 0x0 fffffa80052e3af1 : | | } fffffa80052e3af1 : | }) fffffa80052e3af1 : | Store(P10B, Local0) fffffa80052e3af7 : } fffffa80052e3af7 : Else fffffa80052e3af9 : { fffffa80052e3af9 : | Name(A10B, Package(0x4) fffffa80052e3b01 : | { fffffa80052e3b01 : | | Package(0x4) fffffa80052e3b04 : | | { fffffa80052e3b04 : | | | 0xffff, fffffa80052e3b07 : | | | 0x0, fffffa80052e3b09 : | | | 0x0, fffffa80052e3b0b : | | | 0x26 fffffa80052e3b0d : | | }, fffffa80052e3b0d : | | Package(0x4) fffffa80052e3b10 : | | { fffffa80052e3b10 : | | | 0xffff, fffffa80052e3b13 : | | | 0x1, fffffa80052e3b15 : | | | 0x0, fffffa80052e3b17 : | | | 0x2d fffffa80052e3b19 : | | }, fffffa80052e3b19 : | | Package(0x4) fffffa80052e3b1c : | | { fffffa80052e3b1c : | | | 0xffff, fffffa80052e3b1f : | | | 0x2, fffffa80052e3b21 : | | | 0x0, fffffa80052e3b23 : | | | 0x2f fffffa80052e3b25 : | | }, fffffa80052e3b25 : | | Package(0x4) fffffa80052e3b28 : | | { fffffa80052e3b28 : | | | 0xffff, fffffa80052e3b2b : | | | 0x3, fffffa80052e3b2d : | | | 0x0, fffffa80052e3b2f : | | | 0x2e fffffa80052e3b31 : | | } fffffa80052e3b31 : | }) fffffa80052e3b31 : | Store(A10B, Local0) fffffa80052e3b37 : } fffffa80052e3b37 : Return(Local0) fffffa80052e3b39 : Zero fffffa80052e3b3a : Zero fffffa80052e3b3b : Zero fffffa80052e3b3c : Zero fffffa80052e3b3d : Zero fffffa80052e3b3e : Zero fffffa80052e3b3f : Zero fffffa80052e3b40 : HNSO fffffa80052e3b44 : Not(Zero, ) fffffa80052e3b47 : Zero fffffa80052e3b48 : Zero fffffa80052e3b49 : AMLI_DBGERR: UnAsmOpcode: invalid opcode class 0 AMLI_DBGERR: Failed to unassemble scope at 382d4a0 (size=4096) There are 2 different _PRT tables here, each with 4 packages (think of it as 2 arrays, each containing 4 structures). The first is using link nodes, the second is using static interrupts. The first list is used if we are in PIC mode, the second if we are in APIC mode. We can check the value of PICF to determine the mode. (I expect it to be APIC but let’s check) kd> !amli dns \PICF ACPI Name Space: \PICF (fffffa80052ded18) Integer(PICF:Value=0x0000000000000001[1]) So we’re in APIC mode (PICF != 0), we use the static routing mode. So we will use the 2nd table. What does each package represent? Each is a PCI Routing Table. From ACPI spec section 6.2.12, which describes the _PRT: Table 6-14 Mapping Fields Field Type Description Address DWORD The address of the device (uses the same format as _ADR). Pin BYTE The PCI pin number of the device (0–INTA, 1–INTB, 2–INTC, 3–INTD). Source NamePath Or Name of the device that allocates the interrupt to which the above pin is connected. The name can be a fully qualified path, a relative path, or a simple name segment that utilizes the namespace search rules. Note: This field is a NamePath and not a String literal, meaning that it should not be surrounded by quotes. If this field is the integer constant Zero (or a BYTE value of 0), then the interrupt is allocated from the global interrupt pool. Source Index Index that indicates which resource descriptor in the resource template of the device pointed to in the Source field this interrupt is allocated from. If the Source field is the BYTE value zero, then this field is the global system interrupt number to which the pin is connected. fffffa80052e3b07 : | | | 0x0, << INTA fffffa80052e3b0b : | | | 0x26 << Interrupt line fffffa80052e3b13 : | | | 0x1, << INTB fffffa80052e3b1f : | | | 0x2, << INTC fffffa80052e3b2b : | | | 0x3, << INTD Step 6 - Find the routing entry which represents our IntPin Now, we just have to locate the entry in the routing table with a IntPin value of 2. fffffa80052e3b1f : | | | 0x2, <<< IntPin 2 (INTC) fffffa80052e3b23 : | | | 0x2f << IRQ is 0x2f So the device should be assigned IRQ 0x2F. However, you may have noticed from the !pci output above that in this case the device was actually assigned IntLine (IRQ) 0x2e! Since the wrong interrupt line was assigned after the device changed slots in the system, the device did not receive interrupts and hence was not functional. I hope this was useful to help understand how interrupts are assigned to LBI devices. More reading / references: PCI IRQ Routing on a Multiprocessor ACPI System: ACPI 4.0 spec Hi.. Every Sometimes. Since the 1960’s, hard disks have always used a block size of 512 bytes for the default read/write block size. Recently drive manufacturers have been moving toward a larger block size to improve performance and reliability. Currently there are two types of disks available with a 4KB sector size: 512 byte emulated, and 4KB block sized disks. Disks with 4KB block size and 512 bytes per sector emulation For performance reasons, drive manufacturers have already produced disks with 4KB native block size, which use firmware to emulate 512 bytes per sector. Because of the emulated 512 byte sector size, the file system and most disk utilities will be blissfully unaware that they are running on a 4KB disk. As a result, the on-disk structures will be completely unaffected by the underlying 4KB block size. This allows for improved performance without altering the bytes per sector presented to the file system. These disks are referred to as 512e (pronounced “five-twelve-eee”) disks. Disks with 4KB block size without emulation When the logical bytes per sector value is extended to 4KB without emulation, the actual file system will have to adjust to this new environment. Actually, NTFS is already capable of functioning in this environment provided that no attached FS filter drivers make false assumptions about sector size. Below are the highlights of what you should expect to see on a disk with a 4KB logical sector size. 1. It will not be possible to format with a cluster size that is smaller than the 4KB native block size. This is because cluster size is defined as a multiple of sector size. This multiple will always be expressed as 2n . 2. File records will assume the size of the logical block size of 4KB, rather than the previous size of 1KB. This actually improves scalability to some degree, but the down-side is that each NTFS file record will require 4KB or more in the MFT. 3. Sparse and compressed files will continue to have 16 clusters per compression unit. 4. Since file records are 4 times their normal size, it will be possible to encode more mapping pairs per file record. As a result, larger files can be compressed with NTFS compression without running into file system limitations. 5. Since the smallest allowable cluster size is 4KB, NTFS compression will only work on volumes with a 4KB cluster size. 6. Bytes per index record will be unaffected by the 4K block size since all index records are 4KB in size. The on-disk folder directory structures will be completely unaffected by the new block size, but a performance increase may be seen while accessing folder structure metadata. 7. The BIOS Parameter Block (BPB) will continue to have the same format as before, but the only positive value for clusters per File Record Segment (FRS) will be 1. In the case where clusters per FRS is 1, the FRS byte size is computed by the following equation: NTFS BIOS Parameter Block Information BytesPerSector : 4096 Sectors Per Cluster : 1 ReservedSectors : 0 Fats : 0 RootEntries : 0 Small Sectors : 0 ( 0 MB ) Media Type : 248 ( 0xf8 ) SectorsPerFat : 0 SectorsPerTrack : 63 Heads : 255 Hidden Sectors : 64 Large Sectors : 0 ( 0 MB ) ClustersPerFRS : 1 Clust/IndxAllocBuf : 1 NumberSectors : 50431 ( 196.996 MB ) MftStartLcn : 16810 Mft2StartLcn : 2 SerialNumber : 8406742282501311868 Checksum : 0 (0x0) If the cluster size is larger than the FRS size, then ClustersPerFrs will be a negative number as shown in the example below (0xf4 is -12 decimal). In this case, the record size is computed with the equation: In short, NTFS will always force a 4096 byte cluster size on disk with a 4KB sector size regardless of the cluster size. Sectors Per Cluster : 4 ClustersPerFRS : f4 Clust/IndxAllocBuf : f4 MftStartLcn : 4202 Mft2StartLcn : 1 SerialNumber : 7270585088516976380 8. Aside from the 4KB file record size, there are a few other things to know about 4KB drives. The code for implementing update sequence arrays (USA’s) has always worked on a 512 byte assumed sector size and it will continue to do so. Since file records are 4 times their normal size, the update sequence arrays for file records now contain 9 entries instead of 3. One array entry is required for the sequence number (blue) and eight array entries for the trailing bytes (red). The original purpose of USA is to allow NTFS to detect torn writes. Since the file record size is now equal to the block size, the hardware is capable of writing the entire file record at once, rather than in two parts. _MULTI_SECTOR_HEADER MultiSectorHeader { ULONG Signature : 0x454c4946 "FILE" USHORT SequenceArrayOffset : 0x0030 USHORT SequenceArraySize : 0x0009 } 0x0000 46 49 4c 45 30 00 09 00-dd 24 10 00 00 00 00 00 FILE0...Ý$..... 0x0010 01 00 01 00 48 00 01 00-b0 01 00 00 00 10 00 00 ....H...°...... 0x0020 00 00 00 00 00 00 00 00-06 00 00 00 00 00 00 00 ................ 0x0030 02 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x0040 00 00 00 00 00 00 00 00-10 00 00 00 60 00 00 00 ...........`... 0x0050 00 00 18 00 00 00 00 00-48 00 00 00 18 00 00 00 .......H...... 0x0060 f8 f1 5b 89 36 d2 cb 01-f8 f1 5b 89 36 d2 cb 01 øñ[‰6ÒË.øñ[‰6ÒË. 0x0070 f8 f1 5b 89 36 d2 cb 01-f8 f1 5b 89 36 d2 cb 01 øñ[‰6ÒË.øñ[‰6ÒË. 0x0080 06 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x0090 00 00 00 00 00 01 00 00-00 00 00 00 00 00 00 00 ................ 0x00a0 00 00 00 00 00 00 00 00-30 00 00 00 68 00 00 00 ........0...h... 0x00b0 00 00 18 00 00 00 03 00-4a 00 00 00 18 00 01 00 .......J...... 0x00c0 05 00 00 00 00 00 05 00-f8 f1 5b 89 36 d2 cb 01 ........øñ[‰6ÒË. 0x00d0 f8 f1 5b 89 36 d2 cb 01-f8 f1 5b 89 36 d2 cb 01 øñ[‰6ÒË.øñ[‰6ÒË. 0x00e0 f8 f1 5b 89 36 d2 cb 01-00 00 01 00 00 00 00 00 øñ[‰6ÒË......... 0x00f0 00 00 01 00 00 00 00 00-06 00 00 00 00 00 00 00 ................ 0x0100 04 03 24 00 4d 00 46 00-54 00 00 00 00 00 00 00 ..$.M.F.T....... 0x0110 80 00 00 00 48 00 00 00-01 00 40 00 00 00 01 00 €...H.....@..... 0x0120 00 00 00 00 00 00 00 00-ff 00 00 00 00 00 00 00 ........ÿ....... 0x0130 40 00 00 00 00 00 00 00-00 00 10 00 00 00 00 00 @.............. 0x0140 00 00 10 00 00 00 00 00-00 00 10 00 00 00 00 00 .............. 0x0150 22 00 01 aa 41 00 ff ff-b0 00 00 00 50 00 00 00 "..ªA.ÿÿ°...P... 0x0160 01 00 40 00 00 00 05 00-00 00 00 00 00 00 00 00 ..@............. 0x0170 01 00 00 00 00 00 00 00-40 00 00 00 00 00 00 00 ........@....... 0x0180 00 20 00 00 00 00 00 00-08 10 00 00 00 00 00 00 . ............. 0x0190 08 10 00 00 00 00 00 00-21 01 a9 41 21 01 fd fd .......!.©A!.ýý 0x01a0 00 69 b4 05 80 fa ff ff-ff ff ff ff 00 00 00 00 .i´.€úÿÿÿÿÿÿ.... 0x01b0 00 00 10 00 00 00 00 00-22 00 01 aa 41 00 ff ff ......."..ªA.ÿÿ 0x01c0 b0 00 00 00 50 00 00 00-01 00 40 00 00 00 05 00 °...P.....@..... 0x01d0 00 00 00 00 00 00 00 00-01 00 00 00 00 00 00 00 ................ 0x01e0 40 00 00 00 00 00 00 00-00 20 00 00 00 00 00 00 @........ ...... 0x01f0 08 10 00 00 00 00 00 00-08 10 00 00 00 00 02 00 .............. . 0x03c0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x03d0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x03e0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x03f0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 02 00 ................ 0x05d0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x05e0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x05f0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 02 00 ................ 0x07d0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x07e0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x07f0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 02 00 ................ 0x09d0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x09e0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x09f0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 02 00 ................ 0x0bd0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x0be0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x0bf0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 02 00 ................ 0x0dd0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x0de0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x0df0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 02 00 ................ 0x0fd0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x0fe0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00 ................ 0x0ff0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 02 00 ................ I don’t actually own a 4KB disk, but I was able to give you this preview thanks to a nifty tool called VStorControl. Vstor is a tool which allows you to create virtualized SCSI disks with arbitrary block sizes and is available for download with the Windows 7 SDK. That’s all for now, Dennis Middleton “The NTFS Doctor”..
http://blogs.msdn.com/b/ntdebugging/default.aspx?PageIndex=7
CC-MAIN-2014-41
refinedweb
4,029
66.98
lstat - get symbolic link status #include <sys/stat.h> int lstat(const char *path, struct stat *buf);() returns 0. Otherwise, it returns -1 and sets errno to indicate the error. The lstat() function will fail if: - [EACCES] - A component of the path prefix denies search permission. - [EIO] - An error occurred while reading from the file system. - [ELOOP] - Too many symbolic links were encountered in resolving path. - [ENAMETOOLONG] - The length of a pathname exceeds {PATH_MAX},: - [ENAMETOOLONG] - Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}. - [EOVERFLOW] - One of the members is too large to store into the structure pointed to by the buf argument. None. None. None. fstat(), readlink(), stat(), symlink(), <sys/stat.h>.
http://pubs.opengroup.org/onlinepubs/007908775/xsh/lstat.html
CC-MAIN-2014-42
refinedweb
118
58.69
File::Find::Object::Rule - Alternative interface to File::Find::Object use File::Find::Object::Rule; # find all the subdirectories of a given directory my @subdirs = File::Find::Object::Rule->directory->in( $directory ); # find all the .pm files in @INC my @files = File::Find::Object::Rule->file() ->name( '*.pm' ) ->in( @INC ); # as above, but without method chaining my $rule = File::Find::Object::Rule->new; $rule->file; $rule->name( '*.pm' ); my @files = $rule->in( @INC ); File::Find::Object::Rule is a friendlier interface to File::Find::Object . It allows you to build rules which specify the desired files and directories. WARNING : This module is a fork of version 0.30 of File::Find::Rule (which has been unmaintained for several years as of February, 2009), and may still have some bugs due to its reliance on File::Find'isms. As such it is considered Alpha software. Please report any problems with File::Find::Object::Rule to its RT CPAN Queue. new A constructor. You need not invoke new manually unless you wish to, as each of the rule-making methods will auto-create a suitable object if called as class methods. The File::Find::Object finder instance itself. The rules to match against. For internal use only. name( @patterns ) Specifies names that should match. May be globs or regular expressions. $set->name( '*.mp3', '*.ogg' ); # mp3s or oggs $set->name( qr/\.(mp3|ogg)$/ ); # the same as a regex $set->name( 'foo.bar' ); # just things named foo.bar; The following stat based and or are interchangeable. # find avis, movs, things over 200M and empty files $rule->any( File::Find::Object::Rule->name( '*.avi', '*.mov' ), File::Find::Object::Rule->size( '>200M' ), File::Find::Object::Rule->file->empty, ); none( @rules ) not( @rules ) Negates a rule. (The inverse of any.) none and not are parameters of the name, the path you're in, and the full relative filename. In addition, $_ is set to the current short name, but its use is discouraged since as opposed to File::Find::Rule, File::Find::Object::Rule does not cd to the containing directory. Return a true value if your rule matched. # get things with long names $rules->exec( sub { length > 20 } ); as part of the options hash. For example this allows you to specify following of symlinks like so: my $rule = File::Find::Object::Rule->extras({ follow => 1 }); May be invoked many times per rule, but only the most recent value is used. relative Trim the leading portion of any path found not_* Negated version of the rule. An effective shortand related to ! in the procedural interface. $foo->not_name('*.pl'); $foo->not( $foo->new->name('*.pl' ) ); in( @directories ) Evaluates the rule, returns a list of paths to matching files and directories. start( @directories ) Starts a find across the specified directories. Matching items may then be queried using "match". This allows you to use a rule as an iterator. my $rule = File::Find::Object::Rule->file->name("*.jpeg")->start( "/web" ); while ( my $image = $rule->match ) { ... } match Returns the next file which matches, false if there are no more. Extension modules are available from CPAN in the File::Find::Object::Rule namespace. In order to use these extensions either use them directly: use File::Find::Object::Rule::ImageSize; use File::Find::Object::Rule::MMagic; # now your rules can use the clauses supplied by the ImageSize and # MMagic extension or, specify that File::Find::Object::Rule should load them for you: use File::Find::Object::Rule qw( :ImageSize :MMagic ); For notes on implementing your own extensions, consult File::Find::Object::Rule::Extending my $finder = File::Find::Object::Rule->or ( File::Find::Object::Rule->name( '*.pl' ), File::Find::Object::Rule->exec( sub { if (open my $fh, $_) { my $shebang = <$fh>; close $fh; return $shebang =~ /^#!.*\bperl/; } return 0; } ), ); Based upon this message my $rule = File::Find::Object::Rule->new; $rule->or($rule->new ->directory ->name('CVS') ->prune ->discard, $rule->new); Note here the use of a null rule. Null rules match anything they see, so the effect is to match (and discard) directories called 'CVS' or to match anything. File::Find::Object::Rule also gives you a procedural interface. This is documented in File::Find::Object::Rule::Procedural Corresponds to -A. Corresponds to -T. See "stat tests". Corresponds to -b. See "stat tests". Corresponds to -b. See "stat tests". Corresponds to -C. Corresponds to -c. See "stat tests". See "stat tests". Corresponds to -d. Corresponds to -z. Corresponds to -x. Corresponds to -e. Corresponds to -p. Corresponds to -f. See "stat tests". See "stat tests". See "stat tests". Corresponds to -M. See "stat tests". See "stat tests". Corresponds to -X. Corresponds to -O. A predicate that determines if the file is empty. Uses -s. Corresponds to -o. Corresponds to -R. Corresponds to -W. See "stat tests". Corresponds to -r. Corresponds to -g. Corresponds to -u. See stat tests. Corresponds to -S. Corresponds to -k. Corresponds to -l. See "stat tests". Corresponds to -t. Corresponds to -w. The code relies on qr// compiled regexes, therefore this module requires perl version 5.005_03 or newer. Currently it isn't possible to remove a clause from a rule object. If this becomes a significant issue it will be addressed. Richard Clamp <[email protected]> with input gained from this use.perl discussion: Additional proofreading and input provided by Kake, Greg McCarroll, and Andy Lester [email protected]. Ported to use File::Find::Object as File::Find::Object::Rule by Shlomi Fish. Copyright (C) 2002, 2003, 2004, 2006 Richard Clamp. All Rights Reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. File::Find::Object, Text::Glob, Number::Compare, find(1) If you want to know about the procedural interface, see File::Find::Object::Rule::Procedural, and if you have an idea for a neat extension, see File::Find::Object::Rule::Extending . Path::Class::Rule ’s SEE ALSO contains a review of many directory traversal modules on CPAN, including File::Find::Object::Rule and File::Find::Rule (on which this module is based). The tests don't run successfully when directly inside an old Subversion checkout, due to the presence of .svn directories. ./Build disttest or ./Build distruntest run fine.
http://search.cpan.org/~shlomif/File-Find-Object-Rule-0.0305/lib/File/Find/Object/Rule.pm
CC-MAIN-2017-43
refinedweb
1,033
62.85
TechEd - Morning of Day 2 After my session was finished, I went over to see Payam do his Windows Communication Foundation: Building Secure Services session. I was a little late to this one, but it was a great overview of what you can do with WCF and security. Given that I haven’t had a lot to do with certificates etc, that part of the session was interesting. It’s good so see that in WCF there are a lot of security options available. I like the fact that you can encrypt parts of a message rather than taking the hammer approach and encrypting everything. I think it was good that Payam make a clear distinction between scenarios where you want either no security, want to ensure that the message hasn’t been tampered with or where you don’t want someone to read part or all of a message. I suspect that most people put message tampering and encryption into the same box but they really are different levels of security. After the WCF session, I went to ASP.NET: End-to-End - Building a Complete Web Application Using ASP.NET 2.0, Visual Studio 2005, and IIS 7 (Part 1) by Scott Guthrie. Scott was a great speaker with good stage presence and interactions with the audience. Being a seasoned speaker, I think he handled questions throughout the session really well. He answered a lot of questions during the session (and more afterwards) but he didn’t let the questions change the direction of the session. Because I have spent most of my time developing ASP.Net and the last 18 months or so with VS2005, I didn’t learn anything new from the session, but I still really enjoyed it. After Scott’s session, I asked why System.Web.Caching is under System.Web namespace and whether it relies on some of the ASP.Net framework code. There is a lot of cool stuff with the caching support with the cache dependencies and cache expiration that would be really useful outside ASP.Net. He said that it was tied to ASP.Net in some small ways. From memory, he said that they were planning on releasing caching support outside ASP.Net, but there is also caching support today in the Caching Application Block in the Enterprise Library. Given that Scott used a lot of his break times to answer questions, he didn’t have much time before he was supposed to start Part 2 of his session. I was fortunate to have a one-on-one lunch with him before he had to head off for his next session. It was fantastic to chat with Scott about his work at Microsoft. He was interested to hear about .Net adoption in Australia as well. It was a good chat over good food.
https://www.neovolve.com/2006/08/24/teched-morning-of-day-2/
CC-MAIN-2018-30
refinedweb
474
73.17
05 August 2011 18:04 [Source: ICIS news] LONDON (ICIS)--A European monoethylene glycol (MEG) bulk spot deal was recorded at €968/tonne ($1,363/tonne), up €33/tonne compared with the previous week’s high, the parties involved said on Friday. “If you want it you have to pay the price,” the buyer said, echoing comments made by other sources. While requirements for downstream polyethylene terephthalate (PET) have seen a dip, demand from the antifreeze market is beginning to kick in. Some of this interest is attributed to buyers having held back in expectation of a price fall and nervousness caused by problems at ?xml:namespace> “There is a huge demand that is not yet covered,” one trader said. The continuation of the current strength in “Traders are sitting on parcels they bought earlier,” said one supplier. It remains to be seen whether the bearish global economic environment impacts European MEG prices. The European MEG price was soaring “while the world was tumbling to its knees,” a buyer added. Other reported deals include agreements at €945/tonne and €920/tonne CIF (cost, insurance and freight) NWE ( ($1 = €0.71)
http://www.icis.com/Articles/2011/08/05/9483125/europe-meg-spot-price-increases-by-33tonne-to-968tonne.html
CC-MAIN-2015-06
refinedweb
190
59.74
» 646 Announcements / Re: stdio.h« on: November 20, 2009, 05:51:32 pm » Try using pointers instead of arrays. It works for me.Yes, dynamic arrays work. Static arrays do not work unless you actually define the size of the array, which usually isn't what you want. int x[] = int* x 647 Announcements / Re: stdio.h« on: November 19, 2009, 07:46:32 pm » Apparently, the GCC. It yelled at me when I tried.Apparently, the GCC. It yelled at me when I tried.Also, something I found out:Who says they can't? int (*blah)(int,int)[];Is a pointer to a function which returns an array (and, functions cannot). 648 Announcements / Re: stdio.h« on: November 18, 2009, 07:23:05 pm » 649 Announcements / Re: stdio.h« on: November 16, 2009, 03:15:24 pm » You could use execute_asm(). :/ Also, another question - why is execute_shell() not implemented when it really is just a call for system()? or is it? Also, another question - why is execute_shell() not implemented when it really is just a call for system()? or is it? 650 Announcements / Re: stdio.h« on: November 15, 2009, 09:38:08 pm » Stupid question: is referring to an array going to be able to refer to the first element purely for GM compatibility? Personally, I'd never enable this, ever, but it would be useful for those directly converting from GM. Also, is LGM/unfinished IDE going to use a format better than GMK/GM6? Please? 651 Issues Help Desk / Re: Pointer explosion« on: November 15, 2009, 09:34:56 pm » uint8 requirement(int64 value){return value&0xFFFFFF00?(value&0xFFFF0000?(value&0xFF000000?8:4):2):1;}Yeah, I happened to realize that about a week ago, and then I just figured "screw this" and started working on something else. uint8 requirement(int8 value) { return requirement((int64)value); } Why not just return 1? Anyways the idea is pretty lame since you have to deal with the memory overhead of a void* and all and you waste memory dealing with all that so yeah, pretty silly 652 Off-Topic / Re: Who knows where to download I AM A GIGANTIC FAGGOT PLEASE BAN ME 5.0 Palladium?« on: November 13, 2009, 05:02:17 pm » Though, apparently some spammers are paying people to manually register and spam.Laughing. 653 General ENIGMA / Re: Hardware Acceleration« on: November 10, 2009, 04:15:51 pm » Sorry, is that directed at me or a continuation of what I said?Oh, wow, I didn't realize this. It's a continuation of what you said. :/ 654 General ENIGMA / Re: Hardware Acceleration« on: November 09, 2009, 08:44:34 pm » If you're basing this on an Nvidia subset on the basis that that's 'standard' (like Wine does) thenyou are an idiot and deserve to be stepped on 655 Issues Help Desk / Re: General Question« on: November 06, 2009, 10:16:21 pm » You download both the core and r3. r3 should include LGM with the ability to use ENIGMA. However, both are essentially pre-alpha, so it's virtually useless outside testing. However, both are essentially pre-alpha, so it's virtually useless outside testing. 656 Issues Help Desk / Re: Pointer explosion« on: November 06, 2009, 03:49:47 pm » Just for the record, you put there some unnecessary break statements on get(). Once you use "return", the code is immediatly interrupted.Sorry; just happens to be a habit. I'll do that. Quote Why are you casting to int64 in some cases and int32 in the case 4?Typo/mistake thing. Quote Also, you are using "delete" to a void* variable. Perhaps free() would be better? Quote In third place, your definition of resize has no effect(apart from leaking memory, of course, and increase the risk of future segmentation faults). So I assume you didn't actually notice how you implemented it.I can't believe I forgot about malloc and free. That'll do it. Quote In fourth place, check stdint.h. You might just love it(it defines int8_t, etc.)Would care, but I prefer it without the _t. I could use that for my typedefs, however. Quote Also, you are missing the ';' after the class.Another thing I forgot to do. >_> Quote Last but not least, you really shouldn't name float "decimals". Because they are not. decimals are a data type that uses the decimal system, rather than binary. It is useful to avoid some rounding errors. Float, double and long double are not decimals.I was going to name them rationals, and I'll probably do that. Anyways, thanks a bunch. EDIT: Hooray, it works. And, now, to seem stupid, how do I make two different operators for ++x and x++? Also, I was hoping this would work, but I guess not: // Add functions to use varint in I/O streams std::ostream::operator <<(varint &x) { int64 y=(int64)x; this << y; return this; } std::istream::operator >>(varint &x) { int64 y; this >> y; x=y; return this; } Full code: 657 Issues Help Desk / Pointer explosion« on: November 05, 2009, 07:05:17 pm » // Only include once #ifndef TYPES_INCLUDED #define TYPES_INCLUDED 1 // Include C headers #include <climits> #include <cfloat> // Define 1-bit integer typedef bool int1; // Define 8-bit integer typedef signed char int8; typedef unsigned char uint8; // Define 16-bit integer typedef signed short int int16; typedef unsigned short int uint16; // Define 32-bit integer typedef signed int int32; typedef unsigned int uint32; // Define 64-bit integer typedef signed long long int int64; typedef unsigned long long int uint64; // Size function - returns lowest size in bytes required to set value uint8 requirement(int64 value) { if (value>=CHAR_MIN || value<=CHAR_MAX) { return 1; } else if (value>=SHRT_MIN || value<=SHRT_MAX) { return 2; } else if (value>=INT_MIN || value<=INT_MAX) { return 4; } else { return 8; } } // Define variable-sized integer class varint { // Make pointer to value public: void *value; private: uint8 size; // Make constructor public: varint() { resize(1);set(0); } public: varint(int64 x) { resize(requirement(x));set(x); }; public: varint(int64 x,uint8 size) { resize(size);set(x); }; // Set function - sets value to *value private: void set(int64 x) { switch (size) { case 1: int8 *value8;value8=(int8*)value;*value8=x; break; case 2: int16 *value16;value16=(int16*)value;*value16=x; break; case 4: int32 *value32;value32=(int32*)value;*value32=x; break; case 8: int64 *value64;value64=(int64*)value;*value64=x; break; } } // Get function - gets value of *value private: int64 get() { switch (size) { case 1: int8 *value8=(int8*)value; return (int64)*value8; break; case 2: int16 *value16=(int16*)value; return (int64)*value16; break; case 4: int32 *value32=(int32*)value; return (int32)*value32; break; case 8: int64 *value64=(int64*)value; return (int64)*value64; break; } } // Resize function public: void resize(uint8 bytes) { // Invalid number of bytes? if (bytes!=1 && bytes!=2 && bytes!=4 && bytes!=8) { return; } // Resize if lower size is given only if lower == true if (sizeof(value)!=bytes) { void *temp=value; delete value; switch (bytes) { case 1: void *value=new int8;value=temp; break; case 2: void *value=new int16;value=temp; break; case 4: void *value=new int32;value=temp; break; case 8: void *value=new int64;value=temp; break; } } // Set size variable size=bytes; } // Get size function public: size_t getsize() { return (size_t)size; } // Return operators &operator int64() { return get(); } &operator int32() { return get(); } &operator int16() { return get(); } &operator int8() { return get(); } // Define operators int64 &operator =(int64 x) { if (requirement(x)>sizeof(value)) { resize(sizeof(x)); } set(x);return get(); } int32 &operator =(int32 x) { if (requirement(x)>sizeof(value)) { resize(sizeof(x)); } set(x);return get(); } int16 &operator =(int16 x) { if (requirement(x)>sizeof(value)) { resize(sizeof(x)); } set(x);return get(); } int8 &operator =(int8 x) { if (requirement(x)>sizeof(value)) { resize(sizeof(x)); } set(x);return get(); } } // Define decimals typedef float dec32; typedef double dec64; typedef long double dec96; // Define special typedef std::string str; // End include #endif Now, you know what I do when I'm bored. Just in case you didn't pick up what this is, it's a header for various type definitions and aliases. The one I'm having trouble with is varint. varint is a variable-sized integer. Essentially, it'll only be as big as it needs to be. If I want to make a variable with a value of 0, why do I need more than 1 byte? If it's 256, however, I'll need it to be 2 bytes. Of course, you're probably thinking: "why the hell do I care; it's only a few bytes". Well, err, I don't know what to say. But, whenever I try to compile this, g++ borks and returns tons of warnings. Anyone have any idea what I need to do to fix this? And, just for the record, it's not done; I still have the other operators to do. 658 Announcements / Re: Progress« on: October 29, 2009, 03:20:03 pm » What the crap? Why isn't code supposed to be big? Ever seen the Linux kernel you all love so much?I think you forgot that you were talking to Josh and not me. pages hate me 659 Announcements / Re: Progress« on: October 27, 2009, 03:40:57 pm » DLLs are a practical way to split your executable into multiple files.The point of which is...? 660 Announcements / Re: Progress« on: October 27, 2009, 02:22:53 pm » Just entirely curious, what is the point of DLLs? I mean, it's useful in Linux/UNIX to have libraries so that you don't have to have twenty copies because twenty programs that use it, but why would you care in Windows, since they're always included, anyways?
https://enigma-dev.org/forums/index.php?PHPSESSID=eiuedjis5mi0ii81sh9og57jmf&action=profile;u=22;area=showposts;start=645
CC-MAIN-2022-40
refinedweb
1,618
54.42
Yes, when looking at this problem, I was careless and didn't notice the tree is binary search tree. And I also solve this problem, so I want to share with you. The following is my ideas and code : traversal the tree 1) if find two p and q, return 2 2) if find one of p and q, return 1 and then rollback to the parent node, the common node also rollback to the parent node 3) if find nothing of p or q, return 0 and do nothing to common node. private TreeNode common = null; /** * * 27 / 27 test cases passed. * Status: Accepted * Runtime: 9 - 10ms, bit 26.45% - 14.05% * * @param root * @param p * @param q * @return */ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { helper(root, p, q); return common; } /** * @param root * @param p * @param q * @return */ private int helper(TreeNode root, TreeNode p, TreeNode q) { int count = 0; if (root == null) return count; if (root.val == p.val || root.val == q.val) { if (common == null) { common = root; count = 1; } else return 2; } int res = helper(root.left, p, q); if (res == 1) common = root; else if (res == 2) return res; return count + res + helper(root.right, p, q); } I did the same mistake. This is my stupid passed solution. 27 / 27 test cases passed. Status: Accepted Runtime: 9 ms Your runtime beats 26.49% of java submissions. public class Q235LowestCommonAncestorofaBinarySearchTree { TreeNode commonAncestor = null; public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) { //if this is null, means end of tree if(root == null) return null; TreeNode leftResult = lowestCommonAncestor2(root.left, p, q); TreeNode rightResult = lowestCommonAncestor2(root.right, p, q); //before every check, first check if the commonAncestor has found if(commonAncestor != null) return commonAncestor; //two nodes come to one common ancestor //if the left leave and right leave are not null, this node is the first common ancestor if((leftResult != null) && (rightResult != null)){ commonAncestor = root; return root; } //if one of the leafs is not null else if(leftResult != null || (rightResult != null)){ //check current root, if it is one of two nodes, this is the first common ancestor if((root.val == p.val) || (root.val == q.val)){ commonAncestor = root; } //if the current root is not the one, return the one that is not null to parent return leftResult != null ? leftResult : rightResult ; } else { //if both leafs are null, check current root //if it belongs to the two nodes, return this root if((root.val == p.val) || (root.val == q.val)){ return root; } //or no result in this subtree, return null return null; } } }
https://discuss.leetcode.com/topic/65993/if-the-tree-is-not-binary-search-tree-bst-how-to-do
CC-MAIN-2018-05
refinedweb
425
61.87
table of contents NAME¶ signal - ANSI C signal handling SYNOPSIS¶ #include <signal.h> typedef void (*sighandler_t)(int); sighandler_t signal(int signum, sighandler_t handler); DESCRIPTION¶ WARNING:¶ signal() returns the previous value of the signal handler, or SIG_ERR on error. In the event of an error, errno is set to indicate the cause. ERRORS¶ CONFORMING TO¶ POSIX.1-2001, POSIX.1-2008, C89, C99. NOTES¶ the disposition SIGCHLD is set to SIG_IGN. See signal-safety(7) for a list of the async-signal-safe functions that can be safely called from inside a signal handler. The use of sighandler_t is a GNU extension, exposed if _GNU_SOURCE is defined; glibc also defines (the BSD-derived) sig_t if _BSD_SOURCE (glibc 2.19 and earlier) or _DEFAULT_SOURCE (glibc 2.19 and later) is defined. Without use of such a type, the declaration of signal() is the somewhat harder to read: void ( *signal(int signum, void (*handler)(int)) ) (int); Portability¶action. SEE ALSO¶) COLOPHON¶ This page is part of release 5.10 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.
https://manpages.debian.org/bullseye/manpages-dev/signal.2.en.html
CC-MAIN-2021-43
refinedweb
192
67.35
A SphericalCap is defined by a direction and an aperture. More... #include <StelSphereGeometry.hpp> A SphericalCap is defined by a direction and an aperture. It forms a cone from the center of the Coordinate frame with a radius d. It is a disc on the sphere, a region above a circle on the unit sphere. Construct a SphericalCap from its direction and aperture. Clip the passed great circle connecting points v1 and v2. Return the octahedron contour representation of the polygon. It can be used for safe computation of intersection/union in the general case. Implements SphericalRegion. Compute the intersection of 2 halfspaces on the sphere (usually on 2 points) and return it in p1 and p2. If the 2 SphericalCap don't intersect or intersect only at 1 point, false is returned and p1 and p2 are undefined. Returns whether a SphericalCap intersects with this one. I managed to make it without sqrt or acos, so it is very fast! Reimplemented from SphericalRegion. Returns whether a HalfSpace (like a SphericalCap with d=0) intersects with this SphericalCap. Serialize the region into a QVariant map matching the JSON format. The format is ["CAP", [ra, dec], radius], with ra dec in degree in ICRS frame and radius in degree (between 0 and 180 deg) Implements SphericalRegion.
http://www.stellarium.org/doc/0.11.2/classSphericalCap.html
CC-MAIN-2016-36
refinedweb
215
58.08
From time to time, I am faced with the question: how to draw a smooth curve through a set of 2D points? It seems strange, but we don't have out of the box primitives to do so. Yes, we can draw a polyline, Bezier polyline, or a piece-wise cardinal spline, but they are all not what is desired: polyline isn't smooth; with Bezier and cardinal spline, we have a headache with additional parameters like Bezier control points or tension. Very often, we don't have any data to evaluate these additional parameters. And, very often, all we need is to draw the curve which passes through the points given and is smooth enough. Let's try to find a solution. We have interpolation methods at hand. The cubic spline variations, for example, give satisfactory results in most cases. We could use it and draw the result of the interpolation, but there are some nasty drawbacks: On the other hand, the platform provides us with a suite of Bezier curve drawing methods. Bezier curve is a special representation of a cubic polynomial expressed in the parametric form (so it isn't the subject of single valued function restriction). Bezier curves start and end with two points often named “knots”; the form of the curve is controlled by two more points known as “control points”. Bezier spline is a sequence of individual Bezier curves joined to form a whole curve. The trick to making it a spline is to calculate control points in such a way that the whole spline curve has two continuous derivatives. I spent some time Googling for a code in any C-like language for a Bezier spline, but couldn't found any cool, ready-to-use code. Here, we'll deal with open-ended curves, but the same approach could be applied to the closed curves. A Bezier curve on a single interval is expressed as: B(t)=(1-t)<sup>3</sup>P<sub>0</sub>+3(1-t)<sup>2</sup>tP<sub>1</sub>+3(1-t)t<sup>2</sup>P<sub>2</sub>+t<sup>3</sup>P<sub>3</sub> (1) where t is in [0,1], and t [0,1] P0 P1 P2 P3 The first derivative of (1) is: B’(t)=-3(1-t)<sup>2</sup>P<sub>0</sub>+3(3t<sup>2</sup>–4t+1)P<sub>1</sub>+3(2t–3t<sup>2</sup>)P<sub>2</sub>+3t<sup>2</sup>P<sub>3</sub> The second derivative of (1) is: B’’(t)=6(1 - t)P<sub>0</sub>+3(6t-4)P<sub>1</sub>+3(2–6t)P<sub>2</sub>+6tP<sub>3</sub> If we have just two knot points, our "smooth" Bezier curve should be a straight line, i.e. in (1) the coefficients in the members with the power 2 and 3 should be zero. It's easy to deduce that its control points should be calculated as: 3P<sub>1</sub> = 2P<sub>0</sub> + P<sub>3</sub> P<sub>2</sub> = 2P<sub>1</sub> – P<sub>0</sub> This is the case where we have more than two points. One more time: to make a sequence of individual Bezier curves to be a spline, we should calculate Bezier control points so that the spline curve has two continuous derivatives at knot points. Considering a set of piecewise Bezier curves with n+1 points and n subintervals, the (i-1)-th curve should connect to the i-th one. Now we will denote the points as follows: n+1 n (i-1) i Pi i=1,..,n P1i P2i At the ith subinterval, the Bezier curve will be: B<sub>i</sub>(t)=(1-t)<sup>3</sup>P<sub>i-1</sub>+3(1-t)<sup>2</sup>tP1<sub>i</sub>+3(1-t)t<sup>2</sup>P2<sub>i</sub>+t<sup>3</sup>P<sub>i</sub>; (i=1,..,n) The first derivative at the ith subinterval is: B’<sub>i</sub>(t)=-3(1-t)<sup>2</sup>P<sub>i-1</sub>+3(3t<sup>2</sup>-4t+1)P1<sub>i</sub>+3(2t-3t<sup>2</sup>)P2<sub>i</sub>+3t<sup>2</sup>P<sub>i</sub>; (i=1,..,n) The first derivative continuity condition B’i-1(1)=B’i(0) gives: B’i-1(1)=B’i(0) P1<sub>i</sub>+P2<sub>i-1</sub> = 2P<sub>i-1</sub>; (i=2,..,n) (2) The second derivative at the ith subinterval is: B’’<sub>i</sub>(t)=6(1-t)P<sub>i-1</sub>+6(3t-2)P1<sub>i</sub>+6(1-3t)P2<sub>i</sub>+6tP<sub>i</sub>; (i=1,..,n) The second derivative continuity condition B’’i-1(1)=B’’i(0) gives: P1<sub>i-1</sub>+2P1<sub>i</sub>=P2<sub>i</sub>+2P2<sub>i-1</sub>; (i=2,..,n) (3) Then, as always with splines, we'll add two more conditions at the ends of the total interval. These will be the “natural conditions” B’’1(0) = 0 and B’’n(1) = 0. B’’1(0) = 0 B’’n(1) = 0 2P1<sub>1</sub>-P2<sub>1</sub> = P<sub>0</sub> (4) 2P2<sub>n</sub>-P1<sub>n</sub> = P<sub>n</sub> (5) Now, we have 2n conditions (2-5) for n control points P1 and n control points P2. Excluding P2, we'll have n equations for n control points P1: 2n P1 n 2P1<sub>1</sub> + P1<sub>2</sub> = P<sub>0</sub> + 2P<sub>1</sub> P1<sub>1</sub> + 4P1<sub>2</sub> + P1<sub>3</sub> = 4P<sub>1</sub> + 2P<sub>2</sub> .... P1<sub>i-1</sub> + 4P1<sub>i</sub> + P1<sub>i+1</sub> = 4P<sub>i-1</sub> + 2P<sub>i</sub> (6) .... P1<sub>n-2</sub> + 4P1<sub>n-1</sub> + P1<sub>n</sub> = 4P<sub>n-2</sub> + 2P<sub>n-1</sub> 2P1<sub>n-1</sub> + 7P1<sub>n</sub> = 8P<sub>n-1</sub> + P<sub>n</sub> System (6) is the tridiagonal one with the diagonal dominance, hence we can solve it by simple variable elimination without any tricks. When P1 is found, P2 could be calculated from (2) and (5). /// > /// <exception cref="ArgumentNullException"><paramref name="knots"/> /// parameter must be not null.</exception> /// <exception cref="ArgumentException"><paramref name="knots"/> /// array must contain at least two points.</exception> public static void GetCurveControlPoints(Point[] knots, out Point[] firstControlPoints, out Point[] secondControlPoints) { if (knots == null) throw new ArgumentNullException("knots"); int n = knots.Length - 1; if (n < 1) throw new ArgumentException ("At least two knot points required", "knots"); if (n == 1) { // Special case: Bezier curve should be a straight line. firstControlPoints = new Point[1]; // 3P1 = 2P0 + P3 firstControlPoints[0].X = (2 * knots[0].X + knots[1].X) / 3; firstControlPoints[0].Y = (2 * knots[0].Y + knots[1].Y) / 3; secondControlPoints = new Point[1]; // P2 = 2P1 – P0 secondControlPoints[0].X = 2 * firstControlPoints[0].X - knots[0].X; secondControlPoints[0].Y = 2 * firstControlPoints[0].Y - knots[0].Y;] = (8 * knots[n - 1].X + knots[n].X) / 2.0; //] = (8 * knots[n - 1].Y + knots[n].Y) / 2.0; // : 3 the keyword “static” from the class declaration. static Note that the code uses the System.Windows.Point structure, so it is intended for use with Windows Presentation Foundation, and the using System.Windows; directive is required. But all you should do to use it with Windows Forms is to replace the System.Windows.Point type with System.Drawing.PointF. Equally, it is straightforward to convert this code to C/C++, if desired. System.Windows.Point using System.Windows; System.Drawing.PointF The sample supplied with this article is a Visual Studio 2008 solution targeted at .NET 3.5. It contains a WPF Windows Application project designed to demonstrate some curves drawn with the Bezier spline above. You can select one of the curves from the combo box at the top of the window, experiment with the point counts, and set appropriate XY scales. You can even add your own curve, but this requires coding as follows: CurveNames OnRender In the sample, I use Path elements on the custom Canvas to render the curve, but in a real application, you would probably use a more effective approach like visual layer rendering. Path Canvas GetCurveControlPoints This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Hi, Using the above draw function, when my knots array has more than 3 elements, I am getting blocks of points in the curve. I have uploaded the screen shot here: This what I am doing - 1) Compute the control Points using your logic 2) Interpolating line strips between ptvCtrlPts[i],firstCntrlPts[i], secondCntrlPts[i], ptvCtrlPts[i+1] as done here : Kindly let me know what I am missing here. Thanks! Deepti return new Point[] { new Point(76476, 799283), new Point(74225, 803603), new Point(73971, 803997), new Point(68303, 805135), new Point(68174, 805271) }; return new Point[] { new Point(95046,801135), new Point(101218,800002), new Point(101456,800086), new Point(103836,800890), new Point(104048,801004) }; return new Point[] { new Point(97953,104865), new Point(97963,105291), new Point(96956,106931), new Point(96728,107188), new Point(94425,106846), new Point(94203,106804) }; Point[] CustomCurve() { Point[] points = new Point[] { new Point(470, 323), new Point(380, 150), new Point(370, 134), new Point(143, 89), new Point(64, 226), new Point(50, 188) }; for (int i = 0; i < 6; ++i) { double x = points[i].X; double y = points[i].Y; points[i] = new Point((ScaleX / 100) * x, (ScaleY / 100) * y); } return points; } Point[] points = new Point[] { new Point(113, 249), new Point(360, 294), new Point(369, 291), new Point(464, 258), new Point(473, 254), new Point(474, 264) }; Point[] points = new Point[] { new Point(179, 99), new Point(180, 82), new Point(139, 17), new Point(130, 6), new Point(38, 20), new Point(29, 22) }; 3P<sub>1</sub> = 2P<sub>0</sub> + P<sub>3</sub> and P<sub>2</sub> = 2P<sub>1</sub> – P<sub>0</sub> General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/31859/Draw-a-Smooth-Curve-through-a-Set-of-2D-Points-wit
CC-MAIN-2014-42
refinedweb
1,758
52.39
Opened 4 years ago Closed 3 years ago #20221 closed Bug (fixed) `conditional_escape` does not work with lazy strings Description When passing the result of ugettext_lazy to conditional_escape, the result is not marked properly as safe which results in the data being escaped multiple times if conditional_escape is applied more than once. >>> from django.utils.html import conditional_escape >>> from django.utils.translation import ugettext_lazy >>> >>>>> ss = ugettext_lazy(s) >>> conditional_escape(conditional_escape(s)) '<foo>' >>> str(conditional_escape(conditional_escape(ss))) '&lt;foo&gt;' I ran into this issue by accident when working on #20211 where some old code had been left in and was escaping some strings twice in some cases. In that case, it was easy to work around the bug by simply removing the redundant calls to conditional_escape. Change History (6) comment:1 Changed 4 years ago by comment:2 Changed 4 years ago by comment:3 Changed 4 years ago by The more general problem is that functions marking their output as safe using mark_safe are not compatible with allow_lazy. I've identified two other functions that have this issue: utils.html.escapejs and utils.text.slugify. I've checked all functions using allow_lazy and only those three are combined with mark_safe. It's actually quite simple to solve this while maintaining backwards-compatibility (as long as you weren't relying on the bug itself, that is), because the machinery is there to mark lazy strings as safe. To solve this, I propose the introduction of a mark_safe_dec decorator (with a better name hopefully) that wraps the output of a function in a mark_safe call. With that, one can then decorate the lazified function, like so: def escape(text): """ Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML. """ return force_text(text).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''') escape = mark_safe(allow_lazy(escape, six.text_type)) Note the order of the two decorators, it's important (doing it the other way leads to the behavior we have now). This passes the tests I added with this ticket. I'll add more tests for the two other utils functions then submit a pull request within the next few days. comment:4 Changed 4 years ago by I've prepared a pull request for this ticket that include fixes for 3 other ones: I added some tests for conditional_escapeand tried to make them pass. I think the allow_lazydecorator applied to escapewas the issue here, so I removed and added some special-casing of Promiseobjects in the function itself. Here's the branch I'm working on:
https://code.djangoproject.com/ticket/20221
CC-MAIN-2017-17
refinedweb
424
58.11
I am working in Visual Studio (2019 V 16.8.4) using c#. All components are up-to-date. Working within a newly created "Windows Forms App (.Net Framework)" project, I am trying to create a simple database (which I successfully generated in VS) and access it through a single V.S. form that has one button. The button invokes a click event which is intended to make a connection to the database (*.mdf) located at c:\sub_dir. Each time debug is executed and the button is clicked, an exception occurs when "cnn.Open();" is executed. Essentially, it appears that the database file cannot be located ... no matter where I locate it. I emphasise that I want to work on my local hard drive and I am beginning to wonder if that is part of the problem. Or might it be the configuration of my PC? What I have tried so far: The problem clearly lies in the connection string and execution of "cnn.Open();". I have tried dozens of configurations for the string and tried many, many sites for solutions, including Stack Overflow. None of the solutions are successful for me. I have looked specifically at how to structure the connection string and I have run through literally dozens of tutorials (most recently Guru99 whose copied code is shown below). This is my first attempt at accessing data via SQL so I am new to this. I'll be grateful for whatever help is available. If this problem proves to be unresolvable I intend to try c# file handling as an alternative. Details: Form code is as follows: NOTE: I couldn't get the 'using' statements to conform to your required formatting so omitted them. namespace DemoApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connectionString; SqlConnection cnn; connectionString = @"Data Source=WIN-50GP30FGO75;Initial Catalog=Test1;User ID=sa;Password=demol23"; cnn = new SqlConnection(connectionString); cnn.Open(); MessageBox.Show("Connection Open !"); cnn.Close(); } } } Exception Details System.Data.SqlClient.SqlException HResult=0x80131904 StackTrace:) DemoApplication1.Form1.button1_Click(Object sender, EventArgs e) in C:\Guru99\DemoApplication1\DemoApplication1\Form1.cs:line DemoApplication1.Program.Main() in C:\Guru99\DemoApplication1\DemoApplication1\Program.cs:line 19 Inner Exception 1: Win32Exception: The network path was not found Did you create a Service-Based Database that generated a .mdf file? If so, to get your connection string, please refer to: User contributions licensed under CC BY-SA 3.0
https://windows-hexerror.linestarve.com/q/so65777905-Attempts-to-open-an-SQL-Connection-to-a-database-on-a-local-drive-result-in-SystemDataSqlClientSqlEx
CC-MAIN-2021-21
refinedweb
409
50.43
Minutes of the JEE 5 Working Group meeting Nov 30, 2006 Contents Teleconference on JEE 5 Support in WTP - Nov 30, 2006 Attendance - Bob Frost - Shaun Smith - Tim Wagner - David Williams - Larry Isaacs - Chuck Bridgham - Paul Fullbright - Neil Hauge - Karen Moore - David Gorton - John Goodman - Brian Vosburgh - Kaloyan Raev - Max Andersen - Naci Dai and more.... Minutes - ND: Welcome to the first call of the JEE working group. We will repeat this call weekly to track progress of the implementation. Working group is composed of the component owner who will lead the implementation. Today we have a wider audience. - ND: We will start with a review of the discussion summarized in. To start with lets review what is planned in WTP 2.0 for JEE 5 support. David can you comment on JSP/JSTL support? - DW: There will be some JSP support for JEE5 for WTP 2.0. Details are not clear but there is some work - ND: How about JSTL? I know Raghu was interested in this for JSF. - No answers .... Raghu not online - ND: Neil, Can you comment on JPA and EJB3 status? - NH: Dali projects covers the JPA spec. The rest of EJB 3 is not in its scope. There is some work that can be used for EJB3 like our way of handling metadata but we do not support session beans. - CB: Neil, I know that you have built utilities to handle two different sources for info: Annotations (metadata) and XML descriptors for the model. We are also interested in supporting both sources in JEE 5 models. I think a common layer can be extracted from Dali and contributed to JST. What are your recommendations? - NH: I can say(hope) that a common model can be defined for both sources. What we found is things are very different for these sources. Especially, the behavioral content is very different (descriptors are quite different). They are not very clean. That has caused a lot complexity. Annotation do not support everything in the descriptors + model have to act differently for defaulting - i.e. defaults specs vs java model. - PA: For example containment behavior is different. In XML you start with a mapping, and in the mapping you spec a class. In java you start with class and do the mapping. - BV: Another problem is that both models (XML and Annotations) are too flat for tooling purposes. - CB: We should start talking about solutions to these problems. Thanks to SAP for their contributions. The SAP proposal made us look at how to extend the models. We have to be forward thinking about how to extend the models for future version i.e JEE6. JEE5 is so different that we need to separate it cleanly from the existing models. We need interfaces between Java and XML models. That way we may not need to change the models, which is very important for backward compatibility. We can add interfaces as needed. - MA: Is any of this will be in WTP2.0? WTP 1.5.2 is not EJB3 friendly. We need a release of WTP 1.5 that does not complain about EJB3 for JBoss IDE. - DW: I do not want to sound pessimistic. But we will see what can do. But not sure we will be able to do it in 1.5.3. - CB: I do not think it is a good idea to change the existing models. J2EE is currently hard coded in the models. The models do not not recognize the JEE 5 versions and namespaces. We can create a patch so that the namespace can be handles, all legacy models will be included but anything new will not be recognized. Any work beyond that will be in 2.0 - CB: What are your thoughts on having model interfaces does not have dependencies on EMF. We can have a another set that has the old style interfaces with EMF dependencies. - DW: I support that. Reducing the coupling is better - CB: EMF provides things like notifications etc. We can provide overlapping/alternate interfaces - PF: EMF very slanted towards XML, not natural to use in Java sometimes - CB: Neil, you also have done work to extend AST in JDT with annotation utils. Any plans to push that into a common layer. - BV: No plans - CB: We are very interested in having that contributed to a common layer too. That work is very useful for all kinds of other things. - BV: JDT has very little. That work allows us to manipulate annotations, ignorant of types of annotations, it provides all the sugar on annotations. - DW: These looks like good places to start. I suggest we find things like that and open a patch to move them to a common layer. And iteratively see if this can be done. - SS: There is a lot of support in Dali for editing and validating annotations. I can build EJB3 sessions. Of course, WTP does not recognize them as EJBs. To start with we probably do not need any EJB3 editing tools and wizards. I need validation deployment support. The simple case is just to package them and deploy them. Do not worry about descriptors. - CB: I would like to propose tro extend the existing model to handle XML, recognize the new name space (use the old elements), then start contributing the new plugins as an extended plugins. In phase 2 we can start looking at the annotation model. I am not sure when thi scan start (if at all for WTP 2.0). When we add the support for the namespaces, we can tolerate the EJB3 descriptors. Extended tools would work. I cannot commit to it now. We will start with enabling the JEE 5 models. This work will probably go on after Jan7 (two milestones left) M5 is before eclipsecon. - DW: Ideally we should be done 80% done for M5, M6 should be done and ready to start the end game. - CB: What are peoples thoughts on making these changes - old models and new namespace? - DW: I would caution against that changes: 1) Any temporary changes will become permanent. 2) If not needed for WTP I am against it. But we can provide patches. We should do this incrementally. There are too many unknowns. - BV: You cannot do much with XML without knowing about annotations, so these are temporary changes - MA: Pure EJB project, you do not need too many descriptors. It is easier. Now, WTP 1.5 tooling says you have to be complex. To start with we should think what is the minimal for support for EJB3. - ND: We can probably support EJB3 facets, other specific JEE 5 facets and simple projects. If you have done it for JBoss IDE, rre you interested in contributing that? - MA: We could, they are quite simple. - SS: A word of caution.. Even with simple projects, we must support the old style descriptors so it will not be that easy. - MA: Maybe we should start with simple case. - SS: That is what we start in Dali, we will add complexity later. That is the common use case. Transactions semantics and defaulting is very similar to DALI - CB: Enablement you are speaking of does not require XML. That is what we are trying to get away from - MA: JBoss IDE EJB3 support is a facet, if we can handle that we will be done. There are some deployment limitations and specific problems, I will send to Chuck. Hard coded things and stuff make it hard. - CB: This will be good, because this will get us started with an easier use-case that we can work it. - DW: We should talk about this focus group. It should be limited to people who are working on the code and should be focused on JEE5 support task. - ND: Agreed. - CB: We should use the wiki to start adding comments and minutes. By next we should start talking about a plan and what to do for the milestones. - DW: Focus group should be working on the code. For others we can update status and plans. - ND: Thanks for attending. The notes will be available at the wiki. We will meet next week. These are post meeting comments from: - Kaloyan Raev As you remember I have already submitted a patch in the Bugzilla: The goal of the patch is to make WTP Java EE 5 friendly. With the patch it is possible to create valid Java EE 5 projects and deploy them on Server Runtimes that are Java EE 5 compatible. Everything is very basic, but it makes possible for the user to develop Java EE 5 application with WTP. I think it is a good idea to take a look at the patch again and to consider using it as a baseground for the Java EE 5 support. - Jesper Steen Moller Reading the minutes again (and in the light of the discussions a few weeks back), I noted a slight unease at the prospect of modifying/extending/changing/API'ing the EMF2XML framework. I think this is understandable, since it is mostly unchartered land to many, but it doesn't have to be like that: The framework is very important to making tool support truly good, and with a bit of unit testing, documentation and improved support for some desirable constructs, the unease should go away. I'm referring to bug reports on improving XML namespace support [1], improving consistency in using attributes vs. elements for some object types [2], improving the support for serializing comments [3]. I'm curently working on a unit test suite for the translator framwork. I'd like to hear the committers if work on these issues will be accepted. I'm using the EMF2XML framework for Mule IDE, hence the interest. Or, view it the other way around: Current XML Deployment Descriptor support is not going away. Java EE 5 will continue to use XML deployment descriptors for a while, with or without Annotations (there are still things which can only be done by XML DD's). Who knows how this will change in the future. In this light, why not pick up the Java EE 5 XML DD support offered and then go from there, seeing as there is no current alternative to the EMF2XML framework. [1] [2] [3]
http://wiki.eclipse.org/index.php?title=Minutes_of_the_JEE_5_Working_Group_meeting_Nov_30%2C_2006&oldid=19526
CC-MAIN-2017-39
refinedweb
1,715
75.1
Introduction¶ Why HoloViews?¶ HoloViews is an open-source Python 2 and 3 library for data analysis and visualization. Python already has excellent tools like numpy, pandas, and xarray for data processing, and bokeh and matplotlib for plotting, so why yet another library?. This process can be unfamiliar to those used to traditional data-processing and plotting tools, and this getting-started guide is meant to demonstrate how it all works at a high level. More detailed information about each topic is then provided in the User Guide.). Tabulated data: subway stations¶ To illustrate how this process works, we will demonstrate some of the key features of HoloViews using a collection of datasets related to transportation in New York City. First let's run some imports to make numpy and pandas accessible for loading the data. Here we start with a table of subway station information loaded from a CSV file with pandas: import pandas as pd import numpy as np import holoviews as hv from holoviews import opts hv.extension('bokeh')
http://holoviews.org/getting_started/Introduction.html
CC-MAIN-2019-18
refinedweb
171
59.03
Categories (Core :: Networking, defect) Tracking () Future People (Reporter: rbs, Assigned: neeti) References Details (Keywords: xhtml) Attachments (1 file) Currently, local files with the .xhtml extension are treated as HTML by Mozilla. Since .xhtml files are XML files, this bug is a request to let these files be treatd as XML files. Also, there is a long debate on n.p.m.mathml, under "Cannot render MathML" (from 30 Jan 2001 onwards), arguing that in order to support non-XML browsers and have portable documents, authors are serving their .xhtml documents with the text/html MIME type. This is preventing Mozilla from correctly interpreting fragments that are under different namespaces, such as that of MathML. This bug is also suggesting that documents with the .xhtml extension (regardless the text/html MIME), be treated as XML since Mozilla has the ability to handle mixed contents. One argument in favor of this is that it is not often possible for authors to configure the servers to negotiate the desired MIME type depending on the user-agent. But they are in control of their extension, and if they use .xhtml, they certainly mean that the file is an XHTML/XML file. So the support of XHTML this way will give an edge to Mozilla, while still remaining spec-compliants. Updating the title from ".xhtml to XML" to ".xhtml to XML if pref is set", to reflect that this behavior should happen only if a pref is set -- as per the suggestion in bug 68421, [email protected] 2001-02-10 13:24. Summary: .xhtml to XML → .xhtml to XML if pref is set Target Milestone: --- → Future One of the main reasons why people can't use text/xml is that ".xml" is not sent as text/xml *because they can't configure their server*. Thus, relying on an extension to do this is not suitable. How about this (quoting myself from mail): > > Ok, tell you what. (I'm serious here.) How about we add in support so that > if Mozilla sees exactly the following string as the first thing in a > text/html document, it treats it as text/xml? > > <!-- Mozilla Magic Message: this document is XML. It should be sent > as text/xml, not text/html. However, for compatability with > Internet Explorer, which doesn't yet support text/xml properly, > I have sent it as text/html. Please ignore the actual Content-Type > and treat it as text/xml instead. Thanks. --> > > We could even put a URI in the string that points to a page on mozilla.org > explaining the problem, and require this URI to be in the string (which > maybe could then be shorter) to trigger our XML parser. What do you think? I thought April 1st was a month ago, wasn't it? I am, actually, quite serious... It does what you want, no? Ah. yep, it does. But how is that different from what I am suggesting: that .xhtml goes to the XML parser (right from Necko) if a pref is set. Your suggestion is that .html + <!-- magic string --> goes to the XML parser. === Needless to say, the right fix for everybody is a mod_rewrite in the server :-) +-- text/xml if Mozilla/5 or above / .xhtml < \ +-- text/html otherwise This is how Paul Gartside is serving the MoW (Markup of the Week). I've even written a little perl script for those who can't use mod_rewrite: The reason your suggestion is suboptimal, though, is that it requires someone to change the server configuration to serve .xhtml as text/html in the first place. One of the main arguments given in www-talk for having some magic hack is that users can't touch their servers. Summary: .xhtml to XML if pref is set → .xhtml to XML if pref is set (and other suggested hacks) I read your page, yep it does provide a hack to the problem (albeit convulated and scary to the non expert...). Back to my hack, I was saying that, as far as Mozilla is concerned, just the .xhtml extension would determine the action to be taken. Or are you saying that it may happen that the .xhtml file is been served as 'application/octet-stream' or something to IE because the server wouldn't know the .xhtml extension in the first place? In that case, a _one-time_ addition of 'AddType text/html xhtml' in their .htaccess would solve the problem and is easy to document to newbies. It still seems to me that my hack is easier to implement & maintain for authors in the long run. And once IE fixes their code so as to treat .xhtml as XML, then it is easy to undo/change the AddType fallback. Maybe by then, the .xhtml extension would have already been widely adopted as an extension for XHTML (served as text/xml) so that servers would have the expected configurations, and authors won't have to do anything else with their existing .xhtml files (no need for them to edit and remove the magic string... no need to copy their probably growing legacy of XHTML files with .html to .xhtml, etc...). And in the other scenario where this takes long to happen, the AddType fallback would still be there. Oh, I completely agree with you as far as that goes -- I'm just saying that the www-talk crowd were saying that the primary reason they want us to sniff for XML is that they can't change their server configurations to send back files with .xml extensions as text/xml. One problem with your proposal, though, is that there is no "opt out" clause. How do you make sure that .xhtml files served up as text/html are in fact treated as text/html? By whom? Not Mozilla I guess. Isn't the whole point of this to allow a smooth transition of _new_ content to XHTML? Hence there isn't a backward compatibility issue here and the thinking goes that .xhtml is for XHTML (i.e., in reality text/xml). Part of the deal is that authors ought to move to XHTML while still been able to serve their content in older browsers for some time (not too long, I hope). If the goal isn't to encourage a smooth transition to XHTML (text/xml with the html doctype), then why bother. But I presume you asked your question just for completeness, right? If authors want the good o'ld HTML, let them use .html. I guess that's ok... Seems a bit presumptious though... I can name images ".html" and serve them up as image/jpeg and expect them to go through the JPEG decoder, I can serve .png files as video/mpeg and expect them to go through the helper app code, but I can't serve .xhtml files as text/html and expect them to go through the HTML parser? I guess you're probably right, nobody in there right mind will do that... Are we sure there are no HTML files out there that are named ".xhtml"? (I know many are named ".shtml" or ".jhtml" or ".phtml"...) This is a very special hack to xhtml :-) So that its deployment can get started... I have tried to think if the hack could backfire later, but nothing has struk me (as yet). Do you foresee any harm that may occur? I haven't encountered any .xhtml that is HTML in my everyday browsing so far. By the way, the official XHTML mime type is application/xhtml+xml. Mozilla and Amaya support it, I do not know of others. I recently added support for that, and I also mapped xht and xhtml file suffixes to that mime type, which should cause them to go through the XML parser (if read from a local file system). There is some weirdness here, though, since someone reported that on Windows at least you can mess with some Windows settings which affect which parser we use... Anyway, if we decide to go for content sniffing (which I do not like, and it would also be darn tricky to implement in the current code base since by the time we see some content we have already committed to the implementation (XML/HTML) that handles the content), I think it would be best to follow what XHTML defines a conformant document. Namely, the root element name must be html and it must designate the XHTML namespace. In such a case, we should parse it as XML. Oops, the latter link was not meant here. But it might interest you anyway: it states, among other things, that IE6 passes the W3C CSS1 test suite 100%. How does Mozilla handle it? Here's an html page with a .xhtml extension: mass move, v2. qa to me. QA Contact: tever → benc To try things out: - Apply the patch in mozilla/uriloader/base/ and rebuild - Set the preference in your prefs.js user_pref("advanced.xhtml_as_xml", true); - Visit the MathML testsuite which has lots of .xhtml files served as text/html Can someone _please_ tell me what's wrong with the following solution? It's completely standards-compliant, does the right thing, works on all browsers, and even makes your History look right. It means we don't have to implement nasty hacks (of the sort that web developers despise in IE, and the W3C hates). You could probably eliminate the NOSCRIPT if you had the meta refresh. <html> <head> <meta http- </head> <body> <SCRIPT> <!-- if (isMozilla) { document.location.replace(""); } else { document.location.replace(""); } // --> </SCRIPT> <NOSCRIPT> <center> Please click <a href="">here</a>. </center> </NOSCRIPT> </body> </html> Gerv Yes, that hack works too. In fact, there are many ways to get out of this hook. They differ in their implementation, considering both Mozilla's perspective and authors' perspective. The upshot of the maintainance entailed by your hack on authors is simply going to be a nightmare (I thought that was argued on the newsgroup). Compared with the few lines of my one-time, pref-controlled, hack in the Mozilla' side. I don't think this is a good feature to implement. The W3C themselves urge browser developers to obey Content-Type headers regardless of file extension (see bug 68421). If the idea is to have this feature controlled by a preference, I don't see how it will ease the burden on authors, as is claimed in the earlier comment. An author would have to serve up pages not knowing, and having no control over, whether the browser is going to parse their documents as XML or HTML. Maybe this should be "won't fix"? I think Mozilla should parse local .xhtml files as XML, but I think overriding the HTTP content type is a slippery slope. Parsing anything that looks like XHTML but is sent as text/html as XML won't work. Reason: and the like. For people who don't have access to the full server configuration but who use a reasonably cluefully configured Apache, there is a simple solution that required no scripts. The content type and the markup language of depend on the Accept header. It is implemented using Apache's content negotiation. No Perl. No PHP. No JS. supports three content types. I'm going to be Evil Standards Bastard and WONTFIX this. After the disaster of IE's file extension sniffing, people would jump all over us if we tried something like this. Furthermore, I think that in practical browsing of the web, this would mostly be annoying; people are already starting to slap XHTML Transitional doctypes on top of their malformed tag soup (see MSN, for instance), and in practice people would have to keep switching this pref back and forth to alternately get their XHTML + namespaces to work and keep XHTML Tag-Soup from breaking. Status: NEW → RESOLVED Closed: 21 years ago Resolution: --- → WONTFIX 1. IE does not render XHTML. 2. We can assume that any document with an XHTML doctype served as text/html is XHTML. So let's decide based not on the extension but on the doctype sniffed from the document. Discussion of this issue continues in bug 109837. As Heikki mentioned above, Mozilla *is* parsing local .xhtml and .xht files as application/xhtml+xml now. And yes, disobeying MIME type provided by the server is *bad* idea. verifying WONTFIX Status: RESOLVED → VERIFIED
https://bugzilla.mozilla.org/show_bug.cgi?id=67646
CC-MAIN-2022-27
refinedweb
2,062
74.39
In this article's project, Image Cryptography concepts are used. This project is made in Visual Studio 2010 C#.NET platform. Now a days, Privacy & Security issues of the transmitted data is an important concern in multimedia technology, so this project understands how encryption and decryption happens? In this project, cryptography gets used to hide images. In this, RSA (Ron Rivest, Adi Shamir, and Leonard Adleman ) algorithms are used. In this project, Image takes as input, in properties section, image properties are shown, like file name, image resolution, image size. After loading image, HEX function extracts the image HEX code, HEX code is converted into cipher text depending on RSA settings. An opposite, Cipher text gets loaded, then apply RSA algorithm, then decipher the text, resultant string is converted into image. This project has three class files: 1. RSAalgorithm.cs In this class file, RSA algorithm related functions are available like calculating phi, n, square, and modulus. RSA algorithm is step in this project to encrypt and decrypt images. This algorithm encrypts and decrypts the images, i.e., each frame gets encrypted and decrypted. 2. library.cs In this class file, hex decoding, checking prime number, byte to image conversion, image to byte conversion, vice versa are available. Library is used for basic conversion, processing and decoding Hex values, byte array to image conversion, and opposite as well, i.e. image to byte array conversion. Flow Chart for Encryption and Decryption The above flow chart shows how the project in this article works. The flow chart explains in a step by step manner the processing of the encryption and decryption, using C#. In this project, we only consider the images not audio. Images are encrypted, and create the *.txt file, the same file is used for decryption. Library is used for basic conversion, processing and decoding Hex values, byte array to image conversion, and opposite as well, i.e., image to byte array conversion. Following four functions are part of the library.cs file: DecodeHex IsPrime ConvertByteToImage ConvertImageToByte using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Drawing; namespace ImageCrypto { class library { public static byte[] DecodeHex(string hextext) { String[] arr = hextext.Split('-'); byte[] array = new byte[arr.Length]; for (int i = 0; i < arr.Length; i++) array[i] = Convert.ToByte(arr[i], 16); return array; } public static bool IsPrime(int number) { if (number < 2) return false; if (number % 2 == 0) return (number == 2); int root = (int)Math.Sqrt((double)number); for (int i = 3; i <= root; i += 2) { if (number % i == 0) return false; } return true; } public static Bitmap ConvertByteToImage(byte[] bytes) { return (new Bitmap(Image.FromStream(new MemoryStream(bytes)))); } public static byte[] ConvertImageToByte(Image My_Image) { MemoryStream m1 = new MemoryStream(); new Bitmap(My_Image).Save(m1, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] header = new byte[] { 255, 216 }; header = m1.ToArray(); return (header); } } } RSA is an encryption and authentication system, an algorithm developed in 1977 by Ron Rivest, Adi Shamir, and Leonard Adleman. RSA is a cryptosystem, which is also known as public-key cryptosystems. RSA is normally used for secure data transmission. A user of RSA creates product of two large prime numbers, along with an auxiliary value, as their public key. The prime factors kept secret. The public key is used to encrypt a message, and private key is used to decrypt a message. In the following RSA algorithm, it is clearly shown how to encrypt and decrypt message using RSA with sample numeric example. But in the project given in this article, instead of numeric values we encrypt the Hex string value of images frames. In using the code, section all RSA algorithm related functions are explained in detail. Step 1: Start Step 2: Choose two prime numbers p = 3 and q = 11 Step 3: Compute the value for ‘n’ n = p * q = 3 * 11 = 33 Step 4: Compute the value for ? (n) ? (n) = (p - 1) * (q -1) = 2 * 10 = 20 Step 5: Choose e such that 1 < e < ? (n) and e and n are coprime. Let e = 7 Step 6: Compute a value for d such that (d * e) % ? (n) = 1. d = 3 Public key is (e, n) => (7, 33) Private Key is (d, n) => (3, 33) Step 7: Stop. Let M, is plain text (message), M= 2. Encryption of M is: C = Me % n. Cipher text is, C = 27 % 33. C = 29. Decryption of C is: M = Cd % n. Plain text (message), M= 293 % 33. M= 2 In this class file, RSA algorithm related functions are available like calculating phi, n, square, and modulus. RSA algorithm is first layer step in this project to encrypt and decrypt video images or frames. This algorithm encrypts and decrypts the video frame by frame, i.e., each frame gets encrypted and decrypted. square BigMod n_value n cal_phi using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Drawing; namespace ImageCrypto { class RSAalgorithm { public static long square(long a) { return (a * a); } public static long BigMod(int b, int p, int m) //b^p%m=? { if (p == 0) return 1; else if (p % 2 == 0) return square(BigMod(b, p / 2, m)) % m; else return ((b % m) * BigMod(b, p - 1, m)) % m; } public static int n_value(int prime1, int prime2) { return( prime1 * prime2); } public static int cal_phi(int prime1, int prime2) { return ( (prime1 - 1) * (prime2- 1) ); } public static Int32 cal_privateKey(int phi, int e, int n ) { int d = 0 ; int RES = 0; for (d = 1; ; d++) { RES = (d * e) % phi; if (RES == 1) break; } return d; } } } The following function does the actual encryption task. This function accepts the string parameter. Image hex code is passed as parameter to this function. This string gets converted into character array. Each character is ciphered using RSA setting till the end of array. Cipher string is saved as *.txt extension. public string encrypt(string imageToEncrypt) { string hex = imageToEncrypt; char[] ar = hex.ToCharArray(); String c = ""; progressBar1.Maximum = ar.Length; for (int i = 0; i < ar.Length; i++) { Application.DoEvents(); progressBar1.Value = i; if (c == "") c = c + ImageCrypto.RSAalgorithm.BigMod(ar[i], RSA_E, n); else c = c + "-" + ImageCrypto.RSAalgorithm.BigMod(ar[i], RSA_E, n); } return c; } Following function does the actual decryption task. This function accepts the string parameter. Image cipher code is passed as parameter to this function. Cipher string gets converted into character array. Each character deciphers with RSA setting. Decipher character is converted into actual character value. Each character is cascaded, then the cascaded string is return back. public string decrypt(String imageToDecrypt) { char[] ar = imageToDecrypt.ToCharArray(); int i = 0, j = 0; string c = "", dc = ""; progressBar2.Maximum = ar.Length; try { for (; i < ar.Length; i++) { Application.DoEvents(); c = ""; progressBar2.Value = i; for (j = i; ar[j] != '-'; j++) c = c + ar[j]; i = j; int xx = Convert.ToInt16(c); dc = dc + ((char)ImageCrypto.RSAalgorithm.BigMod(xx, d, n)).ToString(); } } catch (Exception ex) { } return dc; } [1] This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) I have downloaded your project for reference. You have written separate functions for encryption and decryption. In which file are they located? Encryption Prime number 1 = 31; Prime number 2 = 23; Enter 'E' = 7 Decryption Enter 'D' = 283; Enter 'N' = 713; Int16 public static Int32 cal_privateKey(int phi, int e, int n ) {} Int32 d = Convert.ToInt16(textBox9.Text); Convert.ToInt32 decrypt int xx = Convert.ToInt16(c); (3, 9173503) (6111579, 9173503) 3557 2579 int xx = Convert.ToInt32(c); public static byte[] DecodeHex(string hextext) { String[] arr = hextext.Split('-'); byte[] array = new byte[arr.Length]; for (int i = 0; i < arr.Length; i++) array[i] = Convert.ToByte(arr[i],16); return array; } General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://codeproject.freetls.fastly.net/Articles/723175/Image-Cryptography-using-RSA-Algorithm-in-Csharp
CC-MAIN-2021-49
refinedweb
1,315
59.9
HTML Components: Custom Tags and Namespaces HTML Components Custom Tags and Namespaces HTCs are based on custom tags which were first introduced in IE 5.0. They allow Web authors to introduce structure to a document while associating style with that structure. For example, you can define a new tag, <RIGHT>, which right-justifies a paragraph: <HTML XMLNS:DOCJS> <HEAD> <STYLE> @media all { DOCJS\:RIGHT {text-align:right; width:100} } </STYLE> </HEAD> <BODY> <DOCJS:RIGHT> Read Doc JavaScript's columns, tips, tools, and tutorials </DOCJS:RIGHT> </BODY> </HTML> Internet Explorer's support for custom tags on an HTML page requires that a namespace be defined for the tag. Custom tags definition is based on XML syntax and the namespace is an XML namespace. As shown above, the namespace we use is DOCJS: <HTML XMLNS:DOCJS> XMLNS stands for XML Name Space. We defined a custom tag called RIGHT. Every use of this tag should be prefixed by the appropriate XML namespace, to create the new tag DOCJS:RIGHT. If namespaces are not defined, the custom tag is treated as an unknown tag when the document is parsed. Although navigating to a page with an unknown tag does not result in an error, the new custom tag is not able to contain other tags, nor can behaviors be applied to it. It is also possible to define multiple namespaces on a single HTML tag: <HTML XMLNS:DOCJS XMLNS:DOCJAVASCRIPT> Next: How to write the application's top-level page Produced by Yehuda Shiran and Tomer Shiran Created: July 3, 2000 Revised: July 3, 2000 URL:
http://www.webreference.com/js/column64/3.html
CC-MAIN-2015-48
refinedweb
264
54.86
Strings (C++/CX) Text in the Windows Runtime is represented in C++/CX by the Platform::String Class. Use the Platform::String Class when you pass strings back and forth to methods in Windows Runtime classes, or when you are interacting with other Windows Runtime components across the application binary interface (ABI) boundary. The Platform::String Class provides methods for several common string operations, but it's not designed to be a full-featured string class. In your C++ module, use standard C++ string types such as wstring for any significant text processing, and then convert the final result to Platform::String^ before you pass it to or from a public interface. It's easy and efficient to convert between wstring or wchar_t* and Platform::String. Fast pass In some cases, the compiler can verify that it can safely construct a Platform::String or pass a String to a function without copying the underlying string data. Such operations are known as fast pass and they occur transparently. The value of a String object is an immutable (read-only) sequence of char16 (16-bit Unicode) characters. Because a String object is immutable, assignment of a new string literal to a String variable actually replaces the original String object with a new String object. Concatenation operations involve the destruction of the original String object and the creation of a new object. Literals A literal character is a character that's enclosed in single quotation marks, and a literal string is a sequence of characters that's enclosed in double quotation marks. If you use a literal to initialize a String^ variable, the compiler assumes that the literal consists of char16 characters. That is, you don't have to precede the literal with the 'L' string modifier or enclose the literal in a _T() or TEXT() macro. For more information about C++ support for Unicode, see Unicode Programming Summary. The following example shows various ways to construct String objects. // Initializing a String^ by using string literals String^ str1 = "Test"; // ok for ANSI text only. uses current code page String^ str2("Test"); String^ str3 = L"Test"; String^ str4(L"Test"); //Initialize a String^ by using another String^ String^ str6(str1); auto str7 = str2; // Initialize a String from wchar_t* and wstring wchar_t msg[] = L"Test"; String^ str8 = ref new String(msg); std::wstring wstr1(L"Test"); String^ str9 = ref new String(wstr1.c_str()); String^ str10 = ref new String(wstr1.c_str(), wstr1.length()); The String class provides methods and operators for concatenating, comparing strings, and other basic string operations. To perform more extensive string manipulations, use the String::Data() member function to retrieve the value of the String^ object as a const wchar_t*. Then use that value to initialize a std::wstring, which provides rich string handling functions. // Concatenation auto str1 = "Hello" + " World"; auto str2 = str1 + " from C++/CX!"; auto str3 = String::Concat(str2, " and the String class"); // Comparison if (str1 == str2) { /* ... */ } if (str1->Equals(str2)) { /* ... */ } if (str1 != str2) { /* ... */ } if (str1 < str2 || str1 > str2) { /* ... */}; int result = String::CompareOrdinal(str1, str2); if(str1 == nullptr) { /* ...*/}; if(str1->IsEmpty()) { /* ...*/}; // Accessing individual characters in a String^ auto it = str1->Begin(); char16 ch = it[0]; A Platform::String can contain only char16 characters, or the NULL character. If your application has to work with 8-bit characters, use the String::Data Method to extract the text as a const wchar_t*. You can then use the appropriate Windows functions or Standard Library functions to operate on the data and convert it back to a wchar_t* or wstring, which you can use to construct a new Platform::String. The following code fragment shows how to convert a String^ variable to and from a wstring variable. For more information about the string manipulation that's used in this example, see basic_string::replace. // Create a String^ variable statically or dynamically from a literal string. String^ str1 = "AAAAAAAA"; // Use the value of str1 to create the ws1 wstring variable. std::wstring ws1( str1->Data() ); // The value of ws1 is L"AAAAAAAA". // Manipulate the wstring value. std::wstring replacement( L"BBB" ); ws1 = ws1.replace ( 1, 3, replacement ); // The value of ws1 is L"ABBBAAAA". // Assign the modified wstring back to str1. str1 = ref new String( ws1.c_str() ); The String::Length Method returns the number of characters in the string, not the number of bytes. The terminating NULL character is not counted unless you explicitly specify it when you use stack semantics to construct a string. A Platform::String can contain embedded NULL values, but only when the NULL is a result of a concatenation operation. Embedded NULLs are not supported in string literals; therefore, you cannot use embedded NULLs in that manner to initialize a Platform::String. Embedded NULL values in a Platform::String are ignored when the string is displayed, for example, when it is assigned to a TextBlock::Text property. Embedded NULLs are removed when the string value is returned by the Data property. In some cases your code (a) receives a std::wstring, or wchar_t string or L”” string literal and just passes it on to another method that takes a String^ as input parameter. As long as the original string buffer itself remains valid and does not mutate before the function returns, you can convert the wchar_t* string or string literal to a Platform::StringReference, and pass in that instead of a Platform::String^. This is allowed because StringReference has a user-defined conversion to Platform::String^. By using StringReference you can avoid making an extra copy of the string data. In loops where you are passing large numbers of strings, or when passing very large strings, you can potentially achieve a significant performance improvement by using StringReference. But because StringReference essentially borrows the original string buffer, you must use extreme care to avoid memory corruption. You should not pass a StringReference to an asynchronous method unless the original string is guaranteed to be in scope when that method returns. A String^ that is initialized from a StringReference will force an allocation and copy of the string data if a second assignment operation occurs. In this case, you will lose the performance benefit of StringReference. Note that StringReference is a standard C++ class type, not a ref class, you cannot use it in the public interface of ref classes that you define. The following example shows how to use StringReference: void GetDecodedStrings(std::vector<std::wstring> strings) { using namespace Windows::Security::Cryptography; using namespace Windows::Storage::Streams; for (auto&& s : strings) { // Method signature is IBuffer^ CryptographicBuffer::DecodeFromBase64String (Platform::String^) // Call using StringReference: IBuffer^ buffer = CryptographicBuffer::DecodeFromBase64String(StringReference(s.c_str())); //...do something with buffer } }
https://msdn.microsoft.com/library/windows/apps/hh699879.aspx
CC-MAIN-2016-50
refinedweb
1,100
53
Reading and writing text files in Open C++ Overview This code snippet shows how to use Open C++ file I/O classes for text file read and write operations. In this case, a text file is considered to be a file that stores words and sentences in readable plain text. The stream class fstream can be used for both read and write file I/O operations. Ifstream is only capable of file read operations and ofstream is only capable of file write operations. A header file <fstream> must be included in the application before these classes can be used. Reading and writing text files is possible with the extraction (<<) and the insertion (>>) operators and methods like put(), get(), and getline(). Note: In order to use this code, you need to install the Open C/C++ plug-in. This snippet can be self-signed. MMP file The following libraries are required: STATICLIBRARY libcrt0.lib LIBRARY libstdcpp.lib LIBRARY libc.lib LIBRARY euser.lib Source file #include <fstream> //fstream, ifstream, ofstream #include <string> //string, getline() #include <iostream> //cout using namespace std; void simple_write_example() { ofstream file; char line [] = "Text To File"; string str = "Hello"; //default open mode is a text mode, //a new file is created if a file does not exist //if a path is not given the applications's \private folder is used file.open("simple.txt"); //ios::out | ios::trunc file << line << endl; file.put('A') ; file << 1; file << str; //close the file file.close(); } void simple_read_example() { ifstream file; char line [20]; char chr = ' '; int num = 0; string str = ""; file.open("simple.txt"); //ios::in //getline has an optional third argument (character) //that will end getline's input, the default value is '\n' file.getline(line, 20); file.get(chr); // or file >> chr; file >> num; file >> str; cout << "line:"<< line << endl; cout << "chr:" << chr << endl; cout << "num:" << num << endl; cout << "str:"<< str << endl; file.close(); } void simple_read_and_write_example() { fstream file; string line; //fstream provides attributes which define //how a file should be opened: //app = 0x01 - append to the end of a file //ate = 0x02 - place the file marker at the end of the file //binary = 0x04 - open as a binary file //in = 0x08 - open file for reading //out = 0x10 - open file for writing //trunc = 0x20 - truncate an existing file and overwrite (default) file.open("simple.txt", ios::in | ios::out); //write to text file file << "This is a line 1" << endl; file << "This is a line 2" << endl; //fstream works with read and write file pointers, //by moving these pointers it is possible to access any part of //the file at random - seekg() moves the read pointer and //seekp() moves the write pointer //seek attributes: //ios::beg - beginning of the file //ios::end - end of the file //ios::cur - current location of the file file.seekg(0,ios::beg); //read text from file if (file.is_open()) { while (!file.eof()) { getline(file, line); cout << line << endl; } } file.close(); } int main() { //using class ofstream simple_write_example(); //using class ifstream simple_read_example(); //using class fstream simple_read_and_write_example(); return 0; } Postconditions The Open C++ I/O classes fstream, ifstream, and ofstream are used to read and write text from/to the created file simple.txt. Content of the file is displayed as standard output.
http://developer.nokia.com/community/wiki/index.php?title=Reading_and_writing_text_files_in_Open_C%25252B%25252B&oldid=176109
CC-MAIN-2014-35
refinedweb
536
68.5
containerdcontainerd containerd is a daemon to control runC, built for performance and density. containerd leverages runC's advanced features such as seccomp and user namespace support as well as checkpoint and restore for cloning and live migration of containers. Getting startedGetting started The easiest way to start using containerd is to download binaries from the releases page. The included ctr command-line tool allows you interact with the containerd daemon: $ sudo ctr containers start redis /containers/redis $ sudo ctr containers list ID PATH STATUS PROCESSES redis /containers/redis running 14063 /containers/redis is the path to an OCI bundle. See the docs for more information. DocsDocs - Client CLI reference ( ctr) - Daemon CLI reference ( containerd) - Creating OCI bundles - containerd changes to the bundle - Attaching to STDIO or TTY - Telemetry and metrics All documentation is contained in the /docs directory in this repository. BuildingBuilding You will need to make sure that you have Go installed on your system and the containerd repository is cloned in your $GOPATH. You will also need to make sure that you have all the dependencies cloned as well. Currently, contributing to containerd is not for the first time devs as many dependencies are not vendored and work is being completed at a high rate. After that just run make and the binaries for the daemon and client will be localed in the bin/ directory. PerformancePerformance Starting 1000 containers concurrently runs at 126-140 containers per second. Overall start times: [containerd] 2015/12/04 15:00:54 count: 1000 [containerd] 2015/12/04 14:59:54 min: 23ms [containerd] 2015/12/04 14:59:54 max: 355ms [containerd] 2015/12/04 14:59:54 mean: 78ms [containerd] 2015/12/04 14:59:54 stddev: 34ms [containerd] 2015/12/04 14:59:54 median: 73ms [containerd] 2015/12/04 14:59:54 75%: 91ms [containerd] 2015/12/04 14:59:54 95%: 123ms [containerd] 2015/12/04 14:59:54 99%: 287ms [containerd] 2015/12/04 14:59:54 99.9%: 355ms RoadmapRoadmap The current roadmap and milestones for alpha and beta completion are in the github issues on this repository. Please refer to these issues for what is being worked on and completed for the various stages of development. Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. The README.md file, and files in the "docs" folder are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file "LICENSE.docs". You may obtain a duplicate copy of the same license, titled CC-BY-SA-4.0, at.
https://libraries.io/go/github.com%2Fduglin%2Fcontainerd
CC-MAIN-2020-50
refinedweb
440
51.89
LrUUIDareohbee Feb 8, 2012 1:24 PM I've been using the undocumented LrUUID namespace for a while now without any problems, however I just had a user report the error: Could not find namespace: LrUUID He's using Lr3.4 on Vista Anybody know in which version of Lightroom this namespace first appeared? I can't imagine it being an OS thing(?) Thanks, Rob 1. Re: LrUUIDjohnrellis Feb 8, 2012 5:03 PM (in response to areohbee) The perils of using undocumented interfaces (of which I'm equally guilty :-<). Seems unlikely that this would be dependent on the Windows version (i.e. not available in Vista). The result of LrUUID (on Windows 7) looks like a Windows GUID: "C57FA964-8A58-4195-9A76-B6002A9633AC" Windows GUIDs have been around since at least Windows NT 3.5, I think, when Microsoft collaborated on the DCE standard. 2. Re: LrUUIDareohbee Feb 8, 2012 6:00 PM (in response to johnrellis) Thanks John, User is upgrading to Lr3.6 now, I'll let you know if it makes a difference. Rob 3. Re: LrUUIDMatt Dawson Feb 9, 2012 9:52 PM (in response to areohbee) It does seem like an odd error to experience. Namespaces aren't typically something that would change across OSes or even within a major release cycle. Would have expected that namespace to have been available since at least LR3.2 (but more likely LR3.0) so the upgrade shouldn't really be necessary. Lets hope the upgrade fixes the problem for your user. Thanks, Matt (Apologies for the brevity - sent from my Android) -
https://forums.adobe.com/message/4399416?tstart=0
CC-MAIN-2015-32
refinedweb
265
66.13
Below is a list of the types that are built into Python. Extension modules written in C. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don't explicitly return anything. Its truth value is false. Ellipsis. It is used to indicate the presence of the "..." syntax in a slice. Its truth value is true. Python distinguishes between integers and floating point numbers: There are two types of integers:. zcan be retrieved through the?) There is currently a single mutable sequence type: The extension module array provides an additional example of a mutable sequence type. are created by the {...} notation (see section The extension modules dbm, gdbm, bsddb provide additional examples of mapping types. Special namespace of the module in which the function was defined. Of these, func_code, func_defaults and func_doc (and this __doc__) may be writable; the others can never be changed. Additional information about a function's definition can be retrieved from its code object; see the description of internal types below. None) and a user-defined function. Special read-only attributes: im_self is the class attribute of a class instance that is a user-defined function object defined by the class of the instance._func is f(), and m.im_self is None. When x is a C instance, x.f yields a bound method object m where m.im_class is C, m.im_func). list.append(), assuming list; other bits are used internally or reserved for future_lineno gives the line number and most recent exception caught in this frame..
http://www.wingware.com/psupport/python-manual/2.0/ref/types.html
CC-MAIN-2016-40
refinedweb
263
69.28
Tutorial: Use the Azure CLI and Azure portal to configure IoT Hub message routing Message routing enables sending telemetry data from your IoT devices to built-in Event Hub-compatible endpoints or custom endpoints such as blob storage, Service Bus Queues, Service Bus Topics, and Event Hubs. To configure custom message routing, you create routing queries to customize the route that matches a certain condition. Once set up, the incoming data is automatically routed to the endpoints by the IoT Hub. If a message doesn't match any of the defined routing queries, it is routed to the default endpoint. In this 2-part tutorial, you learn how to set up and use these custom routing queries with IoT Hub. You route messages from an IoT device to one of multiple endpoints, including blob storage and a Service Bus queue. Messages to the Service Bus queue are picked up by a Logic App and sent via e-mail. Messages that do not have custom message routing defined are sent to the default endpoint, then picked up by Azure Stream Analytics and viewed in a Power BI visualization. To complete parts 1 and 2 of this tutorial, you performed the following tasks: Part I: Create resources, set up message routing - Create the resources -- an IoT hub, a storage account, a Service Bus queue, and a simulated device. This can be done using the portal, the Azure CLI, Azure PowerShell, or an Azure Resource Manager template. - Configure the endpoints and message routes in IoT Hub for the storage account and Service Bus queue. Part II: Send messages to the hub, view routed results - Create a Logic App that is triggered and sends e-mail when a message is added to the Service Bus queue. - Download and run an app that simulates an IoT Device sending messages to the hub for the different routing options. - Create a Power BI visualization for data sent to the default endpoint. - View the results ... - ...in the Service Bus queue and e-mails. - ...in the storage account. - ...in the Power BI visualization. Prerequisites For part 1 of this tutorial: - You must have an Azure subscription. If you don't have an Azure subscription, create a free account before you begin. For part 2 of this tutorial: - You must have completed Part 1 of this tutorial, and have the resources still available. - Install Visual Studio. - A Power BI account to analyze the default endpoint's stream analytics. (Try Power BI for free.) - An Office 365 account to send notification e-mails.: Create base resources Before you can configure the message routing, you need to create an IoT hub, a storage account, and a Service Bus queue. These resources can be created using one of the four articles that available for part 1 of this tutorial: the Azure CLI, Azure PowerShell, the Azure portal, or an Azure Resource Manager template. Use the same resource group and location for all of the resources. Then at the end, you can remove all of the resources in one step by deleting the resource group. The following sections describe the steps to be performed. Create a resource group. Create an IoT hub in the S1 tier. Add a consumer group to your IoT hub. The consumer group is used by the Azure Stream Analytics when retrieving data. Note You must use an Iot hub in a paid tier to complete this tutorial. The free tier only allows you to set up one endpoint, and this tutorial requires multiple endpoints. Create a standard V1 storage account with Standard_LRS replication. Create a Service Bus namespace and queue. Create a device identity for the simulated device that sends messages to your hub. Save the key for the testing phase. (If creating a Resource Manager template, this is done after deploying the template.) Use the Azure CLI to create the base resources This tutorial uses the Azure CLI to create the base resources, then uses the Azure portal to show how to configure message routing and set up the virtual device for testing.. Copy and paste the script below into Cloud Shell and press Enter. It runs the script one line at a time. This will create the base resources for this tutorial, including the storage account, IoT Hub, Service Bus Namespace, and Service Bus queue. A note about debugging: this script uses the continuation symbol (the backslash \) to make the script more readable. If you have a problem running the script, make sure there are no spaces after any of the backslashes. # This retrieves the subscription id of the account # in which you're logged in. # This field is used to set up the routing rules. # The storage account name must be globally unique, # so add a random value to the end. storageAccountName=contosostorage$randomValue echo "Storage account name = " $storageAccountName # Create the storage account to be used as a routing destination. az storage account create --name $storageAccountName \ --resource-group $resourceGroup \ --location $location \ --sku Standard_LRS # Get the primary storage account key. # You need this to create the message routing You are going to route messages to different resources based on properties attached to the message by the simulated device. Messages that are not custom routed are sent to the default endpoint (messages/events). In the next tutorial, you send messages to the IoT Hub and see them routed to the different destinations. The first step is to set up the endpoint to which the data will be routed. The second step is to set up the message route that uses that endpoint. After setting up the routing, you can view the endpoints and message routes in the portal.. Note The data can be written to blob storage in either the Apache Avro format, which is the default, or JSON (preview). The capability to encode JSON format is in preview in all regions in which IoT Hub is available, except East US, West US and West Europe. The encoding format can be only set at the time the blob storage endpoint is configured. The format cannot be changed for an endpoint that has already been set up. When using JSON encoding, you must set the contentType to JSON and the contentEncoding to UTF-8 in the message system properties. For more detailed information about using a blob storage endpoint, please see guidance on routing to blob storage. next to the Endpoint field to show the supported endpoints, as displayed in the following picture: Select Blob simulated device Next, create a device identity and save its key for later use. This device identity is used by the simulation application to send messages to the IoT hub. This capability is not available in PowerShell or when using an Azure Resource Manager template. The following steps tell you how to create the simulated device using the Azure portal. Open the Azure portal and log into your Azure account. Select Resource groups and then choose your resource group. This tutorial uses ContosoResources. In the list of resources, select your IoT hub. This tutorial uses ContosoTestHub. Select IoT Devices from the Hub pane. Select + Add. On the Add Device pane, fill in the device ID. This tutorial uses Contoso-Test-Device. Leave the keys empty, and check Auto Generate Keys. Make sure Connect device to IoT hub is enabled. Select Save. Now that it's been created, select the device to see the generated keys. Select the Copy icon on the Primary key and save it somewhere such as Notepad for the testing phase of this tutorial. Next steps Now that you have the resources set up and the message routes configured, advance to the next tutorial to learn how to send messages to the IoT hub and see them be routed to the different destinations. Feedback Send feedback about:
https://docs.microsoft.com/en-us/azure/iot-hub/tutorial-routing?WT.mc_id=devto-blog-dglover
CC-MAIN-2019-26
refinedweb
1,296
64.1
This comes as a surprise to me. I thought that: Xup, Xdown, Yup, Ydown and Zup, Zdown meant 6 'lots' of data. The XY and Z are clearly printed on the board: HERE ARE IMAGES OF CALIBRATION RIGLSM303D is in the middle very near the middle of the big wooden pivoting 'arm', pivots on a clear acetate sheet over a printed compass rose glued to plywood on a stainless steel table.In this pic. it just so HAPPENS to be on the 'flat' i.e. X and Y out horizontally and Zup. The rig allows accurate flat (horizontal) rotation with no other rotation: SO I AM CLEARYour last posting means that i am going to need some description of what you say: Here are the conventional labels for the "6 degrees of freedom" (the only one that i also use is 'heading' = yaw): But when we say 'rotate', it may not be clear which we mean, so to clear that up here are conventional labels for referring to WHICH rotation we mean: Can you please let me know each of:1. which three LSM303D orientations do you mean? (eg is X up the 'same' as X down etc), and2. which rotation. (eg turn about thetaZ, thetaY, thetaX)? I have been fixing the LSM303D in all 6 directions and then rotating (10 degree increments) around 360 degrees of thetaZ OMG, I think we might just be getting somewhere.... thanks in anticipation! sixD, you need to have another look and and open your eyes, does mine look anything like yours, l am rotating the axle l am not turning the bucket, my segment device is on the end of the axle and l turn the axle.Have another read of my posts, l never say turn the IMU l say rotate it.You just need to do x,y,z axis once, not in both directions as when it is ROTATED about THE AXIS it goes max +-.As per your drawing of axis and arrows, please explain how turning your device rotates the axis? you are just pointing x,y,z in a different direction around 360 degrees on the flat.REPEAT have a look at my photo, l am NOT turning the bucket, l am rotating the axle.Now l reckon the penny might have dropped. I hoping anyway! The difference between "turn" and "rotate" may be crystal clear to you, but that doesnt mean others will always know what you mean. Your language in your recent post @kevin1961 is not respectful - i have been nothing but polite with you, and i would hope that you could extend the same courtesy to me. I suggest you re read Merlin's posts, he shows how it is to be rotated at the top of the page, best of luck.kevin1961 out I have gone back to first principles and re-read all information here and in the links, but i am still finding the LSM303D uncalibrate-able!! i even closed off the possibility that my unit was faulty and wired in a new unit, but same outcome There must be something that i am overlooking, but for the life of me i cant see what it is. PLEASE SEND HELP!... i just want a tilt-compensated compass. The problem (as with each run earlier in this thread) is that when the heading is constant but the unit tilts or rolls the heading does not remain constant. OK can you see any problems with this process?? For each of A,B and C* my increments are 10 degrees each, so that's 36 stationary points around a circle. * at each reading i average 50 readings back to one data output for that position - the code for this is earlier in this thread.* this gives 108 orientations for Mag & Accel affected ONLY by gravity (they are stationary data reads) For completeness here i can graph the RAW data (all 108 rows of x,y and z outputs, to see if the outputs are something that kinda 'looks right'. Here is MagRAWdata for x-y, then y-z then x-z: ...and here is AccelRAWdata for x-y, then y-z then x-z: For one extra check: i can graph ONLY the relevant parts of each of the 108 data rows [i.e. only the 36 'A'-orientation points for x-y, only the 36 'B'-orientation for y-z, and only the 36 'C' orientation for X-Z] then this is the graphed output: for mag: and then for Accel: Magneto can make the ovals into circles and centre the data and as you can see every one of the charts are like this EXCEPT FOR accel x-y which is weird! could this be where the problem lies? THEN PUT THE DATA INTO MAGNETO i separate the output into two tab-delimited .txt files, one Mag and one for Accel. I assume that i do this for all 108 points, not just the 36 for each orientation?? Can anyone kindly clarify if the process this far is correct? many thanks dB Unless there is an error in the code or the mounting arrangement (with a nearby bit of iron or magnet), the "accel x-y" plot suggests that the sensor is defective. It should look similar to the other two accel plots. Magneto fits an ellipsoid, not ellipses, and can use all the data points you provide. The more points, and the more evenly they are spaced over the 3D orientation sphere, the better. It is in fact undesirable to consider only certain orientations of the sensor. sixD, I don't know a lot about this method of calibration, but I don't think your accelerometer is defective. From looking at your test setup and your graphs, it doesn't look like you ever subject both the X and Y axes (blue and green) to gravitational acceleration at the same time. That is why you only see a cross pattern on your accel X-Y graph, and I think it explains why the software is having such a hard time "circularizing" it. You should be able to get better data by adding another run (i.e. take your "A" setup and tip it over so the axis is parallel to the ground), but I think Jim is right that you want to get readings in as many orientations as you can; it might actually be better to wave the sensor around freely than to try to constrain its rotation to certain axes. Kevin Hi SixD, good to see you finally worked out the difference between turning and rotation of the axis. Hi Kevin, l would thinking waving the IMU around for Cal won't work for the Accel as it would have a acceleration component as well as gravity??Merlin states that you only need to do approx 24 steps i.e 15 degree increments for Magneto to give a good enough correction ratio.My previously attached photo shows a V3 in the position you indicated for the X,Y axis data to be taken.That all being said, after magneto correction to Mag and accel, instead of max/min correction, my tilt error decreased from 13 degree to 11 degree error at 45 degree tilt. So not worth the effort. Better off building a gimbal and decreasing error to <2 at 45 degrees(when you are not constrained by size).What l can't understand is the Accel gives accurate degrees of tilt, which l would have though meant the complete DCM formula would give just as accurate tilt compensated heading, which it doesn't. Hi.thankyou @Jim_Remington thats i i first thought it was a defective unit too, but thinking a bit more on it, and as per @kevin... as he says: REASON: the X and Y are producing reasonable results in other orientations, so they must be working. BUT it's def-o a problem and needs to be fixed. maybe i'm missing one orientation in my calibration. re calibrate 'loose' or on the rig:@kevin, regarding waving the IMU instead, i'll keep it in mind, but from my testing i'd say that i agree with @kevin1961 that it would introduce more problems than it's worth. so instead of plotting values against each other, i plotted my previous data against their dataNumber (for 1 thru 108 data points) and got this: For MAG: and for ACCEL: so, while i thought i had them all covered, the first third (being 1-36) is flat-as-a-pancake so this data says that i am missing one IMU orientation. riiight. so i took away the flat heading rotation that i called "A" above (rotated around a vertical axis) and substituted the data from the missing IMU position for one another rotation (around a horizontal axis) and the new data now looks like this for MAG: hurrah, this looks to me like i think the RAW data should. hopefully you guys agree? so i re-run all 108 data points thru magneto and it produces different calibrations values, but not very different. i input them into heading, carfully checking the +,- signs. OUTCOME: unfortunately the heading output is still NOT tilt-compensated WHERE TO NOW?: this is some progress, no doubt, but i'm still not in the land of a tilt-compensated-compass. my current hunch is that the Xs and Ys should be reversed somehow. (i think this was true of early versions of LSM303 c/w later versions??. @kevin can you shed light on this?) its the only way i can see how a roll or pitch can make heading so much WORSE. any other things to try would be gratefully received! thanks sixD Hey SixD I was having trouble with tilt compensation of my LSM303DLHC compass for an astronomy use. For now I've managed a workaround involving limiting the position of the sensor, but I'm interested in figuring out the whole thing. One quick question: is this the code you are using for calculating the heading:? fXm_comp = fXm*cos(pitch)+fZm*sin(pitch);fYm_comp = fXm*sin(roll)sin(pitch)+fYmcos(roll)-fZm*sin(roll)*cos(pitch); I've noticed in your graphs that you calculate pitch and roll, which tells me you are using these formulas (which involve lots of trigonometric functions like sin and cos). There is another way to calculate the heading, using vector math (dot products and cross products). that's the one I'm using, the bases is contained in the Pololu LSM303 library, ¿have you checked that out? Hey @Adun, yep, thats the one! A number of the tilt-compensated heading calcs i've seen use those formulae. I would add this though: One of the three LSM303 library files is called heading.ino (i've taken out the remarks to keep it short): #include <Wire.h> #include <LSM303.h> LSM303 compass; void setup() { Serial.begin(9600); Wire.begin(); compass.init(); compass.enableDefault(); compass.m_min = (LSM303::vector<int16_t>){-32767, -32767, -32767}; compass.m_max = (LSM303::vector<int16_t>){+32767, +32767, +32767}; } void loop() { compass.read(); float heading = compass.heading(); Serial.println(heading); delay(100); } yup, it doesn't get much simpler than that. in this trouble-shooting saga, i compared the heading output from the above sketch to the heading that outputs from the equation(s) approach (the ones you mention) and they come out exactly the same. i guess the same equations are onboard the IMU too. Anyway that was a) nice to know b) not helpful for solving any part of my problem. i'm glad you are also ...after all this time all i can add is me too! can you tell me more about the either my library isnt uptodate or i'm missing something! thanks much Hi I extended the class from LSM303.h file, which contains the body of the heading() method. The template for the heading() method expects a "from" vector (which should be of magnitude 1 or -1), and it returns a heading relative to it. The library always uses [0, -1, 0] which is the Y axis of the sensor for this, but as the sensor aims higher near zenith, it's heading makes no sense. Above 45° you should use the X axis (and add 90° to the result). This requires modifying (or extending) the Pololu library. Try this experiment: Modify the library to calculate heading using 3 different "from" vectors: X (-1,0,0) Y(0, -1,0) Z(0,0,1), and then plot the data, like you've done (tilting from zero to zenith). You will see what I mean. My workaround was to switch to using the Z axis (0,0,-1) and use the sensor inclined, so that Z should is always be horizontal and give a good reading, it works for me because it's for a telescope (not a boat) and it can keep the sensor vertical (zero rolling) G'day, i understand and as you say @Adun it makes perfect sense for a telescope. and if i needed such a big range i think what you're suggesting would be perfect. if that happened on a boat, the mast is in the water. in regular use for a boat the tilt (roll) would go around 45 degrees but rarely and only momentarily and pitch would only be +/-10 ish i'd guess Hats off to you, sir for getting into the .h file. something i've never done. I'm interested, though that you say... ...and i'm wondering if that is a clue to part of my problem/situation. see, with the board 'on the flat' it's the Z axis which is up/down so heading would be based on X and Y axes, right? i wonder why the library would default to Y?? does that mean all this time that i should have my board on its 'edge' as its starting orientation, rather than on-the flat?? plus it might explain why the outputs for pitch and roll have always seemed so accurate compared with the wild errors that get introduced into the heading output - something i have always wondered how 2 outputs can be so reliable, but the third is lousy. i have noticed that the tilt compensation amount varies around the heading. for example if the heading - that's the red line below - is at 100 (east-ish) and held constant and then the pitch goes up say 20deg - the first blue peak - then heading will wrongly adjust by MINUS 60degrees -thats the first red 'dip'. I'm happy to try ANY experiment, but have never dived into the .h file. can you kindly post some code of what you are suggesting? or maybe the above gives you some clue as to what's going on?!?!? thanks much Come On Jim, how about posting your complete code that can deliver what l would call amazing results that you have been able to get out of IMU's.I ask, because Kris has his code used by possible the biggest supplier of product at our level, has it openly available to all and l have found even his can't, down where l live, come anywhere near the the level of accuracy that you say you can get.Com on supply your code please.Thanks Kevin Next assault. sixD, have you tried Kris's IMU as l said in earlier post's. I know it might be $50 but it will prove one way or the other. He backs his and is the person who shows all codes and fixes everyone else is.He says +-2, which they best l could get was 7.Buy one and prove one way or the other.You shouldn't need to be going into the .h (apart from looking and learning, not needing to change the code, maybe preferances) unless of course you can understand it all and if this was the case, you wouldn't need to be asking these questions.Regards My code is here. It obviously won't work for you, because it's meant for a telescope, and as you said, they don't move like boats. My point is, instead of the code you're using (which has so many trigonometric functions) you could try Pololu's driver. It has a "heading" method which according to the documentation: float LSM303::heading(vector from) "Returns the angular difference in the horizontal plane between the 'from' vector and north, in degrees" Maybe you could try it. Hi Jim, by the look of things you aren't willing to show the code you get the great results of zero tilt error with?????????????????????????????????????????????????????l am very keen to have a look and you could help a lot of people with it, so please post and help the IMU community.Regards Kevin I've been using RTIMULib, which has a decent calibration routine built in, and have no need to revisit code for the LSM303D. I imagine that it wouldn't be difficult to modify RTIMULib to use that sensor, though. My efforts were described here: and I highly recommend this software. Of course, the accuracy of any IMU depends on doing the very best you can to calibrate both the magnetometer and the accelerometer, and in the latest posts, I don't see evidence that you folks have really accomplished that. I would like to see before and after calibration plots, showing nice circles (not ellipses) or spheres perfectly centered on the origin. Thanks Jim, by the sounds of it you are using Rtimulib2 with soft and hard iron correction.Using Magneto l have centred circles on the Mag and Accel and as l said it only improved tilt error correction by 1-2 degrees to about +-10 of error (at worst).Also my guru Jack, devised an even more accurate means of axis measurement (data thru a whole sphere) that we put thru Magneto with no better results. His V3 went from +-7(max/min) to about +-5(magneto), he is in the Northern Hemisphere.Regards Kevin
https://forum.pololu.com/t/lsm303d-tilt-compensation-problem/11611/84
CC-MAIN-2017-51
refinedweb
3,028
68.81
User-Agent: Mozilla/5.0 (compatible; Konqueror/3.5) KHTML/3.5.5 (like Gecko) Build Identifier: Mozilla/5.0 (X11; U; Linux i686; pl; rv:1.8.1) Gecko/20061010 Firefox/2.0 (and later) FF2 introduced anti-phishing protection feature. "Basic mode" is enabled by default. Browser connects regularly (approximately each half hour) to Google's server (there is even no GUI for choice here, see bug 342188). Google's cookie is sent with each update request. This has obvious privacy implications (e.g. Google is able to track usage of the browser by particular user, like when (which hours), how long and where (IP) user uses the browser). Log given in URL was created using 2.0, but situation is identical in regard of cookie and antiphishing in 2.0.0.1 and 2.0.0.2 (i.e. Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.2pre) Gecko/20070125 BonEcho/2.0.0.2pre ) and (IIRC) Gran Paradiso. Google's cookie is set automatically in first run, because default homepage in official builds is Google (well, mozilla.com site, but thanks to magic of redirections browser visits google.com domain anyway). Reproducible: Always Steps to Reproduce: 1. Download browser. 2. Run it. 3. PROFIT! (ok, this part is for Google Inc. only) Actual Results: Google's cookie is set in first run and then sent with each request for update (each half hour approx.). Expected Results: Cookie is not sent. So you're actually reporting three problems, right? 1) You don't like the fact that Google hosts Firefox's start page 2) You don't like the fact that Safebrowsing requires downloading an updated list each time 3) You don't like Google sending cookies to you You can change all of these through preferences. Change the home page, turn off safe browsing, block cookies from Google. BTW. puting jokes inside 'steps to reproduce' doesn't really help with fixing the bugs. Anyone to confirm this bug? BartZilla's "steps to reproduce" haven't really help here. This is intend behavior of the feature. WONTFIX for me. Furthermore there is a UI to stop this "privacy invasion". As stated in comment #1. We looked into sandboxing the connection before, and it was pretty complex as I recall. Not blocking as per the options in comment 1, and as per the privacy policy accompanying the SafeBrowsing service which explicitly prohibits Google from using the cookie information on SafeBrowsing API requests: (cf: "Google will receive standard log information, including a cookie, as part of this process. Google will not associate the information that Phishing Protection logs with other personal information about you.") Created attachment 299788 [details] [diff] [review] don't send cookie in "basic antiphishing" mode Re comment #1: This bug is about sending cookie with each request for update, which is unnecessary and has privacy implications. And my "Steps to Reproduce" is not a joke -- nothing more is needed to reproduce this bug. Re comment #2: I've prepared a little HOWTO about this bug. See it here: Feel free to ask if something is still unclear. Oh, and you may be also interested in this little project: Re comment #3: Oh, sure, I know that this is intended behaviour. It was clear for me after reading comments in bug 345146. Nevertheless, sending cookie is not necessary and has serious privacy implications when you realize who is (default and only, despite GUI that suggests otherwise) "data provider" for antiphishing (Google)....). After applying this patch Firefox doesn't send back cookie with requests for update in "basic antiphishing protection" mode (which is enabled by default), but it still sends cookie in "advanced antiphishing mode" and in "normal circumstances" like visting site in .google.com domain. (Note that I've changed my e-mail in bugzilla preferences. It seems that Google took over mailboxes in "gazeta.pl" domain. (See eg. , in Polish) It is harder and harder with each day to keep private data away from Google's hands...) (In reply to comment #5) > Created an attachment (id=299788) [details] > don't send cookie in "basic antiphishing" mode ... >...). Bart, would you mind making this patch against CVS trunk (HEAD)? That would help it to move forward to review stage. I don't know if this will have an impact on your patch when you update it to be against the trunk, but bear in mind that the remote lookup code (that sends each URL to Google for checking) has been disabled in nightlies, and by the time Fx 3 ships, the code (and the prefpane option) should be gone (as long as bug 388652 gets fixed, that is :) Not sending a cookie would break the request back off code on the server side. That is, if too many client requests come in for table updates, the server will tell some of them to stop asking for updates. It's better to have most users get some data rather than no users getting any data because the servers are being DOSed. Why does that require cookies? Wouldn't responding to a random percentage of requests with "please back off" work just as well? (In reply to comment #9) > Why does that require cookies? Wouldn't responding to a random percentage of > requests with "please back off" work just as well? Not easily. An HTTP 5xx will trigger the client to retry after a minute, but if there are three 5xx responses in a row, the client will back off. If the server wanted to tell a percentage to back off, it wouldn't work since the chance of the same client getting three 5xx in a row would be rare (this wound actually increase the number of client requests because of the retry). Sounds like a dedicated "back off" signal (perhaps a specific 5xx status) should be added to the protocol, so it doesn't take three requests for a client to figure out that the server wants it to back off. That would help even if we do keep cookies for some other reason. Created attachment 301207 [details] [diff] [review] patch against trunk, as requested in comment #6 Tony, if Google is not going to accept any patches fixing this issue, then how about changing Status of this bug to WONTFIX? At least it will be clear that you are not interested in any patches related with this. Comment on attachment 301207 [details] [diff] [review] patch against trunk, as requested in comment #6 given that this breaks the backoff architecture, there's no way we can take this patch at this time. It might be worth doing things differently, though I am not worried that google is misusing this data, but that's not going to happen in time for Firefox 3. Sorry, but IMO this is just another lame excuse. Changes to "backoff architecture" are already there. Namely, FF3 implements new so-called "safebrowsing" protocol (v.2,). With each request for update server (Google) tells client (Firefox) the number of seconds before the client should contact the server again. See, "n:" parameter. Support for this parameter is already implemented, see eg. While we could tell a particular connection to back off with the new protocol, there's other good reasons to leave the cookie in. 1. We can be more fair in how we tell clients to back off. E.g. if you've already been backed off before, we should probably back off someone else before we tell you to back off even longer. 2. Perhaps more importantly, we can use it to improve service quality. There's a lot of important questions that this helps us answer, e.g. "How long is it taking a client to get a full copy of the list", "How out of date are clients given our current strategy for throttling and rate at which we send the data"? "On average, how long do clients wait between connections and given that do we need to make changes to the way we serve data" etc. When the client contacts the Google servers for an update, you're basically saying "Here's the version of the list I have, give me more data". A cookie is sent along with that, and that helps us understand aggregate usage patterns. By removing that cookie, you don't seem to gain much privacy (after all, you're not sending private data, you're just basically saying "I have the following version of the list, give me more data"), and yet it causes many complications for determining whether we're doing a good job of keeping clients up to date. It seems like a poor trade-off, especially given how much we've already done and continue to do to ensure user privacy. I think everyone, both at Google and on the Mozilla team, want to take every feasible step to ensure that users' privacy is maintained and respected, this proposal just doesn't seem to be that feasible in terms of the trade-off of lost data quality utility vs. practically zero privacy gain. I don't think the problem here is that safebrowsing sends _a_ cookie, but instead that it sends the main google.com cookie (that ties the user to iGoogle, GMail, etc.). If safebrowsing had its own separate cookie and did not send any other google.com cookies along with it (basically, it was sandboxed), this wouldn't be a problem and nobody would be complaining about privacy issues. Cookies are a normal part of the web, sure, but sending a cookie that could possibly be linked to an actual user is a problem. Is it possible to use a different cookie? Probably, but really what would this accomplish? First of all, the privacy policies in place explicitly state what we can and can not do with the logging data, and what you are talking about is prohibited. But beyond that, what data are you really leaking? The only information the safebrowsing update requests leak is the fact that a client is online - not active, but rather connected, which for many computers is always. E.g. my computer has firefox always open, so yes, in theory if Google turned evil, violated privacy policies, betrayed user trust, and doomed its future as a company (which is not something we're going to do), someone could from the log data figure out that user ifette leaves Firefox open all the time. I fail to see how this is a privacy concern. I would be much more worried about my ISP logging every single HTTP request I make than I would be worried about Google knowing that I had a habit of leaving Firefox running. What about gethash requests that could theoretically be used to trace what URLs a user is visiting? Sure, there are safeguards against such a thing (bug 419117), but this is just an example of data that Google could possibly get besides how long a computer has been turned on. This will not block the final release of Firefox 3. Can we use the new LOAD_ANONYMOUS flag that bug 389508 added (as per bug 313414, comment #16) for this? (In reply to comment #20) > Can we use the new LOAD_ANONYMOUS flag that bug 389508 added (as per bug > 313414, comment #16) for this? That would be no different than the existing patch in this bug (apart from it being simpler). It would prevent us from sending any cookie headers, which means that we lose the benefits from comment 15. As far as I can tell, the only acceptable fix to this bug as summarized involves implementing a way to keep the cookies set/sent for the safebrowsing requests separate from the rest of the Google cookies despite the hosts being the same. This is possible using the existing http-on-modify-request/http-on-examine-response techniques, but there are of course a costs to doing that work (code complexity, maintenance burden, risk of breaking something). Whether that cost is outweighed by the benefits isn't immediately obvious to me, especially given the fact that if Google really was evil, they could use IP address correlation to do similar tracking (granted, it would be less reliable given NAT, and perhaps less efficient). Though I'm not particularly worried about Google abusing this information, does sending a cookie significantly improve the QoS they're able to provide? As stated in comment #15, we're already sending the version of the list we have, so as far as I can tell all Google has to do is prioritize older versions of the list. If an inordinate amount of users who haven't used FF in a while request an update to their list, certainly other users may be told to back off unfairly often, but with the advantage that the users who need it most get the updated list immediately. (it wouldn't surprise me if they're already doing something like this, I just fail to see the significance of the cookie to them) Doug: how are we doing this (not sending the cookie) for Geolocation? Can you see a clear path to us doing the same thing here? Sorry, wrong dougt - :dougt, see comment 23? the geolocation protocol doesn't use http cookies. The access token is sent in the data structure that we send to google. I think their protocol was designed such that (a) you didn't need to worry about this problem, and (b) some device platforms do not have access to change the http cookies. There was some discussion of creating a "chrome-only" cookie. Such a cookie would allow firefox to talk to a service without passing cookies set by content. Does the SafeBrowsing protocol require cookies? According to the comments in this bug, it does not. Comment 8 - comment 11 indicate that providing a cookie allows the server to be more intelligent about backing off requests when the servers are under load. Comment 15 - comment 17 indicate that Google can obtain significant quality-of-service data from being able to associate clients with requests. It would be good to know where that quality of service data is, so that the users who are contributing to it can also learn from it. Sounds like all of these issues could be equally served with a cookie that is not the same as the user's Google cookie. The issue here is connecting SafeBrowsing activity with the personally identifiable information contained in the Google cookie (ie: the user's Google account). Ian/Tony: would you agree? A separate sandboxed cookie seems like it should work fine. (In reply to comment #30) > A separate sandboxed cookie seems like it should work fine. BartZ - feel like trying your hand at this patch, while we get an answer to shaver's question in comment 28? (In reply to comment #31) > (In reply to comment #30) > > A separate sandboxed cookie seems like it should work fine. > > BartZ - feel like trying your hand at this patch, while we get an answer to > shaver's question in comment 28? Cookies are not necessary at all. Sending them is an unacceptable privacy violation (as is the whole Google's so-called "safebrowsing" enabled by default). For this reason (among others [1]) I am not going to write any patches that "sandbox" them (ie. that keeps separate set of Google cookies and sends them in "sb"-related requests) [0]. The only acceptable outcome for me is to disable so-called "safebrowsing" completely. The issue with cookies is actually only the tip of the privacy violation iceberg. (Apart from cookies, browser also sends another unique identifier with "sb"-related requests, namely wrkey; it is saved in urlclassifierkey3.txt in profile directory; it "survives" unchanged also when entering and leaving Private Browsing mode; visit URL [2] for demo. So explanations from Google in this bug that they really need cookie - only for QoS purposes - are, well, not very convincing, since they could use wrkey for this purpose.) My initial report was written long time ago. Since that time the underlying protocol has changed significantly (in FF 3 / 3.5 there is actually completely another protocol implemented than in FF 2). In order to learn more about it, in more details, I implemented this protocol on a server side [2] - despite the prohibitive language from Google on the site with the spec. (To be clear: my project doesn't use/connect to Google's servers at all since it implements server side functionality itself. After reconfiguring the client side - ie. Firefox - the communication is between my server and a client, there are no connections with Google at all.) I hope I will release source code of this project soon [3] and write extensive documentation and explanations. I'm writing this reply mainly to address Johnathan's request. For now, let me summarize the issues with Google's so-called "safebrowsing" as is implemented and enabled _by default_ in Firefox (SINCE FF 3.0!): - it is possible for a "safebrowsing" server to reliably differentiate between different users (browser's profiles, to be exact); cookie plays a big role in this (and is related with personal information if user uses any Google services), but - as I said above - there is also the issue with wrkey - server may feed the clients (or chosen client(s)) with data that allows server-side to reliably "guess" (with very high probability) the visited URL (well, at least in some well-defined cases - but by "some cases" I mean "in quite many cases"); the list of URLs to monitor must be selected (it is not possible for a "safebrowsing" server to get the whole user's history [4]); the list may be updated rapidly, though - "guessed" URLs may be easy connencted to the same user; also, server is notified immediately when a user visits given URL (ie. server gets the exact time of a visit) - user may not be notified in any way when (if) sending of this notification happens - it all works also when "Private Browsing" is enabled (cookies are "sandboxed" in this case, though - but that's the general feature of the Private Browsing). You may check yourself these issues after reconfiguring Firefox as described in URL [2]. (I realize that this whole thing is not very user-friendly, so I guess this advice is for the people who know what they are doing. Read all info on this page and ask if something is unclear.) In my opinion it is enough to disable Google's so-called "safebrowsing" - if Mozilla really cares about users' privacy, as it officially claims. Footnotes: [0] Please note that an initial title of this bug was "sending Google's cookie with each request for update in default antiphishing mode" and from the beginning I was thinking only about preventing sending cookies completely, not "sandboxing" them. Beltzner changed title of this bug to the current text in November 2007, see "History" link near the top of this page. [1] Another reason is this: how are you going to manage this separate set of cookies? For example: will these "sandboxed" cookies be present in cookie manager? How are you going to differentiate them (from user point of view) between "normal" Google cookies and "sandboxed" set of cookies? How will these "sandboxed" cookies behave when dealing with Private Browsing / clearing private data / clearing cookies / clearing only cookies from .google.com / blocking only cookies from .google.com? Etc., etc... (BTW - the same set of issues already exists with Google's "geolocation" token which is, effectively, a cookie. See eg. bug 491759.) [2] (note that this is a different URL - and different project, since it implements completely another protocol - than mentioned in my comment #5) [3] Probably under GNU Affero General Public License, version 3 or later (as published by the FSF). [4] Unless all of the visited URLs happen to be monitored by the server, of course -- but such case is unlikely. Trying to summarise your points, Bartłomiej: *Cookies are completely unneeded. *The MAC allows the server to track you *Since "Before blocking the site, Firefox will request a double-check to ensure that the reported site has not been removed from the list since your last update." the server can trace visits to any url it wants to. Proposed actions to remove those threats: *Remove cookies from safebrowsing requests. *Add a maximum expiry time for the key, to ensure it gets rotated often enough. *Ability to request disable the use of MAC in the client. *Safebrowsing requests should be disabled on Private Browsing mode, using only the data already present. *There should be a preference for what to do when an url is blocked: Ask the provider for confirmation, Block without asking, Update the safebrowsing db, Offer a dialog where the use can manually ask the provider (could be integrated in blockedSite.xhml) I'd also like to see Firefox able to work with an already downloaded copy, but I have opened a different bug (Bug 511081) for that. I sense a lot of anti-google sentiments, and I doubt that anything I say will change any of that. However, there are some factual errors that I would like to clear up here: 1. People have asked what the wrkey parameter is. We are not using SSL (at the time we published the protocol, using SSL would have been prohibitively expensive for us). As such, we establish a shared secret via SSL once (the "wrapped key", or wrkey), and then use that to authenticate messages (updates etc) so that a MITM can't inject false data into your SafeBrowsing database. 2. Our infrastructure for DoS prevention uses cookies, among other things. Trying to re-write shared google-wide infrastructure to use "wrkey" instead of a cookie is not a pleasing thought.?" 4. We retain the original logs for only two weeks. We are not trying to spy on users, build a profile of all the URLs that you have visted,. 5. We're not getting every URL you visit. We're only getting URLs that match the (partial) data in the local database, so we could not build up a complete profile of all that you've viewed anyways. If you don't trust google, I doubt anything I've said is going to convince you. I would love to invite you over to my desk and show you that the logs are in fact dropped after two weeks, that we're really not spying on you, etc, however that is not feasible for me to do. So, if you don't trust what I'm telling you, you're welcome to turn the feature off, or to use an alternate provider (although I don't know of anyone else giving away comparable data for free to whomever wants to use it.) If we ever were to violate user's trust or privacy, I would fully expect Mike or Jonathan to disable SafeBrowsing - but believe it or not, we're not trying to spy on you, rather we're trying to keep users (all users, not just FF users) safe from phishing and malware. In order to do that, we need to make sure that we are providing a quality, reliable service. Part of that is making sure that our infrastructure can withstand denial of service attacks, part of this is monitoring how the service itself works (are users getting updated frequently enough? what's our hash collision rate? how long does it take for a new user to get all the data? etc.) For these purposes, having cookie data is very useful. We're not trying to track you or tie this information to your Google account etc, and so a sandboxed cookie works fine, but having no cookie compromises our abilities in this area and so is not a good solution. Dan: I don't think that this is in scope for 1.9.2, but please renominate if you think we can do it. If we don't get this for 1.9.2, we definitely want it for 1.9.3 If the experiment <A HREF="> here </A> presented by BartZilla in Comment 5 were successful, then perhaps a simple way to disable safebrowsing would be to set the following values in about:config to null: browser.safebrowsing.malware.reportURL browser.safebrowsing.provider.0.gethashURL browser.safebrowsing.provider.0.keyURL browser.safebrowsing.provider.0.lookupURL browser.safebrowsing.provider.0.reportErrorURL browser.safebrowsing.provider.0.reportGenericURL browser.safebrowsing.provider.0.reportMalwareErrorURL browser.safebrowsing.provider.0.reportMalwareURL browser.safebrowsing.provider.0.reportPhishURL browser.safebrowsing.provider.0.reportURL browser.safebrowsing.provider.0.updateURL browser.safebrowsing.warning.infoURL I have done this without any stability problems so far (I will re-post if this changes). What do you guys think about this workaround? If you want to disable safebrowsing, you don't have to go through all that trouble - there's a checkbox in the preferences window under "Security" ("Block reported attack site/web forgeries"). That isn't what this bug is about. (In reply to comment #35) > Dan: I don't think that this is in scope for 1.9.2, but please renominate if > you think we can do it. If we don't get this for 1.9.2, we definitely want it > for 1.9.3 I agree that we want it - not sure we can block on it. Marking wanted for now. Mmm, OK. I just realized I never replied to Mike's comment. There are a couple ways we could do this for 1.9.3. I'd probably go with a double-keying approach (surprise!), which can be independent of the third-party work. We can make it a session-only thing to avoid changes to the db schema (and thus more risk). This would mean the safebrowsing cookies get reset on browser close. Ian, would that be a big deal? Also, Ian, if things have changed wrt using the wrkey instead of cookies, please let us know. Disabling cookies for safebrowsing transactions would obviously be a simpler solution on our side.. Sid, As I stated in comments 30 and 34, I am fine with isolating it in a separate cookie jar. (In reply to Sid Stamm [:geekboy] from comment #40) >. Josh is adding things to the cookie service which may help with this. I think this is a grossly underestimated privacy disaster, and it isn't because I don't trust Google. I would be extremely surprised if Google were foolish enough to make the business decision to abuse this data. The problem is, the existence of this functionality in Firefox means that 3rd parties who can control Google through legal (or other) means have access to a list of every IP address a user connects from! (And, of course, such a list can be used to establish a user's presence at a given time and place to a degree of certainty which is considered useful for many applications.) Google could be served with a legal demand such as an NSL requiring them to record this data for much longer (and to not tell anyone), or to hand it over in real time to someone else who retains is. There is no way for Mozilla to be sure this isn't happening. I doubt Ian Fette or anyone else at Google can say they are absolutely certain it isn't happening. If Mozilla is going to keep SafeBrowsing enabled by default, they should refuse to send any unique identifiers with these automatic connections! This bug is tracking the implementation of a separate cookie jar for safebrowsing. Discussion of the underlying principles should be moved to mozilla.privacy. I will be doing some work on this bug in the coming week. Working together with Sid and Jonas to move this forward. ... in the coming weekS ... :-) I am not finding much time to actually work on this unfortunately. We'll probably need to hack up the connection here to dump cookies into a "safebrowsing" jar: Jason, I see you were involved with implementing jars for apps. Is there an easy way to say to necko, "hey, when you make this connection, put cookies in jar x"? ". (In reply to comment #49) > ". Yes, although that's not exactly an implementation of general purpose cookie jars. Currently cookie jars are chosen based on app id (derived from the loadgroup/notification callbacks on the channel, from nsILoadContext) and private browsing status. I suppose we could synthesize a load context which has an app id, since nothing else in desktop/mobile firefox makes use of that to my knowledge. Thanks Josh. Eventually we want to have general purpose cookie jars; off the top of your head can you think of an easy way to create an arbitrary load context that causes all cookies and localstorage to get dumped into a given jar? I'm thinking maybe we could make a note in the principal that for non-apps, there may be a "cookie jar" involved... Sid: it's trivial to create nsILoadContext-looking object from JS: Doing this from C++, I think you want to tweak the stub "LoadContext" class we created for e10s use and give it a new constructor that just takes the appId, etc members directly instead of from a SeralizedLoadContext Have it default to setting mIsNotNull=true and all the other params (except AppID) to false/null. And change the comment here to indicate that the class is going to be used for more than just e10s: Just set the LoadContext as the callbacks for the channel, and it'll get whatever appID you pass in and use the appropriate cookie jar (there's no special logic for creating the jar: we just create a new one when we see a new appID). The interesting question is what appId to pass in, and how to make sure it doesn't conflict with any B2G apps (I assume at some point we'll do safebrowsing requests in B2G if we don't already). You definitely do *not* want to use NECKO_NO_APP_ID: that's the default namespace for desktop. And you don't want NECKO_UNKNOWN_APP_ID, since we assert when we see it in many places. I think we need to add some appID constants for uses like this: the best place for them is probably here, i.e add nsIScriptSecurityManager:SAFEBROWSING_APP_ID And we may want to set aside a range of values just below UINT32_MAX and guarantee that B2G never tries to use those for apps. I propose we keep values above UINT32_MAX - 100 as that range (unless someone thinks it needs to be bigger). (Note: necko currently duplicates the NO_APP and UNKNOWN_APP definitions here: but I don't think we need to add the SAFEBROWSING_APPID there, and we should probably just purge the dupes at some point). Justin Looks like we'll need to reserve some range of AppIds for uses like Safebrowsing (see last half of comment 53). So we need to make sure B2G never tries to assign that range of Ids to apps. Do you know where that code lives? jlebar is asking me why we need a cookie jar for this, and I don't have a great answer.?) This seems like at best a mild improvement. Am I right in thinking that we'd get slightly better privacy if we also periodically deleted the cookie, so it doesn't provide a track of all the IP addresses (aka locations) of the user over time? (Of course if correlating with google.com traffic provides the user's regular google.com identity, then it would easy to reconstruct the location too. But at least this requires more effort). It's not clear to me how often Google's safebrowsing DoS infrastructure could handle us deleting the cookie (honestly I'm confused as to why they really need the cookie in the 1st place). It still seems like a pretty thin privacy win overall, but easy enough to do. I wonder if cookies are considered 'communications metadata' (since they are headers, not HTTP body) by our friendly overlords at the NSA? That's a scary thought. Anyway, the place to change the B2G code to make sure it doesn't hand out the reserved range of ID's I'm proposing is here: This code is :fabrice's, so ask him for review. nsCookieService::RemoveCookiesForApp would be the easiest and best way to get purge safebrowsing cookies if we go down that route. Also, as comment 32 points out, app's cookies don't show up in the cookie manager. I'm not sure how to deal with that in general, but we ought to at least delete the cookie when the user asks to clear cookies (and/or recent history). I assume the place to do that is in the Firefox code somewhere. (In reply to Jason Duell (:jduell) from comment #55) > jlebar is asking me why we need a cookie jar for this, and I don't have a > great answer. Goal = Isolate the safebrowsing traffic from my regular traffic. If we don't, and someone blocks third party cookies (and never visits google.com) they get a google.com cookie. This confuses them and also leads to interesting situations when blocking third party cookies from "non-visited" sites. It's a background service. I argue that we should separate it from (foreground) browsing. >?) Correct. This is most beneficial for folks who don't frequently visit Google. Your auth cookies and others won't be sent to safebrowsing (just the solo cookie set by safebrowsing). > This seems like at best a mild improvement. Am I right in thinking that > we'd get slightly better privacy if we also periodically deleted the cookie, > so it doesn't provide a track of all the IP addresses (aka locations) of the > user over time? Yes, we could do this too. Google says they need the cookie to provide the service. Easiest thing for us is to sandbox the safebrowsing connections. Second easiest is to periodically delete the cookie. I think we can do both, but have to agree on the deletion period with Google. Since has landed, I assume this one should be WONTFIX? Sounds like FIXED to me? You're right, looks like the idea of omitting the cookies completely for sb requests was abandoned. . (In reply to Sid Stamm [:geekboy or :sstamm] from comment #61) > . Please, no follow up bugs that are specific to expiring Google cookies :) There's bug 844623 for expiring third-party cookies and (from) makes it clear that we need stricter expiration times for cookies in general. (In reply to Ian Fette (Google) from comment #34) > I sense a lot of anti-google sentiments, and I doubt that anything I say > will change any of that. However, there are some factual errors that I would > like to clear up here: > 2. Our infrastructure for DoS prevention uses cookies, among other things. > Trying to re-write shared google-wide infrastructure to use "wrkey" instead > of a cookie is not a pleasing thought. I still have not seen any explanation why the questionable cookie has to be against "google.com". For DOS prevention and QOS control any other or more specific domain would work trivially? Also not convinced why the cookie needs to identify every single user perfectly uniquely and why expiry needs to be that long. >?" > 5. We're not getting every URL you visit. We're only getting URLs that match > the (partial) data in the local database, so we could not build up a > complete profile of all that you've viewed anyways. if I am understanding your points 3. and 5. correctly it would be very easy for you to get a list of interesting URLs which a particular user is visiting. It is sufficient to make sure that his local database contains hash collisions for every interesting URL to cause the browser to check those URLs remotely. > If you don't trust google, I doubt anything I've said is going to convince > you. It's not just google, it makes spying much easier for anyone sniffing traffic somewhere in the middle of the connection. (In reply to Richard Z. from comment #63) > It's not just google, it makes spying much easier for anyone sniffing > traffic somewhere in the middle of the connection. Turned out to be a valid concern. NSA uses the PREF cookie to track users. Apologies for bug spam, but it is worth noting this bug was marked resolved 2013-10-24 comment 61 with comment 62 as a final observation. I suspect it is rather pointless making comments here now in a closed bug. If you have any further concerns it may be best to write a new bug report.
https://bugzilla.mozilla.org/show_bug.cgi?id=368255
CC-MAIN-2016-30
refinedweb
6,165
69.52
Predicting stock prices has always been an attractive topic to both investors and researchers. Investors always question if the price of a stock will rise or not, since there are many complicated financial indicators that only investors and people with good finance knowledge can understand, the trend of stock market is inconsistent and look very random to ordinary people. Machine learning is a great opportunity for non-experts to be able to predict accurately and gain steady fortune and may help experts to get the most informative indicators and make better predictions. The purpose of this tutorial is to build a neural network in TensorFlow 2 and Keras that predicts stock market prices. More specifically, we will build a Recurrent Neural Network with LSTM cells as it is the current state-of-the-art in time series forecasting. Alright, let's get start. First, you need to install Tensorflow 2 and other libraries: pip3 install tensorflow pandas numpy matplotlib yahoo_fin sklearn More information on how you can install Tensorflow 2 here. Once you have everything set up, open up a new Python file (or a notebook) and import the following libraries: from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from yahoo_fin import stock_info as si from collections import deque import numpy as np import pandas as pd import matplotlib.pyplot as plt import random import time import os We are using yahoo_fin module, it is essentially a Python scraper that extracts finance data from Yahoo Finance platform, so it isn't a reliable API, feel free to use other data sources such as Alpha Vantage. Learn also: How to Build a Spam Classifier using Keras in Python. As a first step, we need to write a function that downloads the dataset from the Internet and preprocess it: def load_data(ticker, n_steps=50, scale=True, shuffle=True, lookup_step=1, test_size=0.2, feature_columns=['adjclose', 'volume', 'open', 'high', 'low']): # see if ticker is already a loaded stock from yahoo finance if isinstance(ticker, str): # load it from yahoo_fin library df = si.get_data(ticker) elif isinstance(ticker, pd.DataFrame): # already loaded, use it directly df = ticker # this will contain all the elements we want to return from this function result = {} # we will also return the original dataframe itself result['df'] = df.copy() # make sure that the passed feature_columns exist in the dataframe for col in feature_columns: assert col in df.columns if scale: column_scaler = {} # scale the data (prices) from 0 to 1 for column in feature_columns: scaler = preprocessing.MinMaxScaler() df[column] = scaler.fit_transform(np.expand_dims(df[column].values, axis=1)) column_scaler[column] = scaler # add the MinMaxScaler instances to the result returned result["column_scaler"] = column_scaler # add the target column (label) by shifting by `lookup_step` df['future'] = df['adjclose'].shift(-lookup_step) # last `lookup_step` columns contains NaN in future column # get them before droping NaNs last_sequence = np.array(df[feature_columns].tail(lookup_step)) # drop NaNs df.dropna(inplace=True) sequence_data = [] sequences = deque(maxlen=n_steps) for entry, target in zip(df[feature_columns].values, df['future'].values): sequences.append(entry) if len(sequences) == n_steps: sequence_data.append([np.array(sequences), target]) # get the last sequence by appending the last `n_step` sequence with `lookup_step` sequence # for instance, if n_steps=50 and lookup_step=10, last_sequence should be of 59 (that is 50+10-1) length # this last_sequence will be used to predict in future dates that are not available in the dataset last_sequence = list(sequences) + list(last_sequence) # shift the last sequence by -1 last_sequence = np.array(pd.DataFrame(last_sequence).shift(-1).dropna()) # add to result result['last_sequence'] = last_sequence # construct the X's and y's X, y = [], [] for seq, target in sequence_data: X.append(seq) y.append(target) # convert to numpy arrays X = np.array(X) y = np.array(y) # reshape X to fit the neural network X = X.reshape((X.shape[0], X.shape[2], X.shape[1])) # split the dataset result["X_train"], result["X_test"], result["y_train"], result["y_test"] = train_test_split(X, y, test_size=test_size, shuffle=shuffle) # return the result return result This function is long but handy, it accepts several arguments to be as flexible as possible. The ticker argument is the ticker we want to load, for instance, you can use TSLA for Tesla stock market, AAPL for Apple and so on.. scale is a boolean variable that indicates whether to scale prices from 0 to 1, we will set this to True as scaling high values from 0 to 1 will help the neural network to learn much faster and more effectively. lookup_step is the future lookup step to predict, the default is set to 1 (e.g next day). We will be using all the features available in this dataset, which are the open, high, low, volume and adjusted close. The above function does the following: To understand even more better, I highly suggest you to manually print the output variable (result) and see how the features and labels are made. Related: How to Make a Speech Emotion Recognizer Using Python And Scikit-learn. Now that we have a proper function to load and prepare the dataset, we need another core function to build our model: def create_model(input_length, units=256, cell=LSTM, n_layers=2, dropout=0.3, loss="mean_absolute_error", optimizer="rmsprop"): model = Sequential() for i in range(n_layers): if i == 0: # first layer model.add(cell(units, return_sequences=True, input_shape=(None, input_length))) elif i == n_layers - 1: # last layer model.add(cell(units, return_sequences=False)) else: # hidden layers model.add(cell(units, return_sequences=True)) # add dropout after each layer model.add(Dropout(dropout)) model.add(Dense(1, activation="linear")) model.compile(loss=loss, metrics=["mean_absolute_error"], optimizer=optimizer) return model Again, this function is flexible too, you can change the number of layers, dropout rate, the RNN cell, loss and the optimizer used to compile the model. The above function constructs a RNN that has a dense layer as output layer with 1 neuron, this model requires a sequence of features of input_length (in this case, we will pass 50) consecutive time steps (which is days in this dataset) and outputs a single value which indicates the price of the next time step. Now that we have all the core functions ready, let's train our model, but before we do that, let's initialize all our parameters (so you can edit them later on your needs): # Window size or the sequence length N_STEPS = 50 # Lookup step, 1 is the next day LOOKUP_STEP = 1 # test ratio size, 0.2 is 20% TEST_SIZE = 0.2 # features to use FEATURE_COLUMNS = ["adjclose", "volume", "open", "high", "low"] # date now date_now = time.strftime("%Y-%m-%d") ### model parameters N_LAYERS = 3 # LSTM cell CELL = LSTM # 256 LSTM neurons UNITS = 256 # 40% dropout DROPOUT = 0.4 ### training parameters # mean squared error loss LOSS = "mse" OPTIMIZER = "rmsprop" BATCH_SIZE = 64 EPOCHS = 300 # Apple stock market ticker = "AAPL" ticker_data_filename = os.path.join("data", f"{ticker}_{date_now}.csv") # model name to save model_name = f"{date_now}_{ticker}-{LOSS}-{CELL.__name__}-seq-{N_STEPS}-step-{LOOKUP_STEP}-layers-{N_LAYERS}-units-{UNITS}" Let's make sure the results, logs and data folders exist before we train: # create these folders if they does not exist if not os.path.isdir("results"): os.mkdir("results") if not os.path.isdir("logs"): os.mkdir("logs") if not os.path.isdir("data"): os.mkdir("data") Also, you may train offline, if the dataset already exists in data folder, let's load it instead: # load the CSV file from disk (dataset) if it already exists (without downloading) if os.path.isfile(ticker_data_filename): ticker = pd.read_csv(ticker_data_filename) Finally, let's train the model: # load the data data = load_data(ticker, N_STEPS, lookup_step=LOOKUP_STEP, test_size=TEST_SIZE, feature_columns=FEATURE_COLUMNS) if not os.path.isfile(ticker_data_filename): # save the CSV file (dataset) data["df"].to_csv(ticker_data_filename) # construct the model model = create_model(N_STEPS, loss=LOSS, units=UNITS, cell=CELL, n_layers=N_LAYERS, dropout=DROPOUT, optimizer=OPTIMIZER) # some tensorflow callbacks checkpointer = ModelCheckpoint(os.path.join("results", model_name), save_best_only=True, verbose=1) tensorboard = TensorBoard(log_dir=os.path.join("logs", model_name)) history = model.fit(data["X_train"], data["y_train"], batch_size=BATCH_SIZE, epochs=EPOCHS, validation_data=(data["X_test"], data["y_test"]), callbacks=[checkpointer, tensorboard], verbose=1) model.save(os.path.join("results", model_name) + ".h5") We used ModelCheckpoint that saves our model in each epoch during the training. We also used TensorBoard to visualize the model performance in the training process. After running the above block of code, it will train the model for 300 epochs, so it will take some time, here is the first output lines: Epoch 1/300 3510/3510 [==============================] - 21s 6ms/sample - loss: 0.0117 - mean_absolute_error: 0.0515 - val_loss: 0.0065 - val_mean_absolute_error: 0.0487 Epoch 2/300 3264/3510 [==========================>...] - ETA: 0s - loss: 0.0049 - mean_absolute_error: 0.0352 Epoch 00002: val_loss did not improve from 0.00650 3510/3510 [==============================] - 1s 309us/sample - loss: 0.0051 - mean_absolute_error: 0.0357 - val_loss: 0.0082 - val_mean_absolute_error: 0.0494 Epoch 3/300 3456/3510 [============================>.] - ETA: 0s - loss: 0.0039 - mean_absolute_error: 0.0329 Epoch 00003: val_loss improved from 0.00650 to 0.00095, saving model to results\2020-01-08_NFLX-mse-LSTM-seq-50-step-1-layers-3-units-256 3510/3510 [==============================] - 14s 4ms/sample - loss: 0.0039 - mean_absolute_error: 0.0328 - val_loss: 9.5337e-04 - val_mean_absolute_error: 0.0150 Epoch 4/300 3264/3510 [==========================>...] - ETA: 0s - loss: 0.0034 - mean_absolute_error: 0.0304 Epoch 00004: val_loss did not improve from 0.00095 3510/3510 [==============================] - 1s 222us/sample - loss: 0.0037 - mean_absolute_error: 0.0316 - val_loss: 0.0034 - val_mean_absolute_error: 0.0300 After the training ends (or during the training), try to run tensorboard using this command: tensorboard --logdir="logs" Now this will start a local HTTP server "localhost:6006", after going to the browser, you'll see something similar to this: The loss is the Mean Squared Error as specified in the create_model() function, the orange curve is the training loss, whereas the blue curve is what we care about the most, the validation loss. As you can see, it is significantly decreasing over time, so this is working ! Now let's test our model: # evaluate the model mse, mae = model.evaluate(data["X_test"], data["y_test"]) # calculate the mean absolute error (inverse scaling) mean_absolute_error = data["column_scaler"]["adjclose"].inverse_transform(mae.reshape(1, -1))[0][0] print("Mean Absolute Error:", mean_absolute_error) Remember that the output will be a value between 0 to 1, so we need to get it back to a real price value, here is the output: Mean Absolute Error: 4.4244003 Not bad, in average, the predicted price is only far to the real price by 4.42$. Alright, let's try to predict the future price of Apple Stock Market: def predict(model, data, classification=False): # retrieve the last sequence from data last_sequence = data["last_sequence"][:N_STEPS] # retrieve the column scalers column_scaler = data["column_scaler"] # reshape the last sequence last_sequence = last_sequence.reshape((last_sequence.shape[1], last_sequence.shape[0])) # expand dimension last_sequence = np.expand_dims(last_sequence, axis=0) # get the prediction (scaled from 0 to 1) prediction = model.predict(last_sequence) # get the price (by inverting the scaling) predicted_price = column_scaler["adjclose"].inverse_transform(prediction)[0][0] return predicted_price This function uses the last_sequence variable we saved in the load_data() function, which is basically the last sequence of prices, we use it to predict the next price, let's call this: # predict the future price future_price = predict(model, data) print(f"Future price after {LOOKUP_STEP} days is {future_price:.2f}$") Output: Future price after 1 days is 308.20$ Sounds interesting ! The last price was 298.45$, the model is saying that the next day, it will be 308.20$. The model just used 50 days of features to be able to get that value, let's plot the prices and see: def plot_graph)) plt.plot(y_test[-200:], c='b') plt.plot(y_pred[-200:], c='r') plt.xlabel("Days") plt.ylabel("Price") plt.legend(["Actual Price", "Predicted Price"]) plt.show() This function plots the last 200 days of the test set (you can edit it as you wish) as well as the predicted prices, let's call it and see how it looks like: plot_graph(model, data) Result: Great, as you can see, the blue curve is the actual test set, and the red curve is the predicted prices ! Notice that the stock price recently is dramatically increasing, that's why the model predicted 308$ for the next day. Until now, we have used to predict only the next day, I have tried to build other models that use different lookup_steps, here is an interesting result in tensorboard: Interestingly enough, the blue curve is the model we used in the tutorial, which uses the next timestep stock price as the label, whereas the green and orange curves used 10 and 30 lookup steps respectively, for instance, in this example, the orange model predicts the stock price after 30 days, which is a great model for more long term investments (which is usually the case). Now you may think that, but what if we just want to predict if the price is going to rise or fall, not the actual price value as we did here, well you can do it using one of the two ways, one is you compare the predicted price with the current price and you make the decision, or you build an entire model and change the last output's activation function to sigmoid, as well as the loss and the metrics. The below function calculates the accuracy score by converting the predicted price to 0 or 1 (0 indicates that the price went down, and 1 indicates that it went up): def get_accuracy)) y_pred = list(map(lambda current, future: int(float(future) > float(current)), y_test[:-LOOKUP_STEP], y_pred[LOOKUP_STEP:])) y_test = list(map(lambda current, future: int(float(future) > float(current)), y_test[:-LOOKUP_STEP], y_test[LOOKUP_STEP:])) return accuracy_score(y_test, y_pred) Now let's call the function: print(LOOKUP_STEP + ":", "Accuracy Score:", get_accuracy(model, data)) Here is the result for the three models that use different lookup_steps: 1: Accuracy Score: 0.5227156712608474 10: Accuracy Score: 0.6069779374037968 30: Accuracy Score: 0.704935064935065 As you may notice, the model predicts more accurately in long term prices, it reaches about 70.5% when we train the model to predict the price of the next month (30 lookup steps), and it reaches about 86.6% accuracy when using 50 lookup steps and 70 sequence length (N_STEPS). Alright, that's it for this tutorial, you can tweak the parameters and see how you can improve the model performance, try to train on more epochs, say 500 or even more, increase or decrease the BATCH_SIZE and see if does change to the better, or play around with N_STEPS and LOOKUP_STEPS and see which combination works best. You can also change the model parameters such as increasing the number of layers or the number of LSTM units, or even try the GRU cell instead of LSTM. Note that there are other features and indicators to use, in order to improve the prediction, it is often known to use some other information as features, such as the company product innovation, interest rate, exchange rate, public policy, the web and financial news and even the number of employees ! I encourage you to change the model architecture, try to use CNNs or Seq2Seq models, or even add bidirectional LSTMs to this existing model, see if you can improve it ! Also, use different stock markets, check the Yahoo Finance page and see which one you actually want ! If you're not using a notebook or an interactive shell, I have splitted the code to different Python files, each one for its purpose, check it here. Read also: How to Make an Image Classifier in Python using Keras. Happy Training ♥View Full Code
https://www.thepythoncode.com/article/stock-price-prediction-in-python-using-tensorflow-2-and-keras
CC-MAIN-2020-05
refinedweb
2,622
54.42
A simple lock file class based on file locking. Project description flockfile Just a simple python lock file class using file locks. Installation pip install flockfile Usage from flockfile import FlockFile, FileNotLocked # init the class using a file name # optionally, the directory can be set to something other than /tmp lock = FlockFile("myscriptname", lock_dir="/tmp") # lock the file lock.lock() # if this is unsuccessful, exception FileNotLocked will be raised. # the following class method can be used to check lock status assert lock.check_lock() # unlock and delete file lock.unlock() Questions or Issues? Please report as a Gitlab issue: 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/flockfile/
CC-MAIN-2019-51
refinedweb
125
66.54
STYLE(9) BSD Kernel Manual STYLE(9) style - BSD style guide for C source code This manual page specifies the preferred style for C source files in the MirOS source tree. For historical reasons, it's still called "Kernel source file style guide (KNF)", although it has been applied to userland code for almost forever. These guidelines should be followed for all new code. In general, code can be considered "new code" when it makes up about 50% or more of the file(s) involved. This is enough to break pre- cedents in the existing code and use the current style guidelines. /*- * Style guide for the MirOS Project's Coding Styles. * Derived from the OpenBSD KNF (Kernel Normal Form). * indent(1) does not reformat this comment. */ /** * This is a documentation comment in doxygen format. * clang -Wcomment checks them for correct syntax. * Use only if you're honouring that standard. */ /* * VERY important single-line comments look like this. */ /* almost all small single-line comments look like this */ /* A few others are sentences, thus end with a full stop. */ /* * Multi-line comments look like this. Make them real sentences, * in contrast to single-line comments. Fill them so they look * like real paragraphs. indent(1) does reformat this comment. * (XXX: does it? It says slash+star+newline isn't reformatted.) * British spelling is preferred in general. Restrict yourself * to the CESU-8 (UTF-8) Unicode BMP subset or, preferably, the * ISO_646.irv:1991 7-bit character set (ANSI_X3.4-1968). Units * are metric and conform to the SI; use ISO/IEC 60027-2 binary * praefices for multiples of 1024 and SI praefices for 1000s. */ Kernel include files (i.e., <sys/*.h>) come first; normally, you'll need either <sys/types.h> or <sys/param.h>, but not both! <sys/param.h> in- cludes <sys/types.h>, which in turn includes <sys/cdefs.h>, and it's okay to depend on that. Also, add <sys/time.h> before the other system in- cludes, but after <sys/types.h>. Put non-local includes in brackets, lo- cal includes in double quotes. #include <sys/types.h> Machine and device includes follow. If it's a networked program, put the network include files next. #include <net/if.h> #include <net/if_dl.h> #include <net/route.h> #include <netinet/in.h> #include <protocols/rwhod.h> Then there's an optional blank line, followed by the other files from /usr/include. The list of include files should be sorted by group, i.e., <sys/param.h> and <sys/time.h> first, then all other system includes sorted, then machine and device includes sorted (if possible), then net- work includes sorted (if possible), then /usr/include files sorted, then local includes (also sorted if possible). #include <stdio.h> Global pathnames are defined in <paths.h>. Pathnames local to the program go in "pathnames.h" in the local directory. #include <paths.h> Then there's a mandatory blank line, and the user include files. #include "pathnames.h" The includes block is separated by another blank line from the file iden- tification block. Add the CVS (or RCS) ID(s) of the file and, if taking over old source code, the SCCS ID and __COPYRIGHT as well; place another blank line after that. It is discouraged listing RCS IDs as comments at the beginning of files if it's possible (this excludes most header files, although some use a technique to define their ID to a macro which is ex- panded by the main source file or somesuch) to use these macros; copy them over, the macros are safe to be used more than once in the same file in MirOS. Note that this may introduce CVS branch merge conflicts. These three macros are defined in <sys/cdefs.h>: __COPYRIGHT("@(#) Copyright (c) 1989, 1993\n\ The Regents [...] reserved.\n"); __SCCSID("@(#)cat.c 8.2 (Berkeley) 4/27/95"); __RCSID("$MirOS: src/bin/cat/cat.c,v [...] Exp $"); All functions are prototyped somewhere. Function prototypes for private functions (i.e., functions not used else- where) go at the top of the first source module. In userland, functions local to one source module should be declared 'static'. This should not be done in kernel land since it makes it almost impossible to use the kernel debugger. Functions used from other parts of the kernel are prototyped in the relevant include file. It is strongly recommended that include files do not include other header files. Document interdependencies in the relevant manual pages. Functions that are used locally in more than one module go into a separate header file, e.g., "extern.h". This file is allowed to precede the, otherwise sorted, list of local include files. Do not use the same names as other well-known header files, such as these in /usr/include, used by library dependencies or part of other applications that are often pulled in by the make(1) ".PATH" command. Use of the __P macro has been deprecated. It is allowed in code imported from other sources but should not be used in native MirOS code. Only write out prototypes with full variable names in manual pages; in all other files, prototypes should not have variable names associated with the types (this is what manpages are for); i.e., use: void function(int); not: void function(int a); Lining up prototypes after type names is discouraged because it is hard to maintain; use a single space. If lining up (existing code), prototypes may have an extra space after a tabulator to enable function names to line up: static char *function(int, const char *); static void usage(void); Function or macro names and their argument list are never separated by a space. Use __dead from <sys/cdefs.h> for functions that don't return, i.e., __dead void abort(void); void usage(int) __dead; Use gcc attributes extensively to catch programming errors, e.g., wchar_t *ambsntowcs(const char *, size_t) __attribute__((__nonnull__ (1))) __attribute__((__bounded__ (__string__, 1, 2))); /* use of an argument mandated by function pointer API */ static int x_del_char(int __unused); In header files, put function prototypes within matching pairs of __BEGIN_DECLS / __END_DECLS. This makes the header file usable from languages like C++. Labels start at the second column, i.e. are prefixed with only a single space (ASCII 20 hex) character, no matter which block they are in. Macros are capitalised and parenthesised and should avoid side-effects. If they are an inline expansion of a function, the function is defined all in lowercase; the macro has the same name all in uppercase. In rare cases, function-like macros that evaluate their arguments only once are allowed to be treated like real functions and use lowercase. If the macro needs more than a single line, use braces. Right-justify the backslashes, as the resulting definition is easier to read. Use a single space after the #define cpp(1) command and, except if lining up single-line macros, after the macro name or closing parentheses. If the macro encapsulates a compound statement, enclose it in a "do" loop, so that it can safely be used in "if" statements, like shown below. Do not forget the CONSTCOND lint(1) command. Any final statement-terminating semicolon shall be sup- plied by the macro invocation rather than the macro, to make parsing easier for pretty-printers and editors. #define MACRO(x, y) do { \ variable = (x) + (y); \ (y) += 2; \ } while (/* CONSTCOND */ 0) Enumeration values are all uppercase. enum enumtype { ONE, TWO } et; When declaring variables in structures, declare them sorted by use, then by size (largest to smallest), then by alphabetical order. You may at- tempt to optimise for structure padding to avoid wasting space. The first category normally doesn't apply, but there are exceptions. Each one gets its own line. It is strongly recommended to not line them up either. Use single spaces, but line up the comments if desirable or, better, place them on their own lines just before the item they apply to.; }; struct foo *foohead; /* head of global foo list */ Use queue(3) and tree(3) macros rather than rolling your own lists when- ever possible. Thus, the previous example would be better written: #include <sys/queue.h> struct foo { /* queue glue for foo lists */ LIST_ENTRY(foo) link;; /* comment for mumble */ struct mumble amumble; int bar; }; /* head of global foo list */ LIST_HEAD(, foo) foohead; typedefs ending in "_t", except as specified in Standard C or by POSIX, such as "uint32_t" (which requires <stdint.h>, or its superset <inttypes.h>). consistency, getopt(3) should be used to parse options. Options should be sorted in the manual page SYNOPSIS and DESCRIPTION, any usage() or similar function, the getopt(3) call and the switch statement, unless parts of the switch cascade. Elements in a switch statement that cascade should have a FALLTHROUGH comment. Numerical arguments should be checked for accuracy. Code that cannot be reached should have a NOTREACHED com- ment. The CONSTCOND, FALLTHROUGH, and NOTREACHED comments benefit lint.; case '?': /* redundant here but ok */ default: usage(); /* NOTREACHED */ } argc -= optind; argv += optind; Cast expressions and the value to be casted are never separated by a space; use parentheses about the latter if it's a compound expression. Use a space after keywords (if, while, for, return, switch) but not unary operators like sizeof. It is recommended to put parentheses around the return argument as well, although this is not a strict requirement. It helps when debugging (define return to a debug expression) though, except for void functions. No braces are used for control statements with zero or only a single statement unless that statement is more than a single line, in which case they are permitted. Always document single-semicolon bodies with a com- ment; here, same line is ok. for (p = buf; *p != '\0'; ++p) ; /* nothing */ while (/* CONSTCOND */ 1) /* or: for (;;) */ stmt; while (/* CONSTCOND */ 1) { z = a + really + long + statement + that + needs + two + lines + gets + indented + four + spaces + on + the + second + and + subsequent + lines; } while (/* CONSTCOND */ 1) { if (cond) stmt; } Parts of a for loop may be left empty, although while loops are prefer- able especially in such cases. Don't put declarations inside blocks un- less the routine is unusually complicated. for (; cnt < 15; cnt++) { stmt1; stmt2; } Indentation is an 8 character tab. Second level indents are four spaces. while (cnt < 20) z = a + really + long + statement + that + needs + two + lines + gets + indented + four + spaces + on + the + second + and + subsequent + lines; Do not add whitespace at the end of a line, and only use tabs followed by spaces to form the indentation. Never use more spaces than a tab will produce and do not use spaces in front of tabs. vim users are required to put "let c_space_errors = 1" into their ~/.vimrc. Closing and opening braces go on the same line as the else. Braces that aren't necessary may be left out, unless they cause a compiler warning. if (test) stmt; else if (bar != NULL) { stmt; stmt; } else stmt; Avoid doing multiple assignments in one statement, like this: /* bad example */ if (foo) { stmt; stmt; } else if (bad) *wp++ = QCHAR, *wp++ = c; else stmt; /* write this as */ if (foo) { stmt; stmt; } else if (good) { *wp++ = QCHAR; *wp++ = c; } else stmt; Do not use spaces after function names. Commas have a space after them. Do not use spaces after '(' or '[' or preceding ']' or ')' characters. if ((error = function(a1, a2))) exit(error); Use positive error codes. Negative errors (except -1) are something only the Other OS does.); It's much better to break after an operator if you need to apply line breaks. This is especially true for shell scripts. The above example could be rewritten as: a = (((b->c[0] + ~d) == (e || f)) || (g && h)) ? \ i : (j >> 1); k = !(l & FLAGS); Lines ought to be not larger than 80 characters. Stick to 75 characters or less if possible, but in some cases it's ok to put a character in the 80th column. Descriptions should not be longer than 66 characters, eMails must not be longer then 72 characters per line. In object-oriented languages, it may be acceptable to use up to 100 characters per line. Exits and returns should be 0 on success, and non-zero for errors. /* * avoid obvious comments such as * "Exit 0 on success." */ exit(0); } The function type should be on a line by itself preceding the function. This eases searching for a function implementation: $ grep -r '^function' . static char * function(int a1, int a2, float fl, int a4) { When declaring variables in functions, declare them sorted by size (larg- est to smallest), then in alphabetical order; multiple ones per line are okay. If a line overflows, reuse the type keyword. Declarations must fol- low ISO C99 or at least ANSI C. Be careful not to obfuscate the code by initialising variables in the de- clarations. Use this feature only thoughtfully. DO NOT use function calls in initialisers! struct foo one, *two; double three; int *four, five; char *six, seven, eight, nine, ten, eleven, twelve; four = myfunction(); Do not declare functions inside other functions: ANSI C says that such declarations have file scope regardless of the nesting of the declara- tion. Note that indent(1) comes with a sample .indent.pro which understands most of these rules, starting from MirOS #9. As of MirOS #11, it will also be installed into the user home skeleton directory. Use of the "register" specifier is discouraged in new code. Optimising compilers such as gcc can generally do a better job of choosing which variables to place in registers to improve code performance. The excep- tion to this is in functions containing assembly code where the "register" specifier is required for proper code generation in the ab- sence of compiler optimisation. In C99 code, use "__restrict__" instead of "restrict" if required. The <sys/cdefs.h> include file defines them out if an old compiler is used. When using longjmp() or vfork() in a program, the -Wext im- proper code generation when optimisation is enabled. Note that for pointers, the location of "volatile" specifies if the type-qualifier ap- plies to the pointer or the thing being pointed to. A volatile pointer is declared with an optional extra space and "volatile" to the right of the "*". Example: char * volatile foo; says that "foo" is volatile, but "*foo" is not. To make "*foo" (the thing being pointed to) volatile use the syntax volatile char *foo; If both the pointer and the thing pointed to are volatile use volatile char * volatile foo; "const" is also a type-qualifier and the same rules apply. Assume string literals are constant. Never make use of broken C APIs such as strchr(3) to "cast away" the "const" qualifiers. The description of a read-only hardware register might look something like: const volatile char *reg; Global flags set inside signal handlers should be of type "volatile sig_atomic_t" if possible. This guarantees that the variable may be ac- cessed as an atomic entity, even when a signal has been delivered. Global variables of other types (such as structures) are not guaranteed to have consistent values when accessed via a signal handler. NULL is the preferred null pointer constant. Never use 0 in place of NULL. Use NULL instead of (type *)0 or (type *)NULL in all cases except for arguments to variadic functions where the compiler does not know the type. Don't use '!' for tests unless it's a boolean (or an integral flag used in a boolean context, almost certainly with a bitwise AND operation, since otherwise using a bool would be correct), i.e., use if (p != NULL && *p == '\0') not if (p && !*p) Use <stdbool.h> for boolean values, not int. Routines returning void * should not have their return values cast to any pointer type. Functions used as procedures should not have their return value explicitly cast to void, either. The exception are function-like macros like sigaddset(3), where failure to do so may result in compiler warnings about unused LHS in comma operations. You can assume that pointers to variables and function pointers share the same address space and have the same size as ptrdiff_t. Use err(3) or warn(3), don't roll your own! if ((four = malloc(sizeof(struct foo))) == NULL) err(1, NULL); if ((six = (int *)overflow()) == NULL) errx(1, "Number overflowed."); return (eight); } Old-style function declarations looked like this: static char * function(a1, a2, fl, a4) int a1, a2; /* declare ints, too, don't default them */ float fl; /* beware double vs. float prototype differences */ int a4; /* list in order declared */ { ... } You really ought to replace them with ISO C99 function declarations. Long parameter lists are wrapped with a normal four space indent. Variable numbers of arguments should look like this: #include <stdarg.h> void vaf(const char *fmt, ...) __attribute__((format (printf, 1, 2))); void vaf(const char *fmt, ...) { va_list ap; va_start(ap, fmt); STUFF; va_end(ap); /* No return needed for void functions. */ } static void usage(void) { /* from crt0.o */ extern const char *__progname; Usage statements should take the same form as the synopsis in manual pages. Options without operands come first, in alphabetical order inside a single set of braces, followed by options with operands, in alphabeti- cal order, each in braces, followed by required arguments in the order they are specified, followed by optional arguments in the order they are specified. A bar ('|') separates either-or options/arguments, and multiple options/arguments which are specified together are placed in a single set of braces. If numbers are used as options, they should be placed first, as shown in the example below. Uppercase letters take precedence over lowercase. Note that the options list in manual pages should be purely alphabetical, ex- cept that the no-argument options are listed first. "usage: f [-12aDde] [-b barg] [-m marg] req1 req2 [opt1 [opt2]]\n" "usage: f [-a | -b] [-c [-de] [-n number]]\n" The __progname string may be used instead of hard-coding the program's name. It's better to place the extern declaration outside of the function body though, as it's file-global in ISO C either way, and that makes this fact more visible. fprintf(stderr, "usage: %s [-ab]\n", __progname); exit(1); } New core kernel code should be reasonably compliant with the style guides. The guidelines for third-party maintained modules and device drivers are more relaxed but at a minimum should be internally consistent with their style; the current MirPorts Framework package tools are a bad example of style inconsistency (such as three different indentation styles: three spaces, four spaces and KNF one tab) and a good example of why it must be prevented. Whenever possible, code should be run through at least one code checker (e.g., "gcc -Wall -W -Wpointer-arith -Wbad-function-cast ...", "make __CRAZY=Yes", lint(1) or splint from the ports tree) and produce minimal warnings. Try to write source code that will compile without any warn- ings, failures or malfunctions with gcc3 -Os -std=c99 -Wbounded, pcc -O, SUNWcc, and gcc4 -O2 -fwrapv -fno-strict-aliasing -Wformat. Note that documentation follows its own style guide, as documented in mdoc.samples(7). This however does not invalidate the hints given in this guide. Shell scripts also follow what is applicable from this guide, ex- cept that function declarations are all on one line; use Korn syntax throughoutly; never use the ` character; it is okay to use reasonably re- cent mksh(1) extensions. Do not use the typeset built-in command, always write local instead. function bla { (( x )) && foo=abcdefghijklmnopqrstuvwxyz$(fnord \ ABCDEFGHIJKLMNOPQRSTUVWXYZ) [[ $foo = @([a-z_]*([a-z0-9_]) ]] || exit 1 } /usr/share/misc/licence.template Licence preferred for new code. ~/.indent.pro should contain at least the following items: -c0 -ci4 -di0 -nbs -ncsp -nfc1 -nlp -nlpi -Tbool -Tint16_t -Tint32_t -Tint64_t -Tint8_t -Tintmax_t -Tintptr_t -Tmbstate_t -Toff_t -Tptrdiff_t -Tsize_t -Tssize_t -Ttime_t -Tuint16_t -Tuint32_t -Tuint64_t -Tuint8_t -Tuintmax_t -Tuintptr_t -Twchar_t -Twint_t and a bunch of others. Note that the -c0 option might be problematic for existing code and may be better left out. mircvs://src/usr.bin/indent/.indent.pro contains a more complete list; even then, indent(1) does only basic help to apply KNF. indent(1), lint(1), err(3), queue(3), warn(3), mdoc.samples(7) This man page is largely based on the src/admin/style/style file from the BSD 4.4-Lite2 release, with updates to reflect the current practice and desire first of the OpenBSD project, then for the MirOS source tree, in- cluding an improved Open Source licence. MirOS BSD #10-current December 14, 2012 9.
http://www.mirbsd.org/htman/i386/man9/style.htm
CC-MAIN-2013-20
refinedweb
3,431
64.61
The OmniBoard is a novel Electric Skateboard-Hoverboard Hybrid controllable through a Bluetooth Smartphone Application. It is able to move with all three degrees of freedom achievable by both boards combined, go forward, spin around its axis, and strafe sideways. This allows you to move in whichever direction you desire as well as do nifty tricks that you would not otherwise be able to with your typical mode of transportation such as (electric) skateboards, hoverboards, cars, bikes, etc. My friend and I decided to build the OmniBoard as a fun exercise and challenge, as well as enter to some Instructables contests, namely the wheels challenge. We wanted to make something that has never been done before, is cool, and would be useful. As the public transit system is often unreliable, and city traffic is awful during the morning and afternoon drive to and from work, an alternative mode of transportation such as biking or skateboard are useful. Electric skateboards and bikes are useful for long range commutes, but there are already many consumer and DIY solutions for this topic. So we decided to reinvent the wheel, quite literally, and make a new and fun OmniBoard. Step 1: Tools and Materials Drive system - (4) Omni Wheels - (4) 60 tooth pulley - (4) 20 tooth pulley - (4) GT2 Timing Belt (we used 140 tooth) - (8) 7mm ID, 19mm OD bearing* - (20) M5 (or similar size) machine screws, roughly 25 mm long* - (28) Nuts, same size as machine screws* - (32) No. 2 wood screws, 3/8" long* - (16) Angle brackets, preferably four holes, must be at least 1/2" from corner to screw hole* - 1'x2' Plywood sheet* - Skateboard surface Electronics: Drive System - (4) DC Motors - (4) Electronic Speed Controllers (ESC) - Power Distribution Board (PDB) - 16AWG Silicone wire - Red and Black - XT90 Connector Parallel Splitter - XT90 Connector Male with Tail - (8 Pairs) 4mm Bullet Connector - (4 Pairs) XT60 Connectors - (2) LiPo Batteries Remote Control - Double-Sided Perf Board* - LM7805 Voltage Regulator* - 24AWG Solid Core Wires - Assorted Colour* - HC-05 Bluetooth Module* - Arduino Uno v3* - (32 pin) Dual-Sided Male Pin Headers* - (12 pin) Single-Sided ale Pin Headers* Tools: - Soldering station and Solder - Wire cutters - Wire strippers - Pliers - Scissors - Drill bits:1-3/8", 3/4", 1/4" Equipment: - 3D Printer - Laser Cutter - Band Saw - Drill Press *Gotten from the local electronics store or hardware store. Step 2: How It Works The Omniboard is an electric skateboard and hoverboard in one! It is capable of moving forward and back, side to side, and rotating, all controlled by a joystick on your phone. The Omniboard is powered by four motors each attached to an omnidirectional wheel. Because the omni wheels are allowed to slide laterally, varying the speed and direction of each motor allows the board to move in any direction the user chooses, as depicted in the image above. Step 3: Assembling the Omni Wheel Axles The parts you'll need for assembling the axles are: - (8) 3D printed bearing spacer - (4) 3D printed large pulley spacer - (8) Bearing - (4) Omni wheel - (4) Large pulley - (4) 3x3x80mm keystock First, you want to put a bearing spacer on the end of the shaft as shown. The spacer is made to be a very tight fit, so I recommend using a vice or mallet to get it on. If it's too loose a fit, shift it a little further up the keystock and attach a collar. You need not worry about a collar for the other end. Next you slide the omni wheel on followed by a bearing spacer facing the opposite direction. You can slip the bearings on now (it doesn't matter as much of they're not snug) and it should look like the picture. Finally, you can slip the long skinny pulley spacers into the pulleys. At this point, do not tighten the pulley set screws or put them on the keystock. Those come later. Step 4: Cutting and Drilling the Omni Wheel Trucks This is where your laser cutter and 3/8" thick plywood comes in handy! The CAD for laser cutting the frame is attached in a .dxf format. Next you will drill two holes over the little crosses that the laser cutter will leave on the plywood. The slightly smaller cross will be drilled with the 3/4" bit only 1/4" of the way through, while the larger cross will be drilled with the 1-3/8" bit all of the way through. It is very important that you remember for half the pieces to cut the 3/4" holes from one side and the other half from the other side. Next drill a smaller 3/8" hole through the middle of the 3/4" holes, all the way through the layer you didn't cut before. Finally, screw the angle brackets to the shorter sides of the rectangular pieces. You have almost everything you need now to assemble the omni wheel trucks. Step 5: Assembling the Omni Wheel Trucks Now we can finish the truck assembly! You'll need the parts from the last two steps plus: - (4) Timing belt - (4) 3D printed small pulley spacer - (4) Small pulley - (4) Motor Slip each plywood side onto the bearings. If the 3/4" holes don't fit easily over the bearings, use a Dremel to sand them a bit wider. Once they fit on, put the pulley over the protruding keystock and tighten the set screws. Screw the rectangular piece into the notch above the omni wheel. At this point, check that your omni wheel spins freely. If it doesn't, your pulley might be clamping down on the plywood. Raise it a bit further up the keystock. Next we'll fit the motors in. The 1-3/8" holes are a bit too small, so slowly sand the inner circle with a Dremel until the motor fits snugly inside. Be careful not to force the motor in and deform the housing. Once the motor in in position, slip the belt over the small pulleys, then the small pulleys over their spacers and onto the 3.175mm motor shaft. Tighten the set screws. For the sake of compactness and symmetry, you'll want to put the pulleys and belts on one side of the truck for two of them and the other side for the other two. Step 6: Mounting to the Skateboard Platform Now we're going to attach the trucks to the skateboard platform. You could make yours from plywood and grip tape; ours was taken from an old skateboard. First, you'll want to drill 1/4" holes in both sides of the plywood as shown in the picture. In each hole, attach an angle bracket with an M5 screw and double nut it on the inner side to prevent it from coming loose due to vibrations. Measure and drill the holes that allow you to mount the trucks as close to the ends and at as steep a taper angle as possible while staying within the footprint of the platform. Now flip it over and give it a load test! Step 7: Soldering the Motors Solder the 4mm male bullet connectors to a wire which will connect to the motors, then solder this wire onto the motor terminals. For cable organization, each wires are cut to 6cm and stripped from both ends Tip: It is easier to solder the wires onto the bullet connectors first then solder it to the motor than the other way around. To solder the bullet connector onto the wire, place it onto an insulated alligator clip of the helping hand (as the heat dissipates quickly from the body of the bullet connector to the metallic, heat conducting helping hand body). Then pool some solder onto the the bullet connector, about half way and while keeping the iron in the connector, dip the wire onto the solder pool, as shown in the video. Then heat shrink the wire and the bullet connector. Then, place the wire next to the motor terminal and hold it upright using the helping hand. I used the solder roll to hold the motor upside down. Then solder the wire onto the motor terminal. The order and colour of the wires are ambiguous and does not matter, as the ordering can be switched to reverse the rotation, which will be done in the next steps if necessary. Step 8: Soldering ESC Battery Connectors Prior to soldering, cut some heat shrink for each of the wires which will be used to insulate the exposed soldered ends. Cut of one of the leads to the battery connector, strip it, slip the heat shrink in, and solder it to the XT60 connector with the red connecting to the positive terminal of the XT60 and the black to the negative terminal of the XT60. Warning: Only cut the ESC wires one at a time, as there is a capacitor that may be charged in between the positive and negative terminals which will short if the scissors or wire cutters cut through both at once. To solder the wire onto the XT60 connector, use the helping hands to hold the XT60 connector's body. Then, pool some solder to the XT60 terminal about half way and while keeping the soldering iron on the XT60 connector, dip the wire into the liquid solder pool, as shown in the video from the previous step. Once cool, slide the heat shrink down to insulate the exposed end and heat it with the sides of the soldering iron. Repeat this for the rest of the wires of the battery connectors of the ESCs. Step 9: Soldering the Power Distribution Board (PDB) The PDB will take in input from the two Lithium Polymer (LiPo) batteries with a combined voltage and current of 11.1V and 250A, respectively, and distribute it to the four ESCs. Tip: It is easier to solder the male XT90 connector leads to the PDB pads first, then the16 AWG wires to the ESCs, followed by the XT60 connectors onto these wires. Before, soldering the wires, cut the heat shrink to fit each of the wires, so it can be slipped onto the exposed soldered end later to prevent short circuiting. To solder the wires onto the PDB pads, 10: Connecting the Wires Connect the motor wires to the bullet connector terminals of the ESC. Then, plug in the white signal pin from the ESC to pin 9 and the black ground pin to the GND pin on the Arduino. Dual lock strips was used to secure all the ESCs and wires to the board. To check if the rotation of the motors are correct (spinning towards the front), by run the sample code on the Arduino below. #include <Servo.h> Servo motor; byte clockwiseSpeed = 110; unsigned long interval = 1500; int motorPin = 9; void setup() { Serial.begin(9600); motor.attach(motorPin); Serial.println("Beginning test"); } void loop() { motor.write(clockwiseSpeed); Serial.println("Stop Motor From Spinning"); delay(interval); } The order of wires connected from the ESC to the motor determine the rotation of the motor. If the motor spin is counterclockwise, then keep note of the motor and change the boolean in the controller code on step "Programming the Omniboard Controller". If it is spinning clockwise towards the front, then the rotation is correct. Do this for each of the four motors. If the motor is not spinning, double check all your connectors if there are any cold solder resulting in a loose connection. Step 11: Changing the ESC Mode By default, the brushed ESCs are at practice mode. This is indicated by the blinking LED light. In order to programmatically control a motor to the reverse direction, climbing mode is needed. To access this mode, connect the ESC to the Arduino by plugging in the white signal pin from the ESC to pin 9 and the black ground pin to the GND pin on the Arduino. Then upload and run the following program to the Arduino board: #include <Servo.h> Servo motor; byte stopSpeed = 90; unsigned long interval = 1500; int motorPin = 9; void setup() { Serial.begin(9600); motor.attach(motorPin); Serial.println("Beginning test"); } void loop() { motor.write(stopSpeed); Serial.println("Stop Motor From Spinning"); delay(interval); } Turn on the ESC, then press and hold the programming button for two seconds. The LED indicator will now be steady as opposed to flashing, which means the mode has been successfully changed to climbing mode. Step 12: Interfacing With Bluetooth Module and Phone The HC-05 Bluetooth module allows the Arduino to connect with a phone to allow wireless control of the skateboard through an App. As I have found issues certain faulty the Bluetooth module interfaces, it would be better to test it out first before soldering the final circuitry, We will be using 4 of the 6 pins on the Bluetooth module. These are: Tx (Transmit), Rx (Receive), 5V, and GND (Ground). Connect the Tx and Rx pins from the HC-05 Bluetooth module to pins 10 and 11 on the Arduino, respectively. Then, connect the 5V pin and GND pins to the pins with the label the same on the Arduino. On the Blynk App, add the bluetooth and button widgets, as shown in the images above. Then, assign digital pin D13, which is connected to the built-in LED on the Arduino Uno, to the button. Upload and run the following code to the Arduino with the bluetooth module plugged in and open serial monitor to see if the bluetooth module has connected. Then toggle the On/Off button and observe the built-in LED on the Arduino change. #define BLYNK_PRINT Serial<br> #include <BlynkSimpleSerialBLE.h> #include <SoftwareSerial.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "Your Authentication Token"; SoftwareSerial SerialBLE(10, 11); // RX, TX BLYNK_WRITE(V1) { int pinValue = param.asInt(); // assigning incoming value from pin V1 to a variable } void setup() { Serial.begin(9600); // debug console SerialBLE.begin(9600); Blynk.begin(SerialBLE, auth); Serial.println("Waiting for connections..."); } void loop() { Blynk.run(); } Step 13: Soldering the Arduino Shield In order to clean up the circuitry and loose jumper wires from the prototype, we will be soldering an Arduino shield that connects to each of the ESCs and Bluetooth module, as well as a power supply to the Arduino. Solder the following schematic above onto a double-sided perf board. I first sized and plugged in the Dual-Sided Male Pin Headers onto the Arduino female headers then soldered it to the top side of the perf board for both side. Once they were soldered, I removed it from the Arduino board to solder the bottom portion of the board. Then, I soldered the ESC Single-Sided Male Pin Headers in 4 sets of 3 onto the bottom side of the perf board. After which, I placed the HC-05 Bluetooth module upright and soldered the connectors onto the bottom side of the perf board as well. Since the Bluetooth module requires a 5V voltage input and the PDB is only regulated to 12V, I used a LM7805 to step down the current to limit the current draw from the Arduino. This same 5V supply is also connected to the 5V pin of the Arduino such that the Arduino can be powered through the shield as opposed to an additional barrel jack adaptor. The pins of the LM7805 was soldered to the bottom side of the perf board with the voltage regulator component sitting atop the perf board as shown in the image above. I soldered all the power connections to each of the components and ESC pin headers and HC-05 Bluetooth module as described in the schematic. The 12V output of the PDB was then soldered to the VCC input (left most) pin and ground pin (middle) of the LM7805 voltage regulator. Lastly, each of the ESC signal pin headers and HC-05 Bluetooth module Tx and Rx pins to the Arduino digital pins through the Dual-Sided Male Pin Headers as shown in the schematic. Step 14: Creating the App Through Blynk The Omniboard will be controlled over Bluetooth using any smartphone via the Blynk App. Blynk is an Android and iOS app that allows one to use modules and widgets that can interface with several microcontrollers with Bluetooth or wireless capabilities or Bluetooth / wireless modules, like the HC-05. 1. Install Blynk onto your phone. 2. Create an account and login 3. Create a new project and name it. I named mine "Omniboard controller", select Arduino Uno as the microcontroller, and select Bluetooth as the interface type. 4. Drag and drop the following widgets on screen: Bluetooth, Map, 2 Buttons, and Joystick Step 15: Interfacing Widgets With Arduino The button will be used to toggle Hoverboard mode vs Skateboard mode. Hoverboard mode allows for precise control of spin and strafe while holding a cruise velocity. While, skateboard mode gives precise control of forward velocity and spin. The joystick will control the skateboard with two degrees of freedom which are interchanged by the toggle button. The map will display your current location as well as waypoints for other places to go to. The bluetooth allows the interface to connect with a Bluetooth module. Joystick Settings: - Select "Merge" for the output type and assign it to Virtual pin V1. Buttons Setting: - Name the first button "Hover Mode" and the second button "Cruise Control." - Assign the output of the first button to Virtual pin V2 and change the Mode to "Switch." - Assign the output of the second button to Virtual pin V3 and change the Mode to "Switch." - Rename the toggle names of the first buttons as "Hover" and "Skate" and retain "ON" and "OFF." Map Settings: - Assign the input to be V4. Bluetooth Settings: Select the Bluetooth widget on the Blynk app and connect with your module. The default password for the Bluetooth module is '1234' Step 16: Programming the Omniboard Controller The dynamics of the Omniboard was programmed based on the dynamics algorithm derived from the "How it Works" section. Each of the 3 degrees of freedom, forwards, strafe, and spin are calculated independently and are superimposed on each other to result in full range of motion control of the Omniboard. The control of each motors are linearly proportional to the movement of the joystick. Upload and run the following code to the Arduino. #define BLYNK_PRINT Serial<br> #include <BlynkSimpleSerialBLE.h> #include <SoftwareSerial.h> #include <Servo.h> Servo motorFR; Servo motorFL; Servo motorBR; Servo motorBL; bool motorFRrev = true; bool motorFLrev = true; bool motorBRrev = true; bool motorBLrev = true; float motorFRang = 330.0*PI/180.0; float motorFLang = 30.0*PI/180.0; float motorBRang = 210.0*PI/180.0; float motorBLang = 150.0*PI/180.0; float motorFRspeedT; float motorFLspeedT; float motorBRspeedT; float motorBLspeedT; float motorFRspeedR; float motorFLspeedR; float motorBRspeedR; float motorBLspeedR; float maxAccel = 10; byte forwardSpeed = 110; byte backSpeed = 70; byte stopSpeed = 90; // change to experimenally deternmied number int cruiseControl; int yawMode; // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "8523d5e902804a8690e61caba69446a2"; SoftwareSerial SerialBLE(10, 11); // RX, TX BLYNK_WRITE(V2) {cruiseControl = param.asInt();} BLYNK_WRITE(V3) {yawMode = param.asInt();} WidgetMap myMap(V4); BLYNK_WRITE(V1) { int x = param[0].asInt(); int y = param[1].asInt(); if (!cruiseControl) calcTranslation(x, y); if (yawMode) calcRotation(x, y); else { motorFRspeedR = 0; motorFLspeedR = 0; motorBRspeedR = 0; motorBLspeedR = 0; } writeToMotors(); } void setup() { motorFR.attach(9); motorFL.attach(6); motorBR.attach(5); motorBL.attach(3); delay(1500); // wait for motors to initialize // Debug console Serial.begin(9600); SerialBLE.begin(9600); Blynk.begin(SerialBLE, auth); Serial.println("Waiting for connections..."); // If you want to remove all points: //myMap.clear(); int index = 1; float lat = 43.653172; float lon = -79.384042; myMap.location(index, lat, lon, "value"); } void loop() { Blynk.run(); } void calcTranslation(int joyX, int joyY) { float normX = (joyX - 127.0)/128.0; float normY = (joyY - 127.0)/128.0; motorFRspeedT = (normY*cos(motorFRang) + normX*sin(motorFRang))*(1 - 2*motorFRrev); motorFLspeedT = (normY*cos(motorFLang) + normX*sin(motorFLang))*(1 - 2*motorFLrev); motorBRspeedT = (normY*cos(motorBRang) + normX*sin(motorBRang))*(1 - 2*motorBRrev); motorBLspeedT = (normY*cos(motorBLang) + normX*sin(motorBLang))*(1 - 2*motorBLrev); } void calcRotation(int joyX, int joyY) { float normX = (joyX - 127.0)/128.0; float normY = (joyY - 127.0)/128.0; motorFRspeedR = joyX*(1 - 2*motorFRrev); motorFLspeedR = -joyX*(1 - 2*motorFLrev); motorBRspeedR = -joyX*(1 - 2*motorBRrev); motorBLspeedR = joyX*(1 - 2*motorBLrev); } void writeToMotors() { float motorFRspeed = motorFRspeedT + motorFRspeedR; float motorFLspeed = motorFLspeedT + motorFLspeedR; float motorBRspeed = motorBRspeedT + motorBRspeedR; float motorBLspeed = motorBLspeedT + motorBLspeedR; long motorFRmapped = map((long) (100*motorFRspeed), -100, 100, backSpeed, forwardSpeed); long motorFLmapped = map((long) (100*motorFLspeed), -100, 100, backSpeed, forwardSpeed); long motorBRmapped = map((long) (100*motorBRspeed), -100, 100, backSpeed, forwardSpeed); long motorBLmapped = map((long) (100*motorBLspeed), -100, 100, backSpeed, forwardSpeed); motorFR.write(motorFRmapped); motorFL.write(motorFLmapped); motorBR.write(motorBRmapped); motorBL.write(motorBLmapped); } Step 17: Installing the Electronics Housing In order to keep all the wires and parts from dangling out of the bottom, 3D print the housing attached, then screw it onto the skateboard using M5 screws. Step 18: Painting The inspiration for the top deck design are PCB circuitry and patterns. To do this, first the bottom of the skateboard is covered my wrapping painter's tape around it. Then the whole top deck is coated with white paint. Once dry, it's masked with the negative of the circuit pattern, then repainted with a black coat. Then, peel of the maskings from the top layer carefully and voila, a cool-looking skateboard. I encourage you to personalize the design for your own Omniboard and exercise your creative freedom. Step 19: Test and Demo. Plug in the batteries to the XT90 Splitter in parallel, then plug it in to the PDB. Connect the ESC's to the ESC pin headers on the custom-made Arduino Shield, then turn on the ESCs. Launch your Blynk app and connect to the Arduino via Bluetooth. Control your skateboard with the joy stick. Enjoy and Have fun! Second Prize in the Wheels Contest 2017 First Prize in the Remote Control Contest 2017 4 Discussions 1 year ago Excellent documentation! This is a substantial project that requires some preparation and effort. Congratulations! You rock! 1 year ago Sell this and you will make millions!!!!!!!!!!! 1 year ago No. The motors are chosen for low acceleration but capable of high cruise velocity. You can also programmatically limit acceleration as well. 1 year ago Would you fall off if the acceleration to the side is to great?
https://mobile.instructables.com/id/OmniBoard-Skateboard-and-Hoverboard-Hybrid-With-Bl/
CC-MAIN-2019-13
refinedweb
3,764
61.16
We learnt in Part 2 that we can easily control Firefox OS using Marionette client commands, but typing them into a Python console is as slow and tedious. The key advantage of test automation is that it can run autonomously. We will learn how to do that in this part, as we put all of our code commands into a Python file that can then be run all in one go. Test case recap In Part 2 we went through the steps to run a typical test case — opening up the Contacts app and adding a new contact: - Unlock Firefox OS (optional; in Part 2 we turned off the lock screen manually, therefore we won't include this in the code below.) - Switch to Contacts app - Tap add new contact icon - Type in the contact’s name - Tap done - Wait and check that the contact is present Putting our test into a Python file If we put all of these steps into a Python file, we can re-use it and run it much more quickly. Create a new text file called test_add_contact.py in a convenient directory of your choosing. Into this file, enter the commands we saw in Part 2, as listed below. We'll use a Python class structure, as it is good practice, and forms a good base to build on in future steps of the tutorial. import time from marionette import Marionette class TestContacts: def __init__(self): self.test_add_contacts() def test_add_contacts(self): # Create the client for this session. Assuming you're using the default port on a Marionette instance running locally self.marionette = Marionette() self.marionette.start_session() # Switch context to the homescreen iframe and tap on the contacts icon time.sleep(2) home_frame = self.marionette.find_element('css selector', 'div.homescreen iframe') self.marionette.switch_to_frame(home_frame) contacts_icon = self.marionette.find_element('xpath', "//div[@class='icon']//span[contains(text(),'Contacts')]") contacts_icon.tap() # Switch context back to the base frame self.marionette.switch_to_frame() time.sleep(2) # Switch context to the contacts app contacts_frame = self.marionette.find_element('css selector', "iframe[data-url*='contacts']") self.marionette.switch_to_frame(contacts_frame) # Tap [+] to add a new Contact self.marionette.find_element('id', 'add-contact-button').tap() time.sleep(2) # Type name into the fields self.marionette.find_element('id', 'givenName').send_keys('John') self.marionette.find_element('id', 'familyName').send_keys('Doe') # Tap done self.marionette.find_element('id', 'save-button').tap() time.sleep(2) # Close the Marionette session now that the test is finished self.marionette.delete_session() if __name__ == '__main__': TestContacts() Note: one additional thing you'll notice in the code that we didn't cover in Part 2 is the Python time.sleep() function — this makes the script pause for a certain length of time (defined in seconds) before continuing onto the next line. We have added these lines into the automated test because we need to simulate the user manually tapping buttons, etc. and waiting for Firefox OS to complete the resulting actions. If we ran this script without any delays, Python would complete everything instantaneously, probably causing the test to fail, as Firefox OS wouldn't be able to keep up. Now you can run the test by navigating to the directory the test is saved in in your terminal and running the following command: python test_add_contact.py Note: Be aware of Python’s indentation rules. After copying and pasting you may need to indent everything correctly for the code to run. If you get an error related to this, make sure that all indentation levels are separated by a tab. Note: You'll also notice that the name inserted using the code above is "John Doe", different to the "Foo Bar" name in Part 2. We've done this so that the code will run successfully and add another contact. If you try to add a contact with the same name, Firefox OS will warn you about duplicate contacts. For the moment, the best way to repeat run the test is to go into the Firefox OS interface and manually delete the contact before each run. Adding an assertion One thing we're still missing from our test, which is important to automated tests, is an assertion — a report or measure of whether Firefox OS has reached the state we want it to reach; whether the test was successful. We’ll do this by adding some code to check whether the new contact is present in the app. Just before the # Close the Marionette session... line, add in this code, making sure it is indented to the same level as the other lines in the class: # Now let's find the contact item and get its text contact_name = self.marionette.find_element('css selector', 'li.contact-item:not([data-group$="ice"]) p').text assert contact_name == 'John Doe' Delete the old contact and try running the test again, with the following: python test_add_contact.py If it all runs well then great, now we have a functional test! Note: If the assertion fails, be sure that the previous 'Foo Bar' contact does not exist anymore. The CSS selector before the assert is actually picking up the first contact in the list (that can be seen by calling print "Contact name: %s" % contact_name before calling the assert). Note: The assertion won't currently appear to do anything, but assertions are very important when we start to use test runners, as introduced in Part 5: Introducing a test runner. Test runners like unittest use assertions to check whether tests have completed successfully or not, and then return the results of these tests (OK or FAIL.) A note on timing One of the most difficult things to deal with when writing an automated test is the timing. If the test moves onto the next step before Firefox OS completes the last one, then we’re likely to get a failure. As mentioned above, In the sample code we added time.sleep(x) commands to solve this problem. However, using time.sleep(x) is not a good practice. Using a hardcoded set time can cause your test to run too long or not long enough. The latter is the worst case; it will cause false negative test results — meaning a test that reports a failure when in fact the app is perfectly functional but behaved a bit slower thn the test was expecting. In the next part, we’ll progress onto abstracting out certain parts of the test into separate Python functions, and replacing the sleep() functions with proper dynamic waits.
https://developer.mozilla.org/en-US/docs/Archive/B2G_OS/Automated_testing/gaia-ui-tests/Part_3_Reusable_tests
CC-MAIN-2019-04
refinedweb
1,079
63.09
Interfacing HC-SR04 Ultrasonic Sensor with Raspberry Pi Contents Ultrasonic distance sensors are designed to measure distance between the source and target using ultrasonic waves. We use ultrasonic waves because they are relatively accurate across short distances and don’t cause disturbances as they are inaudible to human ear. HC-SR04 is a commonly used module for non contact distance measurement for distances from 2cm to 400cm. It uses sonar (like bats and dolphins) to measure distance with high accuracy and stable readings. It consist of an ultrasonic transmitter, receiver and control circuit. The transmitter transmits short bursts which gets reflected by target and are picked up by the receiver. The time difference between transmission and reception of ultrasonic signals is calculated. Using the speed of sound and ‘Speed = Distance/Time‘ equation, the distance between the source and target can be easily calculated. HC-SR04 ultrasonic distance sensor module has four pins : - VCC – 5V, input power - TRIG – Trigger Input - ECHO – Echo Output - GND – Ground Working of HC-SR04 - Provide trigger signal to TRIG input, it requires a HIGH signal of atleast 10μS duration. - This enables the module to transmit eight 40KHz ultrasonic burst. - If there is an obstacle in-front of the module, it will reflect those ultrasonic waves - If the signal comes back, the ECHO output of the module will be HIGH for a duration of time taken for sending and receiving ultrasonic signals. The pulse width ranges from 150μS to 25mS depending upon the distance of the obstacle from the sensor and it will be about 38ms if there is no obstacle. . The following equation can be used for calculating resistor values, “Vout = Vin x R2/(R1+R2)” Connection Diagram Distance Calculation Time taken by pulse is actually for to and fro travel of ultrasonic signals, while we need only half of this. Therefore Time is taken as Time/2. Distance = Speed * Time/2 Speed of sound at sea level = 343 m/s or 34300 cm/s Thus, Distance = 17150 * Time (unit cm) Calibration For accurate distance readings the output can be calibrated using a ruler. In the below program a calibration of 0.5 cm is added. Python Programming import RPi.GPIO as GPIO #Import GPIO library import time #Import time library GPIO.setmode(GPIO.BCM) #Set GPIO pin numbering TRIG = 23 #Associate pin 23 to TRIG ECHO = 24 #Associate pin 24 to ECHO print "Distance measurement in progress" GPIO.setup(TRIG,GPIO.OUT) #Set pin as GPIO out GPIO.setup(ECHO,GPIO.IN) #Set pin as GPIO in while True: GPIO.output(TRIG, False) #Set TRIG as LOW print "Waitng For Sensor To Settle" time.sleep(2) #Delay of 2 seconds GPIO.output(TRIG, True) #Set TRIG as HIGH time.sleep(0.00001) #Delay of 0.00001 seconds GPIO.output(TRIG, False) #Set TRIG as LOW while GPIO.input(ECHO)==0: #Check whether the ECHO is LOW pulse_start = time.time() #Saves the last known time of LOW pulse while GPIO.input(ECHO)==1: #Check whether the ECHO is HIGH pulse_end = time.time() #Saves the last known time of HIGH pulse pulse_duration = pulse_end - pulse_start #Get pulse duration to a variable distance = pulse_duration * 17150 #Multiply pulse duration by 17150 to get distance distance = round(distance, 2) #Round to two decimal points if distance > 2 and distance < 400: #Check whether the distance is within range print "Distance:",distance - 0.5,"cm" #Print distance with 0.5 cm calibration else: print "Out Of Range" #display out of range Run the above program. Output Distance is measured every two seconds and displayed. Reading accuracy - For greater accuracy use C over Python as Python on a Linux environment is not good for precise timing. As precise timing is required for accurate distance measurements. - The sensor has a wide angle of sensitivity. If there are objects near the line of sight it may give shorter readings. - The ultrasonic sensor touching any surface can give wrong readings. Any doubts? Comment below. If you are following the aforementioned circuit diagram, try using different pin numbers (worked for me with pin numbers 16 and 18, instead of 23 and 24 respectively). how can i put the data on the QT desinger? using this code can i get continuously the water depth I am having the same issue, despite checking my circuit diagram. Were you able to resolve your issue? If yes, please let me know how. Thanks! when we get out of range can we send that message to our phone?? do we have any code for that?? Thank you I have used your example to build a basic rig, I am planning on coding a C++ version to store values in a database for historic reporting and alerting. You have really helped start me my project. Yes, for sending emails anyway you need internet connection. but that will require internet connection so how to do that?? internet connection on raspberry pi will u explain. Make sure that you have python gpio library. It seems like there is some connection mistake. i have the same problrm :/ nothing seems to work This program is not working for me..it’s stuck on “Waitng For Sensor To Settle”.. I’ve checked all the wiring and nothing seems to work.. any idea or pre requesit in raspberry configurations that are needeD? Hi, I ran the code but it’s not displaying the result. It stucked at a “Waiting for Sensor to settle”. Checked circuit diagram also, everything seems to be correct. sorry i put a comma in the multiplier it works good. When i run this it says that a in line 32 a float is required. as far as i can tell my code is exactly the same as yours. You can install some SMTP applications and send mail through it. how to get email alert from this sensor? i mean do you have code for that You can add a calibration to make the results more accurate. Why 0.5cm calibration? Vcc and ground putted together to waste only 2 ports. for trigger and echo I suggest you to use 6 wires for 3 sensors and set a delay between triggering them (be aware u mustn’t trigger them all at once, even if they are separed. Ultra sound can quickly come back to the sensor by reflecting from walls and corners giving you wrong calculations) the minimum delay needs to be 38 uS, when i was doing a project with them i putted a delay of 100ms and it was more than enough. i cant help you more, i wasnt using rasperry. anyone know how to connect 3 ultrasonic sensors to raspberry pi? anyone know how I can connect 3 HCSR04 type sensors to raspberry pi? It will increase the current flow 10 times, make sure that it doesn’t exceed the output current limit of SR04. I used 470 ohm and 1k resistors in my setup (exactly 1/10th of what you have). It works, but should I anticipate problems? Try to find where program fails by printing comments at different parts of your program. It is clearly explained above. Hello I cannot take 5V from echo pin. What is it reason ? Any suggestions ? time.time function ?? please can any one help me i have been trying to use 2 ultra sonic sensors on the pi with one of my robotics projects but i cant seem to get the code to work properly. i cant figure out get a response from the second on i think the problem is with the time.time function I replaced both while GPIO.input(ECHO)==0: and ==1; with GPIO.wait_for_edge(GPIO_ECHO, GPIO.BOTH) start = time.time() GPIO.wait_for_edge(GPIO_ECHO, GPIO.BOTH) stop = time.time() and initialized with GPIO.add_event_detect(GPIO_ECHO, GPIO.BOTH) Reducing CPU load significantly. I tried using GPIO.RISING the GPIO.FALLING, but some times the device triggers all on its own and can be in the middle of an echo reply. Verify whether the echo pin of sensor is wired correctly. I have this letter all time and it wont go away and stays for very long time. Waiting for sensor to settle Any suggestions ? Thanks for your suggestion.. Good. But Voltage divider using resistors are not accurate for high speed signals. Better use a 3.3v Zener diodes.
https://electrosome.com/hc-sr04-ultrasonic-sensor-raspberry-pi/
CC-MAIN-2022-40
refinedweb
1,384
66.44
In my case my server create adapter list as dynamic. For example some times list contain 4 stocks in some times 2 stocks or in some times stock list will be empty and that time need to show the market closed message. I have created external feedsimulater class like bellow datastructure,(Remote adapter) public class RateRow { private String itemName; private String instrumentName; private String bidRate; private String askRate; private String low_price; private String high_price; } And i have assigned the values to this class. Finally for every 500 millisecond it will assign the values to this class.And my array list look like private final ArrayList<RateRow> bidaskrates = new ArrayList<RateRow>(); Now i need to show this list to client browser. Whenever the changes happens in arraylist it should be reflect in user browser. Now i created my RateRow class with itemName property. This itemName manually created like item1,item2 etc upto my stocklist. Now can i create some static 30 item names(like item1,item2 ... item30) in client and while subscription using MERGE mode can i compare with server stock items and display in client browser only available stocks in server. If supose server contain 4 items means i need to display only 4 items in client. Bookmarks
https://forums.lightstreamer.com/showthread.php?4982-Create-runnable-jar-for-remote-java-adapter&s=5b018ae001e9e2b706bdcbe6706913c7&goto=nextoldest
CC-MAIN-2021-10
refinedweb
208
61.36
One of the most common problem SQL Server developers face while dealing with XML is related to writing the correct XPath expression to read a specific value from an XML document. I usually get a lot of questions by email, on my blog or in the forums which looks like the following: “I have the following XML document and I am trying to read the value from xyz node. When I run my query, I get a NULL value” My friend Jacob Sebastian (SQL Server MVP) has written excellent article on the subject SELECT * FROM XML, I strongly recommend to either bookmark it and read it before continuing further in this article. In most cases, I have seen that the problem was due to an incorrect XPath expression. XPath expressions are not complicated at all, but they need a close attention to get them right. Assume that we have the following XML fragment. Looking at the structure of the XML document, it is quite easy to figure out the XPath expression pointing to each element and attribute. The following illustration shows how to do this. One of the simplest ways is to identify the nodes with their position as given in the above illustration. A more detailed listing is given below. The above example also used the “position” of the elements to uniquely identify them. In real life you might need to have more complex matching criteria such as the “email of the Employee element whose id is 10001”. The following example shows how to apply this type of filters. /Employees/Employee[@id=”1001″]/Email In most cases, you will be able to easily build your XPath expressions. However, if you find it difficult, you can take help from my helper function given here. This function allows you to run ‘blind’ queries on the XML document very similar to the ‘select * from table’ queries that we usually run on unknown tables. For example, if you would like to quickly examine the above XML document and see the elements, attributes and their XPath expression, you can execute something like the following: Make sure that you create the function XMLTable() using the script given in the above URL. Once you have the output of the function, you can copy the XPath expressions from the results and use in your Queries. For example, if you are looking for the email address of Pinal, you can just copy the expression from row 8 (highlighted in the image given above) and use in your query as: SELECT @x.value('Employees[1]/Employee[2]/Email[1]','VARCHAR(50)') I hope you will find this post interesting and the XMLTable() function might help you to solve some of the XML querying problems you may face in your SQL Server Journey. If you have got any question about XML in general, or about this function in particular, please feel free to post them on the XML forum and I will try my best to help you out. Reference: Pinal Dave () Very nice article. I was always scared using XML. But, after reading this, I think it is very easy and handy. Thanks for sharing such a nice thing. Very Nice article………Pinal can u explain about the what are the diff types of Database Documentation,how it is useful? etc…and How a Start up firm implement these types of documentation based on Agile model.I am Expecting an Interesting Article from you……… Very nicely written, This really helps out with XPATH, one of the challenging things i have faced with XML is more of the mechanics of XPATH, this example makes it easier. Very nicely written. I’m wonderin how the function can be modified to take namespaces into account? I’m looking for SELECT * FROM @Xml into one result row, one column per attribute, with the attribute name as the column name, and the attribute value as the value in the one row. I’m not there yet, but this T-Sql: declare @idoc int exec sp_xml_preparedocument @idoc OUTPUT, ”; WITH EdgeTable AS ( FROM OPENXML (@idoc, ‘/*’) ) SELECT e1.localname Attribute, e2.text Value FROM EdgeTable e1 join EdgeTable e2 on e1.id = e2.parentid where e2.localname = ‘#text’; EXEC sp_xml_removedocument @idoc returns this: Attribute Value ——— —– Name Jones Phone 123 And I don’t know the schema. I’m trying to make a generic routine that can be run on any xml. All I want is the data. I’m trying to get it into one row though, and so far, no luck. Any help would be appreciated. A solution not involving OPENXML would be better also. I’ll post if I solve it first. Did you get a solution? my xml got chopped out of my sample code. exec sp_xml_preparedocument @idoc OUTPUT, ‘<Customer Name=”Jones” Phone=”123″ />’; Also, my result data has 2 columns and looks like this: Attribute|Value Name |Jones Phone |123 Sorry about the 2nd post. Very useful article Pinal :) Hi Pinal, Please see the query below, declare @tstTable table(txt xml) insert @tstTable X Y A B ‘ select * from @tstTable I need to get the output as following, i need to use the xml.Modify I am expecting your reply.Plese help. X Y A B declare @tstTable table(txt xml) insert @tstTable select ‘<root> <parent> <firstname>X</firstname> <lastname>Y</lastname> </parent> <child> <firstname>A</firstname> <lastname>B</lastname> </child> </root>’ select * from @tstTable I need to get the output as following, i need to use the xml.Modify I am expecting your reply.Plese help. <root> <parent> <fullname>X Y</fullname> </parent> <child> <fullname>A B</fullname> </child> </root> If node randomly change then how get the node value Hi Pinal, I have a particular content to be searched in an attribute of an xml column where attribute might vary with different columns but content to be searched is same suppose want to search vmqa1 content in an xml column where I m not sure of the attribute where it appears within the xml column I searched a lot but did not get proper syntax for this Am worried about Xpath mapping. Now am free mind…Extremely thank :( cant put XML code here… —— // –LINE-1// —— // Vince —– -// –LINE-2// —– -// Lakka —- –// –LINE-3// —- –// Dinki —- –// –LINE-4// —- –// Lucy —- –// –LINE-5// —- –// Mac —- –// —- –//
http://blog.sqlauthority.com/2010/06/23/sqlauthority-news-guest-post-select-from-xml-jacob-sebastian/?like=1&source=post_flair&_wpnonce=1c9f85538d
CC-MAIN-2016-44
refinedweb
1,047
68.7
The all Xamarin.Forms apps did was display data once and the screens never changed, but alas, that's not the case. The app needs to support dynamic data, or data that changes at runtime. That is what this article will cover: how to incorporate dynamic data with XAML in a Xamarin.Forms app using dynamic resources and data binding. In the previous article, I mentioned one way to store and subsequently retrieve static data was via the ResourceDictionary property on a class that inherits from VisualElement – and generally whatever is read from the ResourceDictionary does not change. The code to access a static value in a ResourceDictionary looks like the following: <ContentPage.Resources> <ResourceDictionary> <x:String x:Recipe Name</x:String> </ResourceDictionary> </ContentPage.Resources> <!-- Some other code here --> <EntryCell Label="{StaticResource RecipeNameLabel}" /> However, should the need ever arise to change that EntryCell's label – it can't be done…or can it? This is where DynamicResources come to the rescue! A DynamicResource allows the value of the ResourceDictionary object to be changed at runtime, and that updated value will be reflected in whatever property that references the object. Setting up a ResourceDictionary to use a DynamicResource is exactly the same as for StaticResources – no changes are needed. The change comes in on how the object is referenced – and, as you may have guessed by now, it's referenced by the DynamicResource keyword. So in the example from above, the EntryCell control would access the RecipeNameLabel object in the ResourceDictionary as follows: <EntryCell Label="{DynamicResource RecipeNameLabel}" /> The difference between DynamicResource and StaticResource is that the XAML compiler will only access anything defined as a StaticResource once, pop in the value and then leave it be. Whereas with DynamicResource a link is maintained between that dictionary item and the property it's set to. The natural question then is – how does the RecipeNameLabel entry in the ResourceDictionary get changed? That will have to happen in the XAML's code-behind file. In response to some external event, the Resources dictionary is accessed, and the dictionary item is updated – exactly in the same way that any dictionary item is updated. In the example below, a button that indicates the recipe is "the world's greatest" is clicked. worldsGreatest.Clicked += (sender, e) => { Resources["RecipeNameLabel"] = "The world's greatest recipe name:"; }; The ResourceDictionary is located in the Resources property. DynamicResources are not the only way to update data – Xamarin.Forms comes with a powerful data binding engine that allows properties (and events) of controls to be bound to (special) properties and actions of various classes. Updating a control's property value through a DynamicResource is all well and fine – but it's not robust enough to make use of on a large scale. One of the benefits that I've been touting about XAML is that all of the code for the user interface can be expressed in the XAML markup and a lot of logic can stay out of the code-behind file. An excellent way to keep true to that benefit is to use data binding. Data binding allows a control to be bound to a backing model (or something that purely represents data) class and have both various properties of the control and the model be updated whenever either changes… without having to handle any events. In other words – imagine there is a class that models recipe data. Naturally it would have properties for the recipe's name, ingredients, directions, and so on. That class would be used to both capture data from the user interface and then save the recipe to a data store of some type. In the case of the recipe data entry, data binding saves the developer from writing a bunch of boilerplate code that sets the Recipe's properties to the various properties of the controls that display them – and then more code to move the new values from the controls back into the Recipe object. This becomes especially tedious when that same model class is used throughout the app. Thus databinding frees the developer to focus on implementing core app logic instead of boilerplate code…like getting the Recipe to save to the data store. Setting up the XAML code to make use of data binding is simple – all one needs to do is set whatever property you want to bind equal to the Binding keyword and then the model's property that should be bound to. A simple form that displays and updates recipes would look like the following: <TableView Intent="Form"> <TableView.Root> <TableSection Title="Enter Data"> <EntryCell Label="Recipe Name" Text="{Binding RecipeName}" /> <EntryCell Label="Ingredients" Text="{Binding Ingredients}" /> <EntryCell Label="Directions" Text="{Binding Directions}" /> </TableSection> </TableView.Root> </TableView> But…there is some extra work that needs to be done in the model class that enables the two way communication between it and the view. Specifically, it must implement the INotifyPropertyChanged interface. It's this interface that allows the control's on the UI to know that something has changed, and vice versa. Only one event must be implemented as part of INotifyPropertyChanged: public event PropertyChangedEventHandler PropertyChanged; By invoking that event every time a property changes value, the user interface will automatically get updated. And by extension, the model will get updated every time the user interface changes. The Recipe class, when fully implemented will look like the following: public class Recipe : INotifyPropertyChanged { string _recipeName; public string RecipeName { get => _recipeName; set { if (string.Equals(_recipeName, value)) return; _recipeName = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RecipeName))); } } string _ingredients; public string Ingredients { get => _ingredients; set { if (string.Equals(_ingredients, value)) return; _ingredients = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Ingredients))); } } string _directions; public string Directions { get => _directions; set { if (string.Equals(_directions, value)) return; _directions = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Directions))); } } public event PropertyChangedEventHandler PropertyChanged; } A couple things to note, the first is that if the passed in value of the property is the same as what is already there – nothing happens. You don't want to have the binding fire to set something that is already set. The second is that I'm making sure something is subscribed to the PropertyChanged event before invoking it – to avoid any null exceptions. Then there is a final piece of the puzzle to get data binding to work – associating the model to the Page that hosts the controls – and that's done through the BindingContext property. You can set the BindingContext either in the code-behind file, or in XAML by using the constructor syntax you learned about in the last article to create the model. Here's an example of setting the BindingContext on the ContentPage using the XAML constructor syntax. <ContentPage.BindingContext> <local:Recipe /> </ContentPage.BindingContext> Here's an example of a button on a Xamarin.Forms page simulating a database update. Pretend the button click event is actually a database service call coming back and updating the model – you can see how the control's in the UI get updated instantly. dbSimulation.Clicked += (s, e) => { // The recipe object would be returned from the data store - this is only for demo var bc = BindingContext as Recipe; bc.RecipeName = "new recipe"; bc.Ingredients = "new ingredients"; bc.Directions = "new directions"; }; It should be noted that anything in Xamarin.Forms that inherits from BindableObject has a BindingContext property. Controls are one thing that inherit from BindableObject. So it is possible to have different controls bound to different data sources all on the same page. The BindingContext of a parent control will be applied to all of its child controls – so setting it at the page level (as done above at the ContentPage) – will be sure to make all the controls beneath it have the same BindingContext. One thing you may be saying to yourself is, "I don't want to mess my models up with INotifyPropertyChanged"…and I don't blame you. There is a design pattern around that, and it's called MVVM, or Model-View-ViewModel, where the ViewModel implements INotifyPropertyChanged. I'll cover that in a future article. In this article you learned that controls defined in XAML don't have to have static properties that are set at design time and never change. Or they only change by modifying the XAML's code-behind file. You learned that XAML controls can update their values dynamically when data attached to them changes. The first method was through DynamicResources, which uses items defined in a ResourceDictionary, and updates those at runtime. The second is databinding. The databinding engine is powerful, it allows both the UI to be updated whenever the model class it is bound to is updated, and the UI to update the model. Pingback: Dew Drop - July 25, 2017 (#2527) - Morning Dew()
http://developer.telerik.com/topics/mobile-development/using-xaml-xamarin-forms-part-3-accessing-dynamic-data/
CC-MAIN-2017-34
refinedweb
1,462
52.6
Hi,On Sun, Jun 05, 2011 at 03:30:55PM -0400, Alan Stern wrote:> > > > good point. BTW, do we need this #ifdef CONFIG_PM stuff which has been> > > > popping on most drivers recently ? To me it looks like driver.pm field> > > > is always available even if PM is disabled, so what's the point ? Saving> > > > a few bytes ?> > > > > > Basically, yes (you may want to avoid defining the object this points to if> > > CONFIG_PM is unset).> > > > wouldn't it look nicer to have a specific section for dev_pm_ops which> > gets automatically freed if CONFIG_PM isn't set ? I mean, there are a> > few drivers which don't have the ifdeferry around dev_pm_ops anyway.> > > > So, something like:> > > > #define __pm_ops __section(.pm.ops)> > > > static const struct dev_pm_ops my_driver_pm_ops __pm_ops = {> > .suspend = my_driver_suspend,> > .resume = my_driver_resume,> > [ blablabla ]> > };> > > > to simplify things, you could:> > > > #define DEFINE_DEV_PM_OPS(_ops) \> > const struct dev_pm_ops _ops __pm_ops> > > > that would mean changes to all linker scripts, though and a utility call> > that only does anything ifndef CONFIG_PM to free the .pm.ops section.> > In my opinion this would make programming harder, not easier. It'sI tend to disagree with this statement, see below.> very easy to understand "#ifdef" followed by "#endif"; people see themvery true... Still everybody has to put them in place.> all the time. The new tags you propose would force people to go> searching through tons of source files to see what they mean, and thenonly those who want to see "how things work" would be forced to do that,other people would be allowed to "assume it's doing the right thing".> readers would still have to figure out when these tags should be used> or what advantage they might bring.not really, if you add a macro which adds that correctly and duringreview we only accept drivers using that particular macro, thingswouldn't go bad at all.> It's a little like "typedef struct foo foo_t;" -- doing this forceshey c'mon. Then you're saying that all __initdata, __devinitdata,__initconst and all of those are "typedef struct foo foo_t" ;-)> people to remember one extra piece of information that serves no real> purpose except perhaps a minimal reduction in the amount of typing. and a guarantee that the unused data will be freed when it's really notneeded ;-)> Since the limiting factor in kernel programming is human brainpower,> not source file length, this is a bad tradeoff. (Not to mention thatOTOH we are going through a big re-factor of the ARM port to reduce theamount of code. Not that these few characters would change much but mypoint is that amount of code also matters. So does uniformity, codingstyle, etc...> it also obscures an important fact: A foo_t is an extended structure> rather than a single value.)then it would make sense to have dev_pm_ops only defined when CONFIG_PMis set to force all drivers stick to a common way of handling this.Besides, currently, everybody who wants to keep the ifdeferry, needs todefine a macro for &my_dev_pm_ops or have two #ifdef..#endif blocks.Either you do:#ifdef CONFIG_PMstatic int my_driver_suspend(struct device *dev){ ... return 0;}....static const struct dev_pm_ops my_driver_pm_ops = { .suspend = my_driver_suspend, ...};#define DEV_PM_OPS (&my_driver_pm_ops)#else#define DEV_PM_OPS NULL#endifstatic struct platform_driver my_driver = { ... .driver = { .pm = DEV_PM_OPS },};or you do:#ifdef CONFIG_PMstatic int my_driver_suspend(struct device *dev){ ... return 0;}....static const struct dev_pm_ops my_driver_pm_ops = { .suspend = my_driver_suspend, ...};#endifstatic struct platform_driver my_driver = { ... .driver = {#ifdef CONFIG_PM .pm = &my_driver_pm_ops,#endif },};So, while this is a small thing which is easy to understand, it's stillyet another thing that all drivers have to remember to add. And wheneverybody needs to remember that, I'd rather have it done"automatically" by other means.I mean, we already free .init.* sections after __init anyway, so what'sthe problem in freeing another section ? I don't see it as obfuscationat all. I see it as if the kernel is smart enough to free all unuseddata by itself, without myself having to add ifdefs or freeing it by myown.On top of all that, today, we have driver with both ways of ifdefs plusdrivers with no ifdeferry at all, leaving dev_pm_ops floating around fornothing.IMHO, if things aren't uniform, we will have small problems, such asthis, proliferate because new drivers are based on other drivers,generally.-- balbi[unhandled content-type:application/pgp-signature]
https://lkml.org/lkml/2011/6/5/171
CC-MAIN-2016-07
refinedweb
713
64.3
34428/javascript-code-to-download-a-file-from-amazon-s3 Is there a javascript code to download a file from Amazon S3? I couldn't find anything useful resources on the internet. So, if any of you have done something similar to this can you post the code? Well, is it possible to write a javascript code to download a file from S3? Hai, I was thinking along the same lines. Then I figured out I could make use of node.js, ie. use AWS SDK for javascript in node.js. var AWS = require('aws-sdk'); AWS.config.update( { accessKeyId: ".. your key ..", secretAccessKey: ".. your secret key ..", } ); var s3 = new AWS.S3(); s3.getObject( { Bucket: "my-bucket", Key: "my-picture.jpg" }, function (error, data) { if (error != null) { alert("Failed to retrieve an object: " + error); } else { alert("Loaded " + data.ContentLength + " bytes"); } } ); Try this out! Hi Prashanth, To run your script on the client-side, you need to use some automation tools. Generally in this type of use case, we use Terraform. But we can also use the Ansible playbook to do this task. Here is the Python code using boto ...READ MORE Hi@akhtar, Boto3 supports upload_file() and download_file() APIs to ...READ MORE If you observe, it must be giving ...READ MORE Boto3 is the library to use for ...READ MORE Here's a UNIX/Linux shell way. for f in ...READ MORE You don't actually need cli to get the ...READ MORE Hi, Here for the above mentioned IAM user ...READ MORE The IAM username and password can only ...READ MORE The code would be something like this: import ...READ MORE There is one way. If the other ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/34428/javascript-code-to-download-a-file-from-amazon-s3
CC-MAIN-2021-21
refinedweb
287
79.67
Working with NSThread Assume the task routine is doFoo, defined by the class Foo. Assume also that the routine does not take any arguments. To create an NSThread instance within class Foo, use the factory method as follows: NSThread *tFoo; tFoo = [NSThread detachNewThreadSelectory:@selector(doFoo) toTarget:self withObject:nil]; The above statement refers to the doFoo routine with the @selector directive. The target class is set to self, the input argument to nil. The factory method returns the thread instance as its output, and it starts the thread. Suppose the routine is doFooWithNumber:, which takes an integer value for input. In this case, enclose the value in an NSNumber object and pass the object to the factory method. NSNumber *tArg; tArg = [NSNumber numberWithInt:12345]; tFoo = [NSThread detachNewThreadSelectory:@selector(doFooWithNumber:) toTarget:self withObject:tArg]; The same also applies for other data types: strings with NSString, arrays with NSArray, and so on. Make sure to include the colon token in the routine's name as shown above. To create a thread with the instance method, pair the method with an alloc call: NSThread *tFoo; tFoo = [[NSThread alloc] initWithTarget:self selector:@selector(doFoo) object:nil]; Note how the instance method uses a different order of arguments. Unlike the factory method, it one does not start the thread instance. To do so, send a start message to the instance: [tFoo start]; As stated earlier, this method does not mark the thread for autorelease. To dispose of it, send a release message to the thread instance: if ([tFoo isFinished]) [tFoo release]; Make sure the thread is not running prior to disposal. Otherwise, the thread will fail with a BAD_EXC_ACCESS error. Listing Four shows how we might prepare class Foo for threading. Listing Four: Preparing a class for threading. // // CLASS:DECLARATION // #import <Cocoa/Cocoa.h> @interface Foo : NSObject { NSAutoreleasePool *pPool; } // class methods go here - (void)doFoo; - (void)doFooWithNumber:(NSNumber *)anArg; @end // // CLASS:IMPLEMENTATION // @implementation Foo // Initialise the class - (id)init { if (self = [super init]) { // create the local autorelease pool pPool = [[NSAutoreleasePool alloc] init]; if (pPool != nil) return (self); else return (nil); } else // the parent has failed to initialise return (nil); } // Dispose the class - (void)dealloc { // dispose the pool [gPool release]; // invoke the parent method [super dealloc]; } // -- MAIN THREAD TASKS - (void)doFoo { // task code goes here... } - (void)doFooWithNumber:(NSNumber *)anArg { if ((anArg != nil) && ([anArg isKindOfClass:[NSNumber class]]) { // task code goes here... } else [self doFoo]; } @end In its init method (line 26), Foo creates its own autorelease pool pPool. In its dealloc method, Foo disposes of the pool before calling its parent's dealloc (line 41). By using its own pool, Foo avoids using the main application process to dispose of its locally created objects. This improves thread performance and reduces the overall memory footprint. Foo defines two task routines: doFoo and doFooWithNumber:. The doFoo routine does not take any input arguments (lines 11, 48), while doFooWithNumber: takes an NSNumber argument (lines 12, 53). The doFooWithNumber: routine checks if its argument is a valid NSNumber object (lines 55-56). If that check proves false, doFooWithNumber: passes control to doFoo (line 61). As for mutex constructs, Cocoa provides the NSLock class (Figure 2). Figure 2: The NSLock class. Unlike most Cocoa objects, an NSLock instance is created only with the standard alloc and init messages. NSLock *tLock; tLock = [[NSLock alloc] init]; This instance must not be marked for autorelease. It must be disposed of explicitly and only after all threads using the shared resource are done. Listing Five describes how class Foo implements an NSLock as one of its properties. Listing Five: Implementing NSLock. // // CLASS:DECLARATION // #import <Cocoa/Cocoa.h> @class Bar; @interface Foo : NSObject { NSAutoreleasePool *pPool; NSLock *pLock; Bar *modelBar; } // instance methods go here - (void)doFoo; @end // // CLASS:IMPLEMENTATION // @implementation Foo // Initialise the class - (id)init { if (self = [super init]) { // create the local autorelease pool pPool = [[NSAutoreleasePool alloc] init]; // create the mutex lock pLock = [[NSLock alloc] init]; // create the shared object modelBar = [[Bar alloc] init]; if (pPool != nil) { // more initialisation code follows... return (self); } else // unable to initialise the key properties return (nil); } else // the parent has failed to initialise return (nil); } // Dispose the class - (void)dealloc { // dispose the shared object [modelBar release]; // dispose the mutex lock [pLock release]; // dispose the pool [pPool release]; // invoke the parent method [super dealloc]; } // -- MAIN THREAD TASKS - (void)doFoo { // check the key properties if ((gLock != nil) && (modelBar != nil)) { id tData; // first part of task code runs... // lock the resource [gLock lock]; tData = [modelBar getData]; [gLock unlock]; // second part of task code runs... // lock the resource [gLock lock]; [modelBar setData:tData]; [gLock unlock]; // third part of task code runs... } } @end In its init method, Foo creates its NSLock instance ( pLock) right after creating autorelease pool (line 31). In its dealloc method, Foo disposes of the NSLock instance just before disposing of the autorelease pool (line 58). Its shared resource is the property modelBar, which is an instance of class Bar (line 11). Its creation and disposal are performed in the same init and dealloc methods (lines 34, 55). The routine doFoo performs the first part of its threaded task. Before it access modelBar, doFoo sends a lock message to pLock (line 78). The routine reads its data from modelBar and sends an unlock message to pLock (line 80). Next, doFoo continues with the second part of its task. It sends another lock message to pLock (line 85) and writes its data to modelBar. It sends an unlock message (line 87) and does the rest of its task. So when there are two NSThread instances, with both using doFoo, the pLock mutex prevents the two threads from using modelBar at the same time. Comparing Thread Solutions To compare performance, I ran a task of 32-bit Whetstone benchmark set for 5120 loops. It was run ten times, always from a cold start. The test machine was a MacBook with a 2.4 GHz Intel Core 2 Duo and 2 GB of physical RAM running MacOS X 10.6.6. On average, the POSIX solution ran the results in 7.5 seconds vs. 12.5 for NSThread. In part this is because the NSThread instance is a heavyweight thread. It takes up more resources and it has a greater overhead. A POSIX thread lacks the rich feature set of NSThread. It is not object-oriented, due to its strict C-only interfaces. Plus, it uses explicit malloc() and free() calls to manage its memory. This means the thread cannot rely easily on garbage collection. Instances of NSThread can communicate with each other in several ways. They can use an NSNotification object to post messages on the responder chain. Those messages are visible to other NSThread instances and to the main application process. An NSThread instance can use an NSMessagePort object to signal other active processes on the same machine. And it can use NSAppleEventDescriptor objects to control scriptable processes. As for POSIX threads, they have to rely on a Mach port and a CFSocket. A Mach port is a lightweight user-level service provided by the Mach 3 kernel. CFSocket is a developer-friendly wrapper for BSD sockets. Both have C-style interfaces, and both require Cocoa objects rendered as CF data types. Threading with Safety Here are some guidelines for preparing a thread-safe task. These are taken from the official Apple guide on threaded programming. Though they focus on NSThread, they can be applied to POSIX threads as well. - Use immutable objects whenever possible.Immutable objects like NSStringand CFStringare thread-safe because their data content stays unchanged during a threaded task. When they modify their data, they return a modified copy as an immutable object. And when they extract parts of that same data, they return those parts as immutable objects as well. Mutable objects are not thread-safe. Their content can change unpredictably during the thread task. They also have a larger memory overhead than immutable ones. - Avoid sharing resources. A thread runs best when it maintains only its resources. If threads share a resource, they will need a mutual exclusion construct to co-ordinate their access. Too many mutexes, however, add to the application's memory footprint. They can also affect thread performance. If the shared resource is a view (like a progress bar), a thread should place its update code in the view's thread-safe routines. In the case of NSView, those routines would be lockFocusIfCanDrawand unlockFocus. Both routines run atomically, allowing the view to update its visual appearance. - Use mutex constructs properly and wisely. Use a mutex only to protect a shared resource. Create and dispose of it at the same time as the resource. Make sure no threads that use the construct are active and running before disposing of it. A thread should check for a valid mutex construct before attempting a lock. It should lock the mutex just before using the resource, and it should always clear the lock immediately afterwards. It should not use a locked resource as part of a loop or a recursion. - A thread should handle its own exceptions. A thread should avoid relying on the main application process to handle its exceptions. There is no guarantee the main process will handle a thread's exception properly. Plus, the context switch from thread to process degrades performance and leaves the thread unstable. So, a thread should have its own exception traps. Those traps should catch every possible exceptions thrown by the thread. At least one trap should deal with all generic exceptions. Conclusion The MacOS X platform has four thread solutions, two of which are obsolete as of version 10.7. In this article, I explored the remaining solutions: the POSIX thread library and the NSThread class and compared the benefits of each as well as their performance in a single, quick benchmark. Threads can be beneficial to any Cocoa software product. When used properly, threads can help optimize performance. They allow the product make use of multicore processors, and they ensure the product remains responsive, even while running computationally intensive tasks. Choose the threading library that best suits your needs and you'll be ready to go. References NSThread Class Reference. MacOS X Developer Library [PDF]. pthread(3) MacOS X Manual Page. MacOS X Developer Library. [HTML]. Threading Programming Guide. MacOS X Developer Library. [PDF]. Blaise Barney. POSIX Threads Programming. Lawrence Livermore National Laboratory. UCRL-MI-133316. Wikipedia. POSIX Threads. José R.C. Cruz is a freelance engineering writer based in British Columbia. He frequently contributes articles to Dr. Dobb's and other technical publications. He can be contacted through at [email protected].
http://www.drdobbs.com/cpp/mastering-threads-on-macos-x/232602177?pgno=3
CC-MAIN-2014-41
refinedweb
1,763
66.23
Friday Java Quiz: Null Character In Strings The usual rules (no Googling, no compiling, etc.) Q: True or false? In Java, a java.lang.String may contain the null character. The New Bloglines Beta: Habit Breaking Changes I tried the new Bloglines Beta today. Two of the most obvious changes (changes that I noticed within 10 seconds of using it) are: - The "Keep New []" checkbox is gone. In its place is a "[] Read" checkbox, just like Google Reader. - Whin I click on an empty feed in the left nav, instead of getting a regular feed page (only with zero entries) on the right panel, I get a generic feed independent page. These improvements break a couple of my blog reading habits, which I'll state as use cases: Use Case 1: Marking a feed as read - Click on the feed in the left nav Use Case 2: Visit the website of a feed - Click on the feed in the left nav - Click on the title link in the right panel Granted, these two use cases must have not been the original use cases for the developers of Bloglines. Otherwise they won't be broken in a new version. However, these are implied use cases from the overall behavior of the current version of the software. I just happen to depend on these implied use cases. Back when I did a comparison between Bloglines and Google Readers, Use Case 1 was one of the reason I favored Bloglines. I'm not sure if I should redo that evaluation. One thing that I liked is the new "3-pane view" that's available in Yahoo!Mail: Log. New Language Features Galore Just as Java's new language features buzz is dying down (reified generics no longer being mentioned, etc.) the C++0x standards is nearing completion. In today's OCI internal C++ lunch, Adam Mitz (who apparently needs a more updated homepage) talked about the new C++ language features that may become available in the updated standard. We've covered the new library features in a previous C++ lunch. Here's some of the more interesting features. Raw strings R"$ A string that may contain embedded new line characters. $" Lambdas <>(int x, int y) -> int {return x + y; } Closures std::cout& os = ...; setCallback(<>(int i) extern(os) { os << i; }); RValue References A&& r = getA(); Variadic Templates template <class... Elements> class tuple; Alternative syntax for typedef using callback = void (*)(void*, int); Type inference auto pi = 3.1415926535; const auto& v = map["key"]; Concepts template <LessThanComparable T> class ...; auto concept LessThanComparable <typename T> { bool operator<(T, T); }; Range based for loop for (int i: vector_of_ints) { std::cout << i; } String enums enum class E : unsigned long long {A, B, C}; And the quote of the day came when Adam answered the question "is this a hack?" with It's all a hack, but so is the whole language. For detailed information, Adam points us to JTC1/SC22/WG21 - The C++ Standards Committee Home Page. SUNW Is Now JAVA I was off the internet for a couple of days and missed this announcement from Sun: Jonathan Schwarz: And so next week, we're going to embrace that reality by changing our trading symbol, from SUNW to JAVA. Shouldn't it read "Java™ technology-based ticker symbol"? :) Quote Of The Day "Just because we are done, doesn't mean that we are done." Printer-Friendly CSS Terence Tao: I recently discovered a CSS hack which automatically makes wordpress pages friendlier to print (stripping out the sidebar and header), and installed it on this blog (in response to an emailed suggestion). There should be no visible changes unless you “print preview” the page. Being a print-it-out kind of person, I ran into the "weblogs (or other web pages) not printing properly" problem way too often. Typical problems are: i) words being cut off on the right hand side; ii) only one page of real content is printed (example: Neal Gafter's blog). I hope that someone can take the idea from the above link and make it work with other blogging engines/providers. It doesn't look very hard. (Pebble, the engine behind this blog, already uses a separate stylesheet for printing.) Jython 2.2 Released Frank Wierzbicki: On behalf of the Jython development team, I'm pleased to announce that Jython 2.2 is available for download. See the installation instructions. This is the first production release of Jython in nearly six years, and it contains many new features: - new-style classes - Java List integration - NEWS file in the release. Only the version numbers changed in the code from 2.2rc3 to this release. Woohoo!! Woohoo!! indeed. HTML Needs New Tags I am a firm believer of standard based software development. When it comes to web standards such as HTML and JavaScript, I should also add that the standards need to evolve. The way the web standards evolve is through experiments of their implementations. That's why I was excited about the Mozilla canvas tag when it first appeared. That's why I'm excited about the video tag that Brendan Eich, the King of Mozilladom, mentions in his blog: Brendan Eich: From the inimitable Chris Double of Mozilla's New Zealand brain trust: moving, rotating, scaling <video> in SVG (so who needs yet another non-standard plugin?). It is true that these tags are not part of the HTML standard, yet. But there is no reason why they can't be. It may take some time before all the vendors agree on the exact syntax. Some vendors may even resist the incorporation of such innovations. But at the end of the day, it is the usefulness of these new tags that will attract web content developers, and through them, the web content consumers. As to the comment "Why needs yet another non-standard plugin?" The answer is "Mozilla has always needed non-standard plugins." Try removing all non-standard plugins from your browser and see if the web still "works"? The trick is to standardize the access to such plugins in a way that promotes competition and prevents lock-ins. My Shrinking Blogroll A few people I know stopped publishing their blogs. Eric Burke even went so far as to remove his blog from the internet (after a "I'm going to remove it" next-to-last post). As a result, some of the links in my blogroll become stale. So I went ahead and cleaned it up yesterday. The number of feeds went from almost 300 down to 69. If you are watching the number of subcribers to your feed from Bloglines or NetNewsGear, and see it being decremented, that's me unsubscribing from your feed. I unsubscribed from the feeds that are gone or sparingly published. And I also unsubscribed from the feeds that I'm no longer interested in. Just as Eric felt it right to remove a blog that he's not motivated to continue to publish, I have overcome the tendency to not unsubscribe from less-than-frequently published feeds to not hurt the author's feelings. (If you've been meaning to delete your blog, but are thinking "What about all my subscribers?" There is one less subscriber for you to worry about today.) Given that this blog was started after Eric told me all about blogging, Eric's departure from blogging also made me reflect a bit about the future of this blog. And here's what I am certain: - Like everything else, this blog won't last forever - I'm still motivated to write a few times a week, so I'll continue to write - I have found (as a few others have found) a few of my past entries useful. So I'll try to keep this blog up for as long as I can support it. - I'll keep an eye on what the smart people are doing, and jump to that if I can emulate it. Given my tendency to be extremely retro (do a Google image search for "Windows 3.1", and you will find my blog at the number one spot), I'll probably be among the last few bloggers remaining when everyone else have moved on. But that's fine with me. Friday Java Challenge: Write A Regular Expression Parser Instead of a Friday Java Quiz, I'll pose a challenge. And it is not a challenge to your Java skills, but a challenge to the Test-First Design doctrine, which holds that a test-first approach can result in a better or simpler design. I first witnessed this principle at work at the first No Fluff Just Stuff conference in St. Louis several years ago, where I sat in on Uncle Bob's session on test-first design and followed his "score a bowling game" demonstration. I have been following a test-driven approach ever since, and I have benefited enormously from this approach: this is true especially in the responsibility allocation among cooperating classes, untangling tightly coupling, and API designs. However, I have always felt that certain systems can only be designed with enough knowledge about the domain that might not be gained through the mere writing of tests. This is particularly true in areas where non-trivial theories are involved in the solution of a problem. My usual example is "You can't write Math.sin() with a test-first approach." It seems to me that the test-first design is applicable for trivial problems, but not for complicated problems where the naive solution is the wrong solution. With that in mind, here's today's Java challenge: Using a test-first approach, and without resorting to any text books, or Google, or looking at the sources of existing regular expression implementations, write a simple regular expression matcher that supports the following features: - c: literal character c - . (period): any single character - ^: beginning of input string - $: end of input string - *: zero or more occurrences of the previous character Friday Java Quiz: What Is Integer.TYPE? Of course you know what Integer.TYPE is. Now fill in the blank in the following class: public class Foo { public static void main(String[] args) { System.out.println(________ == Integer.TYPE); } }with something other than Integer.TYPE so that the program will print "true" when compiled and run. IntelliJ IDEA License Give away At The JUG I've mentioned it a couple of times in passing a couple of times, but never called it out. For the past several months, JetBrains has been a sponsor of the St. Louis Java Users Group. They have been giving away one(1) IntelliJ IDEA 6 license to a lucky member of the audience every month. They also give one to the presenter. That doesn't sound to much. After all, Microsoft has been known to give away XBoxes at C#/.NET meetings. But if you think about it. the St. Louis JUG is regularly attended by 20-40 people, some of them already have an IDEA license. We've had people declining the offer because they already have one at least twice. (I have to decline the offer last month when I presented on JavaFX, because I already bought an IDEA 6 license.) So come to the JUG meeting this evening, when Jay Meyer (of Harpoon Technologies Inc.) will talk about tools and techniques that developers can use write a secure application from scratch, or test an already-installed application. The line-up the the next few months also look interesting: Widening The JVM Language Group: They Need Us! Widening the JVM Languages Group: We Need You! Charles Nutter: We lanuage. I joined the JVM Language Group project when Charles announced it the first time around 74 days ago. Although language design and implementation is not my specialty, watching others discuss it is still a lot of fun. One thing I noticed, for a long time now, is Charles's healthy respect for the other JVM languages, especially Jython, which has been around for more than ten years now. That is so unlike the other Ruby guys that I encounter online. The goal of the group is to come up with something, some sort of a library or <shudder>framework</shudder>, that would aid the implementation of JVM languages, as well as a forum for other discussions. I think you want to join even if you are not a language guy. After all, JRuby, (or Jython, or Groovy, or whatever), is just a big Java program. The Amazon.com Spam Inference Engine Have I told you I love Amazon.com spams? They keep on getting more and more creative and suggesting books in areas I have not the faintest interest in buying: Back in the old days, when they told me people who bought a HP LaserJet 1100 ink cartridge also bought ink cartridges for the Canon C-120, I can at least see the logic in their inference. But how could they jump from network programming to system on silicon is beyond me. My guess would be Joe, who developed the inference engine, left Amazon.com. And he did not tell his colleagues in Bangalore that they are not supposed to crank the "stretch.imagination" parameter up to beyond 1: - 0 is lame - 1 is reasonable - 2 is hilarious - 3 is universal You just wait. One of these days they are going to crank that number up to 3, and the internet will be filled with Amazon spams for forty years: foreach (book1 in the catalog, book2 in the catalog, dummy in customer) where (dummy bought book1) { sendEmail(to: dummy, youBought: book1, youWillLove: book2); } The Number One Ill Of Java ... ... is its stupid "directory structure reflecting the package hierarchy" (mis)feature. I was "helping" 20-year programming veterans to "understand" this (mis)feature in 1998. I'm still "helping" people to understand it now. "I have a directory full of Java sources right here. Why do I have to tell javac or my IDE that the sources are three directories up?" There is no good answer to this question. Sure, you can get use to it. You can even be proud that you are among the 5% programmers who persevered in understanding it. But it doesn't make it right! You can label the on switch "off" and the off switch "on". People will get used to it. But that doesn't make it right. It causes unnecessary problems. And its another barrier to true understanding. That, and zero-based array indexing, have got to go. Alexander Stepanov: Notes On Programming Alexander A. Stepanov: This book does not attempt to solve complicated problems. It will attempt to solve very simple problems which most people find trivial: minimum and maximum, linear search and swap. These problems are not, however, as simple as they seem. I have been forced to go back and revisit my view of them many times. And I am not alone. I often have to argue about different aspects of the interface and implementation of such simple functions with my old friends and collaborators. There is more to it, than many people think. I do understand that most people have to design systems somewhat more complex than maximum and minimum. But I urge them to consider the following: unless they can design a three line program well, why would they be able to design a three hundred thousand line program. We have to build our design skills by following through simple exercises, the way a pianist has to work through simple finger exercises before attempting to play a complicated piece. ... and I thought all I have to do was to write millions of tests! And write the simplest thing that will make the tests work.
http://www.weiqigao.com/blog/2007/08.html
crawl-001
refinedweb
2,633
71.34
The effects of weak memory models on programs running on shared-memory multiprocessors can be very difficult to understand. Today I was looking for the simplest program that illustrates the difference between sequentially consistent execution and TSO (the memory model provided by x86 and x86-64). Based on an example from Section 8.2.3.4 of the big Intel reference manual, I came up with this: #include <pthread.h> #include <stdio.h> #include <assert.h> volatile int x, y, tmp1, tmp2; void *t0 (void *arg) { x = 1; tmp1 = y; return 0; } void *t1 (void *arg) { y = 1; tmp2 = x; return 0; } int main (void) { while (1) { int res; pthread_t thread0, thread1; x = y = tmp1 = tmp2 = 0; res = pthread_create (&thread0, NULL, t0, NULL); assert (res==0); res = pthread_create (&thread1, NULL, t1, NULL); assert (res==0); res = pthread_join (thread0, NULL); assert (res==0); res = pthread_join (thread1, NULL); assert (res==0); printf ("%d %d\n", tmp1, tmp2); if (tmp1==0 && tmp2==0) break; } return 0; } It is easy to see that this program cannot terminate on a sequentially consistent multiprocessor (assuming that all system calls succeed). On the other hand, the program can and does terminate under TSO. Because individual processors are sequentially consistent, the program will not terminate on a multicore Linux machine if you pin it to a single core: $ gcc -O tso.c -o tso -pthread $ taskset -c 1 ./tso It’s easy to “fix” this code so that it does not terminate in the multicore case by adding one memory fence per thread. In GCC on x86 and x86-64 a memory fence is: asm volatile ("mfence"); In some cases this version is preferable since it also stops some kinds of reordering done by the compiler: asm volatile ("mfence" ::: "memory"); The stronger version should be unnecessary here: since the relevant reads and writes are to volatile-qualified objects, the compiler is already not allowed to reorder them across sequence points. Thinking abstractly about this stuff always messes with my head; it’s better to just write some code. Also I recommend Section 8.2 of Intel manual, it contains a lot of excellent material. 11 thoughts on “Simplest Program Showing the Difference Between Sequential Consistency and TSO” This a small nit, but can be important: For portability one should not compile with -lpthread but with -pthread as the former does not set preprocessor flags or link in every required library. Thanks Eitan! Fixed in the post. I was under the impression that in the new C/C++11 world order, volatile means absolutely nothing with respect to sharing memory between threads. So this program is full of data races, which means it is undefined. This may be completely tangential to the point you’re trying to make, but I wanted to point it out. Hi Ben, I wasn’t really thinking about the new memory models when I wrote this, but that’s a good point. As far as I can tell, it’s not possible to write this program in a race-free way since destroying the kind of behavior I’m showing here is kind of the point of DRF. Perhaps the way to make this point in (somewhat) conforming C11/C++11 is to write a bit of inline assembly language. Hi John if “volatile” is replaced by “atomic” and the memory accesses are labelled as “relaxed”, the resulting program will be data-race free (and well-defined according to C11/C++11) but it will still exhibit the 0,0 behaviour when executed on x86 (or Power/ARM) hardware. And, ahem, some advertising based on my experience: To explore the hardware memory model I suggest to rely on the “litmus” tool, which takes care of the proper thread synchronisation (and adds some noise in the memory subsystem to increase the probability of observing non-sc behaviours). The “litmus” tool can be downloaded from To compute the behaviours allowed by a C11/C++11 program, then the interactive “cppmem” tool can be handy (especially when exploring some corners of the semantics of low-level atomics): -francesco Well there are the weak atomic operations, which: (1) I know very little about and (2) I suspect have pretty spotty support at this point. In theory those let you write programs that don’t violate the C/C++11 memory model, but do have a kind of data race. There are several interesting variations of this example in C/C++11 using different flavours of relaxed atomics – e.g., with relaxed atomics or release/acquire pairs the non-SC behaviour is allowed, while with SC atomics it isn’t. In the terminology of the standard, the intuitive races don’t count as “data races”. If you want to experiment with the examples, you can try the “SB” tests in this tool: (built from Mark Batty et al.’s formal model for C/C++11 concurrency). If you instead want to illustrate the raw x86 hardware behaviour, without the possibility of confusion from compiler reordering, then one nice way is with the “litmus” tool by Luc Maranget, Susmit Sarkar and others: (the first example in the doc there is basically the same as the one you have above), which runs an litmus-test assembly program in a test harness. I quite often do this in lectures – it’s nice to see the non-SC behaviour for real, and also to see the variation in how often it shows up. Thanks Peter! In fact I was looking for the simplest program in order to better explain these issues to my operating systems class, I’ll think about using Litmus in this capacity as well. Another interesting question is: “What’s the simplest C++11 program that shows a difference between putting seq_cst fences between every operation and making the operations themselves seq_cst?” The simplest one I know of is “IRIW”, “Independent Reads of Independent Writes”. IRIW is the simplest to understand in my opinion, although other more esoteric relaxed behaviours seem to be allowed as well. In particular, the C11 analogues of RWC and WRR+2W from the following document are allowed: Thanks everyone!
http://blog.regehr.org/archives/898
CC-MAIN-2016-30
refinedweb
1,024
54.86
Google. Community comments About bubkets name issue by Michel Graciano, About bubkets name issue by Michel Graciano, Your message is awaiting moderation. Thank you for participating in the discussion. I have seen that what you say about bubkets name rules is not true, according to the documentation [1], "Bucket names reside in a single Google Storage namespace. As a consequence, every bucket name must be unique across the entire Google Storage namespace. If you try to create a bucket with a bucket name that is already taken, Google Storage responds with an error message", so the error you faced was as expected. Regards [1] code.google.com/intl/pt-BR/apis/storage/docs/bu...
https://www.infoq.com/news/2011/05/Google-Storage-for-Developers/
CC-MAIN-2021-43
refinedweb
114
53.71
extdirect 0.4 Python implementation of an Ext.Direct router ============ Introduction ============ To use this package, you must either have simplejson installed, or be using Python 2.6 (which includes simplejson as the json package). ExtJS 3.0 provides Ext.Direct, an extremely simple way to remote server-side methods to the client side. extdirect provides a Python implementation of a server-side Ext.Direct router, which can accept and parse Ext.Direct request data, route it to the correct method, and create, encode and return the proper data structure wrapping the results. extdirect also provides a class that can generate the client-side JavaScript defining an Ext.Direct provider from a router class. For a full description of Ext.Direct's features, see: Let's see how the server side works. First, we'll define a router: >>> from extdirect.router import DirectRouter >>> class TestUtils(DirectRouter): ... ... def capitalize(self, word): ... return word.upper() ... ... def today(self): ... return "Today is Wednesday." We've defined two methods we want remoted to the client. Although we don't have a real client in this test runner, here's how one would generate the code that needs to be given to the client defining the provider. Ignoring actual implementation, which would depend on the framework being used, let's say we'll have this class available at URL '/utils', and we want our client-side namespace containing these methods simply to be called 'Remote.' >>> from extdirect.router import DirectProviderDefinition >>> print DirectProviderDefinition(TestUtils, '/utils', 'Remote').render() ... #doctest: +NORMALIZE_WHITESPACE <script type="text/javascript"> Ext.Direct.addProvider({"url": "/utils", "namespace": "Remote", "type": "remoting", "id": "TestUtils", "actions": {"TestUtils": [{"name": "capitalize", "len": 1}, {"name": "today", "len": 1}]}}); </script> Now, assuming that, one way or another, we've provided this code to the client and our class is available at that URL, we are now able to access these methods from the browser: Remote.TestUtils.capitalize({word:'foo'}, console.log) That example would make a call to the 'capitalize' method on our TestUtils class and feed the result to our callback, which in this case merely prints the result to the JS console. Let's see how that would work from the perspective of the server. That call would make a POST request with a JSON-encoded body, so let's create that manually: >>> from extdirect.router import json >>> data = {"action":"TestUtils","method":"capitalize","data":[{"word":"foo"}],"type":"rpc","tid":1} >>> body = json.dumps(data) Our class name is passed in as "action", the method name as "method", and whatever data we sent as a single-member array containing a hash of our parameters. For our purposes, "type" will always be "rpc". Ext.Direct requests also provide a transaction id ("tid") which may be used as you see fit to handle the possibility of stale data. Now, let's make an instance of our server-side class: >>> utils = TestUtils() This instance is callable and accepts the request body, and returns a JSON-encoded object exhibiting the structure expected by Ext.Direct on the client: >>> utils(body) '{"tid": 1, "action": "TestUtils", "type": "rpc", "method": "capitalize", "result": "FOO"}' Notice the "result", which is what we'd expect. The client would decode this object and pass the "result" value to the callback. Just for fun, let's check out our other defined method: >>> data = {"action":"TestUtils","method":"today","data":[],"type":"rpc","tid":1} >>> body = json.dumps(data) >>> resultob = json.loads(utils(body)) >>> print resultob['result'] Today is Wednesday. =========== Zope Router =========== Using extdirect in Zope is extremely simple, due to a custom ZCML directive that registers both a BrowserView for the server-side API and a viewlet to deliver the provider definition to the client. 1. Define your class e.g., in myapi.py: from extdirect.zope import DirectRouter class MyApi(DirectRouter): def a_method(self): return 'A Value' 2. Register the class as a direct router <configure xmlns=""> <include package="extdirect.zope" file="meta.zcml"/> <directRouter name="myapi" namespace="MyApp.remote" class=".myapi.MyApi" /> </configure> 3. Provide the extdirect viewletManager in your template. (Note: Ext is a prerequisite.) <tal:block tal: 4. Call methods at will! <script> function a_method_callback(result){ ... do something with result ... } MyApp.remote.a_method({}, a_method_callback); </script> ============= Django Router ============= So, you have a Django app, and you want to add Ext.Direct. Here's how: 1. Add 'extdirect.django' to INSTALLED_APPS in settings.py 2. In a new file called direct.py, define your router class and register it: from extdirect.django import DirectRouter, register_router class MyRouter(DirectRouter): def uppercase(self, word): return word.upper() def lowercase(self, word): return word.lower() register_router(MyRouter, 'Remote') The arguments to register_router are the router class, the client-side namespace, and an optional url under /extdirect at which the router should be available (defaults to the name of the class). 3. In the root URLconf, map the extdirect urls by adding: (r'^extdirect/', include('extdirect.django.urls')) 4. Also in the root URLconf, add these two lines: import extdirect.django as extdirect extdirect.autodiscover() 5. In your template, load the provider definitions: {% load direct_providers %} {% direct_providers %} 6. That's it. You should now have access on that template to the remote methods: Remote.MyRouter.uppercase({word:'a word'}, callback); 0.4 Removed stripped-down direct.js for licensing reasons Rereleased under BSD license Added request batching support (thanks to Brian Edwards, [email protected]) Added provided timeout option in Zope (thanks to Jon-Pierre Gentil, [email protected]) 0.3 Updated django subpackage with Avizoa's patch replacing "import views" with the much cleaner "extdirect.autodiscover()". 0.2 Added django subpackage 0.1 Initial release, including zope subpackage - Author: Ian McCracken - License: BSD - Categories - Package Index Owner: iancmcc - DOAP record: extdirect-0.4.xml
http://pypi.python.org/pypi/extdirect/0.4
crawl-003
refinedweb
947
50.94
Hosting HTML pages from Domino¶ Summary¶ This is a simple example on how to host a HTML page on Domino. There are a number of ways to host web applications of course but this example shows how you can integrate a simple HTTP server using python with Domino. You could also add java script and other pages to your project. The example in this note just shows how you would start the server to support your page(s). Files¶ You’ll need to create two files in your project (in addition to your files required for your page such as index.html etc) app.sh #!/usr/bin/env bash python ./app.py app.py import SimpleHTTPServer import SocketServer PORT = 8888 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever() Publishing¶ To publish your app, go to the left-hand sidebar in your browser and click Publish. The Publish page should now be visible in your browser. Click the App tab. Your screen should now look something like this. Click Publish to publish your app. Getting started with App Publishing.
https://docs.dominodatalab.com/en/3.6/reference/publish/apps/advanced/Hosting_HTML_pages_from_Domino.html
CC-MAIN-2019-47
refinedweb
185
68.97