text
stringlengths 454
608k
| url
stringlengths 17
896
| dump
stringclasses 91
values | source
stringclasses 1
value | word_count
int64 101
114k
| flesch_reading_ease
float64 50
104
|
|---|---|---|---|---|---|
How To Fix the XML Memory “Leak”
Dealing with XML files can very easily trigger Flash to “leak” memory. Your app may only keep a tiny fraction of the XML file’s contents, but the whole file may stay in memory and never get garbage collected. Today’s article examines how this happens and how you can clean up all that unused memory.
This particular memory “leak” stems from a peculiar behavior in Flash where strings that are built from other strings do not actually have a copy of the original string’s characters. Instead, they have a “master string” field which references the characters in the original string. In a debug version of Flash Player you can see the contents of the “master string” using the flash.sampler.getMasterString. Consider the following example:
Even though you’re only using the “AB” string, Flash is holding the whole “ABCDEFGHIJKLMNOPQRSTUV” string in memory since that’s what “AB” was built from. While a few letters of the alphabet is just fine, the problem can get out of control when you’re dealing with huge XML files. What if all you did was save one tiny string from the XML to a variable? As it turns out, the entire XML file will stay in memory in this case. To illustrate, here’s a small example:
How about JSON? Does the same problem happen there, too? Luckily, it does not:
So what do you do if you want to get rid of all that master string baggage from the XML file? To solve that issue I’ve created a tiny static function that modifies the string just enough to convince the Flash Player to dump its master string. Feel free to use this in your own projects:
With this function the master string will be simply “_John”.
Finally, I’ve created a small example application to test strings from XML, JSON, and “cleaned” strings from XML using the above utility function. You’ll need a debug version of Flash Player to run it since it uses
flash.sampler.getMasterString.
Have a better way of cleaning master strings? Run into this problem in your own app? Spot a bug? Post a comment!
#1 by Peter Henry on June 3rd, 2013 · | Quote
I assume you tried the following and it does not work?
return (“”+str).substr(0);
#2 by jackson on June 3rd, 2013 · | Quote
I did, but since adding an empty string doesn’t result in a new string the master string is unchanged too. The same goes with
substr(0).
#3 by Andrew Start on June 3rd, 2013 · | Quote
Is the XML kept around as the master string even if you dispose of it with System.disposeXML()?
#4 by jackson on June 3rd, 2013 · | Quote
Yes:
I believe this is because the
XMLobject is garbage collected but the
Stringobject it was built from is not.
#5 by Clark on June 3rd, 2013 · | Quote
Ahh man, an old concept application at work killed me, it used a lot of text/xml, I debugged it forever and we ended up giving up. I bet this is the problem!
Also it is entirely off topic, but have you ever used ? Every few months I celebrate it as I discover something cool but I am not sure what performance is like? Well just thought I would ask. It has been around for many years now and its usefulness is staggering.
#6 by jackson on June 3rd, 2013 · | Quote
I haven’t used it before, but I may do a performance test of it. Thanks for the link!
#7 by Gene on June 3rd, 2013 · | Quote
var xml:XML = new XML(
”
);
var xmlJohn:String = xml.person[0].@first[0];
var map:Object={};
// <– map[xmlJohn]=xmlJohn;
trace(xmlJohn + " has master string " + flash.sampler.getMasterString(xmlJohn));
try it .. :)
#8 by jackson on June 3rd, 2013 · | Quote
Very interesting find! I played around with it and it turns out that you can also use a
Dictionaryand you don’t need to set the string as the value in the map:
This leads to an alternative way of “cleaning” strings compared to the version in the article:
That will completely remove strings’ master string and never grow the
Dictionarybeyond a temporary single entry.
Thanks for the tip!
#9 by zeh on February 4th, 2014 · | Quote
Just for completeness, I tried this variant and it seems to still keep the original master string around. The original solution with “_” and substr() still works.
#10 by benjamin guihaire on June 21st, 2013 · | Quote
Great article ! Note that the new Scout version released by Adobe on Monday 17th has Memory Profiling capabilities.
In my experience, the XML memory leak was caused by the extensive use of describeType, and the way to reduce the number of leaks was to use the mx.utils.describeTypeCache , so no new XML is created when requesting a describeType for the same class over and over again. It also has an advantage of making the calls to describeType much faster the second time you request it for a given class.
#11 by jackson on June 21st, 2013 · | Quote
Sounds like a handy utility, but the memory “leak” triggered by the code in the article never uses
describeTypeso perhaps we’re talking about two different issues.
#12 by Ivo on June 22nd, 2013 · | Quote
From what i understand it appears this is actually an issue with the way substr() is implemented causing pointers to the original string’s location in memory and not letting it be garbage collected. This raises another interesting question, do string.slice() and string.concat() behave in the same manner if the string is not modified or do they actually create copies of the old string.
If so then according to logic it would be enough to simply append something like .slice() after .substr() to ensure a new object is created and the raw input is free for garbage collection.
#13 by jackson on June 22nd, 2013 · | Quote
The
Stringclass has many functions that may or may not involve master strings. Trying them all out sounds like a good experiment.
#14 by skyboy on July 1st, 2013 · | Quote
The native JSON parser creates a new String object from scratch for every thing it parses, but if you were to use a 3rd party library you’d most likely see some different results; I know mine uses substring to process strings more quickly than the native one does where possible, others may as well. It would also be an interesting test to see if after enough memory is allocated the master string is broken up into smaller strings and freed, and what impact that has on performance.
It also would seem that the native XML parser uses substring internally to improve performance, and would be subject to the same potential pitfalls (permanent memory leak / massive performance drops in unrelated code).
#15 by Fabien on August 22nd, 2013 · | Quote
Thank you so much Jackson, this helped a lot!
#16 by Pierre Chamberlain on August 30th, 2013 · | Quote
If you’re going to use the attributes of an XML element as Number, int, or uint anyways, does this memory leak issue still apply? Should we clean the value as a String before casting it to a Number, int or uint?
#17 by jackson on August 30th, 2013 · | Quote
XML is string-based, so you’re always reading
Stringvalues from it. If all you do is convert the
Stringto
intor something else that has no reference to the
Stringobject, then the
Stringyou got from the
XMLobject will be unreferenced anywhere and therefore eligible for garbage collection and there won’t be a memory “leak”. The problem comes about when you keep the
Stringyou got from
XMLin some way, such as the names in the article. As shown there, just one
Stringis enough to keep the entire XML string around, so just keeping one
Stringand converting another million
Stringvalues to
intwill still mean that the one
Stringis keeping the whole XML string around in memory. If you use the technique in the article to “clean” that one
String, you’ll be OK.
#18 by makc3d on November 6th, 2013 · | Quote
For the sake of completeness: alternativa3d solution.
#19 by Benny on February 20th, 2014 · | Quote
hey,
try this,
slave = slave.substr(0,1)+slave.substr(1);
#20 by jackson on February 21st, 2014 · | Quote
This is a really interesting approach as the resulting string has a master string that is just its first character. I’m not entirely sure what’s going on behind the scenes or which version is better—the article version, this one, or the
Dictionaryversion from my comment above—but this probably warrants further investigation. Thanks for the tip!
|
http://jacksondunstan.com/articles/2260
|
CC-MAIN-2017-22
|
refinedweb
| 1,460
| 68.6
|
In the last couple of months you’ve probably heard talk around the watercooler about React as a simpler and more maintainable way to build applications. It has received a lot of attention since Google’s Angular 2 announcement last fall and there’s been a noticable increase in the number blog posts, hacker news references and stackoverflow questions regarding it. If you are interested in seeing how you can leverage React for your next project you’ve come to the right place.
Part #2: Building with React & Flux: Hello React Banners
There is no time like the present to learn React and we are going to do so with a series of tutorials to build a banner management application with React, Node and MongoDB. We’ll start off slowly with an introduction to React and Flux, then we’ll build a bare-bones React app with Flux so you can see all of the working parts in motion and finally we’ll round out the series with a full-fledged production app backed by an API with authentication and data persistence.
What React Is?
React is Facebook’s UI library for creating interactive, stateful & reusable UI components. It’s the “V” in MVC and could care less about the rest of your technology stack. It has a lot of great features such as a Virtual DOM, one-way data flow, client and server-side rendering and more. We’ll hit on a number of these topics shortly.
Let’s start by clearing up any misconceptions about React right from the start. There’s been a lot of talk on the interwebs lately about React as an alternative to Angular, Ember, Backbone or [insert random JavaScript framework]. Comparing React to other JavaScript frameworks, such as Angular, is like comparing Superman to Batman. One can fly, is impervious to harm, has super strength and heat vision while they other is really good with tech. Angular is a complete framework (views, routing, templating, dependency injection, directives, etc.) while React is simply a view layer. You can’t build an SPA with React by itself. React needs help from Flux… it needs its Robin.
In React functionality is incapsulated into components. You build components that have their own “properties” and “scope”, so you can easily define the functionality of the component and reuse them as many times as you want without conflicting with one another. Each component defines a
render function which returns the generated HTML from the component in the browser.
Components can be written in pure JavaScript or what Facebook calls JSX, a Javascript XML syntax. JSX allows you to write HTML inside of Javascript without having to wrap strings around it. Now we’ve all been conditioned to separate our functionality from our view, but if you think about it, they are actually intrinsic tied to one another. Once you get past the wierd syntax, combining JavaScript and its accompanying markup into a reusable component becomes quite refreshing.
var HelloMessage = React.createClass({ render: function() { var name = 'jeffdonthemic'; return (Hello {name}; ) } }); React.render(, document.body);
You can either transform JSX into JavaScript at runtime in the browser but this is not recommended for production as it slows down page loads. You can use something like gulp or grunt to setup preprocess build tasks to do this for you.
React is just a view layer. That’s it. All React does is render HTML for you.
Why React is so awesome
React concepts are very easy to graps and the code, being simply JavaScript, is readable and easy to maintain. Once you understand the difference between properties and state you’ve got half the battle won. React implements a one-way data flow pattern which reduces boilerplate and make it easier to follow the flow of your application logic. (Side note: Angular 2 will also implement unidirectional data flow.)
React’s main strength is that it is super fast at rendering markup. It uses a concept called the Virtual DOM that selectively renders DOM nodes based upon state changes for the component. So if you have a large HTML table and your state changes in only one row, React simply update the DOM for that single row instead of rewriting the entire DOM. Its diff algorithm does the least amount of DOM manipulation possible in order to keep your view up to date. (Side note: Angular 2 will also implement a Shadow DOM.)
React runs JavaScript on both the client & server in what is called Isomorphic JavaScript. While most frameworks use client-side DOM rendering, React provides a better experience by performing these actions server-side. Not only is it faster and easier to maintain, but code is indexable by search engines as well.
React Tutorials
There are a ton of great resources for learning React so I’m not going to reinvent the wheel. My favorites are Ryan Clark’s Getting started with React (great overview), the egghead.io React tutorials (don’t skip these!!) and the scotch.io Learning React.js series. You also need to check out this collection of awesome React libraries, resources and shiny things. Tons of great stuff!
What is Flux?
Like I said, you cannot build a SPA simply with React. Every superhero needs a sidekick to do the dirty work, and in this case React’s Robin is Flux. The main thing to understand is that Flux is an architectural pattern for building applications with React. Flux is not a framework nor a library nor any type of MVC paradigm.
What the Flux? has a far better explanation of this, but The Flux Application Architcture is composed of the following parts.
- Views – the rendered HTML from your component
- Action Creators – dispatcher help methods that get more “stuff”
- Actions – perform some type of action on the “stuff”
- Dispatcher – notifies listeners that there is new “stuff”
- Store – a singleton that holds state and business logic for your stuff
So the flow is that your component’s view triggers an event (e.g., user types text in a form field), that fires an event to update the model, then the model triggers an event and the component responds by re-rendering the view with the latest data. Simple!? Another great article you should read is Flux For Stupid People.
Now, I’m not a rocket surgeon nor do I play one on TV but this looks like a lot of work and is pretty damn confusing when you look at some sample Flux code. Since Facebook doesn’t provide a Flux library the community has implemented a number of their own including Flux Dispatcher, Fluxxor, ReactFlux, Flux-Action and RefluxJS. I’ll be using Reflux for this series. I found it much easier to grok then the other libraries, it has a “strong” community on github and is very straightforward to implement. [React.js architecture – Flux VS Reflux](React.js architecture – Flux VS Reflux) is a great article you should read regarding the differences and advantages of Reflux.
So that wraps up our first post in the series. In our next one we’ll build a very simple React application with Reflux to demonstrate how this process works.
|
https://www.topcoder.com/blog/building-with-react-flux-getting-started/
|
CC-MAIN-2018-05
|
refinedweb
| 1,201
| 62.68
|
Last Updated on December 13, 2020.
In react native, we use onPress prop in touchable components to enable pressing functionality. But, what about having onPress function for the View component itself? This feature is one of the things I was missing when I compare react native to native Android development.
If you are using react native version greater than 0.55.3 then you can add onPress kind of functionality to any View component using onStartShouldSetResponder prop. This prop makes the view responds on the start of touch- which is strikingly similar to the onPress prop of other components.
In the following react native view on press example, I have a view component with onStartShouldSetResponder prop which invokes an Alert function. This means the alert will appear when the view is pressed. That’s how you add onPress functionality to View in React Native.
import React from 'react'; import {View, Alert, StyleSheet} from 'react-native'; const Home = () => { return ( <View style={styles.container}> <View style={styles.view} onStartShouldSetResponder={() => Alert.alert('OnPress', 'Clicked on View') } /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', }, view: { height: 100, width: '100%', backgroundColor: '#00BCD4', }, }); export default Home;
The output will be as given below.
|
https://reactnativeforyou.com/how-to-set-onpress-function-to-view-in-react-native/
|
CC-MAIN-2021-43
|
refinedweb
| 204
| 58.38
|
- JGraph Intro
- Component Architecture
- Conclusion
For more information on Java development, visit our Java Reference Guide or sign up for our Java Newsletter.
Last time, I introduced you to a series on useful open-source tools that could prove beneficial to your Java career. The inaugural article focused on iText, an open-source Java library for creating PDF, HTML, RTF, and XML documents. This article continues the series by presenting JGraph.
Computer science defines a graph as a nonempty finite set of vertices (labelled points) and a set of edges (pairs of vertices) that signify connections between the vertices. Graphs represent networks of related and (typically) interconnected objects such as roads, molecules, database schemas, and the Internet. Although the graph concept is easy to understand, creating the software to construct, display, and manipulate graphs can be difficult. Thanks to Java and a utility called JGraph, you do not need to create your own graph software.
This article introduces you to JGraph. After showing you how to acquire JGraph, install this tool, and set the CLASSPATH environment variable, I present a simple Java application that uses JGraph to create and display a sample graph. This application introduces you to several operations that JGraph provides for graph manipulation. The article then explores several important areas of JGraph’s architecture. This JGraph overview provides you with enough knowledge to quickly start creating your own graphs.
JGraph Intro
JGraph, created by Gaudenz Alder, is an open-source, Swing-based component for building, displaying, and manipulating graphs. JGraph is available as a free version under the GNU Lesser General Public License (LGPL) and as a commercial version under the JGraph General License. The main difference between these licenses: LGPL requires you to include JGraph’s source code (including any modifications you make to JGraph) when distributing an application that uses JGraph; JGraph’s source code does not need to be included under the General License.
Visit the JGraph Free Downloads page to download the binary and source distributions for the latest free version of JGraph. You need only the binary distribution for this article: Click the Download Latest Binary Distribution link to obtain that distribution. After the download finishes, you will discover jgraph-latest-lgpl.jar on your hard drive.
From the command line, invoke java -jar jgraph-latest-lgpl.jar to install JGraph. After agreeing to all terms in the license agreement, choose an installation directory, such as c:\jgraph (which is the installation directory assumed in this article). JGraph installs to this directory. If installation is successful, the installation directory will contain the following files and directories:
- ChangeLog identifies those changes introduced by each version of JGraph.
- LICENSE presents version 2.1 of the LGPL.
- README introduces JGraph and provides instructions for building this tool from its source code.
- WHATSNEW describes new features and bug fixes introduced by each JGraph version. This file’s content is similar to the content found in ChangeLog.
- doc provides JGraph documentation. Its api subdirectory contains Javadoc files that describe the API. The pdf subdirectory contains an updating.pdf file with information that can help you update existing JGraph code to the latest version.
- examples provides a package of Java programs that demonstrate JGraph features.
- lib provides the jgraph.jar Jar file, which you must add to your CLASSPATH environment variable before you can use JGraph. For Windows 98 SE, the command to set CLASSPATH is set classpath=%classpath%;c:\jgraph\lib\jgraph.jar;. If you are using a different version of Windows, or a non-Windows operating system, study your OS documentation to find out how to set this environment variable.
Now that JGraph has been downloaded, installed, and configured, we can explore a Java application that uses JGraph to create a sample graph. Take a look at Listing 1.
Listing 1 SampleGraph.java
// SampleGraph.java import org.jgraph.JGraph; import javax.swing.*; public class SampleGraph extends JFrame { public SampleGraph (String title) { super (title); setDefaultCloseOperation (EXIT_ON_CLOSE); getContentPane ().add (new JScrollPane (new JGraph ())); pack (); setVisible (true); } public static void main (String [] args) { new SampleGraph ("Sample Graph"); } }
Listing 1 describes a Swing application that introduces a sample graph into its GUI. The application’s constructor introduces the sample graph by creating an org.jgraph.JGraph object and invoking its public JGraph() constructor to initialize this object. The JGraph object is then placed into a JScrollPane (to make sure that the entire graph is viewable, even when the graph exceeds its display area because the window has been resized smaller) and the JScrollPane is added to the JFrame’s content pane.
After compiling Listing 1, run this application. You will see the sample graph that is presented in Figure 1. The rectangles serve as the graph’s vertices, and the lines serve as its edges.
Figure 1’s sample graph is not just for show: You can also manipulate this graph by performing various operations. For example, double-click the vertex that displays JComponent (or single-click that vertex to select it and then press F2). In response, an editor appears over the vertex to perform in-place editing of the vertex’s label. Type abc into that text field and then press Enter. You should now see abc instead of JComponent. Figure 2 reveals the editor and the entered label.
When you select a vertex, you will notice small handles (rectangles that you can grip for sizing) in the vertex’s corners and along its sides. Similarly, the selection of an edge results in handles at the source and target of that edge. These handles make it possible to resize the vertex or edge. Accomplish that task by using the mouse to select and drag a handle: The vertex or edge resizes in that direction. For example, resize the JGraph vertex by selecting that vertex, gripping the handle in the lower-right corner, and dragging the handle downward and to the right. Figure 3 shows this vertex expanding.
You can select a combination of vertices and edges by holding down Shift during the selection process. If you accidentally select a vertex or edge that you do not want to be included, release Shift and press Ctrl to deselect that vertex/edge. A pair of selected vertices and the edge that connects those vertices are dragged to another location in Figure 4.
Resizing or dragging a selection—you can abort either operation by pressing Esc—is accomplished through a cell handle. In contrast to an editor that uses a text component to change a vertex/edge label through in-place editing, a cell handle uses other means (such as performing a color change and showing grayed edges in their new locations) to provide users with visual feedback on how a graph will look after the change has been made. JGraph refers to this feature as live-preview.
JGraph supports the placement of related vertices and edges into groups, a mechanism for structurally organizing a graph. The presence of groups within a graph affects the selection process. When selecting a vertex or edge within a group, the first mouse click on the vertex or edge selects the group (whose members can then be resized or dragged as a single unit—you can even edit the group’s name); the second mouse click selects the vertex/edge. (If groups are nested within other groups, it can take multiple clicks on the vertex or edge before that vertex/edge is selected.) Figure 5 illustrates this stepping into groups feature. Notice the dashed outline around a group, consisting of vertex GraphModel, edge implements, and vertex DefaultGraphModel. That outline indicates the selection of the group. Also notice the selection of the implements edge, whose label appears in the editor.
You can select multiple groups, vertices, and edges by pressing Shift and clicking each entity, but that is somewhat cumbersome. If those entities exist within a rectangular area, an easier way to accomplish this task involves marquee selection.
Marquee selection is a selection mechanism in which you move the mouse pointer to any location in the graph and press a mouse button. As you drag the mouse pointer, you observe a rectangle—known as a marquee—that expands or contracts, based on the direction of movement. When you release the mouse button, the marquee disappears; all groups, vertices, and edges completely within the marquee are selected. Figure 6 reveals the marquee. When the mouse button is released, the JComponent vertex, the extends edge, and the JGraph vertex will be selected.
Sometimes, you will want to more accurately place a vertex, an edge, or a group during a drag operation—by constraining the drag to horizontal and vertical movement. In other words, you do not want to drag diagonally. JGraph provides a constrained drag operation to help you accomplish this task. That operation requires you to hold down Shift while dragging the mouse.
There is one final operation to consider: clone selection (the duplication of a vertex, an edge label, or a group by holding down the Ctrl key while dragging the mouse). Unlike constrained drag, clone selection cannot be demonstrated in SampleGraph without changing the source code. The change requires replacing the following line of code:
getContentPane ().add (new JScrollPane (new JGraph ()));
with this code fragment:
graph = new JGraph (); graph.setCloneable (true); getContentPane ().add (new JScrollPane (graph));
Modify SampleGraph.java to incorporate the code fragment above, compile the source code, and run the application. Position the mouse pointer over a vertex, an edge label, or a group member and then hold down Ctrl while dragging the mouse. You will end up with a clone of the vertex, edge label, or group.
For more practice with JGraph’s operations, you will want to check out the graph editor example that ships with JGraph. Compile the graph editor’s source code, which resides in c:\jgraph\examples\org\jgraph\example\GraphEd.java, and run that program as an application—you can also run the graph editor as an applet. Figure 7 reveals the graph editor’s GUI.
The graph editor’s toolbar presents several icons. Click the leftmost icon to introduce a vertex into the GUI. The icon immediately to the right, when it appears as an arrow, causes a small rectangle to appear in the midst of a vertex. Selecting that rectangle and dragging the mouse results in an edge being drawn from the vertex (presumably you want to draw the edge to another vertex). But if the icon appears with a stylized red X drawn on top, you cannot draw an edge.
|
http://www.informit.com/articles/article.aspx?p=431106
|
CC-MAIN-2017-30
|
refinedweb
| 1,756
| 55.44
|
Someone a while back wanted to wget from an svn repository. But you can't just
grab the regular url, since someone may commit in the middle. I wrote the
script below as a small exercise, and as an excuse to install cadaver. Given a
repository and a path, it gets the baseline collection url.
Props to sussman for walking me through the three steps to the baseline
collection. That was a few weeks ago on irc.
Enjoy :-)
Craig
$ cat get-bc-url
#!/usr/bin/env expect
log_user 0
set timeout -1
set usage_text "
Returns the current magic baseline collection URL for a given REPO PATH
combination. If authentication is required, use USER and read the password
from stdin.
Usage:
get-bc-url REPO PATH \[USER]
Examples:
get-bc-url trunk
get-bc-url path user << EOF
EOF
bcurl=\$(get-bc-url ...)
wget -q -np --mirror -e \"robots = off\" \"\${bcurl}\"
"
proc usage {} {
global usage_text
send_error "$usage_text"
exit
}
if { $argc < 2 } { usage }
set url [string trim [lindex "$argv" 0] "/"]
set path [string trim [lindex "$argv" 1] "/"]
set username [lindex "$argv" 2]
proc handle_auth {} {
global username
if { $username == "" } { usage }
send "$username\n"
expect "Password:"
stty -echo
expect_user -re "(.*)\n"
stty echo
set password "$expect_out(1,string)"
send "$password\n"
expect ">"
}
spawn cadaver $url
expect ">" {} "Username:" { handle_auth }
send "set namespace DAV:\n"
expect ">"
# figure out version controlled configuration
send "propget . version-controlled-configuration\n"
expect -re "<href>(.+)</href>"
set vcc "$expect_out(1,string)"
expect ">"
# figure out baseline resource
send "propget $vcc checked-in\n"
expect -re "<href>(.+)</href>"
set br "$expect_out(1,string)"
expect ">"
# figure out baseline collection
send "propget $br baseline-collection\n"
expect -re "<href>(.+)</href>"
set bc "$expect_out(1,string)"
expect ">"
send "cd $bc$path\n"
expect ">"
send "pwd\n"
expect -re "`(.+)'\."
set out "$expect_out(1,string)"
send_user "$out\n"
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org
For additional commands, e-mail: dev-help@subversion.tigris.org
Received on Fri Dec 6 02:28:27 2002
This is an archived mail posted to the Subversion Dev
mailing list.
|
https://svn.haxx.se/dev/archive-2002-12/0331.shtml
|
CC-MAIN-2017-17
|
refinedweb
| 340
| 56.15
|
Can python nosetest and py.test frameworks run tests with multiprocessing
I have the following code that works fine when run as a python unittest but fails if using nosetest or py.test with the following error messages:
NoseTest error: PicklingError: Can't pickle : it's not found as teamcity.nose_report.newCaptureBeforeTest
py.test error: PicklingError: Can't pickle : it's not found as __builtin__.module
Code:
import unittest import multiprocessing as mp import time TIME_LIMIT = 1 class TestCases(unittest.TestCase): def setUp(self): self.a = 0 def my_func(self): time.sleep(2) self.q.put(self.a + 1) def run_case(self, func): self.q = mp.Queue() test_process = mp.Process(target=func) test_process.start() test_process.join(TIME_LIMIT) self.assertFalse(test_process.is_alive(), 'timeout exceeded') def test_case1(self): self.run_case(self.my_func) self.assertEquals(self.a + 1, self.q.get())
See also questions close to this topic
- ununderstandable behavior subprocess.Popen(cmd,stdout) and os.system(cmd)
I use an external command inside a python script using firstly:
subprocess.Popen(cmd, stdout=subprocess.PIPE)
then i get the stdout.
The problem is that the result of this external command when executing it inside the script is not the same if i execute it directly in the command line.
I use then
os.system(cmd), but the same problem.
Is this instructions in python use some buffers?
How can i explain the difference between the two results (command line and inside the script).
- Update table sqlite3
I am attempting to update an sql table in python to increase the value of an Americano coffee, but the sql statement
con = sqlite3.connect('Users.db')
cur = con.cursor()
cur.execute("UPDATE USERS SET AMERICANO = 2 WHERE ID = ?;", (self.Id))
Doesn't update the table and I have no idea why.
- How do I combine two variables in python?
What i'm looking for is something like this ... if there is a way like this, the help would be appreciated.
item12 = "SAMPLE TEXT" i = 12 print(item(i)) > SAMPLE TEXT
- pytest: how to use a fixture to parametrize
in
conftest.pythere is a fixture defined that returns a list:
@pytest.fixture(scope="session") def targets_to_try(): with open( "{}/xxx/cicd/xxx/manifest.yaml".format(os.environ["APPFOLDER"]), "rt" ) as f: manifest = yaml.safe_load(f.read()) schema = Manifest.ManifestSchema() appobj = schema.load(manifest) return appobj.data.targets_to_try
In test file
test_interfaces_cfg.pyI would like to use the above fixture in order to parametrize the test function
import pytest @pytest.mark.parametrize("target", targets_to_try) def test_interfaces_cfg(manifest, target): pass
This causes the following error:
E NameError: name 'targets_to_try' is not defined
Could you please advise how to achieve the desired behaviour ?
- ModuleNotFoundError: No module named
In
conftest.pyI am loading the module
blueprint.Manifest, which in turn loads the module
Headfor example. Please see minimal example at the bottom of the description. But I get the following error:
$ py.test manifest/test_schema.py/test_schema.py') During handling of the above exception, another exception occurred:') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/_pytest/config/__init__.py", line 412, in _importconftest return self._conftestpath2mod[conftestpath] KeyError: local('/home/app/ip-spotlight/code/cicd/lydia/conftest.py') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/_pytest/config/__init__.py", line 418, in _importconftest mod = conftestpath.pyimport() File "/usr/lib/python3.6/site-packages/py/_path/local.py", line 668, in pyimport __import__(modname) File "/usr/lib/python3.6/site-packages/_pytest/assertion/rewrite.py", line 296, in load_module six.exec_(co, mod.__dict__) File "/home/app/ip-spotlight/code/cicd/lydia/conftest.py", line 5, in <module> from blueprint.Manifest import ManifestSchema File "/home/app/ip-spotlight/code/cicd/lydia/blueprint/Manifest.py", line 5, in <module> from Head import HeadSchema ModuleNotFoundError: No module named 'Head' ERROR: could not load /home/app/ip-spotlight/code/cicd/lydia/conftest.py
my current environment is
$ py.test --version This is pytest version 3.8.0, imported from /usr/lib/python3.6/site-packages/pytest.py setuptools registered plugins: pytest-xdist-1.23.0 at /usr/lib/python3.6/site-packages/xdist/plugin.py pytest-xdist-1.23.0 at /usr/lib/python3.6/site-packages/xdist/looponfail.py pytest-timeout-1.3.2 at /usr/lib/python3.6/site-packages/pytest_timeout.py pytest-sugar-0.9.1 at /usr/lib/python3.6/site-packages/pytest_sugar.py pytest-metadata-1.7.0 at /usr/lib/python3.6/site-packages/pytest_metadata/plugin.py pytest-html-1.19.0 at /usr/lib/python3.6/site-packages/pytest_html/plugin.py pytest-forked-0.2 at /usr/lib/python3.6/site-packages/pytest_forked/__init__.py celery-4.2.1 at /usr/lib/python3.6/site-packages/celery/contrib/pytest.py
Minimal example: my project's structure is like:
$ tree . |-- attributes | `-- __init__.py |-- bgp | `-- __init__.py |-- blueprint | |-- Head.py | |-- __init__.py | |-- InterfacesIx.py | |-- InterfacesLacp.py | |-- Manifest.py | |-- NeighborIx.py | `-- Tail.py |-- communities | `-- __init__.py |-- conftest.py |-- customize | `-- __init__.py |-- interfaces | `-- __init__.py |-- manifest | |-- blueprint | |-- __init__.py | `-- test_schema.py |-- policies | `-- __init__.py |-- prefixes | `-- __init__.py `-- pytest.ini
The
conftest.pylooks like this:
import os import yaml import pytest from blueprint.Manifest import ManifestSchema @pytest.fixture(scope="session") def manifest(): with open( "{}/ip-spotlight/code/cicd/manifest.yaml".format(os.environ["APPFOLDER"]), "rt" ) as f: manifest = yaml.safe_load(f.read()) schema = ManifestSchema() appobj = schema.load(manifest) return appobj
and
blueprint/Manifest.pylooks like this:
import marshmallow import dictdiffer import requests from Head import HeadSchema
Could you please advise what I am doing wrong and and help me with solving this issue ?
- check values using pytest python dataframe
I have a dataframe with a index holding different measures I need to check whether the 4 measures holds values in them. Like index has A,B,C,D, I need to check if A,B,C,D are present and doesn't hold any null values. Can anyone suggest how to achieve this .
- Separate process sharing queue with main process (producer/consumer)
I'm pretty new to multiprocessing in Python and I've done a lot of digging around, but can't seem to find exactly what I'm looking for. I have a bit of a consumer/producer problem where I have a simple server with an endpoint that consumes from a queue and a function that produces onto the queue. The queue can be full, so the producer doesn't always need to be running.
While the queue isn't full, I want the producer task to run but I don't want it to block the server from receiving or servicing requests. I tried using multithreading but this producing process is very slow and the GIL slows it down too much. I want the server to be running all the time, and whenever the queue is no longer full (something has been consumed), I want to kick off this producer task as a separate process and I want it to run until the queue is full again. What is the best way to share the queue so that the producer process can access the queue used by the main process?
-
- Threading And MultiProcessing Combination [Python]
I'm trying to experiment with using both threading and Multiprocessing module
import multiprocessing as mp import threading from threading import Thread import time QP = mp.Queue() Lock = mp.Lock() Input = 100 Checked = mp.Value("i",0) class MultiThreading(threading.Thread): def __init__(self,QP,Checked): threading.Thread.__init__(self) self.QP = QP self.Checked = Checked def run(self): global Input global Lock QueueMode = self.QP.get() First,Second = QueueMode Lock.acquire() print ("{} {} - Has Successfully Done".format(First,Second)) Checked.value += 1 time.sleep(0.25) Lock.release() if not Input == Checked.value: t = MultiThreading(QP,Checked) t.setDaemon(False) t.start() def MultiCall(QP,Checked): for i in range(10): t = MultiThreading(QP,Checked) t.setDaemon(False) t.start() if __name__ == "__main__": for i in range(100): QP.put((i,i+i)) Processes = [] for i in range(4): p = mp.Process(target=MultiCall, args=(QP,Checked)) Processes.append(p) p.start() p.join while not Input == Checked: continue print ("Task Done")
The code above is what i've been currently on,when i run the code regulerly it goes on an error either "unable to start new thread" or just freeze,however when i use the debugger it works however slow,so i'm confuse as to what is going on
- Migrating form noses setup_package() to pytest
right now I'm trying to convert some API tests from Nose to Pytest. When I tried to do that I faced a little problem: Pytest doesnt support the "setup_package()" functionality. The "setup_package()" is in the __init__.py file of where the tests are.
This is the directory structure:
tests/__init__.py test_001.py test_002.py ...
A easy solution would be to give the setup_package() function a fixture, but the problem here is, that my setup_package() is accessing a global counter in the __init__.py. So that the __ini__.py file looks like that:
counter_id = 0 def setup_package(): global counter counter = some_function() def teardown_package(): global counter clear_object(counter_id)
Im pretty sure, that there is very easy solution to migrate this but as I'm new to Pytest I want to know the "pytestian" way of migrating this particular example to Pytest! My first idea was to use a fixture with params functionality, but I'm not sure if it's a good way to migrate at all.
- Have nosetests ignore minimum coverage if exit due to test failure?
On my test runner to determine if a git branch passes or fails, I test my python like so:
nosetests -x --with-coverage ${PACKAGE} --cover-min-percentage=80
The
-x(exit on first failure) is a new addition, as we want to immediately fail the build if any unit tests fail. However, if an early test fails and we exit, nosetests falsely says that min coverage has not been met if some of the early packages have low coverage because it wasn't able to cover everything.
How can I have the coverage check be aborted/ignored if any tests fail?
- How to test if a jinja template is loaded with nose - Flask
Right now I have these tests on my Flask application:
from usio import app import unittest import nose class TestLatest(unittest.TestCase): def test_fixerio_latest(self): """ Here we are testing latest rates fixer.io we are ensuring that we will have response 200 on the server side """ # Use Flask's test client for our test. self.test_app = app.test_client() response = self.test_app.post('/', data={'From': 'my_key'}) # Assert response is 200 OK. self.assertEquals(response.status, "200 OK") class TestHistorical(unittest.TestCase): def test_fixerio_historical(self): """ Here we are testing historical rates fixer.io we are ensuring that we will have response 200 on the server side """ # Use Flask's test client for our test. self.test_app = app.test_client() response = self.test_app.post('/historical', data={'From': 'my_key'}) # Assert response is 200 OK. self.assertEquals(response.status, "200 OK") if __name__ == '__main__': nose.run()
However, for example, on this function:
def getExchangeRates(): """ Here we have the function that will retrieve the latest rates from fixer.io """ rates = [] response = urlopen('my_key') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']: try: rates.append(rates_from_rdata[rate_symbol]) except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates
I load a template with this function:
@app.route("/" , methods=['GET', 'POST']) def index(): rates = getExchangeRates() return render_template('index.html',**locals())
How can I test from my test file, if the
render_templateis actually loading the
index.htmlfile?
I know it might sound dumb, but I just want to add a new test to my application, any ideas?
|
http://quabr.com/51276575/can-python-nosetest-and-py-test-frameworks-run-tests-with-multiprocessing
|
CC-MAIN-2018-39
|
refinedweb
| 1,987
| 52.26
|
Version 25plus(Describes actual ngspice source code at git)Paolo Nenzi, Holger VogtOctober 20, 2013
LocationsThe project and download pages of ngspice may be found atNgspice home page page at sourceforge page at sourceforge source download
StatusThis manual is a work in progress. Some to-dos are listed in the following. More is surelyneeded. You are invited to report bugs, missing items, wrongly described items, bad Englishstyle etc.
To Do1. Review of chapt. 1.32. hfet1,2 model descriptions
Part INgspice User Manual
ContentsI
Introduction
33
1.1
Simulation Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
34
1.1.1
Analog Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.1.2
Digital Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . .
35
1.1.3
Mixed-Mode Simulation . . . . . . . . . . . . . . . . . . . . . . . . .
1.1.4
Mixed-Level Simulation . . . . . . . . . . . . . . . . . . . . . . . . .
36
Supported Analyses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
37
1.2.1
DC Analyses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.2
AC Small-Signal Analysis . . . . . . . . . . . . . . . . . . . . . . . .
38
1.2.3
Transient Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.4
Pole-Zero Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.5
39
1.2.6
Sensitivity Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2.7
Noise Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
40
1.2.8
. . . . . . . . . . . . . . . . . . . . .
1.3
1.4
Convergence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
42
1.4.1
1.4.2
43
1.4.3
Convergence failure . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2
Circuit Description
45
2.1
2.1.1
2.1.2
. . . . . . . . . . . . . . . . . . .
2.1.3
46
CONTENTS2.2
Basic lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
48
2.2.1
.TITLE line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.2
.END Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2.3
49
2.2.4
End-of-line comments . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3
2.4
.SUBCKT Subcircuits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
50
2.4.1
.SUBCKT Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
51
2.4.2
.ENDS Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
52
2.4.3
Subcircuit Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5
.GLOBAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6
.INCLUDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7
.LIB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
53
2.8
2.8.1
.param line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.2
54
2.8.3
Subcircuit parameters . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.4
Symbol scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
55
2.8.5
Syntax of expressions . . . . . . . . . . . . . . . . . . . . . . . . . .
2.8.6
Reserved words
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
58
2.8.7
Alternative syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.FUNC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.10 .CSPARAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
59
2.11 .TEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
60
61
2.13.1 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.9
63
3.1
3.1.1
3.1.2
Technology scaling . . . . . . . . . . . . . . . . . . . . . . . . . . . .
64
3.1.3
Model binning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
CONTENTS3.1.43.2
7Multiplier m, initial conditions . . . . . . . . . . . . . . . . . . . . . .
Elementary Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
65
3.2.1
Resistors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2.2
Semiconductor Resistors . . . . . . . . . . . . . . . . . . . . . . . . .
66
3.2.3
3.2.4
68
3.2.5
Capacitors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2.6
Semiconductor Capacitors . . . . . . . . . . . . . . . . . . . . . . . .
69
3.2.7
3.2.8
71
3.2.9
Inductors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
72
73
74
. . . . . . . . . . . . . .
75
3.2.14 Switches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
76
77
79
4.1
4.1.1
Pulse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
80
4.1.2
Sinusoidal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
81
4.1.3
Exponential . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.1.4
Piece-Wise Linear . . . . . . . . . . . . . . . . . . . . . . . . . . . .
82
4.1.5
Single-Frequency FM . . . . . . . . . . . . . . . . . . . . . . . . . .
4.1.6
83
4.1.7
4.1.8
84
4.1.9
85
4.2.1
4.2.2
86
4.2.3
4.2.4
4.2.5
87
4.2
CONTENTSNon-linear Dependent Sources (Behavioral Sources)
89
5.1
5.1.1
5.1.2
92
5.1.3
par(expression) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.1.4
95
5.2.1
VOL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2.2
VALUE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2.3
TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2.4
POLY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.2.5
LAPLACE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
96
97
5.3.1
CUR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.3.2
5.3.3
5.3.4
98
5.3.5
5.3.6
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
99
5.2
5.3
5.46
Transmission Lines6.1
6.2
6.3
6.4
101
6.4.2
Diodes
107
7.1
7.2
7.3
CONTENTS8
BJTs
9115
8.1
8.2
JFETs
121
9.1
9.2
9.2.2
10 MESFETs
125
127
10
CONTENTS
139
. . . . . . . . . . . . . . . . . . . . 139
11
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
223
12
225
227
13
255
14
CONTENTS16.11Server mode option -s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26516.12Ngspice control via input, output fifos . . . . . . . . . . . . . . . . . . . . . . 26616.13Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26816.13.1 Compatibility mode . . . . . . . . . . . . . . . . . . . . . . . . . . . 26816.13.2 Missing functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26816.13.3 Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26916.13.4 Controls and commands . . . . . . . . . . . . . . . . . . . . . . . . . 26916.14Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27016.15Reporting bugs and errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
17 Interactive Interpreter
273
. . . . . . . . . . . . . . . . 282
15
. . . . . . . . . . . . . 292
16
CONTENTS17.5.52 Rspice*: Remote ngspice submission . . . . . . . . . . . . . . . . . . 30117.5.53 Run*: Run analysis from the input file . . . . . . . . . . . . . . . . . . 30117.5.54 Rusage: Resource usage . . . . . . . . . . . . . . . . . . . . . . . . . 30117.5.55 Save*: Save a set of outputs . . . . . . . . . . . . . . . . . . . . . . . 30217.5.56 Sens*: Run a sensitivity analysis . . . . . . . . . . . . . . . . . . . . . 30317.5.57 Set: Set the value of a variable . . . . . . . . . . . . . . . . . . . . . . 30417.5.58 Setcirc*: Change the current circuit . . . . . . . . . . . . . . . . . . . 30417.5.59 Setplot: Switch the current set of vectors . . . . . . . . . . . . . . . . 30417.5.60 Setscale: Set the scale vector for the current plot . . . . . . . . . . . . 30417.5.61 Settype: Set the type of a vector . . . . . . . . . . . . . . . . . . . . . 30517.5.62 Shell: Call the command interpreter . . . . . . . . . . . . . . . . . . . 30517.5.63 Shift: Alter a list variable . . . . . . . . . . . . . . . . . . . . . . . . . 30517.5.64 Show*: List device state . . . . . . . . . . . . . . . . . . . . . . . . . 30517.5.65 Showmod*: List model parameter values . . . . . . . . . . . . . . . . 30617.5.66 Snload*: Load the snapshot file . . . . . . . . . . . . . . . . . . . . . 30617.5.67 Snsave*: Save a snapshot file . . . . . . . . . . . . . . . . . . . . . . 30717.5.68 Source: Read a ngspice input file . . . . . . . . . . . . . . . . . . . . 30717.5.69 Spec: Create a frequency domain plot . . . . . . . . . . . . . . . . . . 30817.5.70 Status*: Display breakpoint information . . . . . . . . . . . . . . . . . 30817.5.71 Step*: Run a fixed number of time-points . . . . . . . . . . . . . . . . 30817.5.72 Stop*: Set a breakpoint . . . . . . . . . . . . . . . . . . . . . . . . . . 30917.5.73 Strcmp: Compare two strings . . . . . . . . . . . . . . . . . . . . . . 30917.5.74 Sysinfo*: Print system information . . . . . . . . . . . . . . . . . . . 31017.5.75 Tf*: Run a Transfer Function analysis . . . . . . . . . . . . . . . . . . 31017.5.76 Trace*: Trace nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . 31117.5.77 Tran*: Perform a transient analysis . . . . . . . . . . . . . . . . . . . 31117.5.78 Transpose: Swap the elements in a multi-dimensional data set . . . . . 31117.5.79 Unalias: Retract an alias . . . . . . . . . . . . . . . . . . . . . . . . . 31217.5.80 Undefine: Retract a definition . . . . . . . . . . . . . . . . . . . . . . 31217.5.81 Unlet: Delete the specified vector(s) . . . . . . . . . . . . . . . . . . . 31217.5.82 Unset: Clear a variable . . . . . . . . . . . . . . . . . . . . . . . . . . 31217.5.83 Version: Print the version of ngspice . . . . . . . . . . . . . . . . . . . 31317.5.84 Where*: Identify troublesome node or device . . . . . . . . . . . . . . 31417.5.85 Wrdata: Write data to a file (simple table) . . . . . . . . . . . . . . . . 31417.5.86 Write: Write data to a file (Spice3f5 format) . . . . . . . . . . . . . . . 314
17
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
335
18
CONTENTS18.6 Postscript printing options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33918.7 Gnuplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34018.8 Integration with CAD software and third party GUIs . . . . . . . . . . . . . 34018.8.1 KJWaves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34018.8.2 GNU Spice GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34018.8.3 XCircuit
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
343
19
20 TCLspice
359
371
383
20
391
397
II
25 XSPICE Basics
401403
405
417
21
427
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
461
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
. . . . . . . . . . . . . . . . . . . . . . . . . . . 471
22
III
CIDER
473
475
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
30.8.1 DESCRIPTION30.9 MATERIAL
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
23
30.9.1 DESCRIPTION
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
30.10.1 DESCRIPTION
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
30.12MODELS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49230.12.1 DESCRIPTION
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
30.13.1 DESCRIPTION
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
24
CONTENTS30.16.1 DESCRIPTION
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
30.18NBJT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50230.18.1 DESCRIPTION
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
30.19.1 DESCRIPTION
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
IV
Appendices
507509
25
. . . 543
. . . 547
565
26
CONTENTS32.1.8 Installation Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57032.1.9 Optional Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57032.1.10 Specifying the System Type . . . . . . . . . . . . . . . . . . . . . . . 57132.1.11 Sharing Defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57132.1.12 Operation Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57132.2 Ngspice Compilation under WINDOWS OS
. . . . . . . . . . . . . . . . . . 571
. . . . . . . . . . . . 571
579
PrefacesPreface to the first editionThis manual has been assembled from different sources:1. The spice3f5 manual,2. the XSPICE users manual,3. the CIDER users manualand some original material needed to describe the new features and the newly implementedmodels. This cut and paste approach, while not being orthodox, allowed ngspice to have a fullmanual in a fraction of the time that writing a completely new text would have required. The useof LaTex and Lyx instead of TeXinfo, which was the original encoding for the manual, furtherhelped to reduce the writing effort and improved the quality of the result, at the expense of anon-line version of the manual but, due to the complexity of the software I hardly think that userswill ever want to read an on-line text version.In writing this text I followed the cut of spice3f5 manual, both in the chapter sequence andpresentation of material, mostly because that was already the user manual of spice.Ngspice is an open source software, users can download the source code, compile, and run it.This manual has an entire chapter describing program compilation and available options to helpusers in building ngspice (see chapt. 32). The source package already comes with all safeoptions enabled by default, and activating the others can produce unpredictable results and thusis recommended to expert users only. This is the first ngspice manual and I have removed allthe historical material that described the differences between ngspice and spice3, since it wasof no use for the user and not so useful for the developer who can look for it in the Changelogsof in the revision control system.I want to acknowledge the work dome Emmanuel Rouat and Arno W. Peters for converting toTEXinfo the original spice3f documentation, their effort gave ngspice users the only availabledocumentation that described the changes for many years. A good source of ideas for thismanual comes from the on-line spice3f manual written by Charles D.H. Williams (Spice3f5User Guide), constantly updated and useful for some insight that he gives in it.As always, errors, omissions and unreadable phrases are only my fault.Paolo NenziRoma, March 24th 2001
27
28
CONTENTSIndeed. At the end of the day, this is engineering, and one learns to livewithin the limitations of the tools.
Acknowledgmentsngspice contributorsSpice was originally written at The University of California at Berkeley (USA).Since then, there have been many people working on the software, most of them releasingpatches to the original code through the Internet.The following people have contributed in some way:Vera Albrecht,Cecil Aswell,Giles C. Billingsley,Phil Barker,Steven Borley,Stuart Brorson,Mansun Chan,Wayne A. Christopher,Al Davis,Glao S. Dezai,Jon Engelbert,Daniele Foci,Noah Friedman,David A. Gates,Alan Gillespie,John Heidemann,Jeffrey M. Hsu,JianHui Huang,S. Hwang,Chris Inbody,Gordon M. Jacobs,Min-Chie Jeng,
29
30Beorn Johnson,Stefan Jones,Kenneth H. Keller,Francesco Lannutti,Robert Larice,Mathew Lew,Robert Lindsell,Weidong Liu,Kartikeya Mayaram,Richard D. McRoberts,Manfred Metzger,Wolfgang Muees,Paolo Nenzi,Gary W. Ng,Hong June Park,Stefano Perticaroli,Arno Peters,Serban-Mihai Popescu,Georg Post,Thomas L. Quarles,Emmanuel Rouat,Jean-Marc Routure,Jaijeet S. Roychowdhury,Lionel Sainte Cluque,Takayasu Sakurai,Amakawa Shuhei,Kanwar Jit Singh,Bill Swartz,Hitoshi Tanaka,Steve Tell,Andrew Tuckey,Andreas Unger,Holger Vogt,Dietmar Warning,Michael Widlok,
31
XSPICEThe XSPICE simulator is based on the SPICE3 program developed by the Electronics ResearchLaboratory, Department of Electrical Engineering and Computer Sciences, University of California at Berkeley. The authors of XSPICE gratefully acknowledge UC Berkeleys developmentand distribution of this software, and their licensing policies which promote further improvements to simulation technology.We also gratefully acknowledge the participation and support of our U.S. Air Force sponsors, the Aeronautical Systems Center and the Warner Robins Air Logistics Command, withoutwhich the development of XSPICE would not have been possible.
32
Chapter 1IntroductionNgspice is a general-purpose circuit simulation program for nonlinear and linear analyses. Circuits may contain resistors, capacitors, inductors, mutual inductors, independent or dependentvoltage and current sources, loss-less and lossy transmission lines, switches, uniform distributedRC lines, and the five most common semiconductor devices: diodes, BJTs, JFETs, MESFETs,and MOSFETs.Some introductory remarks on how to use ngspice may be found in chapter 21.Ngspice is an update of Spice3f5, the last Berkeleys release of Spice3 simulator family. Ngspiceis being developed to include new features to existing Spice3f5 and to fix its bugs. Improvinga complex software like a circuit simulator is a very hard task and, while some improvementshave been made, most of the work has been done on bug fixing and code refactoring.Ngspice has built-in models for the semiconductor devices, and the user need specify only thepertinent model parameter values. There are three models for bipolar junction transistors, allbased on the integral-charge model of Gummel and Poon; however, if the Gummel-Poon parameters are not specified, the basic model (BJT) reduces to the simpler Ebers-Moll model. In eithercase and in either models, charge storage effects, ohmic resistances, and a current-dependentoutput conductance may be included. The second bipolar model BJT2 adds dc current computation in the substrate diode. The third model (VBIC) contains further enhancements foradvanced bipolar devices.The semiconductor diode model can be used for either junction diodes or Schottky barrierdiodes. There are two models for JFET: the first (JFET) is based on the model of Shichmanand Hodges, the second (JFET2) is based on the Parker-Skellern model. All the original sixMOSFET models are implemented: MOS1 is described by a square-law I-V characteristic,MOS2 [1] is an analytical model, while MOS3 [1] is a semi-empirical model; MOS6 [2] is asimple analytic model accurate in the short channel region; MOS9, is a slightly modified Level3 MOSFET model - not to confuse with Philips level 9; BSIM 1 [3, 4]; BSIM2 [5] are theold BSIM (Berkeley Short-channel IGFET Model) models. MOS2, MOS3, and BSIM includesecond-order effects such as channel-length modulation, subthreshold conduction, scatteringlimited velocity saturation, small-size effects, and charge controlled capacitances. The recentMOS models for submicron devices are the BSIM3 (Berkeley BSIM3 web page) and BSIM4(Berkeley BSIM4 web page) models. Silicon-on-insulator MOS transistors are described by theSOI models from the BSIMSOI family (Berkeley BSIMSOI web page) and the STAG [18] one.There is partial support for a couple of HFET models and one model for MESA devices.
CHAPTER 1. INTRODUCTION
Ngspice supports mixed-level simulation and provides a direct link between technology parameters and circuit performance. A mixed-level circuit and device simulator can provide greatersimulation accuracy than a stand-alone circuit or device simulator by numerically modeling thecritical devices in a circuit. Compact models can be used for noncritical devices. The mixedlevel extensions to ngspice are two: CIDER: a mixed-level circuit and device simulator integrated into ngspice code. CIDERwas originally the name of the mixed-level extension made to spice3f5. GSS: GSS (now called GENIUS) TCAD is a 2D simulator developed independently fromngspice. The device simulator itself is free and not included into ngspice, but a socketinterface is provided.Ngspice supports mixed-signal simulation through the integration of XSPICE code into it.XSPICE software, developed as an extension to Spice3C1 from GeorgiaTech, has been portedto ngspice to provide board level and mixed-signal simulation.New devices can be added to ngspice by two means: the XSPICE code-model interface and theADMS interface based on Verilog-A and XML.Finally, numerous small bugs have been discovered and fixed, and the program has been portedto a wider variety of computing platforms.
Simulation Algorithms
Computer-based circuit simulation is often used as a tool by designers, test engineers, andothers who want to analyze the operation of a design without examining the physical circuit.Simulation allows you to change quickly the parameters of many of the circuit elements todetermine how they affect the circuit response. Often it is difficult or impossible to changethese parameters in a physical circuit.However, to be practical, a simulator must execute in a reasonable amount of time. The key toefficient execution is choosing the proper level of modeling abstraction for a given problem. Tosupport a given modeling abstraction, the simulator must provide appropriate algorithms.Historically, circuit simulators have supported either an analog simulation algorithm or a digitalsimulation algorithm. Ngspice inherits the XSPICE framework and supports both analog anddigital algorithms and is a mixed-mode simulator.
Analog Simulation
Analog simulation focuses on the linear and non-linear behavior of a circuit over a continuoustime or frequency interval. The circuit response is obtained by iteratively solving KirchhoffsLaws for the circuit at time steps selected to ensure the solution has converged to a stable valueand that numerical approximations of integrations are sufficiently accurate. Since Kirchhoffslaws form a set of simultaneous equations, the simulator operates by solving a matrix of equations at each time point. This matrix processing generally results in slower simulation timeswhen compared to digital circuit simulators.
The response of a circuit is a function of the applied sources. Ngspice offers a variety ofsource types including DC, sine-wave, and pulse. In addition to specifying sources, the usermust define the type of simulation to be run. This is termed the mode of analysis. Analysismodes include DC analysis, AC analysis, and transient analysis. For DC analysis, the timevarying behavior of reactive elements is neglected and the simulator calculates the DC solutionof the circuit. Swept DC analysis may also be accomplished with ngspice. This is simply therepeated application of DC analysis over a range of DC levels for the input sources. For ACanalysis, the simulator determines the response of the circuit, including reactive elements tosmall-signal sinusoidal inputs over a range of frequencies. The simulator output in this caseincludes amplitudes and phases as a function of frequency. For transient analysis, the circuitresponse, including reactive elements, is analyzed to calculate the behavior of the circuit as afunction of time.
Digital Simulation
Digital circuit simulation differs from analog circuit simulation in several respects. A primarydifference is that a solution of Kirchhoffs laws is not required. Instead, the simulator must onlydetermine whether a change in the logic state of a node has occurred and propagate this changeto connected elements. Such a change is called an event.When an event occurs, the simulator examines only those circuit elements that are affected bythe event. As a result, matrix analysis is not required in digital simulators. By comparison,analog simulators must iteratively solve for the behavior of the entire circuit because of theforward and reverse transmission properties of analog components. This difference results ina considerable computational advantage for digital circuit simulators, which is reflected in thesignificantly greater speed of digital simulations.
Mixed-Mode Simulation
Modern circuits often contain a mix of analog and digital circuits. To simulate such circuitsefficiently and accurately a mix of analog and digital simulation techniques is required. Whenanalog simulation algorithms are combined with digital simulation algorithms, the result istermed mixed-mode simulation.Two basic methods of implementing mixed-mode simulation used in practice are the nativemode and glued mode approaches. Native mode simulators implement both an analog algorithm and a digital algorithm in the same executable. Glued mode simulators actually use twosimulators, one of which is analog and the other digital. This type of simulator must define aninput/output protocol so that the two executables can communicate with each other effectively.The communication constraints tend to reduce the speed, and sometimes the accuracy, of thecomplete simulator. On the other hand, the use of a glued mode simulator allows the componentmodels developed for the separate executables to be used without modification.Ngspice is a native mode simulator providing both analog and event-based simulation in thesame executable. The underlying algorithms of ngspice (coming from XSPICE and its CodeModel Subsystem) allow use of all the standard SPICE models, provide a pre-defined collectionof the most common analog and digital functions, and provide an extensible base on which tobuild additional models.
361.1.3.1
CHAPTER 1. INTRODUCTIONUser-Defined Nodes
Ngspice supports creation of User-Defined Node types. User-Defined Node types allow youto specify nodes that propagate data other than voltages, currents, and digital states. Like digitalnodes, User-Defined Nodes use event-driven simulation, but the state value may be an arbitrarydata type. A simple example application of User-Defined Nodes is the simulation of a digitalsignal processing filter algorithm. In this application, each node could assume a real or integervalue. More complex applications may define types that involve complex data such as digitaldata vectors or even non-electronic data.Ngspice digital simulation is actually implemented as a special case of this User-Defined Nodecapability where the digital state is defined by a data structure that holds a Boolean logic stateand a strength value.
Mixed-Level Simulation
Ngspice can simulate numerical device models for diodes and transistors in two different ways,either through the integrated DSIM simulator or interfacing to GSS TCAD system. DSIM isan internal C-based device simulator which is part of the CIDER simulator, the mixed-levelsimulator based on spice3f5. CIDER within ngspice provides circuit analyses, compact modelsfor semiconductor devices, and one- or two-dimensional numerical device models.1.1.4.1
CIDER (DSIM)
DSIM provides accurate, one- and two-dimensional numerical device models based on the solution of Poissons equation, and the electron and hole current-continuity equations. DSIMincorporates many of the same basic physical models found in the Stanford two-dimensionaldevice simulator PISCES. Input to CIDER consists of a SPICE-like description of the circuitand its compact models, and PISCES-like descriptions of the structures of numerically modeleddevices. As a result, CIDER should seem familiar to designers already accustomed to thesetwo tools. CIDER is based on the mixed-level circuit and device simulator CODECS, important in scaled-down MOSFETs and a polysilicon modelfor poly-emitter bipolar transistors. Temperature dependence has been included over the rangefrom -50C to 150C. The numerical models can be used to simulate all the basic types of semiconductor devices: resistors, MOS capacitors, diodes, BJTs, JFETs and MOSFETs. BJTs andJFETs can be modeled with or without a substrate contact. Support has been added for themanagement of device internal states. Post-processing of device states can be performed usingthe ngnutmeg user interface.1.1.4.2
GSS TCAD
GSS is a TCAD software which enables two-dimensional numerical simulation of semiconductor device with well-known drift-diffusion and hydrodynamic method. GSS has Basic DDM
(drift-diffusion method) solver, Lattice Temperature Corrected DDM solver, EBM (energy balance method) solver and Quantum corrected DDM solver which based on density-gradient theory. The GSS program is directed via input statements by a user specified disk file. Supportstriangle mesh generation and adaptive mesh refinement. Employs PMI (physical model interface) to support various materials, including compound semiconductor materials such as SiGeand AlGaAs. Supports DC sweep, transient and AC sweep calculations. The device can bestimulated by voltage or current source(s).GSS is no longer updated, but is still available as open source as a limited edition of the commercial GENIUS TCAD tool.
Supported Analyses
DC Analyses
The dc analysis portion of ngspice determines the dc operating point of the circuit with inductorsshorted and capacitors opened. The dc analysis options are specified on the .DC, .TF, and .OPcontrol lines.There is assumed to be no time dependence on any of the sources within the system description.The simulator algorithm subdivides the circuit into those portions which require the analogsimulator algorithm and those which require the event-driven algorithm. Each subsystem blockis then iterated to solution, with the interfaces between analog nodes and event-driven nodesiterated for consistency across the entire system.
Once stable values are obtained for all nodes in the system, the analysis halts and the resultsmay be displayed or printed out as you request them.A dc analysis is automatically performed prior to a transient analysis to determine the transientinitial conditions, and prior to an ac small-signal analysis to determine the linearized, smallsignal models for nonlinear devices. If requested, the dc small-signal value of a transfer function(ratio of output variable to input source), input resistance, and output resistance is also computedas a part of the dc solution. The dc analysis can also be used to generate dc transfer curves: aspecified independent voltage, current source, resistor or temperature1 is stepped over a userspecified range and the dc output variables are stored for each sequential source value.
AC Small-Signal Analysis
AC analysis is limited to analog nodes and represents the small signal, sinusoidal solution of theanalog system described at a particular frequency or set of frequencies. This analysis is similarto the DC analysis in that it represents the steady-state behavior of the described system with asingle input node at a given set of stimulus frequencies.The program first computes the dc operating point of the circuit and determines linearized,small-signal models for all of the nonlinear devices in the circuit. The resultant linear circuitis then analyzed over a user-specified range of frequencies. The desired output of an ac smallsignal analysis is usually a transfer function (voltage gain, transimpedance, etc). If the circuithas only one ac input, it is convenient to set that input to unity and zero phase, so that outputvariables have the same value as the transfer function of the output variable with respect to theinput.
Transient Analysis
Transient analysis is an extension of DC analysis to the time domain. A transient analysis begins by obtaining a DC solution to provide a point of departure for simulating time-varyingbehavior. Once the DC solution is obtained, the time-dependent aspects of the system are reintroduced, and the two simulator algorithms incrementally solve for the time varying behavior ofthe entire system. Inconsistencies in node values are resolved by the two simulation algorithmssuch that the time-dependent waveforms created by the analysis are consistent across the entiresimulated time interval. Resulting time-varying descriptions of node behavior for the specifiedtime interval are accessible to you.All sources which are not time dependent (for example, power supplies) are set to their dc value.The transient time interval is specified on a .TRAN control line.
Pole-Zero Analysis
The pole-zero analysis portion of Ngspice computes the poles and/or zeros in the small-signalac transfer function. The program first computes the dc operating point and then determinesthe linearized, small-signal models for all the nonlinear devices in the circuit. This circuit is1 Temperature
(TEMP) and resistance sweeps have been introduced in Ngspice, they were not available in theoriginal code of Spice3f5.
then used to find the poles and zeros of the transfer function. Two types of transfer functionsare allowed: one of the form (output voltage)/(input voltage) and the other of the form (outputvoltage)/(input current). These two types of transfer functions cover all the cases and one canfind the poles/zeros of functions like input/output impedance and voltage gain. The input andoutput ports are specified as two pairs of nodes. The pole-zero analysis works with resistors,capacitors, inductors, linear-controlled sources, independent sources, BJTs, MOSFETs, JFETsand diodes. Transmission lines are not supported. The method used in the analysis is a suboptimal numerical search. For large circuits it may take a considerable time or fail to find allpoles and zeros. For some circuits, the method becomes "lost" and finds an excessive numberof poles or zeros.
The distortion analysis portion of Ngspice computes steady-state harmonic and intermodulationproducts for small input signal magnitudes. If signals of a single frequency are specified as theinput to the circuit, the complex values of the second and third harmonics are determined atevery point in the circuit. If there are signals of two frequencies input to the circuit, the analysisfinds out the complex values of the circuit variables at the sum and difference of the inputfrequencies, and at the difference of the smaller frequency from the second harmonic of thelarger frequency. Distortion analysis is supported for the following nonlinear devices: Diodes (DIO), BJT, JFET (level 1), MOSFETs (levels 1, 2, 3, 9, and BSIM1), MESFET (level 1).All linear devices are automatically supported by distortion analysis. If there are switchespresent in the circuit, the analysis continues to be accurate provided the switches do not changestate under the small excitations used for distortion calculations.If a device model does not support direct small signal distortion analysis, please use the Fourierstatement and evaluate the output per scripting.
Sensitivity Analysis
Ngspice will calculate either the DC operating-point sensitivity or the AC small-signal sensitivity of an output variable with respect to all circuit variables, including model parameters.Ngspice calculates the difference in an output variable (either a node voltage or a branch current)by perturbing each parameter of each device independently. Since the method is a numericalapproximation, the results may demonstrate second order affects in highly sensitive parameters,or may fail to show very low but non-zero sensitivity. Further, since each variable is perturbby a small fraction of its value, zero-valued parameters are not analyzed (this has the benefit ofreducing what is usually a very large amount of data).
Noise Analysis
The noise analysis portion of Ngspice does analysis device-generated noise for the given circuit. When provided with an input source and an output port, the analysis calculates the noisecontributions of each device (and each noise generator within the device) to the output portvoltage. It also calculates the input noise to the circuit, equivalent to the output noise referredto the specified input source. This is done for every frequency point in a specified range - thecalculated value of the noise corresponds to the spectral density of the circuit variable viewed asa stationary Gaussian stochastic process. After calculating the spectral densities, noise analysisintegrates these values over the specified frequency range to arrive at the total noise voltage/current (over this frequency range). This calculated value corresponds to the variance of the circuitvariable viewed as a stationary Gaussian process.
Temperature, in ngspice, is a property associated to the entire circuit, rather than an analysis option. Circuit temperature has a default (nominal) value of 27C (300.15 K) that can be changedusing the TEMP option in an .option control line (see 15.1.1) or by the .TEMP line (see 2.11),which has precedence over the .option TEMP line. All analyses are, thus, performed at circuittemperature, and if you want to simulate circuit behavior at different temperatures you shouldprepare a netlist for each temperature.All input data for ngspice is assumed to have been measured at the circuit nominal temperature. This value can further be overridden for any device which models temperature effects byspecifying the TNOM parameter on the .model itself. Individual instances may further overridethe circuit temperature through the specification of TEMP and DTEMP parameters on the instance.The two options are not independent even if you can specify both on the instance line, the TEMPoption overrides DTEMP. The algorithm to compute instance temperature is described below:
41
T1IS (T1 ) = IS (T0 )T0
XT I
Eg q (T1 T0 )expk (T1 T0 )
(1.1)
where k is Boltzmanns constant, q is the electronic charge, Eg is the energy gap which is amodel parameter, and XT I is the saturation current temperature exponent (also a model parameter, and usually equal to 3).The temperature dependence of forward and reverse beta is according to the formula:
T1B (T1 ) = B (T0 )T0
XT B(1.2)
where T0 and T1 are in degrees Kelvin, and XT B is a user-supplied model parameter. Temperature effects on beta are carried out by appropriate adjustment to the values of BF , ISE , BR , andISC (spice model parameters BF, ISE, BR, and ISC, respectively).Temperature dependence of the saturation current in the junction diode model is determined by:
XT IN
Eg q (T1 T0 )expNk (T1 T0 )
(1.3)
where N is the emission coefficient, which is a model parameter, and the other symbols havethe same meaning as above. Note that for Schottky barrier diodes, the value of the saturationcurrent temperature exponent, XT I, is usually 2. Temperature appears explicitly in the value ofjunction potential, U (in Ngspice PHI), for all the device models.The temperature dependence is determined by:kTU (T ) =lnq
Na NdNi (T )2
!(1.4)
where k is Boltzmanns constant, q is the electronic charge, Na is the acceptor impurity density, Nd is the donor impurity density, Ni is the intrinsic carrier concentration, and Eg is the
energy gap. Temperature appears explicitly in the value of surface mobility, M0 (or U0 ), for theMOSFET model.The temperature dependence is determined by:M0 (T0 )M0 (T ) = 1.5
(1.5)
TT0
The effects of temperature on resistors, capacitor and inductors is modeled by the formula:hi2R (T ) = R (T0 ) 1 + TC1 (T T0 ) + TC2 (T T0 )
(1.6)
where T is the circuit temperature, T0 is the nominal temperature, and TC1 and TC2 are the firstand second order temperature coefficients.
Convergence
Ngspice uses the Newton-Raphson algorithm to solve nonlinear equations arising from circuitdescription. The NR algorithm is interactive and terminates when both of the following conditions hold:1. The nonlinear branch currents converge to within a tolerance of 0.1% or 1 picoamp (1.0e12 Amp), whichever is larger.2. The node voltages converge to within a tolerance of 0.1% or 1 microvolt (1.0e-6 Volt),whichever is larger.
The algorithm has reached convergence if the difference between the last iteration k and thecurrent one (k + 1): (k+1)(k) vn RELTOL vnmax + VNTOLvn
(1.7)
(k+1) (k) vnmax = max vn , vn
(1.8)
where
The RELTOL (RELative TOLerance) parameter, which default value is 103 , specifies how smallthe solution update must be, relative to the node voltage, to consider the solution to have converged. The VNTOL (absolute convergence) parameter, which has 1V as default becomes important when node voltages have near zero values. The relative parameter alone, in such case,would need too strict tolerances, perhaps lower than computer round-off error, and thus convergence would never be achieved. VNTOL forces the algorithm to consider as converged any nodewhose solution update is lower than its value.
1.4. CONVERGENCE
Ngspice checks the convergence on the non-linear functions that describe the non-linear branchesin circuit elements. In semiconductor devices the functions defines currents through the deviceand thus the name of the criterion.Ngspice computes the difference between the value of the nonlinear function computed for lastvoltage and the linear approximation of the same current computed with the actual voltage:\(k+1)(k)i branch ibranch RELTOL ibrmax + ABSTOL
(1.9)
whereibrmax
\(k+1) (k)= max ibranch , ibranch
(1.10)
Convergence failure
Although the algorithm used in ngspice has been found to be very reliable, in some cases it failsto converge to a solution. When this failure occurs, the program terminates the job. Failureto converge in dc analysis is usually due to an error in specifying circuit connections, elementvalues, or model parameter values. Regenerative switching circuits or circuits with positivefeedback probably will not converge in the dc analysis unless the OFF option is used for someof the devices in the feedback path, .nodeset control line is used to force the circuit to convergeto the desired state.
44
Chapter 2Circuit Description2.12.1.1
The circuit to be analyzed is described to ngspice by a set of element instance lines, whichdefine the circuit topology and element instance values, and a set of control lines, which definethe model parameters and the run controls. All lines are assembled in an input file to be read byngspice. Two lines are essential: The first line in the input file must be the title, which is the only comment line that doesnot need any special character in the first place. The last line must be .end.The order of the remaining lines is arbitrary (except, of course, that continuation lines mustimmediately follow the line being continued). This feature in the ngspice input language datesback to the punched card times where elements were written on separate cards (and cards frequently fell off). Leading white spaces in a line are ignored, as well as empty lines.
Each element in the circuit is a device instance specified by an instance line that contains: the element instance name, the circuit nodes to which the element is connected, and the values of the parameters that determine the electrical characteristics of the element.The first letter of the element instance name specifies the element type. The format for thengspice element types is given in the following manual chapters. In the rest of the manual, thestrings XXXXXXX, YYYYYYY, and ZZZZZZZ denote arbitrary alphanumeric strings.
For example, a resistor instance name must begin with the letter R and can contain one or morecharacters. Hence, R, R1, RSE, ROUT, and R3AC2ZY are valid resistor names. Details of eachtype of device are supplied in a following section 3. Table 2.1 lists the element types which areavailable in ngspice, sorted by the first letter.First letter
Element description
BCD
HIJKL
NOPQRSTUVWXYZ
Comments, links12analog (12.2)digital (12.4)mixed signal (12.3)5.13.2.57linear (4.2.2),non-linear (5.2)linear (4.2.3)linear (4.2.1),non-linear (5.3)linear (4.2.4)4.193.2.113.2.911BSIM3 (11.2.9)BSIM4 (11.2.10)14.26.26.4.283.2.13.2.146.16.34.13.2.142.4.36.4.110
Fields on a line are separated by one or more blanks, a comma, an equal (=) sign, or a left orright parenthesis; extra spaces are ignored. A line may be continued by entering a + (plus) incolumn 1 of the following line; ngspice continues reading beginning with column 2. A name
47
field must begin with a letter (A through Z) and cannot contain any delimiters. A number fieldmay be an integer field (12, -44), a floating point field (3.14159), either an integer or floatingpoint number followed by an integer exponent (1e-14, 2.65e3), or either an integer or a floatingpoint number followed by one of the following scale factors:
SuffixTGMegKmilmunpf
NameTeraGigaMegaKiloMilmillimicronanopicofemto
Factor101210910610325.4 10610310610910121015
Letters immediately following a number that are not scale factors are ignored, and letters immediately following a scale factor are ignored. Hence, 10, 10V, 10Volts, and 10Hz all representthe same number, and M, MA, MSec, and MMhos all represent the same scale factor. Note that1000, 1000.0, 1000Hz, 1e3, 1.0e3, 1kHz, and 1k all represent the same number. Note that M orm denote milli, i.e. 103 . Suffix meg has to be used for 106 .Nodes names may be arbitrary character strings and are case insensitive. The ground nodemust be named 0 (zero). For compatibility reason gnd is accepted as ground node, andwill internally be treated as a global node and be converted to 0. Each circuit has to have aground node (gnd or 0)! Note the difference in ngspice where the nodes are treated as characterstrings and not evaluated as numbers, thus 0 and 00 are distinct nodes in ngspice but not inSPICE2.Ngspice requires that the following topological constraints are satisfied:
The circuit cannot contain a loop of voltage sources and/or inductors and cannot containa cut-set of current sources and/or capacitors.
Every node must have at least two connections except for transmission line nodes (topermit unterminated transmission lines) and MOSFET substrate nodes (which have twointernal connections anyway).
2.2
Basic lines
.TITLE line
Examples:POWER AMPLIFIER CIRCUIT* additional lines following*...T e s t o f CAM c e l l* additional lines following*...The title line must be the first in the input file. Its contents are printed verbatim as the headingfor each section of output.As an alternative you may place a .TITLE <any title> line anywhere in your input deck.The first line of your input deck will be overridden by the contents of this line following the.TITLE statement..TITLE line example:******************************* additional lines following*.... TITLE T e s t o f CAM c e l l* additional lines following*...will internally be replaced byInternal input deck:T e s t o f CAM* additional*...* TITLE T e s t* additional*...
celllines followingo f CAM c e l llines following
.END Line
Examples:. endThe ".End" line must always be the last in the input file. Note that the period is an integral partof the name.
General Form:* < any comment >Examples:* RF=1K Gain s h o u l d be 100* Check openl o o p g a i n and p h a s e m a r g i nThe asterisk in the first column indicates that this line is a comment line. Comment lines maybe placed anywhere in the circuit description.
End-of-line comments
General Form:< any command> ; < any comment >< any command> $ < any comment >Examples:RF2=1K ; Gain s h o u l d be 100C1=10 p $ Check openl o o p g a i n and p h a s e m a r g i n. param n1 =1 / / new v a l u engspice supports comments that begin with single characters ; or double characters $ (dollarplus space) or //. For readability you should precede each comment character with a space.ngspice will accept the single character $, but only outside of a .control section.
General form:. model mname t y p e ( pname1= p v a l 1 pname2= p v a l 2 . . . )Examples:. model MOD1 npn ( b f =50 i s =1e 13 v b f = 50 )Most simple circuit elements typically require only a few parameter values. However, some devices (semiconductor devices in particular) that are included in ngspice require many parametervalues. Often, many devices in a circuit are defined by the same set of device model parameters.For these reasons, a set of device model parameters is defined on a separate .model line andassigned a unique model name. The device element lines in ngspice then refer to the modelname.For these more complex device types, each device element line contains the device name, thenodes to which the device is connected, and the device model name. In addition, other optionalparameters may be specified for some devices: geometric factors and an initial condition (seethe following section on Transistors (8 to 11) and Diodes (7) for more details). mname in theabove is the model name, and type is one of the following fifteen types:
Model TypeSemiconductor resistor modelSemiconductor capacitor modelInductor modelVoltage controlled switchCurrent controlled switchUniform distributed RC modelLossy transmission line modelDiode modelNPN BJT modelPNP BJT modelN-channel JFET modelP-channel JFET modelN-channel MOSFET modelP-channel MOSFET modelN-channel MESFET modelP-channel MESFET model
Parameter values are defined by appending the parameter name followed by an equal sign andthe parameter value. Model parameters that are not given a value are assigned the default valuesgiven below for each model type. Models are listed in the section on each device along withthe description of device element lines. Model parameters and their default values are given inchapter 31.
.SUBCKT Subcircuits
A subcircuit that consists of ngspice elements can be defined and referenced in a fashion similarto device models. Subcircuits are the way ngspice implements hierarchical modeling, but this isnot entirely true because each subcircuit instance is flattened during parsing, and thus ngspiceis not a hierarchical simulator.The subcircuit is defined in the input deck by a grouping of element cards delimited by the.subckt and the .ends cards (or the keywords defined by the substart and subend options(see 17.7)); the program then automatically inserts the defined group of elements wherever thesubcircuit is referenced. Instances of subcircuits within a larger circuit are defined through theuse of an instance card which begins with the letter X. A complete example of all three ofthese cards follows:
Example:* The following is the instance card :*xdiv1 10 7 0 vdivide* The following are the subcircuit definition cards :*. subckt vdivide 1 2 3r1 1 2 10 Kr2 2 3 5 K. ends
.SUBCKT Line
General form:. SUBCKT subnam N1 <N2 N3 . . . >Examples:. SUBCKT OPAMP 1 2 3 4A circuit definition is begun with a .SUBCKT line. SUBNAM is the subcircuit name, and N1, N2,... are the external nodes, which cannot be zero. The group of element lines which immediatelyfollow the .SUBCKT line define the subcircuit. The last line in a subcircuit definition is the.ENDS line (see below). Control lines may not appear within a subcircuit definition; however,subcircuit definitions may contain anything else, including other subcircuit definitions, devicemodels, and subcircuit calls (see below). Note that any device models or subcircuit definitionsincluded as part of a subcircuit definition are strictly local (i.e., such models and definitionsare not known outside the subcircuit definition). Also, any element nodes not included on the.SUBCKT line are strictly local, with the exception of 0 (ground) which is always global. If youuse parameters, the .SUBCKT line will be extended (see 2.8.3).
.ENDS Line
General form:. ENDS <SUBNAM>Examples:. ENDS OPAMPThe .ENDS line must be the last one for any subcircuit definition. The subcircuit name, ifincluded, indicates which subcircuit definition is being terminated; if omitted, all subcircuitsbeing defined are terminated. The name is needed only when nested subcircuit definitions arebeing made.
Subcircuit Calls
General form:XYYYYYYY N1 <N2 N3 . . . > SUBNAMExamples:X1 2 4 17 3 1 MULTISubcircuits are used in ngspice by specifying pseudo-elements beginning with the letter X,followed by the circuit nodes to be used in expanding the subcircuit. If you use parameters, thesubcircuit call will be modified (see 2.8.3).
.GLOBAL
General form:. GLOBAL nodenameExamples:. GLOBAL gnd v c cNodes defined in the .GLOBAL statement are available to all circuit and subcircuit blocks independently from any circuit hierarchy. After parsing the circuit, these nodes are accessible fromtop level.
.INCLUDE
General form:. INCLUDE f i l e n a m eExamples:. INCLUDE / u s e r s / s p i c e / common / bsim3param . mod
2.7. .LIB
Frequently, portions of circuit descriptions will be reused in several input files, particularly withcommon models and subcircuits. In any ngspice input file, the .INCLUDE line may be used tocopy some other file as if that second file appeared in place of the .INCLUDE line in the originalfile.There is no restriction on the file name imposed by ngspice beyond those imposed by the localoperating system.
.LIB
General form:. LIB f i l e n a m e l i b n a m eExamples:. LIB / u s e r s / s p i c e / common / m o s f e t s . l i b mos1The .LIB statement allows to include library descriptions into the input file. Inside the *.libfile a library libname will be selected. The statements of each library inside the *.lib file areenclosed in .LIB libname <...> .ENDL statements.If the compatibility mode (16.13) is set to ps by set ngbehavior=ps (17.7) in spinit (16.5)or .spiceinit (16.6), then a simplified syntax .LIB filename is available: a warning is issuedand filename is simply included as described in chapt. 2.6.
Ngspice allows for the definition of parametric attributes in the netlists. This is an enhancementof the ngspice front-end which adds arithmetic functionality to the circuit description language.
.param line
General form:. param < i d e n t > = < e x p r >
Examples:. param. param. param. param. param
p i p p o =5po =6 pp = 7 . 8 pap ={AGAUSS( p i p p o , 1 , 1 . 6 7 ) }p i p p p ={ p i p p o + pp }p ={ pp }pop = pp+p
This line assigns numerical values to identifiers. More than one assignment per line is possibleusing a space as separator. Parameter identifier names must begin with an alphabetic character.The other characters must be either alphabetic, a number, or ! # $ % [ ] _ as special characters. The variables time, temper, and hertz (see 5.1.1) are no valid identifier names. Otherrestrictions on naming conventions apply as well, see 2.8.6.
The .param lines inside subcircuits are copied per call, like any other line. All assignments areexecuted sequentially through the expanded circuit. Before its first use, a parameter name musthave been assigned a value. Expression defining a parameter have to be put into braces {p+p2},alternatively into single quotes AGAUSS(pippo, 1, 1.67).
General form:{ <expr > }Examples:These are allowed in .model lines and in device lines. A spice number is a floating pointnumber with an optional scaling suffix, immediately glued to the numeric tokens (see chapt.2.8.5). Brace expressions ({..}) cannot be used to parametrize node names or parts of names.All identifiers used within an <expr> must have known values at the time when the line isevaluated, else an error is flagged.
Subcircuit parameters
General form:. s u b c k t < i d e n t n > node node . . .
Examples:. s u b c k t m y f i l t e r i n o u t r v a l =100 k c v a l =100 nF<identn> is the name of the subcircuit given by the user. node is an integer number or anidentifier, for one of the external nodes. The first <ident>=<value> introduces an optionalsection of the line. Each <ident> is a formal parameter, and each <value> is either a spicenumber or a brace expression. Inside the .subckt ... .ends context, each formal parametermay be used like any identifier that was defined on a .param control line. The <value> partsare supposed to be default values of the parameters. However, in the current version of , theyare not used and each invocation of the subcircuit must supply the _exact_ number of actualparameters.The syntax of a subcircuit call (invocation) is:General form:X<name> node node . . . < i d e n t n > < i d e n t >=< v a l u e > < i d e n t >=< v a l u e > . . .Examples:X1 i n p u t o u t p u t m y f i l t e r r v a l =1k c v a l =1nHere <name> is the symbolic name given to that instance of the subcircuit, <identn> is thename of a subcircuit defined beforehand. node node ... is the list of actual nodes where thesubcircuit is connected. <value> is either a spice number or a brace expression { <expr> } .The sequence of <value> items on the X line must exactly match the number and the order offormal parameters of the subcircuit.
Symbol scope
All subcircuit and model names are considered global and must be unique. The .param symbolsthat are defined outside of any .subckt ... .ends section are global. Inside such a section,the pertaining params: symbols and any .param assignments are considered local: theymask any global identical names, until the .ends line is encountered. You cannot reassign to aglobal number inside a .subckt, a local copy is created instead. Scope nesting works up to alevel of 10. For example, if the main circuit calls A which has a formal parameter xx, A callsB which has a param. xx, and B calls C which also has a formal param. xx, there will be threeversions of xx in the symbol table but only the most local one - belonging to C - is visible.A word of caution: Ngspice allows to define circuits with nested subcircuits. Currently it isnot possible however to issue .param statements inside of a .subckt ... .ends section, when thereare additional, nested .subckt ... .ends in the same section. This is a bug, which will be removedasap.
Syntax of expressions
56
of the C language. For equal precedence binary ops, evaluation goes left to right. Functionsoperate on real values only!
Operatornot***/moddiv+==<><=>=<>andor
Alias!^
%\
!=
&&||
Precedence11233334455555567
Descriptionunary unary notpower, like pwrmultiplydividemodulointeger divideaddsubtractequalitynon-equalless or equalgreater or equalless thangreater thanandor
The result of logical operators is 1 or 0 , for True or False. An example input file is shownbelow:
unif(nom, rvar)aunif(nom, avar)limit(nom, avar)
57
Notesreturns 1 if symbol is defined, else 0y=x*xy = sqrt(x)
value1e91e61e31e-31e-61e-91e-121e-15
Note: there are intentional redundancies in expression syntax, e.g. x^y , x**y and pwr(x,y) allhave nearly the same result.
In addition to the above function names and to the verbose operators ( not and or div mod ),other words are reserved and cannot be used as parameter names: and, or, not, div, mod, defined,sqr, sqrt, sin, cos, exp, ln, arctan, abs, pwr, time, temper, hertz.
Alternative syntax
The & sign is tolerated to provide some historical parameter notation: & as the first characterof a line is equivalent to: .param.Inside a line, the notation &(....) is equivalent to {....}, and &identifier means the samething as {identifier} .Comments in the style of C++ line trailers (//) are detected and erased.Warning: this is NOT possible in embedded .control parts of a source file, these lines are outsideof this scope.Now, there is some possible confusion in ngspice because of multiple numerical expressionfeatures. The .param lines and the braces expressions (see next chapter 2.9) are evaluated inthe front-end, that is, just after the subcircuit expansion. (Technically, the X lines are kept ascomments in the expanded circuit so that the actual parameters can correctly be substituted).So, after the netlist expansion and before the internal data setup, all number attributes in thecircuit are known constants. However, there are some circuit elements in Spice which acceptarithmetic expressions that are NOT evaluated at this point, but only later during circuit analysis.These are the arbitrary current and voltage sources (B-sources, 5), as well as E- and G-sourcesand R-, L-, or C-devices. The syntactic difference is that "compile-time" expressions are withinbraces, but "run-time" expressions have no braces. To make things more complicated, the backend ngspice scripting language also accepts arithmetic/logic expressions that operate on its ownscalar or vector data sets (17.2). Please see also chapt. 2.13.It would be desirable to have the same expression syntax, operator and function set, and precedence rules, for the three contexts mentioned above. In the current Numparam implementation,that goal is not yet achieved...
.FUNC
With this line a function may be defined. The syntax of its expression is equivalent to theexpression syntax from the .param line (2.8.5).General form:. func < i d e n t > { <expr > }Examples:. f u n c i c o s ( x ) { c o s ( x ) 1}. func f ( x , y ) {x*y}.func will initiate a replacement operation. After reading the input files, and before parametersare evaluated, all occurrences of the icos(x) function will be replaced by cos(x)-1. All
2.10. .CSPARAM
occurrences of f(x,y) will be replaced by x*y. Function statements may be nested to a depthof t.b.d..
2.10
.CSPARAM
Create a constant vector (see 17.8.2) from a parameter in plot (17.3) const.General form:. csparam < i d e n t > = <expr >Examples:. param p i p p o =5. param pp =6. c s p a r a m p i p p p ={ p i p p o + pp }. param p ={ pp }. c s p a r a m pap = pp+p In the example shown, vectors pippp, and pap are added to the constants, which already residein plot const, with length one and real values. These vectors are generated during circuitparsing and thus cannot be changed later (same as with ordinary parameters). They may beused in ngspice scripts and .control sections (see chapt. 17).The use of .csparam is still experimental and has to be tested. A simple usage is shown below.
* test csparam.param TEMPS = 27.csparam newt = {3*TEMPS}.csparam mytemp = 2 + TEMPS.controlecho $&newt $&mytemp.endc.end
2.11
.TEMP
2.12
General form:. i f ( boolean expression ).... e l s e i f ( boolean expression ).... endifExample 1:* d e v i c e i n s t a n c e i n IFELSE b l o c k. param ok =0 ok2 =1v1 1 0 1R1 1 0 2. i f ( ok && ok2 )R11 1 0 2. elseR11 1 0 0 . 5; < s e l e c t e d. endifExample 2:* . model i n IFELSE b l o c k. param m0=0 m1=1M1 1 2 3 4 N1 W=1 L = 0 . 5. i f ( m0==1). model N1 NMOS l e v e l =49 V e r s i o n = 3 . 1. e l s e i f ( m1==1). model N1 NMOS l e v e l =49 V e r s i o n = 3 . 2 . 4. else. model N1 NMOS l e v e l =49 V e r s i o n = 3 . 3 . 0. endif
; < s e l e c t e d
For now this is a very restricted version of an IF-ELSE block, so several netlist components arecurrently not supported within the IF-ELSE block: .SUBCKT, .INC, .LIB, .PARAM. Nestingof IF-ELSE blocks is not possible. Only one .elseif is allowed per block.
2.13
In ngspice there are several ways to describe functional dependencies. In fact there are threeindependent function parsers, being active before, during, and after the simulation. So it mightbe due to have a few words on their interdependence.
2.13.1
Parameters
Parameters (chapt. 2.8.1) and functions, either defined within the .param statement or withthe .func statement (chapt. 2.9) are evaluated before any simulation is started, that is duringthe setup of the input and the circuit. Therefore these statements may not contain any simulation output (voltage or current vectors), because it is simply not yet available. The syntax isdescribed in chapt. 2.8.5. During the circuit setup all functions are evaluated, all parameters arereplaced by their resulting numerical values. Thus it will not be possible to get feedback froma later stage (during or after simulation) to change any of the parameters.
2.13.2
Nonlinear sources
During the simulation, the B source (chapt. 5) and their associated E and G sources, as wellas some devices (R, C, L) may contain expressions. These expressions may contain parametersfrom above (evaluated immediately upon ngspice start up), numerical data, predefined functions, but also node voltages and branch currents which are resulting from the simulation. Thesource or device values are continuously updated during the simulation. Therefore the sourcesare powerful tools to define non-linear behavior, you may even create new devices by yourself.Unfortunately the expression syntax (see chapt. 5.1) and the predefined functions may deviatefrom the ones for parameters listed in 2.8.1.
2.13.3
Commands, as described in detail in chapt. 17.5, may be used interactively, but also as a command script enclosed in .control ... .endc lines. The scripts may contain expressions(see chapt. 17.2). The expressions may work upon simulation output vectors (of node voltages, branch currents), as well as upon predefined or user defined vectors and variables, and areinvoked after the simulation. Parameters from 2.8.1 defined by the .param statement are notallowed in these expressions. However you may define such parameters with .csparam (2.10).Again the expression syntax (see chapt. 17.2) will deviate from the one for parameters or Bsources listed in 2.8.1 and 5.1.If you want to use parameters from 2.8.1 inside your control script, you may use .csparam(2.10) or apply a trick by defining a voltage source with the parameter as its value, and thenhave it available as a vector (e.g. after a transient simulation) with a then constant output (theparameter). A feedback from here back into parameters (2.13.1) is never possible. Also youcannot access non-linear sources of the preceding simulation. However you may start a firstsimulation inside your control script, then evaluate its output using expressions, change someof the element or model parameters with the alter and altermod statements (see chapt. 17.5.3)and then automatically start a new simulation.
62
Expressions and scripting are powerful tools within ngspice, and we will enhance the examplesgiven in chapt. 21 continuously to describe these features.
Chapter 3Circuit Elements and ModelsData fields that are enclosed in less-than and greater-than signs (< >) are optional. All indicated punctuation (parentheses, equal signs, etc.) is optional but indicate the presence of anydelimiter. Further, future implementations may require the punctuation as stated. A consistent style adhering to the punctuation shown here makes the input easier to understand. Withrespect to branch voltages and currents, ngspice uniformly uses the associated reference convention (current flows in the direction of voltage drop).
3.13.1.1
If you need to simulate more devices of the same kind in parallel, you can use the m (oftencalled parallel multiplier) option which is available for all instances except transmission linesand sources (both independent and controlled). The parallel multiplier is implemented by multiplying the value of m the elements matrix stamp, thus it cannot be used to accurately simulatelarger devices in integrated circuits. The netlist below show how to correctly use the parallelmultiplier:Multiple device example:d1 2 0 mydiode m=10d01 1 0 mydioded02 1 0 mydioded03 1 0 mydioded04 1 0 mydioded05 1 0 mydioded06 1 0 mydioded07 1 0 mydioded08 1 0 mydioded09 1 0 mydioded10 1 0 mydiode...The d1 instance connected between nodes 2 and 0 is equivalent to the parallel d01-d10 connected between 1 and 0.
Technology scaling
Model binning
Binning is a kind of range partitioning for geometry dependent models like MOSFETs. Thepurpose is to cover larger geometry ranges (Width and Length) with higher accuracy then themodel built-in geometry formulas. Each size range described by the additional model parameters LMIN, LMAX, WMIN and WMAX has its own model parameter set. These model cardsare defined by a number extension, like nch.1. NGSPICE has a algorithm to choose the rightmodel card by the requested W and L.This is implemented for BSIM3 (11.2.9) and BSIM4 (11.2.10) models.
3.1.4
The area factor m (often called parallel multiplier) used on the diode, BJT, JFET, and MESFET devices determines the number of equivalent parallel devices of a specified model. Theaffected parameters are marked with an asterisk under the heading area in the model descriptions (see the various chapters on models below). Several geometric factors associated with thechannel and the drain and source diffusions can be specified on the MOSFET device line.Two different forms of initial conditions may be specified for some devices. The first formis included to improve the dc convergence for circuits that contain more than one stable state.If a device is specified OFF, the dc operating point is determined with the terminal voltagesfor that device set to zero. After convergence is obtained, the program continues to iterate toobtain the exact value for the terminal voltages. If a circuit has more than one dc stable state,the OFF option can be used to force the solution to correspond to a desired state. If a deviceis specified OFF when in reality the device is conducting, the program still obtains the correctsolution (assuming the solutions converge) but more iterations are required since the programmust independently converge to two separate solutions.The .NODESET control line (see chapt. 15.2.1) serves a similar purpose as the OFF option. The.NODESET option is easier to apply and is the preferred means to aid convergence. The secondform of initial conditions are specified for use with the transient analysis. These are true initialconditions as opposed to the convergence aids above. See the description of the .IC controlline (chapt. 15.2.2) and the .TRAN control line (chapt. 15.3.9) for a detailed explanation ofinitial conditions.
3.2
Elementary Devices
Resistors
General form:RXXXXXXX n+ n v a l u e < a c = v a l > <m= v a l > < s c a l e = v a l > <temp= v a l >+ <dtemp = v a l > < t c 1 = v a l > < t c 2 = v a l > < n o i s y =0|1 >Examples:R1 1 2RC1 12R2 5 7RL 1 4
10017 1K1K a c =2K2K m=2
Ngspice has a fairly complex model for resistors. It can simulate both discrete and semiconductor resistors. Semiconductor resistors in ngspice means: resistors described by geometricalparameters. So, do not expect detailed modeling of semiconductor effects.n+ and n- are the two element nodes, value is the resistance (in ohms) and may be positive ornegative1 but not zero.Simulating small valued resistors: If you need to simulate very small resistors (0.001 Ohm or less), you should use CCVS (transresistance), it is lessefficient but improves overall numerical accuracy. Think about that a smallresistance is a large conductance.Ngspice can assign a resistor instance a different value for AC analysis, specified using the ackeyword. This value must not be zero as described above. The AC resistance is used in ACanalysis only (not Pole-Zero nor noise). If you do not specify the ac parameter, it is defaultedto value. If you want to simulate temperature dependence of a resistor, you need to specify itstemperature coefficients, using a .model line, like in the example below:Example:RE1 1 2 800 n e w r e s dtemp =5.MODEL n e w r e s R t c 1 = 0 . 0 0 1The temperature coefficients tc1 and tc2 describe a quadratic temperature dependence (seeequation17.12) of the resistance. If given in the instance line (the R... line) their values willoverride the tc1 and tc2 of the .model line (3.2.3). Instance temperature is useful even ifresistance does not vary with it, since the thermal noise generated by a resistor depends on itsabsolute temperature. Resistors in ngspice generates two different noises: thermal and flicker.While thermal noise is always generated in the resistor, to add a flicker noise2 source you haveto add a .model card defining the flicker noise parameters. It is possible to simulate resistorsthat do not generate any kind of noise using the noisy keyword and assigning zero to it, as inthe following example:Example:Rmd 134 57 1 . 5 k n o i s y =01A
negative resistor modeling an active element can cause convergence problems, please avoid it.noise can be used to model carbon resistors.
2 Flicker
VALUEscalemacscalem
(3.1)
If you are interested in temperature effects or noise equations, read the next section on semiconductor resistors.
Semiconductor Resistors
General form:RXXXXXXX n+ n < v a l u e > <mname> < l = l e n g t h > <w= w i d t h > <temp= v a l >+ <dtemp = v a l > <m= v a l > < a c = v a l > < s c a l e = v a l > < n o i s y = 0 | 1 >Examples:RLOAD 2 10 10KRMOD 3 7 RMODEL L=10 u W=1uThis is the more general form of the resistor presented before (3.2.1) and allows the modeling oftemperature effects and for the calculation of the actual resistance value from strictly geometricinformation and the specifications of the process. If value is specified, it overrides the geometric information and defines the resistance. If mname is specified, then the resistance may becalculated from the process information in the model mname and the given length and width.If value is not specified, then mname and length must be specified. If width is not specified,then it is taken from the default width given in the model.The (optional) temp value is the temperature at which this device is to operate, and overridesthe temperature specification on the .option control line and the value specified in dtemp.
The resistor model consists of process-related device data that allow the resistance to be calculated from geometric information and to be corrected for temperature. The parameters availableare:NameParameterUnits Default Example/CTC1first order temperature coeff.0.0
TC2second order temperature coeff./C0.0/RSHsheet resistance50DEFWdefault widthm1e-62e-6NARROWnarrowing due to side etchingm0.01e-7SHORTshortening due to side etchingm0.01e-7
TNOMparameter measurement temperatureC2750KFflicker noise coefficient0.01e-25AFflicker noise exponent0.01.0R (RES) default value if element value not givenW1000The sheet resistance is used with the narrowing parameter and l and w from the resistor deviceto determine the nominal resistance by the formula:
67
Rnom = rsh
l SHORTw NARROW
(3.2)
DEFW is used to supply a default value for w if one is not specified for the device. If either rshor l is not specified, then the standard default resistance value of 1 mOhm is used. TNOM is usedto override the circuit-wide value given on the .options control line where the parametersof this model have been measured at a different temperature. After the nominal resistance iscalculated, it is adjusted for temperature by the formula:
R(T ) = R(TNOM) 1 + TC1 (T TNOM) + TC2 (T TNOM)2
(3.3)
where R(TNOM) = Rnom |Racnom . In the above formula, T represents the instance temperature, which can be explicitly set using the temp keyword or calculated using the circuit temperature and dtemp, if present. If both temp and dtemp are specified, the latter is ignored.Ngspice improves spices resistors noise model, adding flicker noise (1/ f ) to it and the noisykeyword to simulate noiseless resistors. The thermal noise in resistors is modeled according tothe equation:
4kTfi2R =R
(3.4)
where "k" is the Boltzmanns constant, and "T " the instance temperature.Flicker noise model is:
i2Rf n =
KFIRAFff
(3.5)
A small list of sheet resistances (in /) for conductors is shown below. The table representstypical values for MOS processes in the 0.5 - 1 umrange. The table is taken from: N. Weste, K. Eshraghian - Principles of CMOS VLSI Design2nd Edition, Addison Wesley.MaterialInter-metal (metal1 - metal2)Top-metal (metal3)Polysilicon (poly)SilicideDiffusion (n+, p+)Silicided diffusionn-well
Min.0.0050.0031521021000
Typ.0.0070.0042032542000
Max.0.10.05306100105000
General form:RXXXXXXX n+ n R = e x p r e s s i o n < t c 1 = v a l u e > < t c 2 = v a l u e >RXXXXXXX n+ n e x p r e s s i o n < t c 1 = v a l u e > < t c 2 = v a l u e >Examples:R1 r r 0 r = V( r r ) < { Vt } ? {R0} : {2 * R0 } t c 1 =2e 03 t c 2 = 3 . 3 e 06R2 r 2 r r r = {5 k + 50 *TEMPER).An example file is given below.Example input file for non-linear resistor:Nonl i n e a r r e s i s t o r. param R0=1k Vi =1 Vt = 0 . 5* r e s i s t o r d e p e n d i n g on c o n t r o l v o l t a g e V( r r )R1 r r 0 r = V( r r ) < { Vt } ? {R0} : {2 * R0 } * control voltageV1 r r 0 PWL( 0 0 100 u { Vi } ). controlset noaskquitt r a n 100 n 100 u u i cp l o t i ( V1 ). endc. end
Capacitors
General form:CXXXXXXX n+ n < v a l u e > <mname> <m= v a l > < s c a l e = v a l > <temp= v a l >+ <dtemp = v a l > < t c 1 = v a l > < t c 2 = v a l > < i c = i n i t _ c o n d i t i o n >Examples:CBYP 13 0 1UFCOSC 17 23 10U IC =3VNgspice provides a detailed model for capacitors. Capacitors in the netlist can be specifiedgiving their capacitance or their geometrical and physical characteristics. Following the originalSPICE3 "convention", capacitors specified by their geometrical or physical characteristics arecalled "semiconductor capacitors" and are described in the next section.In this first form n+ and n- are the positive and negative element nodes, respectively and valueis the capacitance in Farads.Capacitance can be specified in the instance line as in the examples above or in a .model line,as in the example below:
C1 15 5 c s t dC2 2 7 c s t d. model c s t d C c a p =3nBoth capacitors have a capacitance of 3nF.If you want to simulate temperature dependence of a capacitor, you need to specify its temperature coefficients, using a .model line, like in the example below:CEB 1 2 1u c a p 1 dtemp =5.MODEL c a p 1 C t c 1 = 0 . 0 0 1The (optional) initial condition is the initial (time zero) value of capacitor voltage (in Volts).Note that the initial conditions (if any) apply only if the uic option is specified on the .trancontrol line.Ngspice calculates the nominal capacitance as described below:Cnom = value scale m
(3.6)
The temperature coefficients tc1 and tc2 describe a quadratic temperature dependence (seeequation17.12) of the capacitance. If given in the instance line (the C... line) their values willoverride the tc1 and tc2 of the .model line (3.2.7).
Semiconductor Capacitors
General form:CXXXXXXX n+ n < v a l u e > <mname> < l = l e n g t h > <w= w i d t h > <m= v a l >+ < s c a l e = v a l > <temp= v a l > <dtemp = v a l > < i c = i n i t _ c o n d i t i o n >Examples:CLOAD 2 10 10PCMOD 3 7 CMODEL L=10 u W=1uThis is the more general form of the Capacitor presented in section (3.2.5), and allows for thecalculation of the actual capacitance value from strictly geometric information and the specifications of the process. If value is specified, it defines the capacitance and both process andgeometrical information are discarded. If value is not specified, the capacitance is calculatedfrom information contained model mname and the given length and width (l, w keywords, respectively).It is possible to specify mname only, without geometrical dimensions and set the capacitance inthe .model line (3.2.5).
The capacitor model contains process information that may be used to compute the capacitancefrom strictly geometric information.
70
NameCAPCJCJSWDEFWDEFLNARROWSHORTTC1TC2TNOMDITHICK
Parametermodel capacitancejunction bottom capacitancejunction sidewall capacitancedefault device widthdefault device lengthnarrowing due to side etchingshortening due to side etchingfirst order temperature coeff.second order temperature coeff.parameter measurement temperaturerelative dielectric constantinsulator thickness
UnitsFF/m2F/mmmmmF/CF/C2CF/mm
Default0.01e-60.00.00.00.00.0270.0
Example1e-65e-52e-112e-61e-61e-71e-70.0010.00015011e-9
(3.7)
(3.8)
If neither value nor CAP are specified, then geometrical and physical parameters are take intoaccount:
(3.9)
CJ can be explicitly given on the .model line or calculated by physical parameters. When CJ isnot given, is calculated as:If THICK is not zero:CJ =CJ =
DI0THICKSiO2THICK
if DI is specified,otherwise.
(3.10)
If the relative dielectric constant is not specified the one for SiO2 is used. The values of theFFconstants are: 0 = 8.854214871e 12 mand SiO2 = 3.4531479969e 11 m. The nominalcapacitance is then computed as:Cnom = C0 scale m
(3.11)
After the nominal capacitance is calculated, it is adjusted for temperature by the formula:C(T ) = C(TNOM) 1 + TC1 (T TNOM) + TC2 (T TNOM)2
(3.12)
General form:CXXXXXXX n+ n C = e x p r e s s i o n < t c 1 = v a l u e > < t c 2 = v a l u e >CXXXXXXX n+ n e x p r e s s i o n < t c 1 = v a l u e > < t c 2 = v a l u e >Examples:C1 c c 0 c = V( c c ) < { Vt } ? {C1} : {Ch } t c 1 =1e 03 t c 2 = 1 . 3 e 05Expression).Example input file:Behavioral Capacitor. param Cl =5n Ch=1n Vt =1m I l =100 n. i c v ( cc ) = 0v ( cc2 ) = 0* c a p a c i t o r d e p e n d i n g on c o n t r o l v o l t a g e V( c c )C1 c c 0 c = V( c c ) < { Vt } ? { Cl } : {Ch } * C1 c c 0 c ={Ch}I1 0 1 { I l }Exxx n1copy n2 n2 c c 2 1Cxxx n1copy n2 1Bxxx c c 2 n2 I = (V( c c 2 ) < { Vt } ? { Cl } : {Ch } ) * i ( Exxx )I 2 n2 22 { I l }vn2 n2 0 DC 0* m e a s u r e c h a r g e by i n t e g r a t i n g c u r r e n ta i n t 1 %i d ( 1 c c ) 2 t i m e _ c o u n ta i n t 2 %i d ( 2 2 c c 2 ) 3 t i m e _ c o u n t. model t i m e _ c o u n t i n t ( i n _ o f f s e t = 0 . 0 g a i n = 1 . 0+ o u t _ l o w e r _ l i m i t =1e12 o u t _ u p p e r _ l i m i t =1 e12+ l i m i t _ r a n g e =1e9 o u t _ i c = 0 . 0 ). controlset noaskquitt r a n 100 n 100 uplot v (2)p l o t v ( cc ) v ( cc2 ). endc. end
Inductors
General form:LYYYYYYY n+ n < v a l u e > <mname> < n t = v a l > <m= v a l > < s c a l e = v a l > <temp= v a l >+ <dtemp = v a l > < t c 1 = v a l > < t c 2 = v a l > <m= v a l > < i c = i n i t _ c o n d i t i o n >Examples:LLINK 42 69 1UHLSHUNT 23 51 10U IC = 1 5 . 7MAThe inductor device implemented into ngspice has many enhancements over the original one.n+and n- are the positive and negative element nodes, respectively. value is the inductance inHenry. Inductance can be specified in the instance line as in the examples above or in a .modelline, as in the example below:
L1 15 5 indmod1L2 2 7 indmod1. model indmod1 L i n d =3nBoth inductors have an inductance of 3nH.The nt is used in conjunction with a .model line, and is used to specify the number of turnsof the inductor. If you want to simulate temperature dependence of an inductor, you need tospecify its temperature coefficients, using a .model line, like in the example below:
L l o a d 1 2 1u i n d 1 dtemp =5.MODEL i n d 1 L t c 1 = 0 . 0 0 1The (optional) initial condition is the initial (time zero) value of inductor current (in Amps) thatflows from n+, through the inductor, to n-. Note that the initial conditions (if any) apply only ifthe UIC option is specified on the .tran analysis line.Ngspice calculates the nominal inductance as described below:
Lnom =
3.2.10
value scalem
(3.13)
Inductor model
The inductor model contains physical and geometrical information that may be used to computethe inductance of some common topologies like solenoids and toroids, wound in air or othermaterial with constant magnetic permeability.
Parametermodel inductancecross sectionlengthfirst order temperature coeff.second order temperature coeff.parameter measurement temperaturenumber of turnsrelative magnetic permeability
UnitsHm2mH/CH/C2CH/m
Default0.00.00.00.00.0270.00.0
Example1e-31e-31e-20.0010.00015010-
(3.14)
IND scalem
(3.15)
If neither value nor IND are specified, then geometrical and physical parameters are take intoaccount. In the following formulasNT refers to both instance and model parameter (instance parameter overrides model parameter):If LENGTH is not zero:(Lnom =Lnom =
if MU is specified,
(3.16)
otherwise.
with:0 = 1.25663706143592e 6 Hm . After the nominal inductance is calculated, it is adjustedfor temperature by the formula:2L(T ) = L(TNOM) 1 + TC1 (T TNOM) + TC2 (T TNOM)
(3.17)
where L(TNOM) = Lnom . In the above formula, T represents the instance temperature, whichcan be explicitly using the temp keyword or calculated using the circuit temperature and dtemp,if present.
3.2.11
General form:KXXXXXXX LYYYYYYY LZZZZZZZ v a l u eExamples:K43 LAA LBB 0 . 9 9 9KXFRMR L1 L2 0 . 8 7
LYYYYYYY and LZZZZZZZ are the names of the two coupled inductors, and value is thecoefficient of coupling, K, which must be greater than 0 and less than or equal to 1. Using thedot convention, place a dot on the first node of each inductor.
3.2.12
General form:LXXXXXXX n+ n L = e x p r e s s i o n < t c 1 = v a l u e > < t c 2 = v a l u e >LXXXXXXX n+ n e x p r e s s i o n < t c 1 = v a l u e > < t c 2 = v a l u e >Examples:L1 l 2 l l l L = i (Vm) < { I t } ? { L l } : {Lh } t c 1 =4e 03 t c 2 =6e 05
3.2.13
The simulator supports the specification of voltage and current initial conditions on capacitorand inductor models, respectively. These models are not the standard ones supplied withSPICE3, but are in fact code models which can be substituted for the SPICE models whenrealistic initial conditions are required. For details please refer to chapt. 12. A XSPICE deckexample using these models is shown below:** This circuit contains a capacitor and an inductor with* initial conditions on them. Each of the components
3.2.14
Switches
Two types of switches are available: a voltage controlled switch (type SXXXXXX, model SW)and a current controlled switch (type WXXXXXXX, model CSW). A switching hysteresis maybe defined, as well as on- and off-resistances (0 < R < ).General form:SXXXXXXX N+ N NC+ NC MODEL <ON><OFF>WYYYYYYY N+ N VNAM MODEL <ON><OFF>Examples:s 1 1 2 3 4 s w i t c h 1 ONs 2 5 6 3 0 sm2 o f fS w i t c h 1 1 2 10 0 s m o d e l 1w1 1 2 v c l o c k s w i t c h m o d 1W2 3 0 vramp sm1 ONw r e s e t 5 6 v c l c k l o s s y s w i t c h OFFNodes 1 and 2 are the nodes between which the switch terminals are connected. The modelname is mandatory while the initial conditions are optional. For the voltage controlled switch,nodes 3 and 4 are the positive and negative controlling nodes respectively. For the currentcontrolled switch, the controlling current is that through the specified voltage source. Thedirection of positive controlling current flow is from the positive node, through the source, tothe negative node.The instance parameters ON or OFF are required, when the controlling voltage (current) startsinside the range of the hysteresis loop (different outputs during forward vs. backward voltageor current ramp). Then ON or OFF determine the initial state of the switch.
3.2.15
The switch model allows an almost ideal switch to be described in ngspice. The switch is notquite ideal, in that the resistance can not change from 0 to infinity, but must always have a finitepositive value. By proper selection of the on and off resistances, they can be effectively zeroand infinity in comparison to other circuit elements. The parameters available are:NameVTITVHIHRONROFF
Parameterthreshold voltagethreshold currenthysteresis voltagehysteresis currenton resistanceoff resistance
UnitsVAVA
Default0.00.00.00.01.01.0e+12 (*)
Switch modelSWCSWSWCSWSW,CSWSW,CSW
(*) Or 1/GMIN, if you have set GMIN to any other value, see the .OPTIONS control line(15.1.2) for a description of GMIN, its default value results in an off-resistance of 1.0e+12ohms.The use of an ideal element that is highly nonlinear such as a switch can cause large discontinuities to occur in the circuit node voltages. A rapid change such as that associated with a switchchanging state can cause numerical round-off or tolerance problems leading to erroneous resultsor time step difficulties. The user of switches can improve the situation by taking the followingsteps:
First, it is wise to set ideal switch impedances just high or low enough to be negligiblewith respect to other circuit elements. Using switch impedances that are close to "ideal"in all cases aggravates the problem of discontinuities mentioned above. Of course, whenmodeling real devices such as MOSFETS, the on resistance should be adjusted to a realistic level depending on the size of the device being modeled.
When switches are placed around capacitors, then the option CHGTOL should also be reduced. Suggested values for these two options are 1.0 and 1e-16 respectively. Thesechanges inform ngspice to be more careful around the switch points so that no errors aremade due to the rapid change in the circuit.
78
Chapter 4Voltage and Current Sources4.1
General form:VXXXXXXX N+ N <<DC> DC/TRAN VALUE> <AC <ACMAG <ACPHASE>>>+ <DISTOF1 <F1MAG <F1PHASE>>> <DISTOF2 <F2MAG <F2PHASE>>>IYYYYYYY N+ N <<DC> DC/TRAN VALUE> <AC <ACMAG <ACPHASE>>>+ <DISTOF1 <F1MAG <F1PHASE>>> <DISTOF2 <F2MAG <F2PHASE>>>Examples:VCC 10 0 DC 6VIN 13 2 0 . 0 0 1 AC 1 SIN ( 0 1 1MEG)ISRC 23 21 AC 0 . 3 3 3 4 5 . 0 SFFM( 0 1 10K 5 1K)VMEAS 12 9VCARRIER 1 0 DISTOF1 0 . 1 90.0VMODULATOR 2 0 DISTOF2 0 . 0 1I I N 1 1 5 AC 1 DISTOF1 DISTOF2 0 . 0 0 1n+ and n- are the positive and negative nodes, respectively. Note that voltage sources need notbe grounded. Positive current is assumed to flow from the positive node, through the source, tothe negative node. A current source of positive value forces current to flow out of the n+ node,through the source, and into the n- node. Voltage sources, in addition to being used for circuitexcitation, are the ammeters for ngspice, that is, zero valued voltage sources may be insertedinto the circuit for the purpose of measuring current. They of course have no effect on circuitoperation since they represent short-circuits.DC/TRAN is the dc and transient analysis value of the source. If the source value is zero both fordc and transient analyses, this value may be omitted. If the source value is time-invariant (e.g.,a power supply), then the value may optionally be preceded by the letters DC.ACMAG is the ac magnitude and ACPHASE is the ac phase. The source is set to this value in theac analysis. If ACMAG is omitted following the keyword AC, a value of unity is assumed. IfACPHASE is omitted, a value of zero is assumed. If the source is not an ac small-signal input,the keyword AC and the ac values are omitted.DISTOF1 and DISTOF2 are the keywords that specify that the independent source has distortioninputs at the frequencies F1 and F2 respectively (see the description of the .DISTO control line).
The keywords may be followed by an optional magnitude and phase. The default values of themagnitude and phase are 1.0 and 0.0 respectively.Any independent source can be assigned a time-dependent value for transient analysis. If asource is assigned a time-dependent value, the time-zero value is used for dc analysis. Thereare nine independent source functions: pulse, exponential, sinusoidal, piece-wise linear, single-frequency FM AM transient noise random voltages or currents and external data (only with ngspice shared library).If parameters other than source values are omitted or set to zero, the default values shown areassumed. (TSTEP is the printing increment and TSTOP is the final time (see the .TRAN controlline for explanation)).
Pulse
General form:PULSE ( V1 V2 TD TR TF PW PER )Examples:VIN 3 0 PULSE(1 1 2NS 2NS 2NS 50NS 100NS )NameV1V2TDTRTFPWPER
ParameterInitial valuePulsed valueDelay timeRise timeFall timePulse widthPeriod
Default Value0.0TSTEPTSTEPTSTOPTSTOP
UnitsV, AV, Asecsecsecsecsec
ValueV1V1V2V2V1V1
Sinusoidal
General form:SIN (VO VA FREQ TD THETA)Examples:VIN 3 0 SIN ( 0 1 100MEG 1NS 1E10 )NameVOVAFREQTDTHETA
ParameterOffsetAmplitudeFrequencyDelayDamping factor
Default Value1/T ST OP0.00.0
UnitsV, AV, AHzsec1/sec
Exponential
General Form:EXP ( V1 V2 TD1 TAU1 TD2 TAU2 )Examples:VIN 3 0 EXP(4 1 2NS 30NS 60NS 40NS )NameV1V2TD1TAU1TD2TAU2
ParameterInitial valuepulsed valuerise delay timerise time constantfall delay timefall time constant
Default Value0.0TSTEPTD1+TSTEPTSTEP
UnitsV, AV, Asecsecsecsec
(4.1)
Let V 21 = V 2 V 1 V 12 = V 1 V 2:
V1if 0 t < T D1,
(tT D1) TAU1if T D1 t < T D2,V (t) = V 1 +V 21 1 e
(tT D1)(tT D2)
V 1 +V 21 1 e TAU1 +V 12 1 e TAU2if T D2 t < T ST OP.
(4.2)
Piece-Wise Linear
General Form:PWL( T1 V1 <T2 V2 T3 V3 T4 V4 . . . > ) < r = v a l u e > < t d = v a l u e >Examples:VCLOCK 7 5 PWL( 0 7 10NS 7 11NS 3 17NS 3 18NS 7 50NS 7) r =0 t d =15NSEach pair of values (Ti , Vi ) specifies that the value of the source is Vi (in Volts or Amps) attime = Ti . The value of the source at intermediate values of time is determined by using linearinterpolation on the input values. The parameter r determines a repeat time point. If r is notgiven, the whole sequence of values (Ti , Vi ) is issued once, then the output stays at its finalvalue. If r = 0, the whole sequence from time = 0 to time = Tn is repeated forever. If r = 10ns,the sequence between 10ns and 50ns is repeated forever. the r value has to be one of the timepoints T1 to Tn of the PWL sequence. If td is given, the whole PWL sequence is delayed by adelay time time = td. The current source still needs to be patched, td and r are not yet available.
Single-Frequency FM
General Form:SFFM (VO VA FC MDI FS )Examples:V1 12 0 SFFM( 0 1M 20K 5 1K)NameVOVAFCMDIFS
ParameterOffsetAmplitudeCarrier frequencyModulation indexSignal frequency
Default value1/T ST OP1/T ST OP
UnitsV, AV, AHzHz
(4.3)
General Form:AM(VA VO MF FC TD)Examples:V1 12 0 AM( 0 . 5 1 20K 5MEG 1m)NameVAVOMFFCTD
ParameterAmplitudeOffsetModulating frequencyCarrier frequencySignal delay
Default value1/T ST OP-
UnitsV, AV, AHzHzs
(4.4)
General Form:TRNOISE (NA NT NALPHA NAMP RTSAM RTSCAPT RTSEMT)Examples:VNoiw 1 0 DC 0 TRNOISE ( 2 0 n 0 . 5 n 0 0 )VNoi1of 1 0 DC 0 TRNOISE ( 0 10 p 1 . 1 12 p )VNoiw1of 1 0 DC 0 TRNOISE ( 2 0 10 p 1 . 1 12 p )IALL 10 0 DC 0 t r n o i s e ( 1m 1u 1 . 0 0 . 1m 15m
$ white$ 1/ f$ w h i t e and 1 / f22 u 50 u ) $ w h i t e , 1 / f , RTS
Transient noise is an experimental feature allowing (low frequency) transient noise injection andanalysis. See chapter 15.3.10 for a detailed description. NA is the Gaussian noise rms voltageamplitude, NT is the time between sample values (breakpoints will be enforced on multiples ofthis value). NALPHA (exponent to the frequency dependency), NAMP (rms voltage or currentamplitude) are the parameters for 1/f noise, RTSAM the random telegraph signal amplitude,RTSCAPT the mean of the exponential distribution of the trap capture time, and RTSEMTits emission time mean. White Gaussian, 1/f, and RTS noise may be combined into a singlestatement.NameNANTNALPHANAMPRTSAMRTSCAPTRTSEMT
ParameterRms noise amplitude (Gaussian)Time step1/f exponentAmplitude (1/f)AmplitudeTrap capture timeTrap emission time
Default value0< <2-
UnitsV, AsecV, AV, Asecsec
If you set NT and RTSAM to 0, the noise option TRNOISE ... is ignored. Thus you may switchoff the noise contribution of an individual voltage source VNOI by the commandalter @vnoi[trnoise] = [ 0 0 0 0 ] $ no noisealter @vrts[trnoise] = [ 0 0 0 0 0 0 0] $ no noiseSee chapt. 17.5.3 for the alter command.You may switch off all TRNOISE noise sources by settingset notrnoiseto your .spiceinit file (for all your simulations) or into your control section in front of the nextrun or tran command (for this specific and all following simulations). The commandunset notrnoisewill reinstate all noise sources.The noise generators are implemented into the independent voltage (vsrc) and current (isrc)sources.
The TRRANDOM option yields statistically distributed voltage values, derived from the ngspicerandom number generator. These values may be used in the transient simulation directly withina circuit, e.g. for generating a specific noise voltage, but especially they may be used in the control of behavioral sources (B, E, G sources 5, voltage controllable A sources 12, capacitors 3.2.8,inductors 3.2.12, or resistors 3.2.4) to simulate the circuit dependence on statistically varyingdevice parameters. A Monte-Carlo simulation may thus be handled in a single simulation run.General Form:TRRANDOM( TYPE TS <TD <PARAM1 <PARAM2> > >)Examples:VR1 r 1
0 dc 0 t r r a n d o m ( 2 10m 0 1 ) $ G a u s s i a n
descriptionUniformGaussianExponentialPoisson
PARAM1RangeStandard Dev.MeanLambda
default1111
General Form:EXTERNAL
PARAM2OffsetMeanOffsetOffset
default0000
Examples:Vex 1 0 dc 0 e x t e r n a lI e x i 1 i 2 dc 0 e x t e r n a l <m = xx >Voltages or currents may be set from the calling process, if ngspice is compiled as a sharedlibrary and loaded by the process. See chapt 19.6.3 for an explanation.
4.1.10
The XSPICE option supports arbitrary phase independent sources that output at TIME=0.0 avalue corresponding to some specified phase shift. Other versions of SPICE use the TD (delaytime) parameter to set phase-shifted sources to their time-zero value until the delay time haselapsed. The XSPICE phase parameter is specified in degrees and is included after the SPICE3parameters normally used to specify an independent source. Partial XSPICE deck examples ofusage for pulse and sine waveforms are shown below:* Phase shift is specified after Berkeley defined parameters* on the independent source cards. Phase shift for both of the* following is specified as +45 degrees*v1 1 0 0.0 sin(0 1 1k 0 0 45.0)r1 1 0 1k*v2 2 0 0.0 pulse(-1 1 0 1e-5 1e-5 5e-4 1e-3 45.0)r2 2 0 1k*
Ngspice allows circuits to contain linear dependent sources characterized by any of the fourequationsi = gv
v = ev
i = fi
v = hi
where g, e, f , and h are constants representing transconductance, voltage gain, current gain,and transresistance, respectively. Non-linear dependent sources for voltages or currents (B, E,G) are described in chapter 5.
General form:GXXXXXXX N+ N NC+ NC VALUE <m= v a l >Examples:G1 2 0 5 0 0 . 1
n+ and n- are the positive and negative nodes, respectively. Current flow is from the positivenode, through the source, to the negativenode. nc+ and nc- are the positive and negative controlling nodes, respectively. value is thetransconductance (in mhos). m is an optional multiplier to the output current. val may be anumerical value or an expression according to 2.8.5 containing references to other parameters.
General form:EXXXXXXX N+ N NC+ NC VALUEExamples:E1 2 3 14 1 2 . 0n+ is the positive node, and n- is the negative node. nc+ and nc- are the positive and negativecontrolling nodes, respectively. value is the voltage gain.
General form:FXXXXXXX N+ N VNAM VALUE <m= v a l >Examples:F1 13 5 VSENS 5 m=2n+ and n- are the positive and negative nodes, respectively. Current flow is from the positivenode, through the source, to the negative node. vnam is the name of a voltage source throughwhich the controlling current flows. The direction of positive controlling current flow is fromthe positive node, through the source, to the negative node of vnam. value is the current gain.m is an optional multiplier to the output current.
General form:HXXXXXXX n+ n vnam v a l u eExamples:HX 5 17 VZ 0 . 5Kn+ and n- are the positive and negative nodes, respectively. vnam is the name of a voltage sourcethrough which the controlling current flows. The direction of positive controlling current flowis from the positive node, through the source, to the negative node of vnam. value is thetransresistance (in ohms).
Dependent polynomial sources available in SPICE2G6 are fully supported in ngspice using theXSPICE extension (25.1). The form used to specify these sources is shown in Table 4.1. Fordetails on its usage please see chapter 5.2.4.
Source TypePOLYNOMIAL VCVSPOLYNOMIAL VCCSPOLYNOMIAL CCCSPOLYNOMIAL CCVS
88
Chapter 5Non-linear Dependent Sources (BehavioralSources)The non-linear dependent sources B ( see chapt. 5.1), E (see 5.2), G see (5.3) described inthis chapter allow to generate voltages or currents which result from evaluating a mathematicalexpression. Internally E and G sources are converted to the more general B source. All threesources may be used to introduce behavioral modeling and analysis.
General form:BXXXXXXX n+ n < i = e x p r > <v= e x p r > < t c 1 = v a l u e > < t c 2 = v a l u e >+ <temp= v a l u e > <dtemp = v a l u e >Examples:B1B2B3B4B5
00332
11440
I =cos ( v ( 1 ) ) + s i n ( v ( 2 ) )V= l n ( c o s ( l o g ( v ( 1 , 2 ) ^ 2 ) ) ) v ( 3 ) ^ 4 + v ( 2 ) ^ v ( 1 )I =17V= exp ( p i ^ i ( vdd ) )V = V( 1 ) < {Vlow} ? {Vlow} : V( 1 ) > { Vhigh } ? { Vhigh } : V( 1 )
n+ is the positive node, and n- is the negative node. The values of the V and I parametersdetermine the voltages and currents across and through the device, respectively. If I is giventhen the device is a current source, and if V is given the device is a voltage source. One and onlyone of these parameters must be given.A simple model is implemented for temperature behavior by the formula:I(T ) = I(TNOM) 1 + TC1 (T TNOM) + TC2 (T TNOM)2or
(5.1)
90
V (T ) = V (TNOM) 1 + TC1 (T TNOM) + TC2 (T TNOM)2
(5.2)
In the above formula, T represents the instance temperature, which can be explicitly set usingthe temp keyword or calculated using the circuit temperature and dtemp, if present. If bothtemp and dtemp are specified, the latter is ignored.The small-signal AC behavior of the nonlinear source is a linear dependent source (or sources)with a proportionality constant equal to the derivative (or derivatives) of the source at the DCoperating point. The expressions given for V and I may be any function of voltages and currentsthrough voltage sources in the system.The following functions of a single real variable are defined:Trigonometric functions: cos, sin, tan, acos, asin, atanHyperbolic functions: cosh, sinh, acosh, asinh, atanhExponential and logarithmic: exp, ln, logOther: abs, sqrt, u, u2, uramp, floor, ceilFunctions of two variables are: min, max, powFunctions of three variables are: a ? b:cThe function u is the unit step function, with a value of one for arguments greater than zeroand a value of zero for arguments less than zero. The function u2 returns a value of zerofor arguments less than zero, one for arguments greater than one and assumes the value of theargument between these limits. The function "uramp" is the integral of the unit step: for aninput x, the value is zero if x is less than zero, or if x is greater than zero the value is x. Thesethree functions are useful in synthesizing piece-wise non-linear functions, though convergencemay be adversely affected.The following standard operators are defined: +, -, *, /, ^, unary Logical operators are !=, <>, >=, <=, ==, >, <, ||, &&, ! .A ternary function is defined as a ? b : c , which means IF a, THEN b, ELSE c. Besure to place a space in front of ? to allow the parser distinguishing it from other tokens.Example: Ternary function* B s o u r c e t e s t Clamped v o l t a g e s o u r c e* C . P . B a s s o " S w i t c h e d mode power s u p p l i e s " , New York , 2008. param Vhigh = 4 . 6. param Vlow = 0 . 4Vin1 1 0 DC 0 PWL( 0 0 1u 5 )B c l 2 0 V = V( 1 ) < Vlow ? Vlow : V( 1 ) > Vhigh ? Vhigh : V( 1 ). controlset noaskquitt r a n 5 n 1up l o t V( 2 ) v s V( 1 ). endc. end
91
If the argument of log, ln, or sqrt becomes less than zero, the absolute value of the argument isused. If a divisor becomes zero or the argument of log or ln becomes zero, an error will result.Other problems may occur when the argument for a function in a partial derivative enters aregion where that function is undefined.Parameters may be used like {Vlow} shown in the example above. Parameters will be evaluatedupon set up of the circuit, vectors like V(1) will be evaluated during the simulation.To get time into the expression you can integrate the current from a constant current sourcewith a capacitor and use the resulting voltage (dont forget to set the initial voltage across thecapacitor).Non-linear resistors, capacitors, and inductors may be synthesized with the nonlinear dependentsource. Nonlinear resistors, capacitors and inductors are implemented with their linear counterparts by a change of variables implemented with the nonlinear dependent source. The followingsubcircuit will implement a nonlinear capacitor:Example: Non linear capacitor. S u b c k t n l c a p p o s neg* Bx : c a l c u l a t e f ( i n p u t v o l t a g e )Bx 1 0 v = f ( v ( pos , neg ) )* Cx : l i n e a r c a p a c i t a n c eCx 2 0 1* Vx : Ammeter t o m e a s u r e c u r r e n t i n t o t h e c a p a c i t o rVx 2 1 DC 0 V o l t s* D r i v e t h e c u r r e n t t h r o u g h Cx b a c k i n t o t h e c i r c u i tFx p o s neg Vx 1. endsExample for f(v(pos,neg)):Bx 1 0 V = v ( pos , neg ) * v ( pos , neg )Non-linear resistors or inductors may be described in a similar manner. An example for anonlinear resistor using this template is shown below.Example: Non linear resistor* use of hertz v a r i a b l e in n o n l i n e a r r e s i s t o r* . param r b a s e =1k* some t e s t sB1 1 0 V = h e r t z * v ( 3 3 )B2 2 0 V = v ( 3 3 ) * h e r t zb3 3 0 V = 6 . 2 8 3 e3 / ( h e r t z + 6 . 2 8 3 e3 ) * v ( 3 3 )V1 33 0 DC 0 AC 1*** T r a n s l a t e R1 10 0 R= 1 k / s q r t (HERTZ) t o B s o u r c e ***. S u b c k t n l r e s p o s neg r b = r b a s e* Bx : c a l c u l a t e f ( i n p u t v o l t a g e )Bx10v = 1 / { r b } / s q r t (HERTZ) * v ( pos , neg )* Rx : l i n e a r r e s i s t a n c eRx201
The special variables time and temper are available in a transient analysis, reflecting theactual simulation time and circuit temperature. temper returns the circuit temperature, givenin degree C (see 2.11). The variable hertz is available in an AC analysis. time is zero inthe AC analysis, hertz is zero during transient analysis. Using the variable hertz may costsome CPU time if you have a large circuit, because for each frequency the operating point hasto be determined before calculating the AC response.
par(expression)
The B source syntax may also be used in output lines like .plot as algebraic expressions foroutput (see chapt.15.5.6 ).
Both B source types may contain a piece-wise linear dependency of one network variable:Example: pwl_currentBdio 1 0 I = pwl ( v (A) , 0 , 0 , 3 3 , 1 0m, 1 0 0 , 3 3m, 2 0 0 , 5 0m)v(A) is the independent variable x. Each pair of values following describes the x,y functionalrelation: In this example at node A voltage of 0V the current of 0A is generated - next pair gives10mA flowing from ground to node 1 at 33V on node A and so forth.The same is possible for voltage sources:
93
Example: pwl_voltageB l i m i t b 0 V = pwl ( v ( 1 ) , 4 ,0 , 2 ,2 , 2 , 4 , 4 , 5 , 6 , 5 )
Monotony of the independent variable in the pwl definition is checked - non-monotonic x entrieswill stop the program execution. v(1) may be replaced by a controlling current source. v(1) mayalso be replaced by an expression, e.g. -2*i(Vin). The value pairs may also be parameters, whichhave to be defined before by a .param statement. An example for the pwl function using all ofthese options is shown below:
94
x0=4 y0 =0x1=2 y1 =2x2 =2 y2=2x3 =4 y3 =1xx0=x01xx3=x3 +1
Vin1 0R 1 0 2
DC=0V
* no l i m i t s o u t s i d e o f t h e t a b u l a t e d x v a l u e s ( c o n t i n u e s l i n e a r i l y )Btest2 2 0I = pwl ( v ( 1 ) , x0 , y0 , x1 , y1 , x2 , y2 , x3 , y3 )* l i k e TABLE f u n c t i o n w i t h l i m i t s :Btest3 3 0I = ( v ( 1 ) < x0 ) ? y0 : ( v ( 1 ) < x3 ) ?+ pwl ( v ( 1 ) , x0 , y0 , x1 , y1 , x2 , y2 , x3 , y3 ) : y3 * more e f f i c i e n t and e l e g a n t TABLE f u n c t i o n w i t h l i m i t s*( voltage c o n t r o l l e d ) :Btest4 4 0I = pwl ( v ( 1 ) ,+ xx0 , y0 , x0 , y0 ,+ x1 , y1 ,+ x2 , y2 ,+ x3 , y3 , xx3 , y3 )** more e f f i c i e n t and e l e g a n t TABLE f u n c t i o n w i t h l i m i t s* ( c o n t r o l l e d by c u r r e n t ) :Btest5 5 0I = pwl (2 * i ( Vin ) ,+ xx0 , y0 , x0 , y0 ,+ x1 , y1 ,+ x2 , y2 ,+ x3 , y3 , xx3 , y3 )Rint2 2 0 1Rint3 3 0 1Rint4 4 0 1Rint5 5 0 1. controldc Vin 6 6 0 . 2p l o t v ( 2 ) v ( 3 ) v (4) 0.5 v ( 5 ) + 0 . 5. endc. end
5.25.2.1
General form:EXXXXXXX n+ n v o l = e x p r Examples:E41 4 0 v o, hertz (5.1.2). or{, } may be used to delimit the function.
VALUE
Optional syntax:EXXXXXXX n+ n v a l u e ={ e x p r }Examples:E41 4 0 v a l u e = {V( 3 ) * V(3) O f f s }
TABLE
Data may be entered from the listings of a data table similar to the pwl B-Source (5.1.4). Dataare grouped into x, y pairs. Expression may be an equation or an expression containing nodevoltages or branch currents (in the form of i(vm)) and any other terms as given for the B sourceand described in chapter 5.1. It may contain parameters (2.8.1). or {, } may be used to delimitthe function. Expression delivers the x-value, which is used to generate a corresponding yvalue, according to the tabulated value pairs, using linear interpolation. If the x-value is belowx0 , y0 is returned, above x2 y2 is returned (limiting function). The value pairs have to be realnumbers, parameters are not allowed!Syntax for data entry from table:Exxx n1 n2 TABLE { e x p r e s s i o n } = ( x0 , y0 ) ( x1 , y1 ) ( x2 , y2 )Example (simple comparator):ECMP 11 0 TABLE {V( 1 0 , 9 ) } = (5MV, 0V) ( 5MV, 5V)
POLY
Polynomial sources are only available when the XSPICE option (see 32) is enabled.
General form:EXXXX N+ N POLY(ND) NC1+ NC1 ( NC2+ NC2 . . . ) P0 ( P1 . . . )Example:ENONLIN 100 101 POLY ( 2 ) 3 0 4 0 0 . 0 1 3 . 6 0 . 2 0 . 0 0 5POLY(ND) Specifies the number of dimensions of the polynomial. The number of pairs ofcontrolling nodes must be equal to the number of dimensions.(N+) and (N-) nodes are output nodes. Positive current flows from the (+) node through thesource to the (-) node.The <NC1+> and <NC1-> are in pairs and define a set of controlling voltages. A particularnode can appear more than once, and the output and controlling nodes need not be different.The example yields a voltage output controlled by two input voltages v(3,0) and v(4,0). Fourpolynomial coefficients are given. The equivalent function to generate the output is:0 + 13.6 * v(3) + 0.2 * v(4) + 0.005 * v(3) * v(3)Generally you will set the equation according toPOLY(1) y = p0 +POLY(2) y = p0 ++++POLY(3) y = p0 +++
k1*X1 + p2*X1*X1+ p3*X1*X1*X1 + ...p1*X1+ p2*X2 +p3*X1*X1+ p4*X2*X1+ p5*X2*X2+p6*X1*X1*X1+ p7*X2*X1*X1 + p8*X2*X2*X1 +p9*X2*X2*X2+ ...p1*X1+ p2*X2+ p3*X3+p4*X1*X1 + p5*X2*X1 + p6*X3*X1 +p7*X2*X2 + p8*X2*X3 + p9*X3*X3 + ...
where X1 is the voltage difference of the first input node pair, X2 of the second pair and soon. Keeping track of all polynomial coefficient obviously becomes rather tedious for largerpolynomials.
LAPLACE
Currently ngspice does not offer a direct E-Source element with the LAPLACE option. Thereis however, a XSPICE code model equivalent called x_fer (see chapt. 12.2.16), which you mayinvoke manually. The XSPICE option has to enabled (32.1). AC (15.3.1) and transient analysis(15.3.9) is supported.The following E-Source:ELOPASS 4 0 LAPLACE {V( 1 ) } {10 / ( s / 6 8 0 0 + 1 ) }may be replaced by:AELOPASS
where you have the voltage of node 1 as input, an intermediate output node int_4 and an Esource as buffer, so to keep the name ELOPASS available if further processing is required.If the controlling expression is more complex than just a voltage node, you may add a B-Source(5.1) for evaluating the expression before entering the A-device.E-Source with complex controlling expression:ELOPASS 4 0 LAPLACE {V( 1 ) * v ( 2 ) } {10 / ( s / 6 8 0 0 + 1 ) }may be replaced by:BELOPASS i n t _ 1 0 V=V( 1 ) * v ( 2 )AELOPASS i n t _
5.35.3.1
General form:GXXXXXXX n+ n c u r = e x p r <m= v a l >Examples:G51 55 225 c u special variables (5.1.2). m is an optional multiplierto the output current. val may be a numerical value or an expression according to 2.8.5 containing only references to other parameters (no node voltages or branch currents!), because it isevaluated before the simulation commences.
Optional syntax:GXXXXXXX n+ n v a l u e = e x p r <m= v a l >Examples:G51 55 225 v a l u e = V( 3 ) * V(3) O f f s
A data entry by a tabulated listing is available with syntax similar to the E-Source (see chapt.5.2.3).
m is an optional multiplier to the output current. val may be a numerical value or an expressionaccording to 2.8.5 containing only references to other parameters (no node voltages or branchcurrents!), because it is evaluated before the simulation commences.
Example
*) To get this functionality, the compatibility mode has to be set in spinit or .spiceinit by setngbehavior=all.
5.4
The B, E, G, sources and the behavioral R, C, L elements are powerful tools to set up userdefined models. Unfortunately debugging these models is not very comfortable.
100
In this trivial example, the reason and location for the bug is obvious. However, if you haveseveral equations using behavioral sources, and several occurrences of the log function, thendebugging is nearly impossible.However, if the variable ngdebug (see 17.7) is set (e.g. in file .spiceinit), a more distinctiveerror message is issued, which (after some closer investigation) will reveal the location andvalue of the buggy parameter.Detailed error message for input file with bug (log(-2)):E r r o r : 2 o u t o f r a n g e f o r l o gc a l l i n g PTeval , t r e e =( v0 ) * ( l o g ( v1 ) )d / d v0 : l o g ( v1 )d / d v1 : ( v0 ) * ( ( 0 . 4 3 4 2 9 4 ) / ( v1 ) )values :var0 = 1v a r 1 = 2If variable strict_errorhandling (see 17.7) is set, ngspice exits after this message. If not, gminand source stepping may be started, typically without success.
Chapter 6Transmission LinesNgspice implements both the original SPICE3f5 transmission lines models and the one introduced with KSPICE. The latter provide an improved transient analysis of lossy transmissionlines. Unlike SPICE models, which uses the state-based approach to simulate lossy transmission lines, KSPICE simulates lossy transmission lines and coupled multiconductor line systemsusing the recursive convolution method. The impulse response of an arbitrary transfer functioncan be determined by deriving a recursive convolution from the Pade approximations of thefunction. We use this approach for simulating each transmission lines characteristics and eachmulticonductor lines modal functions. This method of lossy transmission line simulation hasbeen proved to give a speedup of one to two orders of magnitude over SPICE3f5.
6.1
General form:TXXXXXXX N1 N2 N3 N4 Z0=VALUE <TD=VALUE> <F=FREQ <NL=NRMLEN>>+ <IC=V1 , I1 , V2 , I2 >Examples:T1 1 0 2 0 Z0=50 TD=10NSn1 and n2 are the nodes at port 1; n3 and n4 are the nodes at port 2. z0 is the characteristicimpedance. The length of the line may be expressed in either of two forms. The transmissiondelay, td, may be specified directly (as td=10ns, for example). Alternatively, a frequency f maybe given, together with nl, the normalized electrical length of the transmission line with respectto the wavelength in the line at the frequency f. If a frequency is specified but nl is omitted,0.25 is assumed (that is, the frequency is assumed to be the quarter-wave frequency). Note thatalthough both forms for expressing the line length are indicated as optional, one of the two mustbe specified.Note that this element models only one propagating mode. If all four nodes are distinct in the actual circuit, then two modes may be excited. To simulate such a situation, two transmission-lineelements are required. (see the example in chapt. 21.7 for further clarification.) The (optional)initial condition specification consists of the voltage and current at each of the transmission lineports. Note that the initial conditions (if any) apply only if the UIC option is specified on the.TRAN control line.
102
Note that a lossy transmission line (see below) with zero loss may be more accurate than thelossless transmission line due to implementation details.
General form:OXXXXXXX n1 n2 n3 n4 mnameExamples:O23 1 0 2 0 LOSSYMODOCONNECT 10 5 20 5 INTERCONNECT
This is a two-port convolution model for single conductor lossy transmission lines. n1 and n2are the nodes at port 1; n3 and n4 are the nodes at port 2. Note that a lossy transmission linewith zero loss may be more accurate than the lossless transmission line due to implementationdetails.
6.2.1
The uniform RLC/RC/LC/RG transmission line model (referred to as the LTRA model henceforth) models a uniform constant-parameter distributed transmission line. The RC and LC casesmay also be modeled using the URC and TRA models; however, the newer LTRA model is usually faster and more accurate than the others. The operation of the LTRA model is based on theconvolution of the transmission lines impulse responses with its inputs (see [8]). The LTRAmodel takes a number of parameters, some of which must be given and some of which areoptional.
Parameterresistance/lengthinductance/lengthconductance/lengthcapacitance/lengthlength of linebreakpoint controlbreakpoint controldont limit time-step to lessthan line delaydont do complex time-stepcontroluse linear interpolationuse linear when quadraticseems badspecial reltol for historycompactionspecial abstol for historycompactionuse Newton-Raphson methodfor time-step controldont limit time-step to keepimpulse-response errors low
103Units/Type/unitH/unitmhos/unitF/unitunitarbitrary unitflag
Default0.00.00.00.0no default11not set
Example0.29.13e-90.03.65e-121.00.55set
flag
not set
set
flagflag
not setnot set
setset
RELTOL
1.0e-3
ABSTOL
1.0e-9
104
default is a trial and error procedure by cutting the previous time-step in half. REL and ABS arequantities that control the setting of breakpoints.The option most worth experimenting with for increasing the speed of simulation is REL. Thedefault value of 1 is usually safe from the point of view of accuracy but occasionally increasescomputation time. A value greater than 2 eliminates all breakpoints and may be worth tryingdepending on the nature of the rest of the circuit, keeping in mind that it might not be safe fromthe viewpoint of accuracy.Breakpoints may usually be entirely eliminated if it is expected the circuit will not displaysharp discontinuities. Values between 0 and 1 are usually not required but may be used forsetting many breakpoints.COMPACTREL may also be experimented with when the option TRYTOCOMPACT is specified ina .OPTIONS card. The legal range is between 0 and 1. Larger values usually decrease theaccuracy of the simulation but in some cases improve speed. If TRYTOCOMPACT is not specifiedon a .OPTIONS card, history compaction is not attempted and accuracy is high.NO CONTROL, TRUNCDONTCUT and NOSTEPLIMIT also tend to increase speed at the expense ofaccuracy.
General form:UXXXXXXX n1 n2 n3 mname l = l e n <n=lumps >Examples:U1 1 2 0 URCMOD L=50UURC2 1 12 2 UMODL l =1MIL N=6n1 and n2 are the two element nodes the RC line connects, while n3 is the node to which thecapacitances are connected. mname is the model name, len is the length of the RC line inmeters. lumps, if specified, is the number of lumped segments to use in modeling the RC line(see the model description for the action taken if this parameter is omitted).
6.3.1
The URC model is derived from a model proposed by L. Gertzberg in 1974. The model isaccomplished by a subcircuit type expansion of the URC line into a network of lumped RCsegments with internally generated nodes. The RC segments are in a geometric progression,increasing toward the middle of the URC line, with K as a proportionality constant. The number of lumped segments used, if not specified for the URC line device, is determined by thefollowing formula:
N=
(K1) 2 RC2log Fmax L L 2L K
(6.1)log KThe URC line is made up strictly of resistor and capacitor segments unless the ISPERL parameter is given a nonzero value, in which case the capacitors are replaced with reverse biased diodes
105
with a zero-bias junction capacitance equivalent to the capacitance replaced, and with a saturation current of ISPERL amps per meter of transmission line and an optional series resistanceequivalent to RSPERL ohms per meter.NameKFMAXRPERLCPERLISPERLRSPERL
ParameterPropagation ConstantMaximum Frequency of interestResistance per unit lengthCapacitance per unit lengthSaturation Current per unit lengthDiode Resistance per unit length
UnitsHz/mF/mA/m/m
Default2.01.0 G100010e-1500
Example1.26.5 Meg101p-
Area-
Unlike SPICE3, which uses the state-based approach to simulate lossy transmission lines,KSPICE simulates lossy transmission lines and coupled multiconductor line systems using therecursive convolution method. The impulse response of an arbitrary transfer function can bedetermined by deriving a recursive convolution from the Pade approximations of the function.NGSPICE is using this approach for simulating each transmission lines characteristics and eachmulticonductor lines modal functions. This method of lossy transmission line simulation hasshown to give a speedup of one to two orders of magnitude over SPICE3E. Please note that thefollowing two models will support only transient simulation, no ac.Additional Documentation Available: S. Lin and E. S. Kuh, "Pade Approximation Applied to Transient Simulation of LossyCoupled Transmission Lines," Proc. IEEE Multi-Chip Module Conference, 1992, pp.52-55. S. Lin, M. Marek-Sadowska, and E. S. Kuh, "SWEC: A StepWise Equivalent Conductance Timing Simulator for CMOS VLSI Circuits," European Design Automation Conf.,February 1991, pp. 142-148. S. Lin and E. S. Kuh, "Transient Simulation of Lossy Interconnect," Proc. Design Automation Conference, Anaheim, CA, June 1992, pp. 81-86.
6.4.1
General form:YXXXXXXX N1 0 N2 0 mname <LEN=LENGTH>Example:Y1 1 0 2 0 ymod LEN=2.MODEL ymod t x l R= 1 2 . 4 5 L = 8 . 9 7 2 e9 G=0 C= 0 . 4 6 8 e 12 l e n g t h =16n1 and n2 are the nodes of the two ports. The optional instance parameter len is the length ofthe line and may be expressed in multiples of [unit]. Typically unit is given in meters. len willoverride the model parameter length for the specific instance only.
106
Parameterresistance/lengthinductance/lengthconductance/lengthcapacitance/lengthlength of line
Units/Type/unitH/unitmhos/unitF/unitunit
Default0.00.00.00.0no default
Example0.29.13e-90.03.65e-121.0
Model parameter length must be specified as a multiple of unit. Typically unit is given in [m].For transient simulation only.
The CPL multiconductor line model is in theory similar to the RLGC model, but without frequency dependent loss (neither skin effect nor frequency-dependent dielectric loss). Up to 8coupled lines are supported in NGSPICE.General form:PXXXXXXX NI1 NI2 . . . NIX GND1 NO1 NO2 . . . NOX GND2 mname <LEN=LENGTH>Example:P1 i n 1 i n 2 0 b1 b2 0 PLINE. model PLINE CPL l e n g t h ={ Len }+R=1 0 1+L={L11 } { L12 } { L22 }+G=0 0 0+C={C11} {C12} {C22}. param Len =1 Rs=0+ C11 = 9 . 1 4 3 5 7 9 E11 C12 = 9.78265E12 C22 = 9 . 1 4 3 5 7 8 E11+ L11 = 3 . 8 3 5 7 2 E7 L12 = 8 . 2 6 2 5 3 E8 L22 = 3 . 8 3 5 7 2 E7ni1 ... nix are the nodes at port 1 with gnd1; no1 ... nox are the nodes at port 2 with gnd2.The optional instance parameter len is the length of the line and may be expressed in multiplesof [unit]. Typically unit is given in meters. len will override the model parameter length forthe specific instance only.The CPL model takes a number of parameters:NameRLGCLENGTH
All RLGC parameters are given in Maxwell matrix form. For the R and G matrices the diagonalelements must be specified, for L and C matrices the lower or upper triangular elements mustspecified. The parameter LENGTH is a scalar and is mandatory. For transient simulation only.
Chapter 7Diodes7.1
Junction Diodes
General form:DXXXXXXX n+ n mname < a r e a = v a l > <m= v a l > < p j = v a l > < o f f > < i c =vd >+ <temp= v a l > <dtemp = v a l >Examples:DBRIDGE 2 10 DIODE1DCLMP 3 7 DMOD AREA= 3 . 0 IC = 0 . 2The pn junction (diode) implemented in ngspice expands the one found in SPICE3f5. Perimetereffects and high injection level have been introduced into the original model and temperaturedependence of some parameters has been added. n+ and n- are the positive and negative nodes,respectively. mname is the model name. Instance parameters may follow, dedicated to onlythe diode described in the respective line. area is the area scale factor, which may scalethe saturation current given by the model parameters (and others, see table below). pj is theperimeter scale factor, scaling the sidewall saturation current and its associated capacitance. mis a multiplier to area and perimeter, and off indicates an (optional) starting condition on thedevice for dc analysis. If the area factor is omitted, a value of 1.0 is assumed. The (optional)initial condition specification using ic is intended for use with the uic option on the .trancontrol line, when a transient analysis is desired starting from other than the quiescent operatingpoint. You should supply the initial voltage across the diode there. The (optional) temp valueis the temperature at which this device is to operate, and overrides the temperature specificationon the .option control line. The temperature of each instance can be can be specified as anoffset to the circuit temperature with the dtemp option.
The dc characteristics of the diode are determined by the parameters is and n. An ohmic resistance, rs, is included. Charge storage effects are modeled by a transit time, tt, and a nonlineardepletion layer capacitance which is determined by the parameters cjo, vj, and m. The temperature dependence of the saturation current is defined by the parameters eg, the energy and xti,
108
CHAPTER 7. DIODES
the saturation current temperature exponent. The nominal temperature at which these parameters were measured is tnom, which defaults to the circuit-wide value specified on the .optionscontrol line. Reverse breakdown is modeled by an exponential increase in the reverse diodecurrent and is determined by the parameters bv and ibv (both of which are positive numbers).
Junction DC parameters
NameBVIBVIK (IKF)IKRIS (JS)JSWNRS
ParameterReverse breakdown voltageCurrent at breakdown voltageForward knee currentReverse knee currentSaturation currentSidewall saturation currentEmission coefficientOhmic resistance
UnitsVAAAAA
Default
1.0e-31.0e-31.0e-31.0e-141.0e-1410.0
Example401.0e-41.0e-61.0e-61.0e-161.0e-151.5100
Scale factor
ParameterZero-bias junction bottom-wallcapacitanceZero-bias junction sidewallcapacitanceCoefficient for forward-biasdepletion bottom-wall capacitanceformulaCoefficient for forward-biasdepletion sidewall capacitanceformulaArea junction grading coefficientPeriphery junction gradingcoefficientJunction potentialPeriphery junction potentialTransit-time
UnitsF
Default0.0
Example2pF
0.0
.1pF
0.5
0.50.33
0.50.5
VVsec
110
0.60.60.1ns
areaperimeter1/area
NameCJO (CJ0)CJP (CJSW)FC
FCS
M (MJ)MJSWVJ (PB)PHPTT
Scale factorareaperimeter
109
Temperature effectsName
Parameter
Units
EG
Activation energy
eV
1.11
TM1TM2TNOM (TREF)TRS1 (TRS)TRS2TM1TM2TTT1TTT2
1/C
1/C2
0.00.0270.00.00.00.00.00.0
XTI
3.0
TLEVTLEVCCTA (CTC)CTPTCV
1/C1/C1/C
000.00.00.0
1/C2C1/C1/C21/C1/C21/C
Example1.11 Si0.69 Sbd0.67 Ge503.0 pn2.0 Sbd
Noise modelingNameKFAF
ParameterFlicker noise coefficientFlicker noise exponent
Units-
Default01
Diode models may be described in the input file (or an file included by .inc) according to thefollowing example:General form:. model mname t y p e ( pname1= p v a l 1 pname2= p v a l 2 . . . )Examples:. model DMOD D ( b f =50 i s =1e 13 v b f = 50 )
Diode Equations
The junction diode is the basic semiconductor device and the simplest one modeled in ngspice,but its model is quite complex, even if not all the physical phenomena affecting a pn junctionare modeled. The diode is modeled in three different regions: Forward bias: the anode is more positive than the cathode, the diode is "on" and canconduct large currents. To avoid convergence problems and unrealistic high current, it isbetter to specify a series resistance to limit current with rs model parameter.
Scale fac
CHAPTER 7. DIODES Reverse bias: the cathode is more positive than the anode and the diode is "off". A reversebias diode conducts a small leakage current. Breakdown: the breakdown region is model led only if the bv model parameter is given.When a diode enters breakdown the current increase exponentially (remember to limit it);bv is a positive value.
Parameters ScalingModel parameters are scaled using the unit-less parameters area and pj and the multiplier m asdepicted below:AREAe f f = AREA MPJe f f = PJ MISe f f = IS AREAe f f + JSW PJe f fIBVe f f = IBV AREAe f fIKe f f = IK AREAe f fIKRe f f = IKR AREAe f fCJe f f = CJ0 AREAe f fCJPe f f = CJP PJe f fDiode DC, Transient and AC model equations
qVD
effq
3NkT 3ID = ISe f f [1 + ( qVD e ) ] +VD GMIN, if BVe f f < VD < 3 NkTq
q(BVe f f +VD )
NkTISe f f (e) +VD GMIN, if VD BVe f f
(7.1)
The breakdown region must be described with more depth since the breakdown is not modeledin physically. As written before, the breakdown modeling is based on two model parameters:the "nominal breakdown voltage" bv and the current at the onset of breakdown ibv. For thediode model to be consistent, the current value cannot be arbitrary chosen, since the reverse biasand breakdown regions must match. When the diode enters breakdown region from reverse bias,the current is calculated using the formula1 :Ibdwn = ISe f f (e
qBVNkT
1)
(7.2)
The computed current is necessary to adjust the breakdown voltage making the two regionsmatch. The algorithm is a little bit convoluted and only a brief description is given here:Most real diodes shows a current increase that, at high current levels, does not follow the exponential relationship given above. This behavior is due to high level of carriers injected into thejunction. High injection effects (as they are called) are modeled with ik and ikr.1 if
you look at the source code in file diotemp.c you will discover that the exponential relation is replacedwith a first order Taylor series expansion.
111
IDe f f =
rID,
1+ IKID
if VD 3 NkTq
ef f
(7.3)
rID
, otherwise.
1+ IKRIDef f
IDe f fVD
The depletion capacitance is more complex to model, since the function used to approximate itdiverges when the diode voltage become greater than the junction built-in potential. To avoidfunction divergence, the capacitance function is approximated with a linear extrapolation forapplied voltage greater than a fraction of the junction built-in potential.
Cdeplbw =
Cdeplsw =
CJe f f (1 VD )MJ ,VJCJe f f
VD1FC(1+MJI)+MJ VJ(1FC)(1+MJ)
CJPe f f (1 VD )MJSW ,PHPCJPe f f
if VD < FC VJ, otherwise.
VD1FCS(1+MJSW)+MJSW PHP(1+MJSW)(1FCS)
(7.4)
(7.5)
112
Temperature dependenceThe temperature affects many of the parameters in the equations above, the following equations show how. One of the most significant parameter that varies with the temperature for asemiconductor is the band-gap energy:EGnom = 1.16 7.02e4
TNOM2TNOM + 1108.0
(7.6)
T2TNOM + 1108.0
(7.7)
log f actorN
JSW (T ) = JSW e
(7.8)(7.9)
EGTEG
+ XTI ln()Vt (TNOM) Vt (T )TNOM
(7.10)
TNOMTNOMVt (TNOM) Vt (T )TTEGnomEG(T)PHP(T ) = PHP () Vt (T ) 3 ln()+
TNOMTNOMVt (TNOM) Vt (T )
(7.11)
(7.12)
(7.13)
(7.14)
(7.15)
(7.16)
(7.17)
113
Noise modelThe diode has three noise contribution, one due to the presence of the parasitic resistance rsand the other two (shot and flicker) due to the pn junction.The thermal noise due to the parasitic resistance is:i2RS =
4kT fRS
(7.18)
KF IDAFff
(7.19)
114
Chapter 8BJTs8.1
General form:QXXXXXXX nc nb ne <ns > mname < a r e a = v a l > < a r e a c = v a l > < a r e a b = v a l >+ <m= v a l > < o f f > < i c =vbe , vce > <temp= v a l > <dtemp = v a l >Examples:Q23 10 24 13 QMOD IC = 0 . 6 , 5 . 0Q50A 11 26 4 20 MOD1nc, nb, and ne are the collector, base, and emitter nodes, respectively. ns is the (optional)substrate node. If unspecified, ground is used. mname is the model name, area, areab, areacare the area factors (emitter, base and collector respectively), and off indicates an (optional)initial condition on the device for the dc analysis. If the area factor is omitted, a value of 1.0 isassumed.The (optional) initial condition specification using ic=vbe,vce is intended for use with theuic option on a .tran control line, when a transient analysis is desired starting from otherthan the quiescent operating point. See the .ic control line description for a better way to settransient initial conditions. The (optional) temp value is the temperature at which this deviceis to operate, and overrides the temperature specification on the .option control line. Usingdtemp option you can specify instances temperature relative to the circuit temperature.
Ngspice provides three BJT device models, which are selected by the .model card..model QMOD1 BJT level=2This is the minimal version, further optional parameters listed in the table below may replacethe ngspice default parameters. The level keyword specifies the model to be used: level=1 : This is the original SPICE BJT model, and it is the default model if the levelkeyword is not specified on the .model line.
115
116
CHAPTER 8. BJTS level=2 : This is a modified version of the original SPICE BJT that models both verticaland lateral devices and includes temperature corrections of collector, emitter and baseresistors. level=4: Advanced VBIC model (see for details)
The bipolar junction transistor model in ngspice is an adaptation of the integral charge controlmodel of Gummel and Poon. This modified Gummel-Poon model extends the original modelto include several effects at high bias levels. The model automatically simplifies to the simplerEbers-Moll model when certain parameters are not specified. The parameter names used in themodified Gummel-Poon model have been chosen to be more easily understood by the programuser, and to reflect better both physical and circuit design thinking.The dc model is defined by the parameters is, bf, nf, ise, ikf, and ne which determinethe forward current gain characteristics, is, br, nr, isc, ikr, and nc which determine thereverse current gain characteristics, and vaf and var which determine the output conductancefor forward and reverse regions.Level 1 model has among the standard temperature model a extension which is compatible withmost foundry provided process design kits (see parameter table below tlev).Level 1 and 2 model includes substrate saturation current iss. Three ohmic resistances rb, rc,and re are included, where rb can be high current dependent. Base charge storage is modeledby forward and reverse transit times, tf and tr, the forward transit time tf being bias dependentif desired, and nonlinear depletion layer capacitances which are determined by cje, vje, andnje for the B-E junction, cjc, vjc, and njc for the B-C junction and cjs, vjs, and mjs forthe C-S (Collector-Substrate) junction.Level 1 and 2 model defines a substrate capacitance that will be connected to devices base orcollector, to model lateral or vertical devices dependent from the parameter subs. The temperature dependence of the saturation currents, is and iss (for level 2 model), is determined bythe energy-gap, eg, and the saturation current temperature exponent, xti.Additionally base current temperature dependence is modeled by the beta temperature exponentxtb in the new model. The values specified are assumed to have been measured at the temperature tnom, which can be specified on the .options control line or overridden by a specificationon the .model line.Level 4 model (VBIC) has the following improvements beyond the GP models: Improved Earlyeffect modeling, Quasi-saturation modeling, Parasitic substrate transistor modeling, Parasiticfixed (oxide) capacitance modeling, Includes an avalanche multiplication model, Improved temperature modeling, Base current is decoupled from collector current, Electrothermal modeling,Smooth, continuous mode.The BJT parameters used in the modified Gummel-Poon model are listed below. The parameternames used in earlier versions of SPICE2 are still accepted.Gummel-Poon BJT Parameters (incl. model extensions)Name
SUBS
ISISS
BFNFVAF (VA)IKFNKFISENEBRNRVAR (VB)IKRISC
NCRBIRBRBMRERCCJEVJE (PE)MJE (ME)TFXTFVTFITF
117
AA
1.0e-161.0e-16
1.0e-151.0e-15
1001.0
1001
VA
2000.01
A-
0.50.01.511
0.581e-1320.11
area
1e-13
1.51000.1
areaarea
RB
000
1102pF
areaareaarea
Vsec-
0.750.3300
0.60.330.1ns
118
CHAPTER 8. BJTS
PTFCJC
VJC (PC)MJCXCJC
TRCJS
VJS (PS)MJS (MS)XTBEGXTIKFAFFCTNOM (TREF)TLEVTLEVCTRE1TRE2TRC1TRC2TRB1
deg
2pF
V-
0.750.331
secF
00
10ns2pF
0.75
010.5
1e-3
1e-5
TRB2TRBM1TRBM2TBF1TBF2TBR1TBR2TIKF1TIKF2TIKR1TIKR2TIRB1TIRB2TNC1TNC2TNE1TNE2TNF1TNF2TNR1TNR2TVAF1TVAF2
119
120
TVAR1TVAR2CTCCTECTSTVJCTVJETITF1TITF2TTF1TTF2TTR1TTR2TMJE1TMJE2TMJC1TMJC2
Chapter 9JFETs9.1
General form:JXXXXXXX nd ng n s mname < a r e a > < o f f > < i c =vds , vgs > <temp= t >Examples:J 1 7 2 3 JM1 OFFnd, ng, and ns are the drain, gate, and source nodes, respectively. mname is the model name,area is the area factor, and off indicates an (optional) initial condition on the device for dcanalysis. If the area factor is omitted, a value of 1.0 is assumed. The (optional) initial conditionspecification, using ic=VDS,VGS is intended for use with the uic option on the .TRAN controlline, when a transient analysis is desired starting from other than the quiescent operating point.See the .ic control line for a better way to set initial conditions. The (optional) temp value isthe temperature at which this device is to operate, and overrides the temperature specificationon the .option control line.
9.29.2.1
The level 1 JFET model is derived from the FET model of Shichman and Hodges. The dccharacteristics are defined by the parameters VTO and BETA, which determine the variationof drain current with gate voltage, LAMBDA, which determines the output conductance, andIS, the saturation current of the two gate junctions. Two ohmic resistances, RD and RS, areincluded.vgst = vgs V T O
(9.1)
(9.2)
122
CHAPTER 9. JFETS
b f ac =
1BPB V T O
(9.3)
if vgst vds GMIN,IDrain = p vds (vds (b f ac vds B) vgst (2 B + 3 b f ac (vgst vds))) + vds GMIN, if vgst
if vgst 0vds GMIN,IDrain = p vds (2 vgst vds) + vds GMIN, if vgst vds
(9.5)
Charge storage is modeled by nonlinear depletion layer capacitances for both gate junctionswhich vary as the 1/2 power of junction voltage and are defined by the parameters CGS, CGD,and PB.NameVTOBETALAMBDARDRSCGSCGDPBISBKFAFNLEVGDSNOIFCTNOMTCVBEX
ParameterThreshold voltage VT 0Transconductance parameter ( )Channel-length modulationparameter ( )Drain ohmic resistanceSource ohmic resistanceZero-bias G-S junction capacitanceCgsZero-bias G-D junctioncapacitance CgdGate junction potentialGate saturation current ISDoping tail parameterFlicker noise coefficientFlicker noise exponentNoise equation selectorChannel noise coefficient fornlev=3Coefficient for forward-biasdepletion capacitance formulaParameter measurementtemperatureThreshold voltage temperaturecoefficientMobility temperature exponent
UnitsVA/V 1/V
Default-2.01.0e-40
Example-2.01.0e-31.0e-4
Scaling factor
1001005pF
1pF
VA-
11.0e-1410111.0
0.61.0e-141.1
32.0
0.5C
0.1
123
Additional to the standard thermal and flicker noise model an alternative thermal channel noisemodel is implemented and is selectable by setting NLEV parameter to 3. This follows in acorrect channel thermal noise in the linear region.
Snoise =
(1 + + 2 )2 4 k T BETA V gst GDSNOI31+
(9.6)
with
(vds1 vgsVT O , if vgs V T O vds0,
else
(9.7)
The level 2 model is an improvement to level 1. Details are available from Macquarie University. Some important items are:
The description maintains strict continuity in its high-order derivatives, which is essentialfor prediction of distortion and intermodulation. Frequency dependence of output conductance and transconductance is described as afunction of bias. Both drain-gate and source-gate potentials modulate the pinch-off potential, which is consistent with S-parameter and pulsed-bias measurements. Self-heating varies with frequency. Extreme operating regions - subthreshold, forward gate bias, controlled resistance, andbreakdown regions - are included. Parameters provide independent fitting to all operating regions. It is not necessary tocompromise one region in favor of another. Strict drain-source symmetry is maintained. The transition during drain-source potentialreversal is smooth and continuous.
The model equations are described in this pdf document and in [19].
124NameIDACGAMBETACGDCGSDELTAFCHFETAHFE1HFE2HFGAMHFG1HFG2IBDISLFGAMLFG1LFG2MVSTNPQRSRDTAUDTAUGVBDVBIVSTVTOXCXIZRGLGLSLDCDSSAFACNFINGTNOMTEMP
CHAPTER 9. JFETSDescriptionDevice IDTextCapacitance modulationLinear-region transconductance scaleZero-bias gate-source capacitanceZero-bias gate-drain capacitanceThermal reduction coefficientForward bias capacitance parameterHigh-frequency VGS feedback parameterHFGAM modulation by VGDHFGAM modulation by VGSHigh-frequency VGD feedback parameterHFGAM modulation by VSGHFGAM modulation by VDGGate-junction breakdown currentGate-junction saturation currentLow-frequency feedback parameterLFGAM modulation by VSGLFGAM modulation by VDGSubthreshold modulationGate-junction ideality factorLinear-region power-law exponentSaturated-region power-law exponentSource ohmic resistanceDrain ohmic resistanceRelaxation time for thermal reductionRelaxation time for gamma feedbackGate-junction breakdown potentialGate-junction potentialSubthreshold potentialThreshold voltageCapacitance pinch-off reduction factorSaturation-knee potential factorKnee transition parameterGate ohmic resistanceGate inductanceSource inductanceDrain inductanceFixed Drain-source capacitanceGate-width scale factorNumber of gate fingers scale factorNominal Temperature (Not implemented)Temperature
Unit TypeTextNoneNoneCapacitanceCapacitanceNoneNoneNoneNoneNoneNoneNoneNoneCurrentCurrentNoneNoneNoneNoneNoneNoneNoneResistanceResistanceTimeTimeVoltageVoltageVoltageVoltageNoneNoneNoneResistanceInductanceInductanceInductanceCapacitanceNoneNoneTemperatureTemperature
DefaultPF101040F0F0W0.500V 10 V100 V10 V10A1014A00 V10 V10 V11220 Ohm0 Ohm0s0s1V1V0V-2.0 V010000.50 Ohm0H0H0H0F11300 K300 K
Chapter 10MESFETs10.1
MESFETs
General form:ZXXXXXXX ND NG NS MNAME <AREA> <OFF> <IC=VDS, VGS>Examples:Z1 7 2 3 ZM1 OFF
10.2
10.2.1
The MESFET model level 1 is derived from the GaAs FET model of Statz et al. as described in[11]. The dc characteristics are defined by the parameters VTO, B, and BETA, which determinethe variation of drain current with gate voltage, ALPHA, which determines saturation voltage,and LAMBDA, which determines the output conductance. The formula are given by:
Id =
3 B(Vgs VT )2 Vds 1
A3 (1 + LVds )1+b(Vgs VT ) B(Vgs VT )21+b(Vgs VT ) (1 + LVds )
3A
(10.1)
Two ohmic resistances, rd and rs, are included. Charge storage is modeled by total gate chargeas a function of gate-drain and gate-source voltages and is defined by the parameters cgs, cgd,and pb.
126
NameVTOBETABALPHALAMBDARDRSCGSCGDPBKFAFFC
ParameterPinch-off voltageTransconductance parameterDoping tail extending parameterSaturation voltage parameterChannel-length modulation parameterDrain ohmic resistanceSource ohmic resistanceZero-bias G-S junction capacitanceZero-bias G-D junction capacitanceGate junction potentialFlicker noise coefficientFlicker noise exponentCoefficient for forward-bias depletioncapacitance formula
UnitsVA/V 21/V1/V1/V
FFV-
Default-2.01.0e-40.32000001010.5
Example-2.01.0e-30.321.0e-41001005pF1pF0.6
Area*******
Device instance:z1 2 3 0 mesmod a r e a = 1 . 4Model:. model mesmod nmf l e v e l =1 r d =46 r s =46 v t 0 = 1.3+ lambda = 0 . 0 3 a l p h a =3 b e t a = 1 . 4 e3
10.2.2
level 2 (and levels 3,4) Copyright 1993: T. Ytterdal, K. Lee, M. Shur and T. A. Fjeldlyto be writtenM. Shur, T.A. Fjeldly, T. Ytterdal, K. Lee, "Unified GaAs MESFET Model for Circuit Simulation", Int. Journal of High Speed Electronics, vol. 3, no. 2, pp. 201-233, 1992
10.2.3
hfet1
level 5to be writtenno documentation available
10.2.4
hfet2
level6to be writtenno documentation available
Chapter 11MOSFETsNgspice supports all the original mosfet models present in SPICE3f5 and almost all the newerones that have been published and made open-source. Both bulk and SOI (Silicon on Insulator) models are available. When compiled with the cider option, ngspice implements the fourterminals numerical model that can be used to simulate a MOSFET (please refer to numericalmodeling documentation for additional information and examples).
11.1
MOSFET devices
General form:MXXXXXXX nd ng ns nb mname <m= v a l > < l = v a l > <w= v a l >+ <ad= v a l > <as= v a l > <pd= v a l > <ps= v a l > <nrd= v a l >+ < n r s = v a l > < o f f > < i c =vds , vgs , vbs > <temp= t >Examples:M1 24 2 0 20 TYPE1M31 2 17 6 10 MOSN L=5U W=2UM1 2 9 3 0 MOSP L=10U W=5U AD=100P AS=100P PD=40U PS=40UNote the suffixes in the example: the suffix u specifies microns (1e-6 m) and p sq-microns(1e-12 m2 ).The instance card for MOS devices starts with the letter M. nd, ng, ns, and nb are the drain,gate, source, and bulk (substrate) nodes, respectively. mname is the model name and m is themultiplicity parameter, which simulates m paralleled devices. All MOS models support them multiplier parameter. Instance parameters l and w, channel length and width respectively,are expressed in meters. The areas of drain and source diffusions: ad and as, in squared meters(m2 ).If any of l, w, ad, or as are not specified, default values are used. The use of defaults simplifiesinput file preparation, as well as the editing required if device geometries are to be changed. pdand ps are the perimeters of the drain and source junctions, in meters. nrd and nrs designatethe equivalent number of squares of the drain and source diffusions; these values multiply thesheet resistance rsh specified on the .model control line for an accurate representation of theparasitic series drain and source resistance of each transistor. pd and ps default to 0.0 while nrd
128
and nrs to 1.0. off indicates an (optional) initial condition on the device for dc analysis. The(optional) initial condition specification using ic=vds,vgs,vbs is intended for use with theuic option on the .tran control line, when a transient analysis is desired starting from otherthan the quiescent operating point. See the .ic control line for a better and more convenient wayto specify transient initial conditions. The (optional) temp value is the temperature at which thisdevice is to operate, and overrides the temperature specification on the .option control line.The temperature specification is ONLY valid for level 1, 2, 3, and 6 MOSFETs, not for level 4or 5 (BSIM) devices.BSIM3.2 version is also supporting the instance parameter delvto and mulu0 for local mismatch and NBTI (negative bias temperature instability) modeling:Namedelvtomulu0
11.2
ParameterThreshold voltage shiftLow-field mobility multiplier (U0)
UnitsV-
Default0.01.0
Example0.070.9
MOSFET models are the central part of ngspice, probably because they are the most widelyused devices in the electronics world. Ngspice provides all the MOSFETs implemented in theoriginal Spice3f and adds several models developed by UC Berkeleys Device Group and otherindependent groups.Each model is invoked with a .model card. A minimal version is:.model MOSN NMOS level=8 version=3.3.0The model name MOSN corresponds to the model name in the instance card (see 11.1). Parameter NMOS selects an n-channel device, PMOS would point to a p-channel transistor. Thelevel and version parameters select the specific model. Further model parameters are optional and replace ngspice default values. Due to the large number of parameters (more than100 for modern models), model cards may be stored in extra files and loaded into the netlist bythe .include (2.6) command. Model cards are specific for a an IC manufacturing process andare typically provided by the IC foundry. Some generic parameter sets, not linked to a specificprocess, are made available by the model developers, e.g. UC Berkeleys Device Group forBSIM4 and BSIMSOI.Ngspice provides several MOSFET device models, which differ in the formulation of the I-Vcharacteristic, and are of varying complexity. Models available are listed in table 11.1. Currentmodels for IC design are BSIM3 (11.2.9, down to channel length of 0.35 m), BSIM4 (11.2.10,below 0.35 m), BSIMSOI (11.2.12, silicon-on-insulator devices), HiSIM2 and HiSIM_HV(11.2.14, surface potential models for standard and high voltage/high power MOS devices).
11.2.1
MOS Level 1
This model is also known as the Shichman-Hodges model. This is the first model written andthe one often described in the introductory textbooks for electronics. This model is applicableonly to long channel devices. The use of Meyers model for the C-V part makes it non chargeconserving.
Level12345698, 498, 498, 498, 4910, 5814, 5414, 5414, 5414, 5444455556576061, 6862, 73
NameMOS1MOS2MOS3BSIM1BSIM2MOS6MOS9BSIM3v0BSIM3v1BSIM3v32BSIM3B4SOIBSIM4v4BSIM4v5BSIM4v6BSIM4EKVPSPB3SOIFDB3SOIDDB3SOIPDSTAGHiSIM2HiSIM_HV
ModelShichman-HodgesGrove-Frhoman
1.0.2
3.03.13.2 - 3.2.43.3.04.3.14.0 - 4.44.5.04.6.54.7.0
Version-
DeveloperBerkeleyBerkeleyBerkeleyBerkeleyBerkeleyBerkeleyAlan GillespieBerkeleyBerkeleyBerkeleyBerkeleyBerkeleyBerkeleyBerkeleyBerkeleyBerkeleyEPFLGildenblattBerkeleyBerkeleyBerkeleySouthamptonHiroshimaHiroshima
References
adms configuredadms configured
NotesThis is the classical quadratic model.Described in [2]A semi-empirical model (see [1])Described in [3]Described in [5]Described in [2]
130
11.2.2
MOS Level 2
This model tries to overcome the limitations of the Level 1 model addressing several shortchannel effects, like velocity saturation. The implementation of this model is complicated andthis leads to many convergence problems. C-V calculations can be done with the original Meyermodel (non charge conserving).
11.2.3
MOS Level 3
This is a semi-empirical model derived from the Level 2 model. In the 80s this model has oftenbeen used for digital design and, over the years, has proved to be robust. A discontinuity in themodel with respect to the KAPPA parameter has been detected (see [10]). The supplied fix hasbeen implemented in Spice3f2 and later. Since this fix may affect parameter fitting, the optionbadmos3 may be set to use the old implementation (see the section on simulation variablesand the .options line). Ngspice level 3 implementation takes into account length and widthmask adjustments (xl and xw) and device width narrowing due to diffusion (wd).
11.2.4
MOS Level 6
This model is described in [2]. The model can express the current characteristics of shortchannel MOSFETs at least down to 0. 25 m channel-length, GaAs FET, and resistance insertedMOSFETs. The model evaluation time is about 1/3 of the evaluation time of the SPICE3 moslevel 3 model. The model also enables analytical treatments of circuits in short-channel regionand makes up for a missing link between a complicated MOSFET current characteristics andcircuit behaviors in the deep submicron region.
11.2.5
The dc characteristics of the level 1 through level 3 MOSFETs are defined by the device parameters vto, kp, lambda, phi and gamma. These parameters are computed by ngspice if processparameters (nsub, tox, ...) are given, but users specified values always override. vto is positive (negative) for enhancement mode and negative (positive) for depletion mode N-channel(P-channel) devices.Charge storage is modeled by three constant capacitors, cgso, cgdo, and cgbo which representoverlap capacitances, by the nonlinear thin-oxide capacitance which is distributed among thegate, source, drain, and bulk regions, and by the nonlinear depletion-layer capacitances for bothsubstrate junctions divided into bottom and periphery, which vary as the mj and mjsw powerof junction voltage respectively, and are determined by the parameters cbd, cbs, cj, cjsw, mj,mjsw and pb.Charge storage effects are modeled by the piecewise linear voltages-dependent capacitancemodel proposed by Meyer. The thin-oxide charge-storage effects are treated slightly different for the level 1 model. These voltage-dependent capacitances are included only if tox isspecified in the input description and they are represented using Meyers formulation.There is some overlap among the parameters describing the junctions, e.g. the reverse currentcan be input either as is (in A) or as js (in A/m2 ). Whereas the first is an absolute value the
131
second is multiplied by ad and as to give the reverse current of the drain and source junctionsrespectively.This methodology has been chosen since there is no sense in relating always junction characteristics with ad and as entered on the device line; the areas can be defaulted. The same ideaapplies also to the zero-bias junction capacitances cbd and cbs (in F) on one hand, and cj (inF/m2 ) on the other.The parasitic drain and source series resistance can be expressed as either rd and rs (in ohms)or rsh (in ohms/sq.), the latter being multiplied by the number of squares nrd and nrs input onthe device line.NGSPICE level 1, 2, 3 and 6 parameters
NameLEVELVTOKPGAMMAPHILAMBDA
RDRSCBDCBSISPBCGSO
CGDO
CGBO
RSH
ParameterModel indexZero-bias threshold voltage(VT 0 )TransconductanceparameterBulk threshold parameterSurface potential (U)Channel length modulation(MOS1 and MOS2 only)( )Drain ohmic resistanceSource ohmic resistanceZero-bias B-D junctioncapacitanceZero-bias B-S junctioncapacitanceBulk junction saturationcurrent (IS )Bulk junction potentialGate-source overlapcapacitance per meterchannel widthGate-drain overlapcapacitance per meterchannel widthGate-bulk overlapcapacitance per meterchannel widthDrain and source diffusionsheet resistance
UnitsV
Default10.0
A/V 2
2.0e-5
3.1e-5
VV1/V
0.00.60.0
0.370.650.02
0.00.00.0
1.01.020fF
20fF
1.0e-14
1.0e-15
VF/m
0.80.0
0.874.0e-11
F/m
4.0e-11
2.0e-11
/
1.0
132
MJCJSW
MJSWJSTOXNSUBNSSNFSTPG
XJLDUOUCRITUEXP
UTRA
VMAXNEFF
KFAFFC
DELTATHETAETA
ParameterZero-bias bulk junctionbottom cap. per sq-meter ofjunction areaBulk junction bottomgrading coeff.Zero-bias bulk junctionsidewall cap. per meter ofjunction perimeter
UnitsF/m2
Example2.0e-4
0.50 (level1)0.33 (level2, 3)
mcm3cm2cm2-
1.0e-70.00.00.01.0
1.0e-74.0e151.0e101.0e10
mm2cm /V secV/cm
0.00.06001.0e4
1M0.8M7001.0e4
0.3
m/s
5.0e4
5.0
0.01.00.5
1.0e-261.2
1/V
11.2.6
133
ParameterSaturation field factor(MOS3 only)Parameter measurementtemperature
Default0.2
Example0.5
BSIM Models
Ngspice implements many of the BSIM models developed by Berkeleys BSIM group. BSIMstands for Berkeley Short-Channel IGFET Model and groups a class of models that is continuously updated. In general, all parameters of BSIM models are obtained from process characterization, in particular level 4 and level 5 (BSIM1 and BSIM2) parameters are can be generatedautomatically. J. Pierret [4] describes a means of generating a process file, and the programngproc2mod provided with ngspice converts this file into a sequence of BSIM1 .model linessuitable for inclusion in an ngspice input file.Parameters marked below with an * in the l/w column also have corresponding parameters witha length and width dependency. For example, vfb is the basic parameter with units of Volts,and lvfb and wvfb also exist and have units of Volt-meter.The formulaP = P0 +
PLLeffective
PWWeffective
(11.1)
is used to evaluate the parameter for the actual device specified withLeffective = Linput DL
(11.2)
Weffective = Winput DW
(11.3)
Note that unlike the other models in ngspice, the BSIM models are designed for use with aprocess characterization system that provides all the parameters, thus there are no defaults forthe parameters, and leaving one out is considered an error. For an example set of parametersand the format of a process file, see the SPICE2 implementation notes[3]. For more informationon BSIM2, see reference [5]. BSIM3 (11.2.9) and BSIM4 (11.2.10) represent state of the artfor submicron and deep submicron IC design.
11.2.7
BSIM1 model (the first is a long series) is an empirical model. Developers placed less emphasis on device physics and based the model on parametrical polynomial equations to model thevarious physical effects. This approach pays in terms of circuit simulation behavior but the accuracy degrades in the submicron region. A known problem of this model is the negative outputconductance and the convergence problems, both related to poor behavior of the polynomialequations.
134Ngspice BSIM (level 4) parameters
ParameterFlat-band voltageSurface inversion potentialBody effect coefficientDrain/source depletion charge-sharingcoefficientZero-bias drain-induced barrier-loweringcoefficientZero-bias mobilityShortening of channelNarrowing of channelZero-bias transverse-field mobility degradationcoefficientZero-bias velocity saturation coefficientSens. of mobility to substrate bias at v=0Sens. of drain-induced barrier lowering effectto substrate biasSens. of drain-induced barrier lowering effectto drain bias at Vds = VddSens. of transverse field mobility degradationeffect to substrate biasSens. of velocity saturation effect to substratebiasMobility at zero substrate bias and at Vds = VddSens. of mobility to substrate bias at Vds = VddSens. of mobility to drain bias at Vds = VddSens. of velocity saturation effect on drain biasat Vds=VddGate oxide thicknessTemperature at which parameters weremeasuredMeasurement bias rangeGate-drain overlap capacitance per meterchannel widthGate-source overlap capacitance per meterchannel widthGate-bulk overlap capacitance per meterchannel lengthGate-oxide capacitance-charge model flagZero-bias subthreshold slope coefficientSens. of subthreshold slope to substrate biasSens. of subthreshold slope to drain biasDrain and source diffusion sheet resistanceSource drain junction current densityBuilt in potential of source drain junctionGrading coefficient of source drain junction
135UnitsVVV-
l/w****
cm2/V sec
mm1/V/V
/V 2 sec1/V
***
1/V 2
m/V 2
cm2
cm2/V 2 seccm2/V 2 seccm2/V 2 secm/V 2
mCVF/mF/mF/m
/A/m2V-
136
ParameterBuilt in potential of source, drain junctionsidewallGrading coefficient of source drain junctionsidewallSource drain junction capacitance per unit areasource drain junction sidewall capacitance perunit lengthSource drain junction default widthSource drain junction length reduction
l/w
F/m2F/m
mm
xpart = 0 selects a 40/60 drain/source charge partition in saturation, while xpart=1 selectsaassumed. The (optional) initial condition specification, using ic=vds,vgs is intended for usewith the uic option on the .tran control line, when a transient analysis is desired starting fromother than the quiescent operating point. See the .ic control line for a better way to set initialconditions.
11.2.8
This model contains many improvements over BSIM1 and is suitable for analog simulation.Nevertheless, even BSIM2 breaks transistor operation into several distinct regions and this leadsto discontinuities in the first derivative in C-V and I-V characteristics that can cause numericalproblems during simulation.
11.2.9
BSIM3 solves the numerical problems of previous models with the introduction of smoothingfunctions. It adopts a single equation to describe device characteristics in the operating regions.This approach eliminates the discontinuities in the I-V and C-V characteristics. The original model, BSIM3 evolved through three versions: BSIM3v1, BSIM3v2 and BSIM3v3. BothBSIM3v1 and BSIM3v2 had suffered from many mathematical problems and were replaced byBSIM3v3. The latter is the only surviving release and has itself a long revision historyThe following table summarizes the story of this model:ReleaseBSIM3v3.0BSIM3v3.1BSIM3v3.2
Date10/30/199512/09/199606/16/1998
BSIM3v3.3
07/29/2005
Notes
Version flag3.03.13.2, 3.2.2,3.2.3, 3.2.43.3.0
BSIM3v2 and 3v3 models has proved for accurate use in 0.18 m technologies. The model ispublicly available as source code form from University of California, Berkeley.
137
11.2.10
This is the newest class of the BSIM family and introduces noise modeling and extrinsic parasitics. BSIM4, as the extension of BSIM3 model, addresses the MOSFET physical effects intosub-100nm regime. It is a physics-based, accurate, scalable, robust and predictive MOSFETSPICE model for circuit simulation and CMOS technology development. It is developed bythe BSIM Research Group in the Department of Electrical Engineering and Computer Sciences(EECS) at the University of California, Berkeley (see BSIM4 home page). BSIM4 has a longrevision history, which is summarized below.ReleaseBSIM4.0.0BSIM4.1.0BSIM4.2.0BSIM4.2.1BSIM4.3.0BSIM4.4.0BSIM4.5.0BSIM4.6.0...BSIM4.6.5BSIM4.7.0
Date03/24/200010/11/200004/06/200110/05/200105/09/200303/04/200407/29/200512/13/2006
Version flag
****
4.2.14.3.04.4.04.5.0
09/09/200904/08/2011
* *** **
4.6.54.7
*) supported in ngspice, using e.g. the version=<version flag> flag in the parameter file.**) Parallel processing using OpenMP support is available for this model.Details of any revision are to be found in the Berkeley users manuals, a pdf download of themost recent edition is to be found here .We recommend that you use only the most recent BSIM4 model (version 4.7.0), because itcontains corrections to all known bugs. To achieve that, change the version parameter in yourmodelcard files toVERSION = 4.7.If no version number is given in the .model card, this (newest) version is selected as the default.The older models will typically not be supported, they are made available for reference only.
11.2.11
EKV model
Level 44 model (EKV) is not available in the standard distribution since it is not released insource form by the EKV group. To obtain the code please refer to the (EKV model home page,
138
EKV group home page). A verilog-A version is available contributed by Ivan Riis Nielsen11/2006.
11.2.12
BSIMSOI is a SPICE compact model for SOI (Silicon-On-Insulator) circuit design, created byUniversity of California at Berkeley . This model is formulated on top of the BSIM3 framework. It shares the same basic equations with the bulk model so that the physical nature andsmoothness of BSIM3v3 are retained. Four models are supported in ngspice, those based onBSIM3 and modeling fully depleted (FD, level 55), partially depleted (PD, level 57) and both(DD, level 56), as well as the modern BSIMSOI version 4 model (levels 10, 58). Detailed descriptions are beyond the scope of this manual, but see e.g. BSIMSOIv4.4 User Manual for avery extensive description of the recent model version. OpenMP support is available for levels10, 58, version 4.4.
11.2.13
11.2.14
There are two model implementations available - see also HiSIM Research Center:1. HiSIM2 model: Surface-Potential-Based MOSFET Model for Circuit Simulation version2.7.0 - level 61 & 68 (see link to HiSIM2 for source code and manual).2. HiSIM_HV model: Surface-Potential-Based HV/LD-MOSFET Model for Circuit Simulation version 1.2.2 - level 62 & 73 (see link to HiSIM_HV for source code and manual).
Chapter 12Mixed-Mode and Behavioral Modelingwith XSPICENgspice implements XSPICE extensions for behavioral and mixed-mode (analog and digital)modeling. In the XSPICE framework this is referred to as code level modeling. Behavioralmodeling may benefit dramatically because XSPICE offers a means to add analog functionalityprogrammed in C. Many examples (amplifiers, oscillators, filters ...) are presented in the following. Even more flexibility is available because you may define your own models and use themin addition and in combination with all the already existing ngspice functionality. Mixed modesimulation is speeded up significantly by simulating the digital part in an event driven manner,in that state equations use only a few allowed states and are evaluated only during switching,and not continuously in time and signal as in a pure analog simulator.This chapter describes the predefined models available in ngspice, stemming from the originalXSPICE simulator. The instructions for writing new code models are given in chapter 28.To make use of the XSPICE extensions, you need to compile them in. LINUX, CYGWIN,MINGW and other users may add the flag --enable-xspice to their ./configure commandand then recompile. The prebuilt ngspice for Windows distribution has XSPICE already enabled. For detailed compiling instructions see chapter 32.1.
12.1
Ngspice includes a library of predefined Code Models that can be placed within any circuitdescription in a manner similar to that used to place standard device models. Code modelinstance cards always begin with the letter A, and always make use of a .MODEL card todescribe the code model desired. Section 28 of this document goes into greater detail as to howa code model similar to the predefined models may be developed, but once any model is createdand linked into the simulator it may be placed using one instance card and one .MODEL card(note here we conform to the SPICE custom of referring to a single logical line of informationas a card). As an example, the following uses the predefined gain code model which takesas an input some value on node 1, multiplies it by a gain of 5.0, and outputs the new value tonode 2. Note that, by convention, input ports are specified first on code models. Output portsfollow the inputs.
140
Example:a1 1 2 amp. model amp gain ( gain =5.0)
In this example the numerical values picked up from single-ended (i.e. ground referenced)input node 1 and output to single-ended output node 2 will be voltages, since in the InterfaceSpecification File for this code model (i.e., gain), the default port type is specified as a voltage(more on this later). However, if you didnt know this, the following modifications to theinstance card could be used to insure it:
Example:a1 % v (1) % v (2) amp. model amp gain ( gain =5.0)The specification "%v" preceding the input and output node numbers of the instance card indicate to the simulator that the inputs to the model should be single-ended voltage values. Otherpossibilities exist, as described later.Some of the other features of the instance and .MODEL cards are worth noting. Of particularinterest is the portion of the .MODEL card which specifies gain=5.0. This portion of thecard assigns a value to a parameter of the "gain" model. There are other parameters which canbe assigned values for this model, and in general code models will have several. In additionto numeric values, code model parameters can take non-numeric values (such as TRUE andFALSE), and even vector values. All of these topics will be discussed at length in the followingpages. In general, however, the instance and .MODEL cards which define a code model willfollow the abstract form described below. This form illustrates that the number of inputs andoutputs and the number of parameters which can be specified is relatively open-ended and can beinterpreted in a variety of ways (note that angle-brackets < and > enclose optional inputs):
Example:AXXXXXXX <%v ,% i ,% vd ,% id ,% g ,% gd ,% h ,% hd , or %d >+ <[ > <~ > <%v ,% i ,% vd ,% id ,% g ,% gd ,% h ,% hd , or %d >+ < NIN1 or + NIN1 - NIN1 or " null " >+ <~ >... < NIN2 .. <] > >+ <%v ,% i ,% vd ,% id ,% g ,% gd ,% h ,% hd ,% d or % vnam >+ <[ > <~ > <%v ,% i ,% vd ,% id ,% g ,% gd ,% h ,% hd ,or %d > < NOUT1 or + NOUT1 - NOUT1 >+ <~ >... < NOUT2 .. <] > >+ MODELNAME. MODEL MODELNAME MODELTYPE+ <( PARAMNAME1 = <[ > VAL1 < VAL2 ... <] > > PARAMNAME2 .. >) >
141
Square brackets ([ ]) are used to enclose vector input nodes. In addition, these brackets are usedto delineate vectors of parameters.The literal string null, when included in a node list, is interpreted as no connection at that inputto the model. "Null" is not allowed as the name of a models input or output if the model onlyhas one input or one output. Also, null should only be used to indicate a missing connectionfor a code model; use on other XSPICE component is not interpreted as a missing connection,but will be interpreted as an actual node name.The tilde, ~, when prepended to a digital node name, specifies that the logical value of thatnode be inverted prior to being passed to the code model. This allows for simple inversion ofinput and output polarities of a digital model in order to handle logically equivalent cases andothers that frequently arise in digital system design. The following example defines a NANDgate, one input of which is inverted:
a1 [~1 2] 3 nand1. model nand1 d_nand ( rise_delay =0.1 fall_delay =0.2)The optional symbols %v, %i, %vd, etc. specify the type of port the simulator is to expect forthe subsequent port or port vector. The meaning of each symbol is given in Table 12.1.The symbols described in Table 12.1 may be omitted if the default port type for the model isdesired. Note that non-default port types for multi-input or multi-output (vector) ports must bespecified by placing one of the symbols in front of EACH vector port. On the other hand, if allports of a vector port are to be declared as having the same non-default type, then a symbol maybe specified immediately prior to the opening bracket of the vector. The following examplesshould make this clear:
142
%h
%d%vnam
%vd%id%gd%hd
Interpretationrepresents a single-ended voltage port - one node name or number is expectedfor each port.represents a single-ended current port - one node name or number is expectedfor each port.represents a single-ended voltage-input, current-output (VCCS) port - onenode name or number is expected for each port. This type of port is automatically an input/output.represents a single-ended current-input, voltage-output (CCVS) port - onenode name or number is expected for each port. This type of port is automatically an input/output.represents a digital port - one node name or number is expected for each port.This type of port may be either an input or an output.represents the name of a voltage source, the current through which is taken asan input. This notation is provided primarily in order to allow models definedusing SPICE2G6 syntax to operate properly in XSPICE.represents a differential voltage port - two node names or numbers are expected for each port.represents a differential current port - two node names or numbers are expected for each port.represents a differential VCCS port - two node names or numbers are expectedfor each port.represents a differential CCVS port - two node names or numbers are expectedfor each port.Table 12.1: Port Type Modifiers
143
The parameter names listed on the .MODEL card must be identical to those named in the codemodel itself. The parameters for each predefined code model are described in detail in Sections12.2 (analog), 12.3 (Hybrid, A/D) and 12.4 (digital) . The steps required in order to specifyparameters for user-defined models are described in Chapter 28.The following is a list of instance card and associated .MODEL card examples showing use ofpredefined models within an XSPICE deck:a1 1 2 amp.model amp gain(in_offset=0.1 gain=5.0 out_offset=-0.01)a2 %i[1 2] 3 sum1.model sum1 summer(in_offset=[0.1 -0.2] in_gain=[2.0 1.0]+ out_gain=5.0 out_offset=-0.01)a21 %i[1 %vd(2 5) 7 10] 3 sum2.model sum2 summer(out_gain=10.0)a5 1 2 limit5 .model limit5 limit(in_offset=0.1 gain=2.5+ out_lower.limit=-5.0 out_upper_limit=5.0 limit_domain=0.10+ fraction=FALSE)a7 2 %id(4 7) xfer.cntl1.model xfer_cntl1 pwl(x_array=[-2.0 -1.0 2.0 4.0 5.0]+ y_array=[-0.2 -0.2 0.1 2.0 10.0]+ input_domain=0.05 fraction=TRUE)a8 3 %gd(6 7) switch3.model switch3 aswitch(cntl_off=0.0 cntl_on=5.0 r_off=1e6+ r_on=10.0 log=TRUE)
12.2
Analog Models
The following analog models are supplied with XSPICE. The descriptions included consistof the model Interface Specification File and a description of the models operation. This isfollowed by an example of a simulator-deck placement of the model, including the .MODELcard and the specification of all available parameters.
12.2.1
Gain
NAME_TABLE :C_Function_Name :Spice_Model_Name :Description :
cm_gaingain" A simple gain block "
PORT_TABLE :Port Name :Description :Direction :Default_Type :Allowed_Types :Vector :
in" input "inv[v , vd ,i , id , vnam ]no
out" output "outv[v , vd ,i , id ]no
144
Vector . Bounds :Null . Allowed :
no
PARAMETER_TABLE :Parameter_Name :Description :Data_Type :Default_Value :Limits :Vector :Vector_Bounds :Null_Allowed :
in_offset" input offset "real0.0noyes
gain" gain "real1.0noyes
out_offset" output offset "real0.0noyes
Description: This function is a simple gain block with optional offsets on the input and theoutput. The input offset is added to the input, the sum is then multiplied by the gain, andthe result is produced by adding the output offset. This model will operate in DC, AC,and Transient analysis modes.
Example:
a1 1 2 amp. model amp gain ( in_offset =0.1 gain =5.0+ out_offset = -0.01)
12.2.2
Summer
cm_summersummer" A summer block "
PORT_TABLE :Port Name :Description :Direction :Default_Type :Allowed_Types :Vector :Vector_Bounds :Null_Allowed :
in" input vector "inv[v , vd ,i , id , vnam ]yesno
PARAMETER_TABLE :Parameter_Name :Description :Data_Type :
in_offset" input offset vector "real
out" output "outv[v , vd ,i , id ]nono
in_gain" input gain vector "real
145
Default_Value :Limits :Vector :Vector_Bounds :Null_Allowed :
0.0yesinyes
1.0yesinyes
out_gain" output gain "real1.0noyes
Description: This function is a summer block with 2-to-N input ports. Individual gains andoffsets can be applied to each input and to the output. Each input is added to its respectiveoffset and then multiplied by its gain. The results are then summed, multiplied by theoutput gain and added to the output offset. This model will operate in DC, AC, andTransient analysis modes.Example usage:a2 [1 2] 3 sum1. model sum1 summer ( in_offset =[0.1 -0.2] in_gain =[2.0 1.0]+ out_gain =5.0 out_offset = -0.01)
12.2.3
Multiplier
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:
cm_multmult"multiplier block"in"input vector"inv[v,vd,i,id,vnam]yes[2 -]no
out"output"outv[v,vd,i,id]nono
in_offset
in_gain
146
Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
out_gain"output gain"real1.0noyes
out_offset"output offset"real0.0noyes
Description: This function is a multiplier block with 2-to-N input ports. Individual gains andoffsets can be applied to each input and to the output. Each input is added to its respectiveoffset and then multiplied by its gain. The results are multiplied along with the outputgain and are added to the output offset. This model will operate in DC, AC, and Transientanalysis modes. However, in ac analysis it is important to remember that results areinvalid unless only ONE INPUT of the multiplier is connected to a node which bearsan AC signal (this is exemplified by the use of a multiplier to perform a potentiometerfunction: one input is DC, the other carries the AC signal).
12.2.4
Divider
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:
cm_dividedivide"divider block"num"numerator"inv[v,vd,i,id,vnam]no-
den"denominator"inv[v,vd,i,id,vnam]no-
out"output"outv[v,vd,i,id]no-:
147
num_offset"numerator offset"real0.0noyes
num_gain"numerator gain"real1.0noyes
den_offset"denominator offset"real0.0noyes
den_gain"denominator gain"real1.0noyes
den_lower_limit"denominator lower limit"real1.0e-10noyesden_domain"denominator smoothing domain"real1.0e-10noyesfraction"smoothing fraction/absolute value switch"booleanfalsenoyesout_gain
out_offset
148
Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
"output gain"real1.0noyes
"output offset"real0.0noyes
Description: This function is a two-quadrant divider. It takes two inputs; num (numerator) andden (denominator). Divide offsets its inputs, multiplies them by their respective gains,divides the results, multiplies the quotient by the output gain, and offsets the result. Thedenominator is limited to a value above zero via a user specified lower limit. This limit isapproached through a quadratic smoothing function, the domain of which may be specified as a fraction of the lower limit value (default), or as an absolute value. This modelwill operate in DC, AC and Transient analysis modes. However, in ac analysis it is important to remember that results are invalid unless only ONE INPUT of the divider isconnected to a node which bears an AC signal (this is exemplified by the use of the divider to perform a potentiometer function: one input is DC, the other carries the ACsignal).Example SPICE Usage:a4 1 2 4 divider.model divider divide(num_offset=0.1 num_gain=2.5 den_offset=-0.1+ den_gain=5.0 den_lower.limit=1e-5 den_domain=1e-6+ fraction=FALSE out_gain=1.0 out_offset=0.0)
12.2.5
Limiter
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:
cm_limitlimit"limit block"in"input"inv[v,vd,i,id]nono
in_offset"input offset"real0.0no
gain"gain"real1.0no
Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
149
yes
out_lower_limit"output lower limit"real0.0noyes
out_upper_limit"output upper limit"real1.0noyes
limit_range"upper & lower smoothing range"real1.0e-6noyesfraction"smoothing fraction/absolute value switch"booleanFALSEnoyes
Description: The Limiter is a single input, single output function similar to the Gain Block.However, the output of the Limiter function is restricted to the range specified by theoutput lower and upper limits. This model will operate in DC, AC and Transient analysismodes. Note that the limit range is the value BELOW THE UPPER LIMIT AND ABOVETHE LOWER LIMIT at which smoothing of the output begins. For this model, then, thelimit range represents the delta WITH RESPECT TO THE OUTPUT LEVEL at whichsmoothing occurs. Thus, for an input gain of 2.0 and output limits of 1.0 and -1.0 volts,the output will begin to smooth out at 0.9 volts, which occurs when the input value is at0.4.Example SPICE Usage:a5 1 2 limit5.model limit5 limit(in_offset=0.1 gain=2.5 out_lower_limit=-5.0+ out_upper_limit=5.0 limit_range=0.10 fraction=FALSE)
12.2.6
Controlled Limiter
NAME_TABLE:
150_climitclimit"controlled limiter block"in"input"inv[v,vd,i,id,vnam]nono
cntl_upper"upper lim. control input"inv[v,vd,i,id,vnam]nono
cntl_lower"lower limit control input"inv[v,vd,i,id,vnam]nono
in_offset"input offset"real0.0noyes
gain"gain"real1.0noyes
upper_delta"output upper delta"real0.0noyes
lower_delta"output lower delta"real0.0noyes
limit_range"upper & lower sm. range"real1.0e-6noyes
fraction"smoothing %/abs switch"booleanFALSEnoyes
151
Description: The Controlled Limiter is a single input, single output function similar to the GainBlock. However, the output of the Limiter function is restricted to the range specified bythe output lower and upper limits. This model will operate in DC, AC, and Transient analysis modes. Note that the limit range is the value BELOW THE CNTL_UPPER LIMITAND ABOVE THE CNTL_LOWER LIMIT at which smoothing of the output begins(minimum positive value of voltage must exist between the CNTL_UPPER input and theCNTL_LOWER input at all times). For this model, then, the limit range represents thedelta WITH RESPECT TO THE OUTPUT LEVEL at which smoothing occurs. Thus,for an input gain of 2.0 and output limits of 1.0 and -1.0 volts, the output will begin tosmooth out at 0.9 volts, which occurs when the input value is at 0.4. Note also thatthe Controlled Limiter code tests the input values of cntl_lower and cntl_upper to makesure that they are spaced far enough apart to guarantee the existence of a linear range between them. The range is calculated as the difference between (cntl_upper - upper_delta- limit_range) and (cntl_lower + lower_delta + limit_range) and must be greater than orequal to zero. Note that when the limit range is specified as a fractional value, the limitrange used in the above is taken as the calculated fraction of the difference between cntlupper and cntl lower. Still, the potential exists for too great a limit range value to bespecified for proper operation, in which case the model will return an error message.Example SPICE Usage:a6 3 6 8 4 varlimit...model varlimit climit(in_offset=0.1 gain=2.5 upper_delta=0.0+ lower_delta=0.0 limit_range=0.10 fraction=FALSE)
12.2.7
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:
cm_pwlpwl"piecewise linear controlled source"in"input"inv[v,vd,i,id,vnam]nono
x_array"x-element array"realyes
y_array"y-element array"realyes
152
Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:STATIC_VAR_TABLE:Static_Var_Name:Data_Type:
[2 -]no
input_domain"input sm. domain"real0.01[1e-12 0.5]noyes
fraction"smoothing %/abs switch"booleanTRUEnoyes
last_x_valuepointer Description: "iteration holdingvariable for limiting"
Description: The Piece-Wise Linear Controlled Source is a single input, single output function similar to the Gain Block. However, the output of the PWL Source is not necessarilylinear for all values of input. Instead, it follows an I/O relationship specified by you viathe x_array and y_array coordinates. This is detailed below.The x_array and y_array values represent vectors of coordinate points on the x and y axes,respectively. The x_array values are progressively increasing input coordinate points, andthe associated y_array values represent the outputs at those points. There may be as fewas two (x_array[n], y_array[n]) pairs specified, or as many as memory and simulationspeed allow. This permits you to very finely approximate a non-linear function by capturing multiple input-output coordinate points.Two aspects of the PWL Controlled Source warrant special attention. These are the handling of endpoints and the smoothing of the described transfer function near coordinatepoints.In order to fully specify outputs for values of in outside of the bounds of the PWLfunction (i.e., less than x_array[0] or greater than x_array[n], where n is the largest userspecified coordinate index), the PWL Controlled Source model extends the slope foundbetween the lowest two coordinate pairs and the highest two coordinate pairs. This hasthe effect of making the transfer function completely linear for in less than x_array[0]and in greater than x_array[n]. It also has the potentially subtle effect of unrealisticallycausing an output to reach a very large or small value for large inputs. You should thuskeep in mind that the PWL Source does not inherently provide a limiting capability.In order to diminish the potential for non-convergence of simulations when using thePWL block, a form of smoothing around the x_array, y_array coordinate points is necessary. This is due to the iterative nature of the simulator and its reliance on smooth firstderivatives of transfer functions in order to arrive at a matrix solution. Consequently, theinput_domain and fraction parameters are included to allow you some control overthe amount and nature of the smoothing performed.Fraction is a switch that is either TRUE or FALSE. When TRUE (the default setting),the simulator assumes that the specified input domain value is to be interpreted as a fractional figure. Otherwise, it is interpreted as an absolute value. Thus, if fraction=TRUEand input_domain=0.10, The simulator assumes that the smoothing radius about each coordinate point is to be set equal to 10% of the length of either the x_array segment above
153
each coordinate point, or the x_array segment below each coordinate point. The specificsegment length chosen will be the smallest of these two for each coordinate point.On the other hand, if fraction=FALSE and input=0.10, then the simulator will beginsmoothing the transfer function at 0.10 volts (or amperes) below each x_array coordinate and will continue the smoothing process for another 0.10 volts (or amperes) aboveeach x_array coordinate point. Since the overlap of smoothing domains is not allowed,checking is done by the model to ensure that the specified input domain value is not excessive.One subtle consequence of the use of the fraction=TRUE feature of the PWL ControlledSource is that, in certain cases, you may inadvertently create extreme smoothing of functions by choosing inappropriate coordinate value points. This can be demonstrated byconsidering a function described by three coordinate pairs, such as (-1,-1), (1,1), and(2,1). In this case, with a 10% input_domain value specified (fraction=TRUE, input domain=0.10), you would expect to see rounding occur between in=0.9 and in=1.1, andnowhere else. On the other hand, if you were to specify the same function using thecoordinate pairs (-100,-100), (1,1) and (201,1), you would find that rounding occurs between in=-19 and in=21. Clearly in the latter case the smoothing might cause an excessivedivergence from the intended linearity above and below in=1.Example SPICE Usage:a7 2 4 xfer_cntl1...model xfer_cntl1 pwl(x_array=[-2.0 -1.0 2.0 4.0 5.0]+y_array=[-0.2 -0.2 0.1 2.0 10.0]+input_domain=0.05 fraction=TRUE)
12.2.8
Filesource
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:
cm_filesourcefilesource"File Source"out"output"outv[v,vd,i,id]yes[1 -]notimeoffset"time offset"real0.0-
timescale"timescale"real1.0-
154:
noyes
timerelative"relative time"booleanFALSEnoyes
amplstep"step amplitude"booleanFALSEnoyes
amploffset"ampl offset"realyes[1 -]yes
amplscale"amplscale"realyes[1 -]yes
file"file name"string"filesource.txt"noyes
Description: The File Source is similar to the Piece-Wise Linear Source, except that the waveform data is read from a file instead of being taken from parameter vectors.The file format is line oriented ASCII. # and ; are comment characters; all characters froma comment character until the end of the line are ignored.Each line consists of two or more real values. The first value is the time; subsequentvalues correspond to the outputs. Values are separated by spaces.Time values are absolute and must be monotonically increasing, unless timerelative is setto TRUE, in which case the values specify the interval between two samples and must bepositive. Waveforms may be scaled and shifted in the time dimension by setting timescaleand timeoffset.Amplitudes can also be scaled and shifted using amplscale and amploffset. Amplitudesare normally interpolated between two samples, unless amplstep is set to TRUE.Note: The parameter filename in file="filename" has to give an absolute path or name afile placed in an input directory specified with the environmental variable NGSPICE_INPUT_DIR(see 16.7).
155
12.2.9
multi_input_pwl block
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:
cm_multi_input_pwlmulti_input_pwl"multi_input_pwl block"in"input array"invd[vd,id]yes[2 -]no
out"output"outvd[vd,id]nono
x"x array"real0.0yes[2 -]no
y"y array"real0.0yes[2 -]no
model"model type"string
156
Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
"and"noyes
Description: Multi-input gate voltage controlled voltage source that supports and or or gating.The xs and ys represent the piecewise linear variation of output (y) as a function ofinput (x). Only one input determines the state of the outputs, seleczable by the parametermodel. and: the smallest value of all the inputs is chosen as the controlling input anddetermines the output value, or: the smallest value of all the inputs is chosen as thecontrolling input and determines the output value.Example SPICE Usage:a82 [1 0 2 0 3 0] 7 0 pwlm...model pwlm multi_input_pwl((x_array=[-2.0 -1.0 2.0 4.0 5.0]+y_array=[-0.2 -0.2 0.1 2.0 10.0]+model="and")
12.2.10
Analog Switch
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:
cm_aswitchaswitch"analog switch"cntl_in"input"inv[v,vd,i,id]nono
out"resistive output"outgd[gd]nono
cntl_offcntl_on"control off value" "control on value"realreal0.01.0nonoyesyesr_off"off resistance"
log"log/linear switch"
Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
157
real1.0e12noyes
booleanTRUEnoyes
r_on"on resistance"real1.0noyes
Description: The Analog Switch is a resistor that varies either logarithmically or linearly between specified values of a controlling input voltage or current. Note that the input isnot internally limited. Therefore, if the controlling signal exceeds the specified OFF stateor ON state value, the resistance may become excessively large or excessively small (inthe case of logarithmic dependence), or may become negative (in the case of linear dependence). For the experienced user, these excursions may prove valuable for modelingcertain devices, but in most cases you are advised to add limiting of the controlling inputif the possibility of excessive control value variation exists.Example SPICE Usage:a8 3 (6 7) switch3...model switch3 aswitch(cntl_off=0.0 cntl_on=5.0 r_off=1e6+r_on=10.0 log=TRUE)
12.2.11
Zener Diode
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:
cm_zenerzener"zener diode"z"zener"inoutgd[gd]nono
158
Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:STATIC_VAR_TABLE:Static_Var_Name:Data_Type:Description:
v_breakdown"breakdown voltage"real[1.0e-6 1.0e6]nono
i_breakdown"breakdown current"real2.0e-2[1.0e-9 -]noyes
i_sat"saturation current"real1.0e-12[1.0e-15 -]noyes
n_forward"forward emission coefficient"real1.0[0.1 10]noyes
limit_switch"switch for on-board limiting (convergence aid)"booleanFALSEnoyesprevious_voltagepointer"iteration holding variable for limiting"
Description: The Zener Diode models the DC characteristics of most zeners. This modeldiffers from the Diode/Rectifier by providing a user-defined dynamic resistance in thereverse breakdown region. The forward characteristic is defined by only a single point,since most data sheets for zener diodes do not give detailed characteristics in the forwardregion.The first three parameters define the DC characteristics of the zener in the breakdownregion and are usually explicitly given on the data sheet.The saturation current refers to the relatively constant reverse current that is producedwhen the voltage across the zener is negative, but breakdown has not been reached. Thereverse leakage current determines the slight increase in reverse current as the voltageacross the zener becomes more negative. It is modeled as a resistance parallel to thezener with value v breakdown / i rev.Note that the limit switch parameter engages an internal limiting function for the zener.This can, in some cases, prevent the simulator from converging to an unrealistic solutionif the voltage across or current into the device is excessive. If use of this feature fails toyield acceptable results, the convlimit option should be tried (add the following statementto the SPICE input deck: .options convlimit)
159
12.2.12
Current Limiter
NAME_TABLE:
cm_ilimitilimit"current limiter block"in"input"inv[v,vd]nono
pos_pwr"positive power supply"inoutg[g,gd]noyes
neg_pwr"negative power supply"inoutg[g,gd]noyes
out"output"inoutg[g,gd]nono
r_out_source"sourcing resistance"real1.0[1.0e-9 1.0e9]no-
r_out_sink"sinking resistance"real1.0[1.0e-9 1.0e9]no-
160:
i_limit_source"current sourcing limit"real[1.0e-12 -]noyesi_limit_sink"current sinking limit"real[1.0e-12 -]noyesv_pwr_range"upper & lower powersupply smoothing range"real1.0e-6[1.0e-15 -]noyes
i_source_range"sourcing currentsmoothing range"real1.0e-9[1.0e-15 -]noyes
i_sink_range"sinking current smoothing range"real1.0e-9[1.0e-15 -]noyesr_out_domain"internal/external voltage delta smoothing range"real1.0e-9[1.0e-15 -]noyes
Description: The Current Limiter models the behavior of an operational amplifier or compara-
161
tor device at a high level of abstraction. All of its pins act as inputs; three of the fouralso act as outputs. The model takes as input a voltage value from the in connector. Itthen applies an offset and a gain, and derives from it an equivalent internal voltage (veq),which it limits to fall between pos pwr and neg pwr. If veq is greater than the outputvoltage seen on the out connector, a sourcing current will flow from the output pin.Conversely, if the voltage is less than vout, a sinking current will flow into the output pin.Depending on the polarity of the current flow, either a sourcing or a sinking resistancevalue (r_out_source, r_out_sink) is applied to govern the vout/i_out relationship. Thechosen resistance will continue to control the output current until it reaches a maximumvalue specified by either i_limit_source or i_limit_sink. The latter mimics the currentlimiting behavior of many operational amplifier output stages.During all operation, the output current is reflected either in the pos_pwr connector current or the neg_pwr current, depending on the polarity of i_out. Thus, realistic powerconsumption as seen in the supply rails is included in the model.The user-specified smoothing parameters relate to model operation as follows: v_pwr_rangecontrols the voltage below vpos_pwr and above vneg_pwr inputs beyond which veq [=gain * (vin + voffset)] is smoothed; i_source_range specifies the current below i_limit_sourceat which smoothing begins, as well as specifying the current increment above i_out=0.0 atwhich i_pos_pwr begins to transition to zero; i_sink_range serves the same purpose withrespect to i_limit_sink and i_neg_pwr that i_source_range serves for i_limit_source &i_pos_pwr; r_out_domain specifies the incremental value above and below (veq-vout)=0.0at which r_out will be set to r_out_source and r_out_sink, respectively. For values of(veq-vout) less than r_out_domain and greater than -r_out_domain, r_out is interpolatedsmoothly between r_out_source & r_out_sink.Example SPICE Usage:a10 3 10 20 4 amp3...model amp3 ilimit(in_offset=0.0 gain=16.0 r_out_source=1.0+r_out_sink=1.0 i_limit_source=1e-3+i_limit_sink=10e-3 v_pwr_range=0.2+i_source_range=1e-6 i_sink_range=1e-6+r_out_domain=1e-6)
12.2.13
Hysteresis Block
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:
cm_hysthyst"hysteresis block"in"input"inv[v,vd,i,id]no
out"output"outv[v,vd,i,id]no
162:
in_low"input low value"real0.0noyes
in_high"input high value"real1.0noyes
hyst"hysteresis"real0.1[0.0 -]noyes
input_domain"input smoothing domain"real0.01noyes
fraction"smoothing fraction/absolute value switch"booleanTRUEnoyes
Description: The Hysteresis block is a simple buffer stage that provides hysteresis of the outputwith respect to the input. The in low and in high parameter values specify the centervoltage or current inputs about which the hysteresis effect operates. The output valuesare limited to out lower limit and out upper limit. The value of hyst is added to the inlow and in high points in order to specify the points at which the slope of the hysteresisfunction would normally change abruptly as the input transitions from a low to a highvalue. Likewise, the value of hyst is subtracted from the in high and in low values inorder to specify the points at which the slope of the hysteresis function would normallychange abruptly as the input transitions from a high to a low value. In fact, the slope of the
163
hysteresis function is never allowed to change abruptly but is smoothly varied wheneverthe input domain smoothing parameter is set greater than zero.Example SPICE Usage:a11 1 2 schmitt1...model schmitt1 hyst(in_low=0.7 in_high=2.4 hyst=0.5+out_lower_limit=0.5 out_upper_limit=3.0+input_domain=0.01 fraction=TRUE)
12.2.14
Differentiator:
cm_d_dtd_dt"time-derivative block"in"input"inv[v,vd,i,id]nono
out_lower_limit"output lower limit"realnoyes
out_upper_limit"output upper limit"realnoyes
limit_range"upper & lower limit smoothing range"real
164
1.0e-6noyes
Description: The Differentiator block is a simple derivative stage that approximates the timederivative of an input signal by calculating the incremental slope of that signal since theprevious time point. The block also includes gain and output offset parameters to allowfor tailoring of the required signal, and output upper and lower limits to prevent convergence errors resulting from excessively large output values. The incremental value ofoutput below the output upper limit and above the output lower limit at which smoothingbegins is specified via the limit range parameter. In AC analysis, the value returned isequal to the radian frequency of analysis multiplied by the gain.Note that since truncation error checking is not included in the d_dt block, it is not recommended that the model be used to provide an integration function through the use ofa feedback loop. Such an arrangement could produce erroneous results. Instead, youshould make use of the "integrate" model, which does include truncation error checkingfor enhanced accuracy.Example SPICE Usage:a12 7 12 slope_gen...model slope_gen d_dt(out_offset=0.0 gain=1.0+out_lower_limit=1e-12 out_upper_limit=1e12+limit_range=1e-9)
12.2.15
Integrator
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:
cm_intint"time-integration block"in"input"inv[v,vd,i,id]nono
in_offset"input offset"real0.0
gain"gain"real1.0:
165
limit_range"upper & lower limit smoothing range"real1.0e-6noyesout_ic"output initial condition"real0.0noyes
Description: The Integrator block is a simple integration stage that approximates the integralwith respect to time of an input signal. The block also includes gain and input offsetparameters to allow for tailoring of the required signal, and output upper and lower limitsto prevent convergence errors resulting from excessively large output values. Note thatthese limits specify integrator behavior similar to that found in an operational amplifierbased integration stage, in that once a limit is reached, additional storage does not occur.Thus, the input of a negative value to an integrator which is currently driving at the outupper limit level will immediately cause a drop in the output, regardless of how longthe integrator was previously summing positive inputs. The incremental value of outputbelow the output upper limit and above the output lower limit at which smoothing beginsis specified via the limit range parameter. In AC analysis, the value returned is equal tothe gain divided by the radian frequency of analysis.Note that truncation error checking is included in the int block. This should providefor a more accurate simulation of the time integration function, since the model willinherently request smaller time increments between simulation points if truncation errorswould otherwise be excessive.
166
12.2.16:
cm_s_xfers_xfer"s-domain transfer function"in"input"inv[v,vd,i,id]nono
num_coeff"numerator polynomial coefficients"realyes[1 -]noden_coeff"denominator polynomial coefficients"realyes
Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
167
[1 -]noint_ic"integrator stage initial conditions"real0.0yesden_coeffyesdenormalized_freq"denorm. corner freq.(radians) for 1 rad/s coeffs"real1.0noyes
Description: The s-domain transfer function is a single input, single output transfer functionin the Laplace transform variable s that allows for flexible modulation of the frequencydomain characteristics of a signal. Ac and transient simulations are supported. The codemodel may be configured to produce an arbitrary s-domain transfer function with thefollowing restrictions:1. The degree of the numerator polynomial cannot exceed thatof the denominator polynomial in the variable "s".2. The coefficients for a polynomial must be statedexplicitly. That is, if a coefficient is zero, it must beincluded as an input to the num coeff or den coeff vector.The order of the coefficient parameters is from that associated with the highest-powered termdecreasing to that of the lowest. Thus, for the coefficient parameters specified below, the equation in s is shown:.model filter s_xfer(gain=0.139713 int_ic=[0 0 0]+ num_coeff=[1.0 0.0 0.07464102]+ den_coeff=[1.0 0.998942 0.01170077])...specifies a transfer function of the form...2
s +0.7464102}N(s) = 0.139713 { s2 +0.998942s+0.00117077
The s-domain transfer function includes gain and in_offset (input offset) parameters to allowfor tailoring of the required signal. There are no limits on the internal signal values or onthe output value of the s-domain transfer function, so you are cautioned to specify gain and
168
coefficient values that will not cause the model to produce excessively large values. In ACanalysis, the value returned is equal to the real and imaginary components of the total s-domaintransfer function at each frequency of interest.The denormalized_freq term allows you to specify coefficients for a normalized filter (i.e. onein which the frequency of interest is 1 rad/s). Once these coefficients are included, specifyingthe denormalized frequency value shifts the corner frequency to the actual one of interest. Asan example, the following transfer function describes a Chebyshev low-pass filter with a corner(pass-band) frequency of 1 rad/s:1.0}N(s) = 0.139713 { s2 +1.09773s+1.10251
In order to define an s_xfer model for the above, but with the corner frequency equal to 1500rad/s (9425 Hz), the following instance and model lines would be needed:a12 node1 node2 cheby1.model cheby1 s_xfer(num_coeff=[1] den_coeff=[1 1.09773 1.10251]+int_ic=[0 0 0] denormalized_freq=1500)In the above, you add the normalized coefficients and scale the filter through the use of thedenormalized freq parameter. Similar results could have been achieved by performing the denormalization prior to specification of the coefficients, and setting denormalized freq to thevalue 1.0 (or not specifying the frequency, as the default is 1.0 rad/s) Note in the above thatfrequencies are ALWAYS SPECIFIED AS RADIANS/SECOND.Truncation error checking is included in the s-domain transfer block. This should provide formore accurate simulations, since the model will inherently request smaller time incrementsbetween simulation points if truncation errors would otherwise be excessive.The int_ic parameter is an array that must be of the same size as the array of values specifiedfor the den_coeff parameter. Even if a 0 start value is required, you have to add the specificint_ic vector to the set of coefficients (see the examples above and below).Example SPICE Usage:a14 9 22 cheby_LP_3KHz...model cheby_LP_3KHz s_xfer(in_offset=0.0 gain=1.0 int_ic=[0 0 0]+num_coeff=[1.0]+den_coeff=[1.0 1.42562 1.51620])
12.2.17
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:
cm_slewslew"A simple slew rate follower block"in
out:
169
"input"inv[v,vd,i,id]nono
"output"outv[v,vd,i,id]nono
rise_slope"maximum rising slope value"real1.0e9noyesfall_slope"maximum falling slope value"real1.0e9noyesrange"smoothing range"real0.1noyes
Description: This function is a simple slew rate block that limits the absolute slope of theoutput with respect to time to some maximum or value. The actual slew rate effects ofover-driving an amplifier circuit can thus be accurately modeled by cascading the amplifier with this model. The units used to describe the maximum rising and falling slopevalues are expressed in volts or amperes per second. Thus a desired slew rate of 0.5 V/swill be expressed as 0.5e+6, etc.The slew rate block will continue to raise or lower its output until the difference betweenthe input and the output values is zero. Thereafter, it will resume following the input signal, unless the slope again exceeds its rise or fall slope limits. The range input specifiesa smoothing region above or below the input value. Whenever the model is slewing andthe output comes to within the input + or - the range value, the partial derivative of theoutput with respect to the input will begin to smoothly transition from 0.0 to 1.0. Whenthe model is no longer slewing (output = input), dout/din will equal 1.0.
170
12.2.18
Inductive Coupling
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
cm_lcouplelcouple"inductive coupling (for use with core model)"l"inductor"inouthd[h,hd]nono
mmf_out"mmf output (in ampere-turns)"inouthd[hd]nono
num_turns"number of inductor turns"real1.0noyes
Description: This function is a conceptual model which is used as a building block to create awide variety of inductive and magnetic circuit models. This function is normally used inconjunction with the core model, but can also be used with resistors, hysteresis blocks,etc. to build up systems which mock the behavior of linear and nonlinear components.The lcouple takes as an input (on the l port) a current. This current value is multiplied bythe num_turns value, N, to produce an output value (a voltage value which appears on themmf_out port). The mmf_out acts similar to a magnetomotive force in a magnetic circuit;when the lcouple is connected to the core model, or to some other resistive device, acurrent will flow. This current value (which is modulated by whatever the lcouple isconnected to) is then used by the lcouple to calculate a voltage seen at the l port. Thevoltage is a function of the derivative with respect to time of the current value seen atmmf_out.The most common use for lcouples will be as a building block in the construction oftransformer models. To create a transformer with a single input and a single output, youwould require two lcouple models plus one core model. The process of building upsuch a transformer is described under the description of the core model, below.Example SPICE Usage:a150 (7 0) (9 10) lcouple1.model lcouple1 lcouple(num_turns=10.0)
12.2.19
171
Magnetic Core
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector::
cm_corecore"magnetic core"mc"magnetic core"inoutgd[g,gd]noH_array"magnetic field array"realyes[2 -]no
B_array"flux density array"realyes[2 -]no
area"cross-sectional area"realnono
length"core length"realnono
input_domain"input sm. domain"real0.01[1e-12 0.5]noyesfraction"smoothing fraction/abs switch"booleanTRUEno
172
yesmode"mode switch (1 = pwl, 2 = hyst)"int1[1 2]noyesin_low"input low value"real0.0noyes
hyst"hysteresis"real0.1[0 -]noyes
Description: This function is a conceptual model which is used as a building block to createa wide variety of inductive and magnetic circuit models. This function is almost alwaysexpected to be used in conjunction with the lcouple model to build up systems whichmock the behavior of linear and nonlinear magnetic components. There are two fundamental modes of operation for the core model. These are the pwl mode (which is thedefault, and which is the most likely to be of use to you) and the hysteresis mode. Theseare detailed below.PWL Mode (mode = 1)
173
The core model in PWL mode takes as input a voltage which it treats as a magnetomotive force(mmf) value. This value is divided by the total effective length of the core to produce a valuefor the Magnetic Field Intensity, H. This value of H is then used to find the corresponding FluxDensity, B, using the piecewise linear relationship described by you in the H array / B arraycoordinate pairs. B is then multiplied by the cross-sectional area of the core to find the Fluxvalue, which is output as a current. The pertinent mathematical equations are listed below:H = mmf =L, where L = LengthHere H, the Magnetic Field Intensity, is expressed in ampere-turns/meter.B = f (H)The B value is derived from a piecewise linear transfer function described to the model viathe (H_array[],B_array[]) parameter coordinate pairs. This transfer function does not includehysteretic effects; for that, you would need to substitute a HYST model for the core. = BA, where A = AreaThe final current allowed to flow through the core is equal to . This value in turn is used bythe "lcouple" code model to obtain a value for the voltage reflected back across its terminals tothe driving electrical circuit.The following example code shows the use of two lcouple models and one core model toproduce a simple primary/secondary transformer.Example SPICE Usage:a1 (2 0) (3 0) primary.model primary lcouple (num_turns = 155)a2 (3 4) iron_core.model iron_core core (H_array = [-1000 -500 -375 -250 -188 -125 -63 0+63 125 188 250 375 500 1000]+B_array = [-3.13e-3 -2.63e-3 -2.33e-3 -1.93e-3+-1.5e-3 -6.25e-4 -2.5e-4 0 2.5e-4+6.25e-4 1.5e-3 1.93e-3 2.33e-3+2.63e-3 3.13e-3]+area = 0.01 length = 0.01)a3 (5 0) (4 0) secondary.model secondary lcouple (num_turns = 310)HYSTERESIS Mode (mode = 2)The core model in HYSTERESIS mode takes as input a voltage which it treats as a magnetomotive force (mmf) value. This value is used as input to the equivalent of a hysteresis code modelblock. The parameters defining the input low and high values, the output low and high values,and the amount of hysteresis are as in that model. The output from this mode, as in PWL mode,is a current value which is seen across the mc port. An example of the core model used in thisfashion is shown below:
174
12.2.20
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:
cm_sinesine"controlled sine wave oscillator"cntl_in"control input"inv[v,vd,i,id]nono
cntl_array"control array"real0.0yes[2 -]no
freq_array"frequency array"real1.0e3[0 -]yescntl_arrayno
out_lowout_high"output peak low value" "output peak high value"realreal-1.01.0-
Vector:Vector_Bounds:Null_Allowed:
175
Description: This function is a controlled sine wave oscillator with parametrizable values oflow and high peak output. It takes an input voltage or current value. This value is used asthe independent variable in the piecewise linear curve described by the coordinate pointsof the cntl array and freq array pairs. From the curve, a frequency value is determined,and the oscillator will output a sine wave at that frequency. From the above, it is easyto see that array sizes of 2 for both the cntl array and the freq array will yield a linearvariation of the frequency with respect to the control input. Any sizes greater than 2 willyield a piecewise linear transfer characteristic. For more detail, refer to the description ofthe piecewise linear controlled source, which uses a similar method to derive an outputvalue given a control input.Example SPICE Usage:asine 1 2 in_sine.model in_sine sine(cntl_array = [-1 0 5 6]+freq_array=[10 10 1000 1000] out_low = -5.0+out_high = 5.0)
12.2.21
cm_triangletriangle"controlled triangle wave oscillator"cntl_in"control input"inv[v,vd,i,id]nono
out_lowout_high"output peak low value" "output peak high value"
176
real-1.0noyes
real1.0noyes
rise_duty"rise time duty cycle"real0.5[1e-10 0.999999999]noyes
12.2.22
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:
cm_squaresquare"controlled square wave oscillator"cntl_in"control input"inv[v,vd,i,id]nono
PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER.TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector: noVector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
177
out_lowout_high"output peak low value" "output peak high value"realreal-1.01.0nonoyesyesduty_cycle"duty cycle"real0.5[1e-6 0.999999]
rise_time"output rise time"real1.0e-9-
fall_time"output fall time"real1.0e-9noyes
Description: This function is a controlled square wave oscillator with parametrizable valuesof low and high peak output, duty cycle, rise time, and fall time. It takes an input voltageor current value. This value is used as the independent variable in the piecewise linearcurve described by the coordinate points of the cntl_array and freq_array pairs. From thecurve, a frequency value is determined, and the oscillator will output a square wave atthat frequency.From the above, it is easy to see that array sizes of 2 for both the cntl_array and thefreq_array will yield a linear variation of the frequency with respect to the control input.Any sizes greater than 2 will yield a piecewise linear transfer characteristic. For moredetail, refer to the description of the piecewise linear controlled source, which uses asimilar method to derive an output value given a control input.
178
12.2.23
Controlled One-Shot
cm_oneshotoneshot"controlled one-shot"clk"clock input"inv[v,vd,i,id]nono
cntl_in"control input"inv[v,vd,i,id]noyes
clear"clear signal"inv[v,vd,i,id]noyes
clk_trig"clock trigger value"real0.5nono
retrig"retrigger switch"booleanFALSEnoyes
pos_edge_trig"positive/negative edge trigger switch"booleanTRUEno-
179
nocntl_array"control array"real0.0yesyes
pw_array"pulse width array"real1.0e-6[0.00 -]yescntl_arrayyes
out_low"output low value"real0.0noyes
out_high"output high value"real1.0noyes
rise_time"output rise time"real1.0e-9noyes
rise_delay"output delay from trigger"real1.0e-9noyesfall_delay"output delay from pw"real1.0e-9noyes
Description: This function is a controlled oneshot with parametrizable values of low and highpeak output, input trigger value level, delay, and output rise and fall times. It takes an
180
12.2.24
Capacitance Meter
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
cm_cmetercmeter"capacitance meter"in"input"inv[v,vd,i,id]nono
Description: The capacitance meter is a sensing device which is attached to a circuit nodeand produces as an output a scaled value equal to the total capacitance seen on its inputmultiplied by the gain parameter. This model is primarily intended as a building block for
181
other models which must sense a capacitance value and alter their behavior based uponit.Example SPICE Usage:atest1 1 2 ctest.model ctest cmeter(gain=1.0e12)
12.2.25
Inductance Meter
cm_lmeterlmeter"inductance meter"in"input"inv[v,vd,i,id]nono
Description: The inductance meter is a sensing device which is attached to a circuit nodeand produces as an output a scaled value equal to the total inductance seen on its inputmultiplied by the gain parameter. This model is primarily intended as a building block forother models which must sense an inductance value and alter their behavior based uponit.Example SPICE Usage:atest2 1 2 ltest.model ltest lmeter(gain=1.0e6)
12.2.26
Memristor
NAME_TABLE:C_Function_Name:Spice_Model_Name:
cm_memristormemristor
182:
"Memristor Interface"memris"memristor terminals"inoutgd[gd]nonormin"minimum resistance"real10.0nono
rmax"maximum resistance"real10000.0nono
rinit"initial resistance"real7000.0nono
vt"threshold"real0.0nono
alpha"model parameter 1"real0.0nono
beta"model parameter 2"real1.0nono
Description: The memristor is a two-terminal resistor with memory, whose resistance dependson the time integral of the voltage across its terminals. rmin and rmax provide the lowerand upper limits of the resistance, rinit is its starting value (no voltage applied so far).The voltage has to be above a threshold vt to become effective in changing the resistance.alpha and beta are two model parameters. The memristor code model is derived from aSPICE subcircuit published in [23].Example SPICE Usage:amen 1 2 memr.model memr memristor (rmin=1k rmax=10k rinit=7k+ alpha=0 beta=2e13 vt=1.6)
12.3
183
Hybrid Models
The following hybrid models are supplied with XSPICE. The descriptions included below consist of the model Interface Specification File and a description of the models operation. Thisis followed by an example of a simulator-deck placement of the model, including the .MODELcard and the specification of all available parameters.A note should be made with respect to the use of hybrid models for other than simple digital-toanalog and analog-to-digital translations. The hybrid models represented in this section addressthat specific need, but in the development of user-defined nodes you may find a need to translatenot only between digital and analog nodes, but also between real and digital, real and int, etc.In most cases such translations will not need to be as involved or as detailed as shown in thefollowing.
12.3.1:
cm_dac_bridgedac_bridge"digital-to-analog node bridge"in"input"ind[d]yesno
out"output"outv[v,vd,i,id,d]yesno
out_low"0-valued analog output"real0.0noyesout.high"1-valued analog output"real1.0noyes
184
Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
out_undef"U-valued analog output"real0.5noyes
input_load"input load (F)"real1.0e-12noyes
t_rise"rise time 0->1"real1.0e-9noyes
t_fall"fall time 1->0"real1.0e-9noyes
Description: The dac_bridge is the first of two node bridge devices designed to allow for theready transfer of digital information to analog values and back again. The second device isthe adc_bridge (which takes an analog value and maps it to a digital one).The dac_bridgetakes as input a digital value from a digital node. This value by definition may take ononly one of the values 0, 1 or U. The dac_bridge then outputs the value out_low,out_high or out_undef, or ramps linearly toward one of these final values from itscurrent analog output level. The speed at which this ramping occurs depends on the valuesof t_rise and t_fall. These parameters are interpreted by the model such that the riseor fall slope generated is always constant. Note that the dac_bridge includes test codein its cfunc.mod file for determining the presence of the out_undef parameter. If thisparameter is not specified by you, and if out_high and out_low values are specified,then out_undef is assigned the value of the arithmetic mean of out_high and out_low.This simplifies coding of output buffers, where typically a logic family will include anout_low and out_high voltage, but not an out_undef value. This model also posts an inputload value (in farads) based on the parameter input load.Example SPICE Usage:abridge1 [7] [2] dac1.model dac1 dac_bridge(out_low = 0.7 out_high = 3.5 out_undef = 2.2+input_load = 5.0e-12 t_rise = 50e-9+t_fall = 20e-9)
12.3.2
cm_adc_bridgeadc_bridge"analog-to-digital node bridge"in
185
"input"inv[v,vd,i,id,d]yesno
"output"outd[d]yesno
in_low"maximum 0-valued analog input"real1.0noyesin_high"minimum 1-valued analog input"real2.0noyesrise_delay"rise delay"real1.0e-9[1.0e-12 -]noyes
fall_delay"fall delay"real1.0e-9[1.0e-12 -]noyes
Description: The adc_bridge is one of two node bridge devices designed to allow for the readytransfer of analog information to digital values and back again. The second device is thedac_bridge (which takes a digital value and maps it to an analog one). The adc_bridgetakes as input an analog value from an analog node. This value by definition may bein the form of a voltage, or a current. If the input value is less than or equal to in_low,then a digital output value of 0 is generated. If the input is greater than or equal toin_high, a digital output value of 1 is generated. If neither of these is true, then a digitalUNKNOWN value is output. Note that unlike the case of the dac_bridge, no rampingtime or delay is associated with the adc_bridge. Rather, the continuous ramping of theinput value provides for any associated delays in the digitized signal.Example SPICE Usage:abridge2 [1] [8] adc_buff.model adc_buff adc_bridge(in_low = 0.3 in_high = 3.5)
186
12.3.3_d_oscd_osc"controlled digital oscillator"cntl_in"control input"inv[v,vd,i,id]nono
out"output"outd[d]nono
freq_array"frequency array"real1.0e6[0 -]yescntl_arrayno
duty_cycle"duty cycle"real0.5[1e-6 0.999999]noyes
init_phase"initial phase of output"real0[-180.0 +360.0]noyes
rise_delay"rise delay"real1e-9[0 -]noyes
fall_delay"fall delay"real1e-9[0 -]noyes
Description: The digital oscillator is a hybrid model which accepts as input a voltage or current. This input is compared to the voltage-to-frequency transfer characteristic specifiedby the cntl_array/freq_array coordinate pairs, and a frequency is obtained which represents a linear interpolation or extrapolation based on those pairs. A digital time-varyingsignal is then produced with this fundamental frequency.The output waveform, which is the equivalent of a digital clock signal, has rise and fall
187
delays which can be specified independently. In addition, the duty cycle and the phase ofthe waveform are also variable and can be set by you.Example SPICE Usage:a5 1 8 var_clock.model var_clock d_osc(cntl_array+freq_array+duty_cycle+rise_delay
12.3.4
====
[-2 -1 1 2][1e3 1e3 10e3 10e3]0.4 init_phase = 180.010e-9 fall_delay=8e-9)
NAME_TABLE:Spice_Model_Name: d_to_realC_Function_Name: ucm_d_to_realDescription: "Node bridge from digital to realPORT_TABLE:Port_Name:inenableoutDescription:"input""enable""output"Direction:ininoutDefault_Type:ddrealAllowed_Types: [d][d][real]Vector:nononoVector_Bounds: Null_Allowed:noyesnoPARAMETER_TABLE:Parameter_Name: zerooneDescription:"value for 0""value for 1"Data_Type:realrealDefault_Value: 0.01.0Limits:Vector:nonoVector_Bounds: Null_Allowed:yesyes
12.3.5
with enable"
delay"delay"real1e-9[1e-15 -]noyes
NAME_TABLE:Spice_Model_Name: real_delayC_Function_Name: ucm_real_delayDescription: "A Z ** -1 block working on real data"PORT_TABLE:Port_Name:inclkoutDescription:"input""clock""output"Direction:ininoutDefault_Type:realdrealAllowed_Types:[real][d][real]
188
Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
12.3.6
nono
delay"delay from clk to out"real1e-9[1e-15 -]noyes
NAME_TABLE:Spice_Model_Name:C_Function_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
real_gainucm_real_gain"A gain block for event-driven real data"in"input"inreal[real]nono
out"output"outreal[real]nono
delay"delay"real1.0e-9noyes
ic"initial condition"real0.0noyes
12.3.7
189
NAME_TABLE:Spice_Model_Name:C_Function_Name:Description:PORT_TABLE:Port_Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
12.4
real_to_vucm_real_to_v"Node bridge from real to analog voltage"in"input"inreal[real]nono
out"output"outv[v, vd, i, id]nono
transition_time"output transition time"real1e-9[1e-15 -]noyes
Digital Models
The following digital models are supplied with XSPICE. The descriptions included below consist of an example model Interface Specification File and a description of the models operation. This is followed by an example of a simulator-deck placement of the model, including the.MODEL card and the specification of all available parameters. Note that these models havenot been finalized at this time.Some information common to all digital models and/or digital nodes is included here. Thefollowing are general rules which should make working with digital nodes and models morestraightforward:1. All digital nodes are initialized to ZERO at the start of a simulation (i.e., when INIT=TRUE).This means that a model need not post an explicit value to an output node upon initialization if its output would normally be a ZERO (although posting such would certainlycause no harm).
12.4.1
Buffer
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:
cm_d_bufferd_buffer"digital one-bit-wide buffer"
190
PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
in"input"ind[d]nono
rise_delay"rise delay"real1.0e-9[1.0e-12 -]noyes
input_load"input load value (F)"real1.0e-12noyes
Description: The buffer is a single-input, single-output digital buffer which produces as outputa time-delayed copy of its input. The delays associated with an output rise and those associated with an output fall may be different. The model also posts an input load value (infarads) based on the parameter input load. The output of this model does NOT, however,respond to the total loading it sees on its output; it will always drive the output stronglywith the specified delays.Example SPICE Usage:a6 1 8 buff1.model buff1 d_buffer(rise_delay = 0.5e-9 fall_delay = 0.3e-9+input_load = 0.5e-12)
12.4.2
Inverter
cm_d_inverterd_inverter"digital one-bit-wide inverter"in
Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
191
"input"ind[d]nono
"output"outd[d]nono
12.4.3
And
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:
cm_d_andd_and"digital and gate"in"input"in
out"output"out
192
Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
d[d]yes[2 -]no
d[d]nono
Description: The digital and gate is an n-input, single-output and gate which produces anactive 1 value if, and only if, all of its inputs are also 1 values. If ANY of the inputs isa 0, the output will also be a 0;] 8 and1.model and1 d_and(rise_delay = 0.5e-9 fall_delay = 0.3e-9+input_load = 0.5e-12)
12.4.4
Nand
cm_d_nandd_nand"digital nand gate"in"input"in
193
Description: The digital nand gate is an n-input, single-output nand gate which producesan active 0 value if and only if all of its inputs are 1 values. If ANY of the inputsis a 0, the output will be a 1; 3] 8 nand1.model nand1 d_nand(rise_delay = 0.5e-9 fall_delay = 0.3e-9+input_load = 0.5e-12)
12.4.5
Or
cm_d_ord_or"digital or gate"in"input"in
194
12.4.6
Nor
cm_d_nord_nor"digital nor gate"in"input"in
195
Description: The digital nor gate is an n-input, single-output nor gate which produces anactive 0 value if at least one of its inputs is a 1 value. The gate produces a 0 valueif all inputs are 0; if neither of these two conditions holds, the output is unknown.The delays associated with an output rise and those associated with an output fall may bespecified independently. The model also posts an input load value (in farads) based on theparameter input load. The output of this model does NOT, however, respond to the totalloading it sees on its output; it will always drive the output strongly with the specifieddelays.Example SPICE Usage:anor12 [1 2 3 4] 8 nor12.model nor12 d_or(rise_delay = 0.5e-9 fall_delay = 0.3e-9+input_load = 0.5e-12)
12.4.7
Xor
cm_d_xord_xor"digital exclusive-or gate"in"input"in
196
Description: The digital xor gate is an n-input, single-output xor gate which produces anactive 1 value if an odd number of its inputs are also 1 values. The delays associatedwithor3.model xor3 d_xor(rise_delay = 0.5e-9 fall_delay = 0.3e-9+input_load = 0.5e-12)
12.4.8
Xnor
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:
cm_d_xnord_xnor"digital exclusive-nor gate"in"input"
out"output"
Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
197
ind[d]yes[2 -]no
outd[d]nono
Description: The digital xnor gate is an n-input, single-output xnor gate which produces anactive 0 value if an odd number of its inputs are also 1 values. It produces a 1 outputwhen an even number of 1 values occurs on its inputs. The delays associated withnor3.model xnor3 d_xnor(rise_delay = 0.5e-9 fall_delay = 0.3e-9+input_load = 0.5e-12)
12.4.9
Tristate
cm_d_tristated_tristate"digital tristate buffer"in
enable
198
"enable"ind[d]nono
delay"delay"real1.0e-9[1.0e-12 -]noyesinput_load"input load value (F)"real1.0e-12noyesenable_load"enable load value (F)"real1.0e-12noyes
Description: The digital tristate is a simple tristate gate which can be configured to allow foropen-collector behavior, as well as standard tristate behavior. The state seen on the inputline is reflected in the output. The state seen on the enable line determines the strength ofthe output. Thus, a ONE forces the output to its state with a STRONG strength. A ZEROforces the output to go to a HI_IMPEDANCE strength. The delays associated with anoutput state or strength change cannot be specified independently, nor may they be specified independently for rise or fall conditions; other gate models may be used to providesuch delays if needed. The model posts input and enable load values (in farads) basedon the parameters input load and enable.The output of this model does NOT, however,respond to the total loading it sees on its output; it will always drive the output with thespecified delay. Note also that to maintain the technology-independence of the model,any UNKNOWN input, or any floating input causes the output to also go UNKNOWN.Likewise, any UNKNOWN input on the enable line causes the output to go to an UNDETERMINED strength value.
199
12.4.10
Pullup
cm_d_pullupd_pullup"digital pullup resistor"out"output"outd[d]nonoload"load value (F)"real1.0e-12noyes
Description: The digital pullup resistor is a device which emulates the behavior of an analogresistance value tied to a high voltage level. The pullup may be used in conjunctionwith tristate buffers to provide open-collector wired or constructs, or any other logicalconstructs which rely on a resistive pullup common to many tristated output devices. Themodel posts an input load value (in farads) based on the parameters load.Example SPICE Usage:a2 9 pullup1.model pullup1 d_pullup(load = 20.0e-12)
12.4.11
Pulldown
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:
cm_d_pulldownd_pulldown"digital pulldown resistor"
200
Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
out"output"outd[d]nonoload"load value (F)"real1.0e-12noyes
Description: The digital pulldown resistor is a device which emulates the behavior of an analogresistance value tied to a low voltage level. The pulldown may be used in conjunctionwith tristate buffers to provide open-collector wired or constructs, or any other logicalconstructs which rely on a resistive pulldown common to many tristated output devices.The model posts an input load value (in farads) based on the parameters load.Example SPICE Usage:a4 9 pulldown1.model pulldown1 d_pulldown(load = 20.0e-12)
12.4.12
D Flip Flop
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PORT_TABLE:Port Name:Description:Direction:Default_Type:
cm_d_dffd_dff"digital d-type flip flop"data"input data"ind[d]nonoset"asynch. set"ind
clk"clock"ind[d]nonoreset"asynch. reset"ind:
201
[d]noyes
out"data output"outd[d]noyes
Nout"inverted data output"outd[d]noyes
clk_delay"delay from clk"real1.0e-9[1.0e-12 -]noyes
set_delay"delay from set"real1.0e-9[1.0e-12 -]noyes
reset_delay"delay from reset"real1.0[1.0e-12 -]noyes
ic"output initial state"int0[0 2]noyes
data_load"data load value (F)"real1.0e-12noyes
clk_load"clk load value (F)"real1.0e-12noyes
set_load"set load value (F)"real1.0e-12no-
reset_load"reset load (F)"real1.0e-12no-
202
Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
Description: The digital d-type flip flop is a one-bit, edge-triggered storage element which willstore data whenever the clk input line transitions from low to high (ZERO to ONE). Inaddition, asynchronous set and reset signals exist, and each of the three methods of changing the stored output of the d_dff have separate load values and delays associated withthem. Additionally, you may specify separate rise and fall delay values that are added tothose specified for the input lines; these allow for more faithful reproduction of the outputcharacteristics of different IC fabrication technologies.Note that any UNKNOWN input on the set or reset lines immediately results in an UNKNOWN output.Example SPICE Usage:a7 1 2 3 4 5 6 flop1.model flop1 d_dff(clk_delay = 13.0e-9 set_delay = 25.0e-9+reset_delay = 27.0e-9 ic = 2 rise_delay = 10.0e-9+fall_delay = 3e-9)
12.4.13
JK Flip Flop
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:
cm_d_jkffd_jkff"digital jk-type flip flop"j"j input"ind[d]nonoclk"clock"ind[d]
k"k input"ind[d]nono
Vector:Vector_Bounds:Null_Allowed:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_BoundsNull_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
203
nonoset"asynchronous set"ind[d]noyes
reset"asynchronous reset"ind[d]noyes
jk_load"j,k load values (F)"real1.0e-12noyes
204
PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
set_load"set load value (F)"real1.0e-12noyes
reset_load"reset load (F)"real1.0e-12noyes
Description: The digital jk-type flip flop is a one-bit, edge-triggered storage element whichwill store data whenever the clk input line transitions from low to high (ZERO to ONE).In addition, asynchronous set and reset signals exist, and each of the three methods ofchanging the stored output of the d_jkff have separate load values and delays associatedwith them. Additionally, you may specify separate rise and fall delay values that areadded to those specified for the input lines; these allow for more faithful reproduction ofthe output characteristics of different IC fabrication technologies.Note that any UNKNOWN inputs other than j or k cause the output to go UNKNOWNautomatically.Example SPICE Usage:a8 1 2 3 4 5 6 7 flop2.model flop2 d_jkff(clk_delay = 13.0e-9 set_delay = 25.0e-9+reset_delay = 27.0e-9 ic = 2 rise_delay = 10.0e-9+fall_delay = 3e-9)
12.4.14
cm_d_tffd_tff"digital toggle flip flop"t"toggle input"ind[d]no
clk"clock"ind[d]no
Vector_Bounds:Null_Allowed:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PORT.TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_BoundsNull_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:
205
set"set"ind[d]noyes
reset"reset"ind[d]noyes
t_loadclk_load"toggle load value (F)" "clk load value (F)"realreal1.0e-121.0e-12nonoyesyes
206
Parameter_Name:Description:Data_Type:Default.Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
Description: The digital toggle-type flip flop is a one-bit, edge-triggered storage element whichwill toggle its current state whenever the clk input line transitions from low to high (ZEROto ONE). In addition, asynchronous set and reset signals exist, and each of the three methods of changing the stored output of the d_tff have separate load values and delays associated with them. Additionally, you may specify separate rise and fall delay values thatare added to those specified for the input lines; these allow for more faithful reproductionof the output characteristics of different IC fabrication technologies.Note that any UNKNOWN inputs other than t immediately cause the output to go UNKNOWN.Example SPICE Usage:a8 2 12 4 5 6 3 flop3.model flop3 d_tff(clk_delay = 13.0e-9 set_delay = 25.0e-9+reset_delay = 27.0e-9 ic = 2 rise_delay = 10.0e-9+fall_delay = 3e-9 t_load = 0.2e-12)
12.4.15
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:
cm_d_srffd_srff"digital set-reset flip flop"s"set input"ind[d]no-
r"reset input"ind[d]no-
Null_Allowed:
207
clk"clock"ind[d]nonoset"asynchronous set"ind[d]noyes
reset_delay"delay from reset"real1.0e-9[1.0e-12 -]noyes
sr_load
clk_load
208
Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
Description: The digital sr-type flip flop is a one-bit, edge-triggered storage element whichwill store data whenever the clk input line transitions from low to high (ZERO to ONE).The value stored (i.e., the out value) will depend on the s and r input pin values, andwill be:out=ONEout=ZEROout=previous valueout=UNKNOWN
ifififif
In addition, asynchronous set and reset signals exist, and each of the three methods of changingthe stored output of the d_srff have separate load values and delays associated with them. Youmay also specify separate rise and fall delay values that are added to those specified for theinput lines; these allow for more faithful reproduction of the output characteristics of differentIC fabrication technologies.Note that any UNKNOWN inputs other than s and r immediately cause the output to go UNKNOWN.Example SPICE Usage:a8 2 12 4 5 6 3 14 flop7.model flop7 d_srff(clk_delay = 13.0e-9 set_delay = 25.0e-9+reset_delay = 27.0e-9 ic = 2 rise_delay = 10.0e-9+fall_delay = 3e-9)
12.4.16
209
D:
cm_d_dlatchd_dlatch"digital d-type latch"data"input data"ind[d]nono
enable"enable input"ind[d]nono
out"data output"outd[d]nono
Nout"inverter data output"outd[d]nono
data_delay"delay from data"real1.0e-9[1.0e-12 -]noyesenable_delay"delay from enable"real1.0e-9[1.0e-12 -]no
set_delay"delay from SET"real1.0e-9[1.0e-12 -]no
210
reset_delay"delay from RESET"real1.0e-9[1.0e-12 -]noyes
ic"output initial state"boolean0noyes
data_load"data load (F)"real1.0e-12noyes
enable_load"enable load value (F)"real1.0e-12noyes
Description: The digital d-type latch is a one-bit, level-sensitive storage element which willoutput the value on the data line whenever the enable input line is high (ONE). Thevalue on the data line is stored (i.e., held on the out line) whenever the enable line is low(ZERO).In addition, asynchronous set and reset signals exist, and each of the four methods ofchanging the stored output of the d_dlatch (i.e., data changing with enable=ONE, enablechanging to ONE from ZERO with a new value on data, raising set and raising reset) haveseparate delays associated with them. You may also specify separate rise and fall delayvalues that are added to those specified for the input lines; these allow for more faithful
211
12.4.17
Set-Reset:PORT_TABLE:Port Name:Description:Direction:
cm_d_srlatchd_srlatch"digital sr-type latch"s"set"ind[d]yes[2 -]no
r"reset"ind[d]yesrno
enable"enable"ind[d]nonoset"set"ind[d]noyes
out"data output"out
Nout"inverted data output"out
212
Default_Type:Allowed_Types:Vector: no:
d[d]
sr_delay"delay from s or r input change"real1.0e-9[1.0e-12 -]noyesenable_delay"delay from enable"real1.0e-9[1.0e-12 -]noyes
set_delay"delay from SET"real1.0e-9[1.0e-12 -]noyes
sr_loadenable_load"s & r input loads (F)" "enable load value (F)"realreal1.0e-121.0e-12nonoyesyesset_load"set load value (F)"real1.0e-12no
reset_load"reset load (F)"real1.0e-12no
213
Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
Description: The digital sr-type latch is a one-bit, level-sensitive storage element which willoutput the value dictated by the state of the s and r pins whenever the enable input lineis high (ONE). This value is stored (i.e., held on the out line) whenever the enable line islow (ZERO). The particular value chosen is as shown below:
Asynchronous set and reset signals exist, and each of the four methods of changing the storedoutput of the d srlatch (i.e., s/r combination changing with enable=ONE, enable changing toONE from ZERO with an output-changing combination of s and r, raising set and raising reset) have separate delays associated with them. You may also specify separate rise and falldelay values that are added to those specified for the input lines; these allow for more faithfulreproduction of the output characteristics of different IC fabrication technologies.Note that any UNKNOWN inputs other than on the s and r lines when enable=ZERO immediately cause the output to go UNKNOWN.Example SPICE Usage:a4 12 4 5 6 3 14 16 latch2.model latch2 d_srlatch(sr_delay = 13.0e-9 enable_delay = 22.0e-9+set_delay = 25.0e-9+reset_delay = 27.0e-9 ic = 2+rise_delay = 10.0e-9 fall_delay = 3e-9)
12.4.18
State Machine
cm_d_stated_state"digital state machine"in
clk
214
Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:
"input"ind[d]yes[1 -]yes
"clock"ind[d]nono
out"output"outd[d]yes[1 -]no
clk_delayreset_delay"delay from CLK""delay from RESET"realreal1.0e-91.0e-9[1.0e-12 -][1.0e-12 -]nonoyesyesParameter_Name:state_file"state transition specification file name"string"state.txt"nonoreset_state"default state on RESET & at DC"int0nonoinput_load"input loading capacitance (F)"real1.0e-12-
Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:PARAMETER_TABLE:Parameter_Name:Description:Data_Type:Default_Value:Limits:Vector:Vector_Bounds:Null_Allowed:
215
noyesclk_load"clock loading capacitance (F)"real1.0e-12noyesreset_load"reset loading capacitance (F)"real1.0e-12noyes
Description: The digital state machine provides for straightforward descriptions of clockedcombinatorial logic blocks with a variable number of inputs and outputs and with anunlimited number of possible states. The model can be configured to behave as virtuallyany type of counter or clocked combinatorial logic block and can be used to replace verylarge digital circuit schematics with an identically functional but faster representation.The d state model is configured through the use of a state definition file (state.in) whichresides in a directory of your choosing. The file defines all states to be understood by themodel, plus input bit combinations which trigger changes in state. An example state.infile is shown below:----------- begin file ------------* This is an example state.in file. This file* defines a simple 2-bit counter with one input. The* value of this input determines whether the counter counts* up (in = 1) or down (in = 0).0 0s 0s 0 -> 31 -> 11 0s 1z 0 -> 01 -> 22 1z 0s 0 -> 11 -> 33 1z 1z 0 -> 23 1z 1z 1 -> 0------------------ end file --------------Several attributes of the above file structure should be noted. First, ALL LINES IN THE FILEMUST BE ONE OF FOUR TYPES. These are:
216
12.4.19
Frequency Divider
NAME_TABLE:C_Function_Name:Spice_Model_Name:Description:PORT_TABLE:Port Name:Description:Direction:Default_Type:Allowed_Types:
cm_d_fdivd_fdiv"digital frequency divider"freq_in"frequency input"ind[d]
freq_out"frequency output"outd[d]:
217
div_factor"divide factor"int2[1 -]noyes
high_cycles"# of cycles for high out"int1[1 div_factor-1]noyes
i_count"divider initial count value"int0noyesrise_delay"rise delay"real1.0e-9[1.0e-12 -]yesinyes
fall_delay"fall delay"real1.0e-9[1.0e-12 -]yesinyes
freq_in_load"freq_in load value (F)"real1.0e-12noyes
Description: The digital frequency divider is a programmable step-down divider which acceptsan arbitrary divisor (div_factor), a duty-cycle term (high_cycles), and an initial countvalue (i_count). The generated output is synchronized to the rising edges of the inputsignal. Rise delay and fall delay on the outputs may also be specified independently.Example SPICE Usage:a4 3 7 divider.model divider d_fdiv(div_factor = 5 high_cycles = 3
218
++
12.4.20
RAM:
cm_d_ramd_ram"digital random-access memory"data_in"data input line(s)"ind[d]yes[1 -]no
data_out"data output line(s)"outd[d]yesdata_inno
addresswrite_en"address input line(s)" "write enable line"inindd[d][d]yesno[1 -]nonoselect"chip select line(s)"ind[d]yes[1 16]noselect_value"decimal active value for select line comparison"int1[0 32767]noyesic"initial bit state @ dc":
219
int2[0 2]noyesread_delay"read delay from address/select/write.en active"real100.0e-9[1.0e-12 -]noyesdata_loadaddress_load"data_in load value (F)" "addr. load value (F)"realreal1.0e-121.0e-12nonoyesyesselect_load"select load value (F)"real1.0e-12noyesenable_load"enable line load value (F)"real1.0e-12noyes
Description: The digital RAM is an M-wide, N-deep random access memory element withprogrammable select lines, tristated data out lines, and a single write/~read line. Thewidth of the RAM words (M) is set through the use of the word width parameter. Thedepth of the RAM (N) is set by the number of address lines input to the device. The value
220
12.4.21
Digital Source
cm_d_sourced_source"digital signal source"out"output"outd[d]yesnoinput_file"digital input vector filename"string"source.txt"no
221
noinput_load"input loading capacitance (F)"real1.0e-12nono
Description: The digital source provides for straightforward descriptions of digital signal vectors in a tabular format. The model reads input from the input file and, at the timesspecified in the file, generates the inputs along with the strengths listed.The format of the input file is as shown below. Note that comment lines are delineated throughthe use of a single * character in the first column of a line. This is similar to the waythe SPICE program handles comments.* T* i* m* e*0.00001.234e-91.376e-92.5e-72.5006e-75.0e-7
clockUu0s0s1s1s0s
nodeaUu1s0s0s1s1s
nodebUs1s1s1s1s1s
n . . .o . . .d . . .e . . .c . . .Uu . . .0z . . .0z . . .0z . . .0z . . .0z . . .
Note that in the example shown, whitespace (any combination of blanks, tabs, commas) is usedto separate the time and state/strength tokens. The order of the input columns is important; thefirst column is always interpreted to mean time. The second through the Nth columns mapto the out[0] through out[N-2] output nodes. A non-commented line which does not containenough tokens to completely define all outputs for the digital source will cause an error. Also,time values must increase monotonically or an error will result in reading the source file.Errors will also occur if a line exists in source.txt which is neither a comment nor vector line.The only exception to this is in the case of a line that is completely blank; this is treated asa comment (note that such lines often occur at the end of text within a file; ignoring these inparticular prevents nuisance errors on the part of the simulator).Example SPICE Usage:a3 [2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17] input_vector.model input_vector d_source(input_file = "source_simple.text")
222
12.5
The following prewritten node types are included with the XSPICE simulator. These shouldprovide you not only with valuable event-driven modeling capabilities, but also with examplesto use for guidance in creating new UDN (user defined node) types. You may access these nodedata by the plot (17.5.43) or eprint (17.5.23) commands.
12.5.1
The digital node type is directly built into the simulator. 12 digital node values are available.They are described by a two character string (the state/strength token). The first character (0,1, or U) gives the state of the node (logic zero, logic one, or unknown logic state). The secondcharacter (s, r, z, u) gives the "strength" of the logic state (strong, resistive, hi-impedance, orundetermined). So these are the values we have: 0s, 1s, Us, 0r, 1r, Ur, 0z, 1z, Uz, 0u, 1u, Uu.
12.5.2
The real node type provides for event-driven simulation with double-precision floating pointdata. This type is useful for evaluating sampled-data filters and systems. The type implementsall optional functions for User-Defined Nodes, including inversion and node resolution. Forinversion, the sign of the value is reversed. For node resolution, the resultant value at a node isthe sum of all values output to that node. The node is implemented as a user defined node inngspice/src/xspice/icm/xtraevt/real.
12.5.3
The int node type provides for event-driven simulation with integer data. This type is usefulfor evaluating round-off error effects in sampled-data systems. The type implements all optionalfunctions for User-Defined Nodes, including inversion and node resolution. For inversion, thesign of the integer value is reversed. For node resolution, the resultant value at a node is thesum of all values output to that node. The node is implemented as a user defined node inngspice/src/xspice/icm/xtraevt/int.
12.5.4
(Digital) Input/Output
The analog code models use the standard (analog) nodes provided by ngspice and thus are usingall the commands for sourcing, storing, printing, and plotting data.I/O for event nodes (digital, real, int, and UDNs) currently is much more limited to a few tools.For output you may use the plot (17.5.43) or eprint (17.5.23) commands. For input, you maycreate a test bench with existing code models (oscillator (12.3.3), frequency divider (12.4.19),state machine (12.4.18) etc.). Reading data from a file is offered by d_source (12.4.21). Somecomments and hints have been provided by Sdaau. You may also use the analog input from file,(filesource 12.2.8) and convert its analog input to the digital type by the adc_bridge (12.3.2). Ifyou want reading data from a VCD file, you may have a look at ngspice-users forum and applya python script provided by Sdaau to translate the VCD data to d_source or filesource input.
Chapter 13Verilog A Device models13.1
The ngspice-adms interface will implement extra HICUM level0 and level2 (HICUM modelweb page), MEXTRAM(MEXTRAM model web page), EKV(EKV model web page) andPSP(NXP MOS model 9 web page) models written in Verilog-A behavior language.
13.2
adms
To compile Verilog-A compact models into ngspice-ready C models the the program admsXmlis required. Details of this software are described in adms home page.
13.3
13.3.1
The root entry for new Verilog-A models is \src\spicelib\devices\adms. Below the modelnameentry the Verilog-A code should reside in folder admsva(e.g.: ngspice\src\spicelib\devices\adms\ekv\admsva\ekv.va). The file extension is fixed to .va.Certain files must modified to create the interface to ngspice - see the guideline README.admsin the ngspice root.
13.3.2
To facilitate the installation of adms, a source code package has been assembled for use withngspice, available as a zip file for download. It is based on adms source code from the subversion repository downloaded on August 1st, 2010, and has been slightly modified (see ChangeLog).Under OS LINUX (tested with SUSE 11.2, 64 bit) you may expand the zip file and run./autogen_lin.sh, followed by make and make install.
224
Under OS CYGWIN (tested with actual CYGWIN on MS Windows 7, 64 bit), please use./autogen_cyg.sh, followed by make and make install.Under OS MINGW, a direct compilation would require the additional installation of perl moduleXML-LibXML which is not as straightforward as it should be. However you may start with aCYGWIN compile as described above. If you then go to your MSYS window, cd to the admstop directory and start ./mingw-compile.sh, you will obtain admsXml.exe, copied to MSYS/bin, and you are ready to go. To facilitate installation under MS Windows, a admsXml.exezipped binary is available. Just copy it to MSYS /bin directory and start working on your verilogmodels.A short test of a successful installation is:$ admsXml -v$ [usage..] release name="admsXml" version="2.3.0" date="Aug 4 2010"time="10:24:18"Compilation of admsXml with MS Visual Studio is not possible, because the source code hasvariable declarations not only at the top of a block, but deliberately also in the following lines.This is o.k. by the C99 standard, but not supported by MS Visual Studio.
Chapter 14Mixed-Level Simulation (ngspice withTCAD)14.1
Cider
Ngspice implements mixed-level simulation through the merging of its code with CIDER (details see chapt. 30).CIDER is a mixed-level circuit and device simulator that provides a direct link between technology parameters and circuit performance. A mixed-level circuit and device simulator canprovide greater simulation accuracy than a stand-alone circuit or device simulator by numerically modeling the critical devices in a circuit. Compact models can be used for noncriticaldevices.CIDER couples the latest version of SPICE3 (version 3F.2) [JOHN92] to a internal C-baseddevice simulator, DSIM. SPICE3 provides circuit analyses, compact models for semiconductordevices, and an interactive user interface. DSIM provides accurate, one- and two-dimensionalnumerical device models based on the solution of Poissons equation, and the electron andhole current-continuity equations. DSIM incorporates many of the same basic physical modelsfound in the the Stanford two-dimensional device simulator PISCES [PINT85]. Input to CIDERconsists of a SPICE-like description of the circuit and its compact models, and PISCES-likedescriptions of the structures of numerically modeled devices. As a result, CIDER should seemfamiliar to designers already accustomed to these two tools. For example, SPICE3F.2 input filesshould run without modification, producing identical results.CIDER is based on the mixed-level circuit and device simulator CODECS [MAYA88] [GATE90] that is important in scaled-down MOSFETs and apolysilicon model for poly-emitter bipolar transistors. Temperature dependence has been included for most physical models over the range from -50C to 150C. The numerical modelscan be used to simulate all the basic types of semiconductor devices: resistors, MOS capacitors, diodes, BJTs, JFETs and MOSFETs. BJTs and JFETs can be modeled with or without asubstrate contact. Support has been added for the management of device internal states. Postprocessing of device states can be performed using the NUTMEG user interface of SPICE3.
226
Previously computed states can be loaded into the program to provide accurate initial guessesfor subsequent analyses. Finally, numerous small bugs have been discovered and fixed, and theprogram has been ported to a wider variety of computing platforms.Berkeley tradition calls for the naming of new versions of programs by affixing a (number,letter, number) triplet to the end of the program name. Under this scheme, CIDER shouldinstead be named CODECS2A.l. However, tradition has been broken in this case because majorincompatibilities exist between the two programs and because it was observed that the acronymCODECS is already used in the analog design community to refer to coder-decoder circuits.Details of the basic semiconductor equations and the physical models used by CIDER are notprovided in this manual. Unfortunately, no other single source exists which describes all ofthe relevant background material. Comprehensive reviews of device simulation can be foundin [PINT90] and the book [SELB84]. CODECS and its inversion-layer mobility model aredescribed in [MAYA88] and LGATE90], respectively. PISCES and its models are described in[PINT85]. Temperature dependencies for the PISCES models used by CIDER are available in[SOLL90].
14.2
GSS, Genius
For LINUX users the cooperation of the TCAD software GSS with ngspice might be of interest,see. This project is no longer maintained however, buthas moved into the Genius simulator, still available as open source cogenda genius.
Chapter 15Analyses and Output Control (batchmode)The command lines described in this chapter are specifying analyses and outputs within thecircuit description file. They start with a . (dot commands). Specifying analyses and plots(or tables) in the input file with dot commands is used with batch runs. Batch mode is enteredwhen either the -b option is given upon starting ngspicengspice -b -r rawfile.raw circuitfile.ciror when the default input source is redirected from a file (see also chapt. 16.4.1).ngspice < circuitfile.cirIn batch mode, the analyses specified by the control lines in the input file (e.g. .ac, .tran,etc.) are immediately executed. If the -r rawfile option is given then all data generated iswritten to a ngspice rawfile. The rawfile may later be read by the interactive mode of ngspiceusing the load command (see 17.5.36). In this case, the .save line (see 15.5) may be used torecord the value of internal device variables (see Appendix, chapter 31).If a rawfile is not specified, then output plots (in line-printer form) and tables can be printedaccording to the .print, .plot, and .four control lines, described in chapter 15.5.If ngspice is started in interactive mode (see chapt. 16.4.2), likengspice circuitfile.cirand no control section (.control ... .endc, see 16.4.3) is provided in the circuit file, the dotcommands are not executed immediately, but are waiting for manually receiving the commandrun.
15.1
Various parameters of the simulations available in Ngspice can be altered to control the accuracy, speed, or default values for some devices. These parameters may be changed via theoption command (described in chapt. 17.5.42) or via the .options line:
228
General form:. options opt1 opt2 . . . ( or opt= optval
...)
Examples:. o p t i o n s r e l t o l = . 0 0 5 t r t o l =8The options line allows the user to reset program control and user options for specific simulationpurposes. Options specified to Ngspice via the option command (see chapt. ) are alsopassed on as if specified on a .options line. Any combination of the following options maybe included, in any order. x (below) represents some positive number.
15.1.1
General Options
15.1.2
DC Solution Options
The following options controls properties pertaining to DC analysis and algorithms. Sincetransient analysis is based on DC many of the options affect the latter one.ABSTOL=x resets the absolute current error tolerance of the program. The default value is 1pA.GMIN=x resets the value of GMIN, the minimum conductance allowed by the program. Thedefault value is 1.0e-12.ITL1=x resets the dc iteration limit. The default is 100.
229
ITL2=x resets the dc transfer curve iteration limit. The default is 50.KEEPOPINFO Retain the operating point information when either an AC, Distortion, or PoleZero analysis is run. This is particularly useful if the circuit is large and you do not wantto run a (redundant) ".OP" analysis.PIVREL=x resets the relative ratio between the largest column entry and an acceptable pivotvalue.pivoting).PIVTOL=x resets the absolute minimum value for a matrix entry to be accepted as a pivot.The default value is 1.0e-13.RELTOL=x resets the relative error tolerance of the program. The default value is 0.001(0.1%).RSHUNT=x introduces a resistor from each analog node to ground. The value of the resistorshould be high enough to not interfere with circuit operations. The XSPICE option has tobe enabled (see 32.1.5) .VNTOL=x resets the absolute voltage error tolerance of the program. The default value is 1V .15.1.2.1
In most SPICE-based simulators, problems can arise with certain circuit topologies. One ofthe most common problems is the absence of a DC path to ground at some node. This mayhappen, for example, when two capacitors are connected in series with no other connection atthe common node or when certain code models are cascaded. The result is an ill-conditionedor nearly singular matrix that prevents the simulation from completing. The XSPICE optionintroduces the rshunt option to help eliminate this problem. When used, this option insertsresistors to ground at all the analog nodes in the circuit. In general, the value of rshunt shouldbe set to some very high resistance (e.g. 1000 Meg Ohms or greater) so that the operation of thecircuit is essentially unaffected, but the matrix problems are corrected. If you should encountera no DC path to ground or a matrix is nearly singular error message with your circuit, youshould try adding the following .option card to your circuit description deck..option rshunt = 1.0e12Usually a value of 1.0e12 is sufficient to correct the matrix problems. However, if you still haveproblems, you may wish to try lowering this value to 1.0e10 or 1.0e9.Another matrix conditioning problem might occur if you try to place an inductor in parallel toa voltage source. An ac simulation will fail, because it is preceded by an op analysis. Optionnoopac (15.1.3) will help if the circuit is linear. If the circuit is non-linear, you will need theop analysis. Then adding a small resistor (e.g. 1e-4 Ohms) in series to the inductor will help toobtain convergence.
230
15.1.3
AC Solution Options
NOOPAC Do not do an operating point (OP) analysis before the AC analysis. To becomevalid, this option requires that the circuit is linear, thus consists only of R, L, and Cdevices, independent V, I sources and linear dependent E, G, H, and F sources (withoutpoly statement, non-behavioral). If a non-linear device is detected, the OP analysis willbe executed automatically. This option is of interest for example in nested LC circuits,where there is no series resistance for the L device given, which during OP analysis mayresult in an ill formed matrix, yields an error message and aborts the simulation.
15.1.4
AUTOSTOP stops a transient analysis after successfully calculating all measure functions(15.4) specified with the dot command .meas. autostop is not available with meas (17.5.37)used in control mode.CHGTOL=x resets the charge tolerance of the program. The default value is 1.0e-14.CONVSTEP=x relative step limit applied to code models.CONVABSSTEP=x absolute step limit applied to code models.GMINSTEPS=x [*] sets number of Gmin steps to be attempted. If the value is set to zero, thegmin stepping algorithm is disabled. In such case the source stepping algorithm becomesthe standard when the standard procedure fails to converge to a solution.ITL3=x resets the lower transient analysis iteration limit. the default value is 4. (Note: notimplemented in Spice3).ITL4=x resets the transient analysis time-point iteration limit. the default is 10.ITL5=x resets the transient analysis total iteration limit. the default is 5000. Set ITL5=0 toomit this test. (Note: not implemented in Spice3).ITL6=x [*] synonym for SRCSTEPS.MAXEVITER=x sets the number of event iterations that are allowed at an analysis pointMAXOPALTER=x specifies the maximum number of analog/event alternations that the simulator can use in solving a hybrid circuit.MAXORD=x [*] specifies the maximum order for the numerical integration method used bySPICE. Possible values for the Gear method are from 2 (the default) to 6. Using the value1 with the trapezoidal method specifies backward Euler integration.
231
METHOD=name sets the numerical integration method used by SPICE. Possible names are"Gear" or "trapezoidal" (or just "trap"). The default is trapezoidal.NOOPALTER=TRUE|FALSE if set to false alternations between analog/event are enabled.RAMPTIME=x this options sets the rate of change of independent supplies and code modelinductors and capacitors with initial conditions specified.SRCSTEPS=x [*] a non-zero value causes SPICE to use a source-stepping method to find theDC operating point. Its value specifies the number of steps.TRTOL=x resets the transient error tolerance. The default value is 7. This parameter is an estimate of the factor by which ngspice overestimates the actual truncation error. If XSPICEis enabled and A devices included, the value is internally set to 1 for higher precision.This will cost a factor of two in CPU time during transient analysis.
15.1.5
BADMOS3 Use the older version of the MOS3 model with the kappa discontinuity.DEFAD=x resets the value for MOS drain diffusion area; the default is 0.0.DEFAS=x resets the value for MOS source diffusion area; the default is 0.0.DEFL=x resets the value for MOS channel length; the default is 100.0 m.DEFW=x resets the value for MOS channel width; the default is 100.0 m.
15.1.6
TRYTOCOMPACT Applicable only to the LTRA model (see 6.2.1). When specified, thesimulator tries to condense LTRA transmission lines past history of input voltages andcurrents.
15.1.7
There are various ways to set the above mentioned options in Ngspice. If no option or.options lines are set by the user, internal default values are given for each of the simulator variables.You may set options in the init files spinit or .spiceinit via the option command (see chapt.17.5.42). The values given here will supersede the default values. If you set options via the.options line in your input file, their values will supersede the default and init file data. Finallyif you set options inside a .control ... .endc section, these values will supersede any values ofthe respective simulator variables given so far.
232
15.2
Initial Conditions
15.2.1
General form:. NODESET V(NODNUM) =VAL V(NODNUM) =VAL . . .. NODESET ALL=VALExamples:. NODESET V( 1 2 ) = 4 . 5 V( 4 ) = 2 . 2 3. NODESET ALL= 1 . 5The .nodeset line helps the program find the dc or initial transient solution by making a preliminary pass with the specified nodes held to the given voltages. The restriction is then releasedand the iteration continues to the true solution. The .nodeset line may be necessary for convergence on bistable or a-stable circuits. .nodeset all=val allows to set all starting nodevoltages (except for the ground node) in a single line. In general, the .nodeset line should notbe necessary.
15.2.2
General form:. i c v ( nodnum ) = v a l v ( nodnum ) = v a l
...
Examples:. i c v ( 1 1 ) = 5 v (4)= 5 v ( 2 ) = 2 . 2The .ic line is for setting transient initial conditions. It has two different interpretations, depending on whether the uic parameter is specified on the .tran control line. Also, one shouldnot confuse this line with the .nodeset line. The .nodeset line is only to help dc convergence,and does not affect final bias solution (except for multi-stable circuits). The two interpretationsof this line are as follows:1. When the uic parameter is specified on the .tran line, then the node voltages specifiedon the .ic control line are used to compute the capacitor, diode, BJT, JFET, and MOSFETinitial conditions. This is equivalent to specifying the ic=... parameter on each deviceline, but is much more convenient. The ic=... parameter can still be specified and takesprecedence over the .ic values. Since no dc bias (initial transient) solution is computedbefore the transient analysis, one should take care to specify all dc source voltages on the.ic control line if they are to be used to compute device initial conditions.2. When the uic parameter is not specified on the .tran control line, the dc bias (initialtransient) solution is computed before the transient analysis. In this case, the node voltages specified on the .ic control line is forced to the desired initial values during thebias solution. During transient analysis, the constraint on these node voltages is removed.This is the preferred method since it allows ngspice to compute a consistent dc solution.
15.3. ANALYSES
15.3
Analyses
15.3.1
233
General form:. a c d e c nd f s t a r t f s t o p. a c o c t no f s t a r t f s t o p. a c l i n np f s t a r t f s t o pExamples:. a c d e c 10 1 10K. a c d e c 10 1K 100MEG. a c l i n 100 1 100HZ
dec stands for decade variation, and nd is the number of points per decade. oct stands foroctave variation, and no is the number of points per octave. lin stands for linear variation, andnp is the number of points. fstart is the starting frequency, and fstop is the final frequency.If this line is included in the input file, ngspice performs an AC analysis of the circuit over thespecified frequency range. Note that in order for this analysis to be meaningful, at least oneindependent source must have been specified with an ac value. Typically it does not make muchsense to specify more than one ac source. If you do, the result will be a superposition of allsources, thus difficult to interpret.
Example:B a s i c RC c i r c u i tr 1 2 1.0c 2 0 1.0v i n 1 0 dc 0 a c 1 $ < t h e a c s o u r c e. options noacct. a c d e c 10 . 0 1 10. p l o t a c vdb ( 2 ) x l o g. end
In this ac (or small signal) analysis all non-linear devices are linearized around their actual dcoperating point. All Ls and Cs get their imaginary value, depending on the actual frequencystep. Each output vector will be calculated relative to the input voltage (current) given by the acvalue (Vin equals to 1 in the example above). The resulting node voltages (and branch currents)are complex vectors. Therefore you have to be careful using the plot command. Especially youmay use the variants of vxx(node) described in chapter 15.5.2 like vdb(2) (see example above).
234
15.3.2
General form:. dc s r c n a m v s t a r t v s t o p v i n c r [ s r c 2 s t a r t 2 s t o p 2 i n c r 2 ]Examples:. dc. dc. dc. dc. dc
VIN 0 . 2 5VDS 0 10VCE 0 10RLoad 1kTEMP 15
5.0 0.25. 5 VGS 0 5 1. 2 5 IB 0 10U 1U2k 10075 5
The .dc line defines the dc transfer curve source and sweep limits (again with capacitors openand inductors shorted). srcnam is the name of an independent voltage or current source, aresistor or the circuit temperature. vstart, vstop, and vincr are the starting, final, and incrementing values respectively. The first example causes the value of the voltage source VINto be swept from 0.25 Volts to 5.0 Volts in increments of 0.25 Volts. A second source (src2)may optionally be specified with associated sweep parameters. In this case, the first source isswept over its range for each value of the second source. This option can be useful for obtainingsemiconductor device output characteristics. See the example circuit description on transistorcharacteristics (21.3).
15.3.3
General form:. d i s t o d e c nd f s t a r t f s t o p < f 2 o v e r f 1 >. d i s t o o c t no f s t a r t f s t o p < f 2 o v e r f 1 >. d i s t o l i n np f s t a r t f s t o p < f 2 o v e r f 1 >Examples:. d i s t o d e c 10 1kHz 100Mhz. d i s t o d e c 10 1kHz 100Mhz 0 . 9The .disto line does a small-signal distortion analysis of the circuit. A multi-dimensionalVolterra series analysis is done using multi-dimensional Taylor series to represent the nonlinearities at the operating point. Terms of up to third order are used in the series expansions.If the optional parameter f2overf1 is not specified, .disto does a harmonic analysis - i.e.,it analyses distortion in the circuit using only a single input frequency F1 , which is swept asspecified by arguments of the .disto command exactly as in the .ac command. Inputs at thisfrequency may be present at more than one input source, and their magnitudes and phases arespecified by the arguments of the distof1 keyword in the input file lines for the input sources(see the description for independent sources). (The arguments of the distof2 keyword are notrelevant in this case).The analysis produces information about the AC values of all node voltages and branch currentsat the harmonic frequencies 2F1 and , vs. the input frequency F1 as it is swept. (A value of 1(as a complex distortion output) signifies cos(2(2F1 )t) at 2F1 and cos(2(3F1 )t) at 3F1 , using
235
the convention that 1 at the input fundamental frequency is equivalent to cos(2F1t).) Thedistortion component desired (2F1 or 3F1 ) can be selected using commands in ngnutmeg, andthen printed or plotted. (Normally, one is interested primarily in the magnitude of the harmoniccomponents, so the magnitude of the AC distortion value is looked at). It should be noted thatthese are the AC values of the actual harmonic components, and are not equal to HD2 and HD3.To obtain HD2 and HD3, one must divide by the corresponding AC values at F1 , obtained froman .ac line. This division can be done using ngnutmeg commands.If the optional f2overf1 parameter is specified, it should be a real number between (and notequal to) 0.0 and 1.0; in this case, .disto does a spectral analysis. It considers the circuit withsinusoidal inputs at two different frequencies F1 and F2 . F1 is swept according to the .distocontrol line options exactly as in the .ac control line. F2 is kept fixed at a single frequencyas F1 sweeps - the value at which it is kept fixed is equal to f2overf1 times fstart. Eachindependent source in the circuit may potentially have two (superimposed) sinusoidal inputsfor distortion, at the frequencies F1 and F2 . The magnitude and phase of the F1 component arespecified by the arguments of the distof1 keyword in the sources input line (see the description of independent sources); the magnitude and phase of the F2 component are specified by thearguments of the distof2 keyword. The analysis produces plots of all node voltages/branchcurrents at the intermodulation product frequencies F1 + F2 , F1 F2 , and (2F1 ) F2 , vs theswept frequency F1 . The IM product of interest may be selected using the setplot command,and displayed with the print and plot commands. It is to be noted as in the harmonic analysiscase, the results are the actual AC voltages and currents at the intermodulation frequencies, andneed to be normalized with respect to .ac values to obtain the IM parameters.If the distof1 or distof2 keywords are missing from the description of an independentsource, then that source is assumed to have no input at the corresponding frequency. The defaultvalues of the magnitude and phase are 1.0 and 0.0 respectively. The phase should be specifiedin degrees.It should be carefully noted that the number f2overf1 should ideally be an irrational number,and that since this is not possible in practice, efforts should be made to keep the denominatorin its fractional representation as large as possible, certainly above 3, for accurate results (i.e.,if f2overf1 is represented as a fraction A/B, where A and B are integers with no commonfactors, B should be as large as possible; note that A < B because f2overf1 is constrainedto be < 1). To illustrate why, consider the cases where f2overf1 is 49/100 and 1/2. In aspectral analysis, the outputs produced are at F1 + F2 , F1 F2 and 2F1 F2 . In the latter case,F1 F2 = F2 , so the result at the F1 F2 component is erroneous because there is the strongfundamental F2 component at the same frequency. Also, F1 + F2 = 2Fclosely spaced frequency components at F2 and F1 F2 . One of the advantages of the Volterraseries technique is that it computes distortions at mix frequencies expressed symbolically (i.e.nF1 + mF2 ), therefore one is able to obtain the strengths of distortion components accuratelyeven if the separation between them is very small, as opposed to transient analysis for example.The disadvantage is of course that if two of the mix frequencies coincide, the results are notmerged together and presented (though this could presumably be done as a postprocessing step).Currently, the interested user should keep track of the mix frequencies himself or herself andadd the distortions at coinciding mix frequencies together should it be necessary.Only a subset of the ngspice nonlinear device models supports distortion analysis. These are
236
15.3.4
General form:. n o i s e v ( o u t p u t < , r e f >) s r c ( dec | l i n | o c t ) p t s f s t a r t f s t o p+ <pts_per_summary >Examples:. n o i s e v ( 5 ) VIN d e c 10 1kHZ 100Mhz. n o i s e v ( 5 , 3 ) V1 o c t 8 1 . 0 1 . 0 e6 1The .noise line does a noise analysis of the circuit. output is the node at which the totaloutput noise is desired; if ref is specified, then the noise voltage v(output) - v(ref) iscalculated. By default, ref is assumed to be ground. src is the name of an independent sourceto which input noise is referred. pts, fstart and fstop are .ac type parameters that specifythe frequency range over which plots are desired. pts_per_summary is an optional integer; ifspecified, the noise contributions of each noise generator is produced every pts_per_summaryfrequency points. The .noise control line produces two plots:1. one for the Noise Spectral Density curves and2. one for the total Integrated Noise over the specified frequency range.All noise voltages/currents are in squared units (V 2/Hz and A2/Hz for spectral density, V 2 and A2for integrated noise).
15.3.5
General form:. opThe inclusion of this line in an input file directs ngspice to determine the dc operating point ofthe circuit with inductors shorted and capacitors opened.Note: a DC analysis is automatically performed prior to a transient analysis to determine thetransient initial conditions, and prior to an AC small-signal, Noise, and Pole-Zero analysis todetermine the linearized, small-signal models for nonlinear devices (see the KEEPOPINFOvariable 15.1.2).
15.3.6
237
General form:. pz. pz. pz. pz. pz. pz
node1node1node1node1node1node1
node2node2node2node2node2node2
node3node3node3node3NODE3node3
node4node4node4node4node4node4
curcurcurvolvolvol
polzerpzpolzerpz
Examples:. pz 1 0 3 0 c u r p o l. pz 2 3 5 0 v o l z e r. pz 4 1 4 1 c u r pzcur stands for a transfer function of the type (output voltage)/(input current) while vol standsfor a transfer function of the type (output voltage)/(input voltage). pol stands for pole analysisonly, zer for zero analysis only and pz for both. This feature is provided mainly becauseif there is a nonconvergence in finding poles or zeros, then, at least the other can be found.Finally, node1 and node2 are the two input nodes and node3 and node4 are the two outputnodes. Thus, there is complete freedom regarding the output and input ports and the type oftransfer function.In interactive mode, the command syntax is the same except that the first field is pz instead of.pz. To print the results, one should use the command print all.
15.3.7
General form:. SENS. SENS. SENS. SENS
OUTVAROUTVAR AC DEC ND FSTART FSTOPOUTVAR AC OCT NO FSTART FSTOPOUTVAR AC LIN NP FSTART FSTOP
Examples:. SENS V( 1 ,OUT). SENS V(OUT) AC DEC 10 100 100 k. SENS I ( VTEST )The sensitivity of OUTVAR to all non-zero device parameters is calculated when the SENSanalysis is specified. OUTVAR is a circuit variable (node voltage or voltage-source branchcurrent). The first form calculates sensitivity of the DC operating-point value of OUTVAR.The second form calculates sensitivity of the AC values of OUTVAR. The parameters listed forAC sensitivity are the same as in an AC analysis (see ".AC" above). The output values are indimensions of change in output per unit change of input (as opposed to percent change in outputor per percent change of input).
238
15.3.8
General form:. t f outvar insrcExamples:. t f v ( 5 , 3 ) VIN. t f i (VLOAD) VINThe .tf line defines the small-signal output and input for the dc small-signal analysis. outvaris the small signal output variable and insrc is the small-signal input source. If this line isincluded, ngspice computes the dc small-signal value of the transfer function (output/input),input resistance, and output resistance. For the first example, ngspice would compute the ratioof V(5, 3) to VIN, the small-signal input resistance at VIN, and the small signal output resistancemeasured across nodes 5 and 3.
15.3.9
General form:. t r a n t s t e p t s t o p < t s t a r t <tmax >> < u i c >Examples:. t r a n 1 n s 100 n s. t r a n 1 n s 1000 n s 500 n s. t r a n 10 n s 1 u ststep is the printing or plotting increment for line-printer output. For use with the postprocessor, tstep is the suggested computing increment. tstop is the final time, and tstartis the initial time. If tstart is omitted, it is assumed to be zero. The transient analysis alwaysbegins at time zero. In the interval <zero, tstart>, the circuit is analyzed (to reach a steadystate), but no outputs are stored. In the interval <tstart, tstop>, the circuit is analyzed andoutputs are stored. tmax is the maximum stepsize that ngspice uses; for default, the programchooses either tstep or (tstop-tstart)/50.0, whichever is smaller. tmax is useful when onewishes to guarantee a computing interval which is smaller than the printer increment, tstep.An initial transient operating point at time zero is calculated according to the following procedure: all independent voltages and currents are applied with their time zero values, all capacitances are opened, inductances are shorted, the non linear device equations are solved iteratively.uic (use initial conditions) is an optional keyword which indicates that the user does not wantngspice to solve for the quiescent operating point before beginning the transient analysis. If thiskeyword is specified, ngspice uses the values specified using IC=... on the various elements asthe initial transient condition and proceeds with the analysis. If the .ic control line has beenspecified (see 15.2.2), then the node voltages on the .ic line are used to compute the initialconditions for the devices. IC=... will take precedence over the values given in the .ic controlline. If neither IC=... nor the .ic control line is given for a specific node, node voltage zero isassumed.Look at the description on the .ic control line (15.2.2) for its interpretation when uic is notspecified.
15.3.10
239
In contrast to the analysis types described above the transient noise simulation (noise current orvoltage versus time) is not implemented as a dot command, but is integrated with the independent voltage source vsrc (isrc still not yet available) (see 4.1.7) and used in combination withthe .tran transient analysis (15.3.9).
Transient noise analysis deals with noise currents or voltages added to your circuits as a timedependent signal of randomly generated voltage excursion on top of a fixed dc voltage. Thesequence of voltage values has random amplitude, but equidistant time intervals, selectable bythe user (parameter NT). The resulting voltage waveform is differentiable and thus does notrequire any modifications of the matrix solving algorithms.
White noise is generated by the ngspice random number generator, applying the Box-Mullertransform. Values are generated on the fly, each time when a breakpoint is hit.
The 1/f noise is generated with an algorithm provided by N. J. Kasdin (Discrete simulation ofcolored noise and stochastic processes and 1/ f a power law noise generation, Proceedings ofthe IEEE, Volume 83, Issue 5, May 1995 Page(s):802 827). The noise sequence (one for eachvoltage/current source with 1/f selected) is generated upon start up of the simulator and storedfor later use. The number of point is determined by the total simulation time divided by NT,rounded up the the nearest power of 2. Each time a breakpoint (n ? NT , relevant to the noisesignal) is hit, the next value is retrieved from the sequence.
If you want a random, but reproducible sequence, you may select a seed value for the randomnumber generator by adding
set rndseed=nn
The transient noise analysis will allow the simulation of the three most important noise sources.Thermal noise is described by the Gaussian white noise. Flicker noise (pink noise or 1 overf noise) with an exponent between 0 and 2 is provided as well. Shot noise is dependent onthe current flowing through a device and may be simulated by applying a non-linear source asdemonstrated in the following example:
240
Example:* Shot n o i s e t e s t with B source , diode* v o l t a g e on d e v i c e ( d i o d e , f o r w a r d )Vdev o u t 0 DC 0 PULSE ( 0 . 4 0 . 4 5 10 u )* d i o d e , f o r w a r d d i r e c t i o n , t o be modeled w i t h n o i s eD1 mess 0 DMOD. model DMOD D I S =1e 14 N=1X1 0 mess o u t i s h o t* d e v i c e b e t w e e n 1 and 2* new o u t p u t t e r m i n a l s o f d e v i c e i n c l u d i n g n o i s e : 1 and 3. subckt ishot 1 2 3* w h i t e n o i s e s o u r c e w i t h rms 1V* 20000 s a m p l e p o i n t sVNG 0 11 DC 0 TRNOISE ( 1 1n 0 0 )* m e a s u r e t h e c u r r e n t i ( v1 )V1 2 3 DC 0* calculate the shot noise* s q r t (2* c u r r e n t *q* bandwidth )BI 1 3 I = s q r t ( 2 * a b s ( i ( v1 ) ) * 1 . 6 e 19 * 1 e7 ) * v ( 1 1 ). ends i s h o t. t r a n 1 n 20 u. controlrunp l o t ( 1) * i ( vdev ). endc. endThe selection of the delta time step (NT) is worth discussing. Gaussian white noise has unlimited bandwidth and thus unlimited energy content. This is unrealistic. The bandwidth of realnoise is limited, but it is still called "White" if it is the same level throughout the frequencyrange of interest, e.g. the bandwidth of your system. Thus you may select NT to be a factor of10 smaller than the frequency limit of your circuit. A thorough analysis is still needed to clarify the appropriate factor! The transient method is probably most suited for circuits includingswitches, which are not amenable to the small signal .NOISE analysis (chapter 15.3.4).This is the price you have to pay for transient noise analysis: the number of required time stepsfor simulation will increase, and thus the simulation time. But modern computers deliver a lotof speed, and it may be well worth of trying and experimenting.In addition to white and 1/f noise the independent voltage and current sources offer a randomtelegraph signal (RTS) noise source, also known as burst noise or popcorn noise, again fortransient analysis. For each voltage (current) source offering RTS noise an individual noiseamplitude is required for input, as well as a mean capture time and a mean emission time.The amplitude resembles the influence of a single trap on the current or voltage. The captureand emission times emulate the filling and emptying of the trap, typically following a Poissonprocess. They are generated from an random exponential distribution with their respective meanvalues given by the user. To simulate an ensemble of traps, you may combine several current orvoltage sources with different parameters.
241
All three sources (white, 1/f, and RTS) may be combined in a single command line.RTS noise example:* w h i t e n o i s e , 1 / f n o i s e , RTS n o i s e* voltage sourceVRTS2 13 12 DC 0 t r n o i s e ( 0 0 0 0 5m 18 u 30 u )VRTS3 11 0 DC 0 t r n o i s e ( 0 0 0 0 10m 20 u 40 u )VALL 12 11 DC 0 t r n o i s e ( 1m 1u 1 . 0 0 . 1m 15m 22 u 50 u )VW1of 21 0 DC
t r n o i s e ( 1m 1u 1 . 0 0 . 1m)
* current sourceIRTS2 10 0 DC 0 t r n o i s e ( 0 0 0 0 5m 18 u 30 u )IRTS3 10 0 DC 0 t r n o i s e ( 0 0 0 0 10m 20 u 40 u )IALL 10 0 DC 0 t r n o i s e ( 1m 1u 1 . 0 0 . 1m 15m 22 u 50 u )R10 10 0 1IW1of 9 0 DCRall 9 0 1
* sample p o i n t s. t r a n 1 u 500 u. controlrunplot v (13) v (21)plot v (10) v (9). endc. endSome details on RTS noise modeling are available in a recent article [20], available here.Anyhow this transient noise feature is still experimental!The following questions (among others) are to be solved: clarify the theoretical background noise limit of plain ngspice (numerical solver, fft etc.) time step (NT) selection calibration of noise spectral density how to generate noise from a transistor model application benefits and limits
242
15.3.11
15.4
15.4.1
.meas(ure)
The .meas or .measure statement (and its equivalent meas command, see chapt. 17.5.37) areused to analyze the output data of a tran, ac, or dc simulation. The command is executedimmediately after the simulation has finished.
15.4.2
243
.meas analysis may not be used in batch mode (-b command line option), if an output file(rawfile) is given at the same time (-r rawfile command line option). In this batch modengspice will write its simulation output data directly to the output file. The data is not kept inmemory, thus is no longer available for further analysis. This is made to allow a very largeoutput stream with only a relatively small memory usage. For .meas to be active you need torun the batch mode with a .plot or .print command. A better alternative may be to startngspice in interactive mode.If you need batch like operation, you may add a .control ...file:
Example:* input f i l e.... t r a n 1 n s 1000 n s...*********************************. controlrunwrite o u t p u t f i l e data. endc*********************************. endand start ngspice in interactive mode, e.g. by running the commandngspice inputfile ..meas<ure> then prints its user-defined data analysis to the standard output. The analysis includes propagation, delay, rise time, fall time, peak-to-peak voltage, minimum or maximumvoltage, the integral or derivative over a specified period and several other user defined values.
15.4.3
General remarks
The measure type {DC|AC|TRAN|SP} depends on the data which are to be evaluated, eitheroriginating from a dc analysis, an ac analysis, a transient simulation. SP to analyze a spectrumfrom the spec or fft commands is only available when executed in a meas command, see17.5.37.result will be a vector containing the result of the measurement. trig_variable, targ_variable,and out_variable are vectors stemming from the simulation, e.g. a voltage vector v(out).VAL=val expects a real number val. It may be as well a parameter in or {} expanding to areal number.TD=td and AT=time expect a time value if measure type is tran. For ac and sp AT will be afrequency value, TD is ignored. For dc analysis AT is a voltage (or current), TD is ignored aswell.CROSS=# requires an integer number #. CROSS=LAST is possible as well. The same isexpected by RISE and FALL.
244
Frequency and time values may start at 0 and extend to positive real numbers. Voltage (orcurrent) inputs for the independent (scale) axis in a dc analysis may start or end at arbitrary realvalued numbers.*************Be careful because not all of the .measure commands have been implemented so far!deriv and error is missing*************
15.4.4
Input
In the following lines you will get some explanation on the .measure commands. A simplesimulation file with two sines of different frequencies may serve as an example. The transientsimulation delivers time as the independent variable and two voltages as output (dependentvariables).Input file:F i l e : s i m p l e meast r a n . s p* Simple . measurement examples* t r a n s i e n t s i m u l a t i o n o f two s i n e s i g n a l s w i t h d i f f e r e n tfrequenciesv a c 1 1 0 DC 0 s i n ( 0 1 1k 0 0 )v a c 2 2 0 DC 0 s i n ( 0 1 . 2 0 . 9 k 0 0 ). t r a n 10 u 5m*. m e a s u r e t r a n . . . $ f o r t h e d i f f e r e n t i n p u t s s e e below !*. controlrunplot v (1) v (2). endc. endAfter displaying the general syntax of the .measurement statement, some examples are posted,referring to the input file given above.
15.4.5
Trig Targ
.measure according to general form 1 measures the difference in dc voltage, frequency or timebetween two points selected from one or two output vectors. The current examples all are usingtransient simulation. Measurements for tran analysis start after a delay time td. If you run otherexamples with ac simulation or spectrum analysis, time may be replaced by frequency, after adc simulation the independent variable may become a voltage or current.
245
General form 1:. MEASURE {DC | AC | TRAN | SP} r e s u l t TRIG t r i g _ v a r i a b l e VAL= v a l <TD=t d > <CROSS=# | CROSS=LAST> <RISE=# | RISE=LAST> <FALL=# |FALL=LAST> <TRIG AT= t i m e > TARG t a r g _ v a r i a b l e VAL= v a l <TD= t d ><CROSS=# | CROSS=LAST> <RISE=# | RISE=LAST> <FALL=# | FALL=LAST> <TARG AT= t i m e >Measure statement example (for use in the input file given above):.measure tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 RISE=2measures the time difference between v(1) reaching 0.5 V for the first time on its first risingslope (TRIG) versus reaching 0.5 V again on its second rising slope (TARG). I.e. it measuresthe signal period.Output:tdiff = 1.000000e-003 targ= 1.083343e-003 trig= 8.334295e-005Measure statement example:.measure tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 RISE=3measures the time difference between v(1) reaching 0.5 V for the first time on its rising slopeversus reaching 0.5 V on its rising slope for the third time (i.e. two periods).Measure statement:.measure tran tdiff TRIG v(1) VAL=0.5 RISE=1 TARG v(1) VAL=0.5 FALL=1measures the time difference between v(1) reaching 0.5V for the first time on its rising slopeversus reaching 0.5 V on its first falling slope.Measure statement:.measure tran tdiff TRIG v(1) VAL=0 FALL=3 TARG v(2) VAL=0 FALL=3measures the time difference between v(1) reaching 0V its third falling slope versus v(2) reaching 0 V on its third falling slope.Measure statement:.measure tran tdiff TRIG v(1) VAL=-0.6 CROSS=1 TARG v(2) VAL=-0.8 CROSS=1measures the time difference between v(1) crossing -0.6 V for the first time (any slope) versusv(2) crossing -0.8 V for the first time (any slope).Measure statement:.measure tran tdiff TRIG AT=1m TARG v(2) VAL=-0.8 CROSS=3measures the time difference between the time point 1ms versus the time when v(2) crosses -0.8V for the third time (any slope).
15.4.6
The FIND and WHEN functions allow to measure any dependent or independent time, frequency, or dc parameter, when two signals cross each other or a signal crosses a given value.Measurements start after a delay TD and may be restricted to a range between FROM and TO.
246
General form 2:. MEASURE {DC | AC | TRAN | SP} r e s u l t WHEN o u t _ v a r i a b l e = v a l <TD= t d > <FROM= v a l > <TO= v a l > <CROSS=# | CROSS=LAST> <RISE=# | RISE=LAST> <FALL=# | FALL=LAST>Measure statement:.measure tran teval WHEN v(2)=0.7 CROSS=LASTmeasures the time point when v(2) crosses 0.7 V for the last time (any slope).General form 3:. MEASURE {DC | AC | TRAN | SP} r e s u l t WHEN o u t _ v a r i a b l e = o u t _ v a r i a b l e 2<TD= t d > <FROM= v a l > <TO= v a l > <CROSS=# | CROSS=LAST> <RISE=#| RISE=LAST> <FALL=# | FALL=LAST>Measure statement:.measure tran teval WHEN v(2)=v(1) RISE=LASTmeasures the time point when v(2) and v(1) are equal, v(2) rising for the last time.General form 4:. MEASURE {DC | AC | TRAN | SP} r e s u l t FIND o u t _ v a r i a b l e WHENo u t _ v a r i a b l e 2 = v a l <TD= t d > <FROM= v a l > <TO= v a l > <CROSS=# |CROSS=LAST> <RISE=# | RISE=LAST> <FALL=# | FALL=LAST>Measure statement:.measure tran yeval FIND v(2) WHEN v(1)=-0.4 FALL=LASTreturns the dependent (y) variable drawn from v(2) at the time point when v(1) equals a valueof -0.4, v(1) falling for the last time.General form 5:. MEASURE {DC | AC | TRAN | SP} r e s u l t FIND o u t _ v a r i a b l e WHENo u t _ v a r i a b l e 2 = o u t _ v a r i a b l e 3 <TD= t d > <CROSS=# | CROSS=LAST><RISE = # | RISE=LAST> <FALL = # | FALL=LAST>Measure statement:.measure tran yeval FIND v(2) WHEN v(1)=v(3) FALL=2returns the dependent (y) variable drawn from v(2) at the time point when v(1) crosses v(3),v(1) falling for the second time.General form 6:. MEASURE {DC | AC | TRAN | SP} r e s u l t FIND o u t _ v a r i a b l e AT= v a lMeasure statement:.measure tran yeval FIND v(2) AT=2mreturns the dependent (y) variable drawn from v(2) at the time point 2 ms (given by AT=time).
15.4.7
247
AVG|MIN|MAX|PP|RMS|MIN_AT|MAX_AT
General form 7:. MEASURE {DC | AC | TRAN | SP} r e s u l t {AVG | MIN |MAX| PP | RMS | MIN_AT |MAX_AT} o u t _ v a r i a b l e <TD= t d > <FROM= v a l > <TO= v a l >Measure statements:.measure tran ymax MAX v(2) from=2m to=3mreturns the maximum value of v(2) inside the time interval between 2 ms and 3 ms..measure tran tymax MAX_AT v(2) from=2m to=3mreturns the time point of the maximum value of v(2) inside the time interval between 2 ms and3 ms..measure tran ypp PP v(1) from=2m to=4mreturns the peak to peak value of v(1) inside the time interval between 2 ms and 4 ms..measure tran yrms RMS v(1) from=2m to=4mreturns the root mean square value of v(1) inside the time interval between 2 ms and 4 ms..measure tran yavg AVG v(1) from=2m to=4mreturns the average value of v(1) inside the time interval between 2 ms and 4 ms.
15.4.8
Integ
General form 8:. MEASURE {DC | AC | TRAN | SP} r e s u l t INTEG<RAL> o u t _ v a r i a b l e <TD= t d ><FROM= v a l > <TO= v a l >Measure statement:.measure tran yint INTEG v(2) from=2m to=3mreturns the area under v(2) inside the time interval between 2 ms and 3 ms.
15.4.9
param
General form 9:. MEASURE {DC | AC | TRAN | SP} r e s u l t
param = e x p r e s s i o n
Measure statement:.param fval=5.measure tran yadd param=fval + 7will evaluate the given expression fval + 7 and return the value 12.Expression is evaluated according to the rules given in chapt. 2.8.5 during start up of ngspice.It may contain parameters defined with the .param statement. It may also contain parametersresulting from preceding .meas statements.
248
.param vout_diff=50u....measure tran tdiff TRIG AT=1m TARG v(2) VAL=-0.8 CROSS=3.meas tran bw_chk param=(tdiff < vout_diff) ?
1 :
will evaluate the given ternary function and return the value 1 in bw_chk, if tdiff measured issmaller than parameter vout_diff.The expression may not contain vectors like v(10), e.g. anything resulting directly from asimulation. This may be handled with the following .meas command option.
15.4.10
The par(expression) option (15.5.6) allows to use algebraic expressions in the .measurelines. Every out_variable may be replaced by par(expression) within the general forms 1-9described above. Internally par(expression) will be substituted by a vector according to therules of the B source (chapt. 5.1). A typical example of the general form is shown below:General form 10:. MEASURE {DC | AC | TRAN | SP} r e s u l t
FIND p a r ( e x p r e s s i o n ) AT= v a l
Measure statement:.measure tran vtest find par((v(2)*v(1))) AT=2.3mwill return the product of the two voltages at time point 2.3 ms.
15.4.11
Deriv
General form:. MEASURE {DC | AC | TRAN | SP} r e s u l t DERIV<ATIVE> o u t _ v a r i a b l e AT=val. MEASURE {DC | AC | TRAN | SP} r e s u l t DERIV<ATIVE> o u t _ v a r i a b l e WHENout_variable2=val+ <TD= t d >+ <CROSS=# | CROSS=LAST> <RISE = # | RISE=LAST> <FALL = # | FALL=LAST>. MEASURE {DC | AC | TRAN | SP} r e s u l t DERIV<ATIVE> o u t _ v a r i a b l e+ WHEN o u t _ v a r i a b l e 2 = o u t _ v a r i a b l e 3+ <TD= t d >+ <CROSS=# | CROSS=LAST> <RISE = # | RISE=LAST> <FALL = # | FALL=LAST>.MEASURE {DC|AC|TRAN|SP} result DERIV<ATIVE> ... is not yet available.
15.4.12
More examples
Some other examples, also showing the use of parameters, are given below. Correspondingdemonstration input files are distributed with ngspice in folder /examples/measure.
249
Other examples:. meas t r a n i n v _ d e l a y 2 t r i g v ( i n ) v a l = vp / 2 t d =1n f a l l =1 t a r g v( out )+ v a l = vp / 2 r i s e =1. meas t r a n t e s t _ d a t a 1 t r i g AT = 1n t a r g v ( o u t ) v a l = vp / 2 r i s e=3. meas t r a n o u t _ s l e w t r i g v ( o u t ) v a l = 0 . 2 * vp r i s e =2 t a r g v ( o u t )+ v a l = 0 . 8 * vp r i s e =2. meas t r a n d e l a y _ c h k param = ( i n v _ d e l a y < 100 p s ) ? 1 : 0 . meas t r a n skew when v ( o u t ) = 0 . 6. meas t r a n skew2 when v ( o u t ) =skew_meas. meas t r a n skew3 when v ( o u t ) =skew_meas f a l l =2. meas t r a n skew4 when v ( o u t ) =skew_meas f a l l =LAST. meas t r a n skew5 FIND v ( o u t ) AT=2n. meas t r a n v0_min min i ( v0 ) from = d f a l l t o = d f a l l + p e r i o d . meas t r a n v0_avg avg i ( v0 ) from = d f a l l t o = d f a l l + p e r i o d . meas t r a n v 0 _ i n t e g i n t e g i ( v0 ) from = d f a l l t o = d f a l l + p e r i o d . meas t r a n v0_rms rms i ( v0 ) from = d f a l l t o = d f a l l + p e r i o d . meas dc i s _ a t FIND i ( v s ) AT=1. meas dc i s _ m a x max i ( v s ) from =0 t o = 3 . 5. meas dc v d s _ a t when i ( v s ) = 0 . 0 1. meas a c v o u t _ a t FIND v ( o u t ) AT=1MEG. meas a c v o u t _ a t d FIND vdb ( o u t ) AT=1MEG. meas a c vout_max max v ( o u t ) from =1k t o =10MEG. meas a c f r e q _ a t when v ( o u t ) = 0 . 1. meas a c v o u t _ d i f f t r i g v ( o u t ) v a l = 0 . 1 r i s e =1 t a r g v ( o u t ) v a l= 0 . 1 f a l l =1. meas a c f i x e d _ d i f f t r i g AT = 10 k t a r g v ( o u t ) v a l = 0 . 1 r i s e =1. meas a c v o u t _ a v g avgv ( o u t ) from =10 k t o =1MEG. meas a c v o u t _ i n t e g i n t e g v ( o u t ) from =20 k t o =500 k. meas a c f r e q _ a t 2 when v ( o u t ) = 0 . 1 f a l l =LAST. meas a c bw_chk param = ( v o u t _ d i f f < 100 k ) ? 1 : 0 . meas a c v o u t _ r m s rms v ( o u t ) from =10 t o =1G
15.5
Batch Output
15.5.1
General form:. save vector vector vector
Examples:. s a v e i ( v i n ) node1 v ( node2 ). s a v e @m1[ i d ] v s o u r c e # b r a n c h. s a v e a l l @m2[ v d s a t ]
250
The vectors listed on the .SAVE line are recorded in the rawfile for use later with ngspice orngnutmeg (ngnutmeg is just the data-analysis half of ngspice, without the ability to simulate).The standard vector names are accepted. Node voltages may be saved by giving the nodenameor v(nodename). Currents through an independent voltage source are given by i(sourcename)or sourcename#branch. Internal device data are accepted as @dev[param].If no .SAVE line is given, then the default set of vectors is saved (node voltages and voltagesource branch currents). If .SAVE lines are given, only those vectors specified are saved. Formore discussion on internal device data, e.g. @m1[id], see Appendix, chapt. 31.1. If you wantto save internal data in addition to the default vector set, add the parameter all to the additionalvectors to be saved. If the command .save vm(out) is given, and you store the data in arawfile, only the original data v(out) are stored. The request for storing the magnitude is ignored,because this may be added later during rawfile data evaluation with ngnutmeg or ngspice. Seealso the section on the interactive command interpreter (chapter 17.5) for information on howto use the rawfile.
15.5.2
.PRINT Lines
General form:. p r i n t p r t y p e ov1 <ov2 . . . ov8 >Examples:. p r i n t tran v (4) i ( vin ). p r i n t dc v ( 2 ) i ( v s r c ) v ( 2 3 , 1 7 ). p r i n t a c vm ( 4 , 2 ) v r ( 7 ) vp ( 8 , 3 )The .print line defines the contents of a tabular listing of one to eight output variables. prtypeis the type of the analysis (DC, AC, TRAN, NOISE, or DISTO) for which the specified outputsare desired. The form for voltage or current output variables is the same as given in the previous section for the print command; Spice2 restricts the output variable to the following forms(though this restriction is not enforced by ngspice):V(N1<,N2>)
I(VXXXXXXX)
251
Output variables for the noise and distortion analyses have a different general form from that ofthe other analyses. There is no limit on the number of .print lines for each type of analysis.The par(expression) option (15.5.6) allows to use algebraic expressions in the .printlines. .width (15.5.7) selects the maximum number of characters per line.
15.5.3
.PLOT Lines
General form:. p l o t p l t y p e ov1 <( p l o 1 , p h i 1 ) > <ov2 <( p l o 2 , p h i 2 ) > . . . ov8 >Examples:.....
plotplotplotplotplot
dc v ( 4 ) v ( 5 ) v ( 1 )t r a n v (17 , 5) (2 , 5) i ( vin ) v (17) (1 , 9)a c vm ( 5 ) vm ( 3 1 , 2 4 ) vdb ( 5 ) vp ( 5 )d i s t o hd2 hd3 (R) sim2t r a n v (5 , 3) v ( 4 ) (0 , 5) v ( 7 ) (0 , 10)
The .plot line defines the contents of one plot of from one to eight output variables. pltypeis the type of analysis (DC, AC, TRAN, NOISE, or DISTO) for which the specified outputs aredesired. The syntax for the ovi is identical to that for the .print line and for the plot commandin the interactive mode.The overlap of two or more traces on any plot is indicated by the letter X. When more thanone output variable appears on the same plot, the first variable specified is printed as wellas plotted. If a printout of all variables is desired, then a companion .print line should beincluded. There is no limit on the number of .plot lines specified for each type of analysis.The par(expression) option (15.5.6) allows to use algebraic expressions in the .plotlines.
15.5.4
General form:. f o u r f r e q ov1 <ov2 ov3 . . . >Examples:. f o u r 100K v ( 5 )The .four (or Fourier) line controls whether ngspice performs a Fourier analysis as a part ofthe transient analysis. freq is the fundamental frequency, and ov1 is the desired vector to beanalyzed. The Fourier analysis is performed over the interval <TSTOP-period, TSTOP>, whereTSTOP is the final time specified for the transient analysis, and period is one period of thefundamental frequency. The dc component and the first nine harmonics are determined. Formaximum accuracy, TMAX (see the .tran line) should be set to period/100.0 (or less for veryhigh-Q circuits). The par(expression) option (15.5.6) allows to use algebraic expressionsin the .four lines.
252
15.5.5
General form:. probe v e c t o r < v e c t o r v e c t o r . . . >Examples:. probe i ( vin ) i n p u t output. p r o b e @m1[ i d ]Same as .SAVE (see chapt. 15.5.1).
15.5.6
General form:par ( expression )output=par ( expression )
$ not in . measure
Examples:. f o u r 1001 s q 1 = p a r ( v ( 1 ) * v ( 1 ) ). m e a s u r e t r a n v t e s t f i n d p a r ( ( v ( 2 ) * v ( 1 ) ) ) AT= 2 . 3m. p r i n t tran output=par ( v ( 1 ) / v (2) ) v (1) v (2). p l o t dc v ( 1 ) d i f f = p a r ( ( v (4) v ( 2 ) ) / 0 . 0 1 ) o u t 2 2 2In the output lines .four, .plot, .print, .save and in the .measure evaluation it is possible to add algebraic expression for output, in addition to vectors. All of these output linesaccept par(expression), where expression is any expression as has already been definedfor the B source (see chapter 5.1). Thus expression may contain predefined functions, numerical values, constants, simulator output like v(n1) or i(vdb), parameters predefined by a .paramstatement, and the variables hertz, temper, and time.Internally expression is replaced by an internally generated voltage node, which is the outputof a B source, one node and B source per par(...). Several par(...) are allowed in each line,up to 99 per input file. The internal nodes are named pa_00 to pa_99. If your input file alreadycontains such node names, an error will occur, unless you rename these nodes.In .four, .plot, .print, .save, but not in .measure, an alternative syntaxoutput=par(expression) is possible. par(expression) may be used as describedabove. output is the name of the new node to replace the expression. So output has to beunique and a valid node name.The syntax of output=par(expression) is strict, no spaces between par and (, or between( and are allowed, ( and ) both are required. Also there is not much error checking on yourinput, if there is a typo, for example, an error may pop up at an unexpected place.
15.5.7
.width
253
Parameter out yields the maximum number of characters plotted in a row, if printing in columnsor an ASCII-plot is selected.
254
Chapter 16Starting ngspice16.1
Ngspice consists of the simulator and a front-end for data analysis and plotting. Input to thesimulator is a netlist file, including commands for circuit analysis and output control. Interactivengspice can plot data from a simulation on a PC or a workstation display.Ngspice on LINUX (and OSs like Cygwin, BCD, Solaris ...) uses the X Window System forplotting (see chapter 18.3) if the environment variable DISPLAY is available. Otherwise, a console mode (non-graphical) interface is used. If you are using X on a workstation, the DISPLAYvariable should already be set; if you want to display graphics on a system different from theone you are running ngspice or ngutmeg on, DISPLAY should be of the form "machine:0.0".See the appropriate documentation on the X Window System for more details.The MS Windows versions of ngspice and ngnutmeg will have a native graphics interface (seechapter 18.1).The front-end may be run as a separate "stand-alone" program under the name ngnutmeg. ngnutmeg is a subset of ngspice dedicated to data evaluation, still made available for historical reasons. Ngnutmeg will read in the "raw" data output file created by ngspice -r or by the writecommand during an interactive ngspice session.
16.2
The actual distribution of ngspice may be downloaded from the ngspice download web page.The installation for LINUX or MS Windows is described in the file INSTALL to be found inthe top level directory. You may also have a look at chapter 32 of this manual for compilinginstructions.If you want to check out the source code which is actually under development, you may havea look at the ngspice source code repository, which is stored using the Git Source Code Management (SCM) tool. The Git repository may be browsed on the Git web page, also useful fordownloading individual files. You may however download (or clone) the complete repository including all source code trees from the console window (LINUX, CYGWIN or MSYS/MINGW)by issuing the command (in a single line)
256
You need to have Git installed, which is available for all three OSs. The whole source treeis then available in <current directory>/ngspice. Compilation and local installation is againdescribed in INSTALL (or chapter 32). If you later want to update your files and download therecent changes from sourceforge into your local repository, cd into the ngspice directory andjust type
git pull
git pull will deny to overwrite modified files in your working directory. To drop your localchanges first, you can run
To learn more about git, which can be both powerful and difficult to master, please consult, especially: which has pointers to documentation and tutorials.
16.3
Command Synopsis:n g s p i c e [ o l o g f i l e ] [ r r a w f i l e ] [ b ] [ i ] [ i n p u t f i l engnutmeg [ ] [ d a t a f i l e . . . ]
Options are:
... ]
Long option
-n
no-spiceinit
-t TERM
terminal=TERM
-b
batch
-s
server
-i
interactive
-r FILE
rawfile=FILE
-p
pipe
-o FILE
output=FILE
-h-v-a
helpversionautorun
257
MeaningDont try to load the default data file ("rawspice.raw") if noother files are given (ngnutmeg only).Dont try to source the file ".spiceinit" upon start-up.Normally ngspice and ngnutmeg try to find the file in thecurrent directory, and if it is not found then in the usershome directory (obsolete).The program is being run on a terminal with mfb nameterm (obsolete).Run in batch mode. Ngspice reads the default input source(e.g. keyboard) or reads the given input file and performsthe analyses specified; output is either Spice2-likeline-printer plots ("ascii plots") or a ngspice rawfile. Seethe following section for details. Note that if the inputsource is not a terminal (e.g. using the IO redirectionnotation of "<") ngspice defaults to batch mode (-ioverrides). This option is valid for ngspice only.Run in server mode. This is like batch mode, except that atemporary rawfile is used and then written to the standardoutput, preceded by a line with a single "@", after thesimulation is done. This mode is used by the ngspicedaemon. This option is valid for ngspice only.Example for using pipes from the console window:cat adder.cir|ngspice -s|moreRun in interactive mode. This is useful if the standard inputis not a terminal but interactive mode is desired. Commandcompletion is not available unless the standard input is aterminal, however. This option is valid for ngspice only.Use rawfile as the default file into which the results of thesimulation are saved. This option is valid for ngspice only.Allow a program (e.g., xcircuit) to act as a GUI frontendfor ngspice through a pipe. Thus ngspice will assume thatthe input pipe is a tty and allows to run in interactive mode.All logs generated during a batch run (-b) will be saved inoutfile.A short help statement of the command line syntax.Prints a version information.Start simulation immediately, as if a control section.controlrun.endchad been added to the input file.
Further arguments to ngspice are taken to be ngspice input files, which are read and saved (ifrunning in batch mode then they are run immediately). Ngspice accepts Spice3 (and also mostSpice2) input files, and outputs ASCII plots, Fourier analyses, and node printouts as specifiedin .plot, .four, and .print cards. If an out parameter is given on a .width card (15.5.7),the effect is the same as set width = .... Since ngspice ASCII plots do not use multiple ranges,however, if vectors together on a .plot card have different ranges they do not provide as much
258
16.4
Starting options
16.4.1
Batch mode
Lets take as an example the Four-Bit binary adder MOS circuit shown in chapter 21.6, storedin a file adder-mos.cir. You may start the simulation immediately by callingngspice -b -r adder.raw -o adder.log adder-mos.cirngspice will start, simulate according to the .tran command and store the output data in a rawfileadder.raw. Comments, warnings and infos go to log file adder.log. Commands for batch modeoperation are described in chapt. 15.
16.4.2
Interactive mode
If you callngspicengspice will start, load spinit (16.5) and .spiceinit (16.6, if available), and then waits for yourmanual input. Any of the commands described in 17.5 may be chosen, but many of them areuseful only after a circuit has been loaded byngspice 1 -> source adder-mos.cirothers require the simulation being done already (e.g. plot):ngspice 2 ->runngspice 3 ->plot allvIf you call ngspice from the command line with a circuit file as parameter:ngspice adder-mos.cirngspice will start, load the circuit file, parse the circuit (same circuit file as above, containingonly dot commands (see chapt. 15) for analysis and output control). ngspice then just waits foryour input. You may start the simulation by issuing the run command. Following completionof the simulation you may analyze the data by any of the commands given in chapter 17.5.
16.4.3
If you add the following control section to your input file adder-mos.cir, you may call
259
ngspice adder-mos.cirfrom the command line and see ngspice starting, simulating and then plotting immediately.Control section:* ADDER 4 BIT ALLNANDGATE BINARY ADDER. controlset noaskquitsave vcc # branchrunp l o t vcc # branchrusage a l l. endcAny suitable command listed in chapter 17.5 may be added to the control section, as well ascontrol structures described in chapter 17.6. Batch-like behavior may be obtained by changingthe control section toControl section with batch-like behavior:* ADDER 4 BIT ALLNANDGATE BINARY ADDER. controlset noaskquitsave vcc # branchrunw r i t e a d d e r . raw v c c # b r a n c hquit. endcIf you put this control section into a file, say adder-start.sp, you may just add the line.include adder-start.spto your input file adder-mos.cir to obtain the batch-like behavior. In the following example theline .tran ... from the input file is overridden by the tran command given in the controlsection.Control section overriding the .tran command:* ADDER 4 BIT ALLNANDGATE BINARY ADDER. controlset noaskquitsave vcc # brancht r a n 1 n 500 np l o t vcc # branchrusage a l l. endcThe commands within the .control section are executed in the order they are listed and onlyafter the circuit has been read in and parsed. If you want to have a command being executedbefore circuit parsing, you may use the prefix pre_ (17.5.44) to the command.A warning is due however: If your circuit file contains such a control section (.control ... .endc),you should not start ngspice in batch mode (with -b as parameter). The outcome may be unpredictable!
260
16.5
Upon start up ngspice reads its configuration file spinit. spinit may be found inC:\Spice\share\ngspice\scripts (Windows) or /usr/local/share/ngspice/scripts (LINUX). The pathmay be overridden by setting the environmental variable SPICE_LIB_DIR to a path where/scripts will be added. ngspice for Windows will also search for spinit in the directory wherengspice.exe resides. If spinit is not found, a warning message is issued, but ngspice willcontinue (but of course without code models etc.).Standard spinit contents:* Standard ngspice i n i talias exit quita l i a s acct rusage a l lset x11lineararcs* s e t r n d s e e d =12*set filetype=ascii* s e t ngdebug
file
* unset briefstrcmp _ _ f l a g $program " n g s p i c e "i f $__flag = 0* F o r SPICE2 POLYs , e d i t t h e below l i n e t o p o i n t t o t h e l o c a t i o n* of your codemodel .c o d e m o d e l C : / S p i c e / l i b / s p i c e / s p i c e 2 p o l y . cm* The o t h e r c o d e m o d e l scodemodel C : / Spice / l i bcodemodel C : / Spice / l i bcodemodel C : / Spice / l i bcodemodel C : / Spice / l i b
////
spicespicespicespice
/ a n a l o g . cm/ d i g i t a l . cm/ x t r a d e v . cm/ x t r a e v t . cm
endunset __flagspinit contains a script which is run upon start up of ngspice. You may find details of scripting inthe next chapter. Aliases (name equivalences) are set. set filetype=ascii will yield ASCIIoutput in the output data file (rawfile), a more compact binary format is used otherwise. Theasterisk * will comment out this line. If used by ngspice, spinit will then load the XSPICE codemodels from their absolute paths. You may also define relative paths here. set ngdebug willyield a lot of additional debug output. Any other contents of the script. e.g. plotting preferences,may be included here and started automatically by ngspice. The compatibility mode of ngspicehas to be set in spinit by set ngbehavior=all.If the standard path for the libraries (see standard spinit above or /usr/local/lib/spice under CYGWIN and LINUX) is not adequate, you may add for example the ./configure options--prefix=/usr --libdir=/usr/lib64 to set the codemodel search path to /usr/lib64/spice.Besides the standard lib only lib64 is acknowledged.
16.6
261
In addition to spinit you may define a file .spiceinit and put it into the current directoryor in your home directory. This file will be read in and executed after spinit, but before anyother input file is read. It may contain any script and override the commands given in spinit.If the command line option -n is used upon ngspice start up, this file will be ignored.
16.7
Environmental variables
16.7.1
262
16.7.2
16.8
Memory usage
Ngspice started with batch option (-b) and rawfile output (-r rawfile) will store all simulationdata immediately into the rawfile without keeping them in memory. Thus very large circuitsmay be simulated, the memory requested upon ngspice start up will depend on the circuit size,but will not increase during simulation.If you start ngspice in interactive mode or interactively with control section, all data will be keptin memory, to be available for later evaluation. A large circuit may outgrow even Gigabytes ofmemory. The same may happen after a very long simulation run with many vectors and manytime steps to be stored. Issuing the save <nodes> command will help to reduce memoryrequirements by saving only the data defined by the command.
16.9
Simulation time
Simulating large circuits may take an considerable amount of CPU time. If this is of importance,you should compile ngspice with the flags for optimum speed, set during configuring ngspicecompilation. Under LINUX, MINGW, and CYGWIN you should select the following option todisable the debug mode, which slows down ngspice:./configure --disable-debugAdding --disable-debug will set the -O2 optimization flag for compiling and linking.Under MS Visual Studio, you will have to select the release version which includes optimizationfor speed.If you have selected XSPICE (see chapters 12 and II) as part of your compilation configuration(by adding the option --enable-xspice to your ./configure command), the value of trtol(see 15.1.4) is set internally to 1 (instead of default 7) for higher precision if XSPICE codemodel A devices included in the circuit. This may double or even triple the CPU time neededfor any transient simulation, because the amount of time steps and thus iteration steps is morethan doubled. For MS Visual Studio compilation there is currently no simple way to excludeXSPICE during compilation.You may enforce higher speed during XSPICE usage by setting the variable xtrtol in your.spiceinit initialization file or in the .control section in front of the tran command (via setxtrtol=2 using the set command 17.5.57) and override the above trtol reduction. Bewarehowever of precision or convergence issues if you use XSPICE A devices, especially if xtrtolis set to values larger than 2.If your circuit comprises mostly of MOS transistors, and you have a multi-core processor athand, you may benefit from OpenMP parallel processing, as described next (16.10).
16.10
16.10.1
263
Todays computers typically come with CPUs having more than one core. It will thus be usefulto enhance ngspice to make use of such multi-core processors.Using circuits comprising mostly of transistors and e.g. the BSIM3 model, around 2/3 of theCPU time is spent in evaluating the model equations (e.g. in the BSIM3Load() function). Thesame happens with other advanced transistor models. Thus this function should be paralleled, ifpossible. Resulting from that the parallel processing has to be within a dedicated device model.Interestingly solving the matrix takes only about 10% of the CPU time, so paralleling the matrixsolver is of secondary interest here!A recent publication [1] has described a way to exactly do that using OpenMP, which is availableon many platforms and is easy to use, especially if you want to parallel processing of a for-loop.I have chosen the BSIM3 version 3.3.0 model, located in the BSIM3 directory, as the firstexample. The BSIM3load() function in b3ld.c contains two nested for-loops using linked lists(models and instances, e.g. individual transistors). Unfortunately OpenMP requires a loop withan integer index. So in file B3set.c an array is defined, filled with pointers to all instances ofBSIM3 and stored in model->BSIM3InstanceArray.BSIM3load() is now a wrapper function, calling the for-loop, which runs through functionsBSIM3LoadOMP(), once per instance. Inside BSIM3LoadOMP() the model equations are calculated.Typically you now need to synchronize the activities, in that storing the results into the matrixhas to be guarded. The trick offered by the authors now is that the storage is moved out of theBSIM3LoadOMP() function. Inside BSIM3LoadOMP() the updated data are stored in extralocations locally per instance, defined in bsim3def.h. Only after the complete for-loop is exercised, the update to the matrix is done in an extra function BSIM3LoadRhsMat() in the mainthread after the paralleled loop. No extra synchronization is required.Then the thread programming needed is only a single line!!#pragma omp parallel for num_threads(nthreads) private(here)introducing the for-loop.This of course is made possible only thanks to the OpenMP guys and the clever trick on nosynchronization introduced by the above cited authors.The time-measuring function getrusage() used with LINUX or Cygwin to determine the CPUtime usage (with the rusage option enabled) counts tics from every core, adds them up, andthus reports a CPU time value enlarged by a factor of 8 if 8 threads have been chosen. So nowngspice is forced to use ftime for time measuring if OpenMP is selected.
16.10.2
Some results
Some results on an inverter chain with 627 CMOS inverters, running for 200ns, compiled withVisual Studio professional 2008 on Windows 7 (full optimization) or gcc 4.4, SUSE LINUX11.2, -O2, on a i7 860 machine with four real cores (and 4 virtuals using hyperthreading) areshown in table 16.1.
264
16.10.3
Usage
To state it clearly: OpenMP is installed inside the model equations of a particular model. So forthe moment it is available only in BSIM3 version 3.3.0, not in version 3.2.4 nor in any otherBSIM3 model, in BSIM4 versions 4.6.5 or 4.7, not in any other BSIM4 model, and in B4SOI,version 4.3.1, not in any other SOI model. Older parameter files of version 4.6.x (x any numberup to 5) are accepted, you have to check for compatibility.Under LINUX you may run./autogen.sh./configure ...
--enable-openmp
make installThe same has been tested under MS Windows with CYGWIN and MINGW as well and delivers similar results.Under MS Windows with Visual Studio Professional you have to place an additional preprocessor flag USE_OMP, and then enable /openmp. Visual Studio Express is not sufficientdue to lack of OpenMP support. Even Visual Studio Professional lacks debugging supportfor OpenMP. There are local preprocessor flags (USE_OMP3 in bsim3def.h, USE_OMP4 inbsim4def.h, and USE_OMP4SOI in b4soidef.h) which you may modify individually if youwant to switch off OpenMP in only one of the models BSIM3, BSIM4, or B4SOI.The number of threads has to be set manually by placingset num_threads=4into spinit or .spiceinit. If OpenMP is enabled, but num_threads not set, a default value num_threads=2is set internally.If you run a circuit, please keep in mind to select BSIM3 (levels 8, 49) version 3.3.0 (11.2.9),by placing this version number into your parameter files, BSIM4 (levels 14, 54) version 4.6.5or 4.7 (11.2.10), or B4SOI (levels 10, 58) version 4.3.1 (11.2.12).If you run ./configure without --enable-openmp (or without USE_OMP preprocessor flagunder MS Windows), you will get the standard, not paralleled BSIM3 and BSIM4 model, as
265
has been available from Berkeley. If OpenMP is selected and the number of threads set to 1,there will be only a very slight CPU time disadvantage (typ. 3%) compared to the standard, nonOpenMP build.
16.10.4
Literature
[1] R.K. Perng, T.-H. Weng, and K.-C. Li: "On Performance Enhancement of Circuit SimulationUsing Multithreaded Techniques", IEEE International Conference on Computational Scienceand Engineering, 2009, pp. 158-165
16.11
A program may write the spice input to the console. This output is redirected to ngspice via |.ngspice called with the -s option writes its output to the console, which again is redirected to areceiving program by |. In the following simple example cat reads the input file and prints itcontent to the console, which is redirected to ngspice by a first pipe, ngspice transfers its output(similar to a raw file, see below) to less via another pipe.Example command line:c a t i n p u t . c i r | n g s p i c e s | l e s sUnder MS Windows you will need to compile ngspice as a console application (see chapt.32.2.5) for this server mode usage.Example input file:t e s t sv1 1 0 1r 1 1 0 2k. options filetype = ascii. s a v e i ( v1 ). dc v1 1 1 0 . 5. endIf you start ngspice console withngspice -syou may type in the above circuit line by line (not to forget the first line, which is a title andwill be ignored). If you close your input with ctrl Z, and return, you will get the followingoutput (this is valid for MINGW only) on the console, like a raw file:Circuit: test -sDoing analysis at TEMP = 27.000000 and TNOM = 27.000000Title: test -s
266
The number 5 of the last line @@@ 122 5 shows the number of data points, which is missing inthe above line No. Points: 0 because at the time of writing to the console it has not yetbeen available.ctrl Z is not usable here in LINUX, a patch to install ctrl D instead is being evaluated.
16.12
e x e c 3> i n p u t . f i f oecho " I can w r i t e t o i n p u t . f i f o "echo " S t a r t p r o c e s s i n g . . . "echo ""echoechoechoechoechoecho
267
268
Circuit.cir:* Circuit . cirV1 n0 0 SIN ( 0 10 1kHz )C1 n1 n0 3 . 3 nFR1 0 n1 1k. end
16.13
Compatibility
ngspice is a direct derivative of spice3f5 from UC Berkeley and thus inherits all of the commands available in its predecessor. Thanks to the open source policy of UCB (original spice3from 1994 is still available here), several commercial variants have sprung off, either being morededicated to IC design or more concentrating on simulating discrete and board level electronics.None of the commercial and almost none of the freely downloadable spice providers publishesthe source code. All of them have proceeded with the development, by adding functionality, orby adding a more dedicated user interface. Some have kept the original spice syntax for theirnetlist description, others have quickly changed some if not many of the commands, functionsand procedures. Thus it is difficult, if not impossible, to offer a simulator which acknowledgesall of these netlist dialects. ngspice includes some features which enhance compatibility whichare included automatically. This selection may be controlled to some extend by setting the compatibility mode. Others may be invoked by the user by small additions to the netlist input file.Some of them are listed in this chapter, some will be integrated into ngspice at a later stage,others will be added if they are reported by users.
16.13.1
Compatibility mode
The variable (17.7) ngbehavior sets the compatibility mode. all is set as the default value.spice3 as invoked by the commandset ngbehavior=spice3in spinit or .spiceinit will disable some of the advanced ngspice features. ps will enableincluding a library by a simple .lib <lib_filename> statement which is not compatible tothe more comfortable library handling described in chapt. 2.7.
16.13.2
Missing functions
You may add one or more function definitions to your input file, as listed below..func.func.func.func
16.13. COMPATIBILITY
16.13.3
Devices
16.13.3.1
269
16.13.3.2
VSwitch
The VSwitchS1 2 3 11 0 SW.MODEL SW VSWITCH(VON=5V VOFF=0V RON=0.1 ROFF=100K)may becomea1 11 (2 3) sw.MODEL SW aswitch(cntl_off=0.0 cntl_on=5.0 r_off=1e5+ r_on=0.1 log=TRUE)The XSPICE option has to be enabled.
16.13.4
16.13.4.1
.lib
The ngspice .lib command (see 2.7) requires two parameters, a file name followed by a libraryname. If no library name is given, the line.lib filenameshould be replaced by.inc filenameAlternatively, the compatibility mode (16.13.1) may be set to ps.
16.13.4.2
.step
Repeated analysis in ngspice if offered by a short script inside of a .control section (see chapt.17.8.7) added to the input file. A simple application (multiple dc sweeps) is shown below.
270
16.14
Tests
The ngspice distribution is accompanied by a suite of test input and output files, located in thedirectory ngspice/tests. Originally this suite was meant to see if ngspice with all modelswas made and installed properly. It is started by$ make checkfrom within your compilation and development shell. A sequence of simulations is thus started,its outputs compared to given output files by comparisons string by string. This feature ismomentarily used only to check for the BSIM3 model (11.2.9) and the XSPICE extension (12).Several other input files located in directory ngspice/tests may serve as light-weight examplesfor invoking devices and simple circuits.Todays very complex device models (BSIM4 (see 11.2.10), HiSIM (see 11.2.14) and others)require a different strategy for verification. Under development for ngspice is the CMC Regression test by Colin McAndrew, which accompanies every new model. A major advantage is thescalability of the diff comparisons, which check for equality within a given tolerance. A set of
271
Perl modules cares for input, output and comparisons of the models. Currently BSIM4, BSIMSOI4, HiSIM, and HiSIMHV models implement the new test. You may invoke it by runningthe command given above or by$ make -i check 2>&1 | tee results-i will make make to ignore any errors, tee will provide console output as well as printing tofile results. Be aware that under MS Windows you will need the console binary (see 32.2.5)to run the CMC tests, and you have to have Perl installed!
16.15
Ngspice is a complex piece of software. The source code contains over 1500 files. Variousmodels and simulation procedures are provided, some of them not used and tested intensively.Therefore errors may be found, some still evolving from the original spice3f5 code, othersintroduced during the ongoing code enhancements.If you happen to experience an error during the usage of ngspice, please send a report to thedevelopment team. Ngspice is hosted on sourceforge, the preferred place to post a bug report isthe ngspice bug tracker. We would prefer to have your bug tested against the actual source codeavailable at Git, but of course a report using the most recent ngspice release is welcome! Pleaseprovide the following information with your report:Ngspice versionOperating systemSmall input file to reproduce the bugActual output versus the expected output
272
Chapter 17Interactive Interpreter17.1
The simulation flow in ngspice (input, simulation, output) may be controlled by dot commands(see chapt. 15 and 16.4.1) in batch mode. There is, however, a much more powerful controlscheme available in ngspice, traditionally coined Interactive Interpreter, but being much morethan just that. In fact there are several ways to use this feature, truly interactively by typingcommands to the input, but also running command sequences as scripts or as part of your inputdeck in a quasi batch mode.You may type in expressions, functions (17.2) or commands (17.5) into the input console toelaborate on data already achieved from the interactive simulation session.Sequences of commands, functions and control structures (17.6) may be assembled as a script(17.8) into a file, and then activated by just typing the file name into the console input of aninteractive ngspice session.Finally, and most useful, is it to add a script to the input file, in addition the the netlist and dotcommands. This is achieved by enclosing the script into .control ... .endc (see 16.4.3,and 17.8.7 for an example). This feature enables a wealth of control options. You may setinternal (17.7) and other variables, start a simulation, evaluate the simulation output, start a newsimulation based on these data, and finally make use of many options for outputting the data(graphically or into output files).
17.2
Ngspice and ngnutmeg store data in the form of vectors: time, voltage, etc. Each vector has atype, and vectors can be operated on and combined algebraically in ways consistent with theirtypes. Vectors are normally created as the output of a simulation, or when a data file (output rawfile) is read in again (ngspice, ngnutmeg, see the load command 17.5.36), or when the initialdata-file is loaded directly into ngnutmeg. They can also be created with the let command817.5.33).An expression is an algebraic formula involving vectors and scalars (a scalar is a vector oflength 1) and the following operations:
274
+ * / ^ % ,
% is the modulo operator, and the comma operator has two meanings: if it is present in theargument list of a user definable function, it serves to separate the arguments. Otherwise, theterm x , y is synonymous with x + j(y). Also available are the logical operations & (and),| (or), ! (not), and the relational operations <, >, >=, <=, =, and <> (not equal). If used in analgebraic expression they work like they would in C, producing values of 0 or 1. The relationaloperators have the following synonyms:
Operatorgtltgeleneandornoteq
Synonym><>=<=<>&|!=
The operators are useful when < and > might be confused with the internal IO redirection (see17.4, which is almost always happening). It is however safe to use < and > with the definecommand (17.5.14).
avg(vector)
group_delay(vector)
vector(number)
unitvec(number)
FunctionMagnitude of vector (same as abs(vector)).Phase of vector.Phase of vector. Continuous values, no discontinuity atPI.Phase of vector. Continuous values, no discontinuity atPI. Real phase vector in degrees as input.i(sqrt(-1)) times vector.The real component of vector.The imaginary part of vector.20 log10(mag(vector)).The logarithm (base 10) of vector.The natural logarithm (base e) of vector.e to the vector power.The absolute value of vector (same as mag).The square root of vector.The sine of vector.The cosine of vector.The tangent of vector.The inverse tangent of vector.The hyperbolic sine of vector.The hyperbolic cosine of vector.The hyperbolic tangent of vector.Largest integer that is less than or equal to vector.Smallest integer that is greater than or equal to vector.The vector normalized to 1 (i.e, the largest magnitude ofany component is 1).The result is a scalar (a length 1 vector) that is the mean ofthe elements of vector (elements values added, divided bynumber of elements).The average of a vector.Returns a vector where each element is the mean of thepreceding elements of the input vector (including theactual element).Calculates the group delay -dphase[rad]/dw[rad/s]. Input isthe complex vector of a system transfer function versusfrequency, resembling damping and phase per frequencyvalue. Output is a vector of group delay values (real valuesof delay times) versus frequency.The result is a vector of length number, with elements 0, 1,... number - 1. If number is a vector then just the firstelement is taken, and if it isnt an integer then the floor ofthe magnitude is used.The result is a vector of length number, all elements havinga value 1.
275
276
Namelength(vector)interpolate(plot.vector)
deriv(vector)
vecd(vector)vecmin(vector)minimum(vector)vecmax(vector)maximum(vector)fft(vector)ifft(vector)sortorder(vector)
FunctionThe length of vector.The result of interpolating the named vector onto the scaleof the current plot. This function uses the variablepolydegree to determine the degree of interpolation.Calculates the derivative of the given vector. This usesnumeric differentiation by interpolating a polynomial andmay not produce satisfactory results (particularly withiterated differentiation). The implementation onlycalculates the derivative with respect to the real componentof that vectors scale.Compute the differential of a vector.Returns the value of the vector element with minimumvalue. Same as minimum.Returns the value of the vector element with minimumvalue. Same as vecmin.Returns the value of the vector element with maximumvalue. Same as maximum.Returns the value of the vector element with maximumvalue. Same as vecmax.fast fourier transforminverse fast fourier transformReturns a vector with the positions of the elements in a realvector after they have been sorted into increasing orderusing a stable method (qsort).
Several functions offering statistical procedures are listed in the following table:
sgauss(vector)
sunif(vector)
poisson(vector)
exponential(vector)
277
FunctionA vector with each component a random integer between 0and the absolute value of the input vectors correspondinginteger element value.Returns a vector of random numbers drawn from aGaussian distribution (real value, mean = 0 , standarddeviation = 1). The length of the vector returned isdetermined by the input vector. The contents of the inputvector will not be used. A call to sgauss(0) will return asingle value of a random number as a vector of length 1..Returns a vector of random real numbers uniformlydistributed in the interval [-1 .. 1[. The length of the vectorreturned is determined by the input vector. The contents ofthe input vector will not be used. A call to sunif(0) willreturn a single value of a random number as a vector oflength 1.Returns a vector with its elements being integers drawnfrom a Poisson distribution. The elements of the inputvector (real numbers) are the expected numbers l.Complex vectors are allowed, real and imaginary valuesare treated separately.Returns a vector with its elements (real numbers) drawnfrom an exponential distribution. The elements of the inputvector are the respective mean values (real numbers).Complex vectors are allowed, real and imaginary valuesare treated separately.
An input vector may be either the name of a vector already defined or a floating-point number(a scalar). A scalar will result in an output vector of length 1. A number may be written inany format acceptable to ngspice, such as 14.6Meg or -1.231e-4. Note that you can either usescientific notation or one of the abbreviations like MEG or G, but not both. As with ngspice, anumber may have trailing alphabetic characters.The notation expr [num] denotes the numth element of expr. For multi-dimensional vectors,a vector of one less dimension is returned. Also for multi-dimensional vectors, the notationexpr[m][n] will return the nth element of the mth subvector. To get a subrange of a vector, usethe form expr[lower, upper]. To reference vectors in a plot that is not the current plot (see thesetplot command, below), the notation plotname.vecname can be used. Either a plotname ora vector name may be the wildcard all. If the plotname is all, matching vectors from all plotsare specified, and if the vector name is all, all vectors in the specified plots are referenced. Notethat you may not use binary operations on expressions involving wildcards - it is not obviouswhat all + all should denote, for instance. Thus some (contrived) examples of expressions are:Expressions examples:c o s ( TIME ) + db ( v ( 3 ) )s i n ( cos ( log ( [ 1 2 3 4 5 6 7 8 9 1 0 ] ) ) )TIME * r n d ( v ( 9 ) ) 15 * c o s ( v i n # b r a n c h ) ^ [ 7 . 9 e5 8 ]n o t ( ( a c 3 . FREQ [ 3 2 ] & t r a n 1 . TIME [ 1 0 ] ) g t 3 )( s u n i f ( 0 ) ge 0 ) ? 1 . 0 : 2 . 0mag ( f f t ( v ( 1 8 ) ) )
278
Vector names in ngspice may have look like @dname[param], where dname is either the nameof a device instance or of a device model. This vector contains the value of the param parameterof the device or model. See Appendix, chapt. 31 for details of which parameters are available.The value is a vector of length 1. This function is also available with the show command, andis available with variables for convenience for command scripts.There are a number of pre-defined constants in ngspice, which you may use by their name. Theyare stored in plot (17.3) const and are listed in the table below:NamepiecikelvinechargeboltzplanckyesnoTRUEFALSE
Description
Value3.14159...2.71828...m/sec299,792,500
1-273.15C1.60219e-19 C1.38062e-23J/K6.62620e-341010
These constants are all given in MKS units. If you define another variable with a name thatconflicts with one of these then it takes precedence.Additional constants may be generated during circuit setup (see .csparam, 2.10).
17.3
Plots
The output vectors of any analysis are stored in plots, a traditional SPICE notion. A plot is agroup of vectors. A first tran command will generate several vectors within a plot tran1. Asubsequent tran command will store their vectors in tran2. Then a linearize command willlinearize all vectors from tran2 and store them in tran3, which then becomes the current plot. Afft will generate a plot spec1, again now the current plot. The display command always willshow all vectors in the current plot. Echo $plots followed by Return lists all plots generatedso far. Setplot followed by Return will show all plots and ask for a (new) plot to becomecurrent. A simple Return will end the command. Setplot name will change the current plotto name (e.g. setplot tran2 will make tran2 the current plot). A sequence name.vectormay be used to access the vector from a foreign plot.You may generate plots by yourself: setplot new will generate a new plot named unknown1,set curplottitle=a new plot will set a title, set curplotname=myplot will set itsname as a short description, set curplotdate=Sat Aug 28 10:49:42 2010 will set itsdate. Note that strings with spaces have to be given with double quotes.Of course the notion plot will be used by this manual also in its more common meaning,denoting a graphics plot or being a plot command. Be careful to get the correct meaning.
17.4
Command Interpretation
17.4.1
On the console
279
On the ngspice console window (or into the Windows GUI) you may directly type in any command from 17.5. Within a command sequence Input/output redirection is available (see chapt.17.8.8 for an example) - the symbols >, >>, >&, >>&, and < have the same effects as in theC-shell. This I/O-redirection is internal to ngspice commands, and should not be mixed up withthe external I/O-redirection offered by the usual shells (LINUX, MSYS etc.), see 17.5.62.You may type multiple commands on one line, separated by semicolons.
17.4.2
Scripts
If a word is typed as a command, and there is no built-in command with that name, the directories in the sourcepath list are searched in order for a file with the name given by the word. Ifit is found, it is read in as a command file (as if it were sourced). Before it is read, however, thevariables argc and argv are set to the number of words following the file-name on the command line, and a list of those words respectively. After the file is finished, these variables areunset. Note that if a command file calls another, it must save its argv and argc since they arealtered. Also, command files may not be re-entrant since there are no local variables. Of course,the procedures may explicitly manipulate a stack.... This way one can write scripts analogousto shell scripts for ngnutmeg and ngspice.Note that for the script to work with ngspice, it must begin with a blank line (or whatever else,since it is thrown away) and then a line with .control on it. This is an unfortunate resultof the source command being used for both circuit input and command file execution. Notealso that this allows the user to merely type the name of a circuit file as a command and it isautomatically run. The commands are executed immediately, without running any analyses thatmay be specified in the circuit (to execute the analyses before the script executes, include arun command in the script).There are various command scripts installed in /usr/local/lib/spice/scripts (or whatever the path is on your machine), and the default sourcepath includes this directory, so youcan use these command files (almost) like built-in commands.
17.4.3
The problably most common way to invoke the commands described in the following chapter17.5 is to add a .control ... .endc section to the circuit input file (see 16.4.3).
280
Example:. controlpre_set strict_errorhandlingu n s e t ngdebug* s a v e o u t p u t s and s p e c i a l ss a v e x1 . x1 . x1 . 7 V( 9 ) V( 1 0 ) V( 1 1 ) V( 1 2 ) V( 1 3 )rundisplay* p l o t t h e i n p u t s , u s e o f f s e t t o p l o t on t o p o f e a c h o t h e rp l o t v (1) v (2)+4 v (3)+8 v (4)+12 v (5)+16 v (6)+20 v (7)+24 v (8)+28* p l o t t h e o u t p u t s , u s e o f f s e t t o p l o t on t o p o f e a c h o t h e rp l o t v ( 9 ) v (10)+4 v (11)+8 v (12)+12 v (13)+16. endc
17.5
Commands
17.5.1
General Form:a c ( DEC | OCT | LIN ) N F s t a r t F s t o pDo an small signal ac analysis (see also chapter 15.3.1) over the specified frequency range.DEC decade variation, and N is the number of points per decade.OCT stands for octave variation, and N is the number of points per octave.LIN stands for linear variation, and N is the number of points.fstart is the starting frequency, and fstop is the final frequency.Note that in order for this analysis to be meaningful, at least one independent source must havebeen specified with an ac value.In this ac analysis all non-linear devices are linearized around their actual dc operating point.All Ls and Cs get their imaginary value, depending on the actual frequency step. Each outputvector will be calculated relative to the input voltage (current) given by the ac value (Iin equalsto 1 in the example below). The resulting node voltages (and branch currents) are complexvectors. Therefore you have to be careful using the plot command.
17.5. COMMANDS
281
Example:* AC t e s tI i n 1 0 AC 1R1 1 2 100L1 2 0 1. controlAC LIN 101 10 10Kplot v (2)$ real part !p l o t mag ( v ( 2 ) ) $ m a g n i t u d ep l o t db ( v ( 2 ) )$ same a s vdb ( 2 )p l o t imag ( v ( 2 ) ) $ i m a g i n a r y p a r t o f v ( 2 )p l o t r e a l ( v ( 2 ) ) $ same a s p l o t v ( 2 )p l o t phase ( v ( 2 ) ) $ phase in radp l o t cph ( v ( 2 ) ) $ p h a s e i n r a d , c o n t i n u o u s beyond p ip l o t 1 8 0 / P I * p h a s e ( v ( 2 ) ) $ p h a s e i n deg. endc. endIn addition to the plot examples given above you may use the variants of vxx(node) described inchapter 15.5.2 like vdb(2). An option to suppress OP analysis before AC may be set for linearcircuits (15.1.3).
17.5.2
General Form:a l i a s [ word ] [ t e x t
...]
Causes word to be aliased to text. History substitutions may be used, as in C-shell aliases.
17.5.3
Alter changes the value for a device or a specified parameter of a device or model.General Form:a l t e r dev = < e x p r e s s i o n >a l t e r dev param = < e x p r e s s i o n >a l t e r @dev [ param ] = < e x p r e s s i o n ><expression> must be real (complex isnt handled right now, integer is fine though, but nostrings. For booleans, use 0/1.Old style (pre 3f4):a l t e r device valuea l t e r device parameter value [ parameter value ]Using the old style, its first form is used by simple devices which have one principal value (resistors, capacitors, etc.) where the second form is for more complex devices (bjts, etc.). Model
282
parameters can be changed with the second form if the name contains a "#". For specifying alist of parameters as values, start it with "[", followed by the values in the list, and end with "]".Be sure to place a space between each of the values and before and after the "[" and "]".Some examples are given below:Examples (Spice3f4 style):alteralteralteralteralter
vd = 0 . 1vg dc = 0 . 6@m1[w] = 15 e 06@vg [ s i n ] [ 1 1 . 5 2MEG ]@Vi [ pwl ] = [ 0 1 . 2 100 p 0 ]
17.5.4
General form:a l t e r m o d mod param = < e x p r e s s i o n >a l t e r m o d @mod[ param ] = < e x p r e s s i o n >Example:a l t e r m o d nc1 t o x = 10 e9a l t e r m o d @nc1 [ t o x ] = 10 e9Altermod operates on models and is used to change model parameters. The above examplewill change the parameter tox in all devices using the model nc1, which is defined as*** BSIM3v3 model.MODEL nc1 nmos LEVEL=8 version = 3.2.2+ acm = 2 mobmod = 1 capmod = 1 noimod = 1+ rs = 2.84E+03 rd = 2.84E+03 rsh = 45+ tox = 20E-9 xj = 0.25E-6 nch = 1.7E+17+ ...If you invoke the model by the MOS deviceM1 d g s b nc1 w=10u l=1u
283
17.5.5
General Form:asciiplot plotargsProduce a line printer plot of the vectors. The plot is sent to the standard output, so you can putit into a file with asciiplot args ... > file. The set options width, height, and nobreak determinethe width and height of the plot, and whether there are page breaks, respectively. Note that youwill have problems if you try to asciiplot something with an X-scale that isnt monotonic (i.e,something like sin(TIME) ), because asciiplot uses a simple-minded linear interpolation. Theasciiplot command doesnt deal with log scales or the delta keywords.
284
17.5.6
General Form:aspice input f i l e [ output f i l e ]Start an ngspice run, and when it is finished load the resulting data. The raw data is kept ina temporary file. If output-file is specified then the diagnostic output is directed into that file,otherwise it is thrown away.
17.5.7
General Form:bugSend a bug report. Please include a short summary of the problem, the version number andname of the operating system that you are running, the version of ngspice that you are running,and the relevant ngspice input file. (If you have defined BUGADDR, the mail is delivered to there.)
17.5.8
General Form:cd [ d i r e c t o r y ]Change the current working directory to directory, or to the users home directory if none isgiven.
17.5.9
General Form:cdumpDumps the control sequence to the screen (all statements inside the .control ... .endc structurebefore the line with cdump). Indentations show the structure of the sequence. The examplebelow is printed if you add cdump to /examples/Monte_Carlo/MonteCarlo.sp.
285
Example (abbreviated):l e t mc_runs =5l e t r u n =0...d e f i n e a g a u s s ( nom , a v a r , s i g ) ( nom + a v a r / s i g * s g a u s s ( 0 ) )d e f i n e l i m i t ( nom , a v a r ) ( nom + ( ( s g a u s s ( 0 ) >=0) ? a v a r : a v a r ) )d o w h i l e r u n < mc_runsa l t e r c1 = u n i f ( 1 e 09 , 0 . 1 )...a c o c t 100 250 k 10megmeas a c bw t r i g vdb ( o u t ) v a l =10 r i s e =1 t a r g vdb ( o u t ) v a l =10 f a l l =1s e t r u n =" $&r u n "...l e t run=run + 1endp l o t db ( { $ s c r a t c h } . a l l v )echop r i n t { $ s c r a t c h } . bwhcdump
17.5.10
General Form:circbyline lineEnter a circuit line by line. line is any circuit line, as found in the *.cir ngspice input files.The first line is a title line. The entry will be finished by entering .end. Circuit parsing is thenstarted automatically.Example:circbylinecircbylinecircbylinecircbylinecircbylinerunp l o t i ( v1 )
17.5.11
test circuitv1 1 0 1r1 1 0 1. dc v1 0 . 5 1 . 5 0 . 1. end
General Form:codemodel [ l i b r a r y
file ]
Load a XSPICE code model shared library file (e.g. analog.cm ...). Only available if ngspice iscompiled with the XSPICE option (enable-xspice) or with the Windows executable distributedsince ngspice21. This command has to be called from spinit (see chapt. 16.5) (or .spiceinit forpersonal code models, 16.6).
286
17.5.12
General Form:compose name v a l u e s v a l u e 1 [ v a l u e 2 . . . ]compose name parm = v a l [ parm = v a l . . . ]The first form takes the values and creates a new vector, the values may be arbitrary expressions.The second form has the following possible parameters:start The value at which the vector should start.stop The value at which the vector should end.step The difference between successive elements.lin The number of points, linearly spaced..
17.5.13
General Form:dc S o u r c e Name V s t a r t V s t o p V i n c r [ S o u r c e 2 V s t a r t 2 V s t o p 2 V i n c r 2 ]Do a dc transfer curve analysis. See the previous chapter 15.3.2 for more details. Severaloptions may be set (15.1.2).
17.5.14
General Form:d e f i n e f u n c t i o n ( arg1 , arg2 ,
expression
Define the user-definable function with the name function and arguments arg1, arg2, ... to beexpression, which may involve the arguments. When the function is later used, the arguments itis given are substituted for the formal arguments when it is parsed. If expression is not present,any definition for function is printed, and if there are no arguments to define then all currentlyactive definitions are printed. Note that you may have different functions defined with the samename but different arities. Some useful definitions are:Example:d e f i n e max ( x , y ) ( x > y ) * x + ( x <= y ) * yd e f i n e min ( x , y ) ( x < y ) * x + ( x >= y ) * yd e f i n e l i m i t ( nom , a v a r ) ( nom + ( ( s g a u s s ( 0 ) >= 0 ) ? a v a r : a v a r ) )
17.5.15
General Form:d e f t y p e [ v | p ] typename abbrev
287
defines types for vectors and plots. abbrev will be used to parse things like abbrev(name) andto label axes with M<abbrev>, instead of numbers. It may be omitted. Also, the command"deftype p plottype pattern ..." will assign plottype as the name to any plot with one of thepatterns in its Name: field.Example:deftype v capacitance Fs e t t y p e c a p a c i t a n c e moscapp l o t moscap v s v ( c c )
17.5.16
General Form:d e l e t e [ debugnumber . . . ]Delete the specified saved nodes and parameters, breakpoints and traces. The debug numbersare those shown by the status command (unless you do status > file, in which case the debugnumbers are not printed).
17.5.17
General Form:destroy [ plotnames |
all ]
Release the memory holding the output data (the given plot or all plots) for the specified runs.
17.5.18
General Form:d e v h e l p [[ c s v ] d e v i c e _ n a m e [ p a r a m e t e r ] ]Devhelp command shows the user information about the devices available in the simulator. Ifcalled without arguments, it simply displays the list of available devices in the simulator. Thename of the device is the name used inside the simulator to access that device. If the user specifies a device name, then all the parameters of that device (model and instance parameters) willbe printed. Parameter description includes the internal ID of the parameter (id#), the name usedin the model card or on the instance line (Name), the direction (Dir) and the description of theparameter (Description). All the fields are self-explanatory, except the direction. Directioncan be in, out or inout and corresponds to a write-only, read-only or a read/writeparameter. Read-only parameters can be read but not set, write only can be set but not read andread/write can be both set and read by the user.The -csv option prints the fields separated by a comma, for direct import into a spreadsheet.This option is used to generate the simulator documentation.
288
Example:devhelpdevhelp r e s i s t o rdevhelp c a p a c i t o r ic
17.5.19
General Form:d i f f p l o t 1 p l o t 2 [ vec . . . ]Compare all the vectors in the specified plots, or only the named vectors if any are given. Ifthere are different vectors in the two plots, or any values in the vectors differ significantly,the difference is reported. The variables diff_abstol, diff_reltol, and diff_vntol are used todetermine a significant difference.
17.5.20
General Form:d i s p l a y [ varname . . . ]Prints a summary of currently defined vectors, or of the names specified. The vectors are sortedby name unless the variable nosort is set. The information given is the name of the vector, thelength, the type of the vector, and whether it is real or complex data. Additionally, one vectoris labeled [scale]. When a command such as plot is given without a vs argument, this scale isused for the X-axis. It is always the first vector in a rawfile, or the first vector defined in a newplot. If you undefine the scale (i.e, let TIME = []), one of the remaining vectors becomes thenew scale (which one is unpredictable). You may set the scale to another vector of the plot withthe command setscale (17.5.60).
17.5.21
General Form:e c h o [ t e x t . . . ] [ $ v a r i a b l e ] [ " $&v e c t o r " ]Echos the given text, variable or vector to the screen. echo without parameters issues a blankline.
17.5.22
General Form:edit [ file ]Print the current ngspice input file into a file, call up the editor on that file and allow the user tomodify it, and then read it back in, replacing the original file. If a file-name is given, then edit
289
that file and load it, making the circuit the current one. The editor may be defined in .spiceinitor spinit by a command line likeset editor=emacsUsing MS Windows, to allow the edit command calling an editor, you will have to add theeditors path to the PATH variable of the command prompt windows (see here). edit then callscmd.exe with e.g. notepad++ and file as parameter, if you have setset editor=notepad++.exeto .spiceinit or spinit.
17.5.23
Eprint*: Print an event driven node (only used with XSPICE option)
General Form:e p r i n t node [ node ]e p r i n t node [ node ] > n o d e o u t . t x t ; o u t p u t r e d i r e c t e dPrint an event driven node generated or used by an XSPICE A device. These nodes are vectorsnot organized in plots. See chapt. 27.2.2 for an example. Output redirection into a file isavailable.
17.5.24
General Form:f f t vector1 [ vector2 ] . . .This analysis provides a fast Fourier transform of the input vector(s). fft is much faster thanspec (17.5.69) (about a factor of 50 to 100 for larger vectors) !The fft command will create a new plot consisting of the Fourier transforms of the vectors givenon the command line. Each vector given should be a transient analysis result, i.e. it shouldhave time as a scale. You will have got these vectors by the tran Tstep Tstop Tstartcommand.The vector should have a linear equidistant time scale. Therefore linearization using the linearizecommand is recommended before running fft. Be careful selecting a Tstep value small enoughfor good interpolation, e.g. much smaller than any signal period to be resolved by fft (seelinearize command). The Fast Fourier Transform will be computed using a window function as given with the specwindow variable. Its code is based on the FFT function provided at, downloaded April 5th, 2008, now to be foundhere. A new plot named specx will be generated with a new vector (having the same name asthe input vector, see command above) containing the transformed data.
290 ) )
Linearize will create a new vector V(2) in a new plot tran2. The command fft V(2) willcreate a new plot spec1 with vector V(2) holding the resulting data.The variables listed in the following table control operation of the fft command. Each can beset with the set command before calling fft.specwindow: This variable is set to one of the following strings, which will determine thetype of windowing used for the Fourier transform in the spec command. If not set, the defaultis "hanning".none No windowingrectangular Rectangular windowbartlet Bartlett (also triangle) windowblackman Blackman windowhanning Hanning (also hann or cosine) windowhamming Hamming windowgaussian Gaussian windowflattop Flat top window
291
specwindoworder: This can be set to an integer in the range 2-8. This sets the order whenthe Gaussian window is used in the spec command. If not set, order 2 is used.
17.5.25
General Form:f o u r i e r fundamental_frequency [ expression
Fourier is used to analyse the output vector(s) of a preceeding transient analysis (see 17.5.77).It does a Fourier analysis of each of the given values, using the first 10 multiples of the fundamental frequency (or the first nfreqs multiples, if that variable is set - see 17.7). The printedoutput is like that of the .four ngspice line (chapter 15.5.4). The expressions may be any validexpression (see 17.2), e.g. v(2). The evaluated expression values are interpolated onto a fixedspace grid with the number of points given by the fourgridsize variable, or 200 if it is not set.The interpolation is of degree polydegree if that variable is set, or 1. If polydegree is 0, then nointerpolation is done. This is likely to give erroneous results if the time scale is not monotonic,though.The fourier command not only issues a printout, but also generates vectors, one per expression.The size of the vector is 3 x nfreqs (per default 3 x 10). The name of the new vector is fouriermn,where m is set by the mth call to the fourier command, n is the nth expression given in the actualfourier command. fouriermn[0] is the vector of the 10 (nfreqs) frequency values, fouriermn[1]contains the 10 (nfreqs) magnitude values, fouriermn[2] the 10 (nfreqs) phase values of theresult.Example:* do t h e t r a n s i e n t a n a l y s i st r a n 1 n 1m* do t h e f o u r i e r a n a l y s i sf o u r i e r 3 . 3 4 e6 v ( 2 ) v ( 3 ) ; f i r s t c a l lf o u r i e r 100 e6 v ( 2 ) v ( 3 ); second c a l lgetindividualvalues*l e t newt1 = f o u r i e r 1 1 [ 0 ] [ 1 ]l e t newt2 = f o u r i e r 1 1 [ 1 ] [ 1 ]l e t newt3 = f o u r i e r 1 1 [ 2 ] [ 1 ]l e t newt4 = f o u r i e r 1 2 [ 0 ] [ 4 ]l e t newt5 = f o u r i e r 1 2 [ 1 ] [ 4 ]l e t newt6 = f o u r i e r 1 2 [ 2 ] [ 4 ]* p l o t magnitude of seccond e x p r e s s i o n ( v ( 3 ) )* from f i r s t c a l l v e r s u s f r e q u e n c yp l o t f o u r i e r 1 2 [ 1 ] vs f o u r i e r 1 2 [ 0 ]The plot command from the example plots the vector of the magnitude values, obtained bythe first call to fourier and evaluating the first expression in this call, against the vector of thefrequency values.
292
17.5.26
General Form:gnuplot f i l e plotargsLike plot, but using gnuplot for graphics output and further data manipulation. ngspice createsa file called file.plt containing the gnuplot command sequence, a file called file.data containing the data to be plotted, and a file called file.eps containing a postscript hard-copy ofthe plot. On LINUX gnuplot is called via xterm, which offers a gnuplot console to manipulatethe data. On Windows a gnuplot command console window is opened as well as the plot window. Of course you have to have gnuplot installed properly on your system. This option willwork with Gnuplot version 4.2.6, not with version 4.4, but again with 4.5 (as of August 2011).By setting the variable gnuplot_terminal inside the control section to png, gnuplot willgenerate a file file.png containing a compressed bitmap ready to include in text-processingprograms like Word etc.
17.5.27
General Form:hardcopy f i l e p l o t a r g sJust like plot, except that it creates a file called file containing the plot. The file is a postscriptimage. As an alternative the plot(5) format is available by setting the hcopydevtype variable toplot5, and can be printed by either the plot(1) program or lpr with the -g flag.
17.5.28
Prints help. This help information, however, is spice3f5-like, stemming from 1991 and thusis outdated. If commands are given, descriptions of those commands are printed. Otherwisehelp for only a few major commands is printed. On Windows this help command is no longeravailable. Spice3f5 compatible help may be found in the Spice 3 User manual. For ngspiceplease use this manual.
17.5.29
General Form:h i s t o r y [ number ]Print out the history, or the last number commands typed at the keyboard.
17.5.30
General Form:inventory
293
This commands accepts no argument and simply prints the number of instances of a particulardevice in a loaded netlist.
17.5.31
General Form:i p l o t [ node . . . ]Incrementally plot the values of the nodes while ngspice runs. The iplot command can be usedwith the where command to find trouble spots in a transient simulation.The @name[param] notation (31.1) might not work yet.
17.5.32
General Form:jobsReport on the asynchronous ngspice jobs currently running. Ngnutmeg checks to see if thejobs are finished every time you execute a command. If it is done then the data is loaded andbecomes available.
17.5.33
General Form:l e t name = e x p rCreates a new vector called name with the value specified by expr, an expression as describedabove. If expr is [] (a zero-length vector) then the vector becomes undefined. Individual elements of a vector may be modified by appending a subscript to name (ex. name[0]). If there areno arguments, let is the same as display.The command let creates a vector in the current plot, use setplot (17.5.59) to create a new plot.See also unlet (17.5.81), compose (17.5.12).
17.5.34
General Form:l i n e a r i z e vec . . .Create a new plot with all of the vectors in the current plot, or only those mentioned as arguments to the command, all data linearized onto an equidistant time scale.
294 ) ) t s t e p
Linearize will redo the vectors vec or renew all vectors of the current plot (e.g. tran3) if noarguments are given and store them into a new plot (e.g. tran4). The new vectors are interpolatedonto a linear time scale, which is determined by the values of tstep, tstart, and tstop inthe currently active transient analysis. The currently loaded input file must include a transientanalysis (a tran command may be run interactively before the last reset, alternately), and thecurrent plot must be from this transient analysis. The length of the new vector is (tstop- tstart) / tstep + 1.5. This command is needed for example if you want to do a fftanalysis (17.5.24). Please note that the parameter tstep of your transient analysis (see chapter15.3.9) has to be small enough to get adequate resolution, otherwise the command linearizewill do sub-sampling of your signal.
17.5.35
General Form:l i s t i n g [ l o g i c a l ] [ p h y s i c a l ] [ d e c k ] [ e x p a n d ] [ param ]If the logical argument is given, the listing is with all continuation lines collapsed into one line,and if the physical argument is given the lines are printed out as they were found in the file. Thedefault is logical. A deck listing is just like the physical listing, except without the line numbersit recreates the input file verbatim (except that it does not preserve case). If the word expand ispresent, the circuit is printed with all subcircuits expanded. The option param allows to printall parameters and their actual values.
17.5.36
General Form:load [ filename ] . . .Loads either binary or ascii format rawfile data from the files named. The default file-name israwspice.raw, or the argument to the -r flag if there was one.
17.5.37
295
Most of the input forms found in 15.4 may be used here with the command meas instead of.meas(ure). Using meas inside the .control ... .endc section offers additional features compared to the .meas use. meas will print the results as usual, but in addition will store its measurement result (typically the token result given in the command line) in a vector. This vectormay be used in following command lines of the script as an input value of another command.For details of the command see chapt. 15.4. The measurement type SP is only available here,because a fft command will prepare the data for SP measurement. Option autostop (15.1.4)is not available.Unfortunately par(expression) (15.5.6) will not work here, i.e. inside the .control section.You may use an expression by the let command instead, giving let vec_new = expression.Replacement for par(expression) in meas inside the .control sectionl e t v d i f f = v ( n1)v ( n0 )meas t r a n v t e s t f i n d v d i f f a t = 0 . 0 4 e3* t h e f o l l o w i n g w i l l n o t do h e r e :* meas t r a n v t e s t f i n d p a r ( v ( n1)v ( n0 ) ) a t = 0 . 0 4 e3
17.5.38
General Form:mdump < f i l e n a m e >If <filename> is given, the output will be stored in file <filename>, otherwise dumped toyour console.
17.5.39
Mrdump*: Dump the matrix right hand side values to a file (orto console)
General Form:mrdump < f i l e n a m e >If <filename> is given, the output will be appended to file <filename>, otherwise dumped toyour console.Example usage after ngspice has started:* Dump m a t r i x and RHS v a l u e s a f t e r 10 and 20 s t e p s* of a t r a n s i e n t s i m u l a t i o nsource rc . c i rs t e p 10mdump m1 . t x tmrdump mr1 . t x ts t e p 10mdump m2 . t x tmrdump mr2 . t x t* j u s t t o c o n t i n u e t o t h e ends t e p 10000
296
You may create a loop using the control structures (chapt. 17.6).
17.5.40
17.5.41
General Form:opDo an operating point analysis. See chapter 15.3.5 for more details.
17.5.42
General Form:option [ option=val ] [ option=val ] . . .Set any of the simulator variables as listed in chapt. 15.1. See this chapter also for moreinformation on the available options. The option command without any argument lists theactual options set in the simulator (to be verified). Multiple options may be set in a single line.The following example demonstrates a control section, which may be added to your circuit fileto test the influence of variable trtol on the number of iterations and on the simulation time.
297
17.5.43
v ( out50 )
General Form:p l ot exprs [ y l i m i t ylo yhi ] [ x l i m i t xlo xhi ] [ xindices x i l o x i h i ][ x c o m p r e s s comp ] [ x d e l t a x d e l ] [ y d e l t a y d e l ] [ x l o g ] [ y l o g ] [ l o g l o g ][ v s xname ] [ x l a b e l word ] [ y l a b e l word ] [ t i t l e word ] [ samep ][ linear ]Plot the given vectors or exprs on the screen (if you are on a graphics terminal). The xlimitand ylimit arguments determine the high and low x- and y-limits of the axes, respectively. Thexindices arguments determine what range of points are to be plotted - everything between thexiloth point and the xihith point is plotted. The xcompress argument specifies that only oneout of every comp points should be plotted. If an xdelta or a ydelta parameter is present, itspecifies the spacing between grid lines on the X- and Y-axis. These parameter names may beabbreviated to xl, yl, xind, xcomp, xdel, and ydel respectively.The xname argument is an expression to use as the scale on the x-axis. If xlog or ylog arepresent then the X or Y scale, respectively, is logarithmic (loglog is the same as specifying
298
both). The xlabel and ylabel arguments cause the specified labels to be used for the X and Yaxes, linear keyword is used to override a default logscale plot (as in the output for an AC analysis).Finally, the keyword polar generates a polar plot. To produce a smith plot, use the keywordsmith. Note that the data is transformed, so for smith plots you will see the data transformedby the function (x-1)/(x+1). To produce a polar plot with a smith grid but without performingthe smith transform, use the keyword smithgrid.If you specify plot all, all vectors (including the scale vector) are plotted versus the scalevector (see commands display (17.5.20) or setscale (17.5.60) on viewing the vectors of thecurrent plot). The command plot ally will not plot the scale vector, but all other real yvalues. The command plot alli will yield all current vectors, the command plot allv allvoltage vectors.If the vector name to be plotted contains -, or / or other tokens which may be taken for operators of an expression, and plotting fails, try enclosing the name in double quotes, e.g. plot/vout.Plotting of complex vectors, as may occur after an ac simulation, require some special considerations. Please see chapter 17.5.1 for details.
17.5.44
General Form:p r e _ <command>All commands in a .control ... .endc section are executed after the circuit has been parsed. If youneed command execution before circuit parsing, you may add these commands to the generalspinit or local .spiceinit files. Another possibility is adding a leading pre_ to a command withinthe .control section of an ordinary input file, which forces the command to be executed beforecircuit parsing. Basically <command> may be any command listed in chapter 17.5, howeveronly a few commands are indeed useful here. Some examples are given below:Examples:p r e _ u n s e t ngdebugpre_set strict_errorhandlingp r e _ c o d e m o d e l mymod . cmpre_<command> is available only in the .control mode (see 16.4.3), not in interactive mode,where the user may determine herself when a circuit is to be parsed, using the source command(17.5.68) .
17.5.45
299
General Form:p r i n t [ col ] [ l i n e ] expr . . .Prints the vector(s) described by the expression expr. If the col argument is present, print thevectors named side by side. If line is given, the vectors are printed horizontally. col is thedefault, unless all the vectors named have a length of one, in which case line is the default.The options width, length, and nobreak are effective for this command (see asciiplot). If theexpression is all, all of the vectors available are printed. Thus print col all > file prints everythingin the file in SPICE2 format. The scale vector (time, frequency) is always in the first columnunless the variable noprintscale is true. You may use the vectors alli, allv, ally with the printcommand, but then the scale vector will not be printed.Examples:s e t w i d t h =300print alls e t l e n g t h =500
17.5.46
General Form:quitquit [ exitcode ]Quit ngnutmeg or ngspice. Ngspice will ask for an acknowledgment if parameters have notbeen saved. If set noaskquit is specified, ngspice will terminate immediately.The optional parameter exitcode is an integer which set the exit code for ngspice, useful toreturn a success/fail value to the operating system.
17.5.47
General Form:rehashRecalculate the internal hash tables used when looking up UNIX commands, and make allUNIX commands in the users PATH available for command completion. This is useless unlessyou have set unixcom first (see above).
17.5.48
General Form:remcirc
300
This command removes the current circuit from the list of circuits sourced into ngspice. Toselect a specific circuit, use setcirc (17.5.58). To load another circuit, refer to source (17.5.68).The new actual circuit will be the circuit on top of the list of the remaining circuits.
17.5.49
General Form:resetThrow out any intermediate data in the circuit (e.g, after a breakpoint or after one or moreanalyses have been done already), and re-parse the input file. The circuit can then be re-runfrom its initial state, overriding the affect of any set or alter commands.Reset may be required in simulation loops preceding any run (or tran ...) command.
17.5.50
General Form:reshape vector vectororreshape vector vectororreshape vector vector
.... . . [ dimension , dimension ,
. . . [ dimension ] [ dimension ] . . .
This command changes the dimensions of a vector or a set of vectors. The final dimensionmay be left off and it will be filled in automatically. If no dimensions are specified, then thedimensions of the first vector are copied to the other vectors. An error message of the formdimensions of x were inconsistent can be ignored.Example:* g e n e r a t e v e c t o r with a l l ( here 30) elementsl e t newvec= v e c t o r ( 3 0 )* r e s h a p e v e c t o r t o f o r m a t 3 x 10r e s h a p e newvec [ 3 ] [ 1 0 ]* access elements of the reshaped vectorp r i n t newvec [ 0 ] [ 9 ]p r i n t newvec [ 1 ] [ 5 ]l e t newt = newvec [ 2 ] [ 4 ]
17.5.51
General Form:resumeResume a simulation after a stop or interruption (control-C).
17.5.52
301
General Form:rspice input f i l eRuns a ngspice remotely taking the input file as a ngspice input file, or the current circuit if noargument is given. Ngnutmeg or ngspice waits for the job to complete, and passes output fromthe remote job to the users standard output. When the job is finished the data is loaded in aswith aspice. If the variable rhost is set, ngnutmeg connects to this host instead of the defaultremote ngspice server machine. This command uses the rsh command and thereby requiresauthentication via a .rhosts file or other equivalent method. Note that rsh refers to theremote shell program, which may be remsh on your system; to override the default nameof rsh, set the variable remote_shell. If the variable rprogram is set, then rspice uses thisas the pathname to the program to run on the remote system.Note: rspice will not acknowledge elements that have been changed via the alter or altermodcommands.
17.5.53
General Form:run [ r a w f i l e ]Run the simulation as specified in the input file. If there were any of the control lines .ac, .op,.tran, or .dc, they are executed. The output is put in rawfile if it was given, in addition to beingavailable interactively.
17.5.54
General Form:rusage [ resource
Print resource usage statistics. If any resources are given, just print the usage of that resource.Most resources require that a circuit be loaded. Currently valid resources are:decklineno Number of lines in decknetloadtime Nelist loading timenetparsetime Netlist parsing timeelapsed The amount of time elapsed since the last rusage elapsed call.faults Number of page faults and context switches (BSD only).space Data space used.time CPU time used so far.
302
17.5.55
General Form:save [ a l l
| outvec . . . ]
Save a set of outputs, discarding the rest (if not keyword all is given). Maybe used to dramatically reduce memory (RAM) requirements if only a few useful node voltages or branch currentsare saved.Node voltages may be saved by giving the nodename or v(nodename). Currents through anindependent voltage source are given by i(sourcename) or sourcename#branch. Internal devicedata (31.1) are accepted as @dev[param]. The syntax is identical to the .save command (15.5.1).Note: In the .control ....mand to become effective.
.endc section save must occur before the run or tran com-
303
If a node has been mentioned in a save command, it appears in the working plot after a run hascompleted, or in the rawfile written by the write (17.5.86) command. For backward compatibility, if there are no save commands given, all outputs are saved. If you want to trace (17.5.76) orplot (17.5.43) a node, you have to save it explicitly, except for all given or no save commandat all.When the keyword all appears in the save command, all node voltages, voltage source currentsand inductor currents are saved in addition to any other vectors listed.Save voltage and current:s a v e vd_node v s # b r a n c h v ( v s _ n o d e ) i ( v s 2 )Save allows to store and later access internal device parameters. e.g. in a command likeSave internal parameters:s a v e a l l @mn1[ gm ]which saves all standard analysis output data plus gm of transistor mn1 to the internal memory(see also 31.1).save may store data from nodes or devices residing inside of a subcircuit:Save voltage on node 3 (top level), node 8 (from inside subcircuit x2) and current through vmeas(from subcircuit x1):s a v e 3 x1 . x2 . x1 . x2 . 8 v . x1 . x1 . x1 . vmeas # b r a n c hSave internal parameters within subcircuit:s a v e @m. xmos3 . mn1 [ gm ]Use commands listing expand (17.5.35, before the simulation) or display (17.5.20, aftersimulation) to obtain a list of all nodes and currents available. Please see chapter 31 for anexplanation of the syntax for internal parameters.Entering several save lines in a single .control section will accumulate the nodes and parametersto be saved. If you want to exclude a node, you have to get its number by calling status(17.5.70) and then calling delete number (17.5.16).
17.5.56
General Form:sens output_variables e n s o u t p u t _ v a r i a b l e a c ( DEC | OCT | LIN ) N F s t a r t F s t o pPerform a Sensitivity analysis. output_variable is either a node voltage (ex. v(1) orv(A,out)) or a current through a voltage source (ex. i(vtest)). The first form calculatesDC sensitivities, the second form calculates AC sensitivities. The output values are in dimensions of change in output per unit change of input (as opposed to percent change in output orper percent change of input).
304
17.5.57
General Form:s e t [ word ]s e t [ word = v a l u e ] . . .Set the value of word to be value, if it is present. You can set any word to be any value, numericor string. If no value is given then the value is the Boolean true. If you enter a string containingspaces, you have to enclose it with double quotes.The value of word may be inserted into a command by writing $word. If a variable is set toa list of values that are enclosed in parentheses (which must be separated from their values bywhite space), the value of the variable is the list.The variables used by ngspice are listed in section 17.7.Set entered without any parameter will list all variables set, and their values, if applicable.
17.5.58
General Form:s e t c i r c [ c i r c u i t name ]The current circuit is the one that is used for the simulation commands below. When a circuitis loaded with the source command (see below, 17.5.68) it becomes the current circuit.Setcirc followed by return without any parameter will list all circuits loaded.
17.5.59
General Form:s e t p l o t [ plotname ]Set the current plot to the plot with the given name, or if no name is given, prompt the userwith a menu. (Note that the plots are named as they are loaded, with names like tran1 or op2.These names are shown by the setplot and display commands and are used by diff, below.) Ifthe New plot item is selected, the current plot becomes one with no vectors defined.Note that here the word plot refers to a group of vectors that are the result of one ngspice run.When more than one file is loaded in, or more than one plot is present in one file, ngspice keepsthem separate and only shows you the vectors in the current plot.
17.5.60
General Form:setscale [ vector ]Defines the scale vector for the current plot. If no argument is given, the current scale vector isprinted. The scale vector delivers the values for the x-axis in a 2D plot.
17.5.61
305
General Form:settype type vector
Change the type of the named vectors to type. Type names can be found in the following table.Typenotypetimefrequencyvoltagecurrentonoise-spectrumonoise-integratedinoise-spectruminoise-integrated
17.5.62
UnitsHzVA(V or A)^2/HzV or A(V or A)^2/HzV or A
Typepolezeros-paramtemp-sweepres-sweepimpedanceadmittancepowerphasedecibel
Unit
CelsiusOhmsOhmsMhosWDegreedB
General Form:s h e l l [ command ]Call the operating systems command interpreter; execute the specified command or call forinteractive use.
17.5.63
General Form:s h i f t [ varname ] [ number ]If varname is the name of a list variable, it is shifted to the left by number elements (i.e, thenumber leftmost elements are removed). The default varname is argv, and the default numberis 1.
17.5.64
General Form:show d e v i c e s [ : p a r a m e t e r s ] , . . .The show command prints out tables summarizing the operating condition of selected devices.If devices is missing, a default set of devices are listed, if devices is a single letter, devicesof that type are listed. A devices full name may be specified to list only that device. Finally,devices may be selected by model by using the form #modelname.
306
If no parameters are specified, the values for a standard set of parameters are listed. If the list ofparameters contains a +, the default set of parameters is listed along with any other specifiedparameters.For both devices and parameters, the word all has the obvious meaning.Note: there must be spaces separating the : that divides the device list from the parameter list.
17.5.65
General Form:showmod m o d e l s [ : p a r a m e t e r s ] , . . .The showmod command operates like the show command (above) but prints out model parameter values. The applicable forms for models are a single letter specifying the device type letter(e.g. m, or c), a device name (e.g. m.xbuf22.m4b), or #modelname (e.g. #p1).
17.5.66
General Form:snload c i r c u i t f i l e
snload reads the snapshot file generated by snsave (17.5.67). circuit-file is the original circuitinput file. After reading the simulation may be continued by resume (17.5.51).An input script for loading circuit and intermediate data, resuming simulation and plotting isshown below:Typical usage:* SCRIPT : ADDER 4 BIT BINARY* s c r i p t t o r e l o a d c i r c u i t and c o n t i n u e t h e s i m u l a t i o n* begin with e d i t i n g the f i l e l o c a t i o n* t o be s t a r t e d w i t h n g s p i c e a d d e r _ s n l o a d . s c r i p* l o a d c i r c u i t and s n p a s h o t f i l esnload adder_mos_circ . c i r adder500 . snap* continue simulationresume* p l o t some node v o l t a g e splot v (10) v (11) v (12). endcDue to bug we currently need the term script in the title line (first line) of the script.
17.5.67
307
General Form:snsave f i l eIf you run a transient simulation and interrupt it by e.g. a stop breakpoint (17.5.72), you mayresume simulation immediately (17.5.51) or store the intermediate status in a snapshot file bysnsave for resuming simulation later (using snload (17.5.66)), even with a new instance ofngspice.Typical usage:Example i n p u t f i l e f o r s n s a v e* l o a d a c i r c u i t ( i n c l u d i n g t r a n s i s t o r m o d e l s and . t r a n command )* s t a r t s t r a n s i e n t simulation u n t i l stop point* store intermediate data to f i l e* begin with e d i t i n g the f i l e l o c a t i o n* t o be r u n w i t h n g s p i c e a d d e r _ m o s . c i r . include adder_mos_circ . c iset noaskquitset noinit* i n t e r r u p t condition for the simulations t o p when t i m e > 500 n* simulaterun* store snapshot to f i l esnsave adder500 . snapquit. endc. ENDadder_mos_circ.cir is a circuit input file, including the netlist, .model and .tran statements.Unfortunately snsave/snload will not work if you have XSPICE devices (or V/I sources withpolynomial statement) in your input deck.
17.5.68
General Form:source i n f i l eFor ngspice: read the ngspice input file infile, containing a circuit netlist. Ngnutmeg and ngspicecommands may be included in the file, and must be enclosed between the lines .control and
308
.endc. These commands are executed immediately after the circuit is loaded, so a controlline of ac ... works the same as the corresponding .ac card. The first line in any input fileis considered a title line and not parsed but kept as the name of the circuit. Thus, a ngspicecommand script in infile must begin with a blank line and then with a .control line. Also, anyline starting with the characters *# is considered as a control line (.control and .endc is placedaround this line automatically.). The exception to these rules are the files spinit (16.5) and.spiceinit (16.6).For ngutmeg: reads commands from the file infile. Lines beginning with the character * areconsidered comments and are ignored.
17.5.69
General Form:spec s t a r t _ f r e q s t o p _ f r e q s t e p _ f r e q vector [ vector
Calculates a new complex vector containing the Fourier transform of the input vector (typicallythe linearized result of a transient analysis). The default behavior is to use a Hanning window,but this can be changed by setting the variables specwindow and specwindoworder appropriately.Typical usage:ngspicengspicengspicengspice
13141516
>>>>
linearizes e t specwindow = " b l a c k m a n "s p e c 10 1000000 1000 v ( o u t )p l o t mag ( v ( o u t ) )
Possible values for specwindow are: none, hanning, cosine, rectangular, hamming, triangle,bartlet, blackman, gaussian and flattop. In the case of a gaussian window specwindoworder is anumber specifying its order. For a list of window functions see 17.5.24.
17.5.70
General Form:statusDisplay all of the saved nodes and parameters, traces and breakpoints currently in effect.
17.5.71
General Form:s t e p [ number ]Iterate number times, or once, and then stop.
17.5.72
309
General Form:s t o p [ a f t e r n ] [ when v a l u e cond v a l u e ] . . .Set a breakpoint. The argument after n means stop after iteration number n, and the argumentwhen value cond value means stop when the first value is in the given relation with thesecond value, the possible relations beingSymbol=<>><>=<=
Aliaseqnegtltgele
Meaningequal tonot equalgreater thanless thangreater than or equal toless than or equal to
Symbol or alias may be used alternatively. All stop commands have to be given in the controlflow before the run command. The values above may be node names in the running circuit, orreal values. If more than one condition is given, e.g.stop after 4 when v(1) > 4 when v(2) < 2,the conjunction of the conditions is implied. If the condition is met, the simulation and controlflow are interrupted, and ngspice waits for user input.In a transient simulation the = or eq will only work with vector time in commands likestop when time = 200n.Internally a breakpoint will be set at the time requested. Multiple breakpoints may be set. Ifthe first stop condition is met, the simulation is interrupted, the commands following run ortran (e.g. alter or altermod) are executed, then the simulation may continue at the first resumecommand. The next breakpoint requires another resume to continue automatically. Otherwisethe simulation stops and ngspice waits for user input.If you try to stop atstop when V(1) eq 1(or similar) during a transient simulation, you probably will miss this point, because it is notvery likely that at any time step the vector v(1) will have the exact value of 1. Then ngspicesimply will not stop.
17.5.73
General Form:strcmp _flag $ s t r i n g 1 " s t r i n g 2 "The command compares two strings, either given by a variable (string1) or as a string in quotes(string2). _flag is set as an output variable to 0, if both strings are equal. A value greaterthan zero indicates that the first character that does not match has a greater value in str1 than instr2; and a value less than zero indicates the opposite (like the C strcmp function).
310
17.5.74
General Form:sysinfoThe command prints system information useful for sending bug report to developers. Information consists of: Name of the operating system, CPU type, Number of physical processors (not available under Windows OS), number of logicalprocessors, Total amount of DRAM available, DRAM currently available.The example below shows the use of this command.n g s p i c e 1 > s y s i n f oOS : CYGWIN_NT5.1 1 . 5 . 2 5 ( 0 . 1 5 6 / 4 / 2 ) 20080612 1 9 : 3 4CPU : I n t e l (R) P e n t i u m (R) 4 CPU 3 . 4 0 GHzLogical processors : 2T o t a l DRAM a v a i l a b l e = 1 5 3 5 . 4 8 0 4 6 9 MB.DRAM c u r r e n t l y a v a i l a b l e = 9 8 4 . 6 8 3 5 9 4 MB.n g s p i c e 2 >This command has been tested under Windows OS and LINUX. It may not be available in youroperating system environment.
17.5.75
General Form:t f output_node input_sourceThe tf command performs a transfer function analysis, returning: the transfer function (output/input), output resistance, and input resistancebetween the given output node and the given input source. The analysis assumes a small-signalDC (slowly varying) input. The following example file
311
circuit0dc 5210035001500200
. controlt f v ( 3 , 5 ) vsprint all. endc. endwill yield the following output:transfer_function = 3.750000e-001output_impedance_at_v(3,5) = 6.662500e+001vs#input_impedance = 2.000000e+002
17.5.76
General Form:t r a c e [ node . . . ]For every step of an analysis, the value of the node is printed. Several traces may be active atonce. Tracing is not applicable for all analyses. To remove a trace, use the delete (17.5.16)command.
17.5.77
General Form:t r a n T s t e p T s t o p [ T s t a r t [ Tmax ] ] [ UIC ]Perform a transient analysis. See chapter 15.3.9 of this manual for more details.An interactive transient analysis may be interrupted by issuing a ctrl-c (control-C) command.The analysis then can be resumed by the resume command (17.5.51). Several options may beset to control the simulation (15.1.4).
17.5.78
General Form:transpose vector vector
312
This command transposes a multidimensional vector. No analysis in ngspice produces multidimensional vectors, although the DC transfer curve may be run with two varying sources.You must use the reshape command to reform the one-dimensional vectors into two dimensional vectors. In addition, the default scale is incorrect for plotting. You must plot versus thevector corresponding to the second source, but you must also refer only to the first segment ofthis second source vector. For example (circuit to produce the transfer characteristic of a MOStransistor):How to produce the transfer characteristic of a MOS transistor:ngspicengspicengspicengspicengspice
>>>>>
dc vgg 0 5 1 vdd 0 5 1p l o t i ( vdd )reshape a l l [6 ,6]t r a n s p o s e i ( vdd ) v ( d r a i n )p l o t i ( vdd ) v s v ( d r a i n ) [ 0 ]
17.5.79
General Form:u n a l i a s [ word . . . ]Removes any aliases present for the words.
17.5.80
General Form:undefine functionDefinitions for the named user-defined functions are deleted.
17.5.81
General Form:unlet vector [ vector
17.5.82
General Form:u n s e t [ word . . . ]Clear the value of the specified variable(s) (word).
17.5.83
313
General Form:v e r s i o n [ s | f | < v e r s i o n i d > ]Print out the version of ngnutmeg that is running, if invoked without argument or with -s or -f.If the argument is a <version id> (any string different from -s or -f is considered a <version id>), the command checks to make sure that the arguments match the current version of ngspice.(This is mainly used as a Command: line in rawfiles.)Options description: No option: The output of the command is the message you can see when running ngspicefrom the command line, no more no less. -s(hort): A shorter version of the message you see when calling ngspice from the command line. -f(ull): You may want to use this option if you want to know what extensions are includedinto the simulator and what compilation switches are active. A list of compilation optionsand included extensions is appended to the normal (not short) message. May be usefulwhen sending bug reports.The following example shows what the command returns is some situations:Use of the version command:n g s p i c e 10 > v e r s i o n******** n g s p i c e 24 : C i r c u i t l e v e l s i m u l a t i o n p r o g r a m** The U . C . B e r k e l e y CAD Group** C o p y r i g h t 1985 1994 , R e g e n t s o f t h e U n i v e r s i t y o f C a l i f o r n i a .** P l e a s e g e t y o u r n g s p i c e manual fromh t t p : / / ngspice . s o u r c e f o r g e . net / docs . html** P l e a s e f i l e y o u r bugr e p o r t s a th t t p : / / ngspice . s o u r c e f o r g e . net / bugrep . html13:36:34** C r e a t i o n D a t e : J a n 1 2011******n g s p i c e 2 >n g s p i c e 11 > v e r s i o n 14Note : r a w f i l e i s v e r s i o n 14 ( c u r r e n t v e r s i o n i s 2 4 )n g s p i c e 12 > v e r s i o n 24n g s p i c e 13 >Note for developers: The option listing returned when version is called with the-f flag is built at compile time using #ifdef blocks. When new compile switchesare added, if you want them to appear on the list, you have to modify the code inmisccoms.c.
314
17.5.84
General Form:whereWhen performing a transient or operating point analysis, the name of the last node or device tocause non-convergence is saved. The where command prints out this information so that youcan examine the circuit and either correct the problem or make a bug report. You may do thiseither in the middle of a run or after the simulator has given up on the analysis. For transientsimulation, the iplot command can be used to monitor the progress of the analysis. When theanalysis slows down severely or hangs, interrupt the simulator (with control-C) and issue thewhere command. Note that only one node or device is printed; there may be problems withmore than one node.
17.5.85
General Form:wrdata [ f i l e ] [ vecs ]Writes out the vectors to file.This is a very simple printout of data in array form. Column one is the default scale data, columntwo the simulated data. If more than one vector is given, the third column again is the defaultscale, the fourth the data of the second vector. The default format is ASCII. All vectors have tostem from the same plot, otherwise a seg fault may occur. No further information is written tothe file, so you have to keep track of your multiple outputs. The format may be changed in thenear future.output example from two vectors....
-1.845890 e -0064.243518 e -006-5.794628 e -0065.086875 e -006-3.683623 e -0061.330798 e -006-3.804620 e -0079.047444 e -007-2.792511 e -0065.657498 e -006
0.000000 e +000-4.930171 e -0064.769020 e -006-3.670687 e -0061.754215 e -006-1.091843 e -0062.274678 e -006-3.815083 e -0064.766727 e -006-2.397679 e -006
17.5.86
General Form:write [ f i l e ] [ exprs ]
315
17.5.87
General Form:wrs2p [ f i l e ]Writes out the s-parameters of a two-port to file.In the active plot the following is required: vectors frequency, S11 S12 S21 S22, all having thesame length and having complex values (as a result of an ac analysis), and vector Rbase. Fordetails how to generate these data see chapt. 17.9.The file format is Touchstone Version 1, ASCII, frequency in Hz, real and imaginary parts ofSnn versus frequency.The default file name is s-param.s2p.output example:!2 - port S - parameter file! Title : test for scattering parameters! Generated by ngspice at Sat Oct 16 13:51:18 2010# Hz S RI R 50! freqReS11ImS11ReS21...2.500000 e +006 -1.358762 e -003 -1.726349 e -0029.966563 e -0015.000000 e +006 -5.439573 e -003 -3.397117 e -0029.867253 e -001....
17.5.88
General Form:xgraph f i l e [ exprs ] [ p l o t o p t i o n s ]The ngspice/ngnutmeg xgraph command plots data like the plot command but via xgraph, apopular X11 plotting program. If file is either temp or tmp a temporary file is used to holdthe data while being plotted. For available plot options, see the plot command. All optionsexcept for polar or smith plots are supported.
316
17.6
Control Structures
17.6.1
While - End
General Form:while conditionstatement...endWhile condition, an arbitrary algebraic expression, is true, execute the statements.
17.6.2
Repeat - End
General Form:r e p e a t [ number ]statement...endExecute the statements number times, or forever if no argument is given.
17.6.3
Dowhile - End
General Form:dowhile c o n d i t i o nstatement...endThe same as while, except that the condition is tested after the statements are executed.
17.6.4
Foreach - End
General Form:foreach var valuestatement...end
The statements are executed once for each of the values, each time with the variable var set tothe current one. (var can be accessed by the $var notation - see below).
17.6.5
317
If - Then - Else
General Form:if conditionstatement...elsestatement...endIf the condition is non-zero then the first set of statements are executed, otherwise the secondset. The else and the second set of statements may be omitted.
17.6.6
Label
General Form:l a b e l wordIf a statement of the form goto word is encountered, control is transferred to this point, otherwisethis is a no-op.
17.6.7
Goto
General Form:g o t o wordIf a statement of the form label word is present in the block or an enclosing block, control istransferred there. Note that if the label is at the top level, it must be before the goto statement(i.e, a forward goto may occur only within a block). A block to just include goto on the toplevel may look likeExample noop block to include forward goto on top level:if (1)...goto gohere...l a b e l gohereend
17.6.8
Continue
General Form:continueIf there is a while, dowhile, or foreach block enclosing this statement, control passes to the test,or in the case of foreach, the next value is taken. Otherwise an error results.
318
17.6.9
Break
General Form:breakIf there is a while, dowhile, or foreach block enclosing this statement, control passes out of theblock. Otherwise an error results.Of course, control structures may be nested. When a block is entered and the input is theterminal, the prompt becomes a number of >s corresponding to the number of blocks the userhas entered. The current control structures may be examined with the debugging commandcdump (see 17.5.9).
17.7
The operation of both ngutmeg and ngspice may be affected by setting variables with the setcommand (17.5.57). In addition to the variables mentioned below, the set command inngspice also affects the behavior of the simulator via the options previously described underthe section on .OPTIONS (15.1). You also may define new variables or alter existing variablesinside .control ... .endc for later use in your user-defined script (see chapter 17.8).The following list is in alphabetical order. All of them are acknowledged by ngspice. Frontendvariables (e.g. on circuits and simulation) are not defined in ngnutmeg. The predefined variableswhich may be set or altered by the set command are:appendwrite Append to the file when a write command is issued, if one already exists.brief If set to FALSE, the netlist will be printed.colorN These variables determine the colors used, if X is being run on a color display. N maybe between 0 and 15. Color 0 is the background, color 1 is the grid and text color, andcolors 2 through 15 are used in order for vectors plotted. The value of the color variablesshould be names of colors, which may be found in the file /usr/lib/rgb.txt. ngspicefor Windows does support only white background (color0=white with black grid and text)or or color0=black with white grid and text.cpdebug Print control debugging information.curplotdate Sets the date of the current plot.curplotname Sets the name of the current plot.curplottitle Sets the title (a short description) of the current plot.debug If set then a lot of debugging information is printed.device The name (/dev/tty??) of the graphics device. If this variable isnt set then the usersterminal is used. To do plotting on another monitor you probably have to set both thedevice and term variables. (If device is set to the name of a file, nutmeg dumps thegraphics control codes into this file this is useful for saving plots.)
319
diff_abstol The relative tolerance used by the diff command (default is 1e-12).diff_reltol The relative tolerance used by the diff command (default is 0.001).diff_vntol The absolute tolerance for voltage type vectors used by the diff command (defaultis 1e-6).echo Print out each command before it is executed.editor The editor to use for the edit command.filetype This can be either ascii or binary, and determines the format of the raw file (compact binary or text editor readable ascii). The default is binary.fourgridsize How many points to use for interpolating into when doing Fourier analysis.gridsize If this variable is set to an integer, this number is used as the number of equally spacedpoints to use for the Y axis when plotting. Otherwise the current scale is used (whichmay not have equally spaced points). If the current scale isnt strictly monotonic, thenthis option has no effect.gridstyle Sets the grid during plotting with the plot command. Will be overridden by directentry of gridstyle in the plot command. A linear grid is standard for both x and y axis. Allowed values are lingrid loglog xlog ylog smith smithgrid polar nogrid.hcopydev If this is set, when the hardcopy command is run the resulting file is automaticallyprinted on the printer named hcopydev with the command lpr -Phcopydev -g file.hcopyfont This variable specifies the font name for hardcopy output plots. The value is devicedependent.hcopyfontsize This is a scaling factor for the font used in hardcopy plots.hcopydevtype This variable specifies the type of the printer output to use in the hardcopy command. If hcopydevtype is not set, Postscript format is assumed. plot (5) is recognizedas an alternative output format. When used in conjunction with hcopydev, hcopydevtypeshould specify a format supported by the printer.hcopyscale This is a scaling factor for the font used in hardcopy plots (between 0 and 10).hcopywidth Sets width of the hardcopy plot.hcopyheight Sets height of the hardcopy plot.hcopypscolor Sets the color of the hardcopy output. If not set, black & white plotting is assumed with different linestyles for each output vector plotted. Setting to any valid colorinteger value yields a colored plot background (0: black 1: white, others see below) andcolored solid lines. This is valid for postscript only.hcopypstxcolor This variable sets the color of the text in the postscript hardcopy output. If notset, black is assumed on white background, white on black background. Valid colors are0: black 1: white 2: red 3: blue 4: orange 5: green 6: pink 7: brown 8: khaki 9: plum 10:orchid 11: violet 12: maroon 13: turquoise 14: sienna 15: coral 16: cyan 17: magenta18: gray for smith grid 19: gray for smith grid 20: gray for normal grid
320
height The length of the page for asciiplot and print col.history The number of events to save in the history list.lprplot5 This is a printf(3s) style format string used to specify the command to use forsending plot(5)-style plots to a printer or plotter. The first parameter supplied is the printername, the second parameter supplied is a file name containing the plot. Both parametersare strings. It is trivial to cause ngspice to abort by supplying a unreasonable formatstring.lprps This is a printf(3s) style format string used to specify the command to use for sendingPostscript plots to a printer or plotter. The first parameter supplied is the printer name, thesecond parameter supplied is a file name containing the plot. Both parameters are strings.It is trivial to cause ngspice to abort by supplying a unreasonable format string.modelcard The name of the model card (normally .MODEL)nfreqs The number of frequencies to compute in the Fourier command. (Defaults to 10.)ngbehavior Sets the compatibility mode of ngspice. To be set in spinit (16.5) or .spiceinit(16.6).Its value all will improve compatibility to commercial simulators. Full compatibility is however not the intention of ngspice! This value may be set as a standard inthe future. ps, hs and spice3 are available. See chapt. 16.13.noaskquit Do not check to make sure that there are no circuits suspended and no plots unsaved.Normally ngspice warns the user when he tries to quit if this is the case.nobjthack BJTs can have either 3 or 4 nodes, which makes it difficult for the subcircuit expansion routines to decide what to rename. If the fourth parameter has been declared as amodel name, then it is assumed that there are 3 nodes, otherwise it is considered a node.To disable this, you can set the variable "nobjthack" which forces BJTs to have 4 nodes(for the purposes of subcircuit expansion, at least).nobreak Dont have asciiplot and print col break between pages.noasciiplotvalue Dont print the first vector plotted to the left when doing an asciiplot.nobjthack Assume that BJTs have 4 nodes.noclobber Dont overwrite existing files when doing IO redirection.noglob Dont expand the global characters *, ?, [, and ]. This is the default.nomoremode If nomoremode is not set, whenever a large amount of data is being printed tothe screen (e.g, the print or asciiplot commands), the output is stopped every screenfuland continues when a carriage return is typed. If nomoremode is set then data scrolls offthe screen without check.nonomatch If noglob is unset and a global expression cannot be matched, use the global characters literally instead of complaining.noparse Dont attempt to parse input files when they are read in (useful for debugging). Ofcourse, they cannot be run if they are not parsed.
321
noprintscale Dont print the scale in the leftmost column when a print col command is given.nosort Dont have display sort the variable names.nosubckt Dont expand subcircuits.notrnoise Switch off the transient noise sources (chapt. 4.1.7).numdgt The number of digits to print when printing tables of data (a, print col). The defaultprecision is 6 digits. On the VAX, approximately 16 decimal digits are available usingdouble precision, so p should not be more than 16. If the number is negative, one fewerdigit is printed to ensure constant widths in tables.num_threads The number of of threads to be used if OpenMP (see chapt. 16.10) is selected.The default value is 2.plotstyle This should be one of linplot, combplot, or pointplot. linplot, the default,causes points to be plotted as parts of connected lines. combplot causes a comb plotto be done. It plots vectors by drawing a vertical line from each point to the X-axis, asopposed to joining the points. pointplot causes each point to be plotted separately.pointchars Set a string as a list of characters to be used as points in a point plot. Standard isox*+#abcdefhgijklmnpqrstuvwyz. Characters C are not allowed.polydegree The degree of the polynomial that the plot command should fit to the data. Ifpolydegree is N, then nutmeg fits a degree N polynomial to every set of N points anddraw 10 intermediate points in between each end point. If the points arent monotonic,then it tries rotating the curve and reducing the degree until a fit is achieved.polysteps The number of points to interpolate between every pair of points available whendoing curve fitting. The default is 10.program The name of the current program (argv[0]).prompt The prompt, with the character ! replaced by the current event number. Single quotes are required around the string entered!rawfile The default name for rawfiles created.remote_shell Overrides the name used for generating rspice runs (default is "rsh").renumber Renumber input lines when an input file has .includes.rndseed Seed value for random number generator (used by sgauss, sunif, and rnd functions).If not set, the process Id is used as seed value.rhost The machine to use for remote ngspice runs, instead of the default one (see the description of the rspice command, below).rprogram The name of the remote program to use in the rspice command.sourcepath A list of the directories to search when a source command is given. The defaultis the current directory and the standard ngspice library (/usr/local/lib/ngspice, orwhatever LIBPATH is #defined to in the ngspice source.
322
specwindow Windowing for commands spec (17.5.69) or fft (17.5.24). May be one of thefollowing:bartlet blackman cosine gaussian hamming hanning none rectangular triangle.specwindoworder Integer value 2 - 8 (default 2), used by commands spec or fft.spicepath The program to use for the aspice command. The default is /cad/bin/spice.strict_errorhandling If set by the user, an error detected during circuit parsing will immediately lead ngspice to exit with exit code 1 (see 18.5). May be set in files spinit (16.5) or.spiceinit (16.6) only.subend The card to end subcircuits (normally .ends).subinvoke The prefix to invoke subcircuits (normally X).substart The card to begin subcircuits (normally .subckt).term The mfb name of the current terminal.ticmarks An integer value n, n tics (a small x) will be set on your graph. (Arrangement ofthe tics ?)ticlist A list of integers, e.g. ( 4 14 24 ) to set tics (small x) on your graph.(Arrangement ofthe tics ?)units If this is degrees, then all the trig functions will use degrees instead of radians.unixcom If a command isnt defined, try to execute it as a UNIX command. Setting this optionhas the effect of giving a rehash command, below. This is useful for people who want touse ngnutmeg as a login shell.wfont Set the font for the graphics plot in MS Windows. Typical fonts are courier, times,arial and all others found on your machine. Default is courier.wfont_size The size of the windows font. Default is depending on systems settings, somethinglikewidth The width of the page for asciiplot and print col (see also 15.5.7).x11lineararcs Some X11 implementations have poor arc drawing. If you set this option,Ngspice will plot using an approximation to the curve using straight lines.xbrushwidth Linewidth for grid, border and graph.xfont Set the font for the graphics plot in X11 (LINUX, Cygwin, etc.). Input format has still tobe checked.xtrtol Set trtol, e.g. to 7, so to avoid the speed reduction with XSPICE (see 16.9). Be aware ofpotential precision degradation or convergence issues using this option.
17.8. SCRIPTS
17.8
323
Expressions, functions, constants, commands, variables, vectors, and control structures may beassembled into scripts within a .control ... .endc section of the input file. The script allowsto automate a more complex ngspice behavior: simulations are performed, output data are theanalyzed, simulations repeated with modified parameters, output vectors for plotting are assembled. The ngspice scripting language is not very powerful, but easily integrated into thesimulation flow.The ngspice input file for scripting contains the usual circuit netlist, modelcards, and a script,enclosed in the .control .. .endc section. ngspice is started in interactive mode with the inputfile in the command line (or sourced later with the source command). After reading the inputfile, the command sequence is immediately processed. Variables or vectors set by previouscommands may be used in commands following their definition. data may be stored, plotted orgrouped into new vectors for additional charts supporting data evaluation.
17.8.1
Variables
Variables are defined and initialized with the set command (17.5). set output=10 will defined the variable output and set it to a (real) number 10. Predefined variables, which are usedinside ngspice for specific purposes, are listed in chapt. 17.7. Variables are accessible globally.The values of variables may be used in commands by writing $varname where the value of thevariable is to appear, e.g. $output. The special variables $$ and $< refer to the process ID ofthe program and a line of input which is read from the terminal when the variable is evaluated,respectively. If a variable has a name of the form $&word, then word is considered a vector (seebelow), and its value is taken to be the value of the variable. If $foo is a valid variable, and is oftype list, then the expression $foo[low-high] represents a range of elements. Either the upperindex or the lower may be left out, and the reverse of a list may be obtained with $foo[len-0].Also, the notation $?foo evaluates to 1 if the variable foo is defined, 0 otherwise, and $#fooevaluates to the number of elements in foo if it is a list, 1 if it is a number or string, and 0 if it isa Boolean variable.
17.8.2
Vectors
Ngspice and ngnutmeg data is in the form of vectors: time, voltage, etc. Each vector has a type,and vectors can be operated on and combined algebraically in ways consistent with their types.Vectors are normally created as a result of a transient or dc simulation. They are also establishedwhen a data file is read in (see the load command 17.5.36). They can also be created with thelet command 17.5.33 inside a script. If a variable has a name of the form $&word, then wordis considered a vector, and its value is taken to be the value of the variable.
17.8.3
324
17.8.4
control structures
Control structures have been described in chapter 17.6. Some simple examples will be givenbelow.
$ output expected
325
326
327
17.8.5
A typical example script named spectrum is delivered with the ngspice distribution. Even if itis made obsolete by the internal spec command (see 17.5.69) and especially by the much fasterfft command (see 17.5.24), it may act as a good example for getting acquainted with the ngspice(or nutmeg) post-processor language.As a suitable input for spectrum you may run a ring-oscillator, delivered with ngspice in e.g.test/bsim3soi/ring51_41.cir. For an adequate resolution you will need a simulation time of 1s. Then a small control script may start ngspice by loading the R.O. simulation data and startspectrum.Small script to start ngspice, read the simulation data and start spectrum:* t e s t f o r s c r i p t spectrum . controlload ring51_41 . outs p e c t r u m 10MEG 2500MEG 1MEG v ( o u t 2 5 ) v ( o u t 5 0 ). endc
328
17.8.6
329
330
17.8.7
Parameter sweep
While there is no direct command to sweep a device parameter during simulation, you may usea script to emulate such behavior. The example input file contains of an resistive divider withR1 and R2, where R1 is swept from a start to a stop value inside of the control section, usingthe alter command (see 17.5.3).Input file with parameter sweepp a r a m e t e r sweep* r e s i s t i v e d i v i d e r , R1 s w e p t from s t a r t _ r t o s t o p _ rVDD 1 0 DC 1R1 1 2 1 kR2 2 0 1 k. controll e t s t a r t _ r = 1kl e t s t o p _ r = 10 kl e t d e l t a _ r = 1klet r_act = start_r* loopwhile r_act le stop_ra l t e r r1 r _ a c topprint v (2)let r_act = r_act + delta_rend. endc. end
17.8.8
Output redirection
The console outputs delivered by commands like print (17.5.45), echo (17.5.21), or others maybe redirected into a text file. print vec > filename will generate a new file or overwritean existing file named filename, echo text >> filename will append the new data to thefile filename. Output redirection may be mixed with commands like wrdata.
331
17.9
17.9.1
Intro
A command line script, available from the ngspice distribution at examples/control_structs/sparam.cir, together with the command wrs2p (see chapt. 17.5.87) allows to calculate, printand plot the scattering parameters S11, S21, S12, and S22 of any two port circuit at varyingfrequencies.The printed output using wrs2p is a Touchstone version 1 format file. The file follows theformat according to The Touchstone File Format Specification, Version 2.0, available from here.
332
17.9.2
(17.1)
The value of P may be the difference of two real numbers, with K being another real number.
ui = P = a2 b2 = (a+b)(ab) = (a+b)(KK 1 )(ab) = {K(a + b)} K 1 (a b) (17.2)Thus you getK 1 u = a + b
(17.3)
Ki = a b
(17.4)
a=
u + K 2i2K
(17.5)
b=
u K 2i2K
(17.6)
and finally
By introducing the reference resistance Z0 := K 2 > 0 we get finally the Heaviside transformationa=
u + Z0 i ,2 Z0
u Z0 i
2 Z0
(17.7)
U1 + Z0 I1
b1 =
U1 Z0 I1
(17.8)
a2 =
U2 + Z0 I2
b2 =
U2 Z0 I2
(17.9)
b1b2
=
s11 s12s21 s22
a1a2
333
(17.10)
Two obtain s11 we have to set a2 = 0. This is accomplished by loading the output port exactlywith the reference resistance Z0 , which sinks a current I2 = U2 /Z0 from the port.s11 =
s11 =
b1a1
(17.11)a2 =0
U1 Z0 I1U1 + Z0 I1
(17.12)
Loading the input port from an ac source U0 via a resistor with resistance value Z0 , we obtainthe relationU0 = Z0 I1 +U1
(17.13)
2U1 U0U0
(17.14)
s21 =
b2a1
(17.15)a2 =0
U2 Z0 I2 2U2=U1 + Z0 I1U0
(17.16)
Equations 17.14 and 17.16 now tell us how to measure s11 and s21 : Measure U1 at the input port,multiply by 2 using an E source, subtracting U0 which for simplicity is set to 1, and divide byU0 . At the same time measure U2 at the output port, multiply by 2 and divide by U0 . Biasing andmeasuring is done by subcircuit S_PARAM. To obtain s22 and s12 , you have to exchange theinput and output ports of your two-port and do the same measurement again. This is achievedby switching resistors from low (1m) to high (1T ) and thus switching the input and outputports.
17.9.3
Copy and then edit s-param.cir. You will find this file in directory /examples/control_structs ofthe ngspice distribution.The reference resistance (often called characteristic impedance) for the measurements is addedas a parameter.param Rbase=50The bias voltages at the input and output ports of the circuit are set as parameters as well:
334
17.10
C-shell type quoting with and , and backquote substitution may be used. Within singlequotes, no further substitution (like history substitution) is done, and within double quotes,the words are kept together but further substitution is done. Any text between backquotes isreplaced by the result of executing the text as a command to the shell.History substitutions, similar to C-shell history substitutions, are also available - see the C-shellmanual page for all of the details. The characters ~, @{, and @} have the same effects asthey do in the C-Shell, i.e., home directory and alternative expansion. It is possible to use thewildcard characters *, ?, [, and ] also, but only if you unset noglob first. This makes them ratheruseless for typing algebraic expressions, so you should set noglob again after you are done withwildcard expansion. Note that the pattern [^abc] matches all characters except a, b, and c.If X is being used, the cursor may be positioned at any point on the screen when the windowis up and characters typed at the keyboard are added to the window at that point. The windowmay then be sent to a printer using the xpr(1) program.
17.11
When defining aliases like alias pdb plot db( !:1 - !:2 ) you must be careful to quote theargument list substitutions in this manner. If you quote the whole argument it might not workproperly.In a user-defined function, the arguments cannot be part of a name that uses the plot.vec syntax.For example: define check(v(1)) cos(tran1.v(1)) does not work.
Chapter 18Ngspice User Interfacesngspice offers a variety of user interfaces. For an overview (several screen shots) please have alook at the ngspice web page.
18.1
If compiled properly (e.g. using the with-wingui flag for ./configure under MINGW), ngspicefor Windows offers a simple graphical user interface. In fact this interface does not offer muchmore for data input than a console would offer, e.g. command line inputs, command historyand program text output. First of all it applies the Windows api for data plotting. If you run thesample input file given below, you will get an output as shown in fig. 16.1.Input file:***** S i n g l e NMOS T r a n s i s t o r F o r BSIM3V3 . 1g e n e r a l p u r p o s e c h e c k ( IdVd ) ******* c i r c u i t d e s c r i p t i o n ***m1 2 1 3 0 n1 L = 0 . 6 u W= 1 0 . 0 uvgs 1 0 3 . 5vds 2 0 3 . 5vss 3 0 0*. dc v d s 0 3 . 5 0 . 0 5 v g s 0 3 . 5 0 . 5*. controlrunp l o t vss # branch. endc** UCB p a r a m e t e r s BSIM3v3 . 2. i n c l u d e . . / Exam_BSIM3 / M o d e l c a r d s / m o d e l c a r d . nmos. i n c l u d e . . / Exam_BSIM3 / M o d e l c a r d s / m o d e l c a r d . pmos*. end
336
The GUI consists of an I/O port (lower window) and a graphics window, created by the plotcommand.
The output window displays messages issued by ngspice. You may scroll the window to getmore of the text. The input box (white box) may be activated by a mouse click to accept anyof the valid ngspice commends. The lower left output bar displays the actual input file. ngspiceprogress during setup and simulation is shown in the progress window (ready). The Quitbutton allow to interrupt ngspice. If ngspice is actively simulating, due to using only a singlethread, this interrupt has to wait until the window is accessible from within ngspice, e.g. duringan update of the progress window.In the plot window there is the upper left button, which activated a drop down menu. You mayselect to print the plot window shown (a very simple printer interface, to be improved), setup any of the printers available on your computer, or issue a postscript file of the actual plotwindow, either black&white or colored.
337
Instead of plotting with black background, you may set the background to any other color,preferably to white using the command shown below.Input file modification for white background:. controlrun* white backgrounds e t color0 =white* b l a c k g r i d and t e x t ( o n l y n e e d e d w i t h X11 , a u t o m a t i c w i t h MS Win )set color1=black* w i d e r g r i d and p l o t l i n e ss e t x b r u s h w i d t h =2p l o t vss # branch. endc
18.2
MS Windows Console
If the with-wingui flag for ./configure under MINGW is omitted (see 32.2.5) or console_debugor console_release is selected in the MS Visual Studio configuration manager, then ngspice willcompile without any internal graphical input or output capability. This may be useful if youapply ngspice in a pipe inside the MSYS window, or use it being called from another program,and just generating output files from a given input. The plot (17.5.43) command will not doand leads to an error message.
338
18.3
LINUX
The standard user interface is a console for input and the X11 graphics system for output withthe interactive plot (17.5.43) command. If ngspice is compiled with the without-x flag for./configure, a console application without graphical interface results. For more sophisticatedinput user interfaces please have a look at chapt. 18.8.
18.4
CygWin
The CygWin interface is similar to the LINUX interface (18.3), i.e. console input and X11graphics output. To avoid the warning of a missing graphical user interface, you have to startthe X11 window manager by issuing the commands$ export DISPLAY=:0.0$ xwin -multiwindow -clipboard &inside of the CygWin window before starting ngspice.
18.5
Error handling
Error messages and error handling in ngspice have grown over the years, include a lot of traditional behavior and thus are not very systematic and consistent.Error messages may occur with the token Error:. Often the errors are non-recoverable and willlead to exiting ngspice with error code 1. Sometimes, however, you will get an error message,but ngspice will continue, and may either bail out later because the error has propagated intothe simulation, sometimes ngspice will continue, deliver wrong results and exit with error code0 (no error detected!).In addition ngspice may issue warning messages like Warning: .... These should cover recoverable errors only.So there is still work to be done to define a consistent error messaging, recovery or exiting. Afirst step is the user definable variable strict_errorhandling. This variable may be set in filesspinit (16.5) or .spiceinit (16.6) to immediately stop ngspice, after an error is detected duringparsing the circuit. An error message is sent, the ngspice exit code is 1. This behavior deviatesfrom traditional spice error handling and thus is introduced as an option only.XSPICE error messages are explained in chapter 29.
18.6
339
This info is compiled from Roger L. Traylors web page. All the commands and variables youcan set are described in chapt. 17.5. The corresponding input file for the examples given belowis listed in chapt. 21.1. Just add the .control section to this file and run in interactive mode by$ ngspice xspice_c1_print.cir================================================================One way is to setup your printing like this:.controlset hcopydevtype=postscriptoprunplot vcc coll emithardcopy temp.ps vcc coll emit.endcThen print the postscript file temp.ps to a postscript printer.================================================================You can add color traces to it if you wish:.controlset hcopydevtype=postscript* allow color and set background color if set to value > 0set hcopypscolor=1*color0 is background color*color1 is the grid and text color*colors 2-15 are for the vectorsset color0=rgb:f/f/fset color1=rgb:0/0/0oprunhardcopy temp.ps vcc coll emit.endcThen print the postscript file temp.ps to a postscript printer.================================================================You can also direct your output directly to a designated printer (not available in MS Windows):.controlset hcopydevtype=postscript
340
18.7
Gnuplot
Install Gnuplot (on LINUX available from the distribution, on Windows available here). OnWindows expand the zip file to a directory of your choice, add the path <any directory>/gnuplot/binto the PATH variable, and go... The command to invoke Gnuplot (17.5.26) is limited howeverto x/y plots (no polar etc.).
18.8
In this chapter you will find some links and comments on GUIs for ngspice offered from otherprojects and on the integration of ngspice into a circuit development flow. The data given relymostly on information available from the web and thus is out of our control. It also may be farfrom complete. The GUIs KJWaves and GNUSpiceGUI help you to navigate the commandsto need to perform your simulation. XCircuit and the GEDA tools gschem and gnetlist offerintegrating schematic capture and simulation.
18.8.1
KJWaves
KJWaves was written to be a cross-platform SPICE tool in pure Java. It aids in viewing, modifying, and simulating SPICE CIRCUIT files. Output from SPICE3 (ngspice) can be readand displayed. Resulting graphs may be printed and saved. The Java executable will rununder LINUX and Windows (and maybe other OSs). The development site is available at. You may find the project home page at.
18.8.2
18.8.3
XCircuit
CYGWIN and especially LINUX users may find XCircuit valuable to establish a developmentflow including schematic capture and circuit simulation.
18.8.4
341
GEDA
The gEDA project is developing a full GPLd suite and toolkit of Electronic Design Automationtools for use with a LINUX. Ngspice may be integrated into the development flow. Two websites offer tutorials using gschem and gnetlist with ngspice:
18.8.5
CppSim
A complete simulation environment called CppSim has been developed and made available forsystem level simulation of complex mixed signal circuits. ngspice has been integrated into thesimulation flow, as described here.
18.8.6
NGSPICE Online
A web browser based interface is offered here. Simulation is performed on a remote server. Theproject is not directly linked to our ngspice development project.
18.8.7
Spicy Schematics
An IPAD and web interface (including schematics entry) to ngspice is offered here.Simulationis performed on a remote server.
18.8.8
MSEspice
A graphical front end to ngspice, using the Free Pascal cross platform RAD environmentMSEide+MSEgui.
18.8.9
PartSim
A web based guiin your browser, including schematics entry. Simulation is performed on aremote server.
342
Chapter 19ngspice as shared library or dynamic linklibraryngspice may be compiled as a shared library. This allows adding ngspice to an applicationwhich then gains control over the simulator. The shared module offers an interface whichexports functions controlling the simulator and callback functions for feedback.So you may send an input "file" with a netlist to ngspice, start the simulation in a separate thread,read back simulation data at each time point, stop the simulator depending on some condition,alter device or model parameters and then resume the simulation.Shared ngspice does not have any user interface. The calling process is responsible for this. Itmay offer a graphical user interface, add plotting capability or any other interactive element.You may develop and optimize these user interface elements without a need to alter the ngspicesource code itself, using a console application or GUIs like gtk, Delphi, Qt or others.
19.1
Compile options
19.1.1
Currently (as of ngspice-25 being the actual release), you will have to use the direct loading ofthe sources from the git repository (see chapt. 32.1.2).
19.1.2
Compilation is done as described in chapts. 32.1 or 32.2.1. Use the configure option --with-ngsharedinstead of --with-x or --with-wingui.Other operation systems (Mac OS, BSD, ...) have not been tested so far. Your input is welcome!
19.1.3
MS Visual Studio
Compilation is similar to what has been described in chapt. 32.2.3. There is however a dedicated project file coming with the source code to generate ngspice.dll. Go to the directoryvisualc-shared and start the project with double clicking on sharedspice.sln.
344
19.2
Basically there are two methods (as with all *.so, *.dll libraries). The caller may link to a (small)library file during compiling/linking, and then immediately search for the shared library uponbeing started. It is also possible to dynamically load the ngspice shared library at runtime usingthe dlopen/LoadLibrary mechanisms.
19.2.1
While creating the ngspice shared lib, not only the *.so (*.dll) file is created, but also a smalllibrary file, which just includes references to the exported symbols. Depending on the OS, thesemay be called libngspice.dll.a, ngspice.lib. Linux and MINGW also allow linking to the sharedobject itself. The shared object is not included into the executable component but is tied to theexecution.
19.2.2
dlopen (LINUX) or LoadLibrary (MS Windows) will load libngspice.so or ngspice.dll into theaddress space of the caller at runtime. The functions return a handle which may be used toacquire the pointers to the functions exported by libngspice.so. Detaching ngspice at runtime isequally possible (using dlclose/FreeLibrary), after the background thread has been stopped andall callbacks have returned.
19.3
The sources for the ngspice shared library API are contained in a single c file (sharedspice.c)and a corresponding header file sharedspice.h. The type and function declarations are containedin sharedspice.h, which may be directly added to the calling application, if written in C or C++.
19.3.1
Same a s so_vname . * /Same a s s o _ v t y p e . * /F l a g s ( a c o m b i n a t i o n o f VF_ * ) . * /Real d a t a . */Complex d a t a . * /Length of t h e v e c t o r . */
345
The next two structures are used by the callback function SendInitData (see 19.3.3.5). Eachtime a new plot is generated during simulation, e.g. when a sequence of op, ac and tran is usedor commands like linearize or fft are invoked, the function is called once by ngspice. Amongits parameters you find a pointer to a struct vecinfoall, which includes an array of vecinfo, onefor each vector. Pointers to the struct dvec, containing the vector, are included. This struct isdeclared in header file src/include/ngspice/dvec.h.
vecinfotypedef s t r u c t vecinfo{i n t number ;/ * number o f v e c t o r , a s p o s t i o n i n t h elinked l i s t of vectors , s t a r t s with 0 */c h a r * vecname ;/ * name o f t h e a c t u a l v e c t o r * /bool i s _ r e a l ;/ * TRUE i f t h e a c t u a l v e c t o r h a s r e a l d a t a * /void * pdvec ;/ * a v o i d p o i n t e r t o s t r u c t dvec *d , t h eactual vector */v o i d * p d v e c s c a l e ; / * a v o i d p o i n t e r t o s t r u c t d v e c * ds ,the scale vector */} vecinfo , * pvecinfo ;
vecinfoalltypedef s t r u c t vecinfoall{/* the plot */c h a r * name ;char * t i t l e ;char * date ;char * type ;i n t veccount ;/ * t h e d a t a a s an a r r a y o f v e c i n f o w i t hl e n g t h e q u a l t o t h e number o f v e c t o r sin the plot */pvecinfo * vecs ;} vecinfoall , * pvecinfoall ;
The next two structures are used by the callback function SendData (see 19.3.3.4). Each time anew data point (e.g. time value and simulation output value(s)) is added to the vector structureof the current plot, the function SendData is called by ngspice, among its parameters the actualpointer pvecvaluesall, which contains an array of pointers to pvecvalues, one for each vector.
346
vecvaluestypedef s t r u c t vecvalues {c h a r * name ;/ * name o f a s p e c i f i c v e c t o r * /double c r e a l ;/* actual data value */d o u b l e cimag ;/* actual data value */bool i s _ s c a l e ;/ * i f name i s t h e s c a l e v e c t o r * /b o o l i s _ c o m p l e x ; / * i f t h e d a t a a r e complex numbers * /} vecvalues , * pvecvalues ;Pointer vecvaluesall to be found as parameter to callback function SendData.vecvaluesalltypedef s t r u c t vecvaluesall {i n t veccount ;/ * number o f v e c t o r s i n p l o t * /i n t vecindex ;/* index of a c t u a l s e t of vectors , i . e .t h e number o f a c c e p t e d d a t a p o i n t s * /pvecvalues * vecsa ; /* values of a c t u a l s e t of vectors ,i n d e x e d from 0 t o v e c c o u n t 1 * /} vecvaluesall , * pvecvaluesall ;
19.3.2
Exported functions
The functions listed in this chapter are the (only) symbols exported by the shared library.19.3.2.1
After caller has loaded ngspice.dll, the simulator has to be initialized by calling ngSpice_Init(...).Address pointers of several callback functions (see 19.3.3), which are to be defined in the caller,are sent to ngspice.dll. The int return value is not used.Pointers to callback functions (details see 19.3.3):SendChar* callback function for reading printf, fprintf, fputs (NULL allowed)SendStat* callback function for reading status string and percent value (NULL allowed)ControlledExit* callback function for transferring a flag to caller, generated by ngspice upona call to function controlled_exit. May be used by caller to detach ngspice.dll, if dynamically loaded or to try any other recovery method, or to exit. (required)SendData* callback function for sending an array of structs containing data values of all vectors in the current plot (simulation output) (NULL allowed)SendInitData* callback function for sending an array of structs containing info on all vectorsin the current plot (immediately before simulation starts) (NULL allowed)
347
BGThreadRunning* callback function for sending a boolean signal (true if thread is running)(NULL allowed)void* Using the void pointer, you may send the object address of the calling function (selfor this pointer) to ngspice.dll. This pointer will be returned unmodified by any callbackfunction (see the *void pointers in chapter 19.3.3). Callback functions are to be definedin the global section of the caller. Because they now have got the object address of thecalling function, they may direct their actions to the calling object.
19.3.2.2
19.3.2.3
int ngSpice_Command(char*)
Send a valid command (see the control or interactive commands) from caller to ngspice.dll.Will be executed immediately (as if in interactive mode). Some commands are rejected (e.g.plot, because there is no graphics interface). Command quit will remove internal data, andthen send a notice to caller via ngexit(). The function returns a 1 upon error, otherwise 0.
19.3.2.4
19.3.2.5
pvector_info ngGet_Vec_Info(char*)
19.3.2.6
int ngSpice_Circ(char**)
sends an array of null-terminated char* to ngspice.dll. Each char* contains a single line of acircuit (Each line is like it is found in an input file *.sp.). The last entry to char** has to beNULL. Upon receiving the array, ngspice.dll will immediately parse the input and set up thecircuit structure (as if the circuit is loaded from a file by the source command). The functionreturns a 1 upon error, otherwise 0.
19.3.2.7
char* ngSpice_CurPlot(void)
returns to the caller a pointer to the name of the current plot. For a definition of the term plotsee chapt. 17.3.
348
19.3.2.8
char** ngSpice_AllPlots(void)
returns to the caller a pointer to an array of all plots (listed by their typename).19.3.2.9
char** ngSpice_AllVecs(char*)
returns to the caller a pointer to an array of all vector names in the plot named by the string inthe argument.19.3.2.10
bool ngSpice_SetBkpt(double)
19.3.3
Callback functions
Callback functions are a means to return data from ngspice to the caller. These functions aredefined as global functions in the caller, so to be reachable by the C-coded ngspice. They aredeclared according to the typedefs given below. ngspice receives their addresses from the callerupon initialization with the ngSpice_Init(...) function (see 19.3.2.1). If the caller will not makeuse of a callback, it may send NULL instead of the address (except for ControlledExit, whichis always required).If ngspice is run in the background thread (19.4.2), the callback functions (defined in the caller)also are called from within that thread. One has to be carefully judging how this behavior mightinfluence the caller, where now you have the primary and the background thread running inparallel. So make the callback function thread safe. The integer identification number is onlyused if you run several shared libraries in parallel (see chapt. 19.6). Three additional callbackfunction are described in chapt. 19.6.3.19.3.3.1
349
19.3.3.3
19.3.3.4
vecvaluesall* pointer to array of structs containing actual values from all vectorsint number of structs (one per vector)int identification number of calling ngspice shared lib (default is 0, see chapt. 19.6)void* return pointer received from callersend back actual vector data.
19.3.3.5
vecinfoall* pointer to array of structs containing data from all vectors right after initializationint identification number of calling ngspice shared lib (default is 0, see chapt. 19.6)void* return pointer received from callersend back initialization vector data.
350
19.3.3.6
19.4
19.4.1
Basically the input to shared ngspice is the same as if you would start a ngspice batch job, e.g.you enter a netlist and the simulation command (any .dot analysis command like .tran, .op, or.dc etc. as found in chapt. 15.3), as well as suitable options.Typically you should not include a .control section in your input file. Any script described in a.control section for standard ngspice should better be emulated by the caller and be sent directlyto ngspice.dll. Start the simulation according to chapt. 19.4.2 in an extra thread.As an alternative, only the netlist has to be entered (without analysis command), then you mayuse any interactive command as listed in chapt. 17.5 (except for the plot command).The typical usage examples given below are excerpted from a caller written in C.19.4.1.1
As with interactive ngspice, you may use the ngspice internal command source (17.5.68) toload a complete netlist from a file.Typical usage:ngSpice_Command ( " s o u r c e . . / e x a m p l e s / a d d e r _ m o s . c i r " ) ;
19.4.1.2
As with interactive ngspice, you may use the ngspice internal command circbyline (17.5.10) tosend a netlist line by line to the ngspice circuit parser.Typical usage:ngSpice_Command ( "ngSpice_Command ( "ngSpice_Command ( "ngSpice_Command ( "ngSpice_Command ( "
circbylinecircbylinecircbylinecircbylinecircbyline
The first line is a title line, which will be ignored during circuit parsing. As soon as the line.end has been sent to ngspice, circuit parsing commences.
351
Typical usage:c i r c a r r a y = ( char **) malloc ( s i z e o f ( char *) * 7 ) ;circarray [0] = strdup (" t e s t array ");c i r c a r r a y [ 1 ] = s t r d u p ( " V1 1 0 1 " ) ;c i r c a r r a y [ 2 ] = s t r d u p ( " R1 1 2 1 " ) ;c i r c a r r a y [ 3 ] = s t r d u p ( " C1 2 0 1 i c = 0 " ) ;c i r c a r r a y [ 4 ] = s t r d u p ( " . t r a n 10 u 3 u i c " ) ;c i r c a r r a y [ 5 ] = s t r d u p ( " . end " ) ;c i r c a r r a y [ 6 ] = NULL ;ngSpice_Circ ( c i r c a r r a y ) ;An array of char pointers is mallocd, each netlist line is then copied to the array. strdup willcare for the memory allocation. The first entry to the array is a title line, the last entry has tocontain NULL. ngSpice_Circ(circarray); sends the array to ngspice, where circuit parsing isstarted immediately. Dont forget to free the array after sending it, to avoid a memory leak.
19.4.2
The following commands are used to start the simulator in its own thread, halt the simulationand resume it again. The extra (background) thread enables the caller to continue with othertasks in the main thread, e.g. watching its own event loop. Of course you have to take carethat the caller will not exit before ngspice is finished, otherwise you immediately will loose alldata. After having halted the simulator by suspending the background thread, you may assessdata, change ngspice parameters, or read output data using the callers main thread, before youresume simulation using a background thread again. While the background thread is running,ngspice will reject any other command sent by ngSpice_Command.Typical usage:ngSpice_Command ( " b g _ r u n " ) ;...ngSpice_Command ( " b g _ h a l t " ) ;...ngSpice_Command ( " b g _ r e s u m e " ) ;Basically you may send the commands run or resume (no prefix bg_), starting ngspice withinthe main thread. The caller then has to wait until ngspice returns from simulation. A commandhalt is not available then.After simulation is finished (test with callback 19.3.3.6), you may send other commands fromchapt. 17.5, emulating any .control script. These commands are executed in the main thread,which should be o.k., because execution time is typically short.
352
19.4.3
Accessing data
19.4.3.1
Synchronous access
The callback functions SendInitData (19.3.3.5) and SendData (19.3.3.4) allow access to simulator output data synchronized with the simulation progress.Each time a new plot is generated during simulation, e.g. when a sequence of op, ac and tranis used or commands like linearize or fft are invoked, the callback SendInitData is called byngspice. Immediately after setting up the vector structure of the new plot, the function is calledonce. Its parameter is a pointer to the structure vecinfoall (19.3.1), which contains an array ofstructures vecinfo, one for each vector in the actual plot. You may simply use vecname to getthe name of any vector. This time the vectors are still empty, but pointers to the vector structureare available.Each time a new data point (e.g. time value and simulation output value(s)) is added to thevector structure of the current plot, the function SendData is called by ngspice. This allowsyou to immediately access the simulation output synchronized with the simulation time, e.g.to interface it to a runtime plot or to use it for some controlled simulation by stopping thesimulation based on a condition, altering parameters and resume the simulation. SendDatareturns a structure vecvaluesall as parameter, which contains an array of structures vecvalues,one for each vector.Some code to demonstrate the callback function usage is referenced below (19.5).19.4.3.2
Asynchronous access
During simulation, while the background thread is running, or after it is finished, you mayuse the functions ngSpice_CurPlot (19.3.2.7), ngSpice_AllPlots (19.3.2.8), ngSpice_AllVecs(19.3.2.9) to retrieve information about vectors available, and function ngGet_Vec_Info (19.3.2.5)to obtain data from a vector and its corresponding scale vector. The timing of the caller and thesimulation progress are independent from each other and not synchronized.Again some code to demonstrate the callback function usage is referenced below (19.5).
19.4.4
After halting ngspice by stopping the background thread (19.4.2), nearly all ngspice commandsare available. Especially alter (17.5.3) and altermod (17.5.4) may be used to change deviceor model parameters. After the modification, the simulation may be resumed immediately.Changes to a circuit netlist, however, are not possible. You would need to load a complete newnetlist (19.4.1) and restart the simulation from the beginning.
19.4.5
Output
After the simulation is finished, use the ngspice commands write (17.5.86) or wrdata (17.5.85)to output data to a file as usual, use the print command (17.5.45) to retrieve data via callbackSendChar (19.3.3.1), or refer to accessing the data as described in chapter 19.4.3.
353
Typical usage:ngSpice_Command ( " w r i t e t e s t o u t . raw V ( 2 ) " ) ;ngSpice_Command ( " p r i n t V ( 2 ) " ) ;
19.4.6
There are several occasions where standard ngspice suffers from an error, cannot recover internally and then exits. If this is happening to the shared module this would mean that theparent application, the caller, is also forced to exit. Therefore (if not suffering form a seg fault)ngspice.dll will call the function controlled_exit as usual, this now calls the callback functionControlledExit (19.3.3.3), which hands over the request for exiting to the caller. The callernow has the task to handle the exit code for ngspice.If ngspice has been linked at runtime by dlopen/LoadLibrary (see 19.2.2), the callback mayclose all threads, and then detach ngspice.dll by invoking dlclose/FreeLibrary. The caller maythen restart ngspice by another loading and initialization (19.3.2.1).If ngspice is included during linking the caller (see 19.2.1), there is not yet a good and generalsolution to error handling, if the error is non-recoverable from inside ngspice.
19.5
Example applications
Three executables (coming with source code) serve as examples for controlling ngspice. Theseare not meant to be "productive" programs, but just give some commented example usages ofthe interface.ng_start.exe is a MS Windows application loading ngspice.dll dynamically. All functions andcallbacks of the interface are assessed. The source code, generated with Turbo Delphi 2006,may be found here, the binaries compiled for 32 Bit are here.Two console applications, compilable with LINUX, CYGWIN, MINGW or MS Visual Studio,are available here, demonstrating either linking upon start-up or loading shared ngspice dynamically at runtime. A simple feedback loop is shown in tests 3 and 4, where a device parameteris changed upon having an output vector value crossing a limit.
19.6
ngspice parallel
The following chapter describes an offer to the advanced user and developer community. If youare interested in evaluating the parallel and synchronized operation of several ngspice instances,this may be one way to go. However, no ready to use implementation is available. You willfind a toolbox and some hints how to use it. Parallelization and synchronization is your task bydeveloping a suitable caller! And of course another major input has to come from partitioningthe circuit into suitable, loosely coupled pieces, each with its own netlist, one netlist per ngspiceinstance. And you have to define the coupling between the circuit blocks. Both are not providedby ngspice, but are again your responsibility. Both are under active research, and the toolboxdescribed below is an offer to join that research.
354
19.6.1
Go parallel!
A simple way to run several invocations of ngspice in parallel for transient simulation is todefine a caller which loads two or more ngspice shared libraries. There is one prerequisite however to do so: the shared libraries have to have different names. So compile ngspice sharedlib (see 19.1), then copy and rename the library file, e.g. ngspice.dll may become ngspice1.dll,ngspice2.dll etc. Then dynamically load ngspice1.dll, retrieve its address, initialize it by callingngSpice_init() (see 19.3.2.1), then continue initialization by calling ngSpice_init_Sync() (see19.6.2.1). An integer identification number may be sent during this step to later uniquely identify each invocation of the shared library, e.g. by having any callback use this identifier. Repeatthe sequence with ngspice2.dll and so on.Inter-process communication and synchronization is now done by using three callback functions. To understand their interdependency, it might be useful to have a look at the transientsimulation sequence as defined in the ngspice source file dctran.c. The following listing includes the shared library option (It differs somewhat from standard procedure.) and disregardsXSPICE.1. initialization.2. calculation of operating point.3. next time step: set new breakpoints (VSRC, ISRC, TRA, LTRA).4. send simulation data to output, callback function SendData* datfcn.5. check for autostop and other end conditions.6. check for interrupting simulation (e.g. by bg_halt).7. breakpoint handling (e.g. enforce breakpoint, set new small cktdelta if directly after thebreakpoint).8. calling ngspice internal function sharedsync() which calls callback function GetSyncData* getsync with location flag loc = 0.9. save the previous states.10. start endless loop.11. save cktdelta to olddelta, set new time point by adding cktdelta to ckttime.12. new iteration of circuit at new time point, which uses callback functions GetVSRCData*getvdat and GetISRCData* getidat to retrieve external voltage or current inputs, returnsredostep=0, if converged, redostep=1 if not converged.13. if not converged, divide cktdelta by 8.14. check for truncation error with all non-linear devices, if necessary create a new (smaller)cktdelta to limit the error, optionally change integration order.15. calling ngspice internal function sharedsync() which calls callback function GetSyncData* getsync with location flag loc = 1: as a result either goto 3 (next time step) or to10 (loop start), depending on ngspice and user data, see next paragraph.
355
The code of the synchronization procedure is handled in the ngspice internal function sharedsync()and its companion user defined callback function GetSyncData* getsync. The actual setup isas follows:If no synchronization is asked for (GetSyncData* set to NULL), program control jumps to nexttime step (3) if redostep==0, or subtracts olddelta from ckttime and jumps to loop start (9) ifredostep <> 0. This is the standard ngspice behavior.If GetSyncData* has been set to a valid address by ngSpice_Init_Sync(), the callback functiongetsync is involved. If redostep <> 0, olddelta is subtracted from ckttime, getsync is called,either the cktdelta time suggested by ngspice is kept or the user provides his own deltatime,and the program execution jumps to (9) for redoing the last step with the new deltatime. Thereturn value of getsync is not used. If redostep == 0, getsync is called. The user may keepthe deltatime suggested by ngspice or define a new value. If the user sets the return value ofgetsync to 0, the program execution then jumps to next time step (3). If the return value ofgetsync is 1, olddelta is subtracted from ckttime, and the program execution jumps to (9) forredoing the last step with the new deltatime. Typically the user provided deltatime should besmaller than the value suggested by ngspice.
19.6.2
The following functions (exported or callback) are designed to support the parallel action ofseveral ngspice invocations. They may be useful, however, also when only a single library isloaded into a caller, if you want to use external voltage or current sources or play with theadvancing simulation time.19.6.2.1
356
19.6.2.2
Sets a breakpoint in ngspice, a time point which the simulator is enforced to hit during thetransient simulation. After the breakpoint time has been hit, the next delta time starts with asmall value and is ramped up again. A breakpoint should be set only when the backgroundthread in ngspice is not running (before the simulation has started, or after the simulation hasbeen paused by bg_halt). The time sent to ngspice should be larger than the current time (whichis either 0 before start or given by the callback GetSyncData (19.6.3.3). Several breakpointsmay be set.
19.6.3
19.6.3.1
Ask for a VSRC EXTERNAL voltage value. The independent voltage source (see chapt. 4.1)with EXTERNAL option allows to set a voltage value to the node defined in the netlist andnamed here at the time returned by the simulator.
19.6.3.2
Ask for ISRC EXTERNAL value. The independent current source (see chapt. 4.1) with EXTERNAL option allows to set a current value to the node defined by the netlist and named hereat the time returned by the simulator.
357
19.6.4
A first example is available as a compacted 7z archive. It contains the source code of a controlling application, as well as its compiled executable and ngspice.dll (for MS Windows). As theinput circuit an inverter chain has been divided into three parts. Three ngspice shared librariesare loaded, each simulates one partition of the circuit. Interconnections between the partitionsare provided via a callback function. The simulation time is synchronized among the threengspice invocations by another callback function.
358
Chapter 20TCLspiceSpice historically comes as a simulation engine with a Command Line Interface. Spice enginenow can be used with friendly Graphical User Interfaces. Tclspice represent a third approachto interfacing ngspice simulation functionality. Tclspice is nothing more than a new way ofcompiling and using spice source code Spice is no longer considered as a standalone programbut as a library invoked by a TCL interpreter. It either permits direct simulation in a friendlyTCL shell (this is quite analogous to the command line interface of ngspice), or it permits theelaboration of more complex, more specific, or more user friendly simulation programs, bywriting TCL scripts.
20.1
tclspice framework
The technical difference between the ngspice CLI interface and tclspice is that the CLI interfaceis compiled as a standalone program, whereas tclspice is a shared object. Tclspice is designed towork with tools that expand the capabilities of ngspice: TCL for the scripting and programminglanguage interface and BLT for data processing and display. This two tools give tclspice all ofits relevance, with the insurance that the functionality is maintained by competent people.Making tclspice (see 20.6) produces two files: libspice.so and pkgIndex.tcl. libspice.so is theexecutable binary that the TCL interpreter calls to handle spice commands. pkgIndex.tcl takeplace in the TCL directory tree, providing the spice package1 to the TCL user.BLT is a TCL package. It is quite well documented. It permits to handle mathematical vectordata structure for calculus and display, in a Tk interpreter like wish.
20.2
tclspice documentation
A detailed documentation on tclspice commands is available on the original tclspice web page.
20.3
spicetoblt
Tclspice opens its doors to TCL and BLT with a single specific command spicetoblt.1 package
360
TCLspice gets its identity in the command spice::vectoblt This command copies data computedby the simulation engine into a tcl variable. vectoblt is composed of three words: vec, to andblt. Vec means spice vector data. To is the English preposition, and blt is a useful tcl packageproviding a vector data structure. Example:b l t : : vector c r e a t e Iexs p i c e : : v e c t o b l t Vex# b r a n c h I e xHere an empty blt vector is created. It is then filled with the vector representation of the currentflowing out of source Vex. Vex#branch is native spices syntax. Iex is the name of the BLTvector.The reverse operation is handled by native spice commands, such as alter, let and set.
20.4
Running TCLspice
20.5
examples
20.5.1
In this crude implementation of a circuit described by Marc KODRNJA, in his PhD thesis thatI found on the Internet. This simulation outputs a graph representing the virtual capacitanceversus the command voltage. The function C = f (V ) is calculated point by point. For each
20.5. EXAMPLES
361
control voltage value, the virtual capacitance is calculated with the voltage and intensity acrossthe output port in a frequency simulation. A control value that should be as close to zero aspossible is calculated to assess simulation success.
20.5.1.1
Invocation:
20.5.1.2
testbench1.tcl
package r e q u i r e s p i c eThis is a comment (Quite useful if you intend to live with other Human beings)
# Test of v i r t u a l c a p a c i t o r e c i r c u i t# Vary t h e c o n t r o l v o l t a g e and l o g t h e r e s u l t i n g c a p a c i t a n c eA good example of the calling of a spice command: precede it with spice::
setsetsetset
n 30 s e t dv 0 . 2vmax [ e x p r $dv / 2 ]vmin [ e x p r 1 * $dv / 2 ]p a s [ e x p r $dv / $n ]
BLT vector is the structure used to manipulate data. Instantiate the vectors
bltbltbltblt
::::::::
vectorvectorvectorvector
createcreatecreatecreate
CtmpCimcheckVcmd
Data is, in my coding style, plotted into graph objects. Instantiate the graph
362
363
s p i c e : : l e t e r r = r e a l ( mean ( s q r t ( ( Vex# b r a n c h ( 2 * P i * i * f r e q u e n c y * Cim *V(5) V ( 6 ) ) ) ^ 2 ) ) )s p i c e : : v e c t o b l t e r r Ctmp c h e c ka p p e n d $Ctmp ( 0 : end )Build abscissa vectorFALTA ALGO . . . Vcmd a p p e n d $v }Plotp a c k . cimvd. cimvd e l e m e n t c r e a t e l i n e 1 x d a t a Vcmd y d a t a Cimpack . checkvd. c h e c k v d e l e m e n t c r e a t e l i n e 1 x d a t a Vcmd y d a t a c h e c k
20.5.2
This example is both the first and the last optimization program I wrote for an electronic circuit.It is far from perfect.The temperature response of a CTN is exponential. It is thus nonlinear. In a battery chargerapplication floating voltage varies linearly with temperature. A TL431 voltage reference seesits output voltage controlled by two resistors (r10, r12) and a thermistor (r11). The simulationis run at a given temperature. The thermistor is modeled in spice by a regular resistor. Itsresistivity is assessed by the TCL script. It is set with a spice::alter command before runningthe simulation. This script uses an iterative optimization approach to try to converge to a setof two resistor values which minimizes the error between the expected floating voltage and theTL431 output.
20.5.2.1
This script can be executed by the user by simply executing the file in a terminal.. / testbench3 . tclTwo issues are important to point out2 :2 For
those who are really interested in optimizing circuits: Some parameters are very important for quick andcorrect convergence. The optimizer walks step by step to a local minimum of the cost function you define. Startingfrom an initial vector YOU provide, it converges step by step. Consider trying another start vector if the result isnot the one you expected.The optimizer will carry on walking until it reaches a vector which resulting cost is smaller than the target costYOU provide it. You will also provide a maximum iteration count in case the target can not be achieved. Balanceyour time, specifications, and every other parameters. For a balance between quick and accurate convergenceadjust the "factor" variable, at the beginning of minimumSteepestDescent in the file differentiate.tcl.
364
20.5.2.2
testbench3.tcl
This calls the shell sh who then runs wish with the file itself.
# ! / bin / sh# WishFix \e x e c w i s h " $0 " $ {1+"$@" }###Regular package for simulation
package r e q u i r e s p i c eHere the important line is source differentiate.tcl which contains optimization library
source d i f f e r e n t i a t e . t c lGenerates a temperature vector
proc t e m p e r a t u r e s _ c a l c { t e m p _ i n f temp_sup p o i n t s } {s e t t s t e p [ expr " ( $temp_sup $temp_inf ) / $ p o i n t s " ]s e t t $temp_infs e t temperatures ""for { set i 0 } { $i < $points } { incr i } {s e t t [ expr { $t + $ t s t e p } ]set temperatures " $temperatures $t "}return $temperatures }generates thermistor resistivity as a vector, typically run: thermistance_calc res B [ temperatures_calc temp_inf temp_sup points ]
365
proc t h e r m i s t a n c e _ c a l c { res B p o i n t s } {s e t t z e r o 273.15s e t t r e f 25s e t thermistance ""foreach t $points {s e t r e s _ t e m p [ e x p r " $ r e s * exp ( $B * ( 1 / ( $ t z e r o + $ t ) 1/ ( $tzero + $tref ) ) ) " ]s e t t h e r m i s t a n c e " $thermistance $res_temp "}return $thermistance }generates the expected floating value as a vector, typically run: tref_calc res B [ temperatures_calc temp_inf temp_sup points ]
proc t r e f _ c a l c { p o i n t s } {s e t t r e f ""foreach t $points {s e t t r e f " $ t r e f [ e x p r " 6 * ( 2 . 2 7 5 0 . 0 0 5 * ( $ t 2 0 ) ) 9" ] "}return $tref }In the optimization algorithm, this function computes the effective floating voltage at the giventemperature.
### NOTE :### As component v a l u e s a r e m o d i f i e d by a s p i c e : : a l t e rComponent v a l u e s c a n be c o n s i d e r e d a s g l o b a l v a r i a b l e .### R10 and R12 a r e n o t p a s s e d t o i t e r a t i o n f u n c t i o n b e c a u s e i ti s e x p e c t e d t o be c o r r e c t , i e t o h a v e b e e n m o d i f i e d s o o nbefore proc i t e r a t i o n { t } { s e t t z e r o 273.15 s pi ce : : a l t e rr 1 1 = [ t h e r m i s t a n c e _ c a l c 10000 3900 $ t ]# T e m p e r a t u r e s i m u l a t i o n o f t e n c r a s h e s . Comment i t o u t . . .# s p i c e : : s e t temp = [ e x p r " $ t z e r o + $ t " ]s p i c e : : opspice : : v e c t o b l t vref_temp tref_tmp###NOTE :### As t h e l i b r a r y i s e x e c u t e d o n c e f o r t h e whole s c r i p te x e c u t i o n , i t i s i m p o r t a n t t o manage t h e memory### and r e g u l a r l y d e s t r o y u n u s e d d a t a s e t . The d a t a computedh e r e w i l l n o t be r e u s e d . C l e a n i tspice : : destroy a l l r e t u r n [ tref_tmp range 0 0 ] }This is the cost function optimization algorithm will try to minimize. It is a 2-norm (Euclideannorm) of the error across the temperature range [-25:75]C.
366
367
## Results# s p i c e : : a l t e r r10 = $r10s p i c e : : a l t e r r12 = $r12foreach point [ t e m p e r a t u r e s _ b l t range 0 [ expr " [t e m p e r a t u r e s _ b l t l e n g t h ] 1" ] ] {t r e f _ b l t append [ i t e r a t i o n $ p o i n t ]}d is p_ cu rv e $r10 $r12
20.5.3
Progressive display
This example is quite simple but it is very interesting. It displays a transient simulation resulton the fly. You may now be familiar with most of the lines of this script. It uses the ability ofBLT objects to automatically update. When the vector data is modified, the strip-chart displayis modified accordingly.
20.5.3.1
testbench2.tcl
# ! / bin / sh# WishFix \e x e c w i s h f " $0 " $ {1+"$@" }###p a c k a g e r e q u i r e BLT p a c k a g e r e q u i r e s p i c ethis avoids to type blt:: before the blt class commands
namespace i m p o r t b l t : : *wm t i t l e . " V e c t o r T e s t s c r i p t "wm g e o m e t r y . 800 x600 +40+40 p a c k p r o p a g a t e . f a l s eA strip chart with labels but without data is created and displayed (packed)
368
stripchart . chartp a c k . c h a r t s i d e t o p f i l l b o t h e x p a n d t r u e. c h a r t a x i s c o n f i g u r e x t i t l e " Time " s p i c e : : s o u r c e e x a m p l e . c i rs p i c e : : bgr u n a f t e r 1000 v e c t o rc r e a t e a0 v e c t o rc r e a t e b0 v e c t o r r yc r e a t e a1 v e c t o rc r e a t e b1 v e c t o rcreate stimep r o c b l t u p d a t e {} {puts [ spice : : spice_data ]s p i c e : : s p i c e t o b l t a0 a0s p i c e : : s p i c e t o b l t b0 b0s p i c e : : s p i c e t o b l t a1 a1s p i c e : : s p i c e t o b l t b1 b1spice : : s p i c e t o b l t time stimea f t e r 100 b l t u p d a t e }b l t u p d a t e . c h a r t e l e m e n t c r e a t e a0 c o l o r r e d x d a t a s t i m e y d a t a a0. c h a r t e l e m e n t c r e a t e b0 c o l o r b l u e x d a t a s t i m e y d a t a b0. c h a r t e l e m e n t c r e a t e a1 c o l o r y e l l o w x d a t a s t i m e y d a t a a1. c h a r t e l e m e n t c r e a t e b1 c o l o r b l a c k x d a t a s t i m e y d a t a b1
20.6
Compiling
20.6.1
Get tcl8.4 from your distribution. You will need the blt plotting package (compatible to the oldtcl 8.4 only) from here. See also the actual blt wiki../configure --with-tcl ..makesudo make install
20.6.2
MS Windows
Can be done, but is tedious. I will describe my procedure on Windows 7, 64 Bit Home Edition.20.6.2.1
Downloads
369
Tcl
Tk
edit D:\software\tk8.6b2\win\buildall.vc.batline 31 tocall "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"line 53 toif "%TCLDIR%" == "" set TCLDIR=..\..\tcl8.6b2open cmd windowcd tod:\software\tk8.6b2\win>thend:\software\tk8.6b2\win> buildall.vc.bat debugtk will be made as tk86t.dll, in addition wish86t.exe is generated.20.6.2.4
blt
blt sorce files have been downloaded from the blt web page and modified for compatibility withTCL8.6. To facilitate making blt24.dll, the modified source code is available as a 7z compressedfile, including a project file for MS Visual Studio 2008.20.6.2.5
tclspice
ngspice is compiled and linked into a dll called spice.dll which may be loaded by wish86t.exe.MS Visual Studio 2008 is the compiler applied. A project file may be downloaded as a 7zcompressed file. Expand this file in the ngspice main directory. The links to tcl and tk arehard-coded, so both have to be installed in the places described above (d:\software\...). spice.dllmay be generated in Debug, Release or ReleaseOMP mode.
20.7
You may download the compiled binaries, including tcl, tk, blt and tclspice, plus the examples,slightly modified, from.
370
Chapter 21Example CircuitsThis section starts with an ngspice example to walk you through the basic features of ngspiceusing its command line user interface. The operation of ngspice will be illustrated throughseveral examples (chapters 20.1 to 20.7).The first example uses the simple one-transistor amplifier circuit illustrated in Figure 21.1. Thiscircuit is constructed entirely with ngspice compatible devices and is used to introduce basicconcepts, including:
The remainder of the section (from chapter 21.2 onwards) lists several circuits, which have beenaccompanying any ngspice distribution, and may be regarded as the classical SPICE circuits.
21.1
The circuit shown in Figure 21.1 is a simple one-transistor amplifier. The input signal is amplified with a gain of approximately -(Rc/Re) = -(3.9K/1K) = -3.9. The circuit description file forthis example is shown below.
372
373
therefore its name, but you do not need installing the XSPICE option to run it.$ cp /examples/xspice/xspice_c1.cir xspice_c1.cirNow invoke the simulator on this circuit as follows:$ ngspice xspice_c1.cirAfter a few moments, you should see the ngspice prompt:ngspice 1 ->At this point, ngspice has read-in the circuit description and checked it for errors. If any errorshad been encountered, messages describing them would have been output to your terminal.Since no messages were printed for this circuit, the syntax of the circuit description was correct.To see the circuit description read by the simulator you can issue the following command:ngspice 1 -> listingThe simulator shows you the circuit description currently in memory:a berkeley spice3 compatible circuit1 : a berkeley spice3 compatible circuit2 : .global gnd10 : .tran 1e-5 2e-312 : vcc vcc 0 12.013 : vin 1 0 0.0 ac 1.0 sin(0 1 1k)14 : ccouple 1 base 10uf15 : rbias1 vcc base 100k16 : rbias2 base 0 24k17 : q1 coll base emit generic18 : rcollector vcc coll 3.9k19 : remitter emit 0 1k21 : .model generic npn24 : .endThe title of this circuit is A Berkeley SPICE3 compatible circuit. The circuit descriptioncontains a transient analysis control command .TRAN 1E-5 2E-3 requesting a total simulatedtime of 2ms with a maximum time-step of 10us. The remainder of the lines in the circuitdescription describe the circuit of Figure 21.1.Now, execute the simulation by entering the run command:ngspice 1 -> run
374
The simulator will run the simulation and when execution is completed, will return with thengspice prompt. When the prompt returns, issue the rusage command again to see how muchtime and memory has been used now.
To examine the results of this transient analysis, we can use the plot command. First we willplot the nodes labeled 1 and base.ngspice 2 -> plot v(1) baseThe simulator responds by displaying an X Window System plot similar to that shown in Figure21.2.
375
376
This command runs a small-signal swept AC analysis of the circuit to compute the magnitudeand phase responses. In this example, the sweep is logarithmic with "decade" scaling, 10 pointsper decade, and lower and upper frequencies of 0.01 Hz and 100 Hz. Since the commandsweeps through a range of frequencies, the results are vectors of values and are examined withthe plot command. Issue to the following command to plot the response curve at node "coll":
This plot shows the AC gain from input to the collector. (Note that our input source in the circuitdescription "vin" contained parameters of the form "AC 1.0" designating that a unit-amplitudeAC signal was applied at this point.) For plotting data from an AC analysis, ngspice choosesautomatically a logarithmic scaling for the frequency (x) axis.To produce a more traditional "Bode" gain phase plot (again with automatic logarithmic scalingon the frequency axis), we use the expression capability of the "plot" command and the built-inNutmeg functions db( ) and ph( ):
The last analysis supported by ngspice is a swept DC analysis. To perform this analysis, issuethe following command:
This command sweeps the supply voltage "vcc" from 0 to 15 volts in 0.1 volt increments. Toplot the results, issue the command:
Finally, to exit the simulator, use the "quit" command, and you will be returned to the operatingsystem prompt.
So long.
21.2
377
Differential Pair
The following deck determines the dc operating point of a simple differential pair. In addition,the ac small-signal response is computed over the frequency range 1Hz to 100MEGHz.Example:SIMPLE DIFFERENTIAL PAIRVCC 7 0 12VEE 8 0 12VIN 1 0 AC 1RS1 1 2 1KRS2 6 0 1KQ1 3 2 4 MOD1Q2 5 6 4 MOD1RC1 7 3 10KRC2 7 5 10KRE 4 8 10K.MODEL MOD1 NPN BF=50 VAF=50 I S = 1 . E12 RB=100 CJC = . 5 PF TF = . 6NS. TF V( 5 ) VIN. AC DEC 10 1 100MEG. END
21.3
MOSFET Characterization
The following deck computes the output characteristics of a MOSFET device over the range0-10V for VDS and 0-5V for VGS.Example:MOS OUTPUT CHARACTERISTICS. OPTIONS NODE NOPAGEVDS 3 0VGS 2 0M1 1 2 0 0 MOD1 L=4U W=6U AD=10P AS=10P* VIDS MEASURES ID , WE COULD HAVE USED VDS, BUT ID WOULD BE NEGATIVEVIDS 3 1.MODEL MOD1 NMOS VTO=2 NSUB= 1 . 0 E15 UO=550. DC VDS 0 10 . 5 VGS 0 5 1. END
21.4
RTL Inverter
The following deck determines the dc transfer curve and the transient pulse response of a simpleRTL inverter. The input is a pulse from 0 to 5 Volts with delay, rise, and fall times of 2ns anda pulse width of 30ns. The transient interval is 0 to 100ns, with printing to be done everynanosecond.
378
Example:SIMPLE RTL INVERTERVCC 4 0 5VIN 1 0 PULSE 0 5 2NS 2NS 2NS 30NSRB 1 2 10KQ1 3 2 0 Q1RC 3 4 1K.MODEL Q1 NPN BF 20 RB 100 TF . 1 NS CJC 2PF. DC VIN 0 5 0 . 1. TRAN 1NS 100NS. END
21.5
The following deck simulates a four-bit binary adder, using several subcircuits to describe various pieces of the overall circuit.
Example:ADDER 4 BIT ALLNANDGATE BINARY ADDER*** SUBCIRCUIT DEFINITIONS. SUBCKT NAND 1 2 3 4* NODES : INPUT ( 2 ) , OUTPUT, VCCQ1 9 5 1 QMODD1CLAMP 0 1 DMODQ2 9 5 2 QMODD2CLAMP 0 2 DMODRB 4 5 4KR1 4 6 1 . 6KQ3 6 9 8 QMODR2 8 0 1KRC 4 7 130Q4 7 6 10 QMODDVBEDROP 10 3 DMODQ5 3 8 0 QMOD. ENDS NAND
379
380
21.6
Example:ADDER 4 BIT ALLNANDGATE BINARY ADDER*** SUBCIRCUIT DEFINITIONS. SUBCKT NAND i n 1 i n 2 o u t VDD* NODES : INPUT ( 2 ) , OUTPUT, VCCM1 o u t i n 2 Vdd Vdd p1 W= 7 . 5 u L = 0 . 3 5 u pd = 1 3 . 5 u ad = 2 2 . 5 p p s = 1 3 . 5 u a s = 2 2 . 5 pM2 n e t . 1 i n 2 0 0 n1W=3uL = 0 . 3 5 u pd =9uad =9pp s =9ua s =9pM3 o u t i n 1 Vdd Vdd p1 W= 7 . 5 u L = 0 . 3 5 u pd = 1 3 . 5 u ad = 2 2 . 5 p p s = 1 3 . 5 u a s = 2 2 . 5 pM4 o u t i n 1 n e t . 1 0 n1 W=3uL = 0 . 3 5 u pd =9uad =9pp s =9ua s =9p. ENDS NAND. SUBCKT ONEBIT 1 2 3 4 5 6 ANDX21 7 8 6NANDX32 7 9 6NANDX48 9 10 6NANDX53 10 11 6NANDX63 11 12 6NANDX7 10 11 13 6NANDX8 12 13 4 6NANDX9 11 7 5 6NAND. ENDS ONEBIT. SUBCKT TWOBIT 1 2 3 4 5 6 7 8 9* NODES : INPUT BIT0 ( 2 ) / BIT1 ( 2 ) , OUTPUT BIT0 / BIT1 ,CARRYIN , CARRYOUT, VCC*X11 2 7 5 10 9ONEBITX23 4 10 6 8 9ONEBIT. ENDS TWOBIT. SUBCKT FOURBIT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15*NODES : INPUT BIT0 ( 2 ) / BIT1 ( 2 ) / BIT2 ( 2 ) / BIT3 ( 2 ) ,OUTPUT BIT0 / BIT1 / BIT2 / BIT3 , CARRYIN ,*CARRYOUT, VCC*X11 2 3 4 9 10 13 16 15TWOBITX25 6 7 8 11 12 16 14 15TWOBIT. ENDS FOURBIT
381
33333333
000000008
5NS5NS5NS5NS5NS5NS5NS5NS
5NS20NS50NS )5NS30NS 100NS )5NS50NS 200NS )5NS90NS 400NS )5NS 170NS 800NS )5NS 330NS 1600NS )5NS 650NS 3200NS )5NS 1290NS 6400NS )
9 10 11 12
0 13 99 FOURBIT
. option acct. s a v e V( 1 ) V( 2 ) V( 3 ) V( 4 ) V( 5 ) V( 6 ) V( 7 ) V( 8 ) ; INPUTS. s a v e V( 9 ) V( 1 0 ) V( 1 1 ) V( 1 2 ) V( 1 3 ) ; OUTPUTS. TRAN 1NS 6400NS* u s e BSIM3 model w i t h d e f a u l t p a r a m e t e r s. model n1 nmos l e v e l =49 v e r s i o n = 3 . 3 . 0. model p1 pmos l e v e l =49 v e r s i o n = 3 . 3 . 0. END
21.7
Transmission-Line Inverter
The following deck simulates a transmission-line inverter. Two transmission-line elements arerequired since two propagation modes are excited. In the case of a coaxial line, the first line(T1) models the inner conductor with respect to the shield, and the second line (T2) models theshield with respect to the outside world.Example:TRANSMISSIONLINE INVERTERV1 1 0 PULSE ( 0 1 0 0 . 1N)R1 1 2 50X1 2 0 0 4 TLINER2 4 0 50. SUBCKT TLINE 1 2 3 4T1 1 2 3 4 Z0=50 TD= 1 . 5NST2 2 0 4 0 Z0=100 TD=1NS. ENDS TLINE. TRAN 0 . 1 NS 20NS. END
382
Chapter 22Statistical circuit analysis
22.1
Real circuits do not operate in a world with fixed values of device parameters, power suppliesand environmental data. Even if a ngspice output offers 5 digits or more of precision, thisshould not mislead you thinking that your circuits will behave exactly the same. All physicalparameters influencing a circuit (e.g. MOS Source/drain resistance, threshold voltage, transconductance) are distributed parameters, often following a Gaussian distribution with a mean valueand a standard deviation .To obtain circuits operating reliably under varying parameters, it might be necessary to simulatethem taking certain parameter spreads into account. ngspice offers several methods supportingthis task. A powerful random number generator is working in the background. Its seed valueis derived from the process id upon start-up of ngspice. If you need reproducible random numbers, you may start ngspice setting the command set rndseed=<int value> into spinit or.spiceinit. The following three chapters offer a short introduction to the statistical methodsavailable in ngspice. The diversity of approaches stems from historical reasons, and from someefforts to make ngspice compatible to other simulators.
22.2
The ngspice frontend (with its numparam parser) contains the .param (see chapt. 2.8.1) and.func (see chapt. 2.9) commands. Among the built-in functions supported (see 2.8.5) you willfind the following statistical functions:
384
Built-in functiongauss(nom, rvar, sigma)
Notesnominal value plus variation drawn from Gaussiandistribution with mean 0 and standard deviation rvar(relative to nominal), divided by sigmanominal value plus variation drawn from Gaussiandistribution with mean 0 and standard deviation avar(absolute), divided by sigmanominal value plus relative variation (to nominal)uniformly distributed between +/-rvarnominal value plus absolute variation uniformly distributedbetween +/-avarnominal value +/-avar, depending on random number in[-1, 1[ being > 0 or < 0
The frontend parser evaluates all .param or .func statements upon start-up of ngspice, beforethe circuit is evaluated. The parameters aga, aga2, lim obtain their numerical values once. If therandom function appears in a device card (e.g. v11 11 0 agauss(1,2,3)), a new randomnumber is generated.Random number example using parameters:* random number tests. param aga = agauss (1 ,2 ,3). param aga2 = 2* aga . param lim = limit (0 ,1.2). func rgauss (a ,b , c ) 5* agauss (a ,b , c ) * always same value as defined abovev1 1 0 lim v2 2 0 lim * may be a different valuev3 3 0 limit (0 ,1.2) * always new random valuesv11 11 0 agauss (1 ,2 ,3) v12 12 0 agauss (1 ,2 ,3) v13 13 0 agauss (1 ,2 ,3) * same value as defined abovev14 14 0 aga v15 15 0 aga v16 16 0 aga2 * using . func , new random valuesv17 17 0 rgauss (0 ,2 ,3) v18 18 0 rgauss (0 ,2 ,3) . op. controlrunprint v (1) v (2) v (3) v (11) v (12) v (13)print v (14) v (15) v (16) v (17) v (18). endc. end
385
So v1, v2, and v3 will get the same value, whereas v4 might differ. v11, v12, and v13 will getdifferent values, v14, v15, and v16 will obtain the values set above in the .param statements..func will start its replacement algorithm, rgauss(a,b,c) will be replaced everywhere by5*agauss(a,b,c).Thus device and model parameters may obtain statistically distributed starting values. Yousimply set a model parameter not to a fixed numerical value, but insert a parameter instead,which may consist of a token defined in a .param card, by calling .func or by using a builtin function, including the statistical functions described above. The parameter values will beevaluated once immediately after reading the input file.
22.3
All sources listed in the section header may contain parameters, which will be evaluated beforesimulation starts, as described in the previous section (22.2). In addition the nonlinear voltageor current sources (B-source, 5) as well as their derivatives E and G, but also the behavioral R,L, and C may be controlled during simulation by a random independent voltage source V withTRRANDOM option (chapt. 4.1.8).An example circuit, a Wien bridge oscillator from input file /examples/Monte_Carlo/OpWien.spis distributed with ngspice or available at Git. The two frequency determining pairs of R andC are varied statistically using four independent Gaussian voltage sources as the controllingunits. An excerpt of this command sequence is shown below. The total simulation time ttimeis divided into 100 equally spaced blocks. Each block will get a new set of control voltages,e.g. VR2, which is Gaussian distributed, mean 0 and absolute deviation 1. The resistor valueis calculated with 10% spread, the factor 0.033 will set this 10% to be a deviation of 1 sigmafrom nominal value.Examples for control of a behavioral resistor:* random r e s i s t o r. param r e s = 10 k. param t t i m e =12000m. param v a r i a =100. param t t i m e 1 0 = t t i m e / v a r i a * random c o n t r o l v o l t a g e ( G a u s s i a n d i s t r i b u t i o n )VR2 r 2 0 dc 0 t r r a n d o m ( 2 t t i m e 1 0 0 1 )* behavioral resistorR2 4 6 R = r e s + 0 . 0 3 3 * r e s *V( r 2 ) So within a single simulation run you will obtain 100 different frequency values issued by theWien bridge oscillator. The voltage sequence VR2 is shown below.
386
22.4
The ngspice scripting language is described in detail in chapter 17.8. All commands listed inchapter 17.5 are available, as well as the built-in functions decried in chapter 17.2, the controlstructures listed in chapter 17.6, and the predefined variables from chapt. 17.7. Variables andfunctions are typically evaluated after a simulation run. You may created loops with severalsimulation runs and change device and model parameters with the alter (17.5.3) or altermod(17.5.4) commands, as shown in the next section 22.5. You may even interrupt a simulation runby proper usage of the stop (17.5.72) and resume (17.5.51) commands. After stop you maychange device or model parameters and then go on with resume, continuing the simulation withthe new parameter values.The statistical functions provided for scripting are listed in the following table:
22.5
387
Monte-Carlo Simulation
The ngspice scripting language may be used to run Monte-Carlo simulations with statisticallyvarying device or model parameters. Calls to the functions sgauss(0) or sunif(0) (see 17.2) willreturn Gaussian or uniform distributed random numbers (real numbers), stored in a vector. Youmay define (see 17.5.14) your own function using sgauss or sunif, e.g. to change the mean orrange. In a loop (see 17.6) then you may call the alter (17.5.3) or altermod (17.5.4) statementswith random parameters followed by an analysis like op, dc, ac, tran or other.
22.5.1
Example 1
The first examples is a LC band pass filter, where L and C device parameters will be changed 100times. Each change is followed by an ac analysis. All graphs of output voltage versus frequencyare plotted. The file is available in the distribution as /examples/Monte_Carlo/MonteCarlo.spas well as from the CVS repository.
388
Monte-Carlo example 1P e r f o r m Monte C a r l o s i m u l a t i o n i n n g s p i c eV1 N001 0 AC 1 DC 0R1 N002 N001 141*C1 OUT 0 1 e 09L1 OUT 0 10 e 06C2 N002 0 1 e 09L2 N002 0 10 e 06L3 N003 N002 40 e 06C3 OUT N003 250 e 12*R2 0 OUT 141*. controll e t mc_runs = 100l e t run = 1s e t c u r p l o t = new$ c r e a t e a new p l o ts e t s c r a t c h = $ c u r p l o t $ s t o r e i t s name t o s c r a t c h *d e f i n e u n i f ( nom , v a r ) ( nom + nom * v a r * s u n i f ( 0 ) )d e f i n e a u n i f ( nom , a v a r ) ( nom + a v a r * s u n i f ( 0 ) )d e f i n e g a u s s ( nom , v a r , s i g ) ( nom + nom * v a r / s i g * s g a u s s ( 0 ) )d e f i n e a g a u s s ( nom , a v a r , s i g ) ( nom + a v a r / s i g * s g a u s s ( 0 ) )*d o w h i l e r u n <= mc_runsa l t e r c1 = u n i f ( 1 e 09 , 0 . 1 )*a l t e r l 1 = a u n i f ( 1 0 e 06 , 2 e 06)*al t e r c2 = a u n i f ( 1 e 09 , 100 e 12)*a l t e r l 2 = u n i f ( 1 0 e 06 , 0 . 2 )*a l t e r l 3 = a u n i f ( 4 0 e 06 , 8 e 06)*a l t e r c3 = u n i f ( 2 5 0 e 12 , 0 . 1 5 )*a l t e r c1 = g a u s s ( 1 e 09 , 0 . 1 , 3 )a l t e r l 1 = a g a u s s ( 1 0 e 06 , 2 e 06 , 3 )a l t e r c2 = a g a u s s ( 1 e 09 , 100 e 12 , 3 )a l t e r l 2 = g a u s s ( 1 0 e 06 , 0 . 2 , 3 )a l t e r l 3 = a g a u s s ( 4 0 e 06 , 8 e 06 , 3 )a l t e r c3 = g a u s s ( 2 5 0 e 12 , 0 . 1 5 , 3 )a c o c t 100 250K 10Megs e t r u n =" $&r u n "$ c r e a t e a v a r i a b l e from t h e v e c t o rset dt = $curplot$ store the current plot to dtsetplot $scratch$ make s c r a t c h t h e a c t i v e p l o t* store the output vector to plot scratch l e t v o u t { $ r u n }={ $ d t } . v ( o u t )s e t p l o t $dt$ go b a c k t o t h e p r e v i o u s p l o tl e t run = run + 1endp l o t db ( { $ s c r a t c h } . a l l ). endc. end
22.5.2
389
Example 2
A more sophisticated input file for Monte Carlo simulation is distributed with the file /examples/Monte_Carlo/MCring.sp (or git repository). Due to its length it is not reproduced here, butsome comments on its enhancements over example 1 (22.5.1) are presented in the following.A 25-stage ring oscillator is the circuit used with a transient simulation. It comprises of CMOSinverters, modeled with BSIM3. Several model parameters (vth, u0, tox, L, and W) shall bevaried statistically between each simulation run. The frequency of oscillation will be measuredby a fft and stored. Finally a histogram of all measured frequencies will be plotted.The function calls to sunif(0) and sgauss(0) return uniformly or Gaussian distributed random numbers. A function unif, defined by the linedefine unif(nom, var) (nom + (nom*var) * sunif(0))will return a value with mean nom and deviation var relative to nom.The lineset n1vth0=@n1[vth0]will store the threshold voltage vth0, given by the model parameter set, into a variable n1vth0,ready to be used by unif, aunif, gauss, or agauss function calls.In the simulation loop the altermod command changes the model parameters before a call totran. After the transient simulation the resulting vector is linearized, a fft is calculated, and themaximum of the fft signal is measured by the meas command and stored in a vector maxffts.Finally the contents of the vector maxffts is plotted in a histogram.For more details, please have a look at the strongly commented input file MCring.sp.
22.6
390
pl4mag.data is the simulation data, f2(x) the starting curve, f1(x) the fitted Gaussian distribution.This is just a simple example. You might explore the powerful built-in functions of Gnuplot todo a much more sophisticated statistical data analysis.
Chapter 23Circuit optimization with ngspice23.1
Optimization of a circuit
Your circuit design (analog, maybe mixed-signal) has already the best circuit topology. Theremight be still some room for parameter selection, e.g. the geometries of transistors or values ofpassive elements, to best fit the specific purpose. This is, what (automatic) circuit optimizationwill deliver. In addition you may fine-tune, optimize and verify the circuit over voltage, processor temperature corners. So circuit optimization is a valuable tool in the hands of an experienceddesigner. It will relieve you from the routine task of endless repetitions of re-simulating yourdesign.You have to choose circuit variables as parameters to be varied during optimization (e.g. devicesize, component values, bias inputs etc.). Then you may pose performance constraints ontoyou circuits (e.g. Vnode < 1.2V, gain > 50 etc.). Optimization objectives are the variables to beminimized or maximized. The n objectives and m constraints are assembled into a cost function.The optimization flow is now the following: The circuit is loaded. Several (perhaps only one)simulations are started with a suitable starter set of variables. Measurements are done on thesimulator output to check for the performance constraints and optimization objectives. Thesedata are fed into the optimizer to evaluate the cost function. A sophisticated algorithm nowdetermines a new set of circuit variables for the next simulator run(s). Stop conditions have tobe defined by the user to tell the simulator when to finish (e.g. fall below a cost function value,parameter changes fall below a certain threshold, number of iterations exceeded).The optimizer algorithms, its parameters and the starting point influence the convergence behavior. The algorithms have to provide measures to reaching the global optimum, not to stickto a local one, and thus are tantamount for the quality of the optimizer.ngspice does not have an integral optimization processor. Thus this chapter will rely on workdone by third parties to introduce ngspice optimization capability.ngspice provides the simulation engine, a script or program controls the simulator and provides the optimizer functionality.Four optimizers are presented here, using ngspice scripting language, using tclspice, using aPython script, and using ASCO, a c-coded optimization program.
392
23.2
Friedrich Schmidt (see his web site) has intensively used circuit optimization during his development of Nonlinear loadflow computation with Spice based simulators. He has provided anoptimizer using the internal ngspice scripting language (see chapt. 17.8). His original scriptsare found here. A slightly modified and concentrated set of his scripts is available from thengspice optimizer directory.The simple example given in the scripts is o.k. with current ngspice. Real circuits have still tobe tested.
23.3
ngspice offers another scripting capability, namely the tcl/tk based tclspice option (see chapt.20). An optimization procedure may be written using a tcl script. An example is provided inchapter 20.5.2.
23.4
Werner Hoch has developed a ngspice optimization procedure based on the differential evolution algorithm [21]. On his web page he provides a Python script containing the control flowand algorithms.
23.5
The ASCO optimizer, developed by Joao Ramos, also applies the differential evolution algorithm [21]. An enhanced version 0.4.7.1, adding ngspice as a simulation engine, may bedownloaded here (7z archive format). Included are executable files (asco, asco-mpi, ngspice-cfor MS Windows). The source code should also compile and function under LINUX (not yettested).ASCO is a standalone executable, which communicates with ngspice via ngspice input and output files. Several optimization examples, originally provided by J. Ramos for other simulators,are prepared for use with ngspice. Parallel processing on a multi-core computer has been testedusing MPI (MPICH2) under MS Windows. A processor network will be supported as well. AMS Windows console application ngspice_c.exe is included in the archive. Several stand alonetools are provided, but not tested yet.Setting up an optimization project with ASCO requires advanced know-how of using ngspice.There are several sources of information. First of all the examples provided with the distribution give hints how to start with ASCO. The original ASCO manual is provided as well, or isavailable here. It elaborates on the examples, using a commercial simulator, and provides adetailed description how to set up ASCO. Installation of ASCO and MPI (under Windows) isdescribed in a file INSTALL.
393
Some remarks on how to set up ASCO for ngspice are given in the following sections (moreto be added). These a meant not as a complete description, but are an addition the the ASCOmanual.
23.5.1
This example is taken from chapter 6.2.2 Tutorial #2 from the ASCO manual. The directoryexamples/ngspice/amp3 contains four files:
amp3.cfg This file contains all configuration data for this optimization. Of special interest isthe following section, which sets the required measurements and the constraints on the measuredparameters:# Measurements #ac_power:VDD:MIN:0dc_gain:VOUT:GE:122unity_gain_frequency:VOUT:GE:3.15E6phase_margin:VOUT:GE:51.8phase_margin:VOUT:LE:70amp3_slew_rate:VOUT:GE:0.777E6#Each of these entries is linked to a file in the /extract subdirectory, having exactly the samenames as given here, e.g. ac_power, dc_gain, unity_gain, phase_margin, and amp3_slew_rate.Each of these files contains an # Info # section, which is currently not used. The # Commands # section may contain a measurement command (including ASCO parameter #SYMBOL#, see file /extract/unity_gain_frequency). It also may contain a .control section (see file/extract/phase_margin_min). During set-up #SYMBOL# is replaced by the file name, a leadingz, and a trailing number according to the above sequence, starting with 0.
amp3.sp This is the basic circuit description. Entries like #LM2# are ASCO-specific, definedin the # Parameters # section of file amp3.cfg. ASCO will replace these parameter placeholderswith real values for simulation, determined by the optimization algorithm. The .control ... .endcsection is specific to ngspice. Entries to this section may deliver workarounds of some commands not available in ngspice, but used in other simulators. You may also define additionalmeasurements, get access to variables and vectors, or define some data manipulation. In thisexample the .control section contains an op measurement, required later for slew rate calculation, as well as the ac simulation, which has to occur before any further data evaluation. Datafrom the op simulation are stored in a plot op1. Its name is saved in variable dt. The ac measurements sets another plot ac1. To retrieve op data from the former plot, you have to use the{$dt}.<vector> notation (see file /extract/amp3_slew_rate).
394
23.5.2
Digital inverter
This example is taken from chapter 6.2.1 Tutorial #1 from the ASCO manual. In additionto the features already mentioned above, it adds Monte-Carlo and corner simulations. The fileinv.cfg contains the following section:#Optimization Flow#Alter:yes$do we want to do corner analysis?MonteCarlo:yes$do we want to do MonteCarlo analysis?
395
10 , 1(23.1)W = AGAUSS W, 2 W L m 100AV T9delvto = AGAUSS 0, 10 , 12 W L m
(23.2)
The .ALTER command is not available in ngspice. However, a new option in ngspice to thealtermod command (17.5.4) enables the simulation of design corners. The #Alter# section ininv.cfg gives details. Specific to ngspice, again several .control section are used.# ALTER #.control* gate oxide thickness variedaltermod nm pm file [b3.min b3.typ b3.max].endc.control* power supply variationalter vdd=[2.0 2.1 2.2].endc.control
396
run.endc#NMOS (nm) and PMOS (pm) model parameter sets are loaded from three different model files,each containing both NMOS and PMOS sets. b3.typ is assembled from the original parameterfiles n.typ and p.typ, provided with original ASCO, with some adaptation to ngspice BSIM3.The min and max sets are artificially created in that only the gate oxide thickness deviates 1nm from what is found in model file b3.typ. In addition the power supply voltage is varied, soin total you will find 3 x 3 simulation combinations in the input file <computer-name>.sp (afterrunning asco-test).
23.5.3
Bandpass
This example is taken from chapter 6.2.4 Tutorial #4 from the ASCO manual. S11 in thepassband is to be maximised. S21 is used to extract side lobe parameters. The .net command isnot available in ngspice, so S11 and S21 are derived with a script in file bandpass.sp as describedin chapt. 17.9. The measurements requested in bandpass.cfg as# Measurements #Left_Side_Lobe:---:LE:-20Pass_Band_Ripple:---:GE:-1Right_Side_Lobe:---:LE:-20S11_In_Band:---:MAX:--#are realized as measure commands inside of control sections (see files in directory extract).The result of a measure statement is a vector, which may be processed by commands in thefollowing lines. In file extract/S1_In_Band #Symbol# is made available only after a short calculation (inversion of sign), using the print command. quit has been added to this entry becauseit will become the final control section in <computer-name>.sp. A disadvantage of measureinside of a .control section is, that parameters from .param statements may not be used (as isdone in example 23.5.4).The bandpass example includes the calculation of RF parasitic elements defined in rfmodule.cfg(see chapt. 7.5 of the ASCO manual). This calculation is invoked by settingExecuteRF:yes
in bandpass.cfg. The two subcircuits LBOND_sub and CSMD_sub are generated in <computername>.sp to simulate these effects.
23.5.4
This example is taken from chapter 6.2.3 Tutorial #3 from the ASCO manual. In this examplethe ASCO post processing is applied in file extract/P_OUT (see chapter 7.4 of the ASCO manual.). In this example .measurement statements are used. They allow using parameters from.param statements, because they will be located outside of .control sections, but do not allow todo data post processing inside of ngspice. You may use ASCO post processing instead.
Chapter 24Notes24.1
Glossary
card A logical SPICE input line. A card may be extended through the use of the + sign inSPICE, thereby allowing it to take up multiple lines in a SPICE deck.code model A model of a device, function, component, etc. which is based solely on a Cprogramming language-based function. In addition to the code models included with theXSPICE option of the ngspice simulator, you can use code models that you develop forcircuit modeling.deck A collection of SPICE cards which together specify all input information required inorder to perform an analysis. A deck of cards will in fact be contained within a fileon the host computer system.element card A single, logical line in an ngspice circuit description deck which describes acircuit element. Circuit elements are connected to each other to form circuits (e.g., alogical card which describes a resistor, such as R1 2 0 10K, is an element card).instance A unique occurrence of a circuit element. See element card, in which the instanceR1 is specified as a unique element (instance) in a hypothetical circuit description.macro A macro, in the context of this document, refers to a C language macro which supports the construction of user-defined models by simplifying input/output and parameterpassing operations within the Model Definition File..mod Refers to the Model Definition File in XSPICE. The file suffix reflects the file-name ofthe model definition file: cfunc.mod..model Refers to a model card associated with an element card in ngspice. A model card allowsfor data defining an instance to be conveniently located in the ngspice deck such that thegeneral layout of the elements is more readable.Nutmeg The ngspice default post-processor. This provides a simple stand-alone simulatorinterface which can be used with the ngspice simulator to display and plot simulator rawfiles.
398
subcircuit A device within an ngspice deck which is defined in terms of a group of elementcards and which can be referenced in other parts of the ngspice deck through elementcards.
24.2
Bibliography[1] A. Vladimirescu and S. Liu, The Simulation of MOS Integrated Circuits Using SPICE2ERL Memo No. ERL M80/7, Electronics Research Laboratory University of California,Berkeley, October 1980[2] T. Sakurai and A. R. Newton, A Simple MOSFET Model for Circuit Analysis and its application to CMOS gate delay analysis and series-connected MOSFET Structure ERL MemoNo. ERL M90/19, Electronics Research Laboratory, University of California, Berkeley,March 1990[3] B. J. Sheu, D. L. Scharfetter, and P. K. Ko, SPICE2 Implementation of BSIM ERL MemoNo. ERL M85/42, Electronics Research Laboratory University of California, Berkeley,May 1985[4] J. R. Pierret, A MOS Parameter Extraction Program for the BSIM Model ERL Memo Nos.ERL M84/99 and M84/100, Electronics Research Laboratory University of California,Berkeley, November 1984[5] Min-Chie Jeng, Design and Modeling of Deep Submicrometer MOSFETSs ERL MemoNos. ERL M90/90, Electronics Research Laboratory, University of California, Berkeley,October 1990[6] Soyeon Park, Analysis and SPICE implementation of High Temperature Effects on MOSFET, Masters thesis, University of California, Berkeley, December 1986.[7] Clement Szeto, Simulation of Temperature Effects in MOSFETs (STEIM), Masters thesis, University of California, Berkeley, May 1988.[8] J.S. Roychowdhury and D.O. Pederson, Efficient Transient Simulation of Lossy Interconnect, Proc. of the 28th ACM/IEEE Design Automation Conference, June 17-21 1991, SanFrancisco[9] A. E. Parker and D. J. Skellern, An Improved FET Model for Computer Simulators, IEEETrans CAD, vol. 9, no. 5, pp. 551-553, May 1990.[10] R. Saleh and A. Yang, Editors, Simulation and Modeling, IEEE Circuits and Devices, vol.8, no. 3, pp. 7-8 and 49, May 1992.[11] H.Statz et al., GaAs FET Device and Circuit Simulation in SPICE, IEEE Transactions onElectron Devices, V34, Number 2, February 1987, pp160-169.[12] Weidong Liu et al.: BSIM3v3.2.3 MOSFET Model Users Manual, BSIM3v3.2.3
399
400
BIBLIOGRAPHY
[13] Weidong Lui et al.: BSIM3.v3.3.0 MOSFET Model Users Manual, BSIM3v3.3.0[14] SPICE3.C1 Nutmeg Programmers Manual, Department of Electrical Engineering andComputer Sciences, University of California, Berkeley, California, April, 1987.[15] Thomas L. Quarles: SPICE3 Version 3C1 Users Guide, Department of Electrical Engineering and Computer Sciences, University of California, Berkeley, California, April,1989.[16] Brian Kernighan and Dennis Ritchie: The C Programming Language, Second Edition,Prentice-Hall, Englewood Cliffs, New Jersey, 1988.[17] Code-Level Modeling in XSPICE, F.L. Cox, W.B. Kuhn, J.P. Murray, and S.D. Tynor,published in the Proceedings of the 1992 International Symposium on Circuits and Systems, San Diego, CA, May 1992, vol 2, pp. 871-874.[18] A Physically Based Compact Model of Partially Depleted SOI MOSFETs for Analog Circuit Simulation, Mike S. L. Lee, Bernard M. Tenbroek, William Redman-White, JamesBenson, and Michael J. Uren, IEEE JOURNAL OF SOLID-STATE CIRCUITS, VOL. 36,NO. 1, JANUARY 2001, pp. 110-121[19] A Realistic Large-signal MESFET Model for SPICE, A. E. Parker, and D. J. Skellern,IEEE Transactions on Microwave Theory and Techniques, vol. 45, no. 9, Sept. 1997, pp.1563-1571.[20] Integrating RTS Noise into Circuit Analysis, T. B. Tang and A. F. Murray, IEEE ISCAS,2009, Proc. of IEEE ISCAS, Taipei, Taiwan, May 2009, pp 585-588 (link)[21] R. Storn, and K. Price: Differential Evolution, technical report TR-95-012, ICSI, March1995, see report download, or the DE web page[22] M. J. M. Pelgrom e.a.: Matching Properties of MOS Transistors, IEEE J. Sol. State Circ,vol. 24, no. 5, Oct. 1989, pp. 1433-1440[23] Y. V. Pershin, M. Di Ventra: "SPICE model of memristive devices with threshold",arXiv:1204.2600v1 [physics.comp-ph] 12 Apr 2012,
Part IIXSPICE Software Users Manual
401
Chapter 25XSPICE Basics25.1
The XSPICE option allows you to add event-driven simulation capabilities to NGSPICE. NGSPICEnow is the main software program that performs mathematical simulation of a circuit specifiedby you, the user. It takes input in the form of commands and circuit descriptions and producesoutput data (e.g. voltages, currents, digital states, and waveforms) that describe the circuitsbehavior.Plain NGSPICE is designed for analog simulation and is based exclusively on matrix solutiontechniques. The XSPICE option adds even-driven simulation capabilities. Thus, designs thatcontain significant portions of digital circuitry can be efficiently simulated together with analogcomponents. NGSPICE with XSPICE option also includes a User-Defined Node capabilitythat allows event-driven simulations to be carried out with any type of data.The XSPICE option has been developed by the Computer Science and Information TechnologyLaboratory at Georgia Tech Research Institute of the Georgia Institute of Technology, Atlanta,Georgia 30332 at around 1990 and enhanced by the NGSPICE team. The manual is based onthe original XSPICE users manual, made available from Georgia Tech.In the following, the term XSPICE may be read as NGSPICE with XSPICE code model subsystem enabled. You may enable the option by adding --enable-xspice to the ./configurecommand. The MS Windows distribution already contains the XSPICE option.
25.2
The new component of ngspice, the Code Model Subsystem, provides the tools needed to modelthe various parts of your system. While NGSPICE is targeted primarily at integrated circuit (IC)analysis, XSPICE includes features to model and simulate board-level and system-level designsas well. The Code Model Subsystem is central to this new capability, providing XSPICE withan extensive set of models to use in designs and allowing you to add your own models to thismodel set.The NGSPICE simulator at the core of XSPICE includes built-in models for discrete components commonly found within integrated circuits. These model primitives include components such as resistors, capacitors, diodes, and transistors. The XSPICE Code Model Subsystem
403
404
extends this set of primitives in two ways. First, it provides a library of over 40 additional primitives, including summers, integrators, digital gates, controlled oscillators, s-domain transferfunctions, and digital state machines. See chapter 12 for a description of the library entries.Second, it adds a code model generator to ngspice which provides a set of programming utilities to make it easy for you to create your own models by writing them in the C programminglanguage.The code models are generated upon compiling ngspice. They are stored in shared libraries,which may be distributed independently from the ngspice sources. Upon runtime ngspice willload the code model libraries and make the code model instances available for simulation.
25.3
A top-level diagram of the XSPICE system integrated into ngspice is shown in Figure 25.1.The XSPICE Simulator is made up of the NGSPICE core, the event-driven algorithm, circuitdescription syntax parser extensions, a loading routine for code models, and the Nutmeg userinterface. The XSPICE Code Model Subsystem consists of the Code Model Generator, 5 standard code model library sources with more than 40 code models, the sources for Node TypeLibraries, and all the interfaces to User-Defined Code Models and to User-Defined Node Types.
Chapter 26Execution ProceduresThis chapter covers operation of the XSPICE simulator and the Code Model Subsystem. Itbegins with background material on simulation and modeling and then discusses the analysismodes supported in XSPICE and the circuit description syntax used for modeling. Detaileddescriptions of the predefined Code Models and Node Types provided in the XSPICE librariesare also included.
26.1
This section introduces the concepts of circuit simulation and modeling. It is intended primarilyfor users who have little or no previous experience with circuit simulators, and also for thosewho have not used circuit simulators recently. However, experienced SPICE users may wish toscan the material presented here since it provides background for new Code Model and UserDefined Node capabilities of the XSPICE option.
26.1.1
This section provides an overview of the circuit description syntax expected by the XSPICEsimulator. A general understanding of circuit description syntax will be helpful to you shouldyou encounter problems with your circuit and need to examine the simulators error messages,or should you wish to develop your own models.This section will introduce you to the creation of circuit description input files using the Nutmeguser interface. Note that this material is presented in an overview form. Details of circuitdescription syntax are given later in this chapter and in the previous chapters of this manual.26.1.1.1
Although different SPICE-based simulators may include various enhancements to the basicversion from the University of California at Berkeley, most use a similar approach in describingcircuits. This approach involves capturing the information present in a circuit schematic inthe form of a text file that follows a defined format. This format requires the assignment ofalphanumeric identifiers to each circuit node, the assignment of component identifiers to each
406
This file exhibits many of the most important properties common to all SPICE circuit description files including the following: The first line of the file is always interpreted as the title of the circuit. The title mayconsist of any text string. Lines which provide user comments, but no circuit information, are begun by an asterisk. A circuit device is specified by a device name, followed by the node(s) to which it isconnected, and then by any required parameter information. The first character of a device name tells the simulator what kind of device it is (e.g. R =resistor, C = capacitor, E = voltage controlled voltage source). Nodes may be labeled with any alphanumeric identifier. The only specific labeling requirement is that 0 must be used for ground. A line that begins with a dot is a control directive. Control directives are used mostfrequently for specifying the type of analysis the simulator is to carry out.
407
To determine the quiescent operating point of the circuit, the following statement may be inserted in the file..opA fourth analysis type supported by ngspice is swept DC analysis. An example control statement for the analysis mode is.dc Vin -0.1 0.2 .05
This statement specifies a DC sweep which varies the source Vin from -100 millivolts to +200millivolts in steps of 50 millivolts.
408
The file discussed in the previous section illustrated the most basic syntax rules of a circuitdescription file. However, ngspice (and other SPICE-based simulators) include many otherfeatures which allow for accurate modeling of semiconductor devices such as diodes and transistors and for grouping elements of a circuit into a macro or subcircuit description which canbe reused throughout a circuit description. For instance, the file shown below is a representationof the schematic shown in Figure 26.2.
409
This is the same basic circuit as in the initial example, with the addition of two components andsome changes to the simulation file. The two diodes have been included to illustrate the use ofdevice models, and the amplifier is implemented with a subcircuit. Additionally, this file showsthe use of the swept DC control card.Device Models Device models allow you to specify, when required, many of the parametersof the devices being simulated. In this example, model statements are used to define the silicondiodes. Electrically, the diodes serve to limit the voltage at the amplifier input to values betweenabout 700 millivolts. The diode is simulated by first declaring the instance of each diodewith a device statement. Instead of attempting to provide parameter information separately forboth diodes, the label 1n4148 alerts the simulator that a separate model statement is includedin the file which provides the necessary electrical specifications for the device (1n4148 is thepart number for the type of diode the model is meant to simulate).The model statement that provides this information is:.model 1n4148 D (is=2.495E-09 rs=4.755E-01 n=1.679E+00+tt=3.030E-09 cjo=1.700E-12 vj=1 m=1.959E-01+bv=1.000E+02 ibv=1.000E-04)
The model statement always begins with the string .model followed by an identifier and themodel type (D for diode, NPN for NPN transistors, etc).The optional parameters (is, rs, n, etc.) shown in this example configure the simulatorsmathematical model of the diode to match the specific behavior of a particular part (e.g. a1n4148).Subcircuits In some applications, describing a device by embedding the required elements inthe main circuit file, as is done for the amplifier in Figure 26.1, is not desirable. A hierarchicalapproach may be taken by using subcircuits. An example of a subcircuit statement is shown inthe second circuit file:X1 Amp_In 0 Amp_Out
Amplifier Subcircuits are always identified by a device label beginning with X. Just as withother devices, all of the connected nodes are specified. Notice, in this example, that three nodesare used. Finally, the name of the subcircuit is specified. Elsewhere in the circuit file, thesimulator looks for a statement of the form:.subckt <Name> <Node1> <Node2> <Node3> ...
This statement specifies that the lines that follow are part of the Amplifier subcircuit, and that thethree nodes listed are to be treated wherever they occur in the subcircuit definition as referring,respectively, to the nodes on the main circuit from which the subcircuit was called. Normaldevice, model, and comment statements may then follow. The subcircuit definition is concludedwith a statement of the form:.ends <Name>
410
26.1.1.3
In the previous example, the specification of the amplifier was accomplished by using a NGSPICEVoltage Controlled Voltage Source device. This is an idealization of the actual amplifier. Practical amplifiers include numerous non-ideal effects, such as offset error voltages and non-idealinput and output impedances. The accurate simulation of complex, real-world components canlead to cumbersome subcircuit files, long simulation run times, and difficulties in synthesizingthe behavior to be modeled from a limited set of internal devices known to the simulator.To address these problems, XSPICE allows you to create Code Models which simulate complex,non-ideal effects without the need to develop a subcircuit design. For example, the following fileprovides simulation of the circuit in Figure 26.2, but with the subcircuit amplifier replaced witha Code Model called Amp that models several non-ideal effects including input and outputimpedance and input offset voltage.
A statement with a device label beginning with A alerts the simulator that the device usesa Code Model. The model statement is similar in form to the one used to specify the diode.The model label Amp directs XSPICE to use the code model with that name. Parameterinformation has been added to specify a gain of -10, an input offset of 1 millivolt, an inputimpedance of 1 meg ohm, and an output impedance of 0.4 ohm. Subsequent sections of thisdocument detail the steps required to create such a Code Model and include it in the XSPICEsimulator.
411
When a mixed-mode simulator is used, some method must be provided for translating databetween the different simulation algorithms. XSPICEs Code Model support allows you todevelop models that work under the analog simulation algorithm, the event-driven simulationalgorithm, or both at once.In XSPICE, models developed for the express purpose of translating between the different algorithms or between different User-Defined Node types are called Node Bridge models. Fortranslations between the built-in analog and digital types, predefined node bridge models areincluded in the XSPICE Code Model Library.26.1.1.5
In practice, developing models often involves using a combination of NGSPICE passive devices, device models, subcircuits, and XSPICE Code Models. XSPICEs Code Models may beseen as an extension to the set of device models offered in standard NGSPICE. The collectionof over 40 predefined Code Models included with XSPICE provides you with an enriched set ofmodeling primitives with which to build subcircuit models. In general, you should first attemptto construct your models from these available primitives. This is often the quickest and easiestmethod.If you find that you cannot easily design a subcircuit to accomplish your goal using the availableprimitives, then you should turn to the code modeling approach. Because they are written in ageneral purpose programming language (C), code models enable you to simulate virtually anybehavior for which you can develop a set of equations or algorithms.
26.2
If you need to debug a simulation, if you are planning to develop your own models, or if youare using the XSPICE simulator through the Nutmeg user interface, you will need to becomefamiliar with the circuit description language.The previous sections presented example circuit description input files. The following sectionsprovide more detail on XSPICE circuit descriptions with particular emphasis on the syntaxfor creating and using models. First, the language and syntax of the NGSPICE simulator aredescribed and references to additional information are given. Next, XSPICE extensions to thengspice syntax are detailed. Finally, various enhancements to NGSPICE operation are discussedincluding polynomial sources, arbitrary phase sources, supply ramping, matrix conditioning,convergence options, and debugging support.
26.2.1
In the preceding discussion, NGSPICE syntax was reviewed, and those features of NGSPICEthat are specifically supported by the XSPICE simulator were enumerated. In addition to thesefeatures, there exist extensions to the NGSPICE capabilities that provide much more flexibilityin describing and simulating a circuit. The following sections describe these capabilities, aswell as the syntax required to make use of them.
41226.2.1.1
When a simulation is failing to converge, the simulator can be asked to return convergence diagnostic information that may be useful in identifying the areas of the circuit in which convergenceproblems are occurring. When running through the Nutmeg user interface, these messages arewritten directly to the terminal.
26.2.1.2
Digital Nodes
Support is included for digital nodes that are simulated by an event-driven algorithm. Becausethe event-driven algorithm is faster than the standard SPICE matrix solution algorithm, andbecause all digital, real, int and User-Defined Node types make use of the event-drivenalgorithm, reduced simulation time for circuits that include these models can be anticipatedcompared to simulation of the same circuit using analog code models and nodes.
26.2.1.3
User-Defined Nodes
Support is provided for User Defined Nodes that operate with the event-driven algorithm. Thesenodes allow the passing of arbitrary data structures among models. The real and integer nodetypes supplied with XSPICE are actually predefined User-Defined Node types.
26.2.1.4
Supply Ramping
413
Example:Supply ramping option** This circuit demonstrates the use of the option* " ramptime " which ramps independent sources and the* capacitor and inductor initial conditions from* zero to their final value during the time period* specified .**. tran 0.1 5. option ramptime =0.2* a1 1 0 cap. model cap capacitor ( c =1000 uf ic =1)r1 1 0 1 k*a2 2 0 ind. model ind inductor ( l =1 H ic =1)r2 2 0 1.0*v1 3 0 1.0r3 3 0 1 k*i1 4 0 1e -3r4 4 0 1 k*v2 5 0 0.0 sin (0 1 0.3 0 0 45.0)r5 5 0 1 k*. end
26.3
The following instruction to create an additional code model uses the ngspice infrastructure andsome intelligent copy and paste. As an example an extra code model d_xxor is created in thextradev shared library, reusing the existing d_xor model from the digital library. More detailedinformation will be made available in chapter 28.You should have downloaded ngspice, either the most recent distribution or from the Git repository, and compiled and installed it properly according to your operating system and the instructions given in chapter 32 of the Appendix, especially chapt. 32.1.4 (for LINUX users), or chapt.32.2.1 for MINGW and MS Windows (MS Visual Studio will not do, because we not yet haveintegrated the code model generator into this compiler! You may however use all code modelslater with any ngspice executable.) . Then Cd into directory ngspice/src/xspice/icm/xtradev.
414
mkdir d_xxor
Copy the two files cfunc.mod and ifspec.ifs from ngspice/src/xspice/icm/digital/d_xor to ngspice/src/xspice/icm/xtradev/d_xxor. These two files may serve as a template for your new model!
For simplicity reasons we do only a very simple editing to these files here, in fact the functionality is not changed, just the name translated to a new model. Edit the new cfunc.mod: In lines5, 28, 122, 138, 167, 178 replace the old name (d_xor) by the new name d_xxor. Edit the newifspec.ifs: In lines 16, 23, 24 replace cm_d_xor by cm_d_xxor and d_xor by d_xxor.
make
And thats it! In ngspice/release/src/xspice/icm/xtradev/ you now will find cfunc.c and ifspec.cand the corresponding object files. The new code model d_xxor resides in the shared libraryxtradev.cm, and is available after ngspice is started. As a test example you may editngspice/src/xspice/examples/digital_models1.deck, and change line 60 to the new model:
|
https://fr.scribd.com/document/286949382/Ngspice-Manual
|
CC-MAIN-2019-39
|
refinedweb
| 91,762
| 56.55
|
Opened 9 years ago
Closed 6 years ago
Last modified 6 years ago
#5677 closed (fixed)
Debugging with mod_python (apache)
Description
This is what the docs say:.
This is not completely true. Everything you write to sys.stderr ends up in the apache error log, like this
import sys sys.stderr.write('This goes to the apache error log')
Attachments (4)
Change History (23)
comment:1 Changed 9 years ago by mtredinnick
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
comment:2 Changed 9 years ago by grahamd.
comment:3 Changed 9 years ago by nickefford
- Owner changed from nobody to nickefford
comment:4 Changed 9 years ago by nickefford
- Has patch set
- Keywords sprintdec01 added
Done, incorporating suggestions of Malcolm and grahamd.
Changed 9 years ago by nickefford
Patch to modpython.txt to clarify use of print statements
comment:5 Changed 9 years ago by Simon G <dev@…>
- Triage Stage changed from Accepted to Ready for checkin
comment:6 follow-up: ↓ 7 Changed 9 years ago by dharris
What about using standard python logging? Is there a way to get this to go to the error log (or elsewhere)?
comment:7 in reply to: ↑ 6 Changed 8 years ago by adroffner@…
- Component changed from Documentation to Contrib apps
- Has patch unset
- Keywords logging modpython mod_python added; sprintdec01 removed
- Needs documentation set
- Summary changed from Debugging with mod_python (apache) improperly documented to Logging errors with mod_python (apache)
- Triage Stage changed from Ready for checkin to Unreviewed.
comment:8 Changed 8 years ago by anonymous
- Component changed from Contrib apps to Documentation
- Has patch set
- Keywords logging modpython removed
- Needs documentation unset
- Summary changed from Logging errors with mod_python (apache) to Debugging with mod_python (apache)
- Triage Stage changed from Unreviewed to Ready for checkin
comment:9 Changed 8 years ago by ubernostrum
- Triage Stage changed from Ready for checkin to Unreviewed
Please don't anonymously bump something to "ready for checkin"; that status implies a certain level of review by an experienced triager.
comment:10 Changed 8 years ago by guettli
- Triage Stage changed from Unreviewed to Accepted
This ticket was already accepted (Triage Stage).
comment:11 Changed 8 years ago by Camille Harang)
Changed 7 years ago by timo
updated patch, including new location of modpython.txt
comment:12 Changed 7 years ago by timo
- Triage Stage changed from Accepted to Ready for checkin
I don't think we can expect to document every possible solution to debugging, but the current patch looks like a good addition.
comment:13 Changed 7 years ago by kmtracey
- Triage Stage changed from Ready for checkin to Accepted
I do not like the current patch's inclusion of a vague reference to corrupting client output in "some WSGI hosting solutions". This is text going into the page describing mod_python deployment, specifically. It should limit itself to what happens under mod_python. Sure, adding prints to stdout is a bad idea in other hosting environments too, but that's irrelevant to someone trying to figure out how to debug a problem under mod_python and more likely to cause confusion than anything else.
comment:14 Changed 6 years ago by Rupe
- milestone set to 1.2
comment:15 Changed 6 years ago by russellm
- milestone 1.2 deleted
Deferring due to the absence of a trunk-ready patch.
Changed 6 years ago by danielr
Updated patch removing references to WSGI.
comment:16 Changed 6 years ago by danielr
Updated patch removing references to WSGI.
Changed 6 years ago by timo
updated danielr's patch to apply cleanly trunk
comment:17 Changed 6 years ago by timo
- Triage Stage changed from Accepted to Ready for checkin
comment:18 Changed 6 years ago by DrMeers
- Resolution set to fixed
- Status changed from new to closed
If somebody is going to create a patch for this, it must also mention that stderr is buffered in mod_python, so flushing the pipe each time is a necessity if you want to actually see the results in more-or-less realtime.
|
https://code.djangoproject.com/ticket/5677
|
CC-MAIN-2016-36
|
refinedweb
| 677
| 52.73
|
%matplotlib inline import random import numpy as np import matplotlib.pyplot as plt from math import sqrt, pi import scipy import scipy.stats plt.style.use('seaborn-whitegrid')
!pip install --user pydataset
Requirement already satisfied: pydataset in /home/whitead/.local/lib/python3.7/site-packages (0.2.0) Requirement already satisfied: pandas in /home/whitead/miniconda3/lib/python3.7/site-packages (from pydataset) (0.24.2) Requirement already satisfied: pytz>=2011k in /home/whitead/miniconda3/lib/python3.7/site-packages (from pandas->pydataset) (2019.1) Requirement already satisfied: numpy>=1.12.0 in /home/whitead/miniconda3/lib/python3.7/site-packages (from pandas->pydataset) (1.16.3) Requirement already satisfied: python-dateutil>=2.5.0 in /home/whitead/miniconda3/lib/python3.7/site-packages (from pandas->pydataset) (2.8.0) Requirement already satisfied: six>=1.5 in /home/whitead/miniconda3/lib/python3.7/site-packages (from python-dateutil>=2.5.0->pandas->pydataset) (1.12.0)
import pydataset data = pydataset.data('chickwts').values data.shape
initiated datasets repo at: /home/whitead/.pydataset/
(71, 2)
We have loaded a dataset with 71 data points and each data point has 2 pieces of information. Let's see one
print(data[0, :])
[179 'horsebean']
The first slice index says grab row
0 and the second slice says grab all columns. Each data point contains the mass of a chicken and the type of food it was fed.
#load data huron = pydataset.data('LakeHuron').values #see the dimensions of the data print(huron.shape) #look at the first row print(huron[0,:])
(98, 2) [1875. 580.38]
This data has 98 rows and 2 columns. The columns contain the year and the depth of Lake Huron in feet. We cannot simply take the mean of all the data because that would be the mean of all years and depths. Instead, we can slice out only one of the columns
huron_mean = np.mean(huron[:, 1]) print(huron_mean)
579.0040816326531
We now will follow significant figures convention in our calculations. Each data point in the dataset has 5 digits of precision, so our mean should as well. Thus we will print like so:
huron_mean = np.mean(huron[:, 1]) print('The mean is {:.5} ft'.format(huron_mean))
The mean is 579.0 ft
We can similarily calculate the sample standard deviation:
huron_std = np.std(huron[:, 1], ddof=1) print('The sample standard deviation is {:.5} ft'.format(huron_std))
The sample standard deviation is 1.3183 ft
We had to specify manually that we want to have the $N - 1$ term in the denominator.
numpy uses a convention where you can specify what is subtracted from $N$ in the denominator through the
ddof argument, which stands for deducted degrees of freedom. Thus
ddof = 1 means we want to have $N - 1$ in the denominator instead of the default $N$ in the denominator.
#create some data x = [1, 2, 13, 15, 11, 12] #compute histogram counts, bin_edges = np.histogram(x, bins=[0, 10, 20]) for i in range(len(counts)): print('There were {} samples between {} and {}'.format(counts[i], bin_edges[i], bin_edges[i + 1]))
There were 2 samples between 0 and 10 There were 4 samples between 10 and 20
We made two bins, one from 0 to 10 and another from 10 to 20. Those were specified with the
bins = [0, 10, 20] command. We then were given the counts of data within those bins. We can plot using our output from
np.histogram, or we can do both the histogram and plot using
plt.hist.
plt.hist(x, bins=[0, 10, 20]) plt.show()
There are a few problems we can see. The first is that the x-axis has ticks in weird locations. The second problem is that the bars are right on top of one another, so it's hard to tell what's going on. Let's adjust the options to fix this.
#rwidth controls how close bars are plt.hist(x, bins=[0, 10, 20], rwidth = 0.99, normed=False) #set exactly where the ticks should be plt.xticks([0, 10, 20]) plt.yticks([2, 4]) plt.xlim(0, 20) plt.ylim(0, 5) let's take a look at the Lake Huron level.
plt.hist(huron) plt.show()
What went wrong?
plt.hist(huron[:, 1]) plt.xlabel('Lake Huron Level in Feet') plt.ylabel('Number of Times Observed') plt.show()
The ticks aren't great and I personally don't like the bars touching. Let's work a little on improving the plot.
plt.style.use('seaborn') plt.hist(huron[:, 1], rwidth=0.9) plt.xlabel('Lake Huron Level in Feet') plt.ylabel('Number of Times Observed') plt.yticks([0, 5, 10, 15, 20]) plt.ylim(0,20) plt.axvline(x=np.mean(huron[:,1]),color='red', label='mean') plt.legend() plt.show()
We can see a lot from this figure. We can see the lowest and highest depths. This representation may remind you of how probability distributions look and indeed, this representation is how you can reconstruct probability mass functions. To see this, let's look at another example.
We'll look at a larger dataset that is speed of cars.
car_speed = pydataset.data('amis').values speeds = car_speed[:, 0] print(len(speeds))
8437
#now we'll use normed plt.hist(speeds, normed=True) plt.xlabel('Speed in mph') plt.ylabel('Proportion') the y-axis shows the proportion of times that a particular speed was observed. Thanks to the Law of Large Numbers, and the fact we have 8,500 samples, we know that these proportions will approach the probabilities of these intervals. For example, the probability of observing a speed between 25 and 30 mph is $\approx 0.012$. If we make our bins small enough, we'll eventually be able to assign a probability to any value and thus we'll have recreated the probability mass function!
import seaborn as sns sns.distplot(speeds, bins=range(15, 65))")
The new solid line shows us that a normal distribution would be a good fit, although the right tail is a little long. This line is generated by estimating what the histogram would look like if the bins were infinitely small.
Sometimes we'll have measured some quantity, like mass of a chicken, under multiple conditions. This is not exactly 2D, because the conditions are usually categorical data. For example, my conditions are the kind of food I've fed to my chickens. We can analyze this using a boxplot, which shows the category and quartiles in one plot.
data = pydataset.data('chickwts').values categories = np.unique(data[:,1]) print(categories)
['casein' 'horsebean' 'linseed' 'meatmeal' 'soybean' 'sunflower']
This first step is a way to find all the unique labels to find our possible categories. Now we'll use that to separate our data into a list of arrays, one for each catgory, instead of one large array.
data_as_arrays = [] #loop over categories for c in categories: #get a True/False array showing which rows had which category rows_with_category = data[:,1] == c #now slice out the rows with the category and grab column 0 (the chicken mass) data_slice = data[rows_with_category, 0] #now we need to make the data into floats, because it happened to be loaded as a string data_as_arrays.append(data_slice.astype(float))
Whew! That was a lot of work. We used a few tricks. One was that you can slice using True and False values in numpy. Let's see a smaller example:
x = np.array([4, 10, 20]) my_slice = [True, False, True] x[my_slice]
array([ 4, 20])
The other thing we did is convert the array into floating point numbers. Recall that in
numpy each array can only be one data type. The original chicken dataset had strings in it, like 'linseed', so that the whole array was strings. We thus had to convert to floats to do calculations on the chicken weights. We used the
astype() method on the array.
So we found which rows had their second column (the category column) be equal to category
c and then slice out those rows. Now we can make the boxplot.
#NOTICE WE USE Seaborn not PLT sns.boxplot(data=data_as_arrays) #Need to replace the ticks (0, through N - 1) with the names of categories plt.xticks(range(len(categories)), categories) plt.xlabel('Feed') plt.ylabel('Chicken Mass in Grams') plt.show()
The box plot shows a quite a bit of information. It should the median in as a horizontal line over the box. The box itself shows the middle two quartiles and the "whiskers" show the bottom 10th and upper 90th percentiles of the data. The points outside of the boxs are outliers.
sns.violinplot(data=data_as_arrays) #Need to replace the ticks (0, through N - 1) with the names of categories plt.xticks(range(len(categories)), categories) plt.xlabel('Feed') plt.ylabel('Chicken Mass in Grams') plt.show()
In this plot, you can see the original boxes inside the "violins". The violins show the same thing we saw above with Kernel Density Estimation and shows how spread the data is.
|
https://nbviewer.jupyter.org/github/whitead/numerical_stats/blob/master/unit_7/lectures/lecture_2.ipynb
|
CC-MAIN-2020-40
|
refinedweb
| 1,509
| 69.07
|
Are you building an application that uses MEF? Want to present to the MEF team your app and tell us about your experience?
If so, contact me.
Are you building an application that uses MEF? Want to present to the MEF team your app and tell us about your experience?
If so, contact me.
We are working in an application that is a container of differents kinds of plugins.
The main application has a network connection with periferic devices.
When the application detects a periferic the needed plugin driver is loaded.
The plugin driver has the code and the user interface to control the periferic device.
If the plugin driver don’t exist it may be downloaded by internet.
Also de main application accepts module plugins that works as mini-applications, in this way differents kinds of task may be done by each module plugin.
This plugin is much more complex than the plugin driver.
Now we have a custom plugin manager that sees files in a folder (device plugin folders) and loads every plugin driver, because is the only way to have the list of the controlled devices (one plugin file may have more than one device driver).
The problem with this is that all the plugin drivers must be loaded and the manager can´t unload the drivers tha doesnt use.
For the module plugins we use the System.Addin namespace provided by the framework.
With this library is possible to load or unload de plugins dinamically but the rigid folders structure is a not very clear solution for a dinamic installation of the plugins when the files are downloaded from internet.
We saw that MEF may be an alterntive to our needs, it seems not to be so powerful as the System.Addin but is much more friendly to use and install.
Our idea is to publish the interface to access the main aplication and create a community of designers for the module applications and for the device drivers.
Do you think that MEF will be the right tool to make an easy platform for plugin developers or is possible that we must to mantain the System.Addin for the more demmanding module applications ?.
Thanks for your comments and keep on working with this excellent code library.
Jose Maria Cuchian
teknel@ciudad.com.ar
Teknel Research
Buenos Aires – Argentina
|
https://blogs.msdn.microsoft.com/gblock/2008/12/11/are-you-using-mef-to-build-a-production-app/
|
CC-MAIN-2017-39
|
refinedweb
| 392
| 65.01
|
Created on 2008-02-16 16:27 by giovannibajo, last changed 2013-01-14 09:15 by vstinner. This issue is now closed.
Under Windows, sys.argv is created through the Windows ANSI API.
When you have a file/directory which can't be represented in the
system encoding (eg: a japanese-named file or directory on a Western
Windows), Windows will encode the filename to the system encoding using
what we call the "replace" policy, and thus sys.argv[] will contain an
entry like "c:\\foo\\??????????????.dat".
My suggestion is that:
* At the Python level, we still expose a single sys.argv[], which will
contain unicode strings. I think this exactly matches what Py3k does now.
* At the C level, I believe it involves using GetCommandLineW() and
CommandLineToArgvW() in WinMain.c, but should Py_Main/PySys_SetArgv() be
changed to also accept wchar_t** arguments? Or is it better to allow for
NULL to be passed (under Windows at least), so that the Windows
code-path in there can use GetCommandLineW()/CommandLineToArgvW() to get
the current process' arguments?
The issue is related to #1342
Since we have dropped support for older versions of Windows (9x, ME,
NT4) I like to get the Python interface to argv, env and files fixed.
I'm attaching a simple patch that seems to work under Py3k. The trick is
that Py3k already attempts (not sure how or why) to decode argv using
utf-8. So it's sufficient to setup argv as UTF8-encoded strings.
Notice that brings the output of "python ààààà" from this:
Fatal Python error: no mem for sys.argv
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-2:
invalid data
to this:
TypeError: zipimporter() argument 1 must be string without null bytes,
not str
which is expected since zipimporter_init() doesn't even know to ignore
unicode strings (let alone handle them correctly...).
I dislike the double decoding, and would prefer if sys.argv would be
created directly from the wide command line.
In addition, I think the patch is incorrect: it ignores the arguments to
Py_Main, which is a documented API function.
One solution might be to declare all these functions (Py_Main,
SetProgramName, GetArgcArgv) to operate on Py_UNICODE*, and then
convert the POSIX callers of Py_Main to use mbstowcs when going
from the command line to Py_Main. WinMain could then become
recompiled for Unicode directly, likewise Modules/python.c
mbstowcs uses LC_CTYPE. Is that correct and consistent with the way
default encoding under UNIX is handled by Py3k?
Would a Py_MainW or similar wrapper be easier on the UNIX guys? I'm just
asking, I don't have a definite idea.
> mbstowcs uses LC_CTYPE. Is that correct and consistent with the way
> default encoding under UNIX is handled by Py3k?
It's correct, but it's not consistent with the default encoding - there
isn't really any default encoding in Py3k. More specifically,
PyUnicode_FromString uses UTF-8, but not as a (changeable) default,
but as part of its API specification.
Command line arguments are in the locale's charset, so the LC_CTYPE
must be used to convert them.
> Would a Py_MainW or similar wrapper be easier on the UNIX guys? I'm just
> asking, I don't have a definite idea.
See above. The current POSIX implementation is incorrect also. It should
use the locale's encoding, but doesn't.
Here is a patch that redoes the entire argv handling, in terms of
wchar_t. As a side effect, it also changes the sys.path handling to use
wchar_t.
This is now fixed in r62178 for Py3k. For 2.6, I don't think fixing it
is feasible.
MvL's recent commit creates compiler warnings for Unicode UCS4 for the
same reason as #2388.
What warnings precisely are you seeing? I didn't see anything in the 3k
branch (not even for #2388, as PyErr_Format doesn't have the GCC format
attribute in 3k, unlike 2.x).
Martin, you are right that they are not from the same reason as that issue.
gcc -c -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk/
-fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
-I. -IInclude -I./Include -DPy_BUILD_CORE -o Modules/main.o Modules/main.c
Modules/main.c: In function 'Py_Main':
Modules/main.c:478: warning: passing argument 1 of 'Py_SetProgramName'
from incompatible pointer type
Modules/main.c: In function 'Py_Main':
Modules/main.c:478: warning: passing argument 1 of 'Py_SetProgramName'
from incompatible pointer type
The following code is being used to work around this issue for Python 2.x in Tahoe-LAFS:
# This works around <>.('utf-8')("-") or arg == "-":
break
argv = argv[1:]
if arg == '-m':
# sys.argv[0] should really be the absolute path of the module source,
# but never mind
break
if arg == '-c':
argv[0] = '-c'
break
Sorry, missed out the imports:
from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
from ctypes.wintypes import LPWSTR, LPCWSTR
Hi,
is it correct that this bug no longer appears in Python 2.7.3? I checked the changelogs of 2.7, but couldn't find anything.
Thanks!
Michael
> is it correct that this bug no longer appears in Python 2.7.3?
Martin wrote that it cannot be fixed in Python 2: "For 2.6, I don't think fixing it is feasible."
The "fix" is to upgrade your application to Python 3.
|
https://bugs.python.org/issue2128
|
CC-MAIN-2019-43
|
refinedweb
| 894
| 66.74
|
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I’m starting with Eclipse and also with the toxiclibs library. And I am a bit confused about how to work with “subclasses” that extends another class.
I’m trying to translate to Eclipse some examples of Shiffman’s book “Nature of Code”. For example “NOC_5_10_SimpleSpring.pde”. So I create a parent class (as the example sketch) that has a child-class “Particle” that “extends VerletParticle2D”.
I’m writing this subclass “Particle” like this:
import processing.core.PApplet; import toxi.geom.Vec3D; import toxi.physics.VerletParticle; public class Particle extends VerletParticle { PApplet p5; Vec3D loc; Particle( PApplet _p5, Vec3D _loc) { p5 = _p5; loc = _loc; } }
And I get this error:_ “Implicit super constructor VerletParticle() is undefined. Must explicitly invoke another constructor”_ and I don’t know exactly what this means.
In Toxiclibs library the class VerletParticle extends Vec3D, so is it possible that the new class “Particle” must have a constructor identically as a Vec3D constructor? Is it necessary? In this case, how to write in Eclipse a subclass that also extends another class?
Thank you for your help!
Answers
The Particle constructor must call super(...) where you replace the ... with the actual parameter names expected by VerletParticle.
The message just says that VerletParticle doesn't have a parameterless constructor, so you must call explicitly one of its defined constructors.
As an alternative, instead of extending VerletParticle, declare and instantiate it 1 inside your class.
Just like you did w/ PApplet & Vec3D instances. Check it out: *-:)
Shorter version extending VerletParticle: :D
@GoToLoop==
but in this type of case what is the interest of extending??? Could not be more simple && quick to write:
and add some display method with pos parameters???
@GoToLoop and @PhiLho, you help me so much!! Now I clearly see how I needed to call the "super(loc)". @GoToLoop: It´s very helpful to watch different alternatives and compare them. The best way to learn. @Akenaton: It is the way that Shiffman used to define classes (nodes, particles,...) in his book. Classes that extends VerletParticles with a display method costumized. thanks!!
|
https://forum.processing.org/two/discussion/10017/eclipse-how-to-write-subclasses-that-extends-another-class-noc5-10-particle-extends-verletparticle
|
CC-MAIN-2020-45
|
refinedweb
| 364
| 60.11
|
!
Hi in February I talked about a great Event which was happening at the Savoy in London.
This was the WTECH event , which was a Women’s Recruitment Event. Microsoft and my specifically my division, Microsoft Premier Field Engineering were taking part and were acting as Headline Sponsors for the Day.
Well if you do not already know the event is happening on the 24th of June and if you have not already registered register here.
This will be an an exciting day with a whole range of events happening throughout the day.
Premier Field Engineering are involved directly in two sessions.
12pm - “Having fun and being a great technical Professional”
This is being presented by Kate Stanton Davies Beatrice Nicolini and Andy Gitsham.
2pm - “Interacting with Technology - by text, face, voice and touch”
Jane Lewis Premier Field Engineering and Eileen Brown Microsoft Evangelist
So I look forward to seeing you there on the day. Hopefully the great British Weather is not going to stop this Event this time !!
I have been tracking this for a while and I think it is important enough to bring this to your attention as the update has now gone live June 9th and may when applied have an impact in your environment.
The original issue was brought to our attention and publicised by ourselves in this security advisory . This highlighted the following risk.
Potential Risk
A malicious user could host a system with a single-label name outside of an organization's boundary and due to DNS devolution may successfully get a Windows DNS client to connect to it as though it were internal to the organizational boundary.
There is now an update to the Microsoft Security Advisory 97188. If applied this will change the way clients resolve single-label and non-fully qualified queries via devolution. This affects the following Clients
Windows 2000,Windows XP,Windows 2003, Windows Vista, Windows 2008.
NOTE: In Windows 7 RTM and Windows 2008 R2 this is enabled by default.
You can dowload it via this kbarticle
So what is DNS Devolution ?
Devolution allows clients in child namespaces within an Active Directory Environment to access resources in the parent namespace without the need to provide the fully qualified domain name of the resource. e.g. client.a.b.com
With devolution enabled, the resolver creates new FQDNs by appending the single-label, unqualified domain name with the parent suffix of the primary DNS suffix name, and the parent of that suffix, and will keep on going until the second-level domain name.
For example,
If an application specified the name mailserver13 and the primary DNS suffix is middle.toytown.com., the resolver will try the following to resolve the following FQDNs
The way that this devolution process functions enables devolution up to and including the 2nd level Domain.
The second level Domain in the Active Directory with the Forest Root Domain “Toytown.com”, “Toytown” is the defined boundary and is the 2nd level Domain Name.
However Dependant on how you have your environment configured your estate may be exempt from DNS Devolution. For Example the following situations means that devolution is not enabled in Active Directory domains.
· If a global suffix search list is configured via group policy.
· If the append parent suffixes of the primary DNS suffix check box is selected on the DNS tab in the Advanced TCP/IP Settings dialog box of the Internet Protocol (TCP/IP) component.
So you may be asking how does this affect me ?
· DNS queries for single label and non-fully qualified names that used to work now will no longer work after the fix has been installed or and upgrade to the client Windows 7
· There may be a disparity between certain OS versions working on some OS versions compared to later OS versions.
This is explained in great depth in the following KB Article
I.
Ok I am looking for suggestions all clean please :). With the launch of Bing (Beta) in the U.K. we have caused quite flurry of responses across the I.T. press.
So I am sat here thinking it would be great to have a Bing speak competition. So if you can think of some cool clean ways of including the word Bing in your conversation then feedback to me with your suggestions.
e.g.
“ I am just going to start Binging for that”
“ Bing bang bong ….found it "!”
“ I am going to Bingle it “
“ I have been Bingled”
“ Bing is your friend”
“Bing to you hearts content”
But in all seriousness give Bing the attention it deserves and try some of the features that are available in the Beta Phase to you in the U.K.;
1. New Image Homepage – we’re using stunning high definition photography that differentiate us from the blank white page.
2. Best Match – the feature presents results for popular searches intuitively and this saves you clicks and gets you to your answer quicker
3. Ciao! Shopping Integration – we’re offering you the opportunity to shop directly from Bing using Ciao! product comparisons and user reviews (Ciao! is the shopping network Microsoft acquired in October -- read more about Ciao! here)
All the above features and more can be looked at here them
So go out today and have a Binging good day. :)
Hi I would like to let you know about a charity event I am running in to raise Money for SANDS. This is a fantastic Charity that raises money for Stillbirth and neonatal death .
I was inspired as part of my involvement with the Connected Women In Technology by Sarah's Speakes story of her precious daughter Amelie, who died from neonatal death 4 years ago. Therefore as a team we are committed to raising money for this great cause. SANDS helps bereaved parents in learning to cope with the loss of their baby / babies. They also work closely with local hospitals to improve medical and maternity services and are making a difference in tackling this difficult topic. Please if you feel you can donate a big THANK YOU for your donation - we really appreciate it, The Connecting Women Runners..
Hi ,.
Hi Everyone,
Hot of the press is the new Active Directory Disaster Recovery Guide which has been updated to reflect new features and functionality you can leverage with 2008.
Download it from Here
In particular it talks about;
1. Read Only Domain Controllers considerations for rebuild and recovery
2. Using Wbadmin
3. Global Catalog recovery considerations
4. Excellent Reference and FAQ section
This is a very welcome addition to our portfolio of white papers and technical documents in this arena. If you are in the U.K. you can hear a more detailed discussion around this topic area by Richard Diver who is presenting with myself at the next ADUG user group on June 15th.)
Have a super Weekend, and if you are in the U.K. enjoy the Bank Holiday and lets hope it does not rain too much :).
If you have received this Security Alert 971492 and you wish to verify whether your IIS 6.0 Web Servers have the Webdav Extension enabled, then please see below for a useful script which you can run across your environment. Please of course test this in a pre-production environment prior to deployment in your live production environment.
cscript adsutil.vbs get w3svc/WebSvcExtRestrictionList –s:ServerName
"0,<windir>\system32\inetsrv\httpext.dll,0,WEBDAV,WebDAV" means webdav is disabled,
"1,<windir>\system32\inetsrv\httpext.dll,0,WEBDAV,WebDAV" means webdav is enabled
Hello,
Microsoft Learning has made available some great Windows 7 Learning resources.
See below for some more information. The great thing is that they are packaged up to suit different types of Audiences. So get ahead of the wave in Windows 7 and Enjoy !)
Windows 7 Learning Portal is now live as well! This site is currently showcasing great readiness content, including 7 Silverlight Learning Snacks, free sample chapters from upcoming MS Press Books, Learning Plans, links to clinics/HOLs and more. This page can be found here -
I
interSiteTopologyFailover
CN=NTDS Site Settings,CN=SITENAME,CN=Sites,CN=Configuration
CN=NTDS Site Settings,CN=SITENAME,CN=Sites,CN=Configuration
Default -> “not set” = 120min (W2003)
Default -> “not set” = 120min (W2003)
Eventually the 120mins period will fail and then :)?:London +IS_REDUNDANT_SERVER_TOPOLOGY_ENABLED
Branch10
Current Site Options: (none)
New Site Options: IS_REDUNDANT_SERVER_TOPOLOGY_ENABLED
C:\>repadmin /siteoptions /site:London +IS_TOPL_DETECT_STALE_DISABLED.
Hi.
Hi,
With the release of Windows 7 Release Candidate the back end of last week. Please find below a list of invaluable resources that Technet has made available.
Download Windows 7 Release Candidate now
TalkingAboutWindows.com—where IT pros can hear the “back stories” from the leading engineers for Windows 7, discussing how and why they made the critical decisions and tradeoffs they did; along with videos of IT pros discussing Windows 7 in their environment
Hope you find the above useful and enjoy
Trademarks |
Privacy Statement
|
http://blogs.technet.com/janelewis/
|
crawl-002
|
refinedweb
| 1,490
| 53
|
Our Vision for Rust and WebAssembly.
Are you interested in helping us make these ideals into reality? Join the Rust and WebAssembly domain working group!
Why Focus on Performance-Sensitive Code?
In the most performance-sensitive contexts, JavaScript hinders rather than helps. Its dynamic type system and non-deterministic garbage collection pauses get in the way. Seemingly small code changes can result in drastic performance regressions if you accidentally wander off the JIT’s happy path.
On the other hand, Rust gives programmers low-level control and reliable performance. It is free from the non-deterministic garbage collection pauses. Programmers have control over indirection, monomorphization, and memory layout.
With Rust, we don’t need to be performance gurus who are intimately familiar with the inner workings of each JavaScript implementation’s JIT. We can have speed without wizardry.
Do Not Rewrite — Integrate
Rust compiled to WebAssembly doesn’t have a runtime. This results in small
.wasm binary sizes that are proportional to the amount of Rust code that is
being compiled to WebAssembly. Binary size is of huge importance since the
.wasm must be downloaded over the network. The proportionality means you only
pay (in code size) for what you use. In turn, that means it is feasible for
existing JavaScript code bases to incrementally and partially adopt Rust.
Keep the code that already works: we can port only our most performance-sensitive JavaScript functions to Rust and gain immediate benefits.
Keep Your Workflow
If you are a JavaScript hacker and want to use a library that is written in Rust
and WebAssembly, you shouldn’t have to change your workflow at all. We can
publish
.wasm packages to npm, and you can depend on them in
package.json
just like you normally would any other JavaScript library. They can be imported
as ECMAScript modules, CommonJS-style
requires, or added as a new object
property to the JavaScript global. Bundlers will understand Rust and
WebAssembly just as well as they understand JavaScript.
If you are a Rust hacker and want to compile your crate to
.wasm and share it
on npm, you shouldn’t have to change your workflow either. In fact, you
shouldn’t even need to install npm, Node.js, and a whole JavaScript development
environment.
wasm-pack will compile, optimize, and generate JavaScript
bindings for your crate. And then it will publish it to npm for you too!
Current Status
This section provides a snapshot of our current ecosystem, the tools that are available right now, and how this compares to the vision described above.
The Rust and WebAssembly Book
Everything we build is for naught if people can’t learn how to use it themselves. So we are writing The Rust and WebAssembly Book.
Right now, it already has a lot of great content:
- Getting up and running
- Designing and implementing a non-trivial example (the Game of Life) that integrates Rust and JavaScript
- Tips for debugging, time profiling, and code size profiling
- How to publish to npm with
wasm-pack
But it doesn’t have a lot of continuity. It feels like a collection of appendices and random tutorials. We will have a follow up blog post detailing its specific needs, and how to help if you’re interested.
wasm-bindgen
wasm-bindgen facilitates communication between Rust and
JavaScript. You can import JavaScript things into Rust, and
export Rust things to JavaScript. It allows you to send rich types like strings
and structs between wasm and JavaScript, rather than only the simple integers
and floats defined by the WebAssembly standard.
Here is “Hello, World!” between Rust and JavaScript with
wasm-bindgen. First,
we import the
alert function into Rust and export the
greet function to
JavaScript:
extern crate wasm_bindgen; use wasm_bindgen::prelude::*; #[wasm_bindgen] extern { fn alert(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("Hello, {}!", name)); }
Then, we import the wasm as an ECMAScript module in JavaScript, and call the
greet function:
import { greet } from "./hello_world"; greet("World!");
How does
wasm-bindgen work? Simplifying a bit, it is a procedural macro that
takes in Rust source code annotated with
#[wasm_bindgen] attributes,
constructs an abstract syntax tree (AST), and then it emits two artifacts:
Rust bindings that import JavaScript things and export Rust things.
JavaScript bindings that expose a nice interface to Rust-exported things to other JavaScript code and provide the Rust’s desired imports.
wasm-bindgen’s approach to JavaScript binding allows you to pay only for the
imports that you use. Just because you imported the
window.alert function, you
don’t end up with glue code for
window.document.
The big downside is that, right now, you always have to declare imports yourself. There are common imports for JavaScript functions and types and the Web platform APIs that will undoubtedly be repeated by many people many times over. Importing these by-hand is both boring and mechanical. We have a plan for fixing this, but you’ll have to wait for a follow up blog post to learn more.
wasm-pack
wasm-pack seeks to be a one-stop shop for building, optimizing, and
publishing Rust-generated WebAssembly that you would like to interoperate with
JavaScript, in the browser, or with Node.js.
wasm-pack helps you
build and publish Rust-generated WebAssembly to the npm registry to be used
alongside any other JavaScript package in workflows that you already use, such
as a bundler like webpack or a service like greenkeeper.
Drawing by Lin Clark in Making WebAssembly better for Rust & for all languages
The intention is that if you are a Rust developer and want to publish a crate
compiled to wasm on npm,
wasm-pack will
- compile the crate to WebAssembly with the
wasm32-unknown-unknowntarget,
- run the
wasm-bindgenCLI tool on the
.wasmto generate its JavaScript interface,
- run any other post-build tools such as
wasm-snipand
wasm-opt,
- collate any and all npm dependencies your crate and/or its JavaScript bindings might have,
- and publish the resulting package on npm.
All without you, the Rust developer, needing to have a JavaScript toolchain up and running.
Right now, steps 1, 2, and 5 are in place, but you still need to have
npm
installed locally. There are also some more things planned for
wasm-pack, and
our story for orchestrating builds, dependencies, and publishing coming down the
pipe, but you’ll have to wait for the dedicated follow up blog post.
Wait, There’s More!
Twiggy is a code size profiler for
.wasmbinaries. It helps you answer questions like “why did this function even end up in here – who calls it?” and “how much space would be saved if I stopped using this function, removed it, and removed all the functions that become dead code after its removal?”
wee_allocis a tiny allocator designed for WebAssembly that has a (pre compression) code size footprint of only a single kilobyte. It is geared towards code that makes a handful of initial dynamically sized allocations, and then performs its heavy lifting without any further allocations. This scenario requires some allocator to exist, but we are more than happy to trade allocation performance for small code size.
The
console_error_panic_hookcrate provides a panic hook for wasm that logs panics to the developer console via the
console.errorfunction. No more opaque “RuntimeError: unreachable executed” messages! Get the proper assertion failure message or index out-of-bounds information you expect. It makes debugging panics a whole lot easier.
The
wasm-sniptool lets you forcibly replace a function’s body with a single
unreachableinstruction. particularly helpful for removing Rust’s panicking and formatting infrastructure when you intend to ship small
.wasmbinaries with
panic=abort.
As mentioned throughout this post, we’ll be following up with more blog posts detailing specific goals we have for the Rust 2018 edition and how you can help. In the meantime, don’t hesitate to join the Rust and WebAssembly domain working group and help build the future of Rust and WebAssembly now!
|
https://rustwasm.github.io/2018/06/25/vision-for-rust-and-wasm.html
|
CC-MAIN-2019-09
|
refinedweb
| 1,334
| 63.49
|
Tell us what you think of the site.
Hi,
I installed MoBu 2011 Tryout but I’m unable to get Python working! At openening the script editor window, I get error messages: ...ImportError: No module named pyfbsdk… and ...ImportError: No module named pyfbsdk_additions…
I tried it on two computers: Win7 64 and Win7 32
Anyone was able to use Python in MoBu 2011?
Thanks in advance
Of course. Works as intended.
You must have some Installation or OS Problems here…
It seems it had a conflict with the Python and PyQt installed on my computers, removed both and replaced with Python 2.6.4 and PyQt 4.5.2 and everything is working.
I have the same problem:
Traceback (most recent call last):
File "<MotionBuilder>", line 1, in <module>ImportError: No module named pyfbsdk_additions
Traceback (most recent call last):
File "C:/Users/XXXXX/AppData/Local/Autodesk/MB2011x64/config/Python/pythonidelib.py", line 1, in <module>
import pyfbsdk
ImportError: No module named pyfbsdk
Opening Python Editor and doing import pyfbsdk also gives no module named. This is on a few weeks old install of Win7 64bits. Just tried installing Python 2.6.4 but it didn’t chang anything. I will try to install PyQt, but I doubt it might make a difference.
I can’t find anything on the net related to this error. Any ideas? It’s kinda urgent.
Edit: reinstalling MoBu2011 did the trick. Don’t know if having Python and PyQt already installed made any difference though…
That’s a problem with your python path. Search for how to add those files/directories to your python path and you should be able to solve it that way rather than resorting to a reinstall.
tallystick 27 November 2010 08:39 PM
That’s a problem with your python path. Search for how to add those files/directories to your python path and you should be able to solve it that way rather than resorting to a reinstall.
I don’t think so.
I applied the hotfix for the 64-bit version of MB 2011 and I am experiencing the same issue with being unable to run scripts (from pyfbsdk import * doesn’t work).
I set the PYTHON_PATH environment variable to point to the directory containing pyfbsdk and I still get the same error.
I’ve contacted Autodesk support but still no word.
Anyone else?
Did you add it to your .pth or from the python shell? Adding it from the python shell only works for that session.
|
http://www.the-area.com/forum/autodesk-motionbuilder/python/anyone-successful-in-using-python-in-mobu-2011/
|
crawl-003
|
refinedweb
| 419
| 75.3
|
Serverless Stack
Serverless Stack (SST) is a framework that makes it easy to build serverless apps. SST supports JavaScript, TypeScript, Python, Golang, and C#.
Monitor a function
To monitor a specific Lambda function, add the
lumigo:auto-trace tag and set it to
true. Add the following to your CDK code.
import * as cdk from "@aws-cdk/core"; cdk.Tags.of(myfunc).add("lumigo:auto-trace", "true");
Monitor all functions
To monitor all the functions in a stack, you can use the Stack construct's
[getAllFunctions]() method and do the following at the bottom of your stack definition.
import * as cdk from "@aws-cdk/core"; this.getAllFunctions().forEach(fn => cdk.Tags.of(fn).add("lumigo:auto-trace", "true") );
For more info, check out the SST docs.
Updated 10 months ago
Did this page help you?
|
https://docs.lumigo.io/docs/serverless-stack
|
CC-MAIN-2022-40
|
refinedweb
| 135
| 58.99
|
What is Heuristic Search – Techniques & Hill Climbing in AI
Keeping you updated with latest technology trends, Join DataFlair on Telegram
1. Objective – Heuristic Search
In this Python AI tutorial, we will discuss the rudiments of Heuristic Search, which is an integral part of Artificial Intelligence. We will talk about different techniques like Constraint Satisfaction Problems, Hill Climbing, and Simulated Annealing. Also, we will implement CSP in Python.
So, let’s begin Heuristic Search in AI Tutorial.
First, let’s revise the Artificial Intelligence Tutorial
2. What is a Heuristic Search?
A Heuristic is a technique to solve a problem faster than classic methods, or to find an approximate solution when classic methods cannot. This is a kind of a shortcut as we often trade one of optimality, completeness, accuracy, or precision for speed..
You must take a look at NLP Tutorial
So why do we need heuristics?. We use this in AI because we can put it to use in situations where we can’t find known algorithms.
We can say Heuristic Techniques are weak methods because they are vulnerable to combinatorial explosion.
3. Heuristic Search Techniques in Artificial Intelligence
Briefly, we can taxonomize such techniques of Heuristic into two categories:
a. Direct Heuristic Search Techniques in AI
Other names for these are Blind Search, Uninformed Search, and Blind Control Strategy. These aren’t always possible since they demand much time or memory. They search the entire state space for a solution and use an arbitrary ordering of operations. Examples of these are Breadth First Search (BFS) and Depth First Search (DFS).
Do you know about NLTK Python
b. Weak Heuristic Search Techniques in AI
Other names for these are Informed Search, Heuristic Search, and Heuristic Control Strategy. These are effective if applied correctly to the right types of tasks and usually demand domain-specific information. We need this extra information to compute preference among child nodes to explore and expand. Each node has a heuristic function associated with it. Examples are Best First Search (BFS) and A*.
Before we move on to describe certain techniques, let’s first take a look at the ones we generally observe. Below, we name a few.
- Best-First Search
- A* Search
- Bidirectional Search
- Tabu Search
- Beam Search
- Simulated Annealing
- Hill Climbing
- Constraint Satisfaction Problems
4. Hill Climbing in Artifical Intelligence
First, let’s talk about Hill Climbing in Artifical Intelligence. This is a heuristic for optimizing problems mathematically. We need to choose values from the input to maximize or minimize a real function. It is okay if the solution isn’t the global optimal maximum.
Let’s discuss Python Speech Recognition
One such example of Hill Climbing will be the widely discussed Travelling Salesman Problem- one where we must minimize the distance he travels.
a. Features of Hill Climbing in AI
Let’s discuss some of the features of this algorithm (Hill Climbing):
- It is a variant of the generate-and-test algorithm
- It makes use of the greedy approach
This means it keeps generating possible solutions until it finds the expected solution, and moves only in the direction which optimizes the cost function for it.
b. Types of Hill Climbing in AI
- Simple Hill Climbing- This examines one neighboring node at a time and selects the first one that optimizes the current cost to be the next node.
- Steepest Ascent Hill Climbing- This examines all neighboring nodes and selects the one closest to the solution state.
- Stochastic Hill Climbing- This selects a neighboring node at random and decides whether to move to it or examine another.
Let’s revise Python Unit testing
Let’s take a look at the algorithm for simple hill climbing.
- Evaluate initial state- if goal state, stop and return success. Else, make initial state current.
- Loop until the solution reached or until no new operators left to apply to current state:
a. Select new operator to apply to the current producing new state.
b. Evaluate new state:
- If a goal state, stop and return success.
- If better than the current state, make it current state, proceed.
- Even if not better than the current state, continue until the solution reached.
- Exit.
c. Problems with Hill Climbing in AI
We usually run into one of three issues-
- Local Maximum- All neighboring states have values worse than the current. The greedy approach means we won’t be moving to a worse state. This terminates the process even though there may have been a better solution. As a workaround, we use backtracking.
- Plateau- All neighbors to it have the same value. This makes it impossible to choose a direction. To avoid this, we randomly make a big jump.
- Ridge- At a ridge, movement in all possible directions is downward. This makes it look like a peak and terminates the process. To avoid this, we may use two or more rules before testing.
Do you know about Python Assert Statements
5. Constraint Satisfaction Problems (CSP)
A constraint is nothing but a limitation or a restriction. Working with AI, we may need to satisfy some constraints to solve problems. Let’s try solving a problem this way, shall we?
Let’s talk of a magic square. This is a sequence of numbers- usually integers- arranged in a square grid. The numbers in each row, each column, and each diagonal all add up to a constant which we call the Magic Constant. Let’s implement this with Python.
def magic_square(matrix): size=len(matrix[0]) sum_list=[] for col in range(size): #Vertical sum sum_list.append(sum(row[col] for row in matrix)) sum_list.extend([sum(lines) for lines in matrix])#Horizontal sum result1=0 for i in range(0,size): result1+=matrix[i][i] sum_list.append(result1) result2=0 for i in range(size-1,-1,-1): result2+=matrix[i][i] sum_list.append(result2) if len(set(sum_list))>1: return False return True
Now let’s run this code.
>>> magic_square([[1,2,3],[4,5,6],[7,8,9]])
False
This is not a magic square. The numbers in the rows/columns/diagonals do not add up to the same value. Let’s try another list of lists.
Have a look at AI Neural Networks
>>> magic_square([[2,7,6],[9,5,1],[4,3,8]])
True
Since the values add up to the constant 15 in all directions, surely, this is a magic square!
6. Simulated Annealing Heuristic Search
In metallurgy, when we slow-cool metals to pull them down to a state of low energy gives them exemplary amounts of strength. We call this annealing. While high temperatures observe much random movement, low temperatures notice little randomness.
In AI, we take a cue from this to produce something called simulated annealing. This is a way of optimization where we begin with a random search at a high temperature and reduce the temperature slowly. Eventually, as the temperature approaches zero, the search becomes pure greedy descent. At each step, this processes randomly selects a variable and a value. It accepts the assignment only when it is an improvement or doesn’t lead to more conflict. If not, it checks if the temperature is much worse than the current assignment to accept the assignment with some probability.
Do you know about Python ternary Operators
An annealing schedule defines how the temperature drops as the search progress. A very common schedule is geometric cooling. If we begin with a temperature of 10 and multiply by 0.97 after every step, then after 100 steps, we’re left with a temperature of 0.48.
7. Best-First Search (BFS) Heuristic Search
Often dubbed BFS, Best First Search is an informed search that uses an evaluation function to decide which adjacent is the most promising before it can continue to explore. Breadth- and Depth- First Searches blindly explore paths without keeping a cost function in mind. Things aren’t the same with BFS, though. Here, we use a priority queue to store node costs. Let’s understand BFS Heuristic Search through pseudocode.
- Define list OPEN with single node s– the start node.
- IF list is empty, return failure.
- Remove node n (node with best score) from list, move it to list CLOSED.
- Expand node n.
- IF any successor to n is the goal node, return success and trace path from goal node to s to return the solution.
- FOR each successor node:
- Apply evaluation function f.
- IF the node isn’t in either list, add it to list OPEN.
- Loop to step 2.
Let’s learn about Python Slice
So, this was all in Heuristic Search Techniques in AI. Hope you like our explanation.
8. Conclusion – Heuristic Search Techniques
Hence, in this Python AI tutorial, we discussed the Heuristic Search in AI. While we named a few techniques that fall under that, we also discussed, in brief, those like BFS, Hill Climbing, Simulated Annealing, and CSP. We also implemented CSP in Python. Still, if you have any query in Heuristic Search Techniques, feel free to ask in the comment tab.
See also –
Copy in Python
For reference
How to solve shuffled frog leaping algorithm (SFLA) through python ,i am asking about implementation of coding SFLA in python?
explanation was too good
Why the hell you people can’t let the reader concentrate?, popping up completely out of the subject topics in between!! WHEN You can give them at the bottom of the page!
|
https://data-flair.training/blogs/heuristic-search-ai/
|
CC-MAIN-2020-34
|
refinedweb
| 1,564
| 65.83
|
Script that will import .p12 cert into the Secure Settings area of the java store
I have tried using the keytool command, but that will only allow me to import the key into the cacerts area. The cert needs to be in the Secure Sites area of the Java store. Can someone assist with a script for the task below?
Environment
Java 1.6.65 - (highest support version by the vendor)
Java install location - program files (x86)
Windows 7 - x64
Steps to manually import the cert:
1. Copy and paste file to your desktop. Change the extension from rename to p12 (once import you can delete it)
2. Go to C:\Program Files (x86)\Java\jre6\bin
3. Open file javacpl.exe
4. In Java Control Panel
a. Click Security tab > Certificates
b. Change Certificate Type to Secure Site
c. If blank, click Import
d. Click file ‘name of cert’ from Desktop and click Open
<?xml:namespace prefix = o
There are no answers at this time
|
http://www.itninja.com/question/script-that-will-import-p12-cert-into-the-secure-settings-area-of-the-java-store
|
CC-MAIN-2017-51
|
refinedweb
| 166
| 78.35
|
NAME¶
gset_char_up_vec (Set character up vector) - specifies the angle at which subsequent text is to be drawn with gtext.
SYNOPSIS¶
#include <ncarg/gks.h>
void gset_char_up_vec(const Gvec *char_up_vec);
DESCRIPTION¶
- char_up_vec.delta_x
- (Gfloat, Input) - Gives the X (horizontal) world coordinate of a vector.
- char_up_vec.delta_y
- (Gfloat, Input) - Gives the Y (vertical) world coordinate of a vector.
USAGE¶
The coordinates (char_up_vec.delta_x, char_up_vec.delta_y) relative to the point (0.,0.) establish a vector direction. This direction specifies the up direction of individual characters. This direction also specifies the orientation of a text string in that the characters in a string are placed along a line perpendicular to the character up vector. By default the character up vector is (0.,1.) so that characters are drawn in their normal horizontal orientation. The magnitude of the up vector is not used so that (0.,23.) is the same as (0.,1.).
EXAMPLES¶
char_up_vec.delta_x = -1.
char_up_vec.delta_y = 0.
gset_char_up_vec(&char_up_vec);
would specify the character up vector as (-1.,0.) and subsequent text written with gtext would be rotated 90 degrees from normal and would be appropriate for a Y-axis label.
would specify the character up vector as (1.,1.) and subsequent text written with gtext would be rotated -45 degress from normal.would specify the character up vector as (1.,1.) and subsequent text written with gtext would be rotated -45 degress from normal.
char_up_vec.delta_x = 1.
char_up_vec.delta_y = 1..
gset_char_up_vec(&char_up_vec);
ACCESS¶
To use the GKS C-binding routines, load the ncarg_gks and ncarg_c libraries.
SEE ALSO¶
Online: gtext(3NCARG), gset_text_path(3NCARG), gset_text_align(3NCARG), gset_text_font_prec(3NCARG), gset_char_ht(3NCARG), gset_char_spacechar.
|
https://manpages.debian.org/unstable/libncarg-dev/gset_char_up_vec.3NCARG.en.html
|
CC-MAIN-2022-40
|
refinedweb
| 268
| 60.41
|
Learning Haskell by Type (Signatures)
Getting a better understand of Haskell has always been on my list. My typical Tooling for learning another programming language is not so effective with Haskell, because in contrast to say - Ruby[1] - learning Haskell requires me to learn new concepts. On the other hand, Haskell offers some unique features, which make learning it surprisingly easy again. Of these tools, type signatures have quickly become invaluable. Embrace them or perish, I might say, for if you don’t learn to utilize them, everything people typically criticize about the Haskell ecosystem (sparse documentation, obscure love for operators, being completely lost in abstraction) will hit you hard. On the other hand, if you learn to read the Haskell type (signatures), you often know things from quick, formal considerations early on, without having even started to think about the semantics of that piece of code.
Much can be written about type signatures but in this blog post, I try to focus on type signatures of Haskell’s most common abstractions, and point out some patterns and parallels in them (and as it turns out, these are not only parallels in the type signatures, but in semantics too.)
With all the talk about Monads, a lot of introductory material kind of leaves out Functors, Applicative Functors und the merrits of Applicative Functor style. If you have so far diligently learned some Haskell, but were put off by Haskell’s liberal use of weird operators, applicative Functor style will show you how operators can be used for great benefit.
The following compilation is of things I rather understood recently, so bear in mind, that I might have missed one or the other connection.
Overview
The purpose of this blog post is to explain some properties of typical Haskell type classes by looking at the type signatures (see On type signatures) of their member functions. So first of all, the objective is to have these signatures ready for reading. The following signatures were infered by looking for the type signatures interactively in ghc’s ghci prompt. One can also look into the source, though, they should tell you the same.
Normal Functions
We’ll start having a look at normal function applications.
($) :: (a -> b) -> a -> b (.) :: (b -> c) -> (a -> b) -> a -> c
The . operator for function composition allows us in Haskell to write
(f . g) x instead of
f (g x).
$ is a low-priority operator which represents the function
application, so instead of
f x, we can also write
f $ x. It is
mostly used to avoid parentheses in code (to write
f . g $ x for the
above example), but in this blog post, I will use it to represent
function application in general.
Functor
In a functional, statically typed programming language without the
mathematical obsession of the haskell community, a Functor might have
been named
Mappable. Haskell took the name Functor[2] from a mathematical concept
in category theory
(<$>) :: Functor f => (a -> b) -> f a -> f b
Depending on personal preference and style, there is also
fmap, which
is just another name for
(<$>).
Applicative
An Applicative is a special kind of Functor, that extends Functors. It
features the operator
<*> for sequencing computations (combining their
results), and
pure, a function to bring values into an applicative
context.
pure :: Applicative f => a -> f a (<*>) :: Applicative f => f (a -> b) -> f a -> f b -- sequential application
While
pure and
<*> constitute a minimal implementation, typically
the operators
<* and
> are also used, which discard some
computation results instead of combining them like
<>, this is very
handy when writing
megaparsec parsers. My mnemonic to not confuse them: the angle bracket
points to values the value not discarded:
(*>) :: Applicative f => f a -> f b -> f b -- discard the first value (<*) :: Applicative f => f a -> f b -> f a -- discard the second value
Just by looking at the type signature, you can infer that
(*>) keeps
its right-hand-side value and discards the one to the left, because
f a → f b → f b
Monad
Monads are characterized by the bind operator
>>= and the
return
operator.
>>= passes a “monadic” value
m a to a monadic function
(a → m b),
return puts a value into a monadic container.
Monads are also Applicatives and Functors, i.e. they also implement
<$>,
<*>, etc.
-- Sequentially compose two actions, passing any value produced -- by the first as an argument to the second (>>=) :: Monad m => m a -> (a -> m b) -> m b return :: Monad m => a -> m a (>>) :: Monad m => m a -> m b -> m b -- discards value of first monad (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c) -- kleisli composition
Note: Trying to explain a Monad by allegories and metaphors is in my experience often futile (and a common pitfall for Haskell learners). Way more effective is to gain some basic understanding on the type level and imitate Monad usage with various examples.
Operations that Apply
If you think about it, the
<*> operation of the Applicative
(sequential application) and the function application operator
$ have
a pretty similar signature, this is also true for
<$>, the map
operation
($) :: (a -> b) -> a -> b (<$>) :: Functor f => (a -> b) -> f a -> f b (<*>) :: Applicative f => f (a -> b) -> f a -> f b
The first operand of those operators all map from one type
a to the
other
b (in the case of
<*> that
a → b is hidden in an
applicative). The second operand is the argument to the application. In
the case of normal function application this is plainly the function
argument, with the Functor (“Mappable”) it is a Functor, in the case
of the applicative it is an applicative.
The result of the operation is either of type
b, Functor of
b or
applicative of
b.
One instance of Functor and Applicative (an Applicative is always a
Functor) is the list
[] type. The following ghci interactive session
will demonstrate the three applying operators:
> (+10) $ 1 11 > (+10) <$> [1,2,3] [11,12,13] > (+) <$> [1,2,3] <*> [10, 20, 30] [11,21,31,12,22,32,13,23,33]
In Haskell, the list type implements
Monad, which means it also is an
Applicative and a
Functor. Treating the list as a Functor, we can
apply the function that increments by 10 to each element, and treating
the list as an applicative, we can sequentially join two lists by adding
their elements (building the sum of the cartesian product of their
combinations).
Let’s investigate the type properties of that last statement that used
the
f <$> arg1 <*> arg2 pattern (we call this “applicative style”):
> let mapAndApply f arg1 arg2 = f <$> arg1 <*> arg2 > :t mapAndApply mapAndApply :: Applicative f => (a1 -> a -> b) -> f a1 -> f a -> f b
Thus, Haskell infers types for
f :: (a1 → a → b), for
the second argument
arg1 :: f a1
and
arg2 :: f b.
Lifting
This combination is a common function, called
liftA2
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
We can read
liftA2 (+) as “lift the addition to an applicative
action”. After lifting, he have an addition for all applicatives.
> let addApplicative = liftA2 (+) addApplicative :: (Num c, Applicative f) => f c -> f c -> f c
To prove the point, we can experiment with this using various applicatives in the Haskell’s std. library
> addApplicative (Just 1) Nothing Nothing > addApplicative (Just 1) (Just 2) Just 3 > addApplicative Nothing (Just 2) Nothing > addApplicative Nothing Nothing Nothing > addApplicative Nothing Nothing Nothing > addApplicative (Right 5) (Right 6) Right 11 > addApplicative (Right 5) (Left "a") Left "a" > addApplicative [1,2,3] [10,20,30] [11,21,31,12,22,32,13,23,33] > addApplicative [1,2,3] [] []
Using a lifted function gives you the impression of working with
ordinary functions, the symmetry between
(f $ x) y and
f <$> x <*> y
makes this possible.
Applicative Style
The same evaluations can also be written in applicative style.
> (+) <$> Just 1 <*> Nothing Nothing > (+) <$> Just 1 <*> Just 2 Just 3 > (+) <$> Nothing <*> Just 2 Nothing > (+) <$> Nothing <*> Nothing Nothing
Using applicative style emphasizes the resemblance of function
application with arguments
f $ x y and applicative
f <$> x <*> y,
without requiring pre-registered
liftAx functions (x representing the
arity).
Example: Generating a stream of unique labels
This will be a “more real-world” example that applicative style. Suppose we need to generate labels in code, for example while performing operations on an abstract syntax tree. Each label needs to be unique, and we need labels in various functions. Since we use Haskell and pure-functions, we cannot just mutate some counter-variable.
import Control.Monad.State import Control.Applicative type LabelM = State Int increment :: LabelM String increment = state $ \i -> let j = i + 1 in ("$" ++ show j, j) labels :: Bool -> LabelM [(String, String)] labels discard = f <$> twoLabels <*> twoLabels <*> twoLabels where f a b c = if discard then [a, c] else [a, b, c] -- (,) <- is an operator creating a tuple twoLabels :: LabelM (String, String) twoLabels = (,) <$> increment <*> increment
When executed, this program will prompt you to enter either
True or
False, and then it will print out results, depending on the input.
Either
[("$1","$2"), ("$5","$6")] or
[("$1","$2"),("$3","$4"),("$5","$6")]. Notice how even if the second
label-pair is discarded after all, the counter is still incremented. The
entry point is the evaluation of
evalState in
main. Here, we
initialize the state monad’s state with 0 and evaluate the monadic
test function. The state is managed by the state monad
LabelM = State Int, which directly tells us that our state consists of
an integer variable. Finally we have
increment, which increments, that
internal state and returns a label, as well as
twoLabels, which
generates a pair of such labels (by lifting
increment). Note that both
increment and
twoLabels are of type
LabelM _, once
LabelM String
and
LabelM (String, String).
We use
twoLabels in the
labels function, where we use applicative
style to obtain the unique labels and either return them all, or throw
away some (see [intuition]). I condensed this use case from
abstract syntax tree (AST) rewriting code, and if it wouldn’t blow up
the example code, I would show code here, that introduced labels
depending on the AST input to the program.
Solving this issue with label has some benfits. First of all, it makes
the state explicit in the type signatures, which gives you the guarantee
that if you are not using the
LabelM type, you are not touching that
state. Then, the state is handled just like any other value in Haskell –
immutable.
evalState is the bottleneck (in a good sense), that allows
us to evaluate our stateful code and fetch it over in the
LabelM-free world.
Composition Patterns
Another interesting pair of operations with a similar signature are the
operators
(.) and
(⇐<).
(.) :: (b -> c) -> (a -> b) -> (a -> c) (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
The correspondence here is between functions of type
(b → c) and
monadic functions of signature
Monad m ⇒ (b → m c). I.e. the
signatures of
(.) and
(⇐<) have almost the same pattern.
We know this
Monad m ⇒ (b → m c) signatures from the bind-operator’s
second operand:
(>>=) :: Monad m => m a -> (a -> m b) -> m b
By joining two
M a >>= \x → M b operations, I aim to infer
(⇐<),
we’ll use the
Maybe monad and I’ll write the signatures of the lambda
functions to the right.
printLengthPrint :: Int -> Maybe Double printLengthPrint = \w -> Just (show w) -- :: Int -> Maybe String >>= \x -> Just (length x) -- :: String -> Maybe Int >>= \y -> Just (2.0 ^^ y) -- :: Int -> Maybe Double
We can kind of identify the signature of
(⇐<) just by looking at
this. Now spell out the lambda functions in point-free style (I called
them
f,g,h) and we can implement the
printLengthPrint function by
Kleisli’s composition
f :: Int -> Maybe String f = Just . show g :: String -> Maybe Int g = Just . length h :: Int -> Maybe Double h = Just . (2.0 ^^) plp1 = h <=< g <=< f plp2 = f >=> g >=> h
To sum it up: Functional programming is often defined as programming by function composition and application. Monads are a functional concepts and we can see that monads compose in a very similar way. This underlines the fact that Monads are indeed a functional concept (and not – like sometimes stated – imperative programming in sheep’s clothing).
Example
So far this blog post was a bit abstract, looking at type signatures and type signatures. So now we’ll see an example: A parser for simple arithmetic expressions and see when we can use the applicative style shown above, and when not.
The first parser is parsing
Reverse Polish
Notation style expressions, in RPN, the infix expression we are used to
1 + 2 * 3 would be written as
+ 1 * 2 3, it is especially simple to
parse in contrast to the more common infix notation. We use megaparsec
here.
First of all we need to import our parser library and the Identity Functor.
import qualified Text.Megaparsec.Lexer as L import Text.Megaparsec import Text.Megaparsec.String
Now we define an algebraic datatype representing our computation:
Term. A term can either be an addition, a subtraction, a
multiplication, a division, or an integer value here.
data Term = Add Term Term | Sub Term Term | Mul Term Term | Div Term Term | Val Integer deriving (Show, Eq)
Our parsing strategy is to always consume trailing whitespaces with every parsed term.
trimTrailing = L.lexeme space op :: String -> Parser String op = trimTrailing . string
Define multiplication, division, addition and subtraction expressions in
applicative style (the next 5 expressions all have the type
Parser Term)
mult = Add <$> (op "+" *> term) <*> term divi = Div <$> (op "/" *> term) <*> term addi = Mul <$> (op "*" *> term) <*> term subt = Sub <$> (op "-" *> term) <*> term intval = Val <$> trimTrailing L.integer
Now all left to do is define a parser for our expression as an alternative of all arithmetic operations:
term :: Parser Term term = mult <|> divi <|> addi <|> subt <|> intval
Infix Parsing
If you are interested in infix parsing: it is algorithmically more
complex. I.e. in infix parsing when the parser arrives at a number, it
cannot easily know whether this number can stand alone, or whether it
belongs to a binary operation with the operator to the right (in
3 * 4 + 5 the parser would have to find out that 3 is part of a
multiplication expression, and then find out that the multiplication is
part of an addition expression later on).
Luckily the megaparsec library has utilities to make parsing infix notation easier. I included a snippet for completeness.
parens = between (symbol "(") (symbol ")") where symbol = L.symbol space infixExpr = makeExprParser infixTerm table infixTerm = parens infixExpr <|> intval table = [ [ InfixL (op "*" >> return Mul) , InfixL (op "/" >> return Div)] , [ InfixL (op "+" >> return Add) , InfixL (op "-" >> return Sub)]]
We can see at least here, that for this kind of a problem applicatives are not enough and we need Monads.
Resources
For more detail on Haskell’s types see the Typeclassopedia.
To familiarize yourself with Functors and Applicatives, it is really great to write parsers with Megaparsec.
What I wish I knew when learning Haskell by Stephen Diehl is also a great source.
Footnotes
Tooling
Some notes on tooling
In my experience, I learned the best with Haskell, when I used appropriate tooling. They accelerate learning Haskell so much.
hlint is your friend with invaluable information. It notifies you when you use redundant brackets and this feedback will familiarize you with operator precedence much quicker. Like any linter, I suppose that hlint’s value is probably at its peak when used by beginners and I expect it will be less valuable to me over time. Nevertheless I don’t want to go without it right now.
I use neovim with the plugins :
Plug 'benekastah/neomake' Plug 'dag/vim2hs' Plug 'bitc/vim-hdevtools'
Pointfree is another tool, that I use (curiously), it transforms
your code to point-free style. I often use it when I feel that a
line of code could possibly be written in point free style, check it
out and revert back if I feel normal-style Haskell is better. This
has taught me some things I probably wouldn’t have discovered for a
long time, for example that
(,) and
(+3) exist, etc.
On type signatures
Type signatures can be obtained by running ghci and asking it for types
Prelude> import Control.Monad > :t (>>=) (>>=) :: Monad m => m a -> (a -> m b) -> m b > :t (>>) (>>) :: Monad m => m a -> m b -> m b > :t return return :: Monad m => a -> m a > :t fail fail :: Monad m => String -> m a > :t (<$>) (<$>) :: Functor f => (a -> b) -> f a -> f b > :t (<$) (<$) :: Functor f => a -> f b -> f a > :t pure pure :: Applicative f => a -> f a > :t (<*>) (<*>) :: Applicative f => f (a -> b) -> f a -> f b > :t (*>) (*>) :: Applicative f => f a -> f b -> f b > :t (<*) (<*) :: Applicative f => f a -> f b -> f a > :t ($) ($) :: (a -> b) -> a -> b > :t fmap fmap :: Functor f => (a -> b) -> f a -> f b > :t (<=<) (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c > :t (.) (.) :: (b -> c) -> (a -> b) -> a -> c
intuition
My first intuition here was to use monadic functionality (
>>=),
yet as it turns out, Functor and applicative (
<*>) is enough. This
confused me: If applicatives were about sequential actions, where
the current item does not know about its predecessor, how could it
increment the state-monads state? The answer is in the signatures:
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
The
f (a → b) piece tells us, that we map from one value of the
applicative to another. the consecutive
→ f a → f b tell us,
that our
(a → b) operation is applied to
f a to yield
f b.
Thus shouldn’t have surprised me that applicative is in fact capable
of incrementing the counter.
For comparison, Monad’s bind also has this mapping from
a to
b
in it’s signature, however in the form of
(a → m b).
(>>=) :: Monad m => m a -> (a -> m b) -> m b
|
https://www.holger-peters.de/haskell-by-types.html
|
CC-MAIN-2021-25
|
refinedweb
| 2,976
| 55.37
|
The C++ function bool operator>=() compares two array container elements sequentially. Comparision stops at first mismatch or when container elements are exhuasted. For comparision size and data type of both container must be same otherwise compiler will report compilation error.
Following is the declaration for bool operator>=() function form std::array header.
template <class T, size_t N> bool operator>= ( const array<T,N>& arr1, const array<T,N>& arr2 );
arr1 and arr2 − two array containers of same size and type.
Returns true if first array container is greater or equal to the second otherwise false.
This function never throws exception.
Linear i.e. O(n)
The following example shows the usage of bool operator>=() function.
#include <iostream> #include <array> using namespace std; int main(void) { array<int, 5> arr1 = {1, 2, 3, 4, 5}; array<int, 5> arr2 = {1, 2, 3, 4, 5}; if (arr1 >= arr2) cout << "arr1 is greater than or equal to arr2\n"; return 0; }
Let us compile and run the above program, this will produce the following result −
arr1 is greater than or equal to arr2
|
https://www.tutorialspoint.com/cpp_standard_library/cpp_array_greater_than_or_equal_to.htm
|
CC-MAIN-2020-05
|
refinedweb
| 180
| 52.39
|
A library of number theory related functions inspired by Project Euler.
eulerlib is a library of recreational mathematics and number theory related functions inspired by Project Euler. Available functions include:
- Prime number generation
- Divisor functions (sigma functions)
- Euler’s totient function
- Greatest Common Divisor (GCD) using Euclid’s algorithm
- Least Common Multiple (LCM)
- Integer square root
- Fibonacci numbers
- Pandigital numbers
- Palindrome numbers
- Pythagorean triples
Functions from this library can be used to solve recreational mathematics and programming problems such as problems in Project Euler.
Installation
eulerlib is avalaible through Python Package Index (PyPI) using pip.
>>> pip install --upgrade eulerlib
>>> pip uninstall eulerlib
Usage
In Python console you can import functions/classes from eulerlib as needed.
>>> from eulerlib import primes >>> p10 = primes(10) >>> print(p10) [2, 3, 5, 7]
The Divisors class implements functions related to prime factorization, sigma functions etc.
>>> from eulerlib import Divisors >>> mydiv = Divisors(10000) >>> div84 = mydiv.divisors(84) #divisors of 84 >>> print(div84) [1, 2, 3, 4, 6, 7, 12, 14, 21, 28, 42, 84] >>> pf840 = mydiv.prime_factors(840) # prime factors of 840 >>> print(pf840) [(2, 3), (3, 1), (5, 1), (7, 1)]
Example: Solved Project Euler problem 3.
from eulerlib import is_square, primes #get approximate square root of number since #largest prime factor < sq. root (is_sq, sqroot) = is_square(600851475143L) #get a list of primes less than the approx. square root. test_primes = primes(sqroot + 1L) #test the primes from the list to find the largest factor len_p = len(test_primes) for i in range(1,len_p+1): j = 0 - i test_fact = test_primes[j] if 600851475143L%test_fact == 0: break answer = test_fact #Set the answer
See complete documentation.
Modules
Development
Source code repositories (GitHub, BitBucket) are available. Bug reports and suggestions are most welcome.
License
eulerlib is licensed under Apache License 2.0.
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/eulerlib/
|
CC-MAIN-2017-43
|
refinedweb
| 314
| 54.02
|
Readings - Matthew 25: 14-30 (p994) Readers - Rose Young. Wednesdays Service Trinity 21 10.00 am - BCP Communion. Readings - Ephesians 6: 10-20 (p1177), John 4: 46b-end (p1068) Reader - Mrs J Clarkson. Collect Heavenly Lord, you long for the worlds salvation: stir us from apathy, restrain us from excess and revive in us new hope that all creation will one day be healed in Jesus Christ our Lord. Amen. PRAYER All who suffer as a result of war NOTICE BOARD Bishop Steven Visit Bishop Steven will be in the parish tomorrow he will visit All Saints School, The Well, International Produce ltd, lunch with the wardens and the official opening of our TLG centre. If you have any comments or questions for the bishop speak to Don or the wardens. Prayer Meeting This months meeting is tonight at 6.30 pm in Church. Wakefield Cathedral Share Scheme The cathedral is launching a share scheme for everyone to buy a share in the Cathedrals future helping to restore and revitalise it. Shares cost 250, if you purchase two or more shares then you can
have a name engraved in the stone in the Cathedral precincts. See Don for more details. Rotas The service rotas for December are in the pigeon holes. Meaningful Chocolate Tree Decorations Following on from the success of the Easter Eggs, The Meaningful Chocolate Tree Decorations are an opportunity to buy chocolate decorations telling the Christmas story. Each box contains a Christmas story card, sticker set and six hand wrapped quality Fairtrade Chocolate decorations. They cost 3.95 per box, an order form is on the welcome desk, last date for ordering is TODAY Operation Christmas Child Thank you to everyone who filled a shoe box or donated money towards the appeal. Thirty one shoe boxes were donated. PCC The next meeting is on Wednesday 16th November at 7.30 pm, the agendas are in the pigeon holes. Ale and Hymns Wakefield Cathedral, Friday 18th November, 6.00 - 10.00 pm. Real Ale, food and your favourite hymns with our house band. Tickets (which include a souvenir glass and your first half of ale) are 4 in advance or 5 on the door. See notice board for more details. Rock Solid The need for more volunteers has become more acute if you can help please speak to Diane. Personalised Promise Bible Dawn feels she has lent this book to someone and she would welcome its return (No fines from the prison librarian, honest :o)) Talks CDs We now have CDs of both Faith Camp and Global leaders Conference (& DVD). If you want to borrow them let Don know. Church Walking Group Our next Saturday walk is on 19th November and we are planning a walk from Swainby (North Yorkshire moors - between Osmotherley and Stokesley). The walk will be about 7 miles with shorter options (4 to 5 miles). We will meet as usual at the Parish Church Rooms, leaving at 9.00 am. Our next Monday afternoon walk is on the 5th December and we will try Fitzwilliam Country Park, we meet at the Parish Church Rooms at 1.00 pm.
Please let John and Kate know if you are coming on either of these walks (tel: 223893). Health Walks continue fortnightly with the next on Friday 18th November at 10.15 am from The Well. The Yorkshire Philharmonic Choir Will be performing Handels Messiah on Sunday Evening 20th November at 7.30, in Wakefield Cathedral. For those unfamiliar with this 18th century masterpiece, it charts the story of Christs first coming. The words (in English) are from the St James bible, all set to Handels sensitive and often majestic music. The choir would, in particular, like to invite anyone who has not experienced Messiah before, or those not having done so for some time, to join them on this evening, and of course any following the old tradition of hearing Messiah as often as possible will be equally welcome, as the YPC always promises a freshness in its interpretation. The work features Choir, Orchestra and 4 Soloists. Tickets are 12 (10 conc) available from ypctickets@googlemail.com, the cathedral bookshop, tourist information centre or tel (01924) 364862 or speak to Derek Howell or Stephanie Woodhead today. Worship Rotas Sunday 20th November 10.30 am - Morning Prayer & Baptism. Reader - Andy Vanstan. Intercessor - Ron Young. Welcome/Coffee - Rose Young, Lindsay Kerton, Stephanie & Michael Woodhead. Counting - Sally Dinsdale, Debs Atkinson, Gerry Newton. Wednesday 23rd November 10.00 am - BCP Communion. Reader- Miss B Thomas. Weekly Action Tuesday 7.00 pm - The Aftershock in Parish Rooms Wednesday 10.00 am - Traditional Communion in church 1.00 pm - Mums, Dads and Tots in Parish Rooms 6.00 pm - Rock Solid High in Parish Rooms Thursday 4.00 pm - Rock Solid Junior in Parish Rooms 7.30 pm - Youthy in Well@Woodhouse
Sunday Morning Kids Groups Every Sunday 0-2 years under the East Window Every Sunday except the 3rd 3-5 years in Side Chapel Every Sunday except the 1st 6-11 years in Parish Rooms CONTACTS Vicar: Revd. Don Gilkes 01924 893100 07821 325350 don.gilkes@allsaintsnormanton.org TLG Centre Manager: Gavin Budby 01924 220868 07969 089959 Gavin.budby@tlg.org.uk Community Development officer: Jenny Farrall-Bird 01924 892410 07872 551640 jenny@thewellproject.org.uk Churchwardens: Phil Atkinson John Dracup Church Office Admin: Barbara Teece 01924 220868 office@allsaintsnormanton.org Open weekdays 9.00am-3.00pm except Wednesday from 10.00am Call to book Parish rooms Baptism and Weddings Tuesday 7.00-8.00pm Parish Rooms Registered Charity No 1135324 01924 223507 07753 987668
|
https://de.scribd.com/document/72371728/13-November-2011
|
CC-MAIN-2019-39
|
refinedweb
| 935
| 74.79
|
On Wed, Jan 11, 2017 at 5:39 PM, Fabien COELHO <coe...@cri.ensmp.fr> wrote: > > Hello, > >>> The attached patch adds backslash-return (well newline really) >>> continuations >>> to all pgbench backslash-commands. >>> >>> The attached test uses continuations on all such commands (sleep set >>> setshell and shell). >>> >>> I think that adding continuations to psql should be a distinct patch. > > >> The patch does not apply on the latest head, I guess this requires >> rebasing since yours is posted in December. > > > Strange. Here is a new version and a test for all known backslash-commands > in pgbench. > > sh> git br test master > sh> git apply ~/pgbench-continuation-3.patch > # ok > sh> git diff > # ok > sh> cd src/bin/pgbench > sh> make > sh> ./pgbench -t 1 -f SQL/cont.sql > starting vacuum...end. > debug(script=0,command=1): int 0 > debug(script=0,command=2): int 1 > debug(script=0,command=4): int 2 > 3 > debug(script=0,command=8): int 4 > transaction type: SQL/cont.sql > >> Again, it is giving trailing whitespace errors (as I reported for the >> earlier version), plus it does not apply with git apply, > > > It does above with the attached version.
Advertising
It still gives me whitespace errors with git apply, /Users/edb/Downloads/pgbench-continuation-3.patch:31: trailing whitespace. continuation \\{newline} /Users/edb/Downloads/pgbench-continuation-3.patch:39: trailing whitespace. {continuation} { /* ignore */ } /Users/edb/Downloads/pgbench-continuation-3.patch:40: trailing whitespace. /Users/edb/Downloads/pgbench-continuation-3.patch:48: trailing whitespace. {continuation} { /* ignore */ } /Users/edb/Downloads/pgbench-continuation-3.patch:49: trailing whitespace. error: patch failed: doc/src/sgml/ref/pgbench.sgml:810 error: doc/src/sgml/ref/pgbench.sgml: patch does not apply error: patch failed: src/bin/pgbench/exprscan.l:65 error: src/bin/pgbench/exprscan.l: patch does not apply Looks like an editor issue, I used awk '{ sub("\r$", ""); print }' patch1 > patch2 to clean it and it was applying then. >> hopefully that would be fixed once rebased. Other than that, I observed >> that if after backslash space is there, then the command fails. > > > Yes, this is expected. > >> I think it should be something like if after backslash some spaces are >> there, followed by end-of-line then it should ignore these spaces and read >> next line, atleast with this new meaning of backslash. > > > Hmmm. This is not the behavior of backslash continuation in bash or python, > I do not think that this is desirable to have a different behavior. > Okay, seems sensible. >> Otherwise, it should be mentioned in the docs that backslash should not be >> followed by space. > > > I'm not sure. Doc says that continuation is "backslash-return", it cannot be > more explicit. If it must say what it is not, where should it stop? > > -- > Fabien. Please post the clean version and I'll mark it as ready for committer then. -- Regards, Rafia Sabih EnterpriseDB: -- Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org) To make changes to your subscription:
|
https://www.mail-archive.com/pgsql-hackers@postgresql.org/msg302148.html
|
CC-MAIN-2017-04
|
refinedweb
| 491
| 52.76
|
This is the mail archive of the gdb-patches@sourceware.org mailing list for the GDB project.
On 01/12/2017 03:08 PM, Philipp Rudo wrote: > its quite obvious that you are pro C++. My own feelings are quite > mixed. I must amid that the standard library is quite handy, at least > when it works. Debugging it is quite a pain. There's definitely lots of scope for making C++ debugging less painful. I think 2017 will see good advancements here. For example, with the palves/cp-linespec branch on my github, setting breakpoints in C++ methods is soooooo much easier, mainly because I've made linespec tab completion Just Work. The whole "compile" feature for C++ (making use of g++ for the parsing, via the libcc1 plugin) should be making it upstream this year. Etc. Keep in mind that a significant (if not the largest) chunk of our users is using GDB to debug their C++ code too. So in a sense, any pain we now may feel, a good chunk of our users have been feeling for a long while. We just hadn't been dogfooding. > But the syntax sometimes > is unreadable, especially when you use those teplates containing > templates using types is different namespaces. OTOH, stepping through C code that emulates templates using C #defines OTOH is just plain impossible, since all of it is compiled down to a single source line... So in that sense, I think debugging C++ is better than C here. It also helps if you're using a distro that installs pretty printers for the standard library correctly. Fedora does. Ubuntu didn't use to, but I don't know the current state. Thanks, Pedro Alves
|
http://sourceware.org/ml/gdb-patches/2017-01/msg00233.html
|
CC-MAIN-2019-13
|
refinedweb
| 285
| 73.88
|
Hi
I met Jonathan Medd at Tech Ed EMEA this year and he kindly invited me to be interviewed for his PowerShell podcast. If you would like to listen to the podcast it's here:
Happy New Year
BenP
Scripting:
Get-WMIObject –namespace “root\virtualization” -list
.
$vms = $vms | where-object {$_.elementname -eq $vguest}:
"}.
Well that’s it for part 1. Stay tuned for Part 2 –Hyper-V Data Gathering.
Enjoy
Finally, here is the last demo.
Demo 5 – Administering Failover Clustering
I have already written a detailed post, and a similar script on this subject, here. However, I promised all the demos would be on my blog, so attached is the exact script I used at Tech Ed 2008.
Enjoy!
So here is Demo 4 – Administering Hyper-V
I am planning to put more posts on my blog, looking at this subject in more depth, so stay tuned for more in depth demos. This was is what I demo’d at Tech Ed 2008. Notice the namespace that is used:
Gwmi –namespace “root\virtualization” –list
Gwmi –namespace “root\virtualization” –class msvm_computersystem | get-member
Gwmi –namespace “root\virtualization” –class msvm_computersystem | format-table elementname, enabledstate
Thanks
Ola
Demo 3 – How Do I Know Which Classes to Use
In this demo I firstly used WMI Browser, which provides a GUI that can be used to visually display WMI information. That can be downloaded from here:
I then browsed for classes in PowerShell. I have already documented this on my blog and it can be found here:
Phew, that was a short post.
Bon..
Get-Help -name Get-WMIObject
Get-Help -name Get-WMIObject –det
get-wmiobject -namespace "root\cimv2" –list
Gwmi -namespace "root\cimv2" –list
Gwmi -namespace "root\cimv2" -class Win32_LogicalDisk
Gwmi -class Win32_LogicalDisk
Gwmi Win32_LogicalDisk
Gwmi Win32_LogicalDisk –computername localhost
$cred = get-credentials
Gwmi Win32_LogicalDisk –credential $cred
Disks
These lines of code show how to get disk information from a system, identify all the properties and methods of the disk objects that can be used, then uses some properties.
Gwmi Win32_LogicalDisk | Get-Member
$disks = gwmi Win32_LogicalDisk –computername localhost
$disks[0].freespace
$disks[0].freespace/1gb
$disks[0].filesystem
Hotfixes
These lines connect to a system and list all the Hotfixes that have been installed.
$hotfixes = gwmi Win32_QuickFixEngineering –computername localhost
$hotfixes | get-member
$hotfixes | format-table Hotfixid
OperatingSystem
These lines enumerate basic operating system information: the OS version, service pack level and OS architecture type.
$os = gwmi win32_OperatingSystem -computername Serverxxx
$os | get-member
$os | format-list caption, CSDVersion,OSArchitecture
Network Adapter
The following lines modify the IP Address and Subnet Mask of a network adapter using the EnableStatic method.
$nics = Gwmi win32_NetworkAdapterConfiguration
$nic = $nics | where{$_.description –like “*XXXXXXXXXXXX*”}
$IPAddress = x.x.x.x
$subnetmask = x.x.x.x
$nic.EnableStatic($IPAddress, $SubnetMask)
Well that’s the first demo stay tuned for Demo 2 – Administering Servers in Bulk.
Ladies and Gents
Many months ago I posted a script on how to search a namespace for different classes. The post is here
A common question I then get asked is “How do I know what WMI namespaces are installed on a system?” The answer is not immediately obvious so I thought I’d share it with you all.
Get-WMIObject -class __Namespace -namespace root | Format-Table name
I get the following output from my Vista RTM machine.
name
----
subscription
DEFAULT
MicrosoftDfs
CIMV2
Cli
Nap
SECURITY
SmsDm
RSOP
ccm
WMI
directory
Policy
ServiceModel
SecurityCenter
MSAPPS12
Microsoft
Aspnet
So by searching the host for a list of namespaces, and then searching each namespace for the classes available you can find some really useful stuff.
Some of you may of heard about this already, but it's recently been announced that PowerShell will be in the Microsoft Common Engineering Criteria for 2009.
What is the Common Engineering Criteria?
The Common Engineering Criteria is a set of criteria that each Microsoft server product should adhere to. The criteria was set up in 2005 and has been updated each year with a new set of requirements. The word on the street is that in 2009, PowerShell support will be added to this list, meaning that from 2009 all server products that are released should have full PowerShell support. Wahoo!
For more details on the Common Engineering Criteria check out the homepage:
For a checklist of the current criteria, and a report on which products implement them, check out this link:
So to all those that haven't learnt PowerShell yet ... it is time. PowerShell is not going away!
Cheers all
BenP
I had the pleasure of presenting a joint session at the PowerShell UK User Group this week. I presented a joint session with Jeremy Peck from HP on an Introduction to SCVMM and scripting it with PowerShell. I have attached my slide deck from the first half of the session. In order to see Jeremy's deck with PowerShell examples, and the other sessions that were presented at the event please see the links on the Get-PSUGUK homepage (if they are not there yet Richard Siddaway should have them up soon)
PS C:\Users\benp> Get-EventLog -list
Max(K) Retain OverflowAction Entries Name
------ ------ -------------- ------- ----
15,168 0 OverwriteAsNeeded 1,381 Application
15,168 0 OverwriteAsNeeded 0 DFS Replication
20,480 0 OverwriteAsNeeded 0 Hardware Events
512 7 OverwriteOlder 0 Internet Explorer
512 7 OverwriteOlder 0 Key Management Service
8,192 0 OverwriteAsNeeded 0 Media Center
16,384 0 OverwriteAsNeeded 0 Microsoft Office Diagnostics
16,384 0 OverwriteAsNeeded 29 Microsoft Office Sessions
15,168 0 OverwriteAsNeeded 4,109 System
15,360 0 OverwriteAsNeeded 40 Windows PowerShell
PS C:\Users\benp> wevtutil.exe qe Microsoft-Windows-UAC/Operational /c:2 /f:text
Event[0]:
Log Name: Microsoft-Windows-UAC/Operational
Source: Microsoft-Windows-UAC
Date: 2007-10-30T11:14:00.524
Event ID: 1
Task: N/A
Level: Error
Opcode: Info
Keyword: N/A
User: S-1-5-21-1721234763-462695806-1538865281-2692397
User Name: testdom\benp
Computer: vista.test.microsoft.com
Description:
The process failed to handle ERROR_ELEVATION_REQUIRED during the creation of a child process.
This sample connects to the UAC Operational log and displays the newest 2 items as text. (There is only 1 event listed, because I only have 1 entry in the log).
So yes I can access these logs using PowerShell, but no I can't use the Get-EventLog cmdlet to do it. Check out the following link for detailed syntax for using wevtutil.exe
Thanks to Narayanan Lakshmanan for answering the many questions I had about this.
That is all
Hello
I hate writing up scripts. Writing the scripts themselves is great, it’s just explaining them after which is really boring J
Here is the second demo script I used last week, Create-ChildVM.ps1. This script is invaluable if you need to quickly deploy machines in a test lab. I say test lab rather than production because this script uses differencing disks, which do not perform as well as fixed disk. They are great to use when you have disk space constraints, but on a beefy production system I would use fixed disks. A differencing disk has a read-only parent disk which can be used to store the operating system. Then any changes made to the disk are actually stored in the differencing disk. In this example my parent disk is a Windows 2003 SP2 sysprepped disk. The child then holds any differences. Multiple children can point to the same parent and parent disks can be chained together.
This script takes no parameters, and provides a menu system. The VM is created in seconds and the machine is up running in a matter of minutes.
I won’t explain the whole script, but just shout if you have any questions. There is no error checking in this script. Version 2 will have some error checking built in – I promise J
Thanks go to Steven Adler who's code I plagiarised for some (most) of the sections.
Trademarks |
Privacy Statement
|
http://blogs.technet.com/benp/
|
crawl-002
|
refinedweb
| 1,330
| 52.09
|
Home Skip to content Skip to navigation Skip to footer
Cisco.com Worldwide Home
CCO Date: February 23, 2004
Part Number OL-5637-01
These release notes are for Cisco VPN 3000 Series Concentrator Release 3.6 and for its incremental "point" releases through Release 3.6.8.A software. Please note that product release numbers are not necessarily consecutive. These release notes describe new features, limitations and restrictions, interoperability notes, and related documentation. They also list issues you should be aware of and the procedures you should follow before loading this release. The section, "Usage Notes," describes interoperability considerations and other issues you should be aware of when installing and using the VPN 3000 Series Concentrator. Read these release notes carefully prior to installing this release.
These release notes describe the following topics:
System Requirements
Upgrading to Release 3.6.7
New Features in Releases 3.6.3 Through 3.6.7
New Features in Release 3.6.1
Usage Notes
Open Caveats for VPN 3000 Series Concentrator
Caveats Resolved in Release 3.6.8.A
Caveats Resolved in Release 3.6.8
Caveats Resolved in Release 3.6.7.H
Caveats Resolved in Release 3.6.7.G
Caveats Resolved in Release 3.6.7.F
Caveats Resolved in Release 3.6.7.E
Caveats Resolved in Release 3.6.7.D
Caveats Resolved in Release 3.6.7.C
Caveats Resolved in Release 3.6.7.B
Caveats Resolved in Release 3.6.7.A
Caveat Resolved in Release 3.6.7
Caveats Resolved in Release 3.6.6
Caveats Resolved in Release 3.6.5
Caveats Resolved in Release 3.6.4
Caveats Resolved in Release 3.6.3
Caveats Resolved in Release 3.6.1
Documentation Updates
Obtaining Documentation
Obtaining Technical Assistance
This section describes the system requirements for Release 3.6.x.
Cisco VPN 3000 Series Concentrator software Release 3.6.7 supports the following hardware platforms:
Release 3.6.7 contains two binary files, one for each of two platforms:
If you are using Internet Explorer, use version 5.0, Service Pack 2 or higher.
This section contains information about upgrading from earlier releases to Release 3.6.7.
When upgrading VPN 3000 Concentrator releases, you must clear the cache in your browser to ensure that all new screens display correctly when you are managing the VPN Concentrator.
Upgrading to a new version of the VPN 3000 Concentrator software does not automatically overwrite the existing configuration file. Configuration options for new features (for example, IKE proposals) are not automatically saved to the configuration file on an upgrade. The HTML Manager displays "Save Needed" (rather than "Save") to indicate that the configuration needs to be saved. If the configuration is not saved, then on the next reboot, the new configuration options are added again. If you need to send the configuration file to the TAC, save the running configuration to the configuration file first.
Before you upgrade to this release, back up your existing configuration to the flash and to an external server. This ensures that you can return to the previous configuration and software if you need to.
Be aware of the following considerations before you upgrade. These are known product behaviors, and your knowing about them at the beginning of the process should expedite your product upgrade experience. Where appropriate, the number of the caveat documenting the issue appears at the end of the item. See Open Caveats for VPN 3000 Series Concentrator for a description of using this number to locate a particular caveat.
Release 3.6.7 of the VPN 3000 Concentrator software contains several features that interact with corresponding new features in the Release 3.6.x versions of the VPN Client and VPN 3002 Hardware Client software. To get the full benefit of this release you should upgrade your client software as well as your concentrator software. The VPN 3000 Concentrator software, Release 3.6.7, does operate with VPN Client and VPN 3002 Hardware Client versions 3.0 and higher, but you should upgrade these, too, to take full advantage of the new features.
Use the following backup procedure to ensure that you have a ready backup configuration.
1. Go to Administration | File Management | Files.
2. Select the configuration file and click Copy.
3. Enter a name for the backup file (in 8.3 format; for example, name it CON367BK.TST)
You have now backed up the existing configuration to the flash.
You should also back up the configuration to a server. You can do this in many ways, one of which is to download the file using your Web Browser from the HTML interface (VPN Manager).
You can now upgrade the software with assurance that you can return to your previous firmware using your previous configuration.
If you need to return to a release prior to Release 3.6.7, do the following:
Step 2 Rename the existing configuration (for example, rename it as CON367BK.TST).
Step 3 Delete "CONFIG".
Step 4 Copy the previously saved backup file (for example, CON36BKP.TST) to CONFIG. Do not click Save (otherwise, your original CONFIG file will be overwritten with the running configuration).
Step 5 Perform a software reset.
Your prior firmware and image are restored.
These releases update the VPN 3000 Series Concentrator software to resolve several outstanding caveats. Refer to the appropriate "Caveats Resolved in Release 3.6.x" section of these Release Notes for details for each release.
This section describes the new features in Release 3.6.1 of the VPN 3000 Series Concentrator. For detailed instructions about how to configure and use these features, see VPN 3000 Series Concentrator Reference Volume I: Configuration and VPN 3000 Series Concentrator Reference Volume II: Administration and Management.
Network extension per group lets a network administrator restrict the use of network extension mode on the VPN 3002 Hardware Client. You enable the use of network extension mode for clients on a group basis.
Bandwidth management provides a throttling mechanism to all tunneled traffic that limits the maximum amount of bandwidth allowed per group/user (policing) or provides a minimum amount of bandwidth allowed per group/user (bandwidth reservation).
Policies containing both bandwidth reservation and policing apply on the interface and group level. You must create a policy before enabling bandwidth management. For an overview of bandwidth management, see Configuration | Policy Management | Traffic Management | Bandwidth Policies | Add or Modify in the VPN 3000 Series Concentrator Reference Vol. I: Configuration.
To configure bandwidth policies, go to Configuration | Policy Management | Traffic Management | Bandwidth Policies.
To enable bandwidth management on the public interface, go to Configuration | Interfaces | Public Interface and select the Bandwidth Management tab. Check the Bandwidth Management check box, set the Link Rate, and apply a policy to the interface. The policy applied to the public interface is considered the default or global policy for all groups/users that do not have a bandwidth policy applied to their group.
The defined Link Rate must be based on available Internet bandwidth and not on the physical LAN connection rate. For example, if the Internet router in front of the VPN Concentrator has a T1 connection to the Internet, leave the Link Rate set on the VPN Concentrator at the default value of 1544 kbps.
To configure bandwidth policies on a group, go to Configuration | User Management | Groups | Assign Bandwidth Policy. Select the public interface and apply a policy. This page also has an option to reserve a specific amount of bandwidth per group.
To configure a bandwidth policy for a LAN-to-LAN connection, go to Configuration | System | Tunneling Protocols | IPSec LAN-to-LAN and apply a policy.
The DHCP Relay feature lets wireless clients obtain a network configuration from the corporate network before creating a VPN tunnel. This may be used with the VPN Client autoinitiation feature to obtain a network configuration and automatically connect to the secure gateway when a configured wireless LAN (WLAN) is detected.
To add DHCP, go to Configuration | System | IP Routing.
To configure DHCP Relay, go to Configuration | System | IP Routing | DHCP Relay.
To enable DHCP Relay, you must also assign proper rules to filters in the Configuration | Policy Management | Traffic Management | Filters screen
DHCP Intercept uses DHCP to provide a Microsoft L2TP/IPSec Client with a Subnet Mask, Domain Name, and Classless Static Routes.
This feature allows the VPN Concentrator to reply directly to the Microsoft Client DHCP Inform message. This is useful in environments in which using a DHCP server for this purpose is not advantageous.
You configure this feature on a per-group basis on the Client Config tab of either the Configuration | User Management | Base Group screen or the Configuration | User Management | Groups | Add or Modify screen.
Release 3.6.1 adds support for NAT Traversal (NAT-T), the new IPSec over UDP encapsulation IETF IPSec Working Group draft standard specification (draft-ietf-ipsec-nat-t-ike-02).
NAT-T lets IPSec peers establish a LAN-to-LAN connection through a NAT device. It does this by encapsulating IPSec traffic in UDP datagrams, thereby providing NAT devices with port information. Multiple IPSec clients behind a NAT/PAT device can connect to the same VPN Concentrator, except Microsoft L2TP/IPSec clients (as noted in the following list). NAT-T auto-detects any NAT devices and encapsulates IPSec traffic only when necessary.
NAT-T has the following limitations and requirements:
To configure NAT-T globally, go to the Configuration | System | Tunneling Protocols | IPSec | NAT Transparency screen and check the IPSec over NAT-T check box.
With Release 3.6.1, you can also enable NAT traversal for LAN-to-LAN sessions. For a LAN-to-LAN connection, you must also check the IPSec over NAT-T check box in the Configuration | System | Tunneling Protocols | IPSec LAN-to-LAN | Add or Modify screen.
LAN-to-LAN NAT Traversal has the following limitations and requirements:
Release 3.6.1 adds support for Advanced Encryption Standard (AES), which is more secure than DES and more efficient than triple DES. It also adds:
If you configure AES on a VPN 3000 Concentrator group, only clients that support AES (such as the VPN Client, Release 3.6.1) can connect to that group.
To configure AES to the Encryption parameter in Tunneling, go to Configuration | System | Tunneling Protocols | IPSec LAN-to-LAN or Configuration | System | Tunneling Protocols | IPSec LAN-to-LAN.
Release 3.6.1 adds support for Diffie-Hellman Group 5 for use with LAN-to-LAN connections or VPN Client connections with digital certificates. You can use DH Group 5 with 3DES.
To configure DH 5 and AES, go to Configuration | System | Tunneling Protocols | IPSec | IKE Proposals.
To add DH 5 and AES to the Perfect Forward Secrecy parameter, go to Configuration | Policy Management | Traffic Management | Security Associations.
You can now configure the VPN Concentrator to use the HTTP protocol to retrieve a certificate revocation list (CRL) from a distribution point. If you choose HTTP, you must assign HTTP rules to the public interface filter if you access your distribution points through the public interface. For example, enabling this feature supports the use of public key interfaces (PKI), such as Verisign, that require the use of HTTP.
To configure CRL over HTTP, go to Configuration | System | Management Protocols | HTTP/HTTPS.
You can configure the VPN 3000 Concentrator to store certificate revocation list (CRL) information in volatile memory (RAM). CRL caching can potentially speed up the process of verifying the revocation status of certificates. With CRL caching enabled, when the VPN Concentrator needs to check the revocation status of a certificate, it first checks whether the required CRL exists in the cache and has not expired. Then the VPN Concentrator checks the serial number of the certificate against a list of the serial numbers in the CRL. If a match exists, the authentication fails.
To configure CRL caching, go to Administration | Certificate Management | Configure CA Certificate.
You can now configure the VPN Concentrator to retrieve the CRL from the distribution points specified in the certificate being checked, from a user-specified list of up to five static distribution points, or from a combination of these.During IKE negotiation, if CRL checking is enabled, the VPN Concentrator verifies the revocation status of the IKE peer certificate before allowing the tunnel to be established. CRLs exist on external servers maintained by Certificate Authorities. If you configure retrieval of the CRL from a list of distribution points, the VPN Concentrator tries each in turn until it either finds the relevant CRL or exhausts the list.
To configure backup CRL distribution points, go to Administration | Certificate Management and select the Configure option on the appropriate CA certificate.
Release 3.6.1 updates the implementation of the RSA ACE/Agent on the VPN Concentrator to the RSA/ACE Agent 5.0 release. It supports ACE/Server Replicas (a more advanced primary/backup feature than what was in earlier versions), two-step authentication, load balancing, and group-based support for multiple node secrets.
Split DNS lets an internal DNS server resolve a list of centrally-defined Local Domain Names (LDN), while ISP-assigned DNS servers resolve all other DNS requests. This feature is used in a split-tunneling connection. You configure LDNs on a Base Group/Group basis.
Dynamic DNS passes the host name to the central site device, which uses that name in the DHCP address request. This feature allows the DHCP server and DDNS to dynamically populate the DNS records.
Extensible Authentication Protocol (EAP) lets a VPN Concentrator proxy the authentication process to an authentication server. This feature supports additional authentication options for the Microsoft VPN Client (L2TP/IPSec), including CHAP (EAP/MD5), Smartcards (EAP/TLS), and RSA SecurID (SDI).
Supporting EAP pass-through on the VPN Concentrator means that Microsoft native IPSec clients can authenticate users through Smartcards or SDI tokens.
To configure EAP, go to Configuration | User Management | Base Group or Configuration | User Management | Groups.
You can now configure the Maximum Transmission Unit (MTU) to be a value in the range from 68 through 1500 bytes. To configure the MTU, go to Configuration | Interface | Ethernet 123, General tab.
You can now do secure file transfers using the SCP (Secure CoPy) function over an SSH session. To enable SCP, go to Configuration | System | Management Protocols | SSH and check "Enable SCP".
Release 3.6.1 lets you configure a filter to apply to the traffic that is tunneled through an IPSec LAN-to-LAN connection. To configure LAN-to-LAN filters, go to Configuration | System| Tunneling Protocols | IPSec LAN-to-LAN.
Release 3.6.1 lets you view version and operating system information (when available) for connected clients and connected user session information. You can also sort by any of the columns in the table. To view these enhancements, go to the Administration | Administer Sessions screen and the Monitoring | Sessions screen.
Release 3.6.1 allows LANs with overlapping or same IP addresses between VPN 3000 Concentrators using static, dynamic, and PAT rules. To answer the need for hosts to communicate across overlapping LANs, the private address space must be translated (NATed).
The IPSec fragmentation policy specifies how to treat packets that exceed the MTU setting when tunneling traffic through the public interface. This feature provides a way to handle cases where a router or NAT device between the VPN Concentrator and the VPN Client rejects or drops IP fragments. There are three options:
To configure this option, go to Configuration | Interface | Ethernet 123 | General tab. VPN 3000 Series Concentrator Reference Volume 1: Configuration explains these options and gives an example of their use.
In release 3.6.1, you can define rules to match a user's certificate to a permission group based on fields in the Distinguished Name (DN). To specify a policy for group matching by rules, you must define the rules and enable each rule for a selected group that already exists in the configuration. For more information, refer to the description of the Configuration | Policy Management | Certificate Group Matching screen in VPN 3000 Series Concentrator Reference Volume 1: Configuration. (CSCdy09630).
Online help is now easier to use. Release 3.6.1 provides a global help Table of Contents that lets you view and navigate all available help topics. It also offers a search engine, an index, and a glossary.
Release 3.6.7.F adds the ability to send a "Group Lookup" username to the authentication server during user authentication. This feature restores the ability that was available as a side effect of having "Strip Realm" disabled and "Group Lookup" enabled with "@" delimiter.
In Release 3.6.7 and earlier releases, the strip realm and group lookup feature overlapped when the group lookup delimiter was set to '@'. A side effect of this overlap was the ability to send "username@group" to the authentication server during user authentication. This later was reported as a caveat (CSCea88995), which now has been fixed. Unfortunately, some customers have been taking advantage of this feature and have requested that the capability be added back.
This restored feature applies only to usernames that are in the group lookup format "user@group", "user#group", or "user!group" and only when "Group Lookup" is enabled.
To use this feature, uncheck the "Strip Group" checkbox on the Configuration | System | General | Authentication screen.
This section lists interoperability considerations and other issues to consider before installing and using Release 3.6.7 of the VPN 3000 Series Concentrator software.
The online documentation might not be accessible when using Internet Explorer with Adobe Acrobat, Version 3.0.1. To resolve this issue, upgrade to Acrobat 4.0 or higher. The latest version of Adobe Acrobat is available at the Adobe web site:.
This feature is supported only when using Internal or RADIUS authentication. To ensure that you are using this feature properly please refer to the following URL:
You must enable Start Before Logon on the VPN Client and possibly may need to make sure that DNS and WINS servers are properly configured (CSCdv73252).
The following sections describe known behaviors and issues with the indicated Web browsers.
Currently, the VPN 3000 Concentrator fully supports only Netscape and Internet Explorer. If you are using Internet Explorer, use version 5.0, Service Pack 2 or higher. Using other browsers might cause unacceptable behavior; for example, if you attempt to use an unsupported Web browser to manage the VPN 3000 Concentrator, clicking any of the links might return you to the login screen. (CSCdx87630).
The following are known issues with Internet Explorer 4.X and the VPN Concentrator Manager (the HTML management interface). To avoid these problems, use the latest version of Internet Explorer (at least version 5.0).
After adding a new SSL certificate, you might have to restart the browser to use the new certificate.
VPN Clients, when used with the Zone Labs Integrity Agent, are put into a "restricted state" upon connection to the Integrity Server if a port other than 5054 is used. The restricted state simply means the VPN Client is able to communicate only with the Integrity Server; all other traffic is blocked (CSCdw50994).
Workaround:
Do one of the following:
When an L2TP/IPSec connection is established, authentication should behave as follows:
1. The Tunnel Group is authenticated (using the OU field in the Certificate or using the Base Group).
2. The User should be authenticated (using the authentication method of the tunnel group.
3. The User's Group (as defined by the group delimiter option) should be authenticated.
This all works properly, but in the Administration | Administer Sessions screen, the Tunnel Group displays instead of the User's Group (CSCdy00360).
In Releases 3.0, 3.5, and 3.5.1 of the VPN 3000/3002 products, the SNMP task takes 3-5 minutes to complete initialization after a device reboot. Traps being processed during this interval are queued and sent to the SNMP Management station after SNMP task initialization completes.
However, the cold start trap, normally sent as a result of a device rebooting, is never sent.
In Release 2.5.X, the cold start trap is properly sent to the SNMP Manager after a device reboots (CSCdt01583).
If an Windows NT server follows a non-NT server in the prioritized authentication server list, and the non-NT server becomes unavailable for some reason, the VPN 3000 Concentrator detects this and falls back to the Windows NT server. If the tunnel being established is PPTP or L2TP, the authentication attempt to the Windows NT server also fails.
Therefore, when configuring PPTP or L2TP connections, do not place Windows NT authentication servers behind other types of servers in the applicable authentication server list (CSCdy07226).
The Glossary button at the top of all Help screens tries to contact univercd at (the Cisco documentation site). This connection requires connectivity to Cisco's main web site. If your PC does not have a corporate Internet connection or your firewall blocks access, the following error appears when you attempt to access the Glossary:
"The page cannot be displayed."
To access the Glossary, you must be connected to (CSCdy14238).
The VPN 3000 Concentrator does not support the VRRPNotifications and cipSecMIBNotifications SNMP traps. You can configure VRRP for these SNMP traps without getting an error message, but the traps themselves are not supported, so no action occurs. The same is true of Cisco IPSec-flow MIB notifications (CSCdx44580).
The rekey option to renew an SSL certificate from the RSA CA results in a rejection of the request.
The resubmit/renew feature does work with RSA as long as the certificate being rekeyed or renewed is first deleted from the CA database. RSA does not allow a CA to issue more than 1 certificate with any particular DN (CSCdv27743).
Delays of about 3-50 seconds in making a VPN connection have occurred on Windows XP Professional Edition and Windows 2000 Professional Edition after adding a new NIC card. If you see problems of this nature, reboot the PC after the initial installation of the NIC card (CSCdv27743).
If you have enabled the Reauthentication on Rekey feature, the VPN Concentrator prompts you to enter an ID and password during Phase 1 IKE negotiations and also prompts for user authentication whenever a rekey occurs. Reauthentication provides additional security.
If the configured rekey interval is very short, users might find repeated authorization requests inconvenient. In this case, disable reauthentication. To check your VPN Concentrator's configured rekey interval, see the Lifetime Measurement, Data Lifetime, and Time Lifetime fields on the Configuration | System | Tunneling Protocols | IPSec | IKE Proposals | Add or Modify screen.
The VPN 3000 Concentrator does not support selecting source and destination network lists when defining rules for CPP firewall policy. Instead, you must define the source and destination address in the rule definition (CSCea14152).
The functionality that allows the administrator to create a network list from within a LAN-to-LAN configuration page has changed.
In previous releases, the administrator could create a network list from within the LAN-to-LAN configuration page. The new method for creating a network list uses a link on the LAN-to-LAN index page to the network list configuration page.
This change was resolves a problem with Reverse Route Injection when the network lists are added from within the LAN-to-LAN page. With the previous method, the routes, corresponding to the network lists that were added via the LAN-to-LAN page, were not present in the routing table (CSCea13002, CSCdz87573).
Caveats describe unexpected behavior or defects in Cisco software releases. The following list is sorted by identifier number.
The following problems exist with the VPN 3000 Series Concentrator, Release 3.6.7.
L2TP over IPSec connections fail if going through a NAT device. During the connection establishment, the VPN Client and the VPN 3000 Concentrator exchange IP addresses. When the client sends what it believes to be the VPN 3000 Concentrator's address (really the NATed address), the VPN 3000 Concentrator releases the connection.
This is because the address assigned to the interface does not match the address coming in from the client. The same issue exists on the client side. This will not be resolved until the Windows 2000 MS client supports UDP encapsulation.
When configuring a LAN-to-LAN connection with IOS or PIX, it is important to match the keepalive configuration (both "ON" or both "OFF"). If the keepalive configuration is OFF for the VPN 3000 Concentrator and ON for the IOS device, the tunnel will be established with data.
IOS tears down the tunnel because the VPN 3000 Concentrator does not respond to IOS style keepalives if keepalives are configured to be OFF for the VPN 3000 Concentrator.
Multiple simultaneous connections from users behind a PAT (Port Address Translation) device can work, but only if the PAT device uses a unique source port for each simultaneous user's IKE session.
Some PAT devices use UDP source = 500 for all IKE sessions even if there are multiple simultaneous sessions. This will only allow 1 session to work since the second connection brought up from behind this PAT device will cause the first session to be torn down.
This is unrelated to whether a PAT device supports "ESP" PAT or whether you are using the IPSec/UDP (NAT) functionality.
If the phase 2 SA has a lifetime set to 60 - 119 seconds, the VPN Client connection is automatically disconnected. A phase 2 SA lifetime of 120 seconds and higher rekeys properly. This is an issue in the SW client. LAN-to-LAN and hardware Clients work fine.
In some cases, the Zone Labs Integrity Agent may not properly update on the Windows NT version 4.0 operating system while the VPN Client is connected, policy is changed and re-deployed, and the connection is up. Specifically, if you "Block Internet Servers" under the Firewall Security Rules in the Policy and then Deploy that new policy, a PC running Windows NT version 4.0 receives the updated policy, but it might not put the "Block Internet Servers" setting of that policy into effect.
Reboot the operating system.
You cannot reserve group bandwidth based on a percentage.
Due to a Microsoft bug, Windows XP PCs are not capable of receiving a large number of Classless Static Routes (CSR). The VPN 3000 Concentrator limits the number of CSRs that are inserted into a DHCP INFORM message response when configured to do so.
The VPN 3000 Concentrator limits the number of routes to 28-42, depending on the class.
The Concentrator may display the following events during a VPN Client connection. These events were found to be due to the client being behind a Linksys Cable/DSL router that was incorrectly modifying the Client's packets, causing them to fail authentication when received by the VPN Concentrator. The problem is more prominent if LZS compression is used.
Events:
131500 06/20/2002 17:08:34.300 SEV=4 IPSEC/4 RPT=4632
IPSec ESP Tunnel Inb: Packet authentication failed, username: gray, SPI:
4e01db67, Seq Num: 0000850f. Dump of failed hash follows.
Linksys has been notified about the problem.
Although no workaround currently exists, disabling LZS compression on the Concentrator helps reduce the number of events. To disable LZS compression on the Concentrator set the "IPComp" setting on the IPSec tab of the group configuration to "none".
The Microsoft L2TP/IPSec client for Windows 98, Windows ME, and Windows NT does not connect to the VPN 3000 Concentrator using digital certificates.
Use preshared keys.
When specifying the link rate for bandwidth management on an interface, the VPN 3000 Concentrator only permits specifying the range 1544000 - 100000000 bps.
This renders the feature difficult to use properly when the Internet link is less than T1 speed. We should permit the full range of speeds to allow this feature to be deployed in all environments.
On the VPN 3000 Concentrator running version 3.6 code, a bandwidth management policy is created with a reservation included, and this is applied to a group. No aggregation is applied to the group (left at 0). Interface bandwidth management is enabled and link rate is set to 1.544 Mbs, and a different group is applied for default users with a reservation only.
If the reservation amount is then changed on the policy the following error occurs in the log:
31 11/27/2000 15:43:48.360 SEV=4 BMGT/47 RPT=7
The Policy [ ADCUsers ] with Reservation [ 102000 bps ] being applied to Group [ ADC ] on
Interface [ 1 ] exceeds the Aggregate Reservation [ 0 bps ] configured for that group.
This error does not occur if the policy is first removed from the group, then the reservation is changed and the policy re-applied. No users are connected at the time of the error.
The reservation should be checked against the aggregate only if aggregation is enabled.
On a VPN 3000 Concentrator running Release 3.6 code, a bandwidth management policy is created and applied to a group reserving some portion of the link bandwidth using an aggregate reservation. If this reservation is then changed, the previous committed bandwidth is not freed up first when calculating whether enough bandwidth is available for use.
So, if 600 kbps is reserved from a link of 1544 kbps to start with, and this is then modified to reserve 1000 kbps, an error is generated and the modification is refused. The error shown is as follows:
83 11/27/2000 16:30:44.620 SEV=4 BMGT/31 RPT=7
Attempting to specify an Aggregate Group reservation [ 1000000 bps ] on Group [ ADC ] Interface [ 1 ] which added to the current reservation of the interface [ 600000 bps ] exceeds the link rate [ 1544000 bps ] to which it is being applied.
No bandwidth is reserved by any other policy.
Remove the aggregate reservation from the group first, and then to apply the new setting.
When a customer who is using the NT domain for user authentication and has the group name that is defined in the Concentrator the same as the user name in the NT domain server, the VPN Client can no longer connect to the Concentrator after upgrading the Concentrator to Release 3.6.1.
Cannot perform xauth with a PDC emulator in an Active Directory (AD) environment, when NT is the authentication method from a VPN 30000 Concentrator. In a MIXED MODE environment for Windows 2000 AD setup, using a PDC emulator in the domain for authentication from a VPN 3000 Concentrator does not allow a user to authenticate from a PDC emulator if the length of password is more than 14 characters.
The LAN-to-LAN tunnel might drop and get re-established, but the IKE session doesn't get cleared out of the administer sessions screen.
The VPN 3000 Concentrator does not send the ZoneLabs Integrity Server properly formed markup characters. Ampersands - as well as angle brackets (<,>), apostrophes ('), and double-quotes (") - should be escaped, because they are markup characters. For example: The "&" is not escaped. The result is that a login name of "L&nc&" is sent included in all messages the VPN Concentrator sends Integrity. (The username should be sent as "L&nc&".) Integrity rejects the session, and the VPN Concentrator drops the tunnel.
Attempting to delete a file from an ftp session into the VPN3000 fails and terminates the ftp session.
The file can be deleted from the VPN3000 Web Management screen at Administration | File Management.
After setting up the "config" user in Administration | Access Rights | Administrators | Modify Properties as being able to Read/Write File, this user can't access Administration | File Management. The following message appears:
You do not have sufficient authorization to access the specified page.
In all versions prior to Release 3.6, the Concentrator asked the Client to provide a Domain Name field for Native NT Domain authentication. Since it was believed that this field was not used for anything, this field was removed in Release 3.6.
To establish a connection in Release 3.6, use:
DOMAIN\username
instead of the construction used in earlier releases:
username
DOMAIN
The Client might fail to establish an IPsec session if the Concentrator has a larger certificate. TCP encapsulation is used and there is a PAT router between the Concentrator and the Client.
If CPP, which allows local LAN access, is pushed from Concentrator, the Client allows any traffic from/to the Internet.
With multiple authentication servers defined, if any are defined by DNS name, and the system fails to resolve any of the servers, all incoming authentication requests will be held off for approximately 45 seconds. For example, the first server in the list was defined as an IP address and was working, the second and third servers were defined as DNS names and did not exist on my network (testing with a customer config). When trying to make a VPN Client IPSec connection, the first and second connection attempts time out, the next 10 or so work, then repeat the time out cycle.
Testing with servers only defined by IP address did not exhibit this behavior. In fact, servers defined by IP address that did not exist were recorded as being on-line in the event log
Remove the servers defined by DNS name.
VPN 3000 Concentrator version 3.6.3 sometimes leaves the RRI route in the Concentrator's routing table, even though the client is no longer connected.
When connecting a VPN 3015 Concentrator with Cisco VPN Client Software, the VPN connection fails.
Windows XP becomes unreachable over IP after returning from standby mode if the "Stateful Failover (Always On)" is enabled.
Disable "Stateful Failover (Always On)".
There is a problem with IPSEC SAs reestablishing after checkpoint initiates a soft reset.
After the public IP address and default gateway have been changed, the VPN 3000 Concentrator does not allow incoming data packets encapsulated by UDP(10000), even if an IPsec session is being established correctly. If you use TCP encapsulation or no encapsulation the problem does not occur.
Reload the VPN 3000 Concentrator after IP address modification.
Many "IPSEC ESP bad pad length (8) >= buffer length (8)" messages were logged in a syslog.
Using VPN3000 and PIX EzVPN:
-Phase 2 SA recreation after an expiration of a SA because of an idle timeout (30min)
-35 sec after a creation of a new SA after an old SA lifetime Expiration. (Duplicate of CSCdz33769.)
A VPN 3000 Concentrator fails rekey with Microsoft's L2TP/IPSec client for Windows 95 or Windows 98 (oem'd from Safenet).
This was determined to be a bug in the Microsoft client. The Concentrator always initiates rekeys. When phase 1 rekeys, we send the first main mode packet to the MS client. The Microsoft client responds with a malformed main mode packet.
The packet that Microsoft sends contains a final payload that has the Next Payload fields set to "vendor-id". Since the packet does not actually contain a next payload, we fail on the packet and thus fail the rekey. This caveat is a placeholder to track the issue.
The only workaround is currently to increase phase 1 rekey time(s) to a value that will not be hit. Because IKE will negotiate the lower of the proposed rekey times, this requires a registry change on the client PC(s), as well as a change on the concentrator.
The registry key is:
HKLM\Software\IRE\Safenet\Soft-PK\ACL\1\PH1PROPOSAL_xx, where "xx" is the number of the proposal. The default value of these keys is 28800 (seconds) or 8 hours. This value should be changed to a value that is high enough that users will not run into it.
After working for 2 weeks, the following messages can appear on the Concentrator:
Concentrator memory resources are critical
It might fail, or you might have to reload the Concentrator manually to free the memory.
The VPN3000 Concentrator will transmit data to exceed the negotiated Max Window Size. If going through a PIX edge firewall, the PIX shuts down the session when the window size is exceeded.
This occurs only when the ACKs coming back are delayed in transit.
The default window size for cTCP is 64K. The VPN Client and VPN3002 Hardware Client both generate ACKs at 8K intervals to avoid window issues. In this case the delays in ACK transport are significant enough that the window size is exceeded.
When split-tunnel configured, Windows XP machines with firewall enabled are not able to pass VPN traffic to the central-site concentrator, even though Internet traffic is passing through.
The Internet Connection Firewall is incompatible because the firewall blocks IPC communication from the VPN Client to the VPN Device Driver. In the firewall log, the log consistently blocks UDP 62515; this is the port used to establish the IPSEC SA.
With the Release 3.6.3.C VPN Client connected to a Release 3.6.7.B VPN 3000 Concentrator, a static route pointing to the exit interface (Ethernet) does not route IPSec traffic to the connected VPN Clients, although it can route cleartext traffic just fine. The route has to point to an exit interface instead of a next-hop router.
A VPN 3060 Concentrator running software Release 3.6(7)Rel:
failed with Exception Type: 0x00000300/DSI.
The Concentrator recovered itself after a while with no intervention.
You can access the web admin GUI interface using a MAC OSX machine running IE 5.5 with all updates and java installed. You can get around and configure the device as usual; however, when you click on the live event log link from the left-hand menu options | Monitoring | Filterable Event Log | Live Event Log, the following error appears:
java.lang.ClassNotFoundException eventlog.class
The VPN Client can connect to the VPN 3005 Concentrator, but cannot reach to a network when the packet matches "tunnel default gateway" route. But when the packet matches "static" route, the VPN Client can reach to the network.
When applying a filter to a vpn group the filter settings don't apply to users of this group when connected.
Apply the filter to the individual user.
A VPN3005 fails frequently.
A VPN 3000 Concentrator running Release 3.6.7.C fails to generate a full XML file if the Concentrator has more than 15 LAN-to-LAN tunnels configured.
Network Autodiscovery does not work if the VPN 3000 Concentrator is behind a NAT device and the NAT-T feature is in place.
On the VPN 3000 Concentrator behind the NAT device, do the following steps:
Step 2 Enable L2L-NAT
Step 3 Add static L2L NAT entry: public/0.0.0.0:NAT/0.0.0.0->peer/0.0.0.0,
where 'public' is public IP of the Concentrator behind NAT device, 'NAT' is the public address of the NAT device and 'peer' is the public address of the remote Concentrator.
Explanation of Workaround:
Step 1 updates the filter rules that are used to establish the Public-To-Public IPSec SA. The addressing in the rules must be consistent on each side of the tunnel.
This tunnel is used to sent the autodiscovered networks (via RIP). Steps 2 and 3 tell the Concentrator to NAT packets (to the NAT device's public interface) between the peer's public to its public. This is necessary because the peer directs its RIP packets to what the peer believes to be its peer (the NAT device).
Since the filter rule was modified, the NATed Concentrator needs to NAT its RIP packet to match the modified filter rule.
The VPN Concentrator is not accepting client connections.
After re-booting the VPN 3000 Concentrator, it accepts client connections for some time, then stops accepting client connections.
Re-boot the VPN concentrator.
You cannot use Split Tunnel with ICF on Windows XP. Microsoft does not allow adding an appropriate filter rule to allow the specific ports needed to use for VPN Client communications.
The VPN 3000 Series Concentrator mibs are improperly posted and do not conform to Cisco standards.
With Cisco Integrated Client Firewall and CPP, when you define (on the Concentrator) a filter with "Default Action" set to "Drop & Log", the policy looks good on the VPN Client "Firewall" tab, but the default action (drop) is not correctly enforced.
Choose "drop" as the default action.
Using VPN 3000 Concentrator software Release 3.6.5 or 3.6.7.A, a CRL check fails if the received CRL is empty.
A VPN 3030 Concentrator froze when telnetting on it. Then it rebooted.
The circumstances initiating this set of failures are unclear and at this point unreproducible. The customer network had been running for some time without incident. Suddenly, the system crashed several times within a few days. The initial failure occurred when running Release 3.6.7.A, but upgrading to Release 3.6.7.D made no improvements. The customer environment requires tunnels to be terminate on all three interfaces. At some point IPSec compression was enabled for all groups. It's unclear whether this configuration change was made at the time of the crashes. It is clear that disabling IPSec compression restored stability in the customer network.
A VPN 3000 Concentrator using EAP-TLS and L2TP compression stops encrypting traffic after 2-3 hours, connection stays up.
The user can connect to the VPN 3000 Concentrator (running Release 3.6.7.Rel) without any problem, using L2TP over IPSec /w EAP-TLS authentication, but after 2-3 hours of traffic passage, the VPN 3000 Concentrator stops encrypting traffic, but doesn't drop the connection.
Disable L2TP compression and/or EAP-TLS Auth.
Clicking apply on any LAN-to-LAN SA causes all LAN-to-LAN sessions to drop.
If you have a client user and an admin user with the same name, the client user might not be able to connect when the admin user is logged in and the client user has a simultaneous logins set to 1.
This caveat has been closed because the VPN 3000 Concentrator has a flat namespace. The administrator names should be different from the username for security reasons.
In the LAN-to-LAN NAT rules, the VPN Concentrator accepts network/mask rules such as 192.168.1.0/255.255.0.0.
It should consider this as a typo and either modify it to be 192.168.0.0/255.255.0.0 or it should reject it and warn the user.
After some period of time the concentrator will fail to take any new connections. Each new incoming connection fails with a time-out in building IKE Main Mode Message 6.
Reboot the Concentrator.
VPN3000 crash due to a malformed PPP IP Control Protocol message.
Release 3.6.8.A resolves the following issues:
L2TP and PPTP connections to VPN 3000 running Release 3.6.8 or Release 4.0.2 cause the device to fail.
The following problem occurred on both Release 3.6.8 and Release 4.0.1.C. The primary VPN 3000 Concentrator's interfaces are still primary after being rebooted, even though one of the interfaces is Down.
Release 3.6.8 resolves the following issues:
HTTP Software Updates sometimes fail with "Software Update Error". Retrying the operation does not update the image.
Using a VPN 3060 Concentrator running Release 3.5.5 or 3.6.7.F, when we set VRRP and Master VPN's private interface fails, switchover delay happens at Backup VPN, hence we cannot communicate end-to-end.
The VPN 3000 Concentrator has a minimum password requirement of 8 characters. This requirement can be bypassed and a local user password can be set to blank by editing the username and removing the password at the same time on the VPN 3000 Concentrator, despite the error about the password not meeting minimum length requirements.
Release 3.6.7.H resolves the following issues:
A customer is connecting from a 3002 hardware client configured as a PPPoE client to a VPN 3000 Concentrator using an Internet Service Provider. According to the customer, this configuration was working fine until recently when ISP made a change on their side to use PAP instead of MS-CHAP v1 for PPPoE authentication. The customer sees same behavior whether they use 3.6.3, 3.6.1 or 3.5.5.
VPN Client can't connect using cTCP to the virtual address in the VPN 3000 Series Concentrator using load balancing following a reboot. This issue occurs only in Releases 3.6.7.F, 3.6.7.G, 4.0.1.Rel and 4.0.1.A
VRRP and IPSec over TCP might not work in Releases 3.6.7.F and 4.0.1., but they work in release 3.6.3.
Release 3.6.7.G resolves the following issues:
A VPN 3000 Concentrator might leak message buffers under the following conditions. This could prevent new connections and possibly cause the device to fail.
Conditions:
When using multiple static CRL servers, if the first server fails without being taken off-line, the subsequent searches also fail.
With authentication set to Radius with Expiry, the user is prompted for username, password and domain name when connecting. The ACS authentication report shows "domain\username", but the ACS accounting report page shows only the "username".
The VPN 3000 Concentrator, Releases 3.6.7C, 3.6.7D, and 4.0, sends VRRP messages on the public interface after system shutdown.
Release 3.6.7.F resolves the following issues:
VPN 3002 Ethernet ports might hang intermittently when connected to a Centercom hub.
Changing from DHCP to STATIC on an interface will not stop IP event logs 29 and 34 from showing in the filterable event log.
Release 3.6.7.E resolves the following issue:
The User [user], Group [group] event log message for a VPN Client disconnect is now separated by comma in Release 3.6.7 and later code. In the code before 3.6.7, this comma was not present and the User [user] Group [group] event log message was separated with a space tab format.
Release 3.6.7.D resolves the following issues:
Autoupdate continues to retry even when tunnel fails.
The IPSec terminating interface is the External Interface, and the Inside Interface is the Private Interface. The Ethernet 2 (Public) interface has the Public Interface checkbox checked. but the Interface is set to "NOT CONFIGURED". When this happens, all the IPSec/NAT connections fail by giving the error:
Could not register UDP port for NAT enabled IPSec!
Unchecking the public Interface checkbox when its not configured or giving it any bogus IP Address resolves the issue, and IPSec/NAT starts working fine.
The load balance notify packet arrives at the VPN Client before the certificate packet, and this results in a failed connection attempt. The VPN Client sees this as a malformed packet, and the entire negotiation fails.
The VPN Client does not have the ability to inspect the certificate when it arrives after the load balanced notify packet from the VPN Concentrator. This causes the phase 1 main mode negotiations to fail.
The VPN 3000 Concentrator running 3.6.7 randomly fails after changing LAN-to-LAN rules.
A VPN 3000 Concentrator running Release 3.6.7 is not able to decode the objects in the CA certificate or in the VPN Client certificate.
The VPN 3000 Concentrator accepts the CA certificate and the certificate for the Concentrator, but in Subject and Issuer, it shows Unknown. When the VPN Client connects, it always ends up in the base group, not in the group matching the OU or group match config.
If the DHCP Server address pool on the VPN 3002 is modified, it will still renew IP Address from the previous address pool.
After upgrading to Release 3.6.7.A from 3.6.7 Rel, a VPN 3000 Concentrator does not redirect any traffic coming in from a VPN Client to across LAN-to-LAN tunnel.
PIX-to-PIX spoke connectivity when each PIX is connected LAN-to-LAN to a VPN 3015 Concentrator running Release 3.6.7.A is broken.
Release 3.6.7.C resolves the following issues:
An administrative user who has "Stats Only" permission and who attempts to view users filtered by "Group" on the Monitor | Sessions screen, sees all logged-in users instead of a filtered list.
If a L2L tunnel is initially configured with Auto Discovery then the routing field in the tunnel configuration is changed to 'none' the L2L:AutoDiscovery stays in the network list. If you attempt to remove the entry from the network list, the concentrator goes to 100% CPU.
The following error message appears in the log file:
564520 09/06/2002 12:05:47.830 SEV=1 L2TP/60 RPT=3 pSOS q_send failed
A stable system suddenly started to crash - when removed from the network, the system no longer crashed. The crash dump seems to lead to autodiscovery for LAN-to-LAN tunnels. When autodiscovery is used, each route learned eats up memory by having to create custom (hidden) filters.
When configuring a load balanced configuration, the shared secret can be set to cisco123. Under the VCA L2L, session a preshared key of ALTIGA is listed. Changing this preshared key results in an error:
Error updating group for LAN-to-LAN connection (Not Writable Error).
Cisco 3030 VPN Concentrator running 3.6.1 fails when SDI sockets are depleted. The Concentrator is leaking sockets when the SDI server responses time out (see CSCea08807). This failure is another symptom of that problem.
Even when the master Concentrator is shutdown, VRRP messages are still sent out. As a result, the backup Concentrator never assumes the master role.
The following code Assertion might occur on a system using the SEP-E as tunnels are connecting and disconnecting.
Assertion: "sa->refCnt >= 0" failed, in file fsmact.c, line 4462
Cisco 501 with Individual User Authentication to Cisco ACS fails. The log message on the VPN 3005 Concentrator is:
56 01/16/2003 18:55:24.480 SEV=4 AUTH/9 RPT=52
Authentication failed: Reason = No active server found
handle = 232, server = (none), user = user
The VPN 3000 Concentrator might fail if you are viewing bandwidth management statistics from the HTML management interface.
If RRI (Client and/or Net extension mode) is enabled or disabled in configuration/system/ip routing/reverse route injection, and generate hold down routes is clicked before apply, the enable/disable changes that were made fail to survive. The changes revert back to what they were set to when you entered the page as soon as gen hold down routes is clicked. If you are observing closely, you may realize that your settings were blown away, before clicking apply. Otherwise, you may be confused as to why the routes are not showing up in the routing table.
A problem can occur with a VPN 3000 Series Concentrator that is authenticating against a Windows 2000 server via RADIUS w/ Expiry option. If a user's password expires, the Cisco Client prompts user for change of password. If the new password meets password requirements, then the rest goes well. If not, then subsequent attempts also fail.
This happens only in Release 3.6.1, but not in 3.0.3, which has also been tested. Release 3.6.1 also works correctly if @ is used as group delimiter.
If Group Delimiter is selected; for example, #, the external authentication request is sent with the whole UsernameDelimiterGroupname instead the Username only.
This means no strip-off from Group Delimiter for external authentication. The authentication fails because the Authentication server authenticates based on Username. For example:
user: Cisco
group: Test
Group Delimiter: #
UsernameDelimiterGroupname: Cisco#Test
This means that the VPN 3000 Concentrator sends Cisco#Test to the Authentication server instead of Cisco.
Under Monitoring | Statistics | Authentication, the Requests column never gets updated and shows 0. The Accept, Reject columns counter get updated properly.
When using Unit Authentication for 3002s connecting into a Load Balancing Cluster the connection will fail. Connecting to the individual concentrators within the cluster functions properly. This problem only occurs when connecting to the cluster address.
The VPN 3002 cannot establish an IKE tunnel to a central-site PIX.
Incorrect port number is displayed via CLI for VPN 3002 NAT-T connections.
On the VPN Concentrator's group configuration for the VPN 3002, if you have AES-256 and PFS Group 2 configured in the IPSec SA and the 3002 is using NAT-T, PHASE 2 fails to negotiate, and the tunnel never comes up.
When group lookup is enabled and the user enters username<delimiter>group, the group is not stripped off the username before sending it to the accounting.
For example, "User#MyGroup" would be sent to the accounting server instead of just "User".
A VPN 3002 Hardware Client fails to pass data across a cTCP tunnel for one way streams. This problem occurred because of a TCP windowing issue. The TCP ACKs piggy-back on the ESP data packets. Since data was only going one way, the TCP acks were not being sent. This caused the VPN 3002 Hardware Client to drop new packets (including Dead Peer Detection), and the connection would terminate.
The peer sends a gratuitous ACK for every 8K of data received. This ACK was getting processed but did not adjust the window. This problem was introduced in Release 3.6.7.B when exceeding window size prevention was added.
The password for the Accounting server will reset when you modify the server data but not the password field. This happens when you select Modify Accounting Server and press apply (without changing any fields).
Release 3.6.7.B resolves the following issues:
OSPF updates are not populating the routing table on the VPN Concentrator.
If you add and delete filters through the GUI interface (Configuration | System | Policy Management | Traffic Management | Filters), there is a very small memory leak for each filter created and deleted.
If the 3002's configuration is changed from DHCP to PPPoE, and the PPPoE username or password is configured incorrectly, after 3 attempts to contact the PPPoE Access Server the 3002 will reboot.
If a simple password is configured under the OSPF tab in any of the interface configuration pages, the deleted entry reappears, even after deleting the password, selecting none for OSPF authentication, and clicking apply.
When a user fails authentication due to a restriction placed on the account at the Active Directory server, the Concentrator Events do not display the reason for the failure. Some restrictions on the account could be Account Expired, Account Disabled, Account Locked-Out, Not within Logon Hours and Password Change required. For most of these restrictions you will see the following Events:
124 01/20/2003 11:12:55.590 SEV=10 AUTHDECODE/43 RPT=4
Kerberos: Error type: Client's creds have been revoked
130 01/20/2003 11:12:55.590 SEV=4 AUTH/9 RPT=9 70.139.1.5
Authentication failed: Reason = Invalid response received from server handle = 196, server = 198.133.219.25, user = myuser
When a LAN-to-LAN connection is added and the "Create Network List" feature is used, then the routing table fails to get populated with the remote list entries, as it should when Reverse Route Injection (RRI) is enabled.
If the network lists are constructed first, then the LAN-to-LAN is constructed via the wizard using these lists, then when RRI is applied to the LAN-to-LAN, all entries show up as they should.
When the customer, using VPN3030 with 3.6.5 software, assigns IP addresses, the addresses are allocated on a group basis under the Configuration | User Management | Groups | "hilite the group" Modify Address Pool option. When an entry is deleted from the list, multiple entries are deleted. If you try to enter the second erroneously deleted entry, the VPN Concentrator complains that the network exists in the lists. Rebooting does not solve the problem.
When receiving IKE packets with missing payload(s), events currently only state that the packet had invalid payload(s).
When using split tunneling and routing large frames in-the-clear through the public interface over PPPoE, frames that require fragmentation due to the additional 8 bytes for PPPoE overhead will be dropped. This problem seems to affect only PPPoE connections.
Statically assigned filters take precedence over dynamically assigned filters. It should be the other way around.
Using Kerberos authentication, if you attempt a VPN Client connection and type the username incorrectly or enter an unknown username, the Client simply disconnects and the Concentrator Event Log shows:
122 02/25/2003 08:08:06.690 SEV=4 AUTH/9 RPT=1 192.168.1.24
Authentication failed: Reason = Invalid response received from server handle = 19, server = 10.10.0.10, user = IsThisUserHere
To help troubleshoot Kerberos authentication problems, enable AUTHDECODE up to SEV=10, and you also see this Event:
117 02/25/2003 08:08:06.690 SEV=10 AUTHDECODE/43 RPT=8906
Kerberos: Error type: Client not found in Kerberos DB
Release 3.6.7.A resolves the following issues:.
If a LAN-to-LAN tunnel between a VPN 3000 Concentrator and an IOS device is misconfigured and repeatedly fails to establish, then the VPN 3000 Concentrator could enter a state where a reboot is required.
One way to encounter this problem is to try to set up IOS to handle both LAN-to-LAN tunnels and Remote Access tunnels on the same interface, without breaking the IOS interface into V-LANs. This is a misconfiguration and is not supported by IOS, and it can lead to problems with the VPN 3000 Concentrator.
This configuration is not supported because IOS does not allow the same crypto map to be used to terminate both LAN-to-LAN tunnels and Remote Access tunnels. In addition, IOS only allows one crypto map to be applied per interface.
Consequently, if both types of tunnels must be terminated on a single physical interface, that interface must be broken out into V-LANs. Dividing the physical interface in this way enables a different crypto map to be applied to each virtual interface. This in turn enables both types of tunnels to be terminated on the same physical interface while maintaining a valid configuration.
When viewing bandwidth management statistics via the CLI, with Bandwidth Management enabled and multiple users connected, all user sessions scroll through on the screen without the user being prompted to press space to continue or Q to quit.
Documentation for the Bandwidth Management feature in Release 3.6.1 refers to a configuration option in which bandwidth aggregation is automatically applied to a LAN-to-LAN connection when a bandwidth reservation policy is applied to a LAN-to-LAN connection. This feature is not available in Release 3.6.1.
To ensure that bandwidth is always available for a LAN-to-LAN connection via the HTML interface, navigate to Configuration | User Management | Groups. Highlight the LAN-to-LAN group, and select the Assign Bandwidth Policies button. Select the public interface, and next to the Bandwidth Aggregation parameter, enter the amount of bandwidth to reserve from the total available bandwidth for this connection.
If bandwidth aggregation is not set for a LAN-to-LAN connection, a situation might occur where there is not enough bandwidth available for the tunnel to be established.
The VPN 3002 IPSec tunnel fails to establish if using Perfect Forward Secrecy and NAT Traversal.
The customer cannot set the filter in a LAN-to-LAN connection to NONE. When we set it to NONE and save the configuration, then go back to LAN-to-LAN and apply a filter, NONE is no longer set. It appears that it inherits the filter from a VPN Group that has that filter applied.
After upgrade the CVPN3002 from 3.5.2 to 3.6.1, every user gets a script error message, and some users are no longer able to use the Outlook email application.
When using Certificate Group Matching as described in:
/en/US/products/hw/vpndevc/ps2284/products_configuration_guide_chapter09186a00800b4829.html#xtocid145
it appears that in the instance of having a number of distinguished names to match on, such as multiple OUs, we only try to match the rules on the last attribute (OU). Earlier OU's are ignored.
This occurs when you are using Certificate Group Matching and have multiple OUs in the same certificate.
If you have a Client certificate with multiple OUs under the "Subject", such as:
OU=12345678
OU=
and you have defined rules like this:
ou*12345678
ou*http
then messages similar to these appear in the Concentrator logs (class=CERT):
1 10/02/2002 12:10:21.510 SEV=5 IKE/21 RPT=18 192.168.1.1
No Group found by matching IP Address of Cert peer 192.168.1.1
2 10/02/2002 12:10:21.510 SEV=5 CERT/110 RPT=19
Group match for cert peer 192.168.1.1 failed using rule ou*"12345678"
3 10/02/2002 12:10:21.510 SEV=5 CERT/110 RPT=20
Group match for cert peer 192.168.1.1 succeeded using rule ou*"http"
4 10/02/2002 12:10:21.510 SEV=5 CERT/105 RPT=4
Group [TEST-GROUP] found for cert peer 192.168.1.1 by group match rule ou*"http"
If you remove the first rule, you also (trivially) succeed, matching "http" against the second OU.
If you remove the second rule, the connection fails, because 1234578 is not a pattern inside the last OU ()
If an IPsec policy containing DES appears after policies containing AH, the DES policy is not found. The Concentrator appears to stop matching policies once one containing AH is found.
VPN 3000 Concentrator may not successfully authenticate users that are externally authenticated with SDI to an RSA ACE Server when the number of retries for the SDI server is configured to 0 on the Concentrator.
In Configuration | User Management | Groups | Authentication Servers, "Retries" must be set to zero for the problem to occur.
The problem has been reported in Releases 3.5.5, 3.6.2 and 3.6.4 so far. The problem is confirmed NOT to be present in Release 3.5.2.
When the Concentrator has not yet received the Node Secret from the ACE, it also fails to install it.
On the ACE though, you see the messages "Passcode Accepted" and "Node Secret Sent" to the Concentrator.
When a default gateway is configured, the XML > export > outputs a "dummy" <Route> record with ip/netmask = "0.0.0.0". This issue occurs when using VPNSC download console to download configuration to the VPN 3000 Concentrator.
The VPN 3000 Concentrator does not take an empty string for the shared secret. This issue occurs when downloading a full configuration to the device.
LAN-to-LAN tunnels fail with Null encryption after having tunnelled with AES. LAN-to-LAN, which attempts to negotiate P1 = RSA Cert - SHA1 - AES256, P2 = MD5 - Null or SHA1 - Null, cannot be brought up. This happens only after a previous tunnel has come and gone, using AES.
During connection establishment, the VPN Concentrator received a framed IP netmask that was not consistent with the address pool defined on the VPN Concentrator. User authentication was via RADIUS, with address assignment being done via internal local pools. The netmask received from RADIUS is being acted upon and used in the computation for determining valid addresses to be issued from the local pool. When the broadcast address, based on the received netmask, was to be issued to an incoming client connection, the connection was rejected.
The VPN30xx Concentrator tries to interpret ISAKMP/IPSec packets that arrive on the Public interface even if those packets are not specifically destined for it. This occurs only when trying to build a new tunnel over an existing tunnel built with VPN30xx's.
The Group Delimiter feature is currently not working with a software VPN client. The groupname is not stripped off and the Concentrator tries to authenticate UsernameDelimiterGroupname instead of just Username.
You cannot use the HTML interface to set the IPSec Encryption to Null on the SA configuration page.
If you set it to Null, then click Apply, it reverts to the previous value.
You can set it to Null using the console CLI interface. It then appears on the web page as Null.
HTTP data does not cause a VPN 3002 Hardware Client to initiate a tunnel if cTCP is enabled. ICMP (ping) data does, however, cause the VPN 3002 to initiate the tunnel.
The VPN 3000 Concentrator sends larger DHCP release packets than RFC 2131 specifications. This causes the external DHCP server drop the packets with "Malformed packets" error messages. In turn, the IP addresses are exhausted in the external server, and nobody is then able to obtain IP addresses from the DHCP server.
The rollover text boxes do not appear over the SEP and SEP-E on the Monitoring | System Status screen when moving the cursor over the SEPs in the graphic. This works fine for Netscape 4.x and I.E. 5.x. It does not work for Netscape 6.2.1.
VPN Client connections using cTCP fail to connect after upgrading the client. Changes in the nature of the cTCP code on both the VPN Client and VPN 3000 Concentrator require a concerted upgrade in order to function properly.
To connect using cTCP, VPN Clients upgraded to Release 4.0 and higher require VPN 3000 Concentrator code Release 3.6.7.a and higher.
A VPN 3002 in split-tunneling mode does not pass ICMP error messages from the Internet back to the inside host. This may stop functions such as traceroute from working.
If you attempt to add an existing rule that has been used previously into an existing filter, then click Done, then the Save icon, you might see a crash. Instead of getting the OK box to confirm the save, you may be presented with the outline of the box, after which the Concentrator reboots itself and produces a crashdump.txt file.
Using the Microsoft L2TP/IPSec VPN Client v1.0 for Windows98 SE, the VPN 3000 Concentrator rekeying phase 2 SA drops the tunnel. When testing with 3.6.3, rekeying phase 2 SA generates a second IPSec session under Administration | Admin Sessions | Remote Access, but the tunnel is still working fine.
The VPN3000 is not properly supporting the IP NOP and EOL options. It might reject packets that contain these options. These options have a length of 1 and do not contain a length field.
The VRRP password fails to survive a reboot if the configuration file is encrypted using RC4. Everything works fine if "no encryption" or "DES" encryption is used to encrypt the file.
No connections are accepted when Concentrator reboot is scheduled. When a load balancing Concentrator is scheduled for a reboot, the Concentrator is switched to a secondary role. This causes a problem when all Concentrators in the cluster are scheduled for a reboot, because this leaves no Concentrator as the master.
An SNMPv2 trap generated by a Cisco VPN 3080 Concentrator does not contain the standard format sysUpTime.
A VPN Concentrator with VPN Group configured with Radius with Expiry and "Simultaneous Logins" set to "1" allows more than one connection.
SDI Servers go off line and do not recover. SDIN sockets remain open. This is a frequent but intermittent problem.
Any text When the MIB variable alSepModuleStatsSlotNum is queried on a VPN 3000 Concentrator with a SEP card, it returns a "No Such Instance" SNMP error.
Release 3.6.7 resolves the following issue:
A defect was introduced in the 3.6.6 Release of the VPN3000 Concentrator that causes the Concentrator to stop accepting new connections after 40 cumulative connection failures. On the 3005 & 3015 platforms, the threshold is 15 cumulative failures.
Once the cumulative failure total is hit, no more IKE requests are processed. Current sessions are not immediately affected, but are not be able to rekey. A system reboot is required to reset the cumulative counter.
Release 3.6.6 resolves the following caveats.
When using Quick Config on the VPN3002 to change IP address and enable DHCP, the user is locked out from management access as soon as the IP address is changed.
When you use the Monitoring Sessions screen or the Administer Sessions screen to configure a VPN 3000 Concentrator with a LAN-to-LAN tunnel to any device through the Private Interface, the tunnel shows up under the MANAGEMENT SESSIONS as VCA/IPSEC, rather than under the LAN-to-LAN Tunnels, as should be the case. The tunnel works fine, as expected.
Using the Mozilla 1.0 Web Browser to manage the VPN 3000 Concentrator, clicking any of the links always returns you to the login screen. Currently, the VPN 3000 Concentrator only fully supports Netscape and Internet Explorer.
The VPN 3000 Concentrator failed while freeing memory after telnet session was closed.
New Pin authentication works correctly when authenticating directly to RSA. If RADIUS is used as a proxy for RSA authentication, then new pin mode fails. This failure occurs when RSA's RADIUS server is used. There is no problem when a Cisco Secure ACS server is used.
When using Netscape 7.0 with the VPN 3000 Concentrator, after logging in and then trying to configure something, you are returned to the login screen.
For a VPN 3002 Hardware Client, v3.6 & v3.6.1, you can change PPPoE settings (for example, password) from Quick Configuration, but the changed setting cannot be saved. When you make the PPPoE change and return to the PPPoE setting screen, the Static IP Addressing is checked.
Changing PPPoE settings is not possible. However, if you change the PPPoE settings from Configuration -> Interface, then you have no problem changing the PPPoE setting.
The Linux Web browser Mozilla is not compatible with the VPN 3000 Concentrator or the VPN 3002 Hardware Client Web interface.
If an EZVPN Client does not properly disconnect its tunnel to a VPN3000 Concentrator, its IKE SA is not cleared from the Concentrator. The result is that each lingering IKE SA retains an address out of the address pool.
This occurs only if the Client connects without xauth authentication.
When using a Windows XP client connecting to a VPN 3000 Concentrator using split tunneling with EAP, the networks specified in your network list are not passed down and installed into the client computer.
The XML import did not accept an OSPF router ID of 0.0.0.0, even though OSPF was not enabled. This issue was found when downloading a full configuration to a device via an XML config file import.
The VPN3000 Concentrator might return fragments of Ethernet packet data within PPP reject messages. This behavior occurs only when a decryption error occurs. The reject message might contain data fragments from other Ethernet packets processed by the VPN 3000 Concentrator.
The VPN 3000 Concentrator failed when exporting XML file under File Management with L2L with Auto discovery configured.
The VPN 3000 Concentrator continually requests the node secret from the RSA server. These requests are considered as failed login attempts by the RSA server; therefore, the user's account is disabled. This problem occurs under the following conditions:
Release 3.6.5 resolves the following caveats.
A VPN 3000 Concentrator, upon a DHCP renewal, sends the request to the router's address instead of the IP address of the DHCP server.
Potential buffer overrun in MPPC decompression. MPPC decompression requires additional error handling.
A VPN 3000 Concentrator crashes when a new virtual interface is created for L2TP and PPTP connections.
This issue was introduced by the fix for CSCdv71158 (Disabling VRRP on a VPN 3000 Concentrator does not refresh the interface MAC address).
Release 3.6.4 resolves the following caveats.
Load Balancing Cluster Address should reply to pings for troubleshooting purposes.
When a VPN 3000 Concentrator is configured for redundancy (VRRP), and then the IP address of an interface is changed, and VRRP disabled afterwards, then the MAC address of the changed interface remains the VRRP address instead of changing to the physical MAC address.
To avoid this issue, disable VRRP before changing the IP address of an interface, and re-enable it afterwards.
If a default gateway is not defined on the VPN 3000 Concentrator, the following event is generated:
73 10/18/2001 11:53:52.430 SEV=4 IKE/2 RPT=13 82.171.0.5
Filter missing on interface 0, IKE data from Peer xx.xx.xx.xx dropped
This may not be the only thing that causes this event to be generated, but it is one of the scenarios.
If you create a rule with TCP port of 138 NetBIOS, then you save the rule, and then go back and in and view the rule, you will see that the rule has changed the port to TCP Port 137 NetBIOS Name Service.
AAA authentication for an admin account fails using TACACS+ if Simultaneous Logins in the Base Group is set to "0". It works fine if it is set to any positive number. The default is 3.
When a VPN Client (version 3.6) connects to a VPN 3000 Concentrator (running 3.6 code as well), using Entrust Entelligence (version 6.0) certificates, the username is not displayed under Administration | Administer Sessions and/or Monitoring | Sessions.
This behavior occurs only when using a certificate serial number with a name in the CN field. For example, CN=First Lastname + serial number...
If the CN field includes only the Name (without a serial number), the username is displayed correctly under Administration | Administer Sessions and/or Monitoring | Sessions.
Rare, intermittent VPN 3000 Concentrator failures without any patterns occur during IKE negotiation.
After upgrading VPN3000 Concentrator to release 3.6.3, tunnels do not negotiate to AES.
VPN Client logon to a VPN 3000 Concentrator running Release 3.6.1, using RADIUS for authentication, fails when the VPN 3000 Concentrator assigns the IP address, and the RADIUS server passes back a Framed-IP-Netmask of 255.255.255.255. The error message is:
"Bad refCnt (1) or invalid assigned ip address received (x.x.x.x)."
Hardware clients are able to connect. Local authentication works.
All address allocation is via static pools configured for each group, no addressing comes from the RADIUS server. Under 3.6.x, the user is phase2 authenticated, but then authentication fails.
Cisco VPN 3000 Concentrator can not connect with some third-party devices; for example: Furukawa Denko FITELnet-F40. The VPN 3000 Concentrator required that the third Aggressive mode packet be encrypted. In versions prior to 3.6.Rel, this was not required. The VPN 3000 Concentrator now accepts the third Aggressive mode packet, either encrypted or unencrypted.
Release 3.6.3 resolves the following issues:
SNMPv2 traps miss the standard snmpTrapOID.0 object.
The VPN Client might fail to connect to a load-balanced VPN 3000 Concentrator if it receives out-of-order packets from the VPN 3000 Concentrator.
With local authentication or split-tunneling enabled, a VPN 3002 stops passing voice traffic after about 9-15 hours of normal operation. All other traffic passes through without a problem.
In VPN 3000 Concentrator software, v3.5, the word "VPN" can not be used as group name. The tunnel fails to establish. There is no such problem in the v3.0 software. Any other name, even one using "Vpn" or a similar upper/lower case variant works.
Release 3.5.2/3.5.3 of the VPN 3000 Concentrator does not work with the NETWARE DHCP server. In 3.5.x, when the VPN 3000 Concentrator receives the same IP address from the DHCP server, it never sends the reject; it just fails the connection. On the other hand, in Release 3.02, when the VPN 3000 Concentrator receives the same IP for the second client, it sends a reject to the DHCP server and successfully retrieves a second, unique IP address.
When obtaining an IP address and DNS server attributes via PPPoE, the VPN 3002 might fail to resolve DNS host names, causing the VPN 3002 PING utility to fail, and IPSec VPN tunnels to fail to negotiate.
A view-only administrator session can lock the configuration on a VPN 3000 Concentrator, not allowing an administrator with authority to make a change for a certain time period. To avoid this issue, reboot the VPN 3000 Concentrator or locate the view-only session and log it off.
Maximum connect timeout value does not work.
After setting the maximum connect tim out value to 6 hours, the VPN Client connections do not terminate. They are seen to be live for more than 6 hours.
The maximum connect timeout applies only to each SA. This leads to the issue where SAs started at different times (for example, during split-tunneling) would prevent the connection from terminating. The connection terminates only when the last SA is torn down.
The code has been adjusted to reduce an SAs lifetime by the current uptime for the connection, so no new SAs are permitted after max connect is exceeded. This causes all SAs to expire at max connect.
The VPN 3002 might ignore some Cisco Discovery Protocol (CDP) messages because of checksum errors. The VPN 3002 uses the CDP messages to detect IP Phones on its private network.
This occurs because of an error in the checksum algorithm in the CDP packet with respect to odd length packets.
The error checksum algorithm is now part of the standard, so the VPN 3002 should be updated to this algorithm.
An HTTP 401 Unauthorized error appears on the console when trying to access the VPN 3000 Concentrator through a web browser using admin access, even when administrative rights are given to admin user.
The two events HTTP/9 and HTTP/10 might appear when a user connects to the login page. These are not errors but HTTP status information. As a result, their severity will be lowered from warning(3) to informational(5).
Automatic backup of log files through FTP is failing to a 3COM FTP/TFTP server. The resolution for caveat CSCdy20464 did not solve the problem. Customer is using 3COM 3CDAEMON version 2.0 release 10 and the FTP server is still rejecting the binary command.
IP Phone_a is talking to IP Phone_b. When IP Phone_a mutes the conversation, it stops transmitting packets as the codec goes into receive-only mode. IP Phone_b continues to transmit to IP Phone_a. However, after 5 seconds, IP Phone_b can no longer be heard at IP Phone_a, because the PIX firewall has stopped transmitting packets from the outside to inside interface, and this was caused by the TCP windows being exceeded.
The range displayed in the error message for IPSec SA Lifetime Time is wrong. It displays "IPSec Time Lifetime out of range. (10 - 2147483647)".
The range should be "IPSec Time Lifetime out of range. (60 - 2147483647)". It was displaying Lifetime KB range.
IKE rekey may fail if IKE rekey is set to 60 seconds.
In very rare situations, when connecting via HTTP or HTTPS (SSL) management session, LAN to LAN sessions and Remote Access Sessions are not displayed under Administration | Administer Sessions and/or Monitoring | Sessions. This appears to happen for sessions with SINGLE QUOTES (') in the name.
Telnet, SSH, or console connections successfully display the remote access and LAN to LAN sessions. Remove the SINGLE QUOTE (') from the site name.
With the Mac OS X IE browser, when looking at logged in users under the session management screen, 127.255.255.255 is seen instead of the correct IP address in some cases.
VPN Hardware Client 3002 with version 3.6 does not negotiate the correct MRU that is configured in the interface configuration. It always tries to adjust the MRU to 1492.
When a VPN 3002 is placed behind a PIX firewall with IPSec over TCP connection to a VPN 3000 Concentrator, we cannot bring the connection up once the VPN 3002 is rebooted.
This occurs because PIX firewall has an active TCP connection which was never reset; when the 3002 comes up it uses the same source and destination port number to make the new connection. The sequence number for the packets does not match the previously active connection, and PIX drops the packets. To avoid this issue, clear the connection on the PIX using the clear xlate command.
When users try to enroll a VPN 3000 Concentrator or VPN 3002 Hardware Client to a Verisign Onsite CA using a file-based method, the Verisign enrollment application complains about the PKCS10 request generated by the VPN 3000 concentrator (the error ID on Verisign enrollment page is 105).
The issue is reported only in versions 3.5.4 and 3.6. Downgrading the VPN 3000 Concentrator or VPN 3002 Hardware Client to a version earlier than 3.5.4 and enrolling to the CA works fine. After the enrollment, the VPN concentrators then can be upgraded to higher version if needed.
Internet Explorer does not display any remote access users in the admin or monitoring session tables if any user specifies a domain upon connecting.
The table is displayed in Netscape but the separating '\' is not displayed.
For example: User: test Domain: Lab.com
should be displayed in the table as Lab.com\test, but Netscape displays it as Lab.comtest.
The VPN 3000 Concentrator might fail with an out-of-memory error during heavy memory usage. During heavy memory usage, memory was not being properly freed.
The crashdump exhibits the following symptoms:
VPN 3000 Concentrator can fail with cTCP client and a large network list.
Cannot Set Access Session Timeout to 0, although the error message says that 0 is within the acceptable range.
The VPN 3000 Concentrator fails to install CA chains if any two of the certificates are identical in the first 4 bytes of their serial numbers.
Given the following setup:
NT PDC---vpn3k---Internet
When we configure a group with the same name as a domain username and then test the authentication against the NTPDC, it fails.
This is not a valid configuration. Users and groups cannot share common names.
CSCdy62382
When the administrator enters username/password after configuring TACACS authentication for Administrator access to the GUI, the VPN 3000 Concentrator fails.
This occurs if other TACACS attributes are assigned besides "priv-lvl".
A VPN 3000 Concentrator, renewing DHCP, sends the request to the broadcast address (255.255.255.255) instead of the IP address of the DHCP server.
In version 3.6, int_12, under session details (3060) for a remote access session (Hardware or software client), the Auth mode for the IKE session displays "other" when it should be "Preshared Keys - XAUTH". The session details under CLI correctly displays 'Pre-XTH.
Release 3.6.1 addresses multiple vulnerabilities for the VPN 3000 Series Concentrators and VPN 3002 Hardware Client. Please refer to the following URL for the details on the vulnerabilities addressed.
Release 3.6.1 contains the same fixes as Release 3.6, listed in the following section.
This section lists caveats resolved since Release 3.5. If you have an account on CCO you can check the status of any caveat by using Bug Navigator II.
To reach Bug Navigator II on CCO, choose Software & Support: Online Technical Support: Software Bug Toolkit or navigate to.
Packets coming through a tunnel from a client to a host on the public interface network exit through the Public Interface.
When using RADIUS authentication, if you are running RIP routing on the Private network, the NAS-IP-Address in the RADIUS Authentication is the IP address of the Private Interface on the Concentrator.
If you are running OSPF Routing on the Private network, the NAS-IP-Address in the RADIUS Authentication is the IP address of the Public Interface on the Concentrator.
If you are using OSPF, the NAS-IP-Address is set to the interface with the IP address that has the highest numeric value. For example, if the Private Interface of the VPN Concentrator has the IP address 192.168.10.1, and the Public interface has the IP address 193.111.20.8, the NAS-IP-Address is set to the public interface.
The phase 1 rekey interval is missing from session management on the VPN3000 series concentrator for Site-to-Site tunnels that are established against IOS devices, if the IOS Device initiates the tunnel.
Older versions of Netscape (v4.xx) might not properly display the session table from the Monitoring | Sessions link.
The session management tables might display slowly if there are thousands of users in the VPN Concentrator. HTML pages might take up to a minute or more to display. We are attempting to improve this performance prior to release.
Full bandwidth availability to a single user (bandwidth stealing) does not yet function to full capacity. User will only be given the amount of bandwidth reserved or policed in their policies.
The HTML management interface allows an administrator to enter an invalid Router address when configuring Static Routes. The administrator should verify addressing when entering Static Route information.
Full implementation of bandwidth management statistics has not been completed for this first beta release and should not be tested.
Bandwidth management statistics for a PPTP user are set to all zeros if bandwidth management is disabled.
Using Auto-initiate to connect the client before logging into a domain on Windows 95 may result in no VPN Client tray icon appearing (yellow padlock). The client is connected and can be launched from the start menu to view status or disconnect.
When sorting the session table from HTML management, the Web-browser sometimes stops responding if there are a lot of sessions in the table. (>1000) This behavior may require restarting the browser or, in rare instances, rebooting the management PC.
The concentrator may assert in memory.c line 554 during a very heavy load of calls connecting and disconnecting while using CRLs and doing a dial-hang test.It is unlikely that a beta site will see this unless the load on the box is very high.
In version 3.6.1, disabling DHCP Proxy from the following VPN Concentrator management page will also disable the Concentrators ability to retrieve an address off the network using DHCP.
Configuration | System | IP Routing | DHCP Proxy
If the Concentrator is using DHCP on any of its interfaces do not disable DHCP Proxy at this page. If DHCP Proxy must be disabled, simply uncheck the "Use DHCP" option form the Address Assignment page located at.
Configuration | System | Address Assignment | Assignment
A very heavy load of calls connecting and disconnecting while using CRLs and doing a dial-hang test might cause the Concentrator to fail. It is unlikely that a beta site will see this unless the load on the box is very high.
Starting and stopping FTP Proxy sessions over LAN-to-LAN-NAT tunnels may cause the VPN 3000 to reset, if using static and dynamic rules.
If you set the reserved bandwidth for a group equal to the link rate, the result is that no tunnels are established to the VPN Concentrator for that group.
Interface NAT rule configuration via CLI doesn't automatically disable FTP Proxy when disabling TCP Proxy. Use HTML to disable TCP/FTP Proxy.
The VPN concentrator reboots if an L2TP connection is attempted to the concentrator with Bandwidth management enabled.
When the sorting tabs are clicked on in admin/sessions, while both RAS and LAN-to-LAN sessions are being displayed, the LAN-to-LAN summaries table appears distorted. Specifically, the LAN-to-LAN entries lose the Bytes Received column and the "Action" entries are shifted two columns to the left.
HTML quick config allows the administrator to configure DHCP address pool assignment without specifying a DHCP server. This does not work, because DHCP broadcasts are not supported. All DHCP requests must be directed.
The session management tables may show very large summary statistics at the top of the html page after a reset of statistics followed by a refresh. The number is in the vicinity of 4.3 billion. This is due to the fact that the number of calls has gone down after resetting the counter to zero. We do not currently display negative numbers for current call count statistics, so negative numbers are erroneously being displayed as large positive numbers.
of the route; if more are configured they are not be sent.
Occasionally a client connects and cannot receive any data back from the concentrator. If you see this problem, it usually clears when the client disconnects and reconnects.
If you change the default pre-fragmentation setting on the public interface on the VPN Concentrator, pre-Release 3.6.1 clients (Unity and 3002) fail to pass large packets after a Phase 1 followed by a Phase II rekey. To correct this problem, disconnect and re-establish the tunnel.
The remote access session table is not properly displayed when using Netscape 4.78 or 6.2 and viewing the admin sessions table.
In Release 3.6.1, the VPN 3000 Concentrator software implementation changed the way that the VPN 3000 Concentrator sends its phase 1 ID. This ID consists of a bundle of information including IP address, protocol and port number. The change is that the port is now set to ZERO, whereas before, it was set to 500.
Technically, this is legal because it is up to the peer's policy to enforce whether a port=0 (ignore) is allowed.
Enabling bandwidth management with client tunnels already established is not supported in the Beta 2 release.
You may see the following message on the Concentrator console when a VPN client is attempting a connection:
"RMLogError: bad state=5/event=4 combination".
When a RADIUS server is configured to Authenticate a Group and return Group attributes, the VPN 3000 Concentrator does not check for illegal characters in the attribute "Split-DNS-Names". So, when configuring multiple Split-DNS-names in the RADIUS server, you must separate multiple names with a comma without any spaces or other illegal characters.
The Cisco VPN 3000 Series Concentrator documentation set has been revised for this release and is available online through Cisco.com. This section contains any changes and corrections to the documentation that occurred after the documentation was published.
The following documents require modifications, reflecting product changes, as noted in the following sections:
The method of attaching the feet to the VPN 3000 Series Concentrator has changed. The following illustrations replace those in Figure 2-3, page 2-7 of the VPN 3000 Series Concentrator Getting Started book, version 3.6.
The VPN 3000 Concentrator now supports syslog servers on both Windows and UNIX (Linux and Solaris) operating system platforms. In VPN 3000 Series Concentrator Reference Volume I: Configuration, Chapter 10, "Events," and in the corresponding online Help, the text and the screen captures refer to UNIX syslog servers. This restriction on the type of syslog server operating environment no longer exists.
Add the following text under Administration | Access Rights | Access Settings:
DES = Encrypt sensitive entries in the CONFIG file, using DES encryption. A CONFIG file that is encrypted with DES can be used only by the VPN Concentrator that encrypted it. This option prevents the sharing of encrypted configuration files across different VPN Concentrators.
In addition to these Release Notes, the following documents are new or have been updated for Release 3.6. They have not been changed for the subsequent "point" releases (such as 3.6.6):
For service and support for a product purchased from a reseller, contact the reseller, who offers a wide variety of Cisco service and support programs described in "Service and Support" in Cisco Information Packet shipped with your product.
For service and support for a product purchased directly from Cisco, use CCO.
The Cisco TAC home page includes technical tips and configuration information for the VPN 3000 Concentrator and client. Find this information at:..
This document is to be used in conjunction with the documents listed in the "Related Documentation" section.,403R)
|
http://www.cisco.com/en/US/products/hw/vpndevc/ps2284/prod_release_note09186a00801fc7a4.html#192439
|
crawl-003
|
refinedweb
| 15,388
| 55.44
|
find one string inside another
#include <string.h> size_t strspn( const char *str, const char *charset ); size_t _fstrspn( const char __far *str, const char __far *charset );
The strspn() function computes the length of the initial segment of the string pointed to by str that consists of characters from the string pointed to by charset. The terminating null character is not considered to be part of charset.
The _fstrspn() function is a data-model-independent form of the strspn() function that accepts far pointer arguments. It is most useful in mixed memory model applications.
The length of the segment.
#include <stdio.h> #include <string.h> void main() { printf( "%d\n", strspn( "out to lunch", "aeiou" ) ); printf( "%d\n", strspn( "out to lunch", "xyz" ) ); }
produces the output:
2 0
strcspn()
|
https://users.pja.edu.pl/~jms/qnx/help/watcom/clibref/src/strspn.html
|
CC-MAIN-2022-33
|
refinedweb
| 128
| 64.61
|
Replacing a Node with a New One
Replacing a Node with a New One
... node in a DOM document. JAXP (Java API for XML Processing) is an
interface which..., fchild):-This method replaces
a child node with another.
Xml code
Xml append node problem
to Node.
Output:
111 ---> <?xml version="1.0" ?><cwMin>31<... to append a new node.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><...Xml append node problem print("code sample");Question:
I create
Splitting One Text Node into Three
Splitting One Text Node into Three
...
into three new Node in a DOM document. Methods which are used for splitting... paragraph = (Element) root.getFirstChild():-creates
a new node named paragraph
Java--Xml Modify Node Value - Java Beginners
Java--Xml Modify Node Value I have the following xml.
test...,
Updating xml node is not sufficient to update that xml. You need to prepare whole xml again after updating the node. Use the following method to update xml
Creates element node, attribute node, comment node, processing instruction and a CDATA section
for the node
Xml code for the program generated is:-
<...
Creates element node, attribute node,
comment node, processing...;
This Example shows you how to Create an Element node ,Comment node
Spliting Large XML and one by one Moved to Output Folder
Spliting Large XML and one by one Moved to Output Folder How to Spliting Large XML and one by one Moved to Output Folder
Java get Node Text
of the node in the
specified XML file. For this we have create a 'employee.xml' file...;employee.xml".In order to get the text of the node specified in a XML
file, we... of
GetNodeText.java you get the text of the node specified in
"employee.xml" xml
Java get Node Value
Java get Node Value
In this section, you will learn how to obtain the node value. Before any
further processing, you need a XML file. For this we have create
input output
instance for the output object passed as parameter
InputStream in = new... Input And Output
Introduction
The Java I/O means Java Input/Output and is a part
Insert a Processing Instruction and a Comment Node
a Processing Node
and Comment Node in a DOM document. JAXP (Java API for XML...;close".
root.insertBefore(instruction, node):- This method
inserts a new child node before an existing child node. Here new node is
instruction and existing
Output of this one - Java Interview Questions
Output of this one
public class Test {
int i=-277;
{
try... declared wrong condition in if statement. Therefore it gives number of compile time errors.
The following code displays "Executed" as an output.
public class
Java Xml -Node retrieval - Java Beginners
Java Xml -Node retrieval I have the following xml
test_final_1
2009-025T13:23:45
B2B
In the above xml,I want to retrieve... = DocumentBuilderFactory.newInstance();
File xmlFile2 = new File("D:\\XML_Utility\\Version 11
Java-Xml -Modify and Update Node - Java Beginners
();
System.out.println("XML Data: ");
DefaultHandler dHandler = new...Java-Xml -Modify and Update Node
test_final_1
2009-025T13:23... date=new Date();
public static void main(String[] args) throws IOException
Locate a Node and Change Its Content
of a
node in a DOM document. JAXP (Java API for XML Processing) is an interface... of this node.
Xml code for the program generated is:-
<?xml version="... Locate a Node and Change Its
Content
Creating a Preference Node
Creating a Preference Node
This section demonstrates you to create a Preference Node... Node and System
Preference Node. Here we are going to create a user preference
xml output
xml output generate an xml output in the following format
<FileCount>
<DOC>AA
<RTF>BB
<PDF>CC
<Total>DD
where AA=total number of .DOC files found
BB=total number of .RTF files found,etc
Read XML in java - XML
nodeValue=getElementValue(node);
StringBuffer buffer = new StringBuffer...Read XML in java Hi Deepak, I want to read a xml file which have only one element with multiple attributes with same tag name.
here is my file
output
output Sir,I am experiencing some problems with the output of this program.I got some useful help this website,but the output of the program isn't producing what it should.let me explain the output below is what happen when
Input And Output
for the output object passed as parameter
InputStream in = new FileInputStream(f1...
Input And Output
Introduction
The Java I/O means Java Input/Output and is a part of java.io
Determining If a Preference Node Exists
emits the
xml document representing the node and its descendents.
Here...
Determining If a Preference Node Exists
... Preference node
exists or not.
A preference node can be created automatically
DOM Example For Creating a Child Node
about how to add a Child Node in Dom
document.
The addition of child node is a very logical. To add a child node first
we create blank DOM document and then we create the root node using createElement()
method . This root node
JTree Remove Node
, it
will take node name (New Volume (E:)) in the input box and click the
"OK"... Removing a Node from the JTree Component
... to remove a node
from the JTree component. Removing a node from JTree it means
Node class
Node class hii,
What is a node class?
hello,
A node class is a class that has added new services or functionality beyond the services inherited from its base class
XML Tutorials
;
Replacing a Node with a New One
This Example shows you how to Replace....
Replacing a Text Node with a New... parsing of xml documents. Here the Document BuilderFactory is used to create new DOM
Locating a Node by Using Siblings
the next sibling of this node & gets its name also.
Xml code for the program... Locating a Node by Using Siblings
This Example describes a method to Locate a node by
using
Wrapping, replacing, and removing content
Wrapping, replacing, and removing content
Wrapping, replacing, and removing content
The JQuery provide efficient ways for wrapping, replacing, and removing
JPA One-to-One Relationship
JPA One-to-One Relationship
... will learn about the one-to-one
relationship. In the one-to-one relation mapping a single value association
to another entity.
One-to-One: In one-to-one
Delete the First Child of the Root Node
.
root.removeChild():-This method removes the Child node.
Xml code... Delete the First Child of the Root Node
...
child of the Root node .Methods which are used for Deleting the child
counting the values in input file and and writing the output to a file
= new PrintWriter(fw);
String line = "";
int i = 0, j= 0, one=0, two=0,three=0...counting the values in input file and and writing the output to a file Can any one please correct this code. This is to read a file and later
what is wrong with this program
what is wrong with this program import java.io.*;
class Distance...
{
DataInputStream ob = new DataInputStream(System.in);
Distance d1 = new Distance();
Distance d2 = new Distance();
Distance d3 = new Distance
xml - XML
");
FileOutputStream output = new FileOutputStream("new.xml");
ReadXML xml = new ReadXML();
xml.convert(input, output);
System.out.println("XML File...xml hi
convert xml file to xml string in java ,after getting
What is wrong with my servlet?
What is wrong with my servlet? I'd like to know which part of the code is wrong.
My code is:
print("code sample");
import java.util.*;
import...");
int d = (new Integer(del)).intValue
what is wrong in this program
what is wrong in this program import java.io.*;
class Distance... ob = new DataInputStream(System.in);
Distance d1 = new Distance();
Distance d2 = new Distance();
Distance d3 = new Distance();
d1.read
what is wrong in this program......
what is wrong in this program...... program to implement given...;
DataInputStream ob = new DataInputStream(System.in);
void getRoll...[])
throws IOException
{
Result obj=new Result();
obj.getRoll
i want to remove specific node in xml file
i want to remove specific node in xml file
<A>
<B>hi
<C>by
<A>
<B>hellow
<C>how r u ?
i want to delet node which is == hellow using java program please help me .
tanks in advance
Inserting a New Entry in a List
Inserting a New Entry in a List
This Example shows you how to Insert a new Entry in a
list in a DOM document. JAXP (Java API for XML Processing) is an interface
which
Listening for Changes to Preference Values in a Preference Node
emits an XML document
representing all the preferences contained in the node...
Listening for Changes to Preference Values in a Preference Node... to change the Preference values in a Preference
node. You can see in the given
new
new @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
<%@page contentType... {
/*
* TODO output your page here. You may use following sample code... {
/*
* TODO output your page here. You may use following sample code
XSLT Output Types
plain text using the above line in xslt document.
XML
<xsl:output
XSLT can be used to output XML using the above line...;
}
Output Types
The xsl:output element lets you specify how to generate result
Creates a New DOM Parse Tree
Creates a New DOM Parse Tree
This Example describes a method to create a new DOM
tree .Methods which are used for making a new DOM parse tree are described below
:-
Element
Parsing XML using Document Builder factory - XML
Parsing XML using Document Builder factory Hi ,
I am new to XML . I am trying to parse a XML file while is :
For this i am using Document... org.w3c.dom import Node
from org.w3c.dom import NodeList
nodeList
XML Parsers
for that language).
The DOM presents an XML document as a tree-structure
(a node tree.... This
makes easier to modify the data, to remove it, or even to insert a new one... the parser encounters a new XML
tag or encounters an error, or wants
Appending and replacing string using regular expression
Appending and replacing string using regular expression... to append the String with the existing one using
expression. For this we are going...;}
}
Output of the program:-
Text before replacement
again with xml - XML
again with xml hi all
i am a beginner in xml so pls give me...{
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a XML file name: ");
String xmlFile = buff.readLine with JAVA - XML
a particular node within XML document" .
Explanation of program:- input must be in XML document and the processing in JAVA program . Find the time for each XML element...XML with JAVA Hi..
This is Priya here. Thanks for responding me. I
Retrieving a Preference Node
Retrieving a Preference Node
This section demonstrates you to retrieve a Preference node. You... the
Preference node. The absolute paths begin with '/'. The method name() returns
Sorting Xml file - XML
Sorting Xml file I have an xml file like this:
Smith
USA... sort my xml file. Here is my xslt.
And the output is like this:
Smith
USA
Bob
USA
John
UK
Smith
SG
Amy
A
xml developing - XML
'magnate-williams-1234] ) for new attached file.
for life cycle of my xml, i...xml developing I want to develop XML document with following DTD file with XML format. I have also XSL file as a externatl file to represent my xml
how to write in xml? - XML
(new InputStreamReader(System.in));
System.out.print("Enter XML file name...().newTransformer();
// Output Types (text/xml/html...
Source source = new DOMSource(doc);
// Create File to view your xml
Convert Text To XML
the root and child node into xml file. Pass array string as value of nodes...
Convert Text To XML
Here we are discussing the conversion of a text
file into xml
java and xml problem - XML
xml tree
StringWriter sw = new StringWriter...java and xml problem hi, i need to write a java program that generates an xml file as follows:
aaa
vvv
Exporting the User Type Preferences in a Subtree of Preference Node
<root type="user">
<node name...
Exporting the User Type Preferences in a Subtree of Preference Node... of the user as root type="user" after that it display
the node name Elements
it by adding one more tag ie..<Subject>in
the xml document. So the new modified... an application to fetch
data from the above XML document and produce this output...;
Now the new generated output will look like this
E
NEW IN JAVA - Java Beginners
NEW IN JAVA Suppose you are asked to design a software tool.... The student chooses from a menu one of five arithmetic operations: 1) addition,
2... with exactly 10 questions. For each
question, two random positive one-digit integers
how to edit xml file which is currently running in web server - XML
how to edit xml file which is currently running in web server Hello,
I want to add new element in xml file which is currently running in my web....");
}
// Output the XML to file
TransformerFactory
JavaScript XML Parser
JavaScript XML Parser
... to access and manipulate XML document
using DOM parser in javascript.
XML parser reads and loads the xml into computer memory and converts it into DOM object
JavaScript XML to HTML
node, we display data from the
XML elements name and address as table data...
JavaScript XML to HTML
... to display the XML data into HTML
table.
As you have already learned how
creating tables as an xml document - XML
");
// create string from xml tree
StringWriter sw = new StringWriter...creating tables as an xml document Create a table of a medal tally of the Olympic Games as an XML document. The table must have the name
output error
output error this is my program
import java.io.*;
public class...
{
BufferedReader keyin=new BufferedReader(new InputStreamReader(System.in... len=x.length();
int k;int j=0;
String l[]=new String[len
readXML - XML
readXML hiii i face problems in reading a xml file.. pixvalue1path1...) throws Exception
{
String[] imgId=new String[kyid.length];
ArrayList imageId = new ArrayList();
int cnt=-1;
try
What is the output if....
What is the output if.... Here is my code. what is the output....");
if (lowerLimit < 100)
throw new Exception("Lower limit violation...");
When we put 50 as a lower limit value, output comes:
Entering
XML: An Introduction
a one-piece
document.
How Can You Use XML?
Few Applications of XML
Although...
XML: An Introduction
What is XML?
"XML is a cross-platform, software and
hardware
what is the output?
what is the output? public class MyAr{
public static void main(String argv[])
{
int[] i=new int[5];
System.out.println(i[5]);
}
}
...[]) {
int[] i=new int[5];
i[0]=1;
i[1]=2;
i[2]=3
Removing Line Termination Characters from a String
is mentioned by the
user and replacing all the new line character by the double quote with one space
(" ") wherever it found. When the program shows the string as output
in the console, you will understand where the new line
what will the output
called Sonu is typecast to Parent class as below.
Child sonu = new Child();
Parent p = (Parent) sonu;
p.play();
What will be the output of above section of code
While loop break causing unwanted output
it will output that I was correct but after that it will output something that I'm... numc;
int counter = 0;
Scanner job = new Scanner(System.in...){
System.out.println("You are wrong");
counter = numc;
}else
Java XML modification
Java XML modification
This section explain you how to modify the xml file..., DocumentBuilder and Document classes to get the default DOM parser and parse the xml file. Then call the function delNode() that finds the specified node from the node
JPA One-to-Many Relationship
JPA One-to-Many Relationship
... the one-to-many
relationship and how to develop a one-to-many relation in your JPA
Application.
One-to-Many: In this relationship each record in
Table-A may have
XML
XML please tell me how i remove one tag out of all similar type of tags in xml
JPA Many-to-one Relationship
JPA Many-to-one Relationship
... about the many-to-one
relationship and how to develop a many-to-one relation in your JPA Application.
Many-to-One: In this relationship many related
records
input output
) throws Exception {
FileInputStream in = new FileInputStream("c:/hello.txt");
FileOutputStream out = new FileOutputStream("C:/data.txt");
int c
XML Interviews Question page30,xml Interviews Guide,xml Interviews
exam simulator gave wrong answer on this one. Typing them out also help me to remember them. xlink:actuate onRequest, onLoad, other, none xlink:show replace new...
XML Interviews Question page30
Testing EntityReferences in Xml
)):-Creates a new StreamReader which allows forward, read-only access to XML... Testing EntityReferences in Xml
... in an XML file. JAXP (Java
API for XML Processing) is an interface which provides
What's wrong with my form? - Java Beginners
What's wrong with my form? Dear expert,
I'm having trouble....
Here's my jsp code:
Enquiries
var objForm = new Object();
var strName = new Object();
var strEmail = new Object();
var
Hibernate One-to-many Relationships
Hibernate One-to-many Relationships
Hibernate One-to-many Relationships - One to many example code in
Hibernate using the xml file as metadata.
Here
JavaScript insertBefore method
, referenceElement);
where newElement is the new element node which...;
In this section you will see that how we can insert new node or element
before the referenced node as a child node of the current node
Hibernate One to One Mapping using XML
In this section, you will learn One to One mapping of table in Hibernate using Xml
according to me its ok but is calculating wrong values in
according to me its ok but is calculating wrong values in program to calculate roman numbers .....i.e roman number calculator
import java.util....;
Scanner input=new Scanner(System.in);
System.out.print
Convert Object To XML
into xml file as child node values. Convert Object To XMLTo create a xml file pass...
Convert Object To XML
Here we are discussing the conversion of an object
into xml
JavaScript XML Http Request
contains the server response which allows to display the node values of XML
file...
JavaScript XML Http Request
... how to access XML file with an XMLHTTP object
using JavaScript
|
http://www.roseindia.net/tutorialhelp/comment/100242
|
CC-MAIN-2014-52
|
refinedweb
| 3,047
| 65.93
|
curl_easy_setopt(3) libcurl Manual curl_easy_setopt‐ tion uses many curl_easy_setopt() calls in the setup phase. Options set with this function call are valid for all forthcoming transfers performed using this handle. The options are not in any way reset between transfers, so if you want subsequent transfers with dif‐‐‐ ally have headers preceding the data (like HTTP). CURLOPT_NOPROGRESS Pass a long. If set to 1, it tells the library to shut off the progress meter completely. It will also prevent the CURLOPT_PRO‐ GRESSFUNCTION from getting called. stan‐ dard name resolver, timeouts will not occur while the name resolve takes place. Consider building libcurl with c-ares sup‐ port to enable asynchronous DNS lookups, which enables nice timeouts for name resolves without signals. Setting CURLOPT_NOSIGNAL to 1 makes libcurl NOT ask the system to ignore SIGPIPE signals, which otherwise are sent by the sys‐ tem sig‐ nal to be raised. imple‐ mentation. con‐ structed:[a-z[:upper:]\\].jpeg (This was added in 7.21.0) CALLBACK OPTIONS CURLOPT_WRITEFUNCTION Pass a pointer to a function that matches the following proto‐ type: size_t function( char ‐ ferred body data that can be passed to the write callback is defined in the curl.h header file: CURL_MAX_WRITE_SIZE (the usual default is 16K). If you however have CURLOPT_HEADER set, which sends header data to the write callback, you can get up to CURL_MAX_HTTP_HEADER bytes of header data passed into it. This usually means 100K.‐ LOPT_WRITEFUNCTION if you set this option or you will experience crashes. This option is also known with the older name CURLOPT_FILE, the name CURLOPT_WRITEDATA was introduced in 7.9.7. CURLOPT_READFUNCTION Pass a pointer to a function that matches the following proto‐ type:‐ DATA.‐ LOPT_READFUNCTION if you set this option. This option was also known by the older name CURLOPT_INFILE, the name CURLOPT_READDATA was introduced in 7.9.7. CURLOPT_IOCTLFUNCTION Pass a pointer to a function that matches the following proto‐ type: curlioerr function(CURL *handle, int cmd, void *clientp);. neces‐ sary when doing a HTTP PUT or POST with a multi-pass authentica‐ tion‐ FUNCTION. (Option added in 7.12.3) CURLOPT_SEEKFUNCTION Pass a pointer to a function that matches the following proto‐ type: int function(void *instream, curl_off_t offset, int ori‐ gin); lat‐ ter seek function. If you use the CURLOPT_SEEKFUNCTION option, this is the pointer you'll get as input. If you don't specify a seek callback, NULL is passed. (Option added in 7.18.0) CURLOPT_SOCKOPTFUNCTION Pass a pointer to a function that matches the following proto‐ type: int function(void *clientp, curl_socket_t curlfd, curl‐ socktype purpose);. This function gets called by libcurl after the socket() call but before the connect() call. The callback's purpose argument identifies the exact purpose for this particu‐ lar. It passes the newly created socket descriptor so additional setsockopt() calls can be done at the user's discretion. Return 0 (zero) from the callback on success. Return 1 from the callback func‐ tion to signal an unrecoverable error to the library and it will close the socket and return CURLE_COULDNT_CONNECT. (Option added in 7.16.0) Added in 7.21.5, the callback function may return CURL_SOCK‐ OPT_ALREADY_CONNECTED, which tells libcurl that the socket is in fact already connected and then libcurl will not attempt to con‐ nect it. CURLOPT_SOCKOPTDATA Pass a pointer that will be untouched by libcurl and passed as the first argument in the sockopt callback set with CUR‐ LOPT_SOCKOPTFUNCTION. (Option added in 7.16.0) CURLOPT_OPENSOCKETFUNCTION Pass a pointer to a function that matches the following proto‐ type: curl_socket_t function(void *clientp, curlsocktype pur‐ pose, struct curl_sockaddr *address);. This function gets called by libcurl instead of the socket(2) call. The callback's purpose argument identifies the exact purpose for this particular socket: CURLSOCKTYPE_IPCXN is for IP based connections. Future versions of libcurl may support more purposes. It passes the resolved peer address as a address argument so the callback can modify the address or refuse to connect at all. The callback function should return the socket or CURL_SOCKET_BAD in case no connection could be established or another error was‐ LOPT_OPENSOCKETFUNCTION. (Option added in 7.17.1.) CURLOPT_CLOSESOCKETFUNCTION Pass a pointer to a function that matches the following proto‐ type: int function(void *clientp, curl_socket_t item);. This function gets called by libcurl instead of the close(3) or clos‐ esocket(3) call when sockets are closed (not for any other file descriptors). This is pretty much the reverse to the CUR‐ LOPT_OPENSOCKETFUNCTION option. Return 0 to signal success and 1 if there was an error. (Option added in 7.21.7) CURLOPT_CLOSESOCKETDATA Pass a pointer that will be untouched by libcurl and passed as the first argument in the closesocket callback set with CUR‐ LOPT_CLOSESOCKETFUNCTION. (Option added in 7.21.7) CURLOPT_PROGRESSFUNCTION Pass a pointer to a function that matches the following proto‐ type: int function(void *clientp, double dltotal, double dlnow, double ultotal, double ulnow); . This function gets called by libcurl instead of its internal equivalent with a frequent interval during operation (roughly once per second or sooner) no matter if data is being transferred actu‐ ally get called. CURLOPT_PROGRESSDATA Pass a pointer that will be untouched by libcurl and passed as the first argument in the progress callback set with CUR‐ LOPT_PROGRESSFUNCTION. CURLOPT_HEADERFUNCTION Pass a pointer to a function that matches the following proto‐ type: is very easy using this. The size of the data pointed to by ptr is size multiplied with nmemb. Do not assume that the header line is zero termi‐ nated! The pointer named userdata is the one you set with the CURLOPT_WRITEHEADER option. The callback function must return the number of bytes actually taken care of. If that amount dif‐ fers from the amount passed to your function, it'll signal an error to the library. This will abort the transfer and return CURL_WRITE_ERROR. A complete HTTP header that is passed to this function can be up to CURL_MAX_HTTP_HEADER (100K) bytes. If this option is not set, or if it is set to NULL, but CUR‐ LOPT_HEADERDATA (CURLOPT_WRITEHEADER) is set to anything but NULL, the function used to accept response data will be used instead. That is, it will be the function specified with CUR‐ func‐ tion will get called with the server responses to the commands that libcurl sends. CURLOPT_WRITEHEADER (This option is also known as CURLOPT_HEADERDATA) Pass a pointer to be used to write the header part of the received data to. If you don't use CURLOPT_WRITEFUNCTION or CURLOPT_HEADERFUNCTION to take care of the writing, this must be a valid FILE * as the internal default will then be a plain fwrite(). See also the CURLOPT_HEADERFUNCTION option above on how to set a custom get- all-headers callback. CURLOPT_DEBUGFUNCTION Pass a pointer to a function that matches the following proto‐ type:‐‐ ality is absent. Pass a pointer to a function that matches the following proto‐ type: CURLcode sslctxfun(CURL *curl, void *sslctx, void *parm); This function gets called by libcurl just before the initializa‐ tion of a SSL connection after having processed all other SSL related options to give a last chance to an application to mod‐‐ Pass a pointer to a function that matches the following proto‐ type:‐‐‐ ent on your system. CURLOPT_INTERLEAVEFUNCTION Pass a pointer to a function that matches the following proto‐ type:‐ leaved header as well as the included data for each call. The first byte is always an ASCII dollar sign. The dollar sign is followed by a one byte channel identifier and then a 2 byte integer length in network byte order. See RFC2326 Section 10.12 for more information on how RTP interleaving behaves. If unset or set to NULL, curl will use the default write function. Interleaved RTP poses some challenges for the client applica‐ tion. Since the stream data is sharing the RTSP control connec‐ tion, it is critical to service the RTP in a timely fashion. If the RTP data is not handled quickly, subsequent response pro‐ cessing CUR‐ LOPT_INTERLEAVEFUNCTION when interleaved RTP data is received. (Added in 7.20.0) CURLOPT_CHUNK_BGN_FUNCTION Pass a pointer to a function that matches the following proto‐ type: long function (const void *transfer_info, void *ptr, int remains). This function gets called by libcurl before a part of the stream is going to be transferred (if the transfer supports chunks). This callback makes sense only when using the CURLOPT_WILDCARD‐ MATCH Pass a pointer to a function that matches the following proto‐ type: Pass a pointer to a function that matches the following proto‐ type: read‐ must‐ ately afterwards. NETWORK OPTIONS CURLOPT_URL Pass in a pointer to the actual URL to deal with. The parameter should be a char * to a zero terminated string which must be URL-encoded in the following format: scheme://host:port/path For a greater explanation of the format please see RFC3986. If the given URL lacks the scheme, or protocol, part ("http://" or "ftp://" etc), libcurl will attempt to resolve which protocol to use based on the given host mame. If the protocol is not sup‐ ported, libcurl will return (CURLE_UNSUPPORTED_PROTOCOL) when you call curl_easy_perform(3) or curl_multi_perform(3). Use curl_version_info(3) repre‐ sented.example.com The port is optional and when not specified libcurl will use the default port based on the determined or specified protocol: 80 for HTTP, 21 for FTP and 25 for SMTP, etc. The following exam‐ ples con‐ figuration. - speci‐ fied. user‐ name com‐ puter's host name. However, this may not return the fully quali‐ fied domain name that is required by some mail servers and spec‐ ifying this path allows you to set an alternative name, such as your machine's fully qualified domain name, which you might have obtained from an external function such as gethostname or getad‐ dr mailbox (message) to retrieve. If the mailbox is not specified then a list of waiting messages is returned instead. pop3://user:password@mail.example.com - This lists the available messages pop3://user:password@mail.example.com/1 - This retrieves the first message‐ PWD or CURLOPT_USERNAME speci‐ fied. or CURLOPT_USERNAME option. s - This specifies the file /etc/issue s - This specifies the file my- file in the user's home directory s - This requests a directory listing of the Documents directory under the user's home direc‐ tory LDAP The path part of a LDAP request can be used to specify the: Dis‐ tinguished speci‐ fies an empty DN and requests information about the rootDomain‐ NamingContext attribute for an Active Directory server. For more information about the individual components of a LDAP URL please see RFC4516. NOTES Starting with version 7.20.0, the fragment part of the URI will not be sent as part of the path, which was previously the case.‐ COLS. LO‐ CATION sepa‐ rate‐ LOPT_PROXY option does however override any possibly set envi‐ ronment variables. Setting the proxy string to "" (an empty string) will explicitly disable the use of a proxy, even if there is an environment variable set for it. Since 7.14.1, the proxy host string given in environment vari‐ ables can be specified the exact same way as the proxy can be set with CURLOPT_PROXY, include protocol prefix (http://) and embedded user + password. Since 7.21.7, the proxy string may be specified with a proto‐ col:// prefix to specify alternative proxy protocols. Use socks4://, socks4a://, socks5:// or socks5h:// (the last one to enable socks5 and asking the proxy to do the resolving, also known as CURLPROXY_SOCKS5_HOSTNAME type) to request the specific SOCKS version to be used. No protocol specified, http:// and all others will be treated as HTTP proxies..10), CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A (added in 7.18.0) and CURLPROXY_SOCKS5_HOST‐ NAME con‐ trolled with CURLOPT_HTTP_VERSION. CURLOPT_NOPROXY Pass a pointer to a zero terminated string. The string consists of a comma separated list of host names that do not require a proxy to get reached, even if one is specified. The only wild‐ card available is a single * character, which matches all hosts, and effectively disables the proxy. Each name in this list is matched as either a domain which contains the hostname, or the hostname itself. For example, example.com would match exam‐ ple.com, example ref‐ erence. Starting with 7.24.0: syn‐ chronously. Using the if! format is highly recommended when using the multi interfaces to avoid allowing the code to block. If "if!" is specified but the parameter does not match an exist‐ ing interface, CURLE_INTERFACE_FAILED is returned. CURLOPT_LOCALPORT Pass a long. This sets the local port number of the socket used for connection. This can be used in combination with CUR‐ LOPT_INTERFACE and you are recommended to use CURLOPT_LOCALPOR‐ TRANGE as well when this is set. Valid port numbers are 1 - 65535. (Added in 7.15.2) CURLOPT_LOCALPORTRANGE Pass a long. This is the number of attempts libcurl will make to find a working local port number. It starts with the given CUR‐ LOPT_LOCALPORT and adds one to the number for each retry. Set‐ ting this to 1 or below will make libcurl do only one try for the exact port number. Port numbers by nature are scarce resources that will be busy at times so setting this value to something too low might cause unnecessary connection setup fail‐ ures. ‐ is to be set or cleared (1 = set, 0 = clear). The option is cleared by default. This will have no effect after the connection has been established. Setting this option will disable TCP's Nagle algorithm. The pur‐‐ tion on the network if overdone. CURLOPT_ADDRESS_SCOPE Pass a long specifying the scope_id value to use when connecting to IPv6 link-local or site-local addresses. (Added in 7.19.0) CURLOPT_TCP_KEEPALIVE (Added in 7.25.0). CURLOPT_TCP_KEEPIDLE Pass a long. Sets the delay, in seconds, that the operating sys‐ tem will wait while the connection is idle before sending keepalive probes. Not all operating systems support this option. (Added in 7.25.0) CURLOPT_TCP_KEEPINTVL Pass a long. Sets the interval, in seconds, that the operating system will wait between sending keepalive probes. Not all oper‐ ating systems support this option. (Added in 7.25‐‐ mation cur‐ rent user's home directory. (Added in 7.10.9) CURLOPT_USERPWD Pass a char * as parameter, which should be [user name]:[pass‐‐‐ tal information leakage. CURLOPT_PROXYUSERPWD Pass a char * as parameter, which should be [user name]:[pass‐ word] to use for the connection to the HTTP proxy. Use CUR‐‐ L_PROX‐ Y sup‐ ported virtually everywhere. This sends the user name and password over the network in plain text, easily captured by others. CURLAUTH_DIGEST HTTP Digest authentication. Digest authentication is defined in RFC2617 and is a more secure way to do authen‐ tication over public networks than the regular old-fash‐ ioned Basic method. CURLAUTH_DIGEST_IE HTTP Digest authentication with an IE flavor. Digest authentication is defined in RFC2617 and is a more secure way to do authentication over public networks than the regular old-fashioned Basic method. The IE flavor is sim‐. CURLAUTH_NTLM_WB NTLM delegating to winbind helper. Authentication is per‐ formed by a separate binary application that is executed when needed. The name of the application is specified at compile time but is typically /usr/bin/ntlm_auth (Added in 7.22.0) applica‐ tion. In particular, the application must not uncondi‐ tionally call wait() in its SIGCHLD signal handler to avoid being subject to a race condition. This behavior is subject to change in future versions of libcurl. sin‐ gle specific auth value to force libcurl to probe for un- restricted auth and if not, only that single auth algo‐ rithm authenti‐ cation for TLS is defined in RFC50 ter‐ minated username to use for the TLS authentication method speci‐ fied with the CURLOPT_TLSAUTH_TYPE option. Requires that the CURLOPT_TLS_PASSWORD option also be set. (Added in 7.21.4) CURLOPT_TLSAUTH_PASSWORD Pass a char * as parameter, which should point to the zero ter‐ minated password to use for the TLS authentication method speci‐ fied‐ cial file lib/README.encoding for details. (This option was called CURLOPT_ENCODING before 7.21.6) CURLOPT_TRANSFER_ENCODING automati‐ cally follow. The accepted protocols are set with CUR‐ LOPT_REDIR_PROTOCOLS and it excludes the FILE protocol by default. CURLOPT_UNRESTRICTED_AUTH A parameter set to 1 tells the library it can continue to send authentication (user+password) when following locations, even when hostname changed. This option is meaningful only when set‐ ting, 302 or 303 response back. A parameter with bit 0 set (value CURL_REDIR_POST_301) tells the library to respect RFC2616/10.3.2 conve‐ nience CUR‐ LOPT_FOLLOWLOCATION. (Added in 7.17.1) (This option was known as CURLOPT_POST301 up to 7.19.0 as it only supported the 301 then) CURLOPT_PUT A parameter set to 1 tells the library to use HTTP PUT to trans‐ fer data. The data should be set with CURLOPT_READDATA and CUR‐‐ LOPT_POSTFIELDSIZE_LARGE to set the data size. Optionally, you can provide data to POST using the CURLOPT_READ‐ FUNCTION and CURLOPT_READDATA options but then you must make sure to not set CURLOPT_POSTFIELDS to anything but NULL. When providing data with a callback, you must transmit it using chun‐‐ ting your own with CURLOPT_HTTPHEADER. Using POST with HTTP 1.1 implies the use of a "Expect: 100-con‐ tinue" header. You can disable this header with CURLOPT_HTTP‐ HEADER CUR‐ L conse‐‐ LOPT_POSTFIELDSIZE explicitly to zero, as simply setting CUR‐ LOPT_POSTFIELDS to NULL or "" just effectively disables the sending of the specified string. libcurl will instead assume that you'll send the POST data using the read callback! Using POST with HTTP 1.1 implies the use of a "Expect: 100-con‐ tinue" header. You can disable this header with CURLOPT_HTTP‐‐ sion of the CURLOPT_POSTFIELDSIZE option. (Added in 7.11.1) CURLOPT_COPYPOSTFIELDS Pass a char * as parameter, which should be the full data to post in a HTTP POST operation. It behaves as the CURLOPT_POST‐ FIELDS option, but the original data are copied by the library, allowing the application to overwrite the original data after setting this option. Because data are copied, care must be taken when using this option in conjunction with CURLOPT_POSTFIELDSIZE or CUR‐ LOPT_POSTFIELDSIZE_LARGE: If the size has not been set prior to CURLOPT_COPYPOSTFIELDS, the data are assumed to be a NUL-termi‐ nated string; else the stored size informs the library about the data byte count to copy. In any case, the size must not be changed after CURLOPT_COPYPOSTFIELDS, unless another CUR‐ L-con‐ tinue" header. You can disable this header with CURLOPT_HTTP‐ HEADER as usual. When setting CURLOPT_HTTPPOST, it will automatically set CUR‐‐‐ CUR‐ explicitly‐‐ L, indepen‐ dent if they are session cookies or not. Session cookies are cookies without expiry date and they are meant to be alive and existing for this "session" only. CURLOPT_COOKIELIST Pass a char * to a cookie string. Cookie can be either in Net‐ scape /‐. This should be used to specify the sender's email address when send‐ ing SMTP mail with libcurl. An originator email address should be specified with angled brackets (<>) around it, which if not specified, will be added by libcurl from version 7.21.4 onwards. Failing to provide such brackets may cause the server to reject the email. If this parameter is not specified then an empty address will be sent to the mail server which may or may not cause the email to be rejected. should be specified within a pair of angled brackets (<>), however, should you not use an angled bracket as the first character libcurl will assume you provided a single email address and enclose that address within brackets for you. (Added in 7.20.0) CURLOPT_MAIL_AUTH Pass a pointer to a zero terminated string as parameter. This will be used to specify the authentication address (identity) of a submitted message that is being relayed to another server. This optional parameter allows co-operating agents in a trusted environment to communicate the authentication of individual mes‐ sages and CURLOPT_MAIL_RCPT, the address should not be specified within a pair of angled brackets (<>). However, if an empty string is used then a pair of brackets will be sent by libcurl as required by RFC2554. (Added in 7.25.0) TFTP OPTIONS CURLOPT_TFTP_BLKSIZE Specify block size to use for TFTP data transmission. Valid range as per RFC23 instruc‐ tion.‐ ally followed by a '-' to specify a port range. If the port specified is 0, the operating system will pick a free port. If a range is provided and all ports in the range are not avail‐ able, libcurl will report CURLE_FTP_PORT_FAILED for the handle. Invalid port/range settings are ignored. IPv6 addresses fol‐‐. When speaking to a FTP (or SFTP since 7.24.0) server, prefix the command with an asterisk (*) to make libcurl continue even if the command fails as by default libcurl will stop at first failure..16 neces‐ sary. simultaneous recom‐ mended that if used in conjunction with CURLOPT_TIMEOUT, you set CURLOPT_FTP_RESPONSE_TIMEOUT to a value smaller than CUR‐ Len‐ crypted.‐‐ c responsible descrip‐ tion of the session. For example, if a client is using the server to record a meeting, the client can use Announce to inform the server of all the meta-information about the session. ANNOUNCE acts like cur‐ rently con‐ nections. (Added in 7.20.0) CURL_RTSPREQ_GET_PARAMETER Retrieve a parameter from the server. By default, libcurl will automatically include a Content-Type: text/parame‐ ters header on all non-empty requests unless a custom one is set. GET_PARAMETER acts just like a HTTP PUT or POST. An applica‐ tion may either use CURLOPT_UPLOAD with CURLOPT_READDATA like a HTTP PUT, or it may use CURLOPT_POSTFIELDS like CUR‐ LOPT_RANGE option to modify the record time. (Added in 7.20.0) CURL_RTSPREQ_RECEIVE This is a special request because it does not send any data to the server. The application may call this func‐ tion exam‐ ple, bro‐ ken‐ lar. libcurl does not do a complete ASCII conversion when doing ASCII transfers over FTP. This is a known limitation/flaw that nobody has rectified. libcurl simply sets the mode to ASCII and per‐ forms a standard transfer. CURLOPT_PROXY_TRANSFER_MODE multi‐ ple intervals will cause the HTTP server to send the response document in pieces (using standard MIME separation techniques). For RTSP, the formatting of a range should follow RFC2326 Sec‐ tion‐ tinue can be used to specify the request instead of GET or HEAD when per‐ forming HTTP based requests, instead of LIST and NLST when per‐ forming FTP directory listings and instead of LIST and RETR when issuing POP3 based commands. This is particularly useful, for example, for performing a HTTP DELETE request or a POP3 DELE command. Please don't perform this at will, on HTTP based requests, by making sure your server supports the command you are sending first. When you change the request method by setting CURLOPT_CUSTOMRE‐ QUEST to something, you don't actually change how libcurl behaves or acts in regards to the particular request method, it will only change the actual string sent in the request. For example: With the HTTP protocol CUR‐ LOPT_HTTPGET. With the POP3 protocol when you tell libcurl to use a custom request it will behave like a LIST or RETR command was sent where it expects data to be returned by the server. As such CUR‐ LOPT_NOBODY should be used when specifying commands such as DELE and NOOP for example. Restore to the internal default by setting this to NULL. Many people have wrongly used this option to replace the entire request with their own, including multiple headers and POST con‐. (Support for POP3 added in 7.26.0) CURLOPT_FILETIME Pass a long. If it is 1, libcurl will attempt to get the modifi‐ cation‐ SIZE_LARGE. For uploading using SCP, this option or CURLOPT_INFILESIZE_LARGE is mandatory. When sending emails using SMTP, this command can be used to specify the optional SIZE parameter for the MAIL FROM command. (Added in 7.23.0)‐ SIZE_LARGE options are also interesting for uploads. If the pro‐ tocol is HTTP, uploading means using the PUT request unless you tell libcurl otherwise. Using PUT with HTTP 1.1 implies the use of a "Expect: 100-con‐ tinue" header. You can disable this header with CURLOPT_HTTP‐‐ COND‐‐. Default timeout is 0 (zero) which means it never times out. CURLOPT_TIMEOUT_MS Like CURLOPT_TIMEOUT but takes number of milliseconds instead. If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolu‐ tion for timeouts with a minimum timeout allowed of one second. (Added in 7.16.2) CURLOPT_LOW_SPEED_LIMIT Pass a long as parameter. It contains the transfer speed in bytes per second that the transfer should be below during CUR‐ simul‐‐ tions‐‐ its the connection phase, once it has connected, this option is of no more use. Set to zero to switch to the default built-in connection timeout - 300 seconds. implemented for HTTP, SMTP and POP3. The option can be used to simply test a connection to a server, but is more useful when used with the CURLINFO_LASTSOCKET option to curl_easy_getinfo(3) as for‐ mat opera‐ tions against the HOST+PORT will instead use your provided ADDRESS. You can remove names from the DNS cache again, to stop providing these fake resolves, by including a string in the linked list that uses the format "-HOST:PORT". The host name must be pre‐ fixed with a dash, and the host name and port number must exactly match what was already added previously. (Added in 7.21.3) CURLOPT_DNS_SERVERS Set the list of DNS servers to be used instead of the system default. The format of the dns servers option is: host[:port][,host[:port]]... For example: 192.168.1.100,192.168.1.101,3.4.5.6 This option requires that libcurl was built with a resolver backend that supports this operation. The c-ares backend is the only such one. (Added in 7.24.0) CURLOPT_ACCEPTTIMEOUT_MS Pass a long telling libcurl the maximum number of milliseconds to wait for a server to connect back to libcurl when an active FTP connection is used. If no timeout is set, the internal default of 60000 will be used. (Added in 7.24 for‐‐ mats are "PEM", "DER" and "ENG". The format "ENG" enables you to load the private key from a crypto engine. In this case CURLOPT_SSLKEY is used as an identi‐ con‐ figurations curl_easy_setopt might be defined as a macro taking exactly three arguments. Therefore, it's recommended to pass 1 as parameter to this option. CURLOPT_SSLVERSION Pass a long as parameter to control what version of SSL/TLS to attempt to use. (Added in 7.9.2).x CURL_SSLVERSION_SSLv2 Force SSLv2 CURL_SSLVERSION_SSLv3 Force SSLv3 CURL_SSLVERSION_TLSv1_0 Force TLSv1.0 (Added in 7.34.0) CURL_SSLVERSION_TLSv1_1 Force TLSv1.1 (Added in 7.34.0) CURL_SSLVERSION_TLSv1_2 Force TLSv1.2 (Added in 7.34.0) CURLOPT_SSL_VERIFYPEER Pass a long as parameter. By default, curl assumes a value of 1. This option determines whether curl verifies the authenticity of the peer's certificate. A value of 1 means curl verifies; 0 (zero) means it doesn't. When negotiating a SSL connection, the server sends a certifi‐ cate indicating its identity. Curl verifies whether the cer‐ tificate verifica‐ tion CUR‐ LOPT_SSL_VERIFYPEER option. CURLOPT_CAINFO Pass a char * to a zero terminated string naming a file holding one or more certificates to verify the peer with. This makes sense only when used in combination with the CURLOPT_SSL_VERI‐ FYPEER option. If CURLOPT_SSL_VERIFYPEER is zero, CUR‐ LOPT_CAINFO. CURLOPT_ISSUERCERT Pass a char * to a zero terminated string naming a file holding a CA certificate in PEM format. If the option is set, an addi‐ tional check against the peer certificate is performed to verify the issuer is indeed the one associated with the certificate provided by the option. This additional check is useful in multi-level PKI where one needs to enforce that the peer cer‐‐ sion has failed due to a mismatch with the issuer of peer cer‐ tificate _VERI‐ FYPEER option. If CURLOPT_SSL_VERIFYPEER is zero, CURLOPT_CAP‐ ATH need not even indicate an accessible path. The CURLOPT_CAP‐ ATH‐ tificate verifi‐ cation certifi‐‐ nect. When the value is 1, libcurl will return a failure. It was pre‐ viously (in 7.28.0 and earlier) a debug option of some sorts, but it is no longer supported due to frequently leading to pro‐ grammer mistakes.‐ r:‐ hosted.org/cgit/mod_nss.git/plain/docs/mod_nss.html#Directives_SSL_OPTIONS Pass a long with a bitmask to tell libcurl about specific SSL behaviors. CURLSSLOPT_ALLOW_BEAST is the only supported bit and by setting this the user will tell libcurl to not attempt to use any work‐ arounds loosens the security, and by setting this option to 1 you ask for exactly that. (Added in 7.25) CURLOPT_GSSAPI_DELEGATION Set the parameter to CURLGSSAPI_DELEGATION_FLAG to allow uncon‐ ditional GSSAPI credential delegation. The delegation is dis‐ abled by default since 7.21.7. Set the parameter to CURLGSS‐ API_DELEGATION_POLICY_FLAG to delegate only if the OK-AS-DELE‐ GATE flag is set in the service ticket in case this feature is supported by the GSSAPI implementation and the definition of GSS_C_DELEG_POLICY_FLAG was available at compile-time. (Added in 7.22.0) SSH OPTIONS CURLOPT_SSH_AUTH_TYPES Pass a long set to a bitmask consisting of one or more of CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD and CURLSSH_AUTH_AGENT. Set CURLSSH_AUTH_ANY to let libcurl pick a suitable one. Cur‐ rently CURLSSH_AUTH_HOST has no effect. (Added in 7.16.1) If CURLSSH_AUTH_AGENT is used, libcurl attempts to connect to ssh- agent or pageant and let the agent attempt the authentication. (Added in 7.28.0) $HOME/.ssh/id_dsa.pub if the HOME environment variable is set, and just "id_dsa.pub" in the cur‐ rent directory if HOME is not set. (Added in 7.16.1) If an empty string is passed, libcurl will pass no public key to lib‐ ssh2 which then tries to compute it from the private key, this is known to work when libssh2 1.4.0+ is linked against OpenSSL. (Added in 7.26.0) CURLOPT_SSH_PRIVATE_KEYFILE Pass a char * pointing to a file name for your private key. If not used, libcurl defaults to $HOME/.ssh/id_dsa if the HOME environment variable is set, and just "id_dsa" in the current directory if HOME is not set. If the file is password-pro‐ tected, appli‐ cation to act and decide for libcurl how to proceed. The call‐ back fol‐ lowing return codes to tell libcurl how to act: CURLKHSTAT_FINE_ADD_TO_FILE The host+key is accepted and libcurl will append it to the known_hosts file before continuing with the connec‐ tion.‐‐‐ permis‐ sions permis‐ sions.20.0 1 Jan 2010 curl_easy_setopt(3)[top]
|
http://www.polarhome.com/service/man/?qf=curl_easy_setopt&tf=2&of=Oracle&sf=3
|
CC-MAIN-2020-10
|
refinedweb
| 5,101
| 56.55
|
C library function - ferror()
Advertisements
Description
The C library function int ferror(FILE *stream) tests the error indicator for the given stream.
Declaration
Following is the declaration for ferror() function.
int ferror(FILE *stream)
Parameters
stream − This is the pointer to a FILE object that identifies the stream.
Return Value
If the error indicator associated with the stream was set, the function returns a non-zero value else, it returns a zero value.
Example
The following example shows the usage of ferror() function.
#include <stdio.h> int main() { FILE *fp; char c; fp = fopen("file.txt", "w"); c = fgetc(fp); if( ferror(fp) ) { printf("Error in reading from file : file.txt\n"); } clearerr(fp); if( ferror(fp) ) { printf("Error in reading from file : file.txt\n"); } fclose(fp); return(0); }
Assuming we have a text file file.txt, which is an empty file. Let us compile and run the above program that will produce the following result because we try to read a file which we opened in write only mode.
Error reading from file "file.txt"
stdio_h.htm
Advertisements
|
http://www.tutorialspoint.com/c_standard_library/c_function_ferror.htm
|
CC-MAIN-2016-22
|
refinedweb
| 180
| 57.98
|
Machine learning, natural language process and AI, in general, has gained more audience with the massive growth and investment it has received. Computers can now easily understand and derive meaning from human language. This has opened a new window of opportunity for application developers to build new kinds of products that will interact differently with individuals.
Today, we’ll be building a simple chatbot that can help search for news from the internet by talking to it as you would a human being. We’ll call this “Channel 24 news with Bobby Mc-newsfeed”.
Kindly ensure you have Node, Npm or Yarn installed on your machine before moving past this section. This will be needed for running and managing the dependencies needed by our application. Also, no knowledge of React is required, but a basic understanding of JavaScript may be helpful.
We'll start by setting up our Next.js application. The easiest way to go about this is to clone the nextjs-javascript-starter repo. Run:
git clone chat-bot
This will clone the starter pack into a directory called
chat-bot. Our app directory will look like this.
.jsfile in this directory would be served as a page. So any page we'll want to create would go here.
To install the dependencies needed by our app, run:
# enter app directory cd chat-bot # install dependencies from nextjs-javascript-starter yarn install # add client-side dependencies yarn add axios pusher-js react-chat-ui # add server-side dependencies yarn add cors express pusher body-parser dialogflow country-data newsapi dlv
Now we have all dependencies needed by our app installed.
If you don't have a Pusher account already, kindly create one here. Once you have an account, simply head down to your dashboard and create an app. Once that is done, click on App Keys and note your credentials. We'll be needing them in a bit.
Dialogflow is responsible for analyzing the messages sent to Bobby Mc-newsfeed and breaking them down into meaningful intents that can be processed by our new API. Simply head down here and create an account. Dialogflow already comes with some prebuilt agents that might cover your application needs. Simply click on "Prebuilt Agent" by the left and import the News agent. You can easily search for it to filter out the other available agents on the list.
This would create a new agent for you called News. Our new agent News comes with some already trained intent and entities called sort, source and topic. These are the entities we’ll want to extract from each message sent down to our agent.
The agent also makes use of some prebuilt entities like
geo-location which tells us the country specified.
Click on the setting icon beside your project name, to see more information about the agent you’ve created. You might see a notice about API migration from V1 to V2, like this:
NOTE: This project uses the V2 API, so ensure the API version is set to V2.
Next, we’ll need to get credentials to run this locally. Head down to google cloud console and enable this project.
Simply search for “Dialogflow” and click Enable API. To get our credentials, click on Credentials, then the drop-down Create Credentials and then service account key. Select JSON as your format and begin the download.
Keep this file close by as you’ll be needing it soon. More detailed instruction here.
Head over to the News API homepage and sign up. You’ll get a key needed in the coming section. Now that we have all our credentials ready, we can get on with building our application.
Any
.js file created in the
pages directory becomes a page that can be served by
Next.js. We already have an
index.js file in our page directory. Replace the content with the following below:
// pages/index.js import React from 'react' import axios from 'axios' import { ChatFeed, Message } from 'react-chat-ui' import Pusher from 'pusher-js' import MyChatBubble from '../components/MyChatBubble' import '../css/chat.css' const pusher = new Pusher('key', { cluster: 'eu', encrypted: true }) const channel = pusher.subscribe('news') export default class Index extends React.Component { constructor (props) { super(props) this.state = { message: '', isTyping: false, messages: [ new Message({ id: 'bot', message: 'hello', senderName: 'bot' }), new Message({ id: 2, message: 'hi bobby' }) ]} } componentDidMount () { this.receiveUpdateFromPusher() } /** * When there's an update, * append the message to the Chat field. */ receiveUpdateFromPusher () { channel.bind('news-update', articles => { const messages = articles.map(article => { return new Message({ id: 'bot', message: ` Description: ${article.title || article.description} Url: ${article.url} ` }) }) const intro = messages.length ? 'Here you go, i found some for you' : 'I couldn\'t find any :-(. Search for something else' this.setState({ messages: [ ...this.state.messages, new Message({ id: 'bot', message: intro }), ...messages ] }) }) } handleChange (event) { this.setState({message: event.target.value}) } /** * When user press Enter, send message to the server */ handleKeyPress (e) { if (e.key === 'Enter' && e.target.value) { const message = e.target.value this.setState({message: ''}) this.pushMessage(message) axios.post('', {message}) .then(res => { console.log('received by server') }) .catch(error => { throw error }) } } pushMessage (message) { this.setState({ messages: [ ...this.state.messages, new Message({ id: 2, message }) ] }) } render () { return ( <div className='chat-wrapper'> <h3> Channel 24: News worldwide with Bobby Mc-newsfeed</h3> <ChatFeed messages={this.state.messages} // Boolean: list of message objects isTyping={this.state.isTyping} // Boolean: is the recipient typing hasInputField={false} // Boolean: use our input, or use your own showSenderName // show the name of the user who sent the message bubblesCentered={false} // Boolean should the bubbles be centered in the feed? chatBubble={MyChatBubble} maxHeight={750} /> <input className='chat-input' type='text' value={this.state.message} onChange={this.handleChange.bind(this)} onKeyPress={this.handleKeyPress.bind(this)} </div> ) } }
Replace the
key placeholder string in the Pusher configuration above with your Pusher key.
Since we’re building a chatbot, we’ll be needing to represent the message in some fancy bubble as we’re used to seeing. We’ll be using react-chat-ui to create this, but with a custom chat bubble, which styles our bubble differently depending on the message sender.
# To create file, run: touch components/MyChatBubble.js
Add the following code to the file:
// components/MyChatBubble.js import React from 'react' import { ChatBubble } from 'react-chat-ui' export default class MyChatBubble extends React.Component { render () { let bubbleStyles = {} if (this.props.message.id === 'bot') { bubbleStyles = { text: { fontSize: 12 }, chatbubble: { borderRadius: 70, padding: '10px 30px' } } } else { bubbleStyles = { text: { fontSize: 12 }, chatbubble: { borderRadius: 70, padding: '10px 30px', backgroundColor: 'black', float: 'right' } } } return <ChatBubble bubbleStyles={bubbleStyles} message={this.props.message} /> } } ## ChatBubble style # To create file, run: touch css/chat.css Add the following style to the file: /* css/chat.css */ div#__next { display: flex; justify-content: center; } div.chat-wrapper { width: 500px; border: 1px black solid; border-radius: 2%; padding: 30px; } input.chat-input { border: none; border-top: 1px solid #ddd; font-size: 16px; padding: 30px; width: 90%; padding: 20px 10px; margin: 5px; }
Our sever.js file is responsible for publishing Pusher events, querying Dialogflow for Intent and communicating with the news API. Messages from the chat come straight to the server on the route
/message and forward the message to Dialogflow to interpret and return a result. We can now use the
result gotten from Dialogflow to communicate with the news API and get a list of news articles matching the query.
# To create file, run: touch server.js
Add the following code to the file:
// server.js const express = require('express') const app = express() const bodyParser = require('body-parser') const cors = require('cors') const Pusher = require('pusher') const countryData = require('country-data') const dialogflow = require('dialogflow') const NewsAPI = require('newsapi') const dlv = require('dlv') const newsapi = new NewsAPI('enter your news API token') const projectId = 'project id' // update with your project Id const sessionId = 'a-random-session-id' // use any string as session Id const languageCode = 'en-US' const sessionClient = new dialogflow.SessionsClient() const sessionPath = sessionClient.sessionPath(projectId, sessionId) const countryDataByName = countryData.countries.all.reduce((acc, curr) => { acc[curr.name.toLowerCase()] = curr return acc }, {}) // build query for getting an Intent const buildQuery = function (query) { return { session: sessionPath, queryInput: { text: { text: query, languageCode: languageCode } } } } // use data from intent to fetch news const fetchNews = function (intentData) { const category = dlv(intentData, 'category.stringValue') const geoCountry = dlv(intentData, 'geo-country.stringValue', '').toLowerCase() const country = dlv(countryDataByName, `${geoCountry}.alpha2`, 'us') return newsapi.v2.topHeadlines({ category, language: 'en', country }) } app.use(cors()) app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) const port = process.env.PORT || 8080 const pusher = new Pusher({ appId: 'app_id', key: 'key', secret: 'secret', cluster: 'cluster', encrypted: true }) // receive message sent by client app.post('/message', function (req, res) { return sessionClient .detectIntent(buildQuery(req.body.message)) .then(responses => { console.log('Detected intent') const result = dlv(responses[0], 'queryResult') const intentData = dlv(responses[0], 'queryResult.parameters.fields') // if there's a result and an intent if (result && result.intent) { fetchNews(intentData) .then(news => news.articles) .then(articles => pusher.trigger('news', 'news-update', articles.splice(0, 6))) .then(() => console.log('published to pusher')) } else { console.log(` No intent matched.`) } return res.sendStatus(200) }) .catch(err => { console.error('ERROR:', err) }) }) app.listen(port, function () { console.log('Node app is running at localhost:' + port) })
Copy the service file downloaded from Dialogflow to your project directory. You can now reference this file when starting up the app.
Start the next app with:
# start next app yarn run dev # start server app (bash) GOOGLE_APPLICATION_CREDENTIALS="service-account-file.json" node server.js # in powershell $env:GOOGLE_APPLICATION_CREDENTIALS="service-account-file.json"; node server.js
Update
GOOGLE_APPLICATION_CREDENTIALS to point to the location of the service account file you downloaded previously to start the server app correctly.
You can ask Bobby Mac-newsfeed simple questions like
Our agent will try to pick out location, topic and category for your message and use that to query the news API. Feel free to express yourself freely and see what Bobby replies to you with.
We’ve been able to build a chatbot with the ability to send us news updates we requested for. You can extend the functionality of Bobby to handle a lot more and interpret our message more accurately by training our model more.
The repo for this tutorial lives here. Feel free to contribute.
Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.
|
https://www.pusher.com/tutorials/news-chatbot-nextjs-dialogflow/
|
CC-MAIN-2018-51
|
refinedweb
| 1,739
| 50.33
|
A simple client that talks to the Adyen API
Does not try to be smart, stays close to the documentation while adhering to Ruby conventions.
Setup & Configuration
gem install adyen_client
In your Gemfile:
gem "adyen_client"
Require and configure the client:
```ruby require “adyen_client”
Block style
AdyenClient.configure do |c| c.environment = :test c.username = “ws_123456@Company.FooBar” c.password = “correctbatteryhorsestaple” c.cse_public_key = “10001|…” c.default_merchant_account = “FooBar123” c.default_currency = “EUR” end
Hash style works too, string or symbol keys
AdyenClient.configure(environment: :test, username: “ws_123456@Company.FooBar”, …)
That comes in handy to configure the client from a YAML file
AdyenClient.configure(YAML.load_file(Rails.root.join(“config”, “adyen.yml”))[Rails.env.to_s])
You can override all default_* options for each instance of a client
client = AdyenClient.new(merchant_account: “FooBarSubMerchant123”) eur_client = AdyenClient.new(currency: “EUR”) ```
Examples
Simple payment
ruby
client = AdyenClient.new
response = client.authorise(amount: 100, encrypted_card: "adyenjs_0_1_15$OlmG...")
if response.authorised?
puts "( ノ ゚ー゚)ノ"
else
puts "(-‸ლ)"
end
Setup a recurring contract, charge users later
```ruby user = User.create(email: “john@doe.com”, last_ip: request.remote_ip)
client = AdyenClient.new response = client.create_recurring_contract(encrypted_card: “adyenjs_0_1_15$OlmG…”, shopper: { reference: user.id, email: user.email, ip: user.last_ip # optional but recommended }) if response.authorised? # now we know the users card is valid else # something is wrong with the users card or we got an error end ```
Later, we want to charge the user based on that contract.
```ruby user = User.find_by_email(“john@doe.com”)
client = AdyenClient.new response = client.authorise_recurring_payment(amount: 1699, shopper: { reference: user.id }) if response.authorised? # we know the payment is on its way else # something is wrong, maybe we got an error end ```
Documentation
All publicly usable methods and classes are documented here.
This library does not try to be too smart, it simply provides a layer of abstraction on top of the Adyen JSON API.
Also the default
AdyenClient::Response class basically just wraps the JSON response.
The only work it does is converting
camelCase keys to
sneak_case, removing unnecessary object nestings and providing you with a convenience
authorised? method.
If you want a more sophisticated response class, you can easily hook up your own.
The only method you need to provide is
::parse. It will receive one argument, the
HTTParty::Response for the given request.
ruby
class MyAdyenResponse
def self.parse(http_response)
# ... your fancy code
end
end
Hook it up by initialising the client like this:
AdyenClient.new(response_class: MyAdyenResponse).
Similar, if you want nothing else than the bare
HTTParty::Response, initialise the client with:
response_class: nil.
Contributing
I am very happy to receive pull requests or bug reports for problems with the library. Please make sure you are only reporting an actual issue with the library itself, I cannot help with your payment flow or advise you on anything related to the Adyen API.
Disclaimer
I am not associated with Adyen in any way.
If you have problems with your adyen account or your payment flow, please contact the very helpful Adyen support using
support ät adyen.com.
Please make yourself comfortable with the Adyen documentation on how you want to setup your payment flow.
License
The MIT License (MIT), Copyright (c) 2015 Lukas Rieder
|
https://www.rubydoc.info/github/Overbryd/adyen_client
|
CC-MAIN-2018-30
|
refinedweb
| 530
| 52.46
|
Ok first off. I know what your going to say, "You should learn this and this before you do that". I know I should but I want to skip the stuff I won't use right now and get on to something I will use. I amtrying to make a preogram delete a certain key. Now I heard of this website that tells the functions for it all, but I'm not sure if I am doing any of it right. Well just look at the start of the code...
Code:
#include <iostream.h>
#include <conio.h>
#include <cstdlib>
int main()
{
LONG RegConnectRegistry(mycomputername,HKEY_CURRENT_USER,PHKEY phkResult);
LONG RegDeleteKey(HKEY_CURRENT_USER,Test Key);
getch();
return 0;
}
Yes I did put extra #include files in it because I will use them later. But it says there is a syntaxt error before the ( in the the LONG RegConnectRegistry line.
There is also this error I had before and is relly bugging me...
` LONG' undeclared (first use this function)
Soo.... say anything you want but I would perfer just a little help please...
Thank you.
Edit: I think I may have put this post in the wrong forum. Oops...
Edit Edit: And yes I know I need more functions to make this work but first I need to know what is wrong here.
|
http://cboard.cprogramming.com/windows-programming/55997-some-reg-editing-help-please-printable-thread.html
|
CC-MAIN-2015-14
|
refinedweb
| 219
| 82.65
|
Background Worker Queue in C#Development ·
Sometimes it is required to run multimple tasks in the background, while one task can only start after another has finished. In this case a simple background queue based on the C# TPL can be used.
Most of the time a simple Task.Run() can be used to do work on the background thread pool. But when one has to process multiple tasks one after the other this does not work any more since using Task.Run() does not guarantee any order for the processed tasks.
In this case the following code can be used to have a background queue and execute tasks one after the other.
var queue = new BackgroundQueue(); queue.QueueTask(() => { /* Do some work */ }); queue.QueueTask(() => { /* Do some more work */ }); var result = await queue.QueueTask(() => { return result; });
Here is the code for the background queue class:
public class BackgroundQueue { private Task previousTask = Task.FromResult(true); private object key = new object(); public Task QueueTask(Action action) { lock (key) { previousTask = previousTask.ContinueWith( t => action(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); return previousTask; } } public Task<T> QueueTask<T>(Func<T> work) { lock (key) { var task = previousTask.ContinueWith( t => work(), CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); previousTask = task; return task; } } }
|
https://trenki2.github.io/blog/2019/01/02/background-queue-in-csharp/
|
CC-MAIN-2020-40
|
refinedweb
| 204
| 59.9
|
Roll your own IRC bot
From HaskellWiki
to a Haskell program. We first connect to the server, then set the buffering on the socket off. Once we've got a socket, we can then just read and print any data we receive.Put this code in the module
Use which ever,
argument, evaluates it, and recurses -- an infinite loop function. It is very common to roll our own control structures in Haskell this way, using higher order functions. No need to add new syntax to the language, or lisp-like macros, or meta programming: you just write a normal function to implement whatever control flow you wish. We can also avoid)
While we're here we can tidy up the main function a little, by using
main loop phases of the program -- a useful technique. We can also make the code a bit more robust, by wrapping the main loop in an exceptionhandler, using
main :: IO () main = bracket connect disconnect loop where disconnect = hClose . socket loop st = catch (runReaderT run st) (const $ return ())
arguments: a function to connect to the server, thus import Control.Concurrent
fun. Now we're almost done! Let's run this bot. Using GHC/runhaskell:
$ runhaskell 4.hs
$ ghc --make 4.hs -o tutbot Chasing modules from: 4.hs Compiling Main ( 4.hs, 4.o ) Linking ... $ ./tutbot)
- Haskell.org
- More Haskell code
- Learning Haskell
- A gallery of network apps in Haskell
Or take the bot home, and hack! Some suggestions:
|
https://wiki.haskell.org/index.php?title=Roll_your_own_IRC_bot&oldid=6464
|
CC-MAIN-2017-09
|
refinedweb
| 244
| 73.78
|
Hi Guys,
I am currently looking for a Python solution to a project I am working on. I am VERY new to Python so please go easy on me.
Currently, I have a server setup, only running Windows 7, and on that server, Thunderbird is constantly running checking for new emails that are sent from a server producing nightly builds of some software.
When the email is received by the w7 server, a script is run that fires off some actions.
My problem is, I need to scan the emails received by Thunderbird, and then fire off a script based on the contents of the email received, so the email needs to be scanned, and a variable passed from it to the scripts that are fired off.
I have had a look around on the net for any helpers, but as I am very new to this I'm confused beyond belief at the solutions. Can someone please break down a simple solution for me?
So far I have the following. It connects to the IMAP mail server which is what I require, but I then need to query the emails which I'm struggling with.
Any thoughts? I'm not quite sure I have the first search query correct.
It needs to get a number from the subject, which is only part of the subject as defined by "Build No: xxx"
It then needs to scan through the body of the email to check to see if the build was successful. Which is in the format "Win Build - Passed" or "Win Build - Failed"
Any thoughts?
#!/usr/bin/env python
import os, sys, imaplib, rfc822, re, StringIO
server =' 'myserver'
username='username'
password='password'
M = imaplib.IMAP4_SSL(server)
M.login(username, password)
M.select()
#I want to search for some text in the subject
typ, data = M.search(None, '(UNSEEN SUBJECT "text")')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
#If an email has the correct subject, I then want to query a line in the body, and if
#...it passes, run another python script.
M.close()
M.logout()
|
https://www.daniweb.com/programming/software-development/threads/384199/python-receive-imap-email
|
CC-MAIN-2018-30
|
refinedweb
| 362
| 78.89
|
- NAME
- SYNOPSIS
- DESCRIPTION
- FEEDBACK
- AUTHOR - Aaron Mackey, Steve Chervitz
- DISCLAIMER
- APPENDIX
NAME
Bio::Search::Hit::HitI - Interface for a hit in a similarity search result
SYNOPSIS
# Bio::Search::Hit::HitI objects should not be instantiated since this # module defines a pure interface.
# Given an object that implements the Bio::Search::Hit::HitI interface, # you can do the following things with it:
# Get a HitI object from a SearchIO stream: use Bio::SeachIO; my $searchio = Bio::SearchIO->new(-format => 'blast', -file => 'result.bls'); my $result = $searchio->next_result; my $hit = $result->next_hit; $hit
DESCRIPTION
Bio::Search::Hit::* objects are data structures that contain information about specific hits obtained during a library search. Some information will be algorithm-specific, but others will be generally, Steve Chervitz
DISCLAIMER
This software is provided "as is" without warranty of any kind.
APPENDIX
The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _
name
Title : name Usage : $hit_name = $hit->name(); Function: returns the name of the Hit sequence Returns : a scalar string Args : none
The name of a hit is unique within a Result or within an Iteration.
description
Title : description Usage : $desc = $hit->description(); Function: Retrieve the description for the hit Returns : a scalar string Args : none
accession
Title : accession Usage : $acc = $hit->accession(); Function: Retrieve the accession (if available) for the hit Returns : a scalar string (empty string if not set) Args : none
locus
Title : locus Usage : $acc = $hit->locus(); Function: Retrieve the locus(if available) for the hit Returns : a scalar string (empty string if not set) Args : none
length
Title : length Usage : my $len = $hit->length Function: Returns the length of the hit Returns : integer Args : none : none
raw_score
Title : raw_score Usage : $score = $hit->raw_score(); Function: Gets the "raw score" generated by the algorithm. What this score is exactly will vary from algorithm to algorithm, returning undef if unavailable. Returns : a scalar value Args : : none
bits
Usage : $hit_object->bits(); Purpose : Gets the bit score of the best HSP for the current hit. Example : $bits = $hit_object->bits(); Returns : Integer or double for FASTA reports Argument : n/a Comments : For BLAST1, the non-bit score is listed in the summary line. L<Bio::Search::HSP::BlastHSP> Blast hit. Example : $nhsps = $hit_object->num_hsps(); Returns : Integer Argument : n/a Throws : Exception if the HSPs have not been collected.
seq_inds
Usage : $hit->seq_inds( seq_type, class, collapse ); Purpose : Get a list of residue positions (indices) across all HSPs : for identical or conserved residues in the query or sbjct sequence. Example : @s_ind = $hit->seq_inds('query', 'identical'); : @h_ind = $hit->seq_inds('hit', 'conserved'); : @h_ind = $hit->seq_inds('hit', 'conserved', 1); Returns : Array of integers : May include ranges if collapse is non-zero. Argument : [0] seq_type = 'query' or 'hit' or 'sbjct' (default = 'query') : ('sbjct' is synonymous with 'hit') : [1] class = 'identical' or 'conserved' (default = 'identical') : (can be shortened to 'id' or 'cons') : (actually, anything not 'id' will evaluate to 'conserved'). : [2] collapse = boolean, if non-zero, consecutive positions are merged : using a range notation, e.g., "1 2 3 4 5 7 9 10 11" : collapses to "1-5 7 9-11". This is useful for : consolidating long lists. Default = no collapse. Throws : n/a.
See Also : Bio::Search::HSP::HSPI::seq_inds()
rewind
Title : rewind Usage : $hit->rewind; Function: Allow one to reset the HSP iterator to the beginning if possible Returns : none Args : none
overlap
Usage : $hit_object->overlap( [integer] ); Purpose : Gets/Sets the allowable amount overlap between different HSP sequences. Example : $hit_object->overlap(5); : $overlap = $hit_object->overlap; Returns : Integer. Argument : integer. Throws : n/a Status : Experimental Comments : Any two HSPs whose sequences overlap by less than or equal : to the overlap() number of resides will be considered separate HSPs : and will not get tiled by L<Bio::Search::BlastUtils::_adjust_contigs()>.
See Also : Bio::Search::BlastUtils::_adjust_contigs(), BUGS
n
Usage : $hit_object->n(); Purpose : Gets the N number for the current Blast (BLAST2 reports). Comments : Note that the N parameter is not reported in gapped BLAST2. : of the given BLAST hit. : (Note that P-values are not provided with NCBI Blast2 reports).::Blast()
logical_length
Usage : $hit_object->logical_length( [seq_type] ); : (mostly intended for internal use). Purpose : Get the logical length of the hit sequence. : If the Blast is a TBLASTN or TBLASTX, the returned length : is the length of the would-be amino acid sequence (length/3). : For all other BLAST flavors, this function is the same as length(). Example : $len = $hit_object->logical_length(); Returns : Integer Argument : seq_type = 'query' or 'hit' or 'sbjct' (default = 'query') ('sbjct' is synonymous with 'hit') Throws : n/a Comments : This is important for functions like frac_aligned_query() : which need to operate in amino acid coordinate space when dealing : with [T]BLAST[NX] type reports.
See Also : length(), frac_aligned_query(), frac_aligned_hit()
rank
Title : rank Usage : $obj->rank($newval) Function: Get/Set the rank of this Hit in the Query search list i.e. this is the Nth hit for a specific query Returns : value of rank Args : newvalue (optional)
each_accession_number
Title : each_accession_number Usage : $obj->each_accession_number Function: Get each accession number listed in the description of the hit. If there are no alternatives, then only the primary accession will be given Returns : list of all accession numbers in the description Args : none
tiled_hsps
Usage : $hit_object->tiled_hsps( [integer] ); Purpose : Gets/Sets an indicator for whether or not the HSPs in this Hit : have been tiled. : Methods that rely on HSPs being tiled should check this : and then call SearchUtils::tile_hsps() if not. Example : $hit_object->tiled_hsps(1); : if( $hit_object->tiled_hsps ) { # do something } Returns : Boolean (1 or 0) Argument : integer (optional) Throws : n/a
strand
Usage : $sbjct->strand( [seq_type] ); Purpose : Gets the strand(s) for the query, sbjct, or both sequences : in the best HSP of the BlastHit object after HSP tiling. : Only valid for BLASTN, TBLASTX, BLASTX-query, TBLASTN-hit. Example : $qstrand = $sbjct->strand('query'); : $sstrand = $sbjct->strand('hit'); : ($qstrand, $sstrand) = $sbjct->strand(); Returns : scalar context: integer '1', '-1', or '0' : array context without args: list of two strings (queryStrand, sbjctStrand) : Array context can be "induced" by providing an argument of 'list' or 'array'. Argument : In scalar context: seq_type = 'query' or 'hit' or 'sbjct' (default = 'query') ('sbjct' is synonymous with 'hit') Throws : n/a Comments : This method requires that all HSPs be tiled. If they have not : already been tiled, they will be tiled first automatically.. : If you don't want the tiled data, iterate through each HSP : calling strand() on each (use hsps() to get all HSPs). : : Formerly (prior to 10/21/02), this method would return the : string "-1/1" for hits with HSPs on both strands. : However, now that strand and frame is properly being accounted : for during HSP tiling, it makes more sense for strand() : to return the strand data for the best HSP after tiling. : : If you really want to know about hits on opposite strands, : you should be iterating through the HSPs using methods on the : HSP objects. : : A possible use case where knowing whether a hit has HSPs : on both strands would be when filtering via SearchIO for hits with : this property. However, in this case it would be better to have a : dedicated method such as $hit->hsps_on_both_strands(). Similarly : for frame. This could be provided if there is interest.
See Also : Bio::Search::HSP::HSPI::strand()
frame
Usage : $hit_object->frame(); Purpose : Gets the reading frame for the best HSP after HSP tiling. : This is only valid for BLASTX and TBLASTN/X type reports. Example : $frame = $hit_object->frame(); Returns : Integer (-2 .. +2) Argument : n/a Throws : Exception if HSPs have not been set. Comments : This method requires that all HSPs be tiled. If they have not : already been tiled, they will be tiled first automatically.. : If you don't want the tiled data, iterate through each HSP : calling frame() on each (use hsps() to get all HSPs).
matches
Usage : $hit_object->matches( [class] ); Purpose : Get the total number of identical or conserved matches : (or both) across all HSPs. : (Note: 'conservative' matches are indicated as 'positives' : in BLAST reports.) Example : ($id,$cons) = $hit_object->matches(); # no argument : $id = $hit_object->matches('id'); : $cons = $hit_object->matches('cons'); Returns : Integer or a 2-element array of integers Argument : class = 'id' | 'cons' OR none. : If no argument is provided, both identical and conservative : numbers are returned in a two element list. : (Other terms can be used to refer to the conservative : matches, e.g., 'positive'. All that is checked is whether or : not the supplied string starts with 'id'. If not, the : conservative matches are returned.) Throws : Exception if the requested data cannot be obtained. Comments : This method requires that all HSPs be tiled. If there is more than one : HSP and they have not already been tiled, they will be tiled first automatically.. : : If you need data for each HSP, use hsps() and then interate : through the HSP objects. : Does not rely on wantarray to return a list. Only checks for : the presence of an argument (no arg = return list).
See Also : Bio::Search::HSP::GenericHSP::matches(), hsps()
sort_hits
Title : sort_hsps Usage : $result->sort_hsps(\&sort_function) Function : Sorts the available HSP::Hit::HitI namespace. For example, use : $hit->sort_hsps( sub{$Bio::Search::Result::HitI::a->length <=> $Bio::Search::Result::HitI::b->length}); NOT $hit->sort_hsps($a->length <=> $b->length);
_default sort_hsps
Title : _default_sort_hsps Usage : Do not call directly. Function : Sort hsps in ascending order by evalue Args : None Returns: 1 on success Note : Used by $hit->sort_hsps()
|
https://metacpan.org/pod/release/CJFIELDS/BioPerl-1.6.0/Bio/Search/Hit/HitI.pm
|
CC-MAIN-2020-16
|
refinedweb
| 1,557
| 51.28
|
How to Shift Binary Values in C Programming
The C programming language features two binary operators that perform the equivalent operation of “Everyone move one step to the left (or right).” The << and >> operators shift bits in value, marching them to the left or right, respectively. Here’s the format for the << operator:
v = int << count;
int is an integer value. count is the number of places to shift the value’s bits to the left. The result of this operation is stored in variable v. Any bits that are shifted to the left beyond the width of the int variable x are lost. New bits shifted in from the right are always 0.
As with most binary nonsense, it helps to visually see what’s going on in a value when its bits are shifted.
EVERYONE OUT OF THE POOL!
#include <stdio.h> char *binbin(int n); int main() { int bshift,x; printf("Type a value from 0 to 255: "); scanf("%d",&bshift); for(x=0;x<8;x++) { printf("%sn",binbin(bshift)); bshift = bshift << 1; } return(0); } char *binbin(int n) { static char bin[9]; int x; for(x=0;x<8;x++) { bin[x] = n & 0x80 ? '1' : '0'; n <<= 1; } bin[x] = ' '; return(bin); }
The shift operation takes place at Line 15 in Everyone out of the Pool!. The value in variable bshift is shifted to the left one bit.
Exercise 1: Type the source code from Everyone out of the Pool! into your editor and build a new project.
The net effect of a left bit shift is to double a value. That holds true to a certain point: Obviously, the farther left you shift, some bits get lost and the value ceases to double. Also, this trick works only for unsigned values.
Exercise 2: Modify the source code from Everyone out of the Pool! so that the printf() function at Line 14 also displays the decimal value of the bshift variable. You should also modify the binbin() function so that it displays 16 digits instead of 8.
Here’s the output when using the value 12:
Type a value from 0 to 255: 12 0000000000001100 12 0000000000011000 24 0000000000110000 48 0000000001100000 96 0000000011000000 192 0000000110000000 384 0000001100000000 768 0000011000000000 1536
Try the value 800,000,000 (don’t type the commas) to see how the doubling rule fails as the values keep shifting to the left. Also see the nearby sidebar “Negative binary numbers.”
The >> shift operator works similarly to the << shift operator, though values are marched to the right instead of the left. Any bit that’s marched off the right end is discarded, and only zero bits are inserted on the left side. Here’s the format:
v = int >> count;
int is an integer value, and count is the number of places to shift the bits to the right. The result is stored in variable v.
Exercise 3: Modify the source code from Exercise 2 so that the right shift operator is used instead of the left shift at Line 15. Build the program.
Here’s the result when using the value 128:
Type a value from 0 to 255: 128 0000000010000000 128 0000000001000000 64 0000000000100000 32 0000000000010000 16 0000000000001000 8 0000000000000100 4 0000000000000010 2 0000000000000001 1
Unlike the << operator, the >> is guaranteed to always cut the value in half when you shift one digit to the right. In fact, the >> operator is far quicker to use on an integer value than the / (division) operator to divide a value by 2.
The << and >> operators are available only in the C language. In C++, similar operators are used to receive standard input and send standard output.
Binary numbers are always positive, considering that the values of a bit can be only 1 or 0 and not –1 and 0. So how does the computer do signed integers? Easy: It cheats.
The leftmost bit in a signed binary value is known as the sign bit. When that bit is set (equal to 1), the value is negative for a signed int. Otherwise, the value is read as positive.
In this example, the sign bit is set for a signed char. The values expressed are negative, which is in the range of a signed char variable.
In this example, the sign bit is ignored because the value is an unsigned char. The values can only be positive, which is why the positive range for an unsigned variable is greater than for a signed variable.
|
https://www.dummies.com/programming/c/how-to-shift-binary-values-in-c-programming/
|
CC-MAIN-2019-30
|
refinedweb
| 748
| 71.14
|
infinite loop ;(974869 Nov 19, 2012 6:56 AM
I've got an infinite loop somewhere, & I'm not quite sure where.
Also when entering in a string for the name of the company, I can't put a space in my string name. I never really thought about that until now.
Here's the code:
Also when entering in a string for the name of the company, I can't put a space in my string name. I never really thought about that until now.
Here's the code:
Here is my main:Here is my main:
import java.util.Scanner; public class Stock { private String symbol; private String name; private double previousClosingPrice; private double currentPrice; //No-Arg constructor prompts the user to enter all 4 data members //Make sure that current and previous price are greater than 0 public Stock(){ Scanner input = new Scanner(System.in); System.out.println("Please enter symbol: "); symbol = input.next(); System.out.println("Please enter name: "); name = input.next(); System.out.println("Please enter previous closing price greater than 0: "); previousClosingPrice = input.nextDouble(); if(previousClosingPrice < 0){ System.out.println("Please enter previous closing price greater than 0: "); previousClosingPrice = input.nextDouble(); } System.out.println("Please enter the current price: "); currentPrice = input.nextDouble(); if(currentPrice < 0){ System.out.println("Please enter a current price greater than 0: "); currentPrice = input.nextDouble(); } }
public class Lab8Client{ public static void main(String[] args){ /* Make sure you have completed the Stock class definition before completing the following items */ /* Step 1: * Create two Stock objects. For the first, use the no-arg constructor * and use the data for oracle corp shown in the assignment. For the * second, use the constructor with arguments providing a stock symbol * and name of your choice. Set the two price values for the second * stock using the set methods. Display the stock info (using toString) * and the percent change for both stocks, (formatting the percent). */ String Goog; String Google; Stock firstStock = new Stock(); Stock secondStock = new Stock("Goog", "Google"); secondStock.setPreviousClosingPrice(20000.00); secondStock.setCurrentPrice(40000.00); System.out.println("First Stock info " + firstStock.toString()); System.out.println("Second Stock info " + secondStock.toString()); System.out.println("First Stock percent change:" + firstStock.getChangePercent() + " \nSecond Stock precent change:" + secondStock.getChangePercent()); /* * Step 2: Test the equals method. Show two tests, one where the stocks * are equal, one where they are not. */ if(firstStock.equals(secondStock)){ System.out.println("Stocks percent change is equal."); } else { System.out.println("Stocks percent change isn't equal."); } /* * Step 3: Declare an array of 5 Stock objects. Initialize the array * elements with Stock objects, allowing the user to enter the data * for each object. Output all Stocks in the array using the toString * method. */ Stock[] stockArray = new Stock[5]; for(int i = 0; i < stockArray.length; i++){ stockArray[i] = new Stock(); } /* * Step 4: Write a printStocks method that accepts the stock array and * prints all of the Stocks using the to String method. Call your method * here. You can remove the display of the stocks from Step 3. */ printStocks(stockArray); printLowAndHighPercentChange(stockArray); } public static void printStocks(Stock[] stockArray){ for(int i = 0; i < stockArray.length; i++){ stockArray[i] = new Stock(); } System.out.println("Third Stock info " + stockArray[0].toString()); System.out.println("Fourth Stock info " + stockArray[1].toString()); System.out.println("Fifth Stock info " + stockArray[2].toString()); System.out.println("Sixth Stock info " + stockArray[3].toString()); System.out.println("Seventh Stock info " + stockArray[4].toString()); } /* Step 5: Find and report on which stock had the lowest percentage * change, and which stock had the highest percentage change. */ public static void printLowAndHighPercentChange(Stock[] stockArray){ double min; double max; for(int i = 0; i < stockArray.length; i++){ stockArray[i] = new Stock(); min = stockArray.getChangePercent();
if(stockArray[i].getChangePercent() < min){
min = stockArray[i].getChangePercent();
}
System.out.println("Stock " + stockArray[i] + "had the lowest percent change at: " + min);
}
for(int i = 0; i < stockArray.length; i++){
stockArray[i] = new Stock();
max = stockArray[i].getChangePercent();
if(stockArray[i].getChangePercent() > max){
max = stockArray[i].getChangePercent();
}
System.out.println("Stock " + stockArray[i] + "had the highest percent change at: " + max);
}
}
}
Thanks!!
Edited by: sabre150 on Nov 19, 2012 6:54 AM
Moderator action : added [code ] tags to format the code and make it readable. Please do this for yourself in the future.
This content has been marked as final. Show 1 reply
1. Re: infinite loop ;(sabre150 Nov 19, 2012 6:59 AM (in response to 974869)You need to learn to debug code and the simplest way for you to do this at the moment is to put lots of System.out.println() statements in your code so you can see what is happening.1 person found this helpful
|
https://community.oracle.com/thread/2467505?tstart=165
|
CC-MAIN-2016-36
|
refinedweb
| 777
| 51.85
|
Ferris provides a couple of decorators to help with using the App Engine Memcache API. Caching items in memcache can significantly reduce the cost of running your application while at the same time making your application more responsive.
Decorator that given a cache key and optionally a time to live will automatically cache the result of a function in memcache. The next time the function is called it will return the result from memcache (if it’s still there). This decorator does not take arguments to the wrapped function into account- you can use cached_by_args for that.
This function also adds the cached, uncached, and clear_cache functions to the wrapped function that allow you to get the cached and uncached values and clear the cache.
For example:
from ferris import cached @cached('my-key') def do_something_slow(): return herd_cats() # First call will prime memcache, subsequent calls will get the result from memcache. r = do_something_slow() # This skips memcache and always returns a fresh value. Does not update memcache. r = do_something_slow.uncached() # This clears the value in memcache so that the subsequent call returns a fresh value. do_something_slow.clear_cache()
Similar to @cached, but takes arguments into account. It will turn each argument into a string an use it as part of the key. If the first argument is ‘self’ or ‘cls’, it will ignore it.
|
http://ferris-framework.appspot.com/docs21/users_guide/memcache.html
|
CC-MAIN-2017-13
|
refinedweb
| 222
| 62.98
|
This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.
Most people forget that when performing an identity comparison between numeric/boolean types, they might be using boxed versions... not the primitives.
The example shows a typical case. There should be a hint to either:-
- unbox the Type to a primitive, e.g. use .longValue()
- use .equals()
The hint could serve as a reminder for case b below when dealing with (at least)
- Boolean
- Byte
- Character
- Short
- Integer
- Long
- Float
- Double
similar to the way there is a warning when String is identity compared.
@see
================
public class Scratch {
public static final void main(String[] args) {
Long n = new Long(0);
// XXX not always true! 0 is being boxed to Long
System.out.println(n == 0);
Long m = new Long(0);
System.out.println(n == m);
}
}
|
https://bz.apache.org/netbeans/show_bug.cgi?id=164089
|
CC-MAIN-2020-16
|
refinedweb
| 153
| 65.73
|
Let’s define a simple digital root (PCR) of a natural number N as follows
way. If N is a prime number, then PCC (N) = N. If the number
unambiguous, but not simple (i.e. 1, 4, 6, 8, or 9), then PCC (N) = 0.
In other cases, PCK (N) = PCK (S (N)), where S (N) is the sum of the digits of N.
Input data The input file INPUT.TXT contains the number N (1 ≤ N ≤
231-1).
Output Write a simple digital root to the OUTPUT.TXT file
numbers N.
Please note, in “other cases” a kind of recursion is obtained. Personally, I just didn’t notice it at first. Well, noticing this, I decided to use the solution through recursion.
# include & lt; bits / stdC++. h & gt; using namespace std; bool check_prime (long long n) // check for simplicity { if (n == 1) // & lt; - seems to be superfluous, but how without it? return false; for (int i = 2; i * i & lt; = n; i ++) if (n% i == 0) return false; return true; } int sum (long long n) // sum of digits of the number { int sum = 0; // seems to be quite optimized while (n! = 0) { sum + = n% 10; n / = 10; } return sum; } long long root (long long n) // simple root { if (check_prime (n)) // in theory, conditions can be optimized here. return n; else if (n & lt; 10) return 0; else return root (sum (n)); } int main () { long long n; cin & gt; & gt; n; cout & lt; & lt; root (n); }
However, on one of the tests my program fails – it takes too long. In fact, I do not understand at all why my program takes a long time. Here, in theory, tail recursion and, therefore, it does not work much and for a long time. A simplicity check for the largest number
2 ^ 31 - 1 needs to be
sqrt (2 ^ 31 - 1) ~ 2 ^ 16 = 65536 iterations, which is very doable. How can you optimize the program? And what could be the problem?
Answer 1, authority 100%
Look, 2 ^ 31-1 = 0x7FFFFFFF. What happens for this number (actually, for any of the range 2147395601-2147483647)? When you check
i * i & lt; = n
first, the product of two
int s is calculated – in the form of
int .
So 1, 2, 3 … –
i * i & lt; = n . We get to 46340 – no, 2147395600 is still less … 46341? Square – 2147488281, right? No, not so – because this is more than you can fit into
int , so formally it’s UB, but informally – this number is truncated and turns into -2147479015 – yes, exactly in negative.
It is then converted to
long long for comparison, but this does not change its sign, and we get an eternal loop …
So you just need to – well, these are the input data – fix it
for (int i = 2;
to
for (long long i = 2;
P.S. Well, or write something like
# include & lt; bits / stdC++. h & gt; #define r return int i, N, z; p () {for (i = sqrt (N); i & gt; 1;) if (N% i - == 0) r 0; r N & gt; 1;} K () {rp ()? N: N & gt; 9? [] () {Z = 0; do z + = N% 10; while (N / = 10); N = z;} (), K (): 0;} main () {std :: cin & gt; & gt; N; std :: cout & lt; & lt; K ();}
🙂
Answer 2, authority 33%
For numbers larger than
2 ^ 15.5 , an integer overflow occurs when calculating
i * i . Evaluate the root of
n (once, before the loop) and use in the loop condition.
More. Check division by 2 separately, and then
for (int i = 3; ...; i + = 2) .
|
https://computicket.co.za/c_plus_plus-the-task-of-finding-a-simple-digital-root-c/
|
CC-MAIN-2022-21
|
refinedweb
| 585
| 81.12
|
Chatlog 2011-10-13, az, pfps, macted <sandro> GUEST: Tim (tlebo) Lebo, RPI <sandro> Oops, we didnt have RRSAgent for the introductions.... 00:54:32 <LeeF> LeeF has joined #rdf-wg 11:26:24 <RRSAgent> RRSAgent has joined #rdf-wg 11:26:24 <RRSAgent> logging to 11:26:30 <Zakim> Zakim has joined #rdf-wg 11:26:33 <pfps> pfps has joined #rdf-wg 11:26:34 <sandro> zakim, this is rdf2wg 11:26:34 <Zakim> ok, sandro; that matches SW_RDFWG(F2F)6:00AM 11:26:40 <Guus> zakim, who is here? 11:26:40 <Zakim> On the phone I see ??P0, Peter_Patel-Schneider, MIT_Meeting_Room, AZ 11:26:41 <Zakim> On IRC I see pfps, Zakim, RRSAgent, LeeF, Scott_Bauer, pchampin, AZ, Souri, AlexHall, mox601, iand, cygri, tlebo, gavinc, danbri, ivan, swh, Guus, AndyS, ww, ericP, yvesr, manu, 11:26:43 <Zakim> ... NickH, trackbot, manu1, sandro 11:27:03 <sandro> 11:27:09 <davidwood> davidwood has joined #rdf-wg 11:27:29 <sandro> RRSAgent, make logs public 11:27:39 <Guus> scribe? 11:28:36 <ivan> zakim, MIT_Meeting_Room also has Guus, thomas, danbri, steve, ivan, richard, andy, ian, pchamplin, yves, nicholas 11:28:36 <Zakim> +Guus, thomas, danbri, steve, ivan, richard, andy, ian, pchamplin, yves, nicholas; got it 11:28:57 <ivan> zakim, MIT_Meeting_Room also has micha 11:28:57 <Zakim> +micha; got it 11:31:49 <yvesr> scribe yvesr 11:32:00 <ivan> scribenick: yvesr 11:32:04 <ivan> scribe: yvesr 11:32:14 <tomayac> tomayac has joined #rdf-wg 11:32:19 <yvesr> Guus: let's start with Pat's email 11:32:21 <tomayac> scribenick: tomayac 11:32:31 <ivan> scribe: tomayac 11:33:38 <LeeF> zakim, MIT_Meeting_Room also has TedT 11:33:38 <Zakim> +TedT; got it 11:33:56 <Guus> 11:33:57 <tomayac> Guus suggests to start with ISSUE-71 11:34:23 <tomayac> was originally ISSUE-12, but got closed and is now ISSUE-71 11:34:35 <sandro> issue-71 11:34:37 <sandro> issue-71? 11:34:37 <trackbot> ISSUE-71 -- Reconcile various forms of string literals (time permitting) -- open 11:34:37 <trackbot> 11:34:39 <tomayac> we can either do nothing, or option 2d 11:34:44 <Guus> Proposal for Issue 12 11:34:50 <tomayac> people could live with that 11:35:02 <tomayac> any further discussion required? 11:35:19 <tomayac> got extensively discussed 11:35:27 <tomayac> marked as a feature at risk 11:36:08 <AndyS> and also let RDFa know 11:36:47 <tomayac> AndyS: makes the spec a little cleaner 11:36:49 <mischat> mischat has joined #rdf-wg 11:37:02 <tomayac> Guus: objections? 11:38:27 <Guus> t 11:38:28 <trackbot> ISSUE-71 Reconcile various forms of string literals (time permitting) notes added 11:39:11 <gavinc> gavinc has joined #rdf-wg 11:39:41 <cygri> PROPOSAL: Resolve ISSUE-71 by adopting the phrasing in 11:40:09 <AZ> AZ has left #rdf-wg 11:40:18 <MacTed> MacTed has joined #rdf-wg 11:40:22 <AZ_> AZ_ has joined #rdf-wg 11:40:55 <AZ_> AZ_ has joined #rdf-wg 11:41:05 <LeeF> Can someone paste the wiki page or email that had the various options in it? (the place at which this was option 2d)? 11:41:11 <Souri> Souri has joined #RDF-WG 11:41:15 <ivan> PROPOSAL: Resolve ISSUE-71 by adopting the phrasing in 11:41:33 <davidwood> +1 11:41:36 <AlexHall> AlexHall has joined #rdf-wg 11:41:40 <AndyS> +1 11:41:44 <iand> +0 11:41:46 <AZ_> +1 11:41:47 <cygri> +1 11:41:48 <LeeF> I'm happy with this 11:41:51 <yvesr> +1 11:41:54 <tomayac> Guus: please click on the link, too log to paste. marks a feature at risk. 11:41:58 <pfps> +epsilon 11:42:03 <AlexHall> +1 11:42:12 <NickH> +1 11:42:12 <ivan> -> is the poll result 11:42:13 <tomayac> Guus: Resolved. 11:42:13 <ivan> +1 11:42:22 <gavinc> +0 11:42:32 <ivan> RESOLVED: Resolve ISSUE-71 by adopting the phrasing in 11:42:52 <AndyS> ε > 0 11:43:23 <sandro> +1 it's good enough for 2011; someday maybe we can add more URIs for language tags 11:43:31 <tomayac> Guus: dave proposed to have a discussion on sandro's proposal. 11:43:33 <davidwood>:43:45 <Souri_> Souri_ has joined #RDF-WG 11:43:55 <iand> what are dataset IRIs? 11:44:15 <pfps> I worry about "flying flags" in RDF, particularly if this means building a theory into the semantics of RDF. 11:44:46 <mischat> we would need to inform the RDF 1.1 people about the previous resolution re: manu's email 11:45:01 <tomayac> ivan: sandro, when you say provide some case to flag the cases, what do you mean? 11:45:09 <tlebo> I think is related 11:45:13 <AndyS> tag: denote g-box? Should that be g-snap? 11:45:30 <Souri_> Could you please put the proposal on IRC one more time? 11:45:30 <LeeF> I support this goal, but I worry that adopting it might mean that we are inventing like 4 new mechanisms for communicating this which don't currently exist 11:45:40 <LeeF>:46:16 <Guus> q? 11:46:25 <tomayac> sandro: there are two different kinds of data sets 11:46:30 <tlebo> q+ 11:46:39 <AndyS> The word "tag" is confusing me somewhat. 11:46:48 <iand> sandro, when you say tag do you mean the names in named graphs 11:47:00 <gavinc> I think he does. 11:47:22 <sandro> "NameTag" Datasets vs "KeyTag" Datasets 11:47:34 <mischat> scribe mischat 11:47:41 <davidwood> q+ to suggest there is no reason to find that anything "denotes" anything else until we address Pat's CoU proposal. It may in fact be dangerous to do so. 11:47:43 <swh> scribenick: mischat 11:47:47 <ivan> scribenick: mischat 11:47:56 <tlebo> attempt to reconcile the "tag" with an actual, implied URI: 11:48:10 <mischat> sandro: is asking Andy what is the other word you use instead of name 11:48:16 <mischat> ? 11:48:27 <iand> iand has joined #rdf-wg 11:48:30 <AndyS> AndyS has joined #rdf-wg 11:48:39 <sandro> AndyS, is "label" better than "tag"? 11:48:39 <mischat> s/Andy/Tim/ 11:48:49 <danbri> danbri has joined #rdf-wg 11:49:14 <gavinc> I'll just call it <> ;) 11:49:22 <mischat> tlebo: is trying to reconcile the graph insert in the graph* terminology ^^ 11:49:59 <mischat> tlebo: the example inserts the same triples into two graph containers 11:50:15 <sandro> q+ 11:50:30 <gavinc> ack tlebo 11:50:36 <mischat> tlebo: the proposal is trying present what an insert does in terms on graph* terminology 11:51:04 <mischat> tlebo: the proposal is different from sandro's as the global graph container is different 11:51:14 <swh> q+ to as about the intent 11:51:19 <mischat> q? 11:51:30 <tlebo> archived view: 11:51:34 <ivan> ack davidwood 11:51:34 <Zakim> davidwood, you wanted to suggest there is no reason to find that anything "denotes" anything else until we address Pat's CoU proposal. It may in fact be dangerous to do so. 11:51:45 <AndyS> AndyS has joined #rdf-wg 11:52:28 <Guus> q? 11:52:35 <mischat> davidwood: is concerned about the WG making a finding about how an IRI should be making a decision on what "denotes" when there is no Pat around 11:52:43 <mischat> … and given cygri's email 11:52:53 <mischat> davidwood: would like to move this issue out for the time being 11:52:56 <mischat> q? 11:53:05 <sandro> ack sandro 11:53:23 <mischat> sandro: is asking AndyS what is a better name than tag 11:53:26 <sandro> ReferingNameDatasets vs MerelyTaggingNameDatasets 11:53:30 <Souri_> Shall we refer to it as graph-IRI (to avoid "name" and all those ~4-letter words)? :-) 11:53:39 <tlebo> "name" might, but not 11:53:54 <sandro> ReferingNameDatasets vs MerelyLabelingNameDatasets 11:53:54 <mischat> sandro: is asking if there are two different ways about talking about a dataset 11:54:04 <swh> q- 11:54:07 <mischat> Guus: are you talking about "labelling" 11:54:22 <mischat> " various people " tagging and labelling sound like the same thing 11:54:43 <gavinc> label == name == context == graph name == graph iri == graphName == graph tag ? 11:54:59 <Guus> q? 11:55:32 <iand> sandro, are you asking for the WG to explore a way for datasets to optionally declare that the labels for graphs denote those graphs? 11:55:45 <mischat> sandro: thinks that in sparql it is merely an association 11:55:45 <mischat> davidwood: where the tag is an identifier to what happens have an HTTP Get operation 11:56:08 <mischat> sandro: the name in the, sense of REST, identifies the graph-container 11:56:27 <pchampin> q+ to propose an analogy 11:56:29 <danbri> q? 11:56:30 <mischat> sandro: name identifies and refers to a graph-container ? 11:56:39 <mischat> or s//?$// 11:57:04 <mischat> Guus: sandro could you please formulate your proposal ? 11:57:25 <iand> q+ andys 11:57:30 <davidwood> s/given cygri's email/given Pat's email/ 11:58:14 <ivan> zakim, who is here? 11:58:14 <Zakim> On the phone I see ??P0, Peter_Patel-Schneider, MIT_Meeting_Room, AZ 11:58:15 <Zakim> MIT_Meeting_Room has MIT_Meeting_Room, Guus, thomas, danbri, steve, ivan, richard, andy, ian, pchamplin, yves, nicholas, micha, TedT 11:58:18 <Zakim> On IRC I see danbri, iand, Souri_, AlexHall, AZ_, MacTed, gavinc, mischat, tomayac, davidwood, pfps, Zakim, RRSAgent, LeeF, Scott_Bauer, pchampin, mox601, cygri, tlebo, ivan, swh, 11:58:20 <Zakim> ... Guus, ww, ericP, yvesr, manu, NickH, trackbot, manu1, sandro 11:58:56 <Guus> zakim, ??p0 is BBC 11:58:56 <Zakim> +BBC; got it 11:59:06 <cygri> zakim, I'm with BBC 11:59:06 <Zakim> +cygri; got it 11:59:17 <mischat> zakim, I'm with BBC 11:59:17 <Zakim> +mischat; got it 11:59:22 <MacTed> MacTed has joined #rdf-wg 11:59:26 <sandro> STRAWPOLL: There is a kind of dataset (a "type-2 dataset) dat 11:59:26 <sandro> asets. 11:59:38 <AndyS> AndyS has joined #rdf-wg 12:00:03 <LeeF> q+ 12:00:04 <NickH> zakim, I'm with BBC 12:00:05 <Zakim> +NickH; got it 12:00:07 <cygri> q+ 12:00:18 <yvesr> Zakim, i'm with BBC 12:00:18 <Zakim> +yvesr; got it 12:00:39 <mischat> ack pchampin 12:00:39 <Zakim> pchampin, you wanted to propose an analogy 12:00:54 <mischat> pchampin: thinks he like the proposal. 12:01:48 <mischat> pchampin: there is an analogy: in a school you would ask to have a label on every coat. But you wouldn't be labelling the coat 12:01:57 <mischat> pchampin: like the proposal 12:02:00 <mischat> ack AndyS 12:02:16 <mischat> AndyS: thinks type2 is restrictive 12:02:37 datasets. 12:02:40 <cygri> q+ to say that it's not “types” of datasets but patterns of use 12:02:41 <mischat> … and there is another proposal where the IRI - is a label for a g-snap is the more general case 12:02:44 <gavinc> +q to ask how we are identifying the dataset so that we can type it? 12:02:58 <zwu2> zwu2 has joined #rdf-wg 12:03:05 <mischat> sandro: agrees with sandro 12:03:30 <iand> zakim, I'm with BBC 12:03:30 <Zakim> +iand; got it 12:03:33 <tlebo> we should also propose the convention for how anyone can awww:identify "type-1 datasets" as "type-2 datasets" given the "type-1 dataset"'s "name" (the convention would derive from) 12:03:49 <mischat> AndyS: understands that the proposal fits in with sandro's Web Semantic proposals 12:04:05 <danbri> q+ to ask if it's the dataset that's typed, or the entry in it...? 12:04:10 <mischat> sandro: isn't sparql today a type 1 12:04:38 <mischat> sandro: how about a type-3 being an IRI referring to a gsnap 12:04:42 <mischat> sandro: how about a type-3 being an IRI referring to a g-snap 12:05:12 <mischat> AndyS: would like to see a world while there are different Contexts, as per Pat's suggestion. AndyS doesn't like the current proposal 12:05:16 <AndyS> q? 12:05:41 <ivan> ack LeeF 12:06:00 <mischat> …. seems to give privilege to type 1, and AndyS thinks that this is not the right thing. 12:06:17 <AlexHall> +1 LeeF 12:06:28 <swh> +1 12:06:30 <pchampin> q+ 12:06:41 <mischat> LeeF: this seems to suggest that we will be prescribe a handle of various ways to do RDF, and this is not the best thing to do … 12:06:48 ". Some people want to use type-2 datasets, but people are using type-1 datasets and we can't just mandate type-2. We should provide a standard way for people to indicate when they are using type-2 data 12:06:48 <sandro> sets. 12:06:58 <tlebo> @AndyS, while others can have different contexts, anyone should still be able to awww:identify others' contextualized forms. 12:07:03 <LeeF> s/to do RDF/to annotate RDF to specify which type of dataset you're using 12:07:06 <ivan> ack cygri 12:07:06 <Zakim> cygri, you wanted to say that it's not “types” of datasets but patterns of use 12:07:12 <Guus> ack cygri 12:07:20 <mischat> cygri: thinks it is mistake phrasing this as a type of dataset 12:07:47 <swh> q+ 12:08:03 <iand> Alternate STRAWPOLL phrasing: We should provide a standard way for people to indicate when their the "name" IRIs in their dataset both refers to and awww:identifies the "graph", really a GraphContainer. 12:08:06 <sandro> But I need *interop* of them, 12:08:06 <mischat> cygri: thinks that sandro's approach is not ideal, there is lots of talk about different ways which you can make use of a dataset 12:08:08 <AndyS> "There is a usage of dataset where the "name" IRI both refers to and awww:identifies the "graph", really a GraphContainer. " but ... 12:08:47 <mischat> cygri: but thinks that the current setup allows for sandro's type 2 dataset, and doesn't think that we should give a privileged status to a given way of using a dataset 12:08:50 <tlebo> but how does a third party uniformly refer to a SPARQL endpoint's GraphContainer? 12:08:54 <AndyS> ... then is there behind that a work item for the WG for this form, not others? Is the recognition of this work item the reason for the proposal? 12:09:29 <sandro> +1 Ian's rephrasing 12:09:43 <AndyS> (see Pat's email) 12:09:49 <yvesr> scribe: yvesr 12:09:52 <mischat> scribenick yvesr 12:09:57 <danbri> q? 12:10:06 <ivan> scribenick: yvesr 12:10:09 <sandro> (scribenick is unnecessary with commonscribe, fwiw.) 12:10:17 <AndyS> 12:10:19 <davidwood> +1 to Ian's rephrasing 12:10:23 <Souri_> +1 to David's thoughts that Ian's rephrasing is compatible with Pat's CoU suggestion 12:10:24 <yvesr> Guus: would cygri be more happy with iand's rephrasing? 12:10:29 <mischat> q? 12:10:31 <yvesr> +1 12:10:39 <gavinc> ack me 12:10:39 <Zakim> gavinc, you wanted to ask how we are identifying the dataset so that we can type it? 12:10:40 <ivan> ack gavinc 12:10:53 <tlebo> But how does a third party awww:identify graphs within SPARQL endpoints that do NOT provide @iand's indication? 12:11:01 <yvesr> gavinc: only worry about sandro's proposal - how are we supposed to refer to the dataset? 12:11:10 <yvesr> gavinc: we're on our way to create 'named datasets' 12:11:17 <AndyS> Maybe SPARQL service description helps here. 12:11:27 <yvesr> gavinc: how are we supposed to make assertions about a dataset atm? 12:11:30 <cygri> q+ to answer gavinc 12:11:36 <pchampin> q+ to solve gavin's problem 12:11:46 <AndyS> ... which is "service" not dataset but that's the visible useable thing. 12:12:01 <yvesr> gavinc: sparql descriptions help for sparql end points - how do i move it around a trig dataset? 12:12:02 <sandro> q+ to talk about TriG metadata 12:12:12 <pchampin> 12:12:13 <ivan> ack pchampin 12:12:13 <Zakim> pchampin, you wanted to solve gavin's problem 12:12:42 <sandro> +1 pchampin and graph literals!!! 12:12:43 <yvesr> pchampin: coming back to the proposal i made a while ago - it would be improved by ivan's proposal to work with a datatype 12:13:02 <yvesr> pchampin: if we had graph literals and a vocabulary to express these relationships, then we could be unambiguous 12:13:31 <sandro> +999999 12:13:34 <yvesr> pchampin: not saying it should be how dataset should be implemented, but at least that's a unifying vocabulary to describe this 12:13:37 <yvesr> +99999 too 12:13:41 <ivan> ack cygri 12:13:41 <Zakim> cygri, you wanted to answer gavinc 12:13:54 <yvesr> cygri: makign statements about dataset is easy - just give it a URI 12:14:12 <yvesr> cygri: the SPARQL service description gives us a mechanism to do that 12:14:17 <Guus> q? 12:14:24 <yvesr> cygri: the URI of the Trig file is a good URI to make statements about the dataset 12:14:30 <iand> we already have draft text in RDF Concepts defining an RDF Dataset: 12:14:39 <yvesr> cygri: the problem sandro's trying to solve is to know when a dataset is using a particular convention 12:14:40 <Souri_> s/makign /making / 12:14:45 <danbri> so we don't lose it in the scrollback, --> 12:14:46 <danbri> [13:08] <iand> Alternate STRAWPOLL phrasing: We should provide a standard way for people to indicate when their the "name" IRIs in their dataset both refers to and awww:identifies the "graph", really a GraphContainer. 12:14:49 <yvesr> cygri: having a statement asserting it doesn't solve that problem 12:15:02 <tlebo> Regarding "how does the GraphContainer description travel with TRIG, etc, non-SPARQL" - use service description's sd:NamedGraph/sd:GraphCollection, and replace sd:Service/sd:availableGraphDescriptions () 12:15:02 <sandro> can I respond? 12:15:07 <yvesr> cygri: people lie on the Web - these statements could be false 12:15:24 <danbri> q? 12:15:25 <yvesr> cygri: ... except if you trust the provider of the statement and the dataset to do the right thijng 12:15:50 <yvesr> cygri: people are also wrong with mimetypes 12:15:55 <AndyS> "This WG will write a practice and experience note about using NG IRIs to both refers to and awww:identifies the "graph(g-box)", really a GraphContainer. " 12:16:05 <yvesr> q+ 12:16:12 <yvesr> q- 12:16:19 <ivan> ack danbri 12:16:19 <Zakim> danbri, you wanted to ask if it's the dataset that's typed, or the entry in it...? 12:16:24 <sandro> sandro: It's kjust like mime types --- sometimes they are wrong, sometimes people lie -- but they are still useful. 12:16:25 <davidwood> gavinc should respond, too. I'm curious whether describing data out-of-band with triples is acceptable to him. 12:16:34 <yvesr> cygri, i think it is still *much* more useful than *asumming* something tha tmay be wrong or controversial 12:16:43 <cygri> sandro, you're wrong on that. in sindice we do large-scale RDF processing and we have to ignore mime types. 12:16:58 <sandro> danbri: I'd like smaller granularity, like Ian's strawpoll, instead of Sandro's 12:17:03 <yvesr> danbri: ian's reformulation is more concrete 12:17:16 <tomayac> tomayac has joined #rdf-wg 12:17:32 <yvesr> danbri: in my store, i can have URIs of FOAF files, RSS feeds... I'd love to have descriptions to explain how my data is managed 12:17:38 <sandro> I'm okay with DanBri's, but I thikn it might be harder. 12:17:48 <ivan> ack swh 12:17:51 <Guus> q? 12:18:14 <yvesr> swh: another concern: type-1 includes some things that are undesirable - includign using people URIs as graph identifiers 12:18:32 <gavinc> Out of band triples are totally fine, I'm just confused as to how "just name things with URIs is easy" and the last months of conversations about what exactly naming graphs means are reconcilable? 12:18:44 <AndyS> +1 to "there are bad ways of doing 'associates'" (bad = wrong) 12:18:57 <sandro> NamedGraphs is either: LabeledGraphs and ReferedToGraphs 12:19:07 <sandro> (or Identified Graphs?) 12:19:29 <cygri> LabeledGraphs would be more accurate for what we have in SPARQL. that ship has sailed though :-( 12:19:45 <yvesr> swh: my concern is mainly that enumariting all possibilities is going to be very difficult, and chances of getting it wrong are high 12:19:46 <danbri> e.g. my store might have one graph (for latest version) <> and also the transactions stashed using <uuid:12341234>. A manifest / table of contents / sitemap for the database should let me express that I've done this. But *also* it should let me express mappings from technical entities (servers, accounts, crypto) to social entities (people, orgs, ...). 12:19:46 <Guus> q? 12:19:59 <MacTed> MacTed has joined #rdf-wg 12:20:03 <yvesr> swh: the chances that someone actually use it are infinitely small 12:20:03 <sandro> cygri, I agree that ship has sailed -- but we can launch another ship. 12:20:11 <AndyS> q+ 12:20:27 <sandro> "IdentifiedGraphs" 12:20:29 <danbri> q+ to argue for the social use case too (swh mentioned...) 12:20:44 <ivan> ack sandro 12:20:44 <Zakim> sandro, you wanted to talk about TriG metadata 12:21:02 <yvesr> sandro: trig bizarelly has no way to specify metadata 12:21:13 <yvesr> sandro: no way to assert who is the author or a trig file 12:21:15 <AndyS> <> dc:creator "me" . 12:21:23 <tlebo> +1 AndyS 12:21:26 <yvesr> sandro: you can put the metadata in the default graph 12:21:50 <pchampin> ... but some people argued that the default graph is not more assertive than named graphs 12:21:58 <AndyS> (no different from situation for an RDF graph as far as I can see) 12:22:06 <yvesr> sandro: it would be nice to have a standard place - and what about metadata about metadata? who is the author of the author of the trig annotation? 12:22:07 <cygri> AndyS++ 12:22:29 <yvesr> sandro: which graph has the metadata in it? 12:22:40 <pchampin> @Andy: well, if you chose to believe an RDF file, you have to believe what it says about itself 12:22:51 <iand> q? 12:22:51 <mischat> shouldn't this sit in a Linked Data primer or similar 12:22:52 <Guus> q? 12:22:58 <gavinc> +q to respond 12:23:00 <yvesr> sandro: it seems like it would fail when you're carrying someone else's metadata 12:23:13 <AlexHall> (MIT discussion re metadata graphs described with special rdf:types...) 12:23:38 <swh> <G#meta> { <> dc:subject <G> ; a :MetadataGraph } … or something 12:23:56 <ivan> q? 12:23:59 <LeeF> LeeF: In Anzo, we have "metadata graphs" that give metadata about the graphs. We can also use it to give metadata about datasets, which are first-class objects (i.e. with URIs, etc.) in Anzo 12:24:05 <ivan> ack AndyS 12:24:18 <yvesr> AndyS: about ian's phrasing, i'd change the word 'standard' 12:24:29 <yvesr> AndyS: we'll write a 'practice and experience' note - non-normative 12:24:34 <mischat> +1 to AndyS 12:24:46 <zwu2> +1 AndyS 12:24:50 <LeeF> swh, yes, that's very much what we do 12:24:59 <sandro> If it's not a standard, then ... how does it work? 12:25:01 <swh> LeeF, ditto 12:25:03 <yvesr> danbri: convention? 12:25:09 <tlebo> awww:identifying a GraphContainer in a TRiG file using fragment identifiers? e.g. 12:25:10 <yvesr> AndyS: best practice would work for me 12:25:13 <danbri> q? 12:25:24 <ivan> (what was also said) maybe defining Classes so that rdf:type could be used 12:25:26 <davidwood> In Callimachus, we assign a URI to each data "file" when loaded, thus making a named graph from it. Anyone can upload metadata about a named graph by referring to its URI. Therefore, our approach is similar conceptually to LeeF's. 12:25:29 <iand> i think we could define a class for this type of dataset. that's all we need 12:25:50 <yvesr> danbri: named graphs give you technical partition of your data - not social partition - you need out of band information 12:26:03 <ivan> iand, or a class for this type of (n,G) association, not the whole dataset 12:26:06 <yvesr> danbri: i hope this best practice note tackles that 12:26:06 <pchampin> q? 12:26:07 <LeeF> davidwood, do you do anything different do if you're loading a trig file that defines multiple graphs? 12:26:14 <davidwood> yes 12:26:23 <davidwood> We make multiple graphs 12:26:34 <ivan> q? 12:26:34 <sandro> q+ to say danbri, can't you build that with a vocabulary on top of IdentifiedGraphs ? 12:26:37 <ivan> ack davidwood 12:26:41 <yvesr> danbri: we haven't shown the way on how to make the most of sparql, including this social use-case 12:26:43 <danbri> sandro, yes, we can do. 12:26:44 <ivan> ack danbri 12:26:44 <Zakim> danbri, you wanted to argue for the social use case too (swh mentioned...) 12:26:48 <ivan> ack gavinc 12:26:48 <Zakim> gavinc, you wanted to respond 12:26:49 <pchampin> @danbri: but then, whouldn't it be nice to have this "out of band" information in RDF? 12:27:07 <danbri> (...just arguing that the use case is at least as important as the 'what url i got it from' use case which we've spent hours talking about in various forms) 12:27:13 <danbri> (possibly more important, ultimately) 12:27:19 <yvesr> gavinc: about AndyS's proposal of just adding a triple to a trig file - which graph does that go in? 12:27:28 <danbri> (since so much data will be acquired transactionally, e.g. oauth'd) 12:27:40 <iand> in we define RDF Dataset and we could also define an RDF Denoting Dataset to be an RDF Dataset where the graph names denote the graphs 12:27:44 <yvesr> gavinc: maybe that is enough 12:27:57 <yvesr> gavinc: but if we're all doing it, there should be common practices 12:28:08 <Guus> wonder whether we can get a straw polln a revised phrasing 12:28:11 <sandro> +1 iands, not sure about the name "Denoting", but yes. 12:28:16 <yvesr> gavinc: right now, i have no idea how that works 12:28:19 <Guus> q? 12:28:34 <cygri> iand, that would rather have to go into RDF Semantics i think 12:28:42 <yvesr> AndyS: i don't care how the triple goes - it is an assertion, it could go in many different places 12:29:03 <gavinc> thanks AndyS 12:29:07 <ivan> ack sandro 12:29:07 <Zakim> sandro, you wanted to say danbri, can't you build that with a vocabulary on top of IdentifiedGraphs ? 12:29:19 <yvesr> Guus: are we nearing a point where we can put a modified strawpoll? 12:29:35 <yvesr> sandro: AndyS, I don't think that works - we need an assertive metadata format 12:29:47 <yvesr> sandro: TriG files carry stuff they're not asserting 12:29:51 <yvesr> cygri: where does this come from? 12:29:57 <iand> cygri: we use denotes in RDF Concepts 12:30:06 <yvesr> cygri: i wrote that spec, and it doesn't say anything in that respect 12:30:28 <AndyS> sandro - can you point to concrete text that lead you to that conclusion? 12:30:44 <tlebo> what happened to <> ? 12:30:49 <AlexHall> 3 options for describing a dataset: (1) conventions for special naming or typing of metadata graphs, (2) add a fifth column, (3) reify the dataset 12:31:11 <yvesr> danbri: i agree this is a useful use case 12:31:22 <yvesr> s/danbri/sandro: danbri,/ 12:31:44 <sandro> STRAWPOLL: We should provide a standard way for people to indicate when their the "name" IRIs in their dataset both refers to and awww:identifies the "graph", really a GraphContainer. 12:31:50 <danbri> standards-based; ... 12:31:51 <yvesr> sandro: perhaps we could phrase it by saying 'somebody' should 12:32:14 <danbri> ... sparql-queriable, rdf-describable, ... conventions/ best practice, ... 12:32:30 <cygri> q+ 12:32:35 <AndyS> s/provide a standard way/write some text about/ 12:32:55 <Souri> Souri has joined #RDF-WG 12:33:30 <danbri> swh 'because there are so many, and there are so incredibly complex, it takes us a lot to describe and ... ... this one is a weird special case' 12:33:36 <NickH> +1 to swh 12:34:20 <sandro> AndyS, that s/// will alter the scribe record --- changing my proposed strawpoll ! 12:34:36 <ivan> STRAWPOLL: We should provide a standard way for people to indicate how their 'name' IRIs in their dataset both behave, such as when it awww:indentifies the graph, really a container 12:35:04 <cygri> q+ 12:35:06 <tlebo> any third party should be able to refer to another's GraphContainer, regardless of what the GraphContainer 'owner' offers. 12:35:10 <yvesr> sandro: i am ok with that 12:35:23 <yvesr> Guus: it opens for conventions we document, and conventions we don't document 12:35:38 <ivan> STRAWPOLL: We should provide a standard way for people to indicate how their 'name' IRIs in their dataset behave, such as when it aww:identifies the graph (really a container) 12:35:44 <iand> q+ 12:35:59 <ivan> ack cygri 12:36:00 <MacTed> s/their 'name'/the 'name'/ 12:36:15 <yvesr> cygri: i think this idea of indicating how they do it in their dataset is a waste of time 12:36:20 <yvesr> cygri: it just doesn't work 12:36:32 :36:45 <yvesr> cygri: there's nothing that encourages people to get that triple right 12:36:56 <yvesr> cygri: nothing bad happens when you get it wrong 12:37:02 <iand> q- 12:37:06 <danbri> q? 12:37:21 <sandro> cygri: This is a waste of time -- it just doesn't work. There is nothing that encourages people to get the triple right. Unless there is some Sandro-best-practice person running around.... 12:38:22 <AndyS> +1 to danbri suggestion. /me concerned about "standard" ==> else it's not a dataset. 12:38:39 <cygri> yvesr, yes that's what pedantic web did, and it doesn't scale 12:38:43 <iand> i disagree that it is a waste of time, lots of data is wrong but that doesn't mean we should prevent people from writing data 12:38:48 <sandro> sandro: Yeah, my main point is that it's beneficial 12:38:54 <yvesr> cygri, agreed, but trying to standardise the relationship won't work as well 12:38:54 <ivan> +1 to iand 12:38:58 <yvesr> cygri, we'll never get it right 12:39:04 <gavinc> +1 to iand 12:39:14 <swh> danbri's suggestion seems more plausible 12:39:29 <cygri> yvesr, i think it's useful to document this convention as a good practice. that's all 12:39:46 <swh> I strongly don't feel it's good practice 12:39:52 <yvesr> cygri, but what is the convention? i am not even sure we agree on that 12:40:00 <swh> its one possible way to hold data, but it's not even the best one 12:40:05 <yvesr> swh, +1 12:40:26 <cygri> yvesr, the convention is what sandro said 12:40:32 <sandro> STRAWPOLL: It would be useful to have data-providers using "Referring-IRI" datasets, and for data-consumers to get an indication of whether the data-provider claims to be doing so. 12:40:42 <yvesr> swh, or at least not the only way 12:40:52 <danbri> -1 12:40:54 <cygri> -1 12:40:55 <swh> -1 12:41:00 <tlebo> q? 12:41:00 <iand> -1 12:41:10 <danbri> Lots of things are useful to some people. but this has an advocacy feel. 12:41:29 <iand> (13:34:42) ivan: STRAWPOLL: We should provide a standard way for people to indicate how their 'name' IRIs in their dataset both behave, such as when it awww:indentifies the graph, really a container 12:41:41 <tlebo> The fact is, these things already implicitly exist - it's not a special case. It's universal! 12:42:29 <danbri> for me the issue is granularity --- 12:42:30 <tlebo> The (myriad, nuanced) relationships among anybody's GraphContainers should be described in RDF - and they should choose the vocabulary they want to describe those associations. 12:42:33 <sandro> STRAWPOLL: It would be useful to have data-providers using type-2 datasets, and for data-consumers to get an indication of whether the data-provider claims to be doing so. 12:42:35 <AndyS> alt -- "the WG writes up several usage scenarios " (so can say when to use and when not to) 12:42:48 <tlebo> so, all we need is A WAY to reference anybody's GraphContainers. 12:42:52 <danbri> in my stores some named graphs are referring IRIs, some are transactional, and there are RDF-describable links (derrivation, pipelines, etc) between them 12:42:59 <danbri> (inference even, on occasion) 12:43:24 <yvesr> danbri, +1 12:43:25 <ivan> STRAWPOLL: It would be useful to provide a standard way for people to indicate how their 'name' IRIs behave, such as when it awww:indentifies the graph, really a container 12:43:36 <cygri> -1 12:43:38 <pchampin> +1 12:43:43 <iand> +1 12:43:48 <sandro> +1 12:43:52 <danbri> 'behave' is a little anthroporphic, but sure +1 12:43:55 <gavinc> +1 12:43:56 <pfps> -epsilon 12:44:08 <yvesr> cygri: we should document patterns and conventions, *not* find a standard way 12:44:13 <davidwood> +0 12:44:13 <danbri> thought i think there is too much bias towards this specific use case, so i'll repeat 12:44:15 <danbri> [13:36] :44:16 <tlebo> ALL WE NEED is a way to reference anybody else's GraphContainer. Leave the rest to RDF. 12:44:17 <LeeF> 0 12:44:21 <pchampin> q+ 12:44:25 <yvesr> cygri: we don't have any interest at all documenting all others 12:44:32 <davidwood> +1 to cygri 12:44:44 <yvesr> Guus: it would be useful to document best practice conventions to document how their named IRIs behave 12:44:49 <iand> i think we have no consensus on even whether this is useful :( 12:45:01 <yvesr> cygri: it would be useful to document this one particular convention for using names 12:45:09 <danbri> cygri, I want to be able to sparql a store for subset of its content that is (per some notion of) 'stuff from/by Richard ...' 12:45:10 <sandro> I just want to know what <t> { <t> <p> <o> } means. :-/ 12:45:17 <davidwood> +1 to danbri's proposal 12:45:18 <yvesr> swh: i like danbri's suggestion from earlier 12:45:30 <yvesr> danbri: i want to go to my store, and get all the stuff from cygri 12:45:30 <tlebo> This isn't an opt-in thing, it ALREADY is. We just need a way to reference other's GraphContainers. 12:45:32 <iand> so we are saying we don't agree that it's useful for people to be able to describe their named graphs identifiers 12:45:32 <AndyS> sandro - Pat's proposal/idea? 12:45:34 <MacTed> maybe maybe maybe... 12:45:34 <MacTed> STRAWPOLL: It would be useful to have a standard way for people to indicate how the 'name' IRIs in their dataset behave, e.g., whether they awww:indentifies the graph (really a container), or when they only "refer to" the graph, or both 12:45:45 <danbri> i'm ok with guus's "behaves"; it addresses my use case 12:45:51 <gavinc> q? 12:45:54 <sandro> AndyS, I haven't read the whole thread, but probably. 12:45:58 <iand> s/describe their named graphs/describe the purpose of their named graph/ 12:46:15 <tlebo> RDF handle the "zillion" cases - just give me a URI! 12:46:32 <cygri> -1 to "best practice" 12:46:51 <zwu2> how about good practice? 12:46:52 <tlebo> q? 12:47:02 <cygri> zwu2, just "practice"? 12:47:06 <gavinc> okay, webarch conforming practice? 12:47:29 <yvesr> sandro: we don't have a consensus on any compromise 12:47:44 <yvesr> sandro: it makes no sense to have a uri denote multiple things 12:47:57 <swh> q+ 12:48:00 <pfps> yes, but what do URIs name/denote? 12:48:10 <sandro> resources. 12:48:14 <AZ> AZ has joined #rdf-wg 12:48:26 <pfps> sure, but we've had that since 2004 12:48:39 <danbri> sandro: "it was a small step in the right direction" [...] [...] [...] [...] 12:48:44 <tlebo> sd:name rdfs:subPropertyOf dcterm:identifier ---- handles the "oops, we aren't using URIs properly" 12:48:48 <yvesr> Guus: sandro, you started to say it's a small step in the rght direction 12:49:01 <yvesr> danbri: would you object to such a small step? 12:49:28 <AndyS> q? 12:49:42 <yvesr> swh: i don't understand sandro's logical leap 12:49:46 <sandro> sandro: (big rant a minute ago) It's kind of absurd to use IRIs as merely labels. 12:49:56 <gavinc> huh? 12:49:59 <yvesr> swh: there's no relation between having a uri denote a graph or a thing 12:50:00 <AndyS> Is this not what RDF does? Describe things? 12:50:00 <Guus> ack swh 12:50:13 <yvesr> sandro: an IRI should both identify and refer 12:50:20 <danbri> sandro, they're being used properly, just that there is a missing column for relationship type 12:50:21 <cygri> STRAWPOLL: The WG will non-normatively document a particular convention for using datasets, where in <u,G> the URI is denotes a graph container and G is the state of the container. 12:50:24 <yvesr> sandro: in SPARQL, graph URIs are not used that way - i think that's a problem 12:50:26 <iand> Ivan's strawpoll had the most votes. i propose we re-vote on that strawpoll and move on 12:50:39 <yvesr> sandro: i don't want to standardise new things that build on that problem 12:50:45 <danbri> q+ to suggest thinking of this as a missing 5th column 12:50:51 <tlebo> INSERT { GRAPH ?s {} } ===> :my_s sd:name ?s; !owl:sameAs ?s . 12:50:54 <AndyS> q? 12:50:54 <yvesr> sandro: if you want another relationship, it's not an IRI 12:50:57 <tlebo> INSERT { GRAPH ?s {} } ===> :my_s sd:name ?s; !owl: sameAs ?s . 12:51:00 <cygri> q+ to propose new wording 12:51:08 <Guus> ack pchampin 12:51:28 <danbri> zakim, please mute america 12:51:28 <Zakim> sorry, danbri, I do not know which phone connection belongs to america 12:51:38 <cygri> zakim, apply electroshock to sandro and david 12:51:44 <Zakim> I don't understand 'apply electroshock to sandro and david', cygri 12:51:46 <danbri> zakim, please mute mit_meeting_room 12:51:46 <Zakim> MIT_Meeting_Room should now be muted 12:52:01 <tlebo> Zakim: Sorry, danbri, I don't recognize "america". 12:52:04 <danbri> call us back when you've stopped chatting 12:52:14 <danbri> zakim, unmute mit_meeting_room 12:52:14 <Zakim> MIT_Meeting_Room should no longer be muted 12:52:28 <gavinc> geee, I think it's break time? 12:52:40 <yvesr> gavinc, +1 :) 12:52:40 <cygri> q? 12:53:15 <yvesr> pchampin: i wanted to answer to cygri's concerns - i think the idea is to providing a framework enabling to specify those practices 12:53:23 <NickH> zakim, BBC has Guus thomas swh ivan 12:53:23 <yvesr> pchampin: not to define a fixed set of practices 12:53:25 <Zakim> +Guus, thomas, swh, ivan; got it 12:53:42 <AndyS> Does "document good practices" work for people? 12:53:44 <yvesr> pchampin: danbri's use case fit perfectly into that 12:53:59 <davidwood> I propose to discuss Pat's Context of Use suggestion, which is a better way (IMO) to address these concerns. 12:54:03 <Guus> q? 12:54:26 <yvesr> pchampin: this proposal is to connect the dots - being able to write the right query for scoping all graphs written by X 12:54:37 <sandro> +1 graph literals are at least understandable and well-defined. 12:54:39 <tlebo> INSERT { GRAPH ?s {} } ===> :my_s sd:name ?s; skos:broader ?s; dcterms:identifier ?s . (SOME SPARQL endpoints may pretend ?s owl:sameAs :my_s ) 12:54:40 <ivan> ack danbri 12:54:40 <Zakim> danbri, you wanted to suggest thinking of this as a missing 5th column 12:54:44 <Souri> +1 to discussing Pat's CoU suggestion 12:54:51 <mischat> this seems similar to the discussion about how a "<> a foaf:Person . " is not the right thing™ - but RDF doesn't forbid it. 12:55:05 <pfps> the 64bit question is just what "properly" means here. 12:55:24 <tomayac> tomayac has joined #rdf-wg 12:55:31 <yvesr> danbri: we introduced a 4th column to specify a graph, we should have had a 5th column to explain how we use the 4th one 12:55:35 <tlebo> +1 to fifth column == context 12:55:38 <swh> sandro, can you explain [possibly offline] what you think awww:identifies means? Because my unders�ta�nding is like davidwood's 12:55:48 <iand> what about the context of the context? 12:55:56 <ivan> ack cygri 12:55:56 <Zakim> cygri, you wanted to propose new wording 12:55:58 <yvesr> danbri: we're not doing anything wrong - we're just missing information - a manifest file, a sitemap, anything... 12:56:09 <danbri> yvesr s/should/could/ 12:56:10 <tlebo> (but not actually *having* the fifth column) 12:56:14 <sandro> +1 danbri we're missing some information about the fourth column relates 12:56:36 <cygri> STRAWPOLL: The WG will non-normatively document one particular convention for using datasets, where in <u,G> the URI is denotes a graph container and G is the state of the container. 12:56:41 <yvesr> sandro: i agree with danbri 12:57:18 <sandro> +0.5 I'm fine with us documenting, but that doesn't solve my problem 12:57:38 <iand> cygri: that is the opposite to Pat's email where he suggested URIs identify graph containers and denote graphs 12:57:40 <yvesr> danbri, well, we have a framework for asserting things about the 4th column :) 12:57:44 <yvesr> danbri, RDF :) 12:57:54 <danbri> s/document one/document at least one/ 12:58:03 <zwu2> +1 bettern than no convention 12:58:07 <yvesr> cygri: i mean it in the sense that you can expect to dereference u and get the grah 12:58:23 <danbri> q+ 12:58:26 <sandro> +1 yes, it's a decent step in the right direction. 12:58:35 <ivan> ack danbri 12:58:36 <Guus> q? 12:58:44 <yvesr> danbri: cygri, what's the granularity of your proposal? 12:58:47 <yvesr> cygri: datasets 12:58:56 <cygri> STRAWPOLL: The WG will non-normatively document one particular convention for using datasets, where in <u,G> the URI denotes+awww:identifies a graph container and G is the state of the container. 12:59:05 <tlebo> Everyone else can go beyond "this particular case", iif you give them URIs to reference others' GraphContainers. 12:59:10 <ericP> +1 12:59:12 <iand> +1 12:59:12 <danbri> +1 12:59:17 <ivan> +1 12:59:17 <Guus> +1 12:59:18 <swh> +0.1 12:59:19 <zwu2> +1 12:59:23 <MacTed> +1 12:59:25 <pchampin> +1 12:59:26 <LeeF> 0 12:59:26 <yvesr> +1, but we should strill provide a framework to document other cases 12:59:28 <sandro> +1 it's a step in the right driections . we still need graph literals or good semantics for TriG. 12:59:28 <davidwood> +1 12:59:30 <mischat> 0 12:59:33 <AlexHall> +0.5 12:59:34 <yvesr> s/strill/still 12:59:35 <pfps> =0 because of "denotes" 12:59:45 <NickH> 0 12:59:57 <AndyS> +1 12:59:58 <pfps> 0 because of smilies 13:00:00 <Souri> 0 (state => snapshot?) 13:00:02 <gavinc> +1 13:00:06 <pfps> 0 because of "denotes" 13:00:34 <cygri> s/The WG/sandro/? 13:00:34 <danbri> it's a good thing to do 13:01:07 <pfps> WG activities are not a zero-sum game, so adding work may positively affect other work. 13:01:15 <danbri> ( and s'ing 'sandro' back to 'the wg' won't fix things ) 13:01:26 <cygri> sandro, good point. sorry 13:02:15 <danbri> er *scribe 13:02:59 <Souri> we probably should still consider discussing Pat's CoU suggestion sometime 13:03:09 <Zakim> -AZ 13:03:21 <gavinc> Yes 13:16:05 <Scott_Bauer> Scott_Bauer has joined #rdf-wg 13:19:29 <AndyS1> AndyS1 has joined #rdf-wg 13:23:47 <swh> swh has joined #rdf-wg 13:30:17 <davidwood> davidwood has joined #rdf-wg 13:30:25 <tlebo> BTW, I'm begging for 13:33:38 <mischat> zakim, unmute BBC 13:33:38 <Zakim> BBC was not muted, mischat 13:33:39 <Guus> let's reconvene 13:34:07 <mischat> can you guys at MIT hear us OK ? 13:36:59 <tlebo> Are we talking about ? 13:37:33 <tlebo> This one ? 13:37:38 <Zakim> +AZ 13:37:54 <tomayac> tomayac has joined #rdf-wg 13:38:14 <ivan> -> Pat's email 13:38:42 <tlebo> scribe: tlebo 13:38:58 <ivan> scribenick: tlebo 13:39:01 <cygri> 13:40:00 <tlebo> cygri:given an RDF graph, there is a "context" in which the statements are made and are true. 13:40:11 <tlebo> e.g. "the age of Alice is 29 years" 13:40:21 <tlebo> obviously not true forever. 13:40:52 <tlebo> ... time is not the only situation. Different people can be the "contexts" 13:41:32 <tlebo> ... :age 30 in a different graph; merging the two graphs causes some conflict. 13:41:44 <tlebo> ... merging consolidates the contexts 13:41:57 <tlebo> ... named graphs keeps contexts separate 13:42:22 <tlebo> ... we need to decide case-by-case when to merge the graphs we want. 13:42:32 <Guus> q? 13:43:00 <mischat> 1. RDF Semantics defines an entailment relationship between sets of triples, a.k.a. RDF graphs 13:43:00 <tlebo> @cygri reading points from his email 13:43:04 <mischat> 2. This entailment relationship is only valid if all triples share the same context 13:43:31 <mischat> 3. Therefore, placing triples with incompatible context into a single graph is not seen as as something useful, and we understand RDF graphs as only containing triples of compatible context 13:43:35 <mischat> 4. It follows that merging two graphs with incompatible contexts is not a valid operation 13:43:37 <mischat> 5. Whether two contexts are compatible or not is outside of the scope of RDF Semantics 13:43:44 <sandro> q+ 13:44:04 <sandro> I do :-) 13:44:21 <tlebo> cygri: not sure on response to Pat (aka wrong) 13:44:45 <davidwood> q+ to ask cygri what he thinks of Pat's proposal 13:44:56 <tlebo> ... current semantics is not designed for contexts and time; not extendable to handle it either 13:45:16 <tlebo> ... keep it context free 13:45:33 <mischat> q+ danbri 13:45:58 <tlebo> (I agree with @cygri; we can keep RDF context-free and "compile" what we want from different named graphs/ contexts into the acontextual) 13:46:12 <tlebo> sandro: people are using RDF in different contexts; we should recognize that. 13:46:51 <tlebo> ... Pat's claim that we need to be explicit about contexts is worthwhile. 13:47:02 <Guus> q? 13:47:12 <Guus> ack sandro 13:47:21 <tlebo> ... Pat says not to put :age into a context - b/c you have to decontextualize it. 13:47:53 <pfps> but everything has a context! 13:47:56 <tlebo> ... inferencing across different graphs - we need to decontextualize it into the "universal" context. 13:48:13 <Guus> ack davidwood 13:48:13 <Zakim> davidwood, you wanted to ask cygri what he thinks of Pat's proposal 13:48:16 <tlebo> ... sandro tried to represent Pat's position. 13:48:27 <Souri> I thought Graph-IRI gives us a hook to a context (which could itself comprise of many triples describing why/when/where/how/etc.) 13:48:27 <pchampin> I agree with Sandro's interpretation of Pat's answer (for what it's worth ;) 13:48:55 <ivan> -> pat's response to richard 13:48:56 <mischat> 13:49:14 <mischat> ^^ pat's response 13:49:34 <tlebo> davidwood: we aren't agreeing on "context"; suggests @cygri reread Pat's to see the different interpretations of "context" 13:49:36 <pfps> everything depends on what you mean - could mean "age on 11/11/11" and could mean "born how long ago" 13:49:40 <sandro> sandro: I think there's a huge opportunity for a joint solution here, between Richard and Pat -- where have multiple context, but a special "Web" context where thinks can be merged. 13:50:10 <sandro> q? 13:50:23 <Souri> q+ 13:50:24 <Guus> ack danbri 13:50:25 <tlebo> (beyond "web context", it's also any context we choose to create by merging some graphs and decontexutalizing them) 13:51:13 <tlebo> danbri: example - tried to decontextualize (date of birth, not age) 13:51:38 <tlebo> danbri: foaf, color of cars 13:52:03 <sandro> danbri: we added foaf:age because myspace needed it. we can't make them decontextualize 13:52:05 <tlebo> danbri: foaf people wanted age, e.g. myspace spits it out every day 13:52:32 <tlebo> danbri: we shouldn't be putting it into standards b/c research project 13:52:41 <sandro> danbri: there will be volatile properties; this should be a W3C CG dogin the research. 13:52:47 <cygri> q+ to say that decontextualizing everything looks like a pipe dream 13:52:50 <tlebo> ... volitatile and non-volitile properties 13:52:57 <Guus> ack Souri 13:53:01 <davidwood> Avoiding context makes sense, iff you can be sure you are actually doing it. It is trivial with events, but what about universally true statements made in RDF that are then taken *into* a particular context? 13:53:06 <pchampin> s/volitatile/volatile/ 13:53:13 <pchampin> s/volitile/volatile/ 13:54:13 <tlebo> souri: @cygri's proposition, can associate dimensions of the Graph IRI - why was it created, etc? These are dimensions on the context. 13:54:40 <Guus> q? 13:54:59 <danbri> danbri has joined #rdf-wg 13:55:23 <gavinc> Channeling PatH via email: "No, that is not why named graphs were invented. They were invented so that one could say things about graphs in RDF. Things like who is asserting them, where they came from, etc..,: but not to supply a 'context' for the truth of the triples in them. That would be data, not metadata." 13:55:36 <tlebo> cygri: practice of decontextualizing and modeling decontextulized or not. But can merge without worrying? No, we'll still have to worry about it. 13:55:46 <tlebo> ... most rdf published is context dependent. 13:55:51 <tlebo> ... may contradict 13:55:55 <AndyS> ack cygri 13:55:56 <Zakim> cygri, you wanted to say that decontextualizing everything looks like a pipe dream 13:55:57 <sandro> cygri: it would be great if everyone was modeling in a way that would be true forever and could just be merged, but that's not the world we're living in , and I don't see it happening any time sooon. Most info published is context dependent. Not true forever, has errors, and we have to deal with that. 13:55:57 <tlebo> ... we need to deal with it. 13:56:19 <sandro> cygri: "just decontextualize" doesnt seem very practical. 13:56:26 <Guus> q? 13:56:43 <pchampin> q+ 13:57:00 <danbri> (specifically, if you describe everything as events, you are perfectly decontextual but borderline un-unformative, if you want the state of the world at some specific time...) 13:57:03 <AndyS> ack pchampin 13:57:04 <tlebo> (can't we apply decontextualized semantics to contextualized data that we "choose" to decontextualize it?) 13:57:05 <Guus> ack pchampin 13:57:35 <AndyS> q+ 13:57:46 <tlebo> []: disagreement is centered on SPARQL (?) 13:57:50 <gavinc> the named graph paper is a rather clear input to named graphs in SPARQL isn't it? 13:57:55 <ivan> ack AndyS 13:58:04 <pchampin> pchampin: I think the disagreement btw Richard and Pad concerning named graphs is that Pat is refering to the "Named Graph" paper, while Richard is refering to named graphs in SPARQL 13:58:04 <tlebo> s/[]/pchampin/ 13:58:15 <sandro> agreed -- Pat's proposal was about contexts for just the 4th column 13:58:34 <Souri> +1 to AndyS about Pat's attempt being less ambitious than what Richard's trying to propose 13:58:46 <tlebo> (the SPARQL endpoint named graph is a specific case of contextualized RDF) 13:58:49 <gavinc> +1 AndyS 13:58:54 <sandro> AndyS: Pat's "Context of Use" email was just about the fourth column. 13:59:44 <tlebo> general consensus that @cygri's context is different from Pat's 13:59:45 <AndyS> ack me 13:59:55 <tlebo> Pat wants "web context" 14:00:05 <AndyS> q+ 14:00:21 <tlebo> sandro: we have multiple contexts and need to deal with it. 14:00:25 <tlebo> cygri: yes 14:00:39 <pfps> this is starting to look like the discussions with tbl on common meaning in the Semantic Web 14:00:45 <tlebo> ... not hard to store/query/vis contextualized data - problem is when we approach semantics. 14:00:46 <Souri> event-based formulation (as DanBri said above?) is another way of specifying the context ino 14:01:02 <Souri> s/context ino/context info/ 14:01:20 <tlebo> sandro: cygri gave up on reasoning with RDF graphs b/c they are in different contexts. 14:01:44 <tlebo> cygri: collecting from wires, will need to post-process to check appropriate, clean, remodeling, etc. 14:02:02 <AlexHall> s/wires/the wild/ 14:02:02 <pchampin> s/from wires/from the wild/ 14:02:09 <tlebo> ... when reasoning over web data, those that do it say "of course we clean it up first" 14:02:21 <sandro> q? 14:02:24 <pchampin> q+ 14:02:58 <tlebo> sandro: we could construct ecosystems and feedback loops that increases quality. 14:03:09 <tlebo> ... more rigid consumers (e.g. schema.org) 14:03:11 <mischat> i guess the question next is how does this relate to trig and/or graph serialisations, and whether we wish to be able to reason on top of data given to you in a trig file 14:03:23 <pchampin> q- 14:03:27 <tlebo> ... will give pressure to increase quality - we need to make these systems possible. 14:04:03 <tlebo> []: not "contextualizing web" but "contextualizing web at a point in time" 14:04:11 <AndyS> q- 14:04:18 <tlebo> s/[]/AndyS/ 14:04:30 <sandro> (I'm thinking about Cassandra's "eventual consistency" as a parallel to the way the Web Context might be consistent in the face of errors, lag, etc) 14:05:47 <tlebo> davidwood: re Pat's emails, happy with g-box ... (others disagree) david agrees. (LINK to thread?) 14:06:15 <tlebo> gavinc: straw poll on agreeing to the email 14:06:40 <gavinc> IRI----HTTP/"identifies" ---- g-box 14:06:42 <gavinc> IRI----denotes/names-----g-snap 14:07:09 <tlebo> sandro: what does this mean? 14:07:18 <tlebo> davidwood: Pat's trying to formally define context. 14:07:26 <tlebo> sandro: URIs can denote g-boxes. 14:07:39 <tlebo> ... and you can't stop him. 14:08:09 <tlebo> sandro: you can't identify g-snaps. 14:08:20 <davidwood> Start of thread: 14:08:38 <tlebo> (tlebo disagrees, you can identify g-snaps - in the words of @sandro - you can't stop me.) 14:08:53 <sandro> s/you can't identify g-snaps/identifying g-snaps might be a problem/ 14:09:08 <sandro> 14:09:08 <tlebo> x: need clear definition of "identifies" 14:09:17 <yvesr> s/x/swh 14:09:22 <AndyS> <tag:1234> owl:sameAs { <s> <p> <o> } 14:10:04 <tlebo> sandro: identifies" means it like REST means it. The relationship between a URL and the thing the URL is conceptually associated with in an identifying matter. 14:10:20 <AndyS> That is naming so IRI----HTTP/"names" ---- g-box which is true of HTTP URLs. 14:10:25 <tlebo> sandro: heart of REST and WWW. you put a URL in, you get a representation back. 14:10:37 <AndyS> just don't use a #frag 14:10:48 <tlebo> ... REST - imagine thing over there. URL represents it and you get a representation of it when you request it. 14:11:11 <cygri> q+ 14:12:05 <tlebo> sandro: tag URIs say "there is no representation" - you still get identifying, but david may disagree. 14:12:53 <davidwood> I don't understand "there is no representation", so don't know whether I agree 14:12:56 <cygri> q- 14:13:02 <tlebo> guus: there is no requirement that a representation exists. 14:13:09 <davidwood> ah 14:13:23 <tlebo> swh: now has sense of "identifies" w.r.t. REST's URL and representation. 14:13:47 <sandro> q? 14:13:49 <swh> … actually re this conversation, I'm not sure it's a universal def'n 14:13:49 <tlebo> guus: where does that get us with identifying g-boxes and g-snaps 14:14:02 <davidwood> In that case, I agree with Sandro if he means that TAG URIs *identify* resources even if they cannot be resolved in a manner that returns a representation. 14:14:49 <tlebo> cygri: decontextualization - relationships are to hold "forever" - what about the g-box "can changing." 14:15:06 <tlebo> ... URI for a g-box (that can change b/c the representation cna change tomorrow) 14:15:24 <AlexHall> taking a g-snap decontextualizes the g-box 14:15:31 <tlebo> ... you get different g-snaps when requesting the g-box 14:15:52 <tlebo> sandro and @cygri have concerns with proposal. 14:16:01 <AndyS> :x a :Car does not stop the car changing color 14:16:27 <tlebo> sandro: def b-boxes are representations of g-snaps (?) 14:16:37 <tlebo> (that sounds backwards to me) 14:17:02 <Guus> q? 14:17:15 <tlebo> gavinc: Pat's point: 2 parallel words, a semantic rule when one works, the other has to work. 14:17:18 <sandro> sandro: g-boxes are resources, their representations are g-texts, conveying the contained g-snap 14:18:22 <tlebo> sandro: let's cut this off, Pat is not here. 14:18:47 <tlebo> sandro: where are we with not being able to inference across multiple contexts? 14:19:05 <tlebo> davidwood: the point is that you don't know what contexts there are (in RDF) 14:19:42 <tlebo> ... encoding a context in the graph, and another context in another graph. Third party merges them (can do in RDF) - find logical inconsistency, but above level of merge. 14:19:56 <tlebo> ... assuming apriori out of band contexts to know it SHOULD NOT be combined. 14:20:11 <tlebo> sandro: not knowing context - can assume are different, or same, 14:20:25 <tlebo> davidwood: or don't care about the contexts. 14:20:34 <Souri> q+ 14:20:40 <tlebo> sandro: regardless, they are either the same or different (and you're implicitly deciding)\ 14:20:45 <cygri> q+ to talk about "compatibe/incompatible" contexts 14:20:59 <tlebo> davidwood: merging two graphs does not entail "I have made a decision about contexts" 14:20:59 <Guus> q+ 14:21:08 <tlebo> +1 to sandro 14:21:19 <tlebo> (you've implicitly made a choice about context) 14:21:32 <pchampin> q+ 14:21:55 <tlebo> souri: removing graph names and merging - :age 31 and 32. Can go to event based organization - everything in this event is true (merging can't, because different events). 14:22:03 <AlexHall> propose to give different terms to richard's "context" vs. pat's "context" -- i understand this discussion to be relevant to richard's context 14:22:31 <tlebo> davidwood: have a graph not event-encoded - can have metadata true in a date. (alice graph 1 and 2) 14:22:57 <sandro> q? 14:23:02 <sandro> ack Souri 14:23:18 <tlebo> souri: :g1 graph happened, :g2 graph happened, merging into :g3 eliminates contexts of first two graphs. 14:23:21 <cygri> souri++ 14:23:22 <tlebo> q? 14:23:31 <gavinc> PatH channeling ... " So for example if you write "it is raining' then thats not going to stay true, and if you write "it is raining now' that might be true but we have no way to know since we don't know when 'now' was, but if you write 'it is raining on 08/09/2011' then this stays true while time passes. Which is obviously better for communciation across times. So putting the "context' (or as much of it as necessary to fix the truth of what you are saying) 14:23:33 <gavinc> into the assertion itself is a basic good rule for data which is supposed to last for a while and still be true." 14:23:34 <cygri> ack me 14:23:34 <Zakim> cygri, you wanted to talk about "compatibe/incompatible" contexts 14:23:58 <sandro> +1 gavinc 14:24:13 <tlebo> cygri: merging two graphs - same contexts? need notion of contexts are compatible or not (and depends on use case). 14:24:15 <Guus> [ivan is leaving] 14:24:20 <pchampin> q+ to suggest that contexts are not a property of the graph, but a property of their use 14:24:22 <tlebo> ... depends on what you want to do with it, the modeling. 14:24:25 <sandro> bye Ivan! 14:25:45 <gavinc> but as danbri said, people may just say "it's raining" 14:25:51 <tlebo> (why can't we just leave RDF a-contextual and let us mix contexts when we want to, think we can?) 14:25:54 <davidwood> q+ to respond to Richard 14:26:06 <gavinc> and the process of changing that to it's raining on ISODATETIME is a nice research project 14:26:16 <AlexHall> +1 tlebo 14:26:21 <pchampin> @gavinc: and *where* is it raining, exactly? :-> 14:26:22 <tlebo> guus: YYY is out of context 14:26:33 <davidwood> q- 14:26:35 <gavinc> pchampin, yes that too 14:26:41 <yvesr> ack Guus 14:26:50 <tlebo> guus: naming is main mechanism we have, and dereferencing. that's it. can't go any further. 14:26:58 <tlebo> ... perhaps over-pragmatic, but. 14:27:20 <tlebo> cygri: use cases require holding data in incompatible contexts in same dataset. semantics has to work regardless. 14:27:25 <AlexHall> use prov info to record the context in which a graph is asserted, use the prov info to decide which data to include in the dataset that you want to apply inference to. 14:27:42 <gavinc> We are not meeting those use cases, yeah I'm okay with that ;) 14:27:48 <tlebo> (but since semantics only applies to a-contextual RDF, it's fine) 14:28:08 <tlebo> cygri: keep scope of semantics to individual graphs, since they should be within some context 14:28:12 <tlebo> (+1 cygri) 14:28:28 <Guus> q? 14:28:29 <pchampin> ack me 14:28:30 <Zakim> pchampin, you wanted to suggest that contexts are not a property of the graph, but a property of their use 14:29:00 <cygri> guus: so you don't want to touch semantics at all? 14:29:08 <tlebo> TTT: context of a graph, talking about it is a mistake. the context is in the use of the graph (consuming it) 14:29:20 <tlebo> s/TTT/pchampin/ 14:29:26 <cygri> cygri: well, that would be one way of ensuring no bad entailments from putting incompatible contexts into the same dataset 14:29:49 <sandro> q+ to proposed TriGR, with a "fifth" column. 14:30:06 <Souri> event-centric formulation of triples is good, but verbose, which leads people to not use it. Use of named graphs and associating context info with graph is easier (less verbose), but requires applications or people doing the merge to first check the contexts of the graphs being merged are compatible or not. We can provide some non-normative examples to illustrate this. 14:30:22 <Guus> Guus: "mnmed graphs" is the mechanism to indicate triples are in a particular context, not other ways to characterize/type/formalize context 14:30:26 <tlebo> pchampin: the context is not a property of the graph, but it's use. so the semantics is not cross-context. Semantics tells nothing about XYZ. 14:30:33 <cygri> souri +100 14:30:41 <Guus> Guus: you're on you own to interpret, for example, a merge 14:31:07 <tlebo> (so, contexts matter, but the semantics does not address it?) 14:31:31 <pchampin> s/XYZ/contexts, it just means that it that contexts do not exist outisde the semantics/ 14:31:44 <tlebo> guus: the way people use RDF, and in OWL. We should not (address contexts?). 14:31:46 <pchampin> @tlebo: contexts matter on a pragmatic level 14:31:57 <mischat> similar to the "<> a foaf:Person ." issue which one finds in the wild, we can't say that it is w�rong RDF. 14:32:10 <Souri> q+ 14:32:57 <tlebo> sandro: retreat to syntax? what would help? Simplest is a variation of TRiG - a 5th column to name the context. 14:33:13 <tlebo> ... TRiG-R - b/c relationship is added. 14:33:19 <sandro> <label> <relation> { ... graph .... } 14:33:30 <tlebo> (but <> already IS the context) 14:34:10 <yvesr> looks like n3! 14:34:48 <cygri> q+ to ask about SPARQL 14:34:56 <cygri> q- 14:35:30 <tlebo> sandro: manifests? to not break SPARQL. 14:35:47 <tlebo> guus: OWL used the ontology itself as the manifest. 14:35:49 <sandro> sandro: Maybe the service description could have a manifest of how each label is related. 14:36:12 <sandro> q- 14:36:49 <tlebo> souri: a primer? non-normative. an example of how to specify the context. 14:37:17 <tlebo> (<> already provides context... along with how you got <>) 14:37:19 <Souri> q- 14:37:29 <tlebo> should we discuss manifests? 14:38:03 <danbri> danbri: it just needs to be possible, we don't need to do *all* the work (re manifest formats / aka 'table of contents' for a datastore) 14:38:07 <tlebo> dawg discussed manifests 14:38:26 <tlebo> topic: Manifests 14:38:36 <sandro> q+ 14:38:47 <yvesr> ack sandro 14:38:50 <danbri> q+ to ask andys and dawg folk how much manifest-style work has happened in sparql community 14:39:05 <AndyS> It's one style amongst several/many/open ended ... it's just RDF. 14:39:27 <tlebo> sandro: labels are "..." or <...>? 14:39:43 <tlebo> how is manifest different from sparql service description? 14:39:45 <danbri> (quotes being uri-as-string stuff?) 14:39:46 <danbri> q? 14:41:10 <danbri> i forgot my homepage b/g graphic has a picture of this from another meeting: (colours = graph types, volatile, version, composite etc) 14:41:30 <tlebo> cygri: VoID - RDF datasets vocab. 14:41:35 <Guus> Guus has joined #rdf-wg 14:41:38 <tlebo> ... not quite a manifest, but related. 14:41:54 <tlebo> ... when pub RDF, also publich VoID file that describes the dataset. 14:42:13 <tlebo> ... "here is a dataset, here is a SPARQL endpoint where you can query, here is a dump to put into your own store" 14:42:19 <sandro> q+ to sketch Service Description names the Dataset Manifest Graph M, in the service's dataset; M contains triples like { <G1> eg:relatedBy owl:SameAs. <G2> eg:relatedBy log:Semantics }. 14:42:27 <danbri> ack danbri 14:42:27 <Zakim> danbri, you wanted to ask andys and dawg folk how much manifest-style work has happened in sparql community 14:42:30 <tlebo> ... wanted outside of a SPARQL store, since can access different ways. 14:42:38 <Guus> q? 14:42:45 <Guus> ack sandro 14:42:45 <Zakim> sandro, you wanted to sketch Service Description names the Dataset Manifest Graph M, in the service's dataset; M contains triples like { <G1> eg:relatedBy owl:SameAs. <G2> 14:42:48 <Zakim> ... eg:relatedBy log:Semantics }. 14:43:14 <tlebo> q? 14:43:28 <sandro> vs { [ inDataset <d>; label "G1"; relation owl:SameAs ] } 14:43:39 <mischat> have we won if we are in a position to describe things that people may want to describe, but not limiting people to how they have to describe things? 14:43:43 <tlebo> sandro: sketching a service description - two proposals 14:44:11 <swh> q+ 14:44:26 <tlebo> +1 not following 14:44:37 <tlebo> guus: please no sameAs 14:45:00 <AndyS> sandro - please explain log:semantics as people are unclear about it (or maybe they know and do not like it) 14:45:02 <tlebo> (are we tryign to model contexts still?) 14:45:32 <tlebo> context: where it is and where it came from. 14:45:45 <mischat> +1 14:45:46 <mischat> to tlebo 14:45:52 <sandro> { <G1> eg:relatedBy eg:labeling-a-snap. <G2> eg:relatedBy eg:label-is-url-source } 14:46:15 <gavinc> +q 14:46:15 <sandro> { <G1> eg:relatedBy eg:labeling-a-snap. <G2> eg:relatedBy eg:label-is-url-i-fetched-it-from } 14:46:24 <tlebo> (what is going on?) 14:46:35 <Guus> q? 14:46:40 <Guus> ack swh 14:47:02 <yvesr> { ... } a eg:Snap 14:47:17 <cygri> swh++ 14:47:33 <tlebo> swh: 10s millions of named graphs. 14:47:51 <danbri> I anticipate manifest graphs could use to describe where date was gotten 14:48:12 <danbri> (if we have 10s of millions of named graphs, all the more reason to be able to navigate that jungle...) 14:48:45 <tlebo> gavinc: name of graph is distinct from subjects in the graph, o/w you run into the "OWL problem" b/c the graph name is the subject of the graph - it gets odd. 14:48:49 <sandro> for swh: { <endpoint> eg:uses-dataset-relation eg:labeling-a-snap } 14:49:17 <tlebo> davidwood: "owl problem" is bad name for it. 14:49:18 <swh> sandro, or { <dataset> eg:uses … } 14:49:45 <Guus> q? 14:49:49 <gavinc> ack me 14:49:56 <tlebo> (none of this matters as if you give URIs for the GraphContainers; let people describe what they want in RDF) 14:50:02 <AlexHall> the "graph/resource conflation" problem? 14:50:05 <tlebo> s/as if/if/ 14:50:32 <tlebo> topic: review 14:50:36 <sandro> breajk for an hour in ten minutes 14:50:53 <sandro> guus: after break, go through issues list 14:51:06 <tlebo> guus: let's list issues 14:51:40 <tlebo> guus: what about manifest to discuss? 14:51:50 <Souri> s/breajk/break/ 14:52:14 <tlebo> sandro: TRiGers, do you like something at top state relation, or add fifth column. 14:52:21 <tlebo> (this is already handled by <>) 14:52:22 <swh> -∞ to a 5th c��olumn 14:52:36 <cygri> q+ to ask what we would put in when dumping a sparql store 14:53:10 <Scott_Bauer> Scott_Bauer has joined #rdf-wg 14:53:23 <tlebo> @cygri, either <> or <URI_to_endpoint> 14:53:38 <sandro> PROPOSED: We add to TriG an optional 5 column relationship-indiciator, which defaults to "loose association" as now. 14:53:42 <AndyS> <> :namingStyle rdf:GBoxIdentifies . 14:53:46 <cygri> tlebo, my question� was about the relationship 14:53:52 <iand> wikipedia says "A fifth column is a group of people who clandestinely undermine a larger group such as a nation from within." 14:53:55 <tlebo> gavinc: 5th column does NOT mean fifth column. 14:54:28 <tlebo> context is already handled by where it is and where it came from - this is already represented. 14:54:29 <mischat> mischat has joined #rdf-wg 14:54:40 <tlebo> s/represented/representable/ 14:54:57 <tlebo> sandro: could read the manifest as triples if you'd like. 14:55:59 <tlebo> topic: still manifests 14:56:16 <gavinc> TriG <G1> <eg:labeling-a-snap> {<s> <p> <o> }? 14:56:39 <tlebo> <> prov:wasDerivedFrom :process_of_dumping_SPARQL_endpoint . 14:56:44 <AndyS1> AndyS1 has joined #rdf-wg 14:56:47 <tlebo> <> prov:wasDerivedFrom : process_of_dumping_SPARQL_endpoint . 14:57:17 <tlebo> cygri: many will get confused and will just put garbage into it to "fill the field" 14:57:22 <tlebo> +100 @cygri 14:57:29 <tlebo> ... people dont' care. 14:57:52 <sandro> I think you're right cygri, and I dont know what to do about it. 14:57:55 <tlebo> guus: fine, but what are the benefits? 14:57:57 <yvesr> q+ 14:58:12 <tlebo> UUU: it just needs a vocab. 14:58:20 <cygri> s/UUU/AndyS/ 14:59:06 <AlexHall> it needs a vocab and a reasonable abstract syntax/semantics for RDF datasets that doesn't preclude reasonable things people want to do with that vocab 14:59:25 <pchampin> q+ 14:59:34 <swh> swh has joined #rdf-wg 14:59:37 <cygri> ack me 14:59:37 <Zakim> cygri, you wanted to ask what we would put in when dumping a sparql store 15:00:01 <tlebo> OOO: worried about the "one style" without being sure it's the right one. we already have a system to describe it (RDF) 15:00:12 <Guus> ack yvesr 15:00:15 <swh> +1 to AndyS 15:00:15 <sandro> +1 AndyS we can just tag the style in the TriG metadata 15:01:09 <tlebo> BBC: what do people gain? what is motivation to use it? use cases. 15:01:42 <gavinc> s/OOO/AndyS/ 15:02:23 <AndyS> AndyS has joined #rdf-wg 15:02:33 <mischat> surely when this becomes a real world problem, a WG could look at how people are tackling it in the wild 15:02:33 <tlebo> maybeAndyS: incentive is need for knowledge, but no vocab to get it. Do not completely agree with cygri that can't be useful. 15:02:36 <yvesr> s/BBC/yvesr 15:02:49 <tlebo> (do we need to review what <> means, and that we can describe it with RDF?) 15:02:56 <yvesr> s/maybeAndyS/pchampin 15:02:57 <cygri> s/maybeAndyS/pchampin/ 15:03:28 <tlebo> guus: will revisit issues list 15:03:36 <AZ> bye 15:03:49 <zwu2> I am leaving 15:04:10 <Souri> I need to leave ... meeting at office 15:04:22 <NickH> Zakim, mute MIT_Meeting_Room 15:04:34 <Zakim> -AZ 15:04:37 <cygri> zakim, mute me 15:04:50 <Zakim> MIT_Meeting_Room should now be muted 15:05:13 <Zakim> sorry, cygri, I do not know which phone connection belongs to you 15:05:39 <MacTed> Zakim, who's here? 15:05:59 <Zakim> On the phone I see BBC, Peter_Patel-Schneider, MIT_Meeting_Room (muted) 15:06:03 <Zakim> MIT_Meeting_Room has MIT_Meeting_Room, Guus, thomas, danbri, steve, ivan, richard, andy, ian, pchamplin, yves, nicholas, micha, TedT 15:06:08 <Zakim> BBC has Guus, thomas, swh, ivan 15:06:12 <Zakim> On IRC I see AndyS, swh, mischat, Guus, danbri, tomayac, MacTed, zwu2, iand, AlexHall, gavinc, pfps, Zakim, RRSAgent, LeeF, pchampin, mox601, cygri, tlebo, ww, ericP, yvesr, manu, 15:06:15 <Zakim> ... NickH, trackbot, manu1, sandro 15:06:32 <MacTed> Zakim, mute BBC 15:06:32 <Zakim> BBC should now be muted 15:16:49 <AlexHall_> AlexHall_ has joined #rdf-wg 15:21:25 <Scott_Bauer> Scott_Bauer has joined #rdf-wg 15:56:13 <AndyS> AndyS has joined #rdf-wg 15:56:37 <Guus> reconvene in 5 15:56:48 <Guus> 5/4 15:59:52 <Guus> Boston: ready to reconvene? 16:02:06 <AndyS1> AndyS1 has joined #rdf-wg 16:03:11 <cygri> danbri, thanks for … well put! 16:03:29 <mischat> mischat has joined #rdf-wg 16:03:33 <AndyS> zakim, who is on the phone? 16:03:33 <Zakim> On the phone I see BBC (muted), Peter_Patel-Schneider, MIT_Meeting_Room (muted) 16:03:36 <Zakim> MIT_Meeting_Room has MIT_Meeting_Room, Guus, thomas, danbri, steve, ivan, richard, andy, ian, pchamplin, yves, nicholas, micha, TedT 16:03:39 <Zakim> BBC has Guus, thomas, swh, ivan 16:03:50 <NickH> Zakim, unmute BBC 16:03:50 <Zakim> BBC should no longer be muted 16:03:55 <NickH> Zakim, unmute MIT_Meeting_Room 16:03:55 <Zakim> MIT_Meeting_Room should no longer be muted 16:06:19 <cygri> ACTION: cygri to update rdf-concepts re ISSUE-71 16:06:20 <trackbot> Created ACTION-97 - Update rdf-concepts re ISSUE-71 [on Richard Cyganiak - due 2011-10-20]. 16:08:45 <iand> example of my use of graph literals: 16:08:53 <iand> no datatype though 16:09:10 <iand> schemapedia.com/examples/cf314c8dab338aa1edaa93df2b54ad7b.ttl is turtle version 16:09:16 <iand> 16:11:38 <iand> my use case is to embed examples of usage (i.e. to mention a set of triples without asserting them) 16:11:39 <gavinc> gavinc has joined #rdf-wg 16:13:08 <davidwood> davidwood has joined #rdf-wg 16:13:32 <AlexHall> AlexHall has joined #rdf-wg 16:13:38 <gavinc> Topic: Raised Issues 16:13:40 <gavinc> 16:13:50 <NickH> scribe NickH 16:13:51 <Scott_Bauer> Scott_Bauer has joined #rdf-wg 16:14:02 <NickH> scribe: NickH 16:14:02 <davidwood> scribe: NickH 16:14:09 <AndyS1> AndyS1 has joined #rdf-wg 16:14:12 <NickH> davidwood: there are 8 issues marked as raised 16:14:23 <NickH> davidwood: think we want to open all of these 16:14:33 <NickH> davidwood: ISSUE-63 is the only one that is a black hole 16:14:42 <LeeF> LeeF has joined #rdf-wg 16:14:44 <mischat> 16:14:52 <LeeF> ISSUE-50? 16:14:52 <trackbot> ISSUE-50 -- Revisit "Request to allow b-nodes as property labels" -- raised 16:14:52 <trackbot> 16:14:58 <LeeF> ISSUE-63? 16:14:58 <trackbot> ISSUE-63 -- Introduce an HTML5 datatype -- raised 16:14:58 <trackbot> 16:15:47 <NickH> davidwood: issue-50 is left over. We should mark it as declined because it isn't part of our charter 16:15:50 <sandro> 16:16:18 <davidwood> Propose to close ISSUE-50 stating that this WG will not revisit this issue because it is not chartered to do so. 16:16:24 <iand> +1 16:16:28 <gavinc> +1 16:16:30 <AndyS1> +1 16:16:31 <NickH> +1 16:16:32 <pchampin> +1 16:16:33 <cygri> +2 16:16:46 <AlexHall> +1 16:16:53 <yvesr> +1 16:17:08 <tlebo> tlebo has joined #rdf-wg 16:17:10 <sandro> +1 bnodes as predicate identifiers? kinda late for that in RDF. 16:17:11 <NickH> RESOLVED 16:17:38 <NickH> RESOLVED close ISSUE-50 stating that this WG will not revisit this issue because it is not chartered to do so. 16:17:48 <sandro> RESOLVED: close ISSUE-50 stating that this WG will not revisit this issue because it is not chartered to do so. 16:17:53 <sandro> (need the colon) 16:18:07 <sandro> +1 open the RAISED issues 16:18:10 <NickH> davidwood: 7 remaining issues marked as 'raised' 16:18:15 <danbri> danbri has joined #rdf-wg 16:18:24 <MacTed> MacTed has joined #rdf-wg 16:18:39 <NickH> davidwood: any disscussion about these issues? 16:19:25 <gavinc> +1 16:20:03 <gavinc> 16:20:07 <NickH> cygri: ISSUE-37 I am struggling to remember it 16:20:14 <NickH> cygri: left over from the previous group 16:20:15 <MacTed> RRSAgent, pointer? 16:20:15 <RRSAgent> See 16:20:34 <NickH> cygri: it is reasonable to open it and think about if we should do anything about 16:20:47 <NickH> Guus: unlikely to result in spec change 16:20:58 <NickH> Guus: but might lead to some extra documentation 16:21:04 <cygri> +1 to opening all other raised issues 16:21:38 <NickH> davidwood: chairs can open the remaining issues but didn't want to open things that didn't need opening 16:21:54 <NickH> davidwood: lets move on to open issues 16:21:57 <cygri> q+ to ask if we can get products in the tracker for all specs 16:22:07 <pchampin> q- 16:22:08 <NickH> davidwood: lets focus on the open graph issues 16:22:11 <davidwood> Topic: Open Issues 16:22:13 <davidwood> 16:23:46 <NickH> cygri: the products that we have at the moment are cleanup tasks, then each of the task forces 16:23:55 <sandro> +1 products = specs, if possible 16:23:58 <NickH> cygri: might be good the have products for each of the specs 16:24:23 <NickH> Guus: isn't a product for the primer 16:25:02 <NickH> davidwood: can easily create new projects for primer 16:25:09 <NickH> davidwood: created one for primer 16:25:12 <NickH> davidwood: created one for concepts 16:25:24 <iand> s/projects/products/ 16:26:11 <cygri> ISSUE-76? 16:26:11 <trackbot> ISSUE-76 -- RDF Semantics and RDF Concepts disagree on definition of datatypes -- open 16:26:11 <trackbot> 16:26:12 <NickH> davidwood: ISSUE-76 - which does it belong 16:26:38 <NickH> davidwood: putting it into concecpts 16:26:45 <NickH> cygri: it should go under semantics 16:27:34 <LeeF> ISSUE-75? 16:27:34 <trackbot> ISSUE-75 -- Valid plain literals containing #x0 are ill-typed in RDF 1.1 -- open 16:27:34 <trackbot> 16:27:40 <NickH> davidwood: where would you put ISSUE-75? 16:27:49 <NickH> cygri: concepts 16:28:15 <NickH> davidwood: last uncategorised on is ISSUE-39 16:29:19 <NickH> ACTION: sandro to rdf: and rdfs: namespace should resolve to something that meets best practices 16:29:19 <trackbot> Created ACTION-98 - Rdf: and rdfs: namespace should resolve to something that meets best practices [on Sandro Hawke - due 2011-10-20]. 16:29:54 <davidwood> CLOSED: ISSUE-39 16:29:56 <NickH> CLOSE: ISSUE-39 16:30:22 <NickH> davidwood: everything is categorised correctly more or less 16:30:50 <NickH> davidwood: starting with cleanup tasks 16:31:27 <NickH> ISSUE-6? 16:31:27 <trackbot> ISSUE-6 -- Handling RDF Errata -- open 16:31:27 <trackbot> 16:31:43 <gavinc> Better view: 16:32:20 <NickH> davidwood: asks cygri is this is done for Concepts 16:32:32 <NickH> cygri: either been addressed or there are open issues for it 16:33:53 <NickH> ISSUE-7? 16:33:53 <trackbot> ISSUE-7 -- Leftover issues from the RDF Core WG -- open 16:33:53 <trackbot> 16:34:37 <NickH> davidwood: we have closed a number of these - can either close or open a other issue 16:34:45 <NickH> davidwood: propose closing ISSUE-7 16:35:27 <NickH> davidwood: spent time on this in several telecons in June 16:35:37 <NickH> davidwood: confident that we can close this 16:36:12 <davidwood> Closed ISSUE-7 because all leftover issues have either resulted in new open issues or closed issues due to compliance with our charter. 16:36:53 <NickH> ISSUE-9? 16:36:53 <trackbot> ISSUE-9 -- Inference rules are incomplete in the RDF Semantics -- open 16:36:53 <trackbot> 16:36:56 <AlexHall> fyi, issues 42-62 cover the postponed issues from last wg 16:37:46 <davidwood> 16:37:48 <NickH> davidwood: what does pfps want to do with ISSUE-9? 16:38:18 <NickH> pfps: we should deal with it 16:38:32 <NickH> Guus: added a product 'RDF Semantics' and moved it there 16:39:06 <NickH> ISSUE-10? 16:39:06 <trackbot> ISSUE-10 -- Look if there are RDF(S) notions that are to be deprecated -- open 16:39:06 <trackbot> 16:39:18 <danbri> cygri, re Sindice etc ... how much rss1 is still usefully out there? 16:39:56 <NickH> davidwood: going to leave gavinc to do some work on ISSUE-10 16:40:05 <NickH> ISSUE-11? 16:40:06 <trackbot> ISSUE-11 -- Reconciliation of various, semantics-oriented documents with the core RDF ones -- open 16:40:06 <trackbot> 16:41:04 <NickH> davidwood: 16:41:31 <NickH> davidwood: we leave ISSUE-11 open until our documents are closer to being ready 16:41:34 <gavinc> ISSUE-24? 16:41:34 <trackbot> ISSUE-24 -- Should we deprecate RDF containers (Alt, Bag, Seq)? -- open 16:41:34 <trackbot> 16:41:38 <gavinc> ISSUE-25? 16:41:38 <trackbot> ISSUE-25 -- Should we deprecate (RDF 2004) reification of statements? -- open 16:41:38 <trackbot> 16:41:46 <gavinc> Can close ISSUE-10 16:42:09 <NickH> davidwood: would you like to look at ISSUE-11 in relation to SPARQL 1.1 16:42:21 <NickH> AndyS: would rather not 16:42:50 <NickH> ACTION sandro to look at ISSUE-11 in relation to SPARQL 1.1 16:42:51 <trackbot> Created ACTION-99 - Look at ISSUE-11 in relation to SPARQL 1.1 [on Sandro Hawke - due 2011-10-20]. 16:42:57 <AlexHall> deprecated/archaic features: (needs clean-up) 16:42:58 <sandro> action: sandro to ask editors of SPARQL Entailment Regimes what they'd suggest RDF specs says about their work. 16:42:59 <trackbot> Created ACTION-100 - Ask editors of SPARQL Entailment Regimes what they'd suggest RDF specs says about their work. [on Sandro Hawke - due 2011-10-20]. 16:43:40 <gavinc> Really? RDF XML Literals got lucky 13? 16:44:44 <NickH> Guus: leave ISSUE-13 open for now 16:45:58 <NickH> davidwood: if you think we are ready to close ISSUEs-24 and ISSUE-25, then go for it now 16:46:59 <sandro> STRAWPOLL: we'll suggest people stop using RDF containers (Alt, Bag, Seq) in new work. 16:47:12 <NickH> +1 16:47:16 <sandro> STRAWPOLL: we'll suggest people stop using RDF containers (Alt, Bag, Seq) in new work. (and close ISSUE-24) 16:47:16 <sandro> +1 16:47:18 <NickH> +1 16:47:23 <davidwood> +1 16:47:26 <cygri> q+ to ask what they should use instead 16:47:26 <LeeF> +1 16:47:27 <iand> -1 16:47:31 <AlexHall> +1 16:47:34 <danbri> Proposed: "WG resolves that representing 'ordering' in any open world binary-relation logic language is intrinsically rather annoying; practitioners are notified that RDF containers are annoying, but so are the linked list thingies, and each may be differingly annoying in different situations." 16:47:35 <davidwood> ack cygri 16:47:35 <Zakim> cygri, you wanted to ask if we can get products in the tracker for all specs and to ask what they should use instead 16:47:39 <danbri> -0.12 16:48:07 <NickH> cygri: what is the alternative? Can we put some test in describing what people should do? 16:48:24 <NickH> davidwood: we should promote RDF Lists 16:48:39 <sandro> s/davidwood/sandro/ 16:48:45 <NickH> iand: I don't agree that we should tell people to stop using them 16:48:50 <danbri> q? 16:49:07 <AndyS> -X unless we propose an alternative (not sure on X yet) 16:49:22 <danbri> proposed: "Bag and Alt are mostly harmless, mostly useless." 16:49:58 <NickH> davidwood: can I suggest that we have a proposal that we vote on, to jsut depricate Alt and Bag 16:50:06 <NickH> s/jsut/just/ 16:50:21 <davidwood> Propose to deprecate ALT with the language proposed at 16:50:27 <NickH> sandro: is anyone going to object to deprecating Bag and Alt? 16:50:29 <NickH> iand: yes 16:50:32 <NickH> danbri: yes 16:50:45 <danbri> ' This is an archaic feature of RDF. It was included in the RDF specifications published in 1999 and 2004, but we no longer recommend it be used in new deployments. Some existing software uses it, however, and it will be present in some archival data, so general purpose software must handle it correctly. See @@@ for a more information.' 16:50:55 <pfps> +1 16:51:00 <NickH> davidwood: deprecate does not mean remove 16:51:08 <iand> +1 to archaic 16:51:21 <NickH> danbri: I don't like deprecate and rdf:Seq has its uses 16:51:42 <NickH> danbri: language will be 'This is an archaic feature of RDF' 16:51:46 <cygri> +1 to the text in wiki/ArchaicFeatures for alt, bag and seq 16:51:57 <NickH> s/danbri/davidwood/ 16:51:57 <sandro> PROPOSED: Mark rdf:Alt as an archaic features of RDF 16:52:08 <NickH> danbri: I don't object 16:52:13 <NickH> iand: I don't object 16:52:17 <MacTed> +1 proposal 16:52:17 <danbri> Ian agrees with me 16:52:22 <swh> +1 16:52:28 <iand> i agree with dan 16:52:31 <NickH> iand: I agree with danbri 16:52:32 <sandro> PROPOSED: Mark rdf:Alt as an archaic features of RDF 16:52:40 <gavinc> +1 16:52:40 <NickH> +1 16:52:41 <sandro> +1 16:52:41 <iand> +1 16:52:42 <davidwood> +1 16:52:42 <pfps> +1 16:52:44 <swh> +1 16:52:45 <Guus> =1 16:52:49 <mischat> PROPOSED: Mark rdf:Alt and rdf:Bag as an archaic features of RDF ? 16:52:50 <pchampin> +1 16:52:54 <danbri> stop calling it 'deprecated' please, that's too harsh terminology. I do not want to tell people that their data is bad; just that it is unfashionable. 16:53:17 <mischat> s/PROPOSED: Mark rdf:Alt and rdf:Bag as an archaic features of RDF \?// 16:53:19 <sandro> RESOLVED: Mark rdf:Alt as an archaic features of RDF 16:53:19 <NickH> davidwood: we won't use the term 'deprecated' anymore 16:53:21 <davidwood> RESOLVED: Mark rdf:Alt as an archaic features of RDF 16:53:30 <davidwood> PROPOSED: Mark rdf:Bag as an archaic features of RDF 16:53:36 <sandro> +1 16:53:38 <NickH> +1 16:53:39 <iand> +1 16:53:39 <MacTed> +1 16:53:40 <pfps> +1 16:53:40 <danbri> +1 16:53:41 <swh> +1 16:53:41 <davidwood> +1 16:53:55 <mischat> +1 16:53:56 <pchampin> +1 16:54:08 <NickH> ericP: what is the alternative? 16:54:19 <yvesr> +1 16:54:21 <sandro> eric: I don't know what to tell people to use instead. Maybe x hasFlagColor :red, :blue, :green 16:54:39 <NickH> ericP: I am not really sure what to tell people 16:54:53 <NickH> ericP: is the answer to tell people to use a repeated property? 16:55:02 <iand> people can use custom sequence properties, ex:sequence "1" 16:55:14 <sandro> davidwood: I use a repeated property, possibly off another node. 16:55:18 <pchampin> @ericP: that would be my answer 16:55:39 <gavinc> +1 16:55:56 <NickH> davidwood: are you going to formally object? 16:56:01 <NickH> ericP: no, no 16:56:10 <davidwood> RESOLVED: Mark rdf:Bag as an archaic features of RDF 16:56:28 <NickH> sandro: is anyone objecting? 16:56:33 <NickH> danbri: yes 16:56:35 <AndyS> AndyS has joined #rdf-wg 16:56:48 <NickH> danbri: going to close ISSUE-24 16:56:55 <sandro> s/?/ to doing this with Seq?/ 16:57:14 <NickH> s/danbri/davidwood/ 16:58:04 <NickH> davidwood: closing ISSUE-24 16:58:04 <sandro> ISSUE: Should we mark rdf:Seq as archaic (cf ISSUE-24) 16:58:05 <trackbot> Created ISSUE-77 - Should we mark rdf:Seq as archaic (cf ISSUE-24) ; please complete additional details at . 16:58:33 <NickH> danbri leaves 16:59:29 <NickH> Guus is packing up 16:59:54 <NickH> Guus: my plane is in 2 hours 17:00:33 <NickH> davidwood: I missed you Guus 17:00:45 <tlebo> q+ to ask what OWL 2's annotations fixed that was broken in RDF's reification? (or if OWL 2 fixed them) 17:00:49 <NickH> ISSUE-25? 17:00:49 <trackbot> ISSUE-25 -- Should we deprecate (RDF 2004) reification of statements? -- open 17:00:49 <trackbot> 17:02:14 <gavin_> gavin_ has joined #rdf-wg 17:02:29 <tlebo> owl 2 annotations don't carry any truthfulness in them. 17:02:35 <NickH> pfps: sparql annotations and RDF Reification are completely different 17:02:46 <tlebo> RDF's intent was to be "truthiness" 17:02:49 <yvesr> s/sparql/OWL 17:03:18 <tlebo> "owl annotations are just data sitting on the side; do with it what you will" 17:03:22 <tlebo> q- 17:03:52 <NickH> pfps: when you talk about the truthiness of the Reification, you get the truthiness of the RDF 17:04:18 <AndyS> statings 17:04:21 <NickH> davidwood: when you make a statement about another statement - you are saying something about it 17:04:29 <NickH> davidwood: I could say that it is false 17:05:07 <NickH> davidwood: I think what pfps is saying is, the ability for you saying that statement is true is by expessing a fact about another triple 17:05:31 <NickH> davidwood: I am not saying I agree with it, I am saying I understand what he is saying 17:05:42 <tlebo> RDF had more "truthiness" of the triple cited; while OWL 2 is completely agnostic to the truth of the triple being cited. 17:06:23 <tlebo> Then let's deprecate RDF reification and use OWL 2 if we still want it. 17:06:24 <NickH> davidwood: there is no explicit truthiness tie, just making a statement 17:06:30 <pfps> owl 2 annotations aren't about statements at all, of course, they are "about" classes (or ....) 17:07:08 <tlebo> the rdfs:range of owl:annotatedSource is owl:Class ? 17:07:10 <NickH> sandro: happy to mark Reification as archaic as long as we can provide something to replace it with 17:07:16 <tlebo> (@pfps) 17:07:35 <pfps> saying Bird creationdate 11/11/11 isn't saying something about a logical construct, but is instead might be saying something about an object 17:07:50 <NickH> davidwood: I didn't hear pfps respone to my paraphrasing of him 17:08:31 <NickH> davidwood: not concened about OWL annotations - interested in the deprecation of RDF Reification 17:09:01 <iand> q+ 17:09:09 <davidwood> Straw poll: Should we mark rdf 2004 reification as archaic? 17:09:15 <davidwood> ack iand 17:09:17 <ericP> -0 17:09:48 <gavin_> -0 to wait until something can replace it exists 17:09:57 <NickH> iand: want to make a distinction between reification mechanics and the language used for reification 17:10:19 <NickH> iand: happy to make reification mechanics as archaic 17:10:33 <NickH> iand: as long as the language remains 17:10:49 <NickH> iand: the Talis changespec uses RDF reification 17:11:07 <yvesr> -0 until we understand what we're going to do about graphs and whether we can describe how users can replace one by the other 17:11:14 <sandro> sandro: so let's postpone issue-25 until we have a better solution, then we can mark RDF reificaton as archaic. 17:11:26 <sandro> ian: The reification mechanics (the vocab) are different from the concept of reification in general 17:11:27 <sandro> maybe I got that wrong... 17:11:32 <sandro> ian: I need the reif spec. 17:11:34 <sandro> s/spev/vocab/ 17:11:35 <tlebo> (sorry, @iand - I think i was using @iand to reference Ivan earlier...) 17:11:40 <NickH> pchampin: we are depreicating the non existant reification mechanics 17:11:51 <NickH> davidwood: is there something better? 17:11:58 <cygri> +1 to the archaification of reification 17:12:03 <NickH> iand: I can't think of anyting better at the moment 17:12:49 <NickH> swh: archaic just means that you shouldn't do anything new with it, not that you can't use it for old things 17:12:54 <LeeF> ISSUE-37? 17:12:54 <trackbot> ISSUE-37 -- Handling of fragment identifiers in RDF embedded in other document formats -- open 17:12:54 <trackbot> 17:12:58 <LeeF> ISSUE-46? 17:12:58 <trackbot> ISSUE-46 -- Revisit "Should RDF have a mechanism for declaring two uri's to be equivalent?" -- open 17:12:58 <trackbot> 17:13:16 <NickH> iand: might be a long time before I can change, don't like that idea of my customers using something marked as archaic 17:13:29 <cygri> ACTION: cygri to propose resolution for ISSUE-37 and ISSUE-69 17:13:30 <trackbot> Created ACTION-101 - Propose resolution for ISSUE-37 and ISSUE-69 [on Richard Cyganiak - due 2011-10-20]. 17:13:41 <AndyS> q+ 17:13:54 <NickH> pchampin: my memory of it was that I was the only one who wanted to discuss it 17:14:11 <AndyS> q- 17:14:12 <NickH> pchampin: I had a feeling that people were strongly opposed to it 17:14:13 <gavin_> +0.5 to include sameAssness in RDF (would defer to JJC for a full +1) 17:14:18 <NickH> pchampin: I can live without it 17:14:36 <AlexHall> 17:14:50 <iand> for clarity on ISSUE-25: reification mechanics is and reification vocabulary is 17:15:09 <AndyS> rdf:sameAs owl:sameAs owl:sameAs 17:15:24 <gavin_> Yes, that ;) 17:15:39 <iand> rdf:sameAs owl:equivalentProperty owl:sameAs 17:15:48 <davidwood> Propose to close ISSUE-46 because owl:sameAs is already widely used and accepted. This WG has no better answer. 17:15:50 <pchampin> rdf:sameAs rdf:sameAs owl:sameAs 17:15:55 <pfps> +1 17:15:58 <NickH> +1 17:16:09 <cygri> +! 17:16:11 <gavin_> -0.5 as it adds little bits of OWL when you really don 17:16:13 <cygri> +1 17:16:13 <gavin_> 't need it 17:16:15 <iand> -0 17:16:20 <sandro> +1 17:16:22 <MacTed> +1 17:16:25 <pchampin> +0 17:16:25 <AlexHall> +1 17:16:26 <AndyS> +0.5 17:16:35 <tlebo> OWL is just another vocabulary. 17:16:52 <iand> +1 17:16:54 <AndyS> (other useful owl-isms?) 17:17:06 <davidwood> RESOLVED: Close ISSUE-46 with no action. 17:17:12 <gavin_> Yeah, basiclly RDFS Plus 17:17:15 <pchampin> @Andy: InverseFunctionalProperty ? 17:17:20 <gavin_> owl:sameAs and owl:import 17:17:44 <iand> wasn't owl:imports a bug? :) 17:18:05 <pchampin> owl:imports owl:sameAs rdf:subject 17:18:12 <AndyS> IFP, FP, symmetric,... 17:18:14 <NickH> ISSUE-62? 17:18:14 <trackbot> ISSUE-62 -- Revisit "The test cases manifest format has a semantic error" -- open 17:18:14 <trackbot> 17:18:46 <NickH> davidwood: had anyone looked at test cases recently? 17:18:57 <cygri> q? 17:19:50 <NickH> davidwood: would anyone like to volenteer to take over the RDF test cases? 17:19:59 <NickH> <silence> 17:20:10 <NickH> davidwood: will have to rope ericP into it later 17:20:26 <NickH> ISSUE-1? 17:20:27 <trackbot> ISSUE-1 -- Is TURTLE the same as SPARQL 1.1 triple syntax? -- open 17:20:27 <trackbot> 17:20:28 <tlebo> @iand, "URI reference event r" from; huh? 17:20:40 <AndyS> Test case semantic error 17:21:15 <sandro> gavin_: "Yes, But...." 17:21:47 <NickH> gavin_: escaoping... 17:22:07 <NickH> gavin_: they could be the same apart from some well motivated exceptions 17:22:10 <sandro> PROPOSED: Close issue-1 saying they should be the same except for well-motivated (and small) exceptions. 17:22:36 <NickH> davidwood: not sure we have resolved this issue 17:22:51 <cygri> +1 17:22:54 <sandro> +1 17:22:57 <NickH> sandro: I think we can close this issue 17:22:57 <gavin_> +1 17:23:07 <davidwood> +1 17:23:07 <AndyS> suggest one SPARQL and one RDF person catelogue differences 17:23:09 <MacTed> +1 17:23:14 <gavin_> Hi Andy ;) 17:23:16 <NickH> +1 17:23:49 <AndyS> q+ 17:24:07 <sandro> RESOLVED: Close issue-1 saying they should be the same except for well-motivated (and small) exceptions. 17:24:08 <NickH> gavin_: until Turtle gets closer to being final, hope that the differences will go away 17:24:14 <davidwood> ack AndyS 17:24:25 <NickH> AndyS: no point if you have resolved it 17:24:42 <NickH> AndyS: we should have a definativce cataglogue of what the differences are 17:24:58 <pchampin> s/definativce/definitive/ 17:25:00 <NickH> AndyS: and then work out if it makes sense or not 17:25:18 <NickH> AndyS: I volenteer to do the work from the SPARQL side 17:25:33 <AndyS> For now, on the wiki. 17:25:41 <NickH> davidwood: who shall do the work from the Turtle side? 17:25:51 <NickH> gavin_: me 17:27:02 <AndyS> NB This applies to TriG as well. e.g. trailing DOT 17:27:18 <davidwood> Andy and Gavin will create a list of issues between SPARQL and Turtle. The list will be maintained on the RDF WG wiki and may become an appendix to the Turtle spec. 17:27:34 <NickH> AndyS: yes, that is fine 17:27:38 <NickH> gavin_: yup 17:28:13 <tlebo> +1 17:28:18 <tlebo> (we have issues) 17:28:51 <yvesr> no 17:29:14 <NickH> davidwood: we resolve to put N-Triples into the Turtle document 17:29:49 <NickH> gavin_: no resolution on what to do with old N-Triples that doesn't have a media type and new n-Triples that does have a media type 17:29:55 <AndyS> As long as there is a NT language and mime type (and its suggested to use UTF-8) somewhere 17:30:02 <AndyS> Ditto NQ 17:30:22 <NickH> ISSUE-19? 17:30:22 <trackbot> ISSUE-19 -- Should TURTLE allow triples like "[ :p 123 ]." as SPARQL does ? -- open 17:30:22 <trackbot> 17:30:41 <NickH> gavin_: this can be resolved closed as a duplicate of ISSUE-1 17:30:54 <NickH> gavin_: I have just closed ISSUE-1 17:31:11 <NickH> ISSUE-73? 17:31:11 <trackbot> ISSUE-73 -- IRI_REF vs. IRIref -- open 17:31:11 <trackbot> 17:31:29 <NickH> gavin_: I need to resolve this with AndyS 17:31:43 <NickH> davidwood: do you need help from the working group? 17:31:53 <NickH> gavin_: I need help from AndyS 17:32:04 <NickH> gavin_: they are subtly different 17:32:22 <NickH> gavin_: they shouldn't be combined, they should be renamed 17:33:12 <NickH> ISSUE-74? 17:33:13 <trackbot> ISSUE-74 -- Prefixed names and slashes -- open 17:33:13 <trackbot> 17:33:38 <NickH> gavin_: this is actually a working group issue 17:33:52 <NickH> both are agreed and people think both are right 17:34:12 <NickH> davidwood: end of the Turtle Issues 17:34:20 <NickH> davidwood: lets go to RDF General 17:34:23 <NickH> ISSUE-3? 17:34:23 <trackbot> ISSUE-3 -- Between us, we need to study the feedback we got via on the previous round of specs (and errata) -- open 17:34:23 <trackbot> 17:34:41 <NickH> davidwood: certainly have to do that, certainly havn't done it 17:34:45 <NickH> davidwood: lets move on 17:35:19 <NickH> sandro: if it doesn't require a working group decision, better to put an action on somebody 17:35:50 <NickH> davidwood: I think we should put an action on Ivan 17:36:06 <NickH> davidwood: I can't imageine who else could do this well 17:36:15 <NickH> sandro: I think cygri would do a good job 17:36:39 <tlebo> also not hearing things. 17:36:40 <mischat> mischat has joined #rdf-wg 17:37:53 <NickH> cygri: I am not going to volenteer for this because I think it is going to be a lot of work 17:38:13 <NickH> davidwood: wondering if one of Guus's students might want to do this 17:38:34 <NickH> work for someone young, keen and wanting to prove himself 17:39:17 <sandro> action: davidwood ask Guus to find a student to do the work of ISSUE-3 17:39:17 <trackbot> Created ACTION-102 - Ask Guus to find a student to do the work of ISSUE-3 [on David Wood - due 2011-10-20]. 17:39:20 <Scott_Bauer> scribe: scott 17:39:28 <sandro> scribe: scott 17:40:48 <Scott_Bauer> davidwood: issue 65 where do these exist? 17:40:52 <LeeF> ISSUE-65? 17:40:52 <trackbot> ISSUE-65 -- Update XSD 1.0 references to XSD 1.1 -- open 17:40:52 <trackbot> 17:40:57 <cygri> q+ 17:42:54 <Scott_Bauer> davidwood: we have rdf concepts written when rdf was xml. We ought to push xsd to serializations. 17:43:22 <Scott_Bauer> … need to change wording in concepts. 17:43:38 <davidwood> ack cygri 17:44:17 <Scott_Bauer> cygri: a broader point. Can't have a literal anymore in 1.1. need something more in rdf concepts 17:44:47 <Scott_Bauer> … datatypes only get into rdf when you get into semantics. needs to change. 17:44:56 <gavin_> s/literal/plain literal/ 17:45:02 <pchampin> q+ to ask richard about simple entailment 17:45:03 <Scott_Bauer> … needs to somehow include xsd: string 17:45:35 <Scott_Bauer> davidwood: we have clean up to do in rdf concepts 17:45:46 <Scott_Bauer> … section 5 datatypes. 17:46:31 <cygri> ACTION: cygri to mention ISSUE-65 in RDF Concepts ED (Section 5) 17:46:32 <trackbot> Created ACTION-103 - Mention ISSUE-65 in RDF Concepts ED (Section 5) [on Richard Cyganiak - due 2011-10-20]. 17:46:40 <Scott_Bauer> action: cygri to add issue 65 as an issue on the rdf concepts section 5 datatypes 17:46:41 <trackbot> Created ACTION-104 - Add issue 65 as an issue on the rdf concepts section 5 datatypes [on Richard Cyganiak - due 2011-10-20]. 17:47:08 <Scott_Bauer> davidwood: alex does that address your issue on issue 65 17:47:32 <Scott_Bauer> … richard I propose to take your action and close action 65. 17:47:58 <Scott_Bauer> sandro: at this point its in CR 17:48:28 <Scott_Bauer> davidwood: we can raise an new issue if it stalls 17:48:44 <Scott_Bauer> … closing issue 65 moving to an editorial action. 17:48:56 <Scott_Bauer> … on rdf concepts 17:49:03 <Scott_Bauer> topic: issue 66 17:49:48 <Scott_Bauer> davidwood: this needs to be a semantics issue 17:50:11 <Scott_Bauer> alexwood: owl2 and rid add some not referenced in semantics 17:50:26 <davidwood> s/alexwood/alexhall/ 17:50:48 <Scott_Bauer> cygrid: the concepts in rdf semantics are practical and should be in semantics 17:51:07 <Scott_Bauer> s/cygrid/cygri 17:51:18 <pchampin> s/concepts/list of XSD datatypes/ 17:51:24 <iand> he said the datatype list should be in concepts (as well as semantics) 17:51:32 <gavin_> +1 17:51:42 <pchampin> s/be in semantics/be in RDF concepts/ 17:51:45 <Scott_Bauer> cygri: list of datatypes that are in recommended for use in semantics should be in concepts 17:51:50 <mischat> +1 17:51:50 <iand> +1 17:51:53 <pchampin> +1 17:51:55 <Scott_Bauer> davidwood: i concur 17:51:57 <yvesr> +1 17:52:04 <davidwood> +1 17:52:43 <Scott_Bauer> action: cygri contact pat and peter and make sure they are ok with this 17:52:43 <trackbot> Created ACTION-105 - Contact pat and peter and make sure they are ok with this [on Richard Cyganiak - due 2011-10-20]. 17:53:33 <Scott_Bauer> davidwood: lets leave graphs alone 17:53:46 <gavin_> action: gavinc add link from Turtle datatypes section to recommended list in concepts 17:53:47 <trackbot> Created ACTION-106 - Add link from Turtle datatypes section to recommended list in concepts [on Gavin Carothers - due 2011-10-20]. 17:53:48 <Scott_Bauer> davidwood: topic issue 16 17:54:02 <Scott_Bauer> topic: issue 16 17:54:08 <cygri> ISSUE-16? 17:54:08 <trackbot> ISSUE-16 -- What is the normative serialization of the JSON grammar? -- open 17:54:08 <trackbot> 17:54:16 <Scott_Bauer> davidwood: should this be an issue at all? 17:55:16 <Scott_Bauer> … this should remain open and we move on 17:55:29 <Scott_Bauer> topic: issue 69 17:55:58 <Scott_Bauer> davidwood: richard gave himself an action for 34 and 69. will propose something 17:56:28 <Scott_Bauer> topic: issue 70 17:56:45 <Scott_Bauer> davidwood: close as an editorial issue 17:56:54 <Scott_Bauer> … ? 17:57:04 <Scott_Bauer> cygri: I'd like to keep it open 17:57:33 <gavin_> issue-75? 17:57:33 <trackbot> ISSUE-75 -- Valid plain literals containing #x0 are ill-typed in RDF 1.1 -- open 17:57:33 <trackbot> 17:57:45 <Scott_Bauer> topic: issue 75 17:58:55 <Scott_Bauer> cygri: unicode not allowed in xml version. all sorts of formerly valid rdf plain literals are no longer valid 17:59:27 <Scott_Bauer> … unicode .0 18:00:11 <Scott_Bauer> davidwood: what should the resolution be? 18:00:41 <Scott_Bauer> cygri: we should have all the changes rdf 1.0 and 1.1 in same place. 18:01:11 <Scott_Bauer> sandro: put it in use cases and requirements? 18:01:38 <Scott_Bauer> cygri: do we have such a document? 18:01:44 <Scott_Bauer> sandro: no 18:02:04 <iand> we should notify community early to see if it breaks any implementations 18:02:06 <Scott_Bauer> davidwood: will create a note -- not an action item. 18:02:23 <Scott_Bauer> … 18:02:56 <Scott_Bauer> sandro: we put it in rdf concepts now? 18:03:36 <AlexHall> how many implementors validate xsd:strings right now? 18:03:49 <iand> we could write a negative test case: :x :y "\u0000" . 18:04:09 <iand> ask implementors to try that test and see if they handle it 18:04:11 <Scott_Bauer> letting cygri create the action item? 18:04:16 <cygri> ACTION: cygri to add a note to RDF Concepts re ISSUE-75 18:04:16 <trackbot> Created ACTION-107 - Add a note to RDF Concepts re ISSUE-75 [on Richard Cyganiak - due 2011-10-20]. 18:04:19 <sandro> gavin_: This wasn't a problem pre-turtle because no syntax could express it. 18:04:51 <Scott_Bauer> davidwood: Ian's says it should be a test case 18:05:06 <Scott_Bauer> gavinc: it can't be expressed in n-triples 18:05:30 <Scott_Bauer> sandro: it's a syntax error -- you expect it to fail 18:05:36 <iand> it can be expressed in ntriples (as above) but it is just datatype invalid 18:05:54 <Scott_Bauer> topic: issue 76 18:06:18 <cygri> sandro++ 18:06:46 <Scott_Bauer> sandro: close issue 75 first 18:06:48 <iand> If i can write "x"^^xsd:int then I can write "\u0000"^^xsd:string 18:07:05 <Scott_Bauer> davidwood: closing issue 75 18:07:36 <Scott_Bauer> … issue 76 overcome by events if datatypes move from semantics to concepts 18:07:49 <Scott_Bauer> cygri: it's a bug and needs to stay open. 18:08:15 <Scott_Bauer> davidwood: we resolved this at an earlier date but we forgot to close it 18:08:35 <Scott_Bauer> davidwood: pat closed it 18:08:53 <NickH> ACTION-76? 18:08:53 <trackbot> ACTION-76 -- Patrick Hayes to summarize the options -- due 2011-08-24 -- CLOSED 18:08:53 <trackbot> 18:09:03 <Scott_Bauer> this was action 76 18:09:08 <gavin_> iand, I agree (sort of) but I don't think you could write Recomended RDF that used #x0 at all. 18:09:37 <gavin_> by a strict reading of the specifications 18:09:49 <Scott_Bauer> davidwood: action: check with pat hayes to see if issue 76 can be closed 18:10:04 <Scott_Bauer> action: check with pat hayes to see if issue 76 can be closed 18:10:04 <trackbot> Sorry, couldn't find user - check 18:10:35 <davidwood> action: davidwood to check with pat hayes to see if issue 76 can be closed 18:10:35 <trackbot> Created ACTION-108 - Check with pat hayes to see if issue 76 can be closed [on David Wood - due 2011-10-20]. 18:10:54 <MacTed> RRSAgent, drop action 11 18:11:04 <Scott_Bauer> davidwood: only other issues are with graphs 18:11:30 <Scott_Bauer> … we can do issues for graphs or we can talk about the primer 18:11:30 <cygri> "Review of all outstanding Documents that the WG is updating." 18:11:56 <cygri> q+ to suggest "Review of all outstanding Documents that the WG is updating." 18:12:15 <Scott_Bauer> sandro: issue 21 re node sharing is a possibilities 18:12:24 <pchampin> q- 18:12:31 <Scott_Bauer> cygri: let's not look at graphs now 18:12:37 <gavin_> +1 no more talking about graphs 18:12:39 <iand> no issues were raised from our f2f discussions on named graphs. pity we couldn't get concrete issues from them 18:12:53 <iand> gavin_: we can't talk about graphs anyway 18:13:14 <gavin_> ack cygri 18:13:14 <Zakim> cygri, you wanted to suggest "Review of all outstanding Documents that the WG is updating." 18:13:18 <sandro> indeed, iand.... :-( 18:13:18 <Scott_Bauer> … review outstanding documents 18:13:39 <Scott_Bauer> … need editors drafts for other documents 18:13:54 <Scott_Bauer> … check up on prospective editors for these 18:14:07 <Scott_Bauer> davidwood: we should look into the editors list 18:14:47 <Scott_Bauer> sandro: we need to do one issue per week before last call 18:15:20 <Scott_Bauer> davidwood: let's go through the editors list 18:15:38 <Scott_Bauer> … we'll do the primer if we have time. 18:15:56 <sandro> s/do one/close one (on average)/ 18:16:09 <Scott_Bauer> … vocabulary. we had dan brickley. Do we need a co-editor 18:16:16 <Scott_Bauer> … anyone interested 18:16:33 <pchampin> and if he does, I volunteer 18:16:41 <Scott_Bauer> action: davidwood ask danbri if he would like a co-editor on vocabulary 18:16:41 <trackbot> Created ACTION-109 - Ask danbri if he would like a co-editor on vocabulary [on David Wood - due 2011-10-20]. 18:17:23 <Scott_Bauer> davidwood: n-triples two oracle editors on one documents. 18:17:42 <Scott_Bauer> gavinc: they raised objections and were made editors as a result. 18:19:06 <Scott_Bauer> davidwood: a fait accompli n-triples will be a part of the turtle doc 18:19:13 <iand> thanks sandro - i work better through the medium of text :) 18:19:33 <Scott_Bauer> … sour and she will work with gavin on the document 18:19:48 <Scott_Bauer> s/sour/souri 18:19:56 <gavin_> s/she/zhe/ 18:21:15 <Guus> Guus has joined #rdf-wg 18:21:33 <Guus> [from Heathrow] 18:21:59 <gavin_> This is the Linked Data API stuff yes? 18:22:08 <Scott_Bauer> davidwood: yves could you describe any progress on the JSON recipes note 18:22:27 <Scott_Bauer> yvesr: have not started on it yet. 18:23:29 <Scott_Bauer> action: davidwood ping fabian re rdf syntax spec revised 18:23:30 <trackbot> Created ACTION-110 - Ping fabian re rdf syntax spec revised [on David Wood - due 2011-10-20]. 18:24:12 <Scott_Bauer> davidwood: richard the n-quad syntax? 18:24:43 <Scott_Bauer> cygri: we don't know what's going to have until abstract syntax is better developed 18:24:48 <tomayac> tomayac has joined #rdf-wg 18:25:06 <Scott_Bauer> … might be part of the turtle work for eric or gavin? 18:25:42 <Scott_Bauer> davidwood: I disagree. we agreed that turtle would not deal with named graphs. 18:26:05 <Scott_Bauer> gavinc: I'm willing to work with someone on the the trig syntax. 18:26:22 <Scott_Bauer> … I'd like someone else to co-edit 18:27:14 <Scott_Bauer> cygri: trig and n-quads I've worked with but syntax is a lot of detailed syntax gavin is better at. 18:27:27 <Scott_Bauer> … grammar is 95% the same 18:27:42 <Scott_Bauer> gavin: I need some else but I agree 18:27:50 <Scott_Bauer> … the grammar will not be repeated. 18:28:15 <Scott_Bauer> cygri: Once we know abstract syntax we should revisit. 18:28:41 <Scott_Bauer> … concepts work is unknown. Work may go well 18:29:04 <Scott_Bauer> … I might consider in the future but not now. 18:29:49 <Scott_Bauer> davidwood: process question for sandro. 18:29:58 <sandro> change the shortname "rdf-syntax-grammar" to "rdf-xml" 18:30:01 <sandro> seems fine to me. 18:31:34 <Scott_Bauer> davidwood: should we do anything with our last 30 minutes 18:32:31 <Scott_Bauer> sandro: I have much of the scribe cleanup done but you are free to clean them up as necessary. 18:33:28 <Scott_Bauer> … (referring to the minutes) 18:34:21 <Scott_Bauer> davidwood: rdf primer is scheduled what do people want? 18:35:08 <Scott_Bauer> sandro: will it be a multi syntax document 18:35:11 <Guus> should come back on a telecon 18:35:20 <Scott_Bauer> davidwood: that would be great 18:35:41 <Guus> 1st version turtle/trig, add others later 18:36:27 <Scott_Bauer> … good for the community if all the serializations are represented in the primer. 18:36:52 <Guus> sure 18:36:55 <Scott_Bauer> gavinc: only one will have named graphs or can deal with it. 18:37:22 <Scott_Bauer> sandro: convenient in trig doable in others 18:37:38 <Scott_Bauer> … near a clear model use trig 18:38:34 <sandro> sandro: Once we have a clear enough model, I think it will be easy enough to define a useable way to do it in pure triples. 18:38:47 <Scott_Bauer> s/near a clear mode/need a clear model/ 18:39:06 <sandro> PROPOSED: The primer should have examples in each of our syntaxes 18:39:17 <gavin_> +1 18:39:18 <pchampin> +1 18:39:19 <MacTed> +1 18:39:20 <sandro> +1 18:39:20 <davidwood> +1 18:39:23 <Scott_Bauer> +1 18:39:25 <Guus> +1 18:39:30 <sandro> RESOLVED: The primer should have examples in each of our syntaxes 18:39:45 <sandro> PROPOSED: The primer should have a section on each of our syntaxes 18:39:45 <davidwood> +1 18:39:49 <gavin_> +1 18:39:49 <MacTed> +1 18:39:49 <sandro> +1 18:39:51 <pchampin> +1 18:39:55 <Scott_Bauer> +1 18:39:59 <sandro> RESOLVED: The primer should have a section on each of our syntaxes 18:40:10 <sandro> PROPOSED: The primer should be 500 bytes long. 18:40:11 <Guus> this section may be an appendix 18:40:27 <sandro> PROPOSED: The section on RDF/XML should not be first 18:40:32 <pchampin> +1000 18:40:36 <Guus> good to limit main text length 18:40:57 <sandro> Guus? I thought you left... 18:41:03 <Guus> [anybody hearing me?] 18:41:05 <davidwood> PROPOSED: The section on RDF/XML should be the last syntactical section. Turtle should be first. 18:41:13 <cygri> PROPOSED: The full text for the RDF/XML section should be: “Don't.” 18:41:15 <davidwood> Guus: We don't hear you 18:41:23 <davidwood> Please vote on: 18:41:28 <davidwood> PROPOSED: The section on RDF/XML should be the last syntactical section. Turtle should be first. 18:41:31 <MacTed> +1 18:41:35 <cygri> +1 18:41:36 <pchampin> +1 18:41:44 <AlexHall> +1 18:41:44 <gavin_> +1 given that we resolve name graphs in turtle ;) 18:41:45 <Guus> i think this is going in tto much detail, just formulate reqs, not structure 18:41:48 <sandro> +0 I think that's a little much 18:41:50 <gavin_> hehe 18:41:59 <gavin_> You think? ;) 18:42:32 <gavin_> AlexHall: What font should we use? # SPECIAL MARKER FOR CHATSYNC. DO NOT EDIT THIS LINE OR BELOW. SRCLINESUSED=00001633
|
http://www.w3.org/2011/rdf-wg/wiki/Chatlog_2011-10-13
|
CC-MAIN-2014-41
|
refinedweb
| 20,610
| 63.12
|
- Type:
Bug
- Status: Reopened (View Workflow)
- Priority:
Major
- Resolution: Unresolved
- Component/s: workflow-basic-steps-plugin
- Labels:None
- Similar Issues:
Directories with an ampersand (like @tmp and @script) are not removed when using 'deletedir()' in pipeline stage.
- is duplicated by
JENKINS-44909 Workspace Cleanup does not delete @tmp directories created by libraries
- Closed
Multibranch pipeline (Jenkinsfile):
stage('Checkout') { checkout scm } stage('Build') { def resultDist = sh returnStdout: true, script: './gradlew build' println resultDist } stage('Cleanup') { deleteDir() }
This will create some directories in the Jenkins workspace, e.g:
MyBranch-GWI555O7BRZQK2BI4NIP67CEYQUZYH36AKCBALPQ2TWX4CIGNYIZ MyBranch-GWI555O7BRZQK2BI4NIP67CEYQUZYH36AKCBALPQ2TWX4CIGNYIZ@tmp
After the 'Cleanup' stage the directories with an ampersand are still there
We expect that all directories are removed.
yes Stefan Droog you are right.
i am still facing this issue.
currently i have to delete that directory manual.
i faced this when my storage is fully occupied, i have many branches so each branch taking lots spaces after completed build.
I fail to understand how this issue can be set to "Important" and that importance not be explained in details. At first sight it seems like one of Minor or less priority. Not a bug by the way, more an improvement.
So given this, I would probably not hold my breath that this is fixed anytime soon if people thinking this should be configurable or so contribute this fix.
In my case, I'm doing some dockerized stuffs with admin privileges in a specific subdir created for for this purpose, which is supposed to be removed afterwards. so, these additional temp dirs are created as root. Once outside of the container, the next time jenkins starts the job, it obviously fails to delete this root owned directory, so I have to take care of it "manually" from within the container. OK, our docker should maybe be set differently so that a container root user is not mapped to the global root user, but still, a deleteDir() function which does not delete all leftovers is not just a minor annoyance.
In our case, we are using multibranch pipeline jobs. We also see this issue occurring. This results in our drive filling up with folders that don't get cleaned up properly. Jenkins is running on a VM in Azure in our environment.
Our Jenkins runs out of space once per day while having 50GB of space. Very intensive building occurs. Please fix cleanup
i face this issue as well. @libs and @scripts directories contains too much files, so jenkins master runs out of inodes and must be cleaned manually
Hiten Prajapati, I used the Work Space Cleanup plugin, try this:
ws(pwd() + "@tmp") { step([$class: 'WsCleanup']) }
Experiencing this as well on our master node. Running on Azure, would rather not have to pay for infinite HDD space
We're experiencing this as well, but while using `cleanWs()`. Also, our file / folder ownerships are simply `jenkins:jenkins` so no problem there as mentioned by Alexandre Feblot. The biggest problem about this bug is that it can create a massive overhead of inodes in some cases. We constantly experience `No space left on device` errors. We're now about to create a cronjob to periodically remove the @script / @tmp folders. I'd love to hear better workarounds.
I'd like to add, we've just added the following workaround, which seems to work pretty nicely for now.
post { always { cleanWs() dir("${env.WORKSPACE}@tmp") { deleteDir() } dir("${env.WORKSPACE}@script") { deleteDir() } dir("${env.WORKSPACE}@script@tmp") { deleteDir() } } }
Is there any way to ensure the directories with this format on master get deleted as well?
/var/lib/jenkins/workspace/application_PR-2375-5BLTOX3EZC6OGXGE7L2TFKXEY6Y3FYMDZ2VZ37EORCWPFIFMUKHA@script
These directories are created when Jenkins goes to read and validate the Jenkinsfile initially. No further work appears to be done. These directories continue to accumulate until my master machine runs out of disk space. A bit of a nuisance.
I'm not entirely sure what you mean? These workspace `@script` folders should be deleted with the snippet I posted.
I suspect that only does it on the agent, not on the master. The path on my Jenkins master where files are accumulating is only referenced at the start of a build, and never again throughout.
Ah I see, we only build on the same machine, I'm not sure how a master node would work. I'm not sure how to delete the dirs there.
please Help me this is still problem me cos we have many jobs with many branches in project that's make my ssd full.
I run a simple cleanup bash script inside a job every once in awhile on my nodes.
#!/usr/bin/env bash
- get to main job directory
cd ..
ls -al
cd ..
ls -al
- delete all @tmp files
find . | grep @tmp$ | xargs -n1 rm -fr
Of course you need to make sure you don't have any artifacts that you might match.
The standard cleanWs() leaves at least the tmp directories behind on the agents. This is a real big problem for people using secret files , as it leaves them behind and they could be discoverable from another job!
I'm going to try the workaround posted by Niels van Aken.
For what its worth Alexander Trauzzi I'm not seeing the orphaned @scipt directories on my jenkins master as of version 2.108 for my multibranch pipeline jobs.
Not sure why these directories would be required. There are system-wide temporary directories that should be used for this. The temporary directories, no matter what implementation detail, should not concern us users.
Im having the same issue, but also a folder named WORKSPACE_cleanup is created.
Has anyone solved this for the 'master - slave' setup? Our master is rapidly running out of disk space due to mercurial performing a full checkout into @script just to get the jenkinsfile (see). I'd like a solution that can be implemented within a scripted jenkinsfile eg:
node ('slave') {
// do useful build things first
cleanWs() // clean up workspace on slave
}
cleanWs // clean workspace(s) on master (eg @script @libs directories)
To answer my own question, similar to Niels van Aken solution but running on 'master'
node ('slave') {
// do useful build things first
cleanWs() // clean up workspace on slave
}
node ('master') {
dir("${env.WORKSPACE}@libs") {
deleteDir()
}
dir("${env.WORKSPACE}@script") {
deleteDir()
}
}
Although this only cleans the directories when the stages on the slave succeed. You can use try..catch to catch exceptions from the slave stages and perform the cleanup in a finally block if required.
Together with "external workspace" plugin:
node('master'){
def extWs = exwsAllocate diskPoolId: 'p2000'
exws(extWs) {}}
sh "env | sort >test.txt"
sleep time: 5, unit: 'MINUTES'
cleanWs cleanWhenNotBuilt: false, notFailBuild: true
}
cleanWs cleanWhenNotBuilt: false, notFailBuild: true
}
the result is even worse:
$ls -la /p2000/test-extws/
total 0
drwxr-xr-x 7 jenkins jenkins 62 Jun 25 13:42 .
drwxr-xr-x 3 jenkins jenkins 23 Jun 25 11:38 ..
drwxr-xr-x 2 jenkins jenkins 21 Jun 25 11:38 3
drwxr-xr-x 2 jenkins jenkins 6 Jun 25 11:38
drwxr-xr-x 2 jenkins jenkins 6 Jun 25 11:45
drwxr-xr-x 2 jenkins jenkins 6 Jun 25 11:53
drwxr-xr-x 2 jenkins jenkins 6 Jun 25 13:37
Temp directories are flooding the workspace parent folder.
Hello Guys,
i have the following Jenkinsfile :
pipeline { options { disableConcurrentBuilds() } agent { label 'vhost01' } stages { [..AllStages..] } post { always { cleanWs() } } }
I use multibranch pipeline and have the problem that the folder under my node "vhost01" are not deleted. Can anyone help ?
+1 we now have about 200-300 @tmp/@script folders being created every day across several slave servers.
-
EDIITED-
Will add the script snippet provided above for current jobs for now
+1 I have added in a post always block a set of folderDelete operation... As far as I have only one slave, it is sustainable, but it will become ugly when using a label referencing several slaves.
Please reopen with step by step instructions to reproduce the problem and clear description of what you expect to happen.
|
https://issues.jenkins-ci.org/browse/JENKINS-41805?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&showAll=true
|
CC-MAIN-2019-47
|
refinedweb
| 1,337
| 63.7
|
In this article, we’ll talk about the Tkinter Frame and Label widgets.
Let’s Talk About the Tkinter Frame and Label Widgets
We’ll go over both the widgets one by one to understand the fundamentals
What is a Tkinter Frame?
A frame in tkinter is a widget that appears as a rectangular area on the screen. This widget serves as a base for the placement of other widgets such as Labels, Checkbuttons, RadioButtons, etc. Tkinter frame widgets are basically used to group the other widgets on the screen.
Frames are not only used for widgets, they can also be used to place video overlays and other external processes. The frame widget has various properties such as background color, height and width.
Coding a Tkinter Frame
Here’s an example for the Frame is as shown below.
from tkinter import * root=Tk() frame = Frame(width=100, height=100, bg="red", colormap="new") frame.pack(side=LEFT) # set size of window root.geometry('500x500') # set an infinite loop so window stays in view root.mainloop()
The small red box on the left side of the output is the tkinter frame that we created. Let’s move on to creating a label widget.
What is a Tkinter Label?
Tkinter provides the Label widget to insert any text or images into the frame. Tkinter allows several lines of text to be displayed on the frame however, only one choice of font to the user.
Labels are like typical text boxes and can be of any size. If the user defines the size, then the contents are adjusted within that size and if not it adjusts according to the length of your content on its own.
Labels have
foreground and
background fields to specify your choice of color. The syntax of the same is as shown below.
w = Label(root, text="Hey there", fg="red")
For background color make sure you use
bg as the attribute.
Labels can be used to display PhotoImages and BitMapImages. The syntax for this is also shown below.
photo = PhotoImage(file="welcome.jpg") w = Label(root, image=photo) w.photo = photo
Coding a Label
from tkinter import * root=Tk() label1 = Label(root, text="hi, welcome to GUI using Tkinter") label1.pack() root.geometry('500x400') root.mainloop()
The output of the above code is as shown below.
Implementing Tkinter Frame and Label Widgets
from tkinter import * root=Tk() root.title("My first GUI") # set resizing to false root.resizable(width=FALSE, height=FALSE) # set size of window root.geometry('500x400') leftFrame = Frame(root) leftFrame.pack(side=LEFT) rightFrame = Frame(root) rightFrame.pack(side=RIGHT) label1 = Label(leftFrame, text="Left column") label1.pack() label3 = Label(leftFrame, text="Column content") label3.pack() label2 = Label(rightFrame, text="Right column") label2.pack() # set an infinite loop so window stays in view root.mainloop()
The output of the above code is as shown below.
Conclusion
This comes to the end of our tutorial on the creation of a Frame and Labels using Tkinter. Try out this code and let us know your feedback in the comment section below.
|
https://www.askpython.com/python-modules/tkinter/tkinter-frame-and-label
|
CC-MAIN-2020-50
|
refinedweb
| 514
| 59.4
|
?
So I'm as confused as ever. Going into sleep mode definitely uses less power (I can measure the difference!) but consumption doesn't seem to be anywhere near as low as it should be.
Quote from: dc42 on Apr 25, 2013, 08:31 am ?Yep. I've done it with/without the programmer, it made no real difference.
I don't know what your setup looks like to determine what's wrong. It could be a software issue or hardware issue, such as something wrong with the wiring.
Are you asking how to accurately measure current of the chip using a multi-meter or with the 1M Ohmz method Nick showed?
Here, follow these steps to get your power readings:
I was able to get the Attiny85V chip down to pretty low power in the uA as well using these steps.
You've misunderstood my reply, I didn't say anything about the programmer. What have you done to ensure that none of the I/O pins is a floating input?
#include <Arduino.h>#include <avr/power.h>#include <avr/sleep.h>#include <avr/wdt.h>#include <avr/cpufunc.h>#include <util/delay.h>/*================================================================ Go to sleep for 4 seconds================================================================*/// Watchdog interrupt vectorISR (WDT_vect){ WDTCR &= ~(1<<WDIE); // Disable the watchdog interrupt}void doSleep(){ // Set watchdog time to 4 seconds cli(); byte b = (1<<WDE)|(1<<WDP3)|(0<<WDP2)|(0<<WDP1)|(0<<WDP0); WDTCR = b; WDTCR = b|(1<<WDIE); // Enable watchdog interrupt (this wakes me up!) wdt_reset(); // sleep sei(); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_mode();}/*================================================================ Main program================================================================*/void setup(){ power_all_disable(); // All pins input with pullups DDRB = 0; PORTB = 0x1f; // Do these achieve anything? They don't seem to... ADCSRA = 0; DIDR0 = 0x3c;}// Alternate between sleep/work (the reading on the multimeter will switch every 4s...)void loop(){ // Sleep for 4s doSleep(); // Work for 4s _delay_ms(4000);}
...with the 1M Ohmz method Nick showed?
10.2.5 Digital Input Enable and Sleep ModesAs shown in Figure 10-2, the digital input signal can be clamped to ground at the input of theschmitt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller inPower-down mode to avoid high power consumption if some input signals are left floating, orhave an analog signal level close to VCC/2.SLEEP is overridden for port pins enabled as external interrupt pins. If the external interruptrequest is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by variousother alternate functions as described in "Alternate Port Functions" on page 59.
Try adding a 0.1uF decoupling capacitor between the Vcc and ground pins of the chip. Without it, the chip may misbehave.
btw I just found this in the attiny datasheet:...So it looks like setting the pins to inputs with pullups enabled isn't necessary on the attiny. It might even be worth trying without the internal pullups enabled.
// Wait for button to be pressed do { set_sleep_mode(SLEEP_MODE_PWR_DOWN); cli(); if (PORTB & 0b00000100) { GIMSK = _BV(INT0); sleep_enable(); sei(); sleep_cpu(); sleep_disable(); } sei(); uint32_t now = micros(); while ((micros() - now) < 5000) {} } while (PORTB & 0b00000100);
I built an attiny-based remote control a while ago, and I seem to be using different sleep code. This is what I use:Code: [Select]sleep_enable();sei();sleep_cpu();sleep_disable();
sleep_enable();sei();sleep_cpu();sleep_disable();
What does the current drop to if you don't use the watchdog?
The watchdog is designed for this usage, I doubt it's responsible for the 220uA.
I might just try this out tonight. What fuse settings are you using?
attiny85.name=ATtiny85 (internal 1 MHz clock)attiny85.bootloader.low_fuses=0x62attiny85.bootloader.high_fuses=0xd7attiny85.bootloader.extended_fuses=0xff...
Have you tried it with more than one attiny chip?
Are you sure the watchdog is being set correctly? Normally you need to set WDCE before changing WDE or the prescaler bits.
BTW, after the watchdog interrupt WDIF is cleared automatically (so you don't need to do it in the ISR). Meanwhile the WDT is still running, and may reset the processor before the 4s delay finishes (not that it matters much in this case).
I also noticed that you're not switching the ADC off after disabling it (power reduction register, PRR).
The "power_all_disable()" does that.
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy
|
http://forum.arduino.cc/index.php?topic=158060.msg1216204
|
CC-MAIN-2016-18
|
refinedweb
| 735
| 64.91
|
testhaipham 1.0.1
testhaipham #
A new flutter plugin project.
Getting Started #
For help getting started with Flutter, view our online documentation.
For help on editing plugin code, view the documentation.
0.0.1 #
- TODO: Describe initial release.
import 'package:flutter/material.dart'; import 'dart:async'; import 'package:flutter/services.dart'; void main() => runApp(new MyApp111()); class MyApp111 extends StatefulWidget { @override _MyAppState createState() => new _MyAppState(); } class _MyAppState extends State<MyApp111> { = 'android'; }: testhaipham: haipham/testhaiphamhaipham.dart.
Run
flutter format to format
lib/testhaipham.dart.
Maintenance suggestions
Package is getting outdated. (-46.58 points)
The package was last published 76 weeks ago.
The package description is too short. (-20 points)
Add more detail to the
description field of
pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.
|
https://pub.dev/packages/testhaipham
|
CC-MAIN-2020-05
|
refinedweb
| 135
| 53.17
|
, you may need to create one or more device nodes for the new devices.
On systems without DEVFS (this concerns all FreeBSD versions before 5.0), device nodes are created using the MAKEDEV(8) script as shown below:
# cd /dev # sh MAKEDEV ad1
This example would make the proper device nodes for the second IDE drive when installed.
The device file system, or DEVFS, provides access to kernel's device namespace in the global file system namespace. Instead of having to create and modify device nodes, DEVFS maintains this particular file system for you.
See the devfs(5) manual page for more information.
DEVFS is used by default in FreeBSD 5.0 and above.
This, and other documents, can be downloaded from.
For questions about FreeBSD, read the documentation before contacting <[email protected]>.
For questions about this documentation, e-mail <[email protected]>.
|
https://docs.huihoo.com/freebsd/handbook/basics-devices.html
|
CC-MAIN-2020-40
|
refinedweb
| 142
| 58.89
|
#include <KPasswordDialog>
Detailed Description
A dialog for requesting a password and optionaly a login from the end user.
Usage Example
Requesting a simple password, asynchronous
Requesting a login and a password, synchronous
dialog for requesting login and password from the end user
Definition at line 60 of file kpassworddialog.h.
Member Enumeration Documentation
Definition at line 100 of file kpassworddialog.h.
Definition at line 66 of file kpassworddialog.h.
Constructor & Destructor Documentation
create a password dialog
- Parameters
-
Definition at line 59 of file kpassworddialog.cpp.
Destructor.
Definition at line 69 of file kpassworddialog.cpp.
Member Function Documentation
Reimplemented from QDialog.
Definition at line 376 of file kpassworddialog.cpp.
Adds a comment line to the dialog.
This function allows you to add one additional comment line to this widget. Calling this function after a comment has already been added will not have any effect.
- Parameters
-
Definition at line 217 of file kpassworddialog.cpp.
- Returns
- anonymous mode has been selected.
- Since
- 4.1
Definition at line 202 of file kpassworddialog.cpp.
Returns the button box used in the dialog.
This can be used to add new buttons.
- Returns
- the button box
- Since
- 5.0
Definition at line 414 of file kpassworddialog.cpp.
Virtual function that can be overridden to provide password checking in derived classes.
It should return
true if the password is valid,
false otherwise.
Definition at line 409 of file kpassworddialog.cpp.
Returns the domain entered by the user.
- Returns
- the domain name
- Since
- 4.1
Definition at line 183 of file kpassworddialog.cpp.
emitted when the dialog has been accepted
- Parameters
-
emitted when the dialog has been accepted, and ShowUsernameLine was set on the constructor
- Parameters
-
Returns the icon that appears next to the prompt.
Definition at line 138 of file kpassworddialog.cpp. 212 of file kpassworddialog.cpp.
Returns the password entered by the user.
- Returns
- the password
Definition at line 173 of file kpassworddialog.cpp.
- Deprecated:
- since 5.63 use icon()
Definition at line 149 of file kpassworddialog.cpp.
Returns the prompt.
Definition at line 306 of file kpassworddialog.cpp.
set anonymous mode (all other fields will be grayed out)
- Since
- 4.1
Definition at line 188 of file kpassworddialog.cpp.
set the default domain.
- Since
- 4.1
Definition at line 178 of file kpassworddialog.cpp.
Set the icon that appears next to the prompt.
- Since
- 5.63
Definition at line 128 207 325 of file kpassworddialog.cpp.
Presets the password.
If the password is not empty, the ability to show the password will not be available.
- Parameters
-
Definition at line 311 of file kpassworddialog.cpp.
set an image that appears next to the prompt.
- Deprecated:
- since 5.63 use setIcon()
Definition at line 144 of file kpassworddialog.cpp.
Sets the prompt to show to the user.
- Parameters
-
Definition at line 298 of file kpassworddialog.cpp.
set the default username.
Definition at line 155 of file kpassworddialog.cpp.
Sets the username field read-only and sets the focus to the password field.
this can also be set by passing UsernameReadOnly as flag in the constructor
- Parameters
-
Definition at line 316 of file kpassworddialog.cpp.
Shows an error message in the dialog box.
Prevents having to show a dialog-on-a-dialog.
- Parameters
-
Definition at line 260 of file kpassworddialog.cpp.
Returns the username entered by the user.
- Returns
- the user name
Definition at line 168 of file kpassworddialog.cpp.
The documentation for this class was generated from the following files:
Documentation copyright © 1996-2020 The KDE developers.
Generated on Sun Feb 16 2020 04:56:33 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online.
|
https://api.kde.org/frameworks/kwidgetsaddons/html/classKPasswordDialog.html
|
CC-MAIN-2020-10
|
refinedweb
| 607
| 53.37
|
Drop down menu trobleshootingrossco2009 Sep 7, 2012 2:59 AM
Hi
I'm stuck with this code for a drop down menu. The error message says It's expecting a right brace before the end of the program but as far as I can tell there's already one there... Any ideas are welcome!
import flash.events.Event;
import flash.display.SimpleButton;
addEventListener (Event.ENTER_FRAME,dropmenu1);
pages.stop();
var speed:Number=.3;
function dropmenu1(e:Event) {
if ((menu_1.mouseY<menu_1.height&&menu_1.mouseY>0) && (menu_1.mouseX<menu_1.width&&menu_1.mouseX>0)) {
menu_1.y-=(menu_1.y) *speed;
} else {
menu_1.y-=(55+menu_1.y) *speed;
}
function makebtn (btn:SimpleButton,frame:Number) {
btn.addEventListener (MouseEvent.CLICK,function() {pages.gotoAndStop (frame);});
}
makebtn (menu_1.CAT_strategy_btn,1);
makebtn (menu_1.stage_1_btn,2);
makebtn (menu_1.stage_2_btn,3);
1. Re: Drop down menu trobleshootingNed Murphy Sep 7, 2012 4:15 AM (in response to rossco2009)
Your first function is missing its ending brace
2. Re: Drop down menu trobleshootingrossco2009 Sep 7, 2012 6:45 AM (in response to Ned Murphy)
Hi Ned. That works a treat, thank you for your help. Now the problem I'm having is that the drop down menu appears from the top of the frame. I have a header at the top so the buttons need to drop down a bit further down the screen.
menu_1.y-=(55+menu_1.y) *speed;
This code means that only the bottom button is visible and when I hover over it the rest drop into view. What I want is the same effect but just further down the screen (from 110 on the y axis to be exact.
3. Re: Drop down menu trobleshootingNed Murphy Sep 7, 2012 7:01 AM (in response to rossco2009)
I don't really understand your new problem, but if you need to have something be further down the screen, move it there. If that code is resposible for the placement, then adjust the values in it. If the conditional code that surrounds it dictates when different actions are taken, then adjusting the conditions might help as well.
4. Re: Drop down menu trobleshootingrossco2009 Sep 7, 2012 7:31 AM (in response to Ned Murphy)
Sorted it now. Thanks for your help.
5. Re: Drop down menu trobleshootingNed Murphy Sep 7, 2012 7:41 AM (in response to rossco2009)
You're welcome
|
https://forums.adobe.com/message/4680687?tstart=0
|
CC-MAIN-2017-04
|
refinedweb
| 389
| 75
|
Opened 2 years ago
Closed 12 months ago
Last modified 11 months ago
#30446 closed Cleanup/optimization (fixed)
Automatically resolve Value's output_field for stdlib types.
Description
Hi,
I have a model of AModel. AModel has a SearchVectorField named search_vector. I want to update this vector by indexing a string that is not in any other field.
from django.db.models import Value from django.contrib.postgres.search import SearchVector AModel.objects.filter(pk=1).update(search_vector=SearchVector(Value("a string to be indexed and inserted to search_vector field")))
This code generates this error:
FieldError: Cannot resolve expression type, unknown output_field
It seemed to be a bug since I found similar usages in forums..
Change History (16)
comment:1 Changed 2 years ago by
comment:2 Changed 2 years ago by
comment:3 Changed 2 years ago by
comment:4 Changed 2 years ago by
comment:5 Changed 2 years ago by
comment:6 Changed 23 months ago by
In case it hasn't already been noted - the example above did previously work in 2.2, and the error is a regression in 2.2.1, specifically this commit: . As such, I think this might justify being upgraded to a bug.
(FWIW, we encountered this independently here:)
Specifying an explicit
output_fieldfor
Valueshould resolve your issue.
I guess
Value._resolve_output_fieldcould be made smarter for some stdlib types such as
str,
float,
int,
Decimal,
date,
datetimeso I'm tentatively accepting on this basis.
|
https://code.djangoproject.com/ticket/30446
|
CC-MAIN-2021-31
|
refinedweb
| 241
| 56.05
|
Back in October 1, 2012 when Microsoft Technical Fellow Ander Hejlsberg introduced TypeScript, we had taken a quick look at what is TypeScript and how we could build an MVC 4 template for TypeScript. [That was TypeScript v0.8.x.]
In //BUILD 2013 Anders presented the latest updates to TypeScript as v 0.9.0. Between October 2012 and the present, TypeScript has made steady progress and now includes advanced constructs like Generics and lambda expressions and so on. There has been improvement in the Tooling support as well. Best part has been the community engagement and uptick in TypeScript definition support for majority of JS libraries and frameworks. There is now a Github project called DefinitelyTyped that is maintaining most Type annotations for TypeScript.
So today, we will explore what is takes to use Knockout JS in an app that Uses TypeScript for development of the client side in an ASP.NET MVC 4 application. We will also take a look at the latest tooling support for TypeScript.
TypeScript’s tooling support comes in form of an out-of-band extension to Visual Studio that can be downloaded from. The binary, which was at v0.9.1.1 at the time of writing, is approximately a 12 MB in (download) size.
Once downloaded, close Visual Studio and run the installer. In my case, I ran it on Visual Studio 2013 Preview but the installer works for VS 2012 as well.
The installation takes a minute or so to complete, once done, you are good to get started with TypeScript.
Unlike previous tooling, there are no MVC project templates created for TypeScript. The TypeScript installer only installs the ‘HTML Application with TypeScript” project template.”
While we can use the above for demoing TypeScript’s capabilities, we want to see a slightly more practical use for it and that is in an ASP.NET MVC Application.
Turns out you don’t have to do anything special to include TypeScript in ASP.NET MVC. You start off with the ASP.NET Web Application Project Type.
Next I have selected the MVC template to bring in the nice BootStrap styling etc.
Once the code generation completes, we select the Scripts folder, right click on it and select New Item. In the search window, we type in ‘TypeScript’ to eke out the TypeScript File item and add ‘typescript-list.ts’ file to the project.
Once you click Add, Visual Studio pops up the following dialog for your convenience
This essentially means it has added the build commands required to build .ts files into .js at compile time and if you click Yes, it springs up the Nuget Package Manager dialog.
This is filtered by the tag:typescript thus giving you a list of already available TypeScript definition files. Of the given list, I added jQuery, Knockout, BootStrap and Knockout.Mapping definitions.
Once you click on Close, you’ll end up with a Folder structure for Script as follows
The typings folder has one sub-folder for each library that contains the .ds file for the library’s type definition encapsulated.
Finally we install KnockoutJS using Nuget Package Management Console
PM> install-package knockoutjs
With this, we are all set with the required dependencies, let’s now start with our application.
Note: Installing the Type Definitions does not install the original library. For example installing definitions for KnockoutJS didn’t actually install KO. We had to do that separately.
We will start with an easy target that is to create a Task listing app in TypeScript. To make things even simpler, we’ll implement the List or Index page only for the moment and pass some hardcoded values from the controller.
In the Models folder, we add a Task class with the following definition:
public class TaskDetails{public int Id { get; set; }public string Title { get; set; }public string Details { get; set; }public DateTime Starts { get; set; }public DateTime Ends { get; set; }}
Build the application.
To add a View for the Tasks, we right click on the Views\Home folder and select Scaffold. From the available scaffolding options, we select ‘MVC 5 View – List’ as shown below. This generates the markup for a tabular UI.
In the options of adding the view, we select the Model Class and mark it as a partial view.
Once we click Add, a strongly typed view is scaffolded for us.
Next we add an Action method that returns some dummy data for us:
public ActionResult Tasks(){List<TaskDetails> tasks = new List<TaskDetails>();for (int i = 0; i < 10; i++){ TaskDetails newTask = new TaskDetails { Id = i, Title = "Task " + (i + 1), Details = "Task Details " + (i + 1), Starts = DateTime.Now, Ends = DateTime.Now.AddDays(i + 1) }; tasks.Add(newTask);}return View(tasks);}
As we can see above, the code return 10 Tasks with some sample data generated on the fly. Running the app and navigating to the /Home/Tasks view, we get the following:
This is our Tasks view rendered on the server side. Lets see what it takes to render it on the client side by building our ViewModel out in TypeScript.
In the Tasks.cshtml file, add the following snippet at the bottom of the page
@section Scripts{<script src="~/Scripts/knockout-2.3.0.js"></script><script src="~/Scripts/typescript-list.js"></script>}
The first script reference adds KnockoutJS to our project. But the second dependency is actually pointing to a JS file that doesn’t really exist. Actually we have typescript-list.ts file instead. Well, the Build task that got added to our Project when we added the first TypeScript file, will ensure that there is a corresponding JS file after a successful build.
Just for confirmation, if you run the application again and navigate to /Home/Tasks; in Visual Studio’s Solution explorer you’ll see a folder structure like the following (note the ts file linked to the generated js file).
With our dependencies in place, lets write our first bit of TypeScript.
First thing to do is reference jQuery and Knockout’s definitions. The syntax for that is as follows:
///<reference path="typings/jquery/jquery.d.ts" />///<reference path="typings/knockout/knockout.d.ts" />
Next we create a Class called Task Details and declare the properties of the requisite types
class TaskDetails { id: KnockoutObservable<number>; title: KnockoutObservable<string>; details: KnockoutObservable<string>; starts: KnockoutObservable<string>; ends: KnockoutObservable<string>;// … more to come}
As we can see, we have declared each property as KnockoutObservable with their respective types. The KnockoutObservable<T> generic Type definition is provided via the knockout.d.ts Type description file. Key thing to note here is that we have only defined the variables NOT instantiated them.
To instantiate them, we use the constructor function as per TypeScript syntax as follows:
class TaskDetails{// … variable declarations
constructor(id: number, title: string, details: string, starts: string, ends: string) { this.id = ko.observable(id); this.title = ko.observable(title); this.details = ko.observable(details); this.starts = ko.observable(starts); this.ends = ko.observable(ends);}}
Note, while instantiating the properties, we are using base KO types here with values passed in to the constructor. Now our View Model contains an array of TaskDetails, so lets setup the ViewModel class.
class TaskViewModel {public tasks: KnockoutObservableArray<TaskDetails>; constructor() { this.tasks = ko.observableArray([]);}}
We have declared a TaskViewModel class with one public property task. The type for the property is a KnockoutObservableArray<TaskDetails> that we instantiate in the constructor. Notice how the tasks list is strongly typed so if we try to shove in any random object like we can in JavaScript, we’ll get compile time errors.
Traditionally I’ve used an MVC Action Result to return an Empty View and then do an AJAX GET once the document is loaded. This gives us options to load banners, progress bars etc if required. Today I’ll take a different approach and stuff the JSON serialized model data in a Hidden Input field. Then, once the document is loaded, I’ll retrieve it and build a view Model out of it.
To save the data in Hidden Input field, we add the following markup in the Tasks.cshtml
<input type="hidden" id="serverJSON" value="@Newtonsoft.Json.JsonConvert.SerializeObject(Model)" />
The reason why this works is, as we know, all Razor syntax is evaluated on the server. So the Server uses Newtonsoft Json to serialize the entire Model into JSON and stick it in the Hidden Input field. This method apparently saves one round trip, but if your ViewModel is large, it can result in a rather large page size for initial load.
Now that the data is with us, let’s see how we can use it.
- We first create a serverData object of type any[]. Declaring it as an array gives us minimum Intellisense.
- Next we use the native JSON.parse to convert the string in the serverJSON field to a JS object array. This is the only ‘weakly typed’ object that we have in our TypeScript code. If we were to use Knockout Mapping we could have skipped this step, but we’ll get to KO Mapping another day.
- Next we declare a local variable vm of type TaskViewModel and instantiate it.
- The for loop essentially loops through the data we got from the server and creates strongly typed TaskDetails objects and adds them to the vm.tasks observable array.
- Once the View Model is ready, we use ko.applyBindings to assign the ViewModel to the View.
The complete TypeScript source for this is as follows:
$(document).ready(function () {var serverData: any[];serverData = JSON.parse($("#serverJSON").val());var vm: TaskViewModel;vm = new TaskViewModel();var i: number; for (i = 0; i < serverData.length; i++) { var serverTask: any; serverTask = serverData[i]; vm.tasks.push(new TaskDetails(serverTask.Id, serverTask.Title, serverTask.Details, serverTask.Starts, serverTask.Ends));}ko.applyBindings(vm);});
It is worth stressing here that if we were to try and push any object into the vm.tasks array, we would get an Error as follows:
We remove the entire server side markup and replace it with the following:
<table class="table"><tr> <th>Title</th> <th>Details</th> <th>Starts</th> <th>Ends</th> <th></th></tr><tbody data- <tr> <td data-</td> <td data-</td> <td data-</td> <td data-</td> <td></td> </tr></tbody></table>
This is standard KO binding and there is nothing new to it. If we run the application again now, we should get the following view at /Home/Tasks
Our dates look a little ugly because of the default date to string conversion. We can clean that up with help of moment.js. (On a side note, read about Using jQuery and Moment.js in ASP.NET MVC to do Custom Unobtrusive Date Comparison and Validation).
So we add the Moment JS using Nuget. Note we could potentially add Moment’s TypeScript definitions as well, if we were going to do more complex operations. Since we are going to use it for formatting only, I’ll use Moment directly.
Back in the TaskDetails class, we update the constructor to use Moment as follows:
constructor(id: number, title: string, details: string,starts: string, ends: string) {this.id = ko.observable(id);this.title = ko.observable(title);this.details = ko.observable(details);this.starts = ko.observable(moment(starts).format("MMM DD, YYYY h:mm:ss a"));this.ends = ko.observable(moment(ends).format("MMM DD, YYYY h:mm:ss a"));}
Now if we run the application, we’ll see our view comes up nicely:
Before we can conclude the article, let’s see what was the JavaScript that our TypeScript code compiled down to:
At runtime we opened the typescript-list.js file and we got the script above. As we can see, this is very close to what we would have written if we were writing the ViewModel ourselves. However I must admit it was much easier to think in terms of a ‘TaskDetails’ entity class and a ‘TaskViewModel’ especially if you are coming from a statically typed language like C# or Java to a more dynamic language like JavaScript. TypeScript provides a nice and easy bridge.
To conclude, we saw the following features of TypeScript in action
- Statically typed Classes
- Generic types
- Typed properties
- Knockout’s TypeScript descriptions
The key reasons for using TypeScript is that it offers better structuring of code while building large-scale JavaScript applications. I must admit that it was easier for me to think in terms of classes than functions which resulted in a clean implementation straight off the bat. However we have barely scratched the surface of TypeScript. In future we’ll look at building much larger applications using TypeScript and leverage more language features like Lambda expressions, Modules etc.
Download the entire source code of this article (Github)
|
http://www.dotnetcurry.com/showarticle.aspx?ID=939
|
CC-MAIN-2014-52
|
refinedweb
| 2,130
| 63.9
|
Dear Arduino forum,
I am trying to interface my arduino uno with a Trackpad that I scrapped from a broken Medion Erazer laptop. The Chip on it is a Elan 33200V-3600. I just want to read the PS/2 data with the arduino and display it. A large metal plate is glued to the back of the Trackpad and only two cutouts are accessible. I use the contacts to get my data as in the following image (I also labelled all connections to the official connector, but I soldered to the copper pads directly):
I do this because I found the following image online, where they use the same chip (it is on a different trackpad; but even the pads look very similar)
I now use the following code to read the PS/2 Mouse Data
#include <PS2Mouse.h> #define MDATA 5 // touchpad ps/2 data pin #define MCLK 6 // touchpad ps/2 clock pin PS2Mouse mouse_one(MCLK, MDATA); void setup() { Serial.begin(9600); mouse_one.initialize(); } void loop() { int16_t data[3]; mouse_one.report(data); Serial.print(data[0]); // Status Byte Serial.print(":"); Serial.print(data[1]); // X Movement Data Serial.print(","); Serial.print(data[2]); // Y Movement Data Serial.println(); }
This kind of works, I get the outputs:
8:0,0 which means
data[0] = 8 // Status Byte
data[1] = 0 // X movement
data[2] = 0 // Y movement
When I compare this to the PS/2 protocol I see that the Status Byte has a fixed 1 bit at the position such that you get a value of 8 if all other bits are 0. This means it is working somehow, as when I try different pins for CLK or DATA, there will be no readings at all. However the values do not change if I touch the trackpad and move my finger - everything stays zero.
Do you have an idea what I could be doing wrong? Thanks for your help!
Best wishes,
Simon
|
https://forum.arduino.cc/t/ps-2-interfacing-with-elan-33200v-3600-trackpad/681591
|
CC-MAIN-2022-27
|
refinedweb
| 325
| 69.72
|
Controlling LED Using Nodemcu From Firebase
Hi everyone, in this tutorial we are going to learn on how to control an LED attached to Nodemcu pin by using Google Firebase. This project enable us to control the LED from anywhere around the world as long as there is internet connection for this project to run. Actually there are numerous of IOT platform clouds to achieve the goal of this project but we will be using Google Firebase console specifically for this project.
Firebase is Google’s database platform which is used to create, manage and modify data generated from any android application, web services, sensors etc. For more information on Firebase please visit the official website of Google Firebase.
Setting Up NodeMCU ESP8266 Wi-Fi Module
This step is very simple and does not require much time. All you need to do is setting up the connection as follows.
If this is your first time using Nodemcu, please refer to this link to install Nodemcu board into Arduino IDE Software.
Programming NodeMCU ESP8266 to Connect to Google Firebase
This project needs 2 library files which can be downloaded from these links below.
The complete code for this project will be given at the end of this tutorial. Here we are explaining few important parts of the code. Firstly include the libraries for using ESP8266 and Firebase library.
#include <ESP8266WiFi.h #include <FirebaseArduino.h
Secondly, these two parameters are very important to communicate with firebase. Setting these parameters will enable the data exchange between and ESP8266 and firebase. To find these parameters please refer to next part of this tutorial.
#define FIREBASE_HOST "your-project.firebaseio.com"// the project name address from firebase id #define FIREBASE_AUTH "06dEpqanFg***************qAwnQLwLI"// the secret key generated from firebase
Next, these parameters are used to connect to your home Wi-Fi network or the network that you setup. Replace SSID and password with your network SSID and password. Make sure you have internet connection in order to communicate with firebase.
#define WIFI_SSID "xxxxxxxxxxxxx"// input your home or public wifi name #define WIFI_PASSWORD "xxxxxxxxxxxxxx" //password of wifi ssid
Setting Up Firebase Console
1- Go to and register your account. After completing the registration, click ‘Add Project‘.
2- Name your project and click ‘Create Project‘.
3- After creating the project, go to Project Setting>Service Account>Database Secrets and copy the database secret and keep it for later use.
4- Go to Database tab and click Create Database and make sure the database to be in test mode
5- Once the database created, copy the database link as shown in the picture below and keep the link
6- Now you already have the secret code and the database link to connect your project to Firebase server. Paste both of the parameter into the code of this project. Refer to the picture below
The Code
/* Controlling LED using Firebase console by zentronic */ #include <ESP8266WiFi.h> // esp8266 library #include <FirebaseArduino.h> // firebase library #define FIREBASE_HOST "led-control-c6d7c.firebaseio.com" // the project name address from firebase id #define FIREBASE_AUTH "0HTxkP7OdCBJH0jOVHsO2txcVTPGcKiOXXW09qKM" // the secret key generated from firebase #define WIFI_SSID "Rumah_Saya@unifi" // input your home or public wifi name #define WIFI_PASSWORD "1a2b3c4d5e" //password of wifi ssid String fireStatus = ""; // led status received from firebase int led = D3; // for external led void setup() { Serial.begin(9600); delay(1000); pinMode(LED_BUILTIN, OUTPUT); pinMode(led, OUTPUT); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //try to connect with wifi Serial.print("Connecting to "); Serial.print(WIFI_SSID); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("Connected to "); Serial.println(WIFI_SSID); Serial.print("IP Address is : "); Serial.println(WiFi.localIP()); //print local IP address Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); // connect to firebase Firebase.setString("LED_STATUS", "OFF"); //send initial string of led status } void loop() { fireStatus = Firebase.getString("LED_STATUS"); // get ld status input from firebase if (fireStatus == "ON") { // compare the input of led status received from firebase Serial.println("Led Turned ON"); digitalWrite(LED_BUILTIN, LOW); // make bultin led ON digitalWrite(led, HIGH); // make external led ON } else if (fireStatus == "OFF") { // compare the input of led status received from firebase Serial.println("Led Turned OFF"); digitalWrite(LED_BUILTIN, HIGH); // make bultin led OFF digitalWrite(led, LOW); // make external led OFF } else { Serial.println("Wrong Credential! Please send ON/OFF"); } }
After uploading the code into Nodemcu board, open the database and look at the ‘Led_Status‘ String inside the database. If you can’t notice the string, press the reset button on the Nodemcu. Now you can control the led by changing the string to ON or OFF.
|
http://zentronic.com.my/controlling-led-using-nodemcu-from-firebase/
|
CC-MAIN-2020-05
|
refinedweb
| 753
| 55.84
|
Closed Bug 1143011 Opened 5 years ago Closed 5 years ago
Set take & add are no longer symmetric .
Categories
(Core :: JavaScript Engine: JIT, defect)
Tracking
()
mozilla39
People
(Reporter: nbp, Assigned: nbp)
References
Details
Attachments
(2 files, 5 obsolete files)
Currently, take, does not filter out all aliased registers. takeAny, filters out all aliased registers. add, asserts that all alises can be added back into the register set. For sanity reason we should remove the aliased registers when we take a register out of a register set, but this might cause issues with the register allocator.
Not asking for review yet, I want to see if I can remove some of the function which are already used.
[Tracking Requested - why for this release]: The fuzzers keep finding this.....
tracking-firefox39: --- → ?
Comment on attachment 8577465 [details] [diff] [review] Registerset::{take,add} are now considering aliased registers too. Review of attachment 8577465 [details] [diff] [review]: ----------------------------------------------------------------- ::: js/src/jsapi-tests/moz.build @@ +94,5 @@ > 'testJitGVN.cpp', > 'testJitMoveEmitterCycles-mips.cpp', > 'testJitMoveEmitterCycles.cpp', > 'testJitRangeAnalysis.cpp', > + 'testJitRegisterSet.cpp', missing file in the patch
(In reply to Benjamin Bouvier [:bbouvier] from comment #3) > ::: js/src/jsapi-tests/moz.build > > + 'testJitRegisterSet.cpp', > > missing file in the patch This is a test case, you can just remove this line :) I am working on a larger patch (unfortunately) where we would no longer be able to have such issues. Register sets are used for 2 different use cases, and the methods of the TypedRegisterSet badly reflect this fact. I first thought of replacing all add/take by more verbose variants such as hasRegisterIndex and hasAllocatable, but I figured that we in fact want to have consistent uses of these method over time, i-e that we always use the same variant of has/add/take on one register set. The approach that I am taking with the clean-up patch is to provide the has/add/take accessors based on how the register set is used. Basically we have 2 use cases: When we allocate, and when we remember what got allocated. The first use case should consider aliases — as aliases are no longer available once they are allocated, while the second use cases should only consider register indexes — as we have allocated a register with only one type, and not its aliases.
Attachment #8577465 - Attachment is obsolete: true
Attachment #8579346 - Flags: feedback?(jdemooij)
Comment on attachment 8579346 [details] [diff] [review] (WIP) Extract the has/add/take logic out of the register sets to distinguish between an allocator pool and a live set. Review of attachment 8579346 [details] [diff] [review]: ----------------------------------------------------------------- I think splitting these cases makes sense. I didn't check all the template magic but some comments: - It looks like alignedOrDominatedAliasedSet is the same as (or similar to) aliasedSet? I think aliasedSet is clearer... - s/Allocator/AllocatedSet/ so that it sounds more similar to LiveSet. - LiveSet<GeneralRegisterSet> and AllocatedSet<GeneralRegisterSet> are a bit long and repetitive. Maybe we could add typedefs: LiveGeneralRegisterSet, AllocatedGeneralRegisterSet?
Attachment #8579346 - Flags: feedback?(jdemooij) → feedback+
(In reply to Jan de Mooij [:jandem] from comment #7) > I think splitting these cases makes sense. I didn't check all the template > magic but some comments: > > - It looks like alignedOrDominatedAliasedSet is the same as (or similar to) > aliasedSet? I think aliasedSet is clearer... Unfortunately no, the difference is subtle but it can be seen on ARM: s0 alias s0 | d0. s1 alias s1 | d0. d0 alias s0 | s1 | d0. s0 "is aligned with / dominates" s0 | d0. s1 "is aligned with / dominates" s1. d0 "is aligned with / dominates" s0 | s1 | d0. The later is better, as it does not imply adding additional logic to masking logic when we are taking / adding a register from/to the allocator set. Note that with the later we have the relation alignedOrDominate(d0) == alignedOrDominate(s0) | alignedOrDominate(s1) alignedOrDominate(d0) == alignedOrDominate(s0) ^ alignedOrDominate(s1) which ensures that we can do: Allocator<RegisterSet> pool; pool.add(s0); pool.add(s1); pool.take(d0); without adding special conditions to the take / add functions. By the way, the aliasedSet is nice, but it is no longer used :( > - s/Allocator/AllocatedSet/ so that it sounds more similar to LiveSet. I prefer AllocatorSet over AllocatedSet, as the later implies that the registers which are in the set are already allocated, while this is the opposite. Any register listed in an AllocatorSet is allocatable, and thus not allocated yet. > - LiveSet<GeneralRegisterSet> and AllocatedSet<GeneralRegisterSet> are a bit > long and repetitive. Maybe we could add typedefs: LiveGeneralRegisterSet, > AllocatedGeneralRegisterSet? Sounds good, I will do that :)
The latest patches are only rebased on top of the lastets version of mozilla-central, they do not address any of the comment of the previous feedback.
So far I am unsuccesfull at getting these patches to work with gcc 4.7.2 & gcc 4.7.3 (internal compiler error) that we are using for the Linux slaves on treeherder. I will dig in to see if I can work-around this problem.
Delta: - Apply feedback (rename classes) - Simplify the template magic to avoid template of templates. - Add special case to support gcc 4.7.3 which is used by taskcluster. (even if it appears under the 4.7.2 directory) Note: I am currently compiling gcc 4.7.4 to check if it is affected by this issue on constrexpr of LiveRegisterSet. - Accessor clases are not providing unchecked versions first, and the checks are added after to avoid extra complexity in the AllocatorSetAccessor and LiveSetAccessor classes.
Attachment #8579417 - Attachment is obsolete: true
Attachment #8580140 - Flags: review?(jdemooij)
Comment on attachment 8580140 [details] [diff] [review] Extract the has/add/take logic out of the register sets to distinguish between an allocator pool and a live set. Review of attachment 8580140 [details] [diff] [review]: ----------------------------------------------------------------- ::: mfbt/Attributes.h @@ +95,5 @@ > # define MOZ_HAVE_CXX11_FINAL final > # endif > +# define MOZ_HAVE_CXX11_CONSTEXPR > +# if MOZ_GCC_VERSION_AT_LEAST(4, 7, 4) > +# define MOZ_HAVE_CXX11_CONSTEXPR_IN_TEMPLATES I just checked with 4.7.4, and I can still reproduce the issue, I will bump this value to 4.8.0 and report a bug.
Comment on attachment 8580140 [details] [diff] [review] Extract the has/add/take logic out of the register sets to distinguish between an allocator pool and a live set. Review of attachment 8580140 [details] [diff] [review]: ----------------------------------------------------------------- Some heavy template magic here. The approach makes sense though, I agree this distinction is safer and the way to go. Also nice comments. Requesting review from Waldo for the mfbt/* changes, I don't feel comfortable stamping those. ::: js/src/jit/RegisterSets.h @@ +472,5 @@ > static inline RegisterSet Volatile() { > return RegisterSet(GeneralRegisterSet::Volatile(), FloatRegisterSet::Volatile()); > } > + > + Nit: remove one of these empty lines. @@ +501,5 @@ > + > +}; > + > +// > +// Register sets are used for 2 usage: Nit: "usages", but with "used" it sounds a bit unusual, maybe rephrase as: There are 2 use cases for register sets: @@ +503,5 @@ > + > +// > +// Register sets are used for 2 usage: > +// > +// 1. To serve as a pool of allocatable register. This is useful for working What would you think of calling it AllocatableRegisterSet instead of AllocatorRegisterSet? Allocator is a little confusing, because people may think it means "the result of the register allocator", but *that* is a LiveRegisterSet... @@ +517,5 @@ > +// RegisterSet (for both). These classes are used to store the bit sets to > +// represent each register. > +// > +// Each use case defines an Accessor class, such as AllocatorSetAccessor or > +// LiveSetAccessor, which is parametrized with the type of the register Nit: parameterized @@ +524,5 @@ > +// > +// The RegSetCommonInterface class is used to wrap the accessors with convenient > +// shortcuts which are based on the accessors. > +// > +// Then, to avoid to many level of complexity while using these interfaces, Nit: levels @@ +542,5 @@ > +class LiveSet; > + > +// > +// Base accessors classes have the minimal set of raw methods to manipulate the register set > +// given as parameter in a consistent manner. These methods are: , |addUnchecked|, and Nit: add "has" between ":" and ","? Or just "These methods are:", because we list them below too. @@ +547,5 @@ > +// |takeUnchecked|. > +// > +// - has: Returns if all the bits needed to take a register are present. > +// > +// - takeUnchecked: Substracts the bits used to represent the register in the Nit: Subtracts @@ +558,5 @@ > +// > +// The AllocatorSet accessors are used to make a pool of unused registers. Taking > +// or adding registers should consider the aliasing rules of the architecture. > +// For example, on ARM, we would have the following pieces of code should work > +// fine, knowing that the double register |d0| is composed of float registers Nit: "on ARM, the following piece of code should work fine," Nice explanations btw. @@ +568,5 @@ > +// // d0 is now available. > +// regs.take(d0); > +// > +// These accessors are useful for allocating registers within the function used > +// to generate stubs, such as Trampoline, Inline caches (BaselineIC, IonCache). Nit: functions, trampolines @@ +641,5 @@ > + > + > +// > +// The LiveSet accessors are used to collect a list of allocated > +// registers. Taking or adding a register should *not* consider the alises, as Nit: aliases @@ +732,5 @@ > + explicit MOZ_CONSTEXPR REGSET(SetType set) : Parent(set) {} \ > + explicit MOZ_CONSTEXPR REGSET(RegSet set) : Parent(set) {} > + > +// > +// This class add checked accessors on top of the unchecked variants defined by Nit: adds Also I'd remove the "//" lines before and after each comment, I don't think we do that anywhere else. @@ +928,5 @@ > +}; > + > + > +// > +// Interface which is common to all register sets implementations. It overloads Nit: register set implementations @@ +1009,5 @@ > > + > +// > +// These classes do not provide any additional member, they only use they > +// constructor to forward to the common interface for all register sets. The Nit: members, their constructor
Attachment #8580140 - Flags: review?(jwalden+bmo)
Attachment #8580140 - Flags: review?(jdemooij)
Attachment #8580140 - Flags: review+?
Attachment #8580141 - Flags: review?(jdemooij) → review+
(In reply to Jan de Mooij [:jandem] from comment #17) >? I already verified with the ARM simulator both on try and locally. I will check with LSRA. > :::? RegisterSet are quite large, so using a reference instead of 2 words make sense. I think this would even make more sense on x86 architecture, but I guess I can make a follow-up bug for adding "const" to most of these functions.
(In reply to Nicolas B. Pierron [:nbp] from comment #18) > (In reply to Jan de Mooij [:jandem] from comment #17) > > Can you make sure all jit-tests still pass with --ion-regalloc=lsra and the > > ARM simulator? > > I already verified with the ARM simulator both on try and locally. > I will check with LSRA. Ok, this took a while to check locally, but I tried (most of) the join product of: - x64 / x86 / arm simulator. - compiled with gcc 4.7.2, gcc 4.8.2, clang. - debug and optimized builds. And I also verified that LSRA was working fine with x64-clang / arm-sim-gcc4.8 with debug builds. (rebase on top of mozilla-central) (Apply nits & rename Allocator to Allocatable)
Status: ASSIGNED → RESOLVED
Closed: 5 years ago
status-firefox39: --- → fixed
Resolution: --- → FIXED
Target Milestone: --- → mozilla39
This was backed out from Aurora39 due to bug 1149377.
status-firefox40: --- → fixed
Nicolas, it sounds like once the fix for bug 1149377 lands, you should request uplift for this to aurora.
Flags: needinfo?(nicolas.b.pierron)
Re-landed on Aurora.
Flags: needinfo?(nicolas.b.pierron)
|
https://bugzilla.mozilla.org/show_bug.cgi?id=1143011
|
CC-MAIN-2019-43
|
refinedweb
| 1,832
| 55.64
|
.classpath;20 21 import java.util.EventObject ;22 import java.util.Set ;23 24 /**25 * Event object giving details of a change in the path registry.26 */27 public final class GlobalPathRegistryEvent extends EventObject {28 29 private final String id;30 private final Set <ClassPath> changed;31 32 GlobalPathRegistryEvent(GlobalPathRegistry r, String id, Set <ClassPath> changed) {33 super(r);34 assert id != null;35 assert changed != null && !changed.isEmpty();36 this.id = id;37 this.changed = changed;38 }39 40 /**41 * Get the affected registry.42 * @return the registry43 */44 public GlobalPathRegistry getRegistry() {45 return (GlobalPathRegistry)getSource();46 }47 48 /**49 * Get the type of classpaths that were added or removed.50 * @return the type, e.g. {@link ClassPath#SOURCE}51 */52 public String getId() {53 return id;54 }55 56 /**57 * Get a set of classpaths that were added or removed.58 * @return an immutable and nonempty set of {@link ClassPath}s of the given type59 */60 public Set <ClassPath> getChangedPaths() {61 return changed;62 }63 64 }65
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/org/netbeans/api/java/classpath/GlobalPathRegistryEvent.java.htm
|
CC-MAIN-2017-30
|
refinedweb
| 184
| 66.84
|
However, it will work with some compilers and libraries, if some of the standard header files associated with that implementation happen to #include other standard header files. 07-14-2009 #3 Elysia View You’ll be auto redirected in 1 second. why isn't the interaction of the molecules with the walls of the container (in an ideal gas) assumed negligible? Tweet Most popular tags programming languages visual c++ compile time error messages programming-languages visual-c compile-time-error-messages java mysql dbms runtime-error-messages Photoshop oracle netbeans nudge photoshop mosek rasterize subversion php sql vector data check over here Learning resources Microsoft Virtual Academy Channel 9 MSDN Magazine Community Forums Blogs Codeplex Support Self support Programs BizSpark (for startups) Microsoft Imagine (for students) United States (English) Newsletter Privacy & cookies C++ Information Tutorials Reference Articles Forum Forum BeginnersWindows ProgrammingUNIX/Linux ProgrammingGeneral C++ ProgrammingLoungeJobs Home page | Privacy policy© cplusplus.com, 2000-2016 - All rights reserved - v3.1Spotted an error? One Very Odd Email Tax Free when leaving EU through the different country In a company crossing multiple timezones, is it rude to send a co-worker a work email in the
However, if you define one of these functions without a matching declaration in the class, the compiler detects a conflict.To fix this error, in the class declaration, declare each member function For a better animation of the solution from NDSolve "PermitRootLogin no" in sshd config doesn't prevent `su -` An easy calculus inequality that I can't prove Add-in salt to injury? more stack exchange communities company blog Stack Exchange Inbox Reputation and Badges sign up log in tour help Tour Start here for a quick overview of the site Help Center Detailed
Not the answer you're looking for? Powered by vBulletin Version 4.2.3 Copyright © 2016 vBulletin Solutions, Inc. RaspberryPi serial port Filtering a list by comparing enums against a user choice Can You Add a Multiple of a Matrix Row to itself? You’ll be auto redirected in 1 second.); // The compiler can generate default constructors and destructors (called special member functions) if none are declared in the class. Browse other questions tagged c++ class mobile constructor compiler-errors or ask your own question. The reason you get these errors is because you have never declared those constructors and destructors in the class declarations (as the error message happily tells you).
Outside of your DOS world, your header file is meaningless. 07-14-2009 #4 Aliaks View Profile View Forum Posts Registered User Join Date Jun 2009 Location Adeliade, AU Posts 128 I think Why is there no predicate in "in vino veritas"? And how is it going to affect C++ programming?3What does this error mean?30What does “Unexpected precompiled header error” mean?5What does “class” mean in a constructor?393What does “Could not find or load Think Ill scrap the old compiler its causing me some set backs What old compiler are you using?
Outside of your DOS world, your header file is meaningless. 07-14-2009 #6 Aliaks View Profile View Forum Posts Registered User Join Date Jun 2009 Location Adeliade, AU Posts 128 Yeah as Forum Today's Posts C and C++ FAQ Forum Actions Mark Forums Read Quick Links View Forum Leaders What's New? What does it mean? Not the answer you're looking for?
Why are password boxes always blanked out when other sensitive data isn't? Browse other questions tagged c++ or ask your own question. We appreciate your feedback. Thanks for your prompt response. –Pranesh Jun 12 '11 at 15:10 @Pranesh: No problem! –Lightness Races in Orbit Jun 12 '11 at 15:16 add a comment| up vote 3
RaspberryPi serial port Does The Amazing Lightspeed Horse work, RAW? Work done by gravity What's the name of this output connector of ac adaptor Greek letters do not function inside tabular even with dollar sign Short story about a human entering If you are at an office or shared network, you can ask the network administrator to run a scan across the network looking for misconfigured or infected devices. Yes No Additional feedback? 1500 characters remaining Submit Skip this Thank you!
Quick Navigation C++ Programming Top Site Areas Settings Private Messages Subscriptions Who's Online Search Forums Forums Home Forums General Programming Boards C++ Programming C Programming C# Programming Game Programming Networking/Device Communication Without that header explicitly included, algorithms like transform are not guaranteed to work. Hope this helps :) Oct 30, 2011 at 10:50pm UTC seawolfmoose (57) ok i get the point, but am unsure of the correct syntax, because i thought that that is what
If you are on a personal connection, like at home, you can run an anti-virus scan on your device to make sure it is not infected with malware. The implementation will implicitly define them if they are used, as specified in 12.1, 12.4 and 12.8. All rights reserved. I've used versions of gcc that predate Code::Blocks by well over a decade, and never seen it accept code like yours without complaint.
Dev centers Windows Office Visual Studio Microsoft Azure More... Think Ill scrap the old compiler its causing me some set backs 07-14-2009 #7 grumpy View Profile View Forum Posts Registered User Join Date Jun 2005 Posts 6,815 Originally Posted by I did include namespace but not algorithm. more hot questions question feed lang-cpp about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback Technology Life / Arts Culture / Recreation
By mishna_toreh in forum C Programming Replies: 3 Last Post: 05-13-2005, 08:32 AM Compilers for Windows By LegendsEnd in forum Windows Programming Replies: 2 Last Post: 03-26-2004, 08:03 AM Compilers, Compilers, This documentation is archived and is not being maintained. solved 5 years ago by errorbase (170,010 points) 0 votes Possible resolution: // compile with: /c class C { C::~C(); }; C::~C() {} solved 5 years ago by errorbase (170,010 points) Here is the error that I got in MSVC compiler: "error C2600: 'myclass::myclass' : cannot define a compiler-generated special member function (must be declared in the class first)" c++ share|improve this
The time now is 11:49 AM. Creating a game, from start to finish Recent additions How to create a shared library on Linux with GCC - December 30, 2011 Enum classes and nullptr in C++11 - Code::Blocks is an IDE which can be configured to support a number of compilers. You'll have to declare your own constructor in order to provide an implementation. [special] (2003 wording, 12/1) says: The default constructor (12.1), copy constructor and copy assignment operator (12.8), and destructor
Join them; it only takes a minute: Sign up error C2600: what does this means? Work done by gravity How to take sharper images indoors, scene with all objects in focus? Originally Posted by Salem You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much. Learning resources Microsoft Virtual Academy Channel 9 MSDN Magazine Community Forums Blogs Codeplex Support Self support Programs BizSpark (for startups) Microsoft Imagine (for students) United States (English) Newsletter Privacy & cookies
Last edited by Elysia; 07-14-2009 at 05:58 AM. Last edited by grumpy; 07-14-2009 at 05:52 AM. Search Engine Optimisation provided by DragonByte SEO v2.0.32 (Pro) - vBulletin Mods & Addons Copyright © 2016 DragonByte Technologies Ltd. 程序园 程序员的世界 首页 博客 栏目 教程 程序园 lz465350的专栏 error C2600: 'Point::Point' How exactly does VS compile?
The compiler can generate default constructors and destructors (called special member functions) if none are declared in the class. You may not define it yourself.
|
http://hiflytech.com/cannot-define/cannot-define-a-compiler-generated.html
|
CC-MAIN-2017-47
|
refinedweb
| 1,298
| 50.87
|
I just started out trying to make a simple card game as of last night.
My problem is on line 16 and 17 of the first file. I have successfully created the 52 objects with variables for the cards, and once created they are placed into a Vector (the deck). Just to test it worked I used the below code, but the name is underlined and I get the error
name cannot be resolved or is not a field.
Does anyone know why this may be? The objects are deffinately in the Vector, I just can't get to the variables they contain.
Thanks.
****head.java****head.javaCode:Object ob = (Object) Cards.deck.get(i); System.out.println(ob.name);
Cards.javaCards.javaPHP Code:
import javax.swing.JOptionPane;
public class ****head {
public ****head() {
int p = 0;
for (int i = 0; i < Cards.allCards.length; i++) {
p = p != 13 ? p : 0;
Cards card = new Cards();
card.name = Cards.allCards[i];
card.cardValue = p + 1;
card.imgPath = "images\\cards\\" + card.name + ".gif";
Cards.deck.add(card);
Object ob = (Object) Cards.deck.get(i);
System.out.println(ob.name);
p++;
}
}
public static void main(String[] args) {
****head sh = new ****head();
}
}
PHP Code:
import java.util.Vector;
public class Cards {
static String[] allCards = {
"A-Hearts", "2-Hearts", "3-Hearts", "4-Hearts", "5-Hearts",
"6-Hearts", "7-Hearts", "8-Hearts", "9-Hearts", "10-Hearts",
"J-Hearts", "Q-Hearts", "K-Hearts",
"A-Dimonds", "2-Dimonds", "3-Dimonds", "4-Dimonds", "5-Dimonds",
"6-Dimonds", "7-Dimonds", "8-Dimonds", "9-Dimonds", "10-Dimonds",
"J-Dimonds", "Q-Dimonds", "K-Dimonds",
"A-Clubs", "2-Clubs", "3-Clubs", "4-Clubs", "5-Clubs",
"6-Clubs", "7-Clubs", "8-Clubs", "9-Clubs", "10-Clubs",
"J-Clubs", "Q-Clubs", "K-Clubs",
"A-Spades", "2-Spades", "3-Spades", "4-Spades", "5-Spades",
"6-Spades", "7-Spades", "8-Spades", "9-Spades", "10-Spades",
"J-Spades", "Q-Spades", "K-Spades"
};
static String name;
static int cardValue;
static String imgPath;
static Vector <Object> deck = new Vector<Object>(allCards.length);
public Cards() { }
}
|
http://www.codingforums.com/java-and-jsp/258920-getting-object-vars-after-retrieval-vector.html?s=21a5ba546baba74940307968447c40e6
|
CC-MAIN-2016-30
|
refinedweb
| 333
| 57.16
|
Python Functions - def, *arg, **kwargs
The def create a function object and assigns it to a name. Its general format is:
def <name>(arg1, arg2,...,argN) <statement>
The statement block becomes the function's body. The def header line specifies a function name and the function bodies often contain a return statement:
def <name>(arg1, arg2,...,argN) return <value>
The notable thing here is that the function doesn't define a return datatype. Python functions do not specify the datatype of their return value. They don't even specify whether or not they return a value. Actually, however, every Python function returns a value if the function ever executes a return statement, and it will return that value. Otherwise, it will return None.
Everything in Python is a function, all functions return a value even if it is None, and all functions start with def.
Here are brief descriptions:
- def is an executable code.
Python functions are written with a new statement, the def. Unlike functions in compiled language def is an executable statement. Our function does not exist until Python reaches and runs the def. Actually, it's legal to nest def statements inside if statement, while loops, and even other defs. In general, def statements are coded in module files and are naturally run to generate functions when a module file is first imported.
- def creates an object and assigns it to a name.
When Python reaches and runs a def statement, it generates a new function object and assigns it to the function's name. As with all assignments, the function name becomes a reference to the function object. There's nothing magic about the name of a function. The function object can be assigned to other names, stored in a list, and so son. Functions objects may also have arbitrary user-defined attributes attached to them to record data.
- return sends a result object back to the caller.
When a function is called, the caller stops until the function finishes its work and returns control to the caller. Functions that compute a value send it back to the caller with a return statement. The returned value becomes the result of the function call.
The def is an executable statement. When it runs, it creates a new function object and assigns it to a name. Because it's a statement, a def can appear anywhere a statement can even nested in other statements:
# function.py def func(): print('func()') def func1(): print('func1') def func2(): print('func2') func2() func1() func()
Output should look like this:
$ python function.py func() func1 func2
Because function definition happens at runtime, there's nothing special about the function name. What's important is the object to which it refers:
>>> def func(): print('func()') def func1(): print('func1') def func2(): print('func2') func2() func1() >>> othername = func # Assign function object >>> othername() # Call func again func() func1 func2 >>> othername2 = func() # Call func one more time func() func1 func2
Here, the function was assigned to a different name and called through the new name. Functions are just object. They are recorded explicitly in memory at program execution time. In fact, besides calls, functions allow arbitrary attributes to be attached to record information for later use:
def func():... # Create function object func() # Call object func.attr = value # Attach attributes
Here, we typed the definition of a function, times, interactively. It returns the product of its two arguments:
>>> # Create and assign function >>> def times(x, y): # Create and assign function return x * y # Body executed when called >>> times(2, 5) # Arguments in parentheses 10
When Python reaches and runs this def, it creates a new function object that packages the function's code and assigns the object to the name times. After the def has run, we can call (run) the function as shown above. The times function's body is just a return statement that sends back the result as the value of the call. If we want to use it later we could instead assign it to a variable:
>>> x = times(365,5) >>> x 1825
Let's call the function again with different objects passed in:
>>> times('blah!', 4) 'blah!blah!blah!blah!'
That was possible because we never declared the types of variables , argument, or return values in Python. We can use times to either multiply numbers or repeat sequences. In other words, what our times function means depends on what we pass into it. This is core idea in Python and it is polymorphism.
Let's make a function that collects items held in common in two strings:
>>> def intersect(seq1, seq2): res = [] # Start empty for x in seq1: # Scan seq1 if x in seq2: # Common item? res.append(x) # Add to the end return res
The algorithm of the function is:
for every item in the first argument, if that item is also in the second argument, append the item to the result.
Now, let's call the intersect function:
>>>>>>> intersect(s1, s2) ['W', 'O', 'R', 'D']
We could have used a single list comprehension expression giving the same result:
>>> >>> [x for x in s1 if x in s2] ['W', 'O', 'R', 'D'] >>>
The function intersect is polymorphic. It works on arbitrary types as long as they support the expected object interface:
>>> >>> x = intersect([1, 2, 3],(1, 4)) # Mixed types >>> x [1] >>>
We passed in different types of objects: a list and a tuple. It's working because we don't have to specify the types of argument ahead of time. For intersect, this means that the first argument should support the for loop and the second has to support the in membership test. If we pass in objects that do not support these interfaces (e.g., numbers), Python will detect mismatch and raise an exception:
>>> >>> x = intersect(1, 4) Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> x = intersect(1, 4) File "<pyshell#22>", line 3, in intersect for x in seq1: # Scan seq1 TypeError: 'int' object is not iterable >>> </pyshell#22></module></pyshell#35>
The variable res inside intersect is what is called a local variable. It is visible only to code inside the function def and that exists only while the function runs. All names assigned inside a function are classified as local variables by default. They appear when the function is called and disappear when the function exits. The return statement at the end of intersect sends back the result object, but the name res goes away.
Here is the keyword example:
>>> def f(a, b, c): print(a, b, c) >>> f(1, 2, 3) 1 2 3 >>> f(c=3, b=2, a=1) 1 2 3 >>> f(1, c=3, b=2) 1 2 3
>>> def f(a, b=2, c=3): print(a, b, c) >>> f(1) 1 2 3 >>> f(10, 50) 10 50 3 >>> f(10, 70, 90) 10 70 90 >>> f(10, 200) 10 200 3
Table from Learning Python by Mark Lutz, 2009.
Putting *args and/or **kwargs as the last items in our function definition's argument list allows that function to accept an arbitrary number of anonymous and/or keyword arguments.
Those arguments are called Keyword Arguments. Actually, they are place holders for multiple arguments, and they are useful especially when we need to pass a different number of arguments each time we call the function.
We may want to use *args when we're not sure how many arguments might be passed to our function, i.e. it allows us to pass an arbitrary number of arguments to our function.
>>> def f(*args): print(args) >>> f() () >>> f(10) (10,) >>> f(10, 20, 30) (10, 20, 30)
When the f() is called, Python collects all the positional arguments into a new tuple and assigns the variable args to that tuple. Since it is a normal tuple object, it can be indexed:
>>> def print_all(*args): for x in enumerate(args): print x >>> print_all('A','b','b','a') (0, 'A') (1, 'b') (2, 'b') (3, 'a')
We can pass in lists for the args:
>>> def print_all(*args): ... for x in enumerate(args): ... print x ... >>> print_all([1,2,3],[4,5,6]) (0, [1, 2, 3]) (1, [4, 5, 6])
The ** is similar but it only works for keyword arguments. In other words, it collects them into a new dictionary. Actually, ** allows us to convert from keywords to dictionaries:
>>> def f(**kwargs): print(kwargs) >>> f() {} >>> f(a=10, b=20) {'a': 10, 'b': 20}
The keyword arguments is a special name=value syntax in function calls that specifies passing by name. It is often used to provide configuration options.
>>> def kwargs_function(**kwargs): for k,v in kwargs.items(): print (k,v) >>> kwargs_function(**{'uno':'one','dos':'two','tres':'three'}) ('dos', 'two') ('tres', 'three') ('uno', 'one') >>> >>> kwargs_function(dos='two', tres='three', uno='one') ('dos', 'two') ('tres', 'three') ('uno', 'one')
We can use the * or ** when we call a function. In other words, it unpacks a collection of arguments, rather than constructing a collection of arguments. In the following example, we pass five arguments to a function in a tuple and let Python unpack them into individual arguments:
>>> def f(a, b, c, d, e): print(a, b, c, d, e) >>> args = (10, 20) >>> args += (30, 40, 50)) >>> f(*args) 10 20 30 40 50
In the same way, the ** in a function call unpacks a dictionary of key/value pairs into separate keyword arguments:
>>> kwargs = {'a':10, 'b':20, 'c':30} >>> kwargs['d']=40 >>> kwargs['e']=50 >>> f(**kwargs) 10 20 30 40 50
Also, with various combinations:
>>> f(*(10, 20), **{'d':40, 'e':50, 'c':30}) 10 20 30 40 50 >>> f(10, *(20, 30), **{'d':40, 'e':50}) 10 20 30 40 50 >>> f(10, c = 30, *(20,), **{'d':40, 'e':50}) 10 20 30 40 50 >>> f(10, *(20,30), d=40, e=50) 10 20 30 40 50 >>> f(10, *(20,), c=30, **{'d':40, 'e':50}) 10 20 30 40 50
Let's test what we've learned so far:
def fnc(*args, **kwargs): print('{} {}'.format(args, kwargs)) print('fnc()') fnc() fnc(1,2,3) fnc(1,2,3,'flask') fnc(a=1, b=2, c=3) fnc(a=1, b=2, c=3, d='ansible') fnc(1, 2, 3, a=1, b=2, c=3) lst = [1,2,3] tpl = (4,5,6) dct = {'a':7, 'b':8, 'c':9} fnc(*lst, **dct) fnc(*tpl, **dct) fnc(1,2,*lst) fnc(1,2,*tpl) fnc('jupyter',**dct) fnc(arg='django',**dct) fnc(1,2,*tpl,q='bottle',**dct) print def fnc2(arg1, arg2, *args, **kwargs): print('{} {} {} {}'.format(arg1, arg2, args, kwargs)) print('fnc2()') #fnc2() # error fnc2(1,2) fnc2(1,2,3,'haystack') fnc2(arg1=1, arg2=2, c=3) fnc2(arg1=1, arg2=2, c=3, d='Spark') fnc2(1,2,3, a=1, b=2) fnc2(*lst, **dct) fnc2(*tpl, **dct) fnc2(1,2,*tpl) fnc2(1,*tpl,d='nltk') fnc2(1,2,*tpl,d='scikit')
Output:
fnc() () {} (1, 2, 3) {} (1, 2, 3, 'flask') {} () {'a': 1, 'c': 3, 'b': 2} () {'a': 1, 'c': 3, 'b': 2, 'd': 'ansible'} (1, 2, 3) {'a': 1, 'c': 3, 'b': 2} (1, 2, 3) {'a': 7, 'c': 9, 'b': 8} (4, 5, 6) {'a': 7, 'c': 9, 'b': 8} (1, 2, 1, 2, 3) {} (1, 2, 4, 5, 6) {} ('jupyter',) {'a': 7, 'c': 9, 'b': 8} () {'a': 7, 'c': 9, 'b': 8, 'arg': 'django'} (1, 2, 4, 5, 6) {'a': 7, 'q': 'bottle', 'c': 9, 'b': 8} fnc2() 1 2 () {} 1 2 (3, 'haystack') {} 1 2 () {'c': 3} 1 2 () {'c': 3, 'd': 'Spark'} 1 2 (3,) {'a': 1, 'b': 2} 1 2 (3,) {'a': 7, 'c': 9, 'b': 8} 4 5 (6,) {'a': 7, 'c': 9, 'b': 8} 1 2 (4, 5, 6) {} 1 4 (5, 6) {'d': 'nltk'} 1 2 (4, 5, 6) {'d': 'scikit'}
In the code below, we support any function with any arguments by passing along whatever arguments that were sent in:
>>> def A_function(f, *args, **kwargs): return f(*args, **kwargs) >>> def f(a, b, c, d, e): return a*b*c*d*e >>> print(A_function(f, 10, 20, c=30, d=40, e=50)) 12000000
When the code is run, arguments are collected by the A_function.
f(*args, **kwargs) # newer call syntax: f(*sequence, **dict) apply(f, args, kwargs) # deprecated built-in: apply(f, sequence, dict)
The following function accepts any number of positional or keyword arguments:
>>> def echo(*args, **kwargs): print(args, kwargs) >>> echo(10, 20, a=30, b=40) (10, 20) {'a': 30, 'b': 40}
If we use the apply():
>>> args = (10, 20) >>> kwargs = {'a':30, 'b':40} >>> def echo(*args, **kwargs): print(args, kwargs) >>> apply(echo, args, kwargs) ((10, 20), {'a': 30, 'b': 40}) >>> echo(*args, **kwargs) ((10, 20), {'a': 30, 'b': ...
|
http://www.bogotobogo.com/python/python_functions_def.php
|
CC-MAIN-2017-26
|
refinedweb
| 2,137
| 63.63
|
Frequently Asked Questions about CppUnit
Feel free to add questions or answer ones that already exist
Contents
- Concepts
- Workings
- How do I?
- How do I run something like setUp() and tearDown(), but only once in total, not once per test?
- How do I run a subset of tests
- How would I use CppUnit for automated testing (answer needed)
- How do I stop a test run if a test fails? (answer needed)
- How do I print debug info (answer needed)
- How do I stop abort() being called when a test fails?
- How do I get the name of the test from within the setUp function?
- How can I create test hierarchy (suite of tests that contains other suites)?
- How do I get a minimal set of the cppunit?
- How do I test private/protected member functions?
- Working With Other Programs
Concepts
What are Test Plug-ins for
Test plug-ins can provide two services:
test cases to run for the DllPlugInTester
specific test listeners to use when running the tests with the DllPlugInTester.
This provides a very convenient mean to run unit tests contained in a dynamic library as a post-build step. Also the DllPlugInTester contains multiple command-line options to help getting the progress/output you want.
Additional test listeners can be provided as plug-in to the DllPlugInTester. See examples/ClockerPlugIn for an example that measures how long each test case takes to run and integrate those measurement in the xml output.
Items 2 and 3 of CppUnit2 features provide more details:.
Workings
How is flow of control when CppUnit runs tests? What can run in parallel, what is forced to be sequential. (Answer needed)
CppUnit seems to create one instance of the test class for each test function in it. Also, it seems to run setUp and tearDown in these different instances in parallell. Though it can't run tests in parallell, can it? I have trouble using global resource in test, which seems to be caused by setUp/tearDown running in parallel. Would be nice to know exactly what CppUnit did here. Please replace this with a specification.
How do I?
How do I run something like setUp() and tearDown(), but only once in total, not once per test?
Sometimes, the code for setUp() is really expensive in time or resources, and every test has to do the same setup. In these cases, it would be nice to be able to run the setup just once, and tear it down at the end of all the tests.
First answer is, Don't do it! If you are writing tests "correctly", then each test should take less than 1/100 of a second or less. A reasonable sized program may have thousands of tests, and if they run in much more than a few seconds, then developers won't run them every time they compile, then forget to run them before they check in, etc. etc.
Usually, long setups are due to a class depending on external libraries with setup sequences (such as a random number generator that collects some entropy), or loads an external data source (such as querying a web page, loading a file, connecting to a database), or prepares some class that requires a lot of setup (like a configuration class that loads an XML file). A common solution is to use an abstract interface for this functionality. Your production code uses an implementation class that hooks up to the real resource, and your testing class uses a mock implementation (which just tells you what functions were called), a stub implementation (which just implements what you need), or some other abstraction. See the Wikipedia entry for mock objects for a starting place, and MichaelFeathers' Working Effectively With Legacy Code for in-depth discussions. A word of warning - mock objects can be created on the fly for languages with reflection, but C++ doesn't support reflection. This means a lot of web information about mock objects for C#, Python, Ruby, etc. etc. won't apply to CppUnit.
Using two different implementations implies that you need some sort of acceptance testing for the "real" class, which is expected to be much slower. You can use CppUnit for these acceptance tests as well - just keep them out of your once-per-compile unit tests. You can create an abstract test suite that tests your abstract class (using CPPUNIT_TEST_SUITE_END_ABSTRACT), using a pure virtual "get_impl" that returns a pointer of the interface class type. You can then create a derived class (using CPPUNIT_TEST_SUB_SUITE) that returns your mock interface for get_impl, and another that uses the "real" interface for get_impl, and run one or the other depending on if you are running unit or acceptance tests. See the section on Writing Test Fixtures for help on the non-standard suite macros.
If you've decided that you still really want to just initialize something once, then you have to resort to some sort of global. A fairly clean way is to define a few class static functions in your test:
1 #include <cppunit/extensions/HelperMacros.h> 2 #include "BigNastyClass.h" 3 4 class MyTest : public CppUnit::TestFixture { 5 CPPUNIT_TEST_SUITE( MyTest ); 6 CPPUNIT_TEST( testMyTest ); 7 CPPUNIT_TEST_SUITE_END(); 8 public: 9 static BigNastyClass *my_big_nasty_class = 0; 10 11 static void acquire_BigNastyClass() 12 { 13 if (!my_big_nasty_class) { 14 my_big_nasty_class = new BigNastyClass("plz do lots of things"); 15 } 16 } 17 18 static void release_BigNastyClass() 19 { 20 delete my_big_nasty_class; 21 my_big_nasty_class = 0; 22 } 23 24 void setUp() 25 { 26 acquire_BigNastyClass(); 27 my_big_nasty_class->reset(); 28 } 29 30 void testMyTest() 31 { 32 CPPUNIT_ASSERT(my_big_nasty_class->phone_boss_for_approval_to_run_unit_tests()); 33 } 34 };
NOTE: tearDown does not release the static object (that would defeat the purpose), so there will be a memory leak. Luckily, unit tests are not (or should not be) a long-running process, so it may be OK in this instance. A autoptr may be a good idea, or explicitly release the object in the unit testing main().
How do I run a subset of tests
Non interactive test runners accept one or many test cases to run. You need to figure out which one need to be run and only add those. The base Test class contains some 'find' methods which can be used to locate a specific test/suite.
How would I use CppUnit for automated testing (answer needed)
(more precision needed: what is exactly the meaning of automated testing ?)
Well, CppUnit is all about automatic tests, just avoid user interactions, visual checking and blocking (system) calls.
How do I stop a test run if a test fails? (answer needed)
How do I print debug info (answer needed)
Like what test is it that makes an segmentation fault?
I see mostly two options:
run the tests using BriefTestProgressListener which print the name of each test before running it. In case of crash, the last name is the one of the test that crashed.
- Implements a Protector used to capture system specific exception that occurs during crash (hard to implement this portably).
Here is a code fragment/diff showing how to add this to some of the cookbook recipes:
1 +#include <cppunit/TestResult.h> 2 +#include <cppunit/BriefTestProgressListener.h> 3 4 ... other setup code here ... 5 6 // Adds the test to the list of test to run 7 CppUnit::TextTestRunner runner; 8 runner.addTest( suite ); 9 10 + // Shows a message as each test starts 11 + CppUnit::BriefTestProgressListener listener; 12 + runner.eventManager().addListener( &listener );
How do I stop abort() being called when a test fails?
Enable exceptions. In GCC, compile with -fexceptions. In VC++, use /EHsc (Enable C++ exceptions under Code Generation).
How do I get the name of the test from within the setUp function?
Neither the setUp() nor tearDown() functions know the name of the test being called, so you can't customize these for different tests. If you need to setup the environment for a single test, include that setup with the test. If several tests share the environment, then consider private data and functions, with each test calling the shared setup function. If all but a few need the same environment, then consider putting it in setUp() and tearDown(), and adding extra code to the non-cooperative tests.
How can I create test hierarchy (suite of tests that contains other suites)?
Use the CPPUNIT_TEST_SUB_SUITE() macro. For instance:
1 #include <cppunit/extensions/HelperMacros.h> 2 3 class MyTest { 4 CPPUNIT_TEST_SUITE( MyTest ); 5 CPPUNIT_TEST( testBasic ); 6 CPPUNIT_TEST_SUITE_END(); 7 public: 8 void testBasic(); 9 }; 10 11 class MySubTest : public MyTest { 12 CPPUNIT_TEST_SUB_SUITE( MySubTest, MyTest ); 13 CPPUNIT_TEST( testAdd ); 14 CPPUNIT_TEST( testSub ); 15 CPPUNIT_TEST_SUITE_END(); 16 public: 17 void testAdd(); 18 void testSub(); 19 };
MyTest will run testBasic, while MySubTest will run testAdd, testSub, and testBasic. See the Writing Test Fixture section of the documentation. If you are testing a class heirarchy with abstract classes, CPPUNIT_TEST_SUITE_END_ABSTRACT() may also be useful, to create a test fixture that exercises pure virtual functions.
How do I get a minimal set of the cppunit?
What sources are necessary if I only want to have the basic functionality of unittest? eg. i only need a runner, an assert(boolean), a register. Is there any definition for the minimal set sources to make it runnable?
How do I test private/protected member functions?
There is a lot of debate in the unit testing world surrounding this topic. Some argue that if the logic of the private functions needs unit testing, one should try to refactor it into a different class altogether. After all, private functions should be an implementation detail, which may change in the future. However, protected members should still be considered as APIs. One of the most common way to accomplish this is by declaring the test suite class as the friend of the class to be tested. To be clean, it is better to scope this declaration in a ifdef section.
1 class Foo { 2 public: 3 #ifdef UNITTEST 4 friend class FooTest; 5 #endif 6 ... 7 8 protected: 9 ... 10 11 private: 12 ... 13 };
It would even be better to come up with a helper macro like the following.
1 #ifdef UNITTEST 2 #define ASSIST_UNIT_TEST( class__ ) friend class class__##Test 3 #else 4 #define ASSIST_UNIT_TEST( class__ ) 5 #endif
Use the above macro in the class to be tested.
1 class Foo { 2 public: 3 ASSIST_UNIT_TEST( Foo ); 4 ... 5 6 protected: 7 ... 8 9 private: 10 ... 11 };
Alternatively, if you just need access to the protected members:
1 // Original Class 2 class Foo { 3 protected: 4 void bar(); 5 }; 6 7 // In testing code, possibly in another file 8 class TestFoo : public Foo { 9 public: 10 void test_bar() { bar(); } 11 };
Do your testing against TestFoo, or at least those tests that require access to the protected members. The advantage to this approach is that testing code can be cleanly separated from production code without using macros.
PS: If someone knows a better approach, please document it here.
Working With Other Programs
When unit testing a static library created with "ar", why does the registry not show any tests?
The ar utility strips out some of the static variable information used by CppUnit. So if you create a static library (.a), the CppUnit::TestFactoryRegistry won't return any tests for classes in that static library. The solution is to either compile your test classes in to a dynamic library (.so) or to link your test runner directly with the individual object (.o) files.
Note that you could just explicitly add the test fixtures from a static library to test runner class, bypassing the factory registry entirely.
Is there a program, like JUnitDoclet, that will generate test skeletons automatically?
yes, this was recently developed and is licensed under GPL. It is a component of the turaya-distribution. Short Instructions to get this working:
Download there: (the file turaya-snapshot-060619.tar.gz)
- extraxt the files: tar xvfz turaya-snapshot-060619.tar.gz
- cd turaya/scripts/code2test
- read the readme: less README
Also, see the new code2test Sourceforge project.
Can I integrate CppUnit with CruiseControl?
Yes, with a bit of leg work.
You must be using a build process capable of being launched by CruiseControl (nant works well)
- From within that build you should build cppunit, and build and run the unit tests.
By setting the unit tests to output in junit format to a log directory (for example, using the xslt from the latest development release, or by modifying cppunit) cruise control will display nicely formatted test results. (Don't forget to merge the log results)
Using cruisecontrol as a continous integration process is very nice, even when compared to running nightly builds. Seeing the build results appear very quickly after checkins on integration branches is _very_ nice.
|
http://cppunit.sourceforge.net/cgi-bin/moin.cgi/FrequentlyAskedQuestions
|
crawl-001
|
refinedweb
| 2,108
| 62.48
|
Here is a question from Henry Medina on creating groups that might be of interest to a wider audience:
Question: I have listened to your TV recording several times and was also able to run the Labs project. Your Labs code shows how to draw beams, columns and braces, but not a group. How could I create a new instance of an existing group, set its insertion base point, location, rotation angle, and mirror it? Please show the commands in C#.
Answer: When addressing a question like this, there are a certain number of steps that I recommend always going through:
- RevitAPI.chm
- Getting Started Revit API 2009.doc
- Revit SDK Samples
- Revit 2009 API Developer Guide.pdf
Before looking at these, here are some basics about element creation. Everything that can be created through the Revit API is handled by the Application and Document classes in the Autodesk.Revit.Creation namespace. Since a group is a database resident object, it is generated by the creation document. The creation application is used for objects that a memory resident only, such as geometry objects.
Now, looking at the creation document and its methods in RevitAPI.chm or in the Visual Studio object browser, it is easy to find the NewGroup method. It takes an ElementSet as an argument and returns a newly created Group instance. It creates a new type of group and returns a new instance of it containing the specified elements. Initially the group will have a generic name, such as Group 1. This can be modified by changing the name of the group type using something like newGroup.GroupType.Name = newName. So it actually creates both a GroupType object and an instance of that type. The GroupType class is derived from Autodesk.Revit.Symbol, and Group from Autodesk.Revit.Element.
The Getting Started document turns up one snippet of information on groups in its question and answer section that may be useful to us later, but does not address our immediate need:
Q: When exporting a model containing groups to an external program, the user receives an error at the end of the export: "Changes to group "Group 1" are allowed only in group edit mode. Use the Edit Group command to make the change to all instances of the group. You may use the "Ungroup" option to proceed with this change by ungrouping the changed group instances."
A: Currently the API does not permit changes to members of groups. You can programmatically ungroup, make the change, regroup and then swap the other instances of the old group to the new group to get the same effect.
While this does not help us with our immediate question, it does at least further confirm the degree of programmatic access that is and is not provided to the grouping functionality.
Searching the Revit SDK Samples for NewGroup turns up no hits. Almost all aspects of the Revit API are demonstrated in the samples, so this is actually quite unusual. I have not addressed this in any of my labs yet either.
The next place to look is the developer guide. This is the most in-depth source of information on Revit programming, because it explains relationships and underlying concepts that are not immediately apparent from the classes, properties and methods presented in the help file nor immediately visible in the sample code. Again, we start by searching for 'NewGroup'. If no hits were found, I would then search for just 'group'. This time, 'NewGroup' is found, in section 9.4 Group. This section does indeed explain groups very well from the programming point of view. It also includes two code snippets 9-8: Creating a Group and 9-9: Naming a Group.
This answers the first part of your question, on how to create a group.
Regarding the placement of instances, I continued searching in the creation document members and found the PlaceGroup method, which places an instance of a model group into the Revit project, using a location and a group type.
I have not implemented any code testing any of this yet. If you do, please feel free to pass it on.
I hope this helps you learn to fish, and does not just feed you.
Many thanks, Henry, for this illuminating question, and good luck with your further steps!
|
http://thebuildingcoder.typepad.com/blog/2009/02/creating-a-group-and-how-to-fish.html
|
CC-MAIN-2017-13
|
refinedweb
| 722
| 62.88
|
Your Account
Regular expressions have been used in various programming languages and tools for many years. The .NET Base Class Libraries include a namespace and a set of classes for utilizing the power of regular expressions. They are designed to be compatible with Perl 5 regular expressions whenever possible.
In addition, the regexp classes implement some additional functionality, such as named capture groups, right- to-left pattern matching, and expression compilation.
In this article, I'll provide a quick overview of the classes and methods
of the System.Text.RegularExpression assembly, some examples of
matching and replacing strings, a more detailed walk-through of a grouping
structure, and finally, a set of cookbook expressions for use in your own
applications.
Regular expression knowledge seems to be one of those topics that
most programmers have learned and forgotten, more than once. For the
purposes of this article, I will presume some previous use of regular
expressions, and specifically, some experience with their use within
Perl 5, as a reference point. The .NET regexp classes are a superset
of Perl 5 functionality, so this will serve as a good conceptual
starting point.
I'm also presuming a basic knowledge of C# syntax and the .NET
Framework environment.
If you are new to regular expressions, I suggest starting with some of
the basic Perl 5 introductions. The
perl.com site has some great
resource materials and introductory tutorials.
Related Reading
C# Essentials
By Ben Albahari, Peter Drayton, Brad Merrill
The definitive work on regular expressions is
Mastering Regular
Expressions, by Jeffrey E. F. Friedl. For those who want to get the
most out of working with regular expressions, I highly recommend this
book.
The regexp classes are contained in the
System.Text.RegularExpressions.d actually only six classes and one delegate definition in
the assembly namespace. These are:
The Regex class also contains several static methods:
Let's start with simple expressions using the Regex and the Match class.
Match m = Regex.Match("abracadabra", "(a|b|r)+");
You now have an instance of a Match that can be tested for success, as
in:
if (m.Success)
...
without even looking at the contents of the matched string.
If you wanted to use the matched string, you can simply convert it to
a string:
Console.WriteLine("Match="+m.ToString());
This example gives us the output:
Match=abra
which is the amount of the string that has been successfully
matched.
Simple string replacements are very straightforward. For example,
the statement:
string s = Regex.Replace("abracadabra", "abra", "zzzz"); preceeding and trailing
spaces removed.
The above pattern is actually generally useful for removing leading
and trailing spaces from any string. We also have used the literal
string quote construct in C#. Within a literal string, the compiler
does not process the \ as an escape character. Consequently,
the @"..." is very useful when working with regular
expressions, when you are specifying escaped metacharacters
with a \. Also of note is the use of $1 as the replacement
string. The replacement string can only contain substitutions, which
are references to Capture Group in the regular expression.
Now let's try to understand a slightly more complex sample by doing a
walk-through of a grouping structure. Given the following sample:
";
// use 'x' modifier to ignore comments
Regex r = new Regex(pat, "x");
// sample would
Let's start by examining the string pat, which contains the
regular expression. The first capture group is marked by the first
parenthesis, and then the expression will match an abra, if the
regex engine matches the expression to that which is found in the text.
Then the second capture group, marked by
the second parenthesis, begins, but the definition of the first
capture group is still ongoing. What this tells us is that the
first group must match abracad and the second group would
just match the cad. So, if you decide to make the cad match
an optional occurrence with the ? metacharacter, then abra or
abracad will be matched. Next, you end the first group, and
ask the expression to match 1 or more occurrences by specifying
the + metacharacter.
Now let's examine what happens during the matching process. First,
create an instance of the expression by calling the Regex
constructor, which is also where you specify your options. In this case,
I'm using the x option, as I have included comments in the regular
expression itself, and some whitespace for formatting purposes.
By turning on the x option, the expression will ignore the comments,
and all whitespace that I have not explicitly escaped.
Next, get the list of group numbers (gnums) defined in
this regular expression. You could also have used these numbers
explicitly, but this provides you with a programmatic method. This
method is also useful if you have specified named groups, as a
way of quickly indexing through the set of groups.
Next, perform the first match. Then enter a loop testing for
success of the current match. The next step is to iterate through the
list of groups starting at group 1. The reason you do not use group 0
in this sample is that group 0 is the fully captured match
string, and what you usually (but not always) want to pick out of
a string is a subgroup. You might use group 0 if you wanted to
collect the fully matched string as a single string.
Within each group, iterate through the CaptureCollection.
There is usually only one capture per match, per group, but in
this case, for Group1, two captures show: Capture0 and Capture1.
And if you had asked for only the ToString of Group1,
you would have received abra, although it also did match the
abracad. The group ToString value will be the value of the last
Capture in its CaptureCollection. This is the expected behavior, and
if you want the match to stop after just the abra, you
would remove the + from the expression, telling the regex engine
to match on just the expression.
Generally, the users of regular expressions will tend to, and I
hope this article outlines both the capabilities of the .NET regexp
classes, as well as the trade-offs in complexity and performance
of the solution.
A common processing need is to match certain parts of a string and
perform some processing. So, here's an example that matches words
within a string and capitalizes them:
string text = "the quick red fox jumped over the lazy brown dog.";
System.Console.WriteLine("text=[" + text + "]");
string result = "";
string pattern = @"\w+|\W+";
foreach (Match m in Regex.Matches(text, pattern))
{
// get the matched string
string x = m.ToString();
// if the first char is lower case
if (char.IsLower(x[0]))
// capitalize it
x = char.ToUpper(x[0]) + x.Substring(1, x.Length-1);
// collect all text
result += x;
}
System.Console.WriteLine("result=[" + result + "]"); above example is by providing a
MatchEvaluator, which will process it as a single result set.
So the new sample looks like: = "the quick red fox jumped over the
lazy brown dog.";
System.Console.WriteLine("text=[" + text + "]");
string pattern = @"\w+";
string result = Regex.Replace(text, pattern,
new MatchEvaluator(Test.CapText));
System.Console.WriteLine("result=[" + result + "]");
}
Also of note is that the pattern was simplified since I only
needed to modify the words and not the non-words.
To wrap up this overview of how regular expressions are used in the C#
environment, I'll leave you with a set of useful expressions that have been
used in other environments. I got them from a great book, the
Perl Cookbook,
by Tom Christiansen and Nathan Torkington, and updated them for
C# programmers. I hope you find them useful.''");
Download the source code for
these Cookbook Expressions.
Brad Merrill is a compiler technology engineer in the Microsoft
Developer Relations Group. He has worked with the C# team for more
than two years. He also has worked with
other
non-Microsoft language partners, including
ActiveState, Perl, and
Python, to help make additional languages available on the Microsoft .NET
Framework. You can reach Brad at
brad_merrill@hotmail.com.
O'Reilly & Associates will soon release (February 2001)
C# Essentials.
Sample
Chapter 1, "Introduction," is available free online.
You can also look at the
Table of
Contents.
For more information, or to order the book,
© 2015, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
|
http://archive.oreilly.com/pub/a/windows/archive/csharp-regular-expressions.html
|
CC-MAIN-2015-06
|
refinedweb
| 1,404
| 64
|
This blog entry is dedicated to Michael Spencer whose 120 character-long entry in the PyContest was submitted less than 90 minutes after the official beginning of submissions. Michael's entry gave a target to aim for which few people managed to reach. I strongly suspect that, in large part because of this, various hints have been posted on the web, enabling more people to slowly crawl towards ever-shorter solutions. I must admit that without the various hints I have read, I would never have been able to challenge Michael's solution.
After being asked a few questions here and elsewhere, I've decided that I should try and document the reasoning that eventually led me to my final solution to the PyContest. Of course, it is going to be more linear here (and with fewer dead-end explorations) than it was in real life. I definitely welcome comments from others' journeys.
First solution
After writing on paper the desired output for an input that included all digits, I quickly wrote down the following program to produce the desired output:
def seven_seg(i):
~~n=[[" _ "," "," _ "," _ "," "," _ "," _ "," _ "," _ "," _ "],
~~~~~["| |"," |"," _|"," _|","|_|","|_ ","|_ "," |","|_|","|_|"],
~~~~~["|_|"," |","|_ "," _|"," |"," _|","|_|"," |","|_|"," _|" ]]
~~m=''
~~for j in 0,1,2:
~~~~for d in i:
~~~~~~~~m+=n[j][int(d)]
~~~~m+='\n'
~~return m
print seven_seg('0123456789')
In an attempt to preserve the visual appearance, I have replaced all the leading spaces by "~". In the future, whenever you see a "~", take it to be a space. After removing the print statement, the number of characters is 310, which is quite a ways from 117. One can reduce the number of characters by removing many unnecessary spaces but I will not do that until we are much closer to the "final" solution. Furthermore, I will keep the explicit for loops rather than using generators [with the ''.join() method] until the very end as I find the code easier to read that way. I will, however, move the [m=''] assignment within the function argument, thus removing a line (and at least two extra characters!) from the solution.
My next step was to look at the various "triplets" (three-character combinations) that appeared in "n". Quite a few are repeated. In fact, there are 7 unique triplets; they are:
"~~~", "~_~", "~_|", "|_~", "|_|", "~~|", "|~|"
With this ordering, and giving each triplet a number from 0 to 6, we have each input digit can be given by the following three number combination:
0=164, 1=055, 2=123, 3=133, 4=065, 5=132, 6=134, 7=155, 8=144, 9=142.
Note that the first digit of each triplet is either a 0 or a 1; this will be important later. Using these triplets leads to a second, shorter, solution:
def seven_seg(i, m=''):
~~n=["~~~","~_~","~_|","|_~","|_|","~~|","|~|"]
~~for j in '1011011111', '6622433544', '4632524542':
~~~~for d in i:
~~~~~~m+= n[int(j[int(d)])]
~~~~m+= '\n'
~~return m
Note that the string '1011011111' represents the first digit of each triplet, and that the order in which they appear is '0123456789'.
By moving the inner for loop statement (5th line) at the end of the 4th line, using a single space for the first indentation and a tab character (expanded by Python to 8 spaces) for the second level of indentation and removing other non-required spaces, it is possible to reduce the length of the code to 171 characters -- still a long way from our final goal.
The next step is to eliminate "n" altogether; we can do this in two steps.
The first step is simply use it as is in the line
def seven_seg(i, m=''):
~~for j in '1011011111', '6622433544', '4632524542':
~~~~for d in i:
~~~~~~m+= ["~~~","~_~","~_|","|_~","|_|","~~|","|~|"][int(j[int(d)])]
~~~~m+= '\n'
~~return m
The second step is to try to replace the list of strings by a single string and extract, when assigning, a 3-character substring. The shortest such string that we can construct is 14 character long. There are many such strings; here is one of many examples:
'~_~_|_~~~|~|_|'
~01234567890123
Using this string, we see that the last 3-character substring, '|_|', starts at index 11. To encode the position of each beginning index, we would need at least 2 digits for some. A better way appears to lengthen the string a bit so that each required 3-character substring starts on an even index -- the last character of one substring being the first character of the next. Here is one such solution -- which, other than for some unnecessary spaces, is the exact first solution that I submitted at the exact opening of the contest at 14:00 UTC; for one minute it was in first place. :-)
def seven_seg(i, m=''):
~for s in '5455455555', '2600133611', '1630601610':
~~for k in i:
~~~~j=int(s[int(k)])*2;
~~~~m+='~_|_|~|_~~~_~~|'[j:j+3]
~~m+='\n'
~return m
Not having done any programming for a while, I didn't realise at the time that 'some_string'[j:j+3] could be written as 'some_string'[j][:3], thereby saving one assignment (to j) and some precious characters all around.
The next step is to try to shorten the three long numbers: '5455455555', '2600133611' and '160601610'. This can be done by encoding them in a base other than 10 and extracting the result when needed. A better way however is to re-arrange the number as a series of triplets and then encode the result. For example, the three long numbers just mentioned can be re-ordered as follows:
0=521, 1=466, 2=503, 3=500, 4=416, 5=530, 6=531, 7=566, 8=511, 9=510
This gives rather large integers (ex: 521) to try to encode in a base different from 10. A better choice would be to use the ordering
0=164, 1=055, 2=123, 3=133, 4=065, 5=132, 6=134, 7=155, 8=144, 9=142
that we had mentioned earlier, as it gives smaller integers. Now, Python's built-in function int() allows conversion to base 10 from other bases up to 36. Still, that would require a 2 character encoding from each triplet. A better choice is to take each triplet to be the decimal representation of an ascii character. As each triplet is a number less than 255, this is certainly possible (barring some unfortunate coincidence when a given triplet would correspond to a newline character.)
Actually, since none of the individual digits in the triplets is greater than 6, we can take them to be numbers in a base less than 10; from what I gather, most people chose 8 (as they try to do stuff with bit shifts and the like) and I chose 7 (for one of my submissions). Thus, a number like 164 is taken to mean
164 (in base 7)= 1*49 + 6*7 + 4 = 95 (in base 10). This will help further reduce the number of characters. Let's assume that everything is correct with these choices (i.e. still no newline character) and that the encoding of our triplets can be represented as
0=z, 1=o, 2=t, 3=T, 4=f, 5=F, 6=s, 7=S, 8=e, 9=n
where I have use the first letter of each number as a representation of its encoding.
As an aside, some useful comments about this (and other aspects of this problem) can be found on the following two blog entries (including comments):
Guyon Morée's blog
Roberto Alsina's blog
The corresponding program, still written with the explicit for-loops, can be written schematically as follows:
def seven_seg(i, m=''):
~for a in 49, 7, 0:
~~for k in i:
~~~~m+='~_|_|~|_~~~_~~|'[ord("z0tTfFsSen"[int(k)])/a%7*2:][:3]
~~m+='\n'
~return m
Let's examine what the innermost loop does. We convert each character in the input string into a digit, extract the corresponding ascii-encoded triplet, decode it into an actual number, divide by the appropriate power of our base and take the modulo in that base, thus extracting the relevant digit in the triplet; the result is multiplied by 2 to find the relevant index in our string of "~|_". So you can see the advantage of using a base less than 10 as it takes fewer characters to write.
To make the solution as short as possible, we rewrite it as a lambda and use join() and generators instead of explicit for loops. This also eliminates the use of an extra variable ("m"). The result can be written as:
j=''.join
seven_seg=lambda i:j(
j('~_|_|~|_~~~_~~|'[ord("z0tTfFsSen"[int(k)])/a%7*2:][:3]for k in i)
+'\n' for a in(49,7,0))
When all the extra spaces are removed, this gives a 121-character long solution. I'll refer you to the already mentioned blogs for a 120 character long solution!
To get to 117 characters, we need a slightly different approach.
We need to go back to some assumptions we made earlier. Do we really need to have even-numbered indexes? If not, we could use a shorter "~|_" type string which included all relevant 3-character substrings, thereby possibly saving one character. Let us look at such a possible string and the various indices. I will take the string of my posted 117 character long solution '~_~~~|_|_~_|~|', and extract the location of the indices of the relevant substrings:
"~~~":2, "~_~":0, "~_|":9, "|_~":7, "|_|":5, "~~|":3, "|~|":11.
With these 3-character substrings, our triplets are:
0=0-11-5, 1=233, 2=097, 3=099, 4=253, 5=079, 6=075, 7=033, 8=055, 9=059
For each triplet, instead of encoding it in a given base, we will look at a number which, when taking the modulo with three different bases, will give us back the relevant digit. By this, I mean something like the following:
165%3 = 0
165%14 = 11
165%10 = 5
i.e., the triplet for "0" could be represented by the integer 165 when taking the modulo with 3, 14 and 10 respectively - as I have done in the 117 solution. Using brute force, which is what one does when one is too tired, one can loop over the integers less than 255 and find out if all the relevant triplets can be found. Or, you notice that 11*5*3 = 165 [11%14=11, 5%10=5, 3%3=0], and you proceed from there. With this information (and the comments on the previous blog entry), you should now have all the relevant information to understand how this solution was obtained.
On that final note, I wish you a very Happy New Year!
|
https://aroberge.blogspot.com/2005/12/
|
CC-MAIN-2018-13
|
refinedweb
| 1,815
| 62.61
|
Unable to load 'alut.dll' errorPosted Friday, 6 March, 2009 - 17:33 by Mitch in
I downloaded OpenTK and wrote a simple piece of software to play audio files using the OpenTK.Audio namespace.
All compiled but didn't run, turned out I was missing the alut.dll. I put that next to my .exe and all works great.
BUT if I take it to any other machine it doesn't work. The debugger tells me "Unable to load 'alut.dll' " and this is coming from the OpenTK.Audio.Alut.Init() method.
BUT alut.dll is right there next to my .exe.
On main developement machine I have obviously installed OpenTK. But on other machines I have my .exe, OpenTK.dll and alut.dll all sitting next to each other.
What should I do?
Thanks for any help,
Mitch.
[Moderator edit: changed title to something more descriptive.]
Re: HELP!
Ok, you'll need to provide some more info: which operating system, which .Net version, 32-bit or 64-bit?
Also, OpenTK provides the
AudioContextclass, which replicates Alut.Init (just create an AudioContext instead). This will be easier to use, because you won't have to distribute alut.dll along with your program.
Re: Unable to load 'alut.dll' error
Hi,
thanks for your reply, sorry about delay in my replying - weekend and all.
Are there any examples of how I should use the AudioContext class. I can't get it working - all compiles and runs but no sounds happening.
My code so far is really tiny so it may help to see it:
I have a Class with the following three small methods:
In constructor I just have:
Alut.Init();
And then I have two methods, AddSound and PlaySound as follows (m_soundBuffers is a member of the class declared as List m_soundBuffers = new List();)
public void AddSound(string szFilePathName)
{
int nSoundIndex = m_soundBuffers.Count;
m_soundBuffers.Add(new int[1]);
m_soundBuffers[nSoundIndex] = AL.GenBuffers(1);
m_soundBuffers[nSoundIndex][0] = (int)Alut.CreateBufferFromFile(szFilePathName);
if (AL.GetError() != ALError.NoError)
{
MessageBox.Show("Unable to add sound " + szFilePathName);
}
}
public void PlaySound(int nSound)
{
int[] source = new int[1];
source = AL.GenSources(1);
AL.Source(source[0], ALSourcei.Buffer, m_soundBuffers[nSound][0]);
AL.SourcePlay(source[0]);
}
All works fine. Now I need to replace with AudioContext instead of using Alut.Init() and Alut.CreateBufferFromFile but how?
I tried having a member varibale of type AudioContext, and in the constuctor I had m_audioContext = new AudioContext() etc. And in the AL namespace I can't find a method for replacing Alut.CreateBufferFromFile
Thanks for any help,
Mitch.
Re: Unable to load 'alut.dll' error
OpenTK.Utilities provides an AudioReader class that replaces Alut.CreateBufferFromFile. There is an example using this class under Source/Examples/OpenAL/ (or you can view the code online here).
It's true that the documentation on OpenTK.Audio is a little lacking right now.
Re: Unable to load 'alut.dll' error
Thanks so much for your help.
I've got it working now. The code is really simple to use, very clear.
Basically on SourceForge I had downloaded the .zip version of the file, not the .7z
The former contained version 0.9.4 which had no OpenTK.Utilities. (I downloaded the former three days ago, maybe they are both the same now, I didn't check).
The only new feature now is that when I play some wav files I get a click at the end where I used not to (using alut.dll).
(e.g. C:\Windows\Media\Ding.wav).
Is this a known problem or could I be doing something wrong?
Is there a way to get the number of samples in an AudioReader object?
Right now I call:
AL.BufferData(m_soundBuffers[nSoundIndex], sound.ReadSamples(ReadToEnd());
whereas, in the case of Ding.wav if I call:
AL.BufferData(m_soundBuffers[nSoundIndex], sound.ReadSamples(80000));
I avoid the click at the end.
Thanks for any advice,
Mitch.
Re: Unable to load 'alut.dll' error
The clicking issue sounds like a bug - please open a bug report so it doesn't get lost.
By the way, the zip and 7z packages are identical (but for size). I was afraid for a moment that I made a mistake while creating the release, but both contain OpenTK.Utilities as they should (note that OpenTK.Utilities is unchanged between 0.9.4 and 0.9.5).
Re: Unable to load 'alut.dll' error
Ok I will.
I also found that there are some .wav files that won't play at all.
My code plays most fine but for instance:
C:\Windows\Media\Start.wav causes a NotSupportedException "Could not find a decoder for the specified sound stream.".
Finally, and this is most definately my ignorance, I am unable to run my app on machines other than my developement machine.
Initially it complained that OpenAL32.dll was not present, so I put this next to me .exe and then I get an AudioDeviceException:
"Audio device "default" does not exist or is tied up by another application" - this is occuring in my new AudioContext() call, at OpenTK.Audio.AudioContext.CreateContext(.....
I am obviously being really stupid about something obvious here.
Sorry for all the posts, thanks for all the help,
Mitch.
Re: Unable to load 'alut.dll' error
Did you download OpenAL from Creative's website? If so, you cannot just copy the openal32.dll, you have to use the installer on the other machines.
The other solution is to compile and distribute OpenAL Soft (its openal32.dll does not need an installer).
Re: Unable to load 'alut.dll' error
Okay,
Thanks.
installation of OpenAL solves it.
Having truble building OpenAL Soft's dll (using CMake and Visual Studio 2008) don't suppose you know of a direct download link to the OpenAL Soft windows dll? Or some good instructions for building it on windows?
Thanks,
Mitch.
Re: Unable to load 'alut.dll' error
Just follow instructions on OpenAL soft home page. Run cmake -G "Visual Studio 9 2008" .. , and then build solution. Make sure you have dsound.h/lib files available, because it is required for backend under Windows.
Re: Unable to load 'alut.dll' error
It would be a great resource for the OpenTK community if there would be somewhere to find the binaries for the OpenAL soft library.
Not everyone feels the urge to d/l VC++ and compile stuff. And think of the wasted cpu cycles for such a procedure! If there are N developers wanting to use OpenAL, there are N times as many compilations performed compared to having precompiled binaries. :)
Just a thought. Any volunteers?
|
http://www.opentk.com/node/685
|
CC-MAIN-2013-48
|
refinedweb
| 1,101
| 70.39
|
.
Introduction.Data binding in Visual Studio.NETIn this section, we're going to build a two-tier enterprise application using Visual Studio.NET and the underlying data binding framework. The first step is to start the Visual Studio.NET, and then create a connection to the underlying database using Data Connection tree in the Server Explorer. Go to the Server Explorer window, right-click on the Data Connections node and choose Add Connection from the context menu. In the Add Connection dialog, enter the information to connect to the AdventureWorks database shipped with the installation of Microsoft SQL Server 2005 (see Figure 1).Figure 1Now let's create a solution and two projects: one as class library to package the business logic layer's components (see Figure 2) and the other as Windows Application (see Figure 3) to package the presentation layer's components.Figure 2Figure 3Now we're going to create the business components for the business logic module. As illustrative, we're going to use the Production.Product and Production.ProductModel tables in the AdventureWorks. For this purpose, we're going to create the business entities using Dataset object model. In the Solution Explorer window, right-click on the BusinessLogicCompPkg project, select Add | New Item from the context menu and select Dataset item from the Add New Item dialog box (see Figure 4).Figure 4Once the DataSet designer is open, you can define business entities by right-clicking on the DataSet designer and selecting Add | TableAdapter option from the context menu. When the Table Adapter Configuration Wizard appears, in the Step 1, you choose the created data connection (see Figure 5). Click on Next button.Figure 5In the Step 2, you specify how to store the connection string in the configuration file. Click on Next button. In the Step 3, you can specify the access method to the database. In this case, we're going to write SQL statements (see Figure 6).Figure 6In the Step 4, you must write the underlying SQL SELECT statement (see Figure 7). Click on the Next button.Figure 7The final step is for choose the methods associated to the Data Adapter in order to interact with the data source (see Figure 8).Figure 8Repeat this step in order to create the ProductModel entity. After that, the data set resembles as in Figure 9.Figure 9Finally, compile this project and we're read to use these business components. Now let's move on to the presentation project. Let's add a MenuStrip control from the Toolbox onto the main form. In the menu, create a sub-menu named Entities with two inner child menus named Product and Product Model. Finally, let's add an event handler for the Click event for the Product and Product sub-menu (see Figure 10).Figure 10Now let's add two child forms to display data of the Product and ProductModel entities and a reference to the BusinessLogicCompPkg assembly in order to invoke its objects (see Figure 11).Figure 11Now let's work on the ProductForm. Go to the Data Sources window and click on Add New Data Source icon in order to open the Data Source Configuration Wizard. In the first step, we choose to consume the data from the objects (the business entities created before). Click on Next button. In the Step 2, choose the data objects to bind to the GUI application, in this case the ProductDS object (see Figure 12).Figure 12Now you can see the Product and ProductModel entities in the Data Sources window. The next step in the application is to configure the Product to be displayed in details mode (see Figure 13) and the.Figure 13You must configure the ProductModelID attribute as a combo box (Figure 14).Figure 14Drag and drop the ProductModel node from the Data Sources window onto the ProductModelID attribute.Now we need to add the business logic using C# to fill the data set and update the data source from the changes from the data set (see Listing 1)using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using BusinessLogicCompPkg;using BusinessLogicCompPkg.ProductsDSTableAdapters;
namespace AppGUI{ public partial class ProductForm : Form { public ProductForm() { InitializeComponent(); }
private void ProductBindingNavigatorSaveItem_Click(object sender, EventArgs e) { this.Validate(); this.productBindingSource.EndEdit(); ProductTableAdapter taProduct = new ProductTableAdapter(); taProduct.Update(productsDS.Product); } }}Listing 1Now let's go to the ProductModelForm form how to create a master/detail oriented form. Let's configure the ProductModel node as Details (see Figure 15). Figure 15Then drag and drop the ProductModel onto the ProductModelForm. Then, drag and drop the Product node inside the ProductModel node onto the ProductModelForm. Now we need to add the business logic to fill and update the Product and ProductModel (see Listing 2).using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using BusinessLogicCompPkg;using BusinessLogicCompPkg.ProductsDSTableAdapters;
namespace AppGUI{ public partial class ProductModelForm : Form { public ProductModelForm() { InitializeComponent(); }
private void ProductModelModelBindingNavigatorSaveItem_Click(object sender, EventArgs e) { this.Validate(); this.productModelBindingSource.EndEdit(); this.productBindingSource.EndEdit();
ProductTableAdapter taProduct = new ProductTableAdapter(); taProduct.Update(productsDS.Product);
ProductModelTableAdapter taProductModel = new ProductModelTableAdapter(); taProductModel.Update(productsDS.ProductModel); } }}Listing 2Data binding in JDeveloperIn this section, we're going to build a two-tier enterprise application using ADF Business Components as the business layer containing the business logic, validations and business rules and ADF Swing as the presentation layer for gathering and displaying information.The first step is to start the JDeveloper, and then create a connection to the default ORCL database (shipped with Oracle database installation) using JDBC as the main API to access the relational data source from your application. Go to the Connections Navigator window, right-click on the Database node and choose New Database Connection from the context menu. The Create Database Connection Wizard appears then; click on Next button and in the Step 1 set a name for the connection (see Figure 16). Then click on the Next button.Figure 16In the Step 2, you must enter the authentication information (see Figure 17). Click on Next button.Figure 17In the Step 3, you must specify the connection details (see Figure 18). Click on Next button.Figure 18And finally, you test the created connection. Now let's create the application by going to the Applications Navigator, right-click on the Applications node and select New Application from the context menu. In the Create Application dialog box, enter the name for the application, the working directory and the application package prefix (see Figure 19).Figure 19Then, create a project for the business logic components (see Figure 20).Figure 20Now we're going to create the business components for the business logic module. As illustrative, we're going to use the SCOTT schema shipped with the default installation of Oracle. For this purpose, we're going to create the business entities using ADF Business Components based on tables. In the Application Navigator window, right-click on the business_logic project and select New from the context menu and select Business Components from Tables from the New Gallery dialog box (see Figure 21). Click on OK button.Figure 21Then, a window appears where you have to select the connection to the database and click on OK button and then the Create Business Components Wizard appears. Click on Next button; and in the Step 1, you must select a list of tables for which you want to create entity objects. You can also change the name of the business entities by clicking on Selected list and typing the new name in the Entity Name field (see Figure 22). Click on the Next button.Figure 22In the Step 2, you can create the views associated to the entities created in the Step 1. Select all the entities and change the name of the views as well as to add them to a new package (see Figure 23). Click on the Next button.Figure 23In the Step 3, you can create read-only business entities. In our example, we don't need to create this kind of view. Then click on the Next button. In the Step 4, you set the name for the application module (see Figure 24). The application module bundles together the components and enables transaction support as well as other important data-centric services. Click on the Next button.Figure 24In the Step 5, you can specify the diagram of the components and their relationships (see Figure 25).Figure 25Click on the Next button, and you can see the result of the Wizard, and finally click on the Finish button. Before you create to the presentation layer, let's implement several business logic, format and validation code according to our business requirements. Go to the Applications Navigator and double-click on the Department entity and the Entity Object Editor window appears. Go to the Attributes node to select the attributes to be customized then go the Control Hits tab which enables to specify its format for the graphical presentation of the entity.For the Deptno attribute, we have (see Figure 26).Figure 26And for the Dnam attribute, we have (see Figure 27).Figure 27Finally, for the Loc attribute, we have. We can go on using the same approach for the rest of the attributes of the Employee entity (see Figure 28).Figure 28Now let's develop the Presentation Layer components. Go to the Application Navigator and add a new project named client_presentation (see Figure 29).Figure 29The right-click on the project and select New from the context menu, go to the Client Tier/ ADF Swing node and select Empty Form as the main form (see Figure 30).Figure 30Disable the Generate a menu bar checkbox (because we're going to create a customized menu bar) and set a name for the main form in the Wizard such as MainForm (see Figure 31).Figure 31Now let's design the main menu of the application by drag and drop JMenuBar from Components Palette to the form. Then, create a sub-menu named Entities with inner child menus named Employee and Department. Finally, let's add an event handler for the actionPerformed event for the Employee and Department sub-menus (see Figure 32).Figure 32Now it's time to add the child forms by right-clicking on the project and selecting New from the context menu (see Figure 33 and Figure 34).Figure 33Figure 34Let's work on the EmployeeForm. First of all, select the navigation bar (this is generic for each table) and delete it. Now, go to the Data Control palette, and drag and drop the EmployeeVO1 onto the form, and from the Context Menu select Add Child | Navigation Bar. The go to the Data Control palette and drag and drop the Empno attribute from the EmployeeVO1 node onto the form, and from the Context Menu select Child | Text Field. Repeat this step for each attribute of the EmployeeVO1 node. Now let's add a label for each text field to describe it. Go to the Component Palette, select the ADF Swing Controls library, and drag and drop a JULabel onto the form in front of the Empno textfield. Right-click on the JULabel and select Create Binding | Label For from the context menu in order to bind this control to metadata defined on the Business Component Entity Object. When the Attribute Binding Editor window is open, then go to the EmployeeVO1, and choose the Empno attribute (see Figure 35).Figure 35Now let's repeat this step for each attribute of the EmployeeVO1 node. It's remarkable to say that in the case of the Depno attribute, actually we don't want to display the department number, instead we want to display the department name using a combo box control which allows to select a from a list of department name. Drag and drop the Deptno attribute on EmployeeVO1 from the Data Control Palette onto the form and then choose Add Child | Combo box. If you run the application, you can see a list of department number. In order to bind the department number to department name, you need to set up the underlying binding. Go to the Applications Navigator window, and navigate to the EmployeeFormPageDef.xml and then go to the Structure window, and double-click on the EmployeeVO1Deptno node and the List Binding Editor appears. Select the Dynamic List option, then click on Add… button and inside the Add Data Source window, select the DepartmentVO1 node (see Figure 36).Figure 36Next, you have to map the attributes from the Base Data Source and the List Data Source. Finally, set the Display Attribute to Dept to DName (see Figure 37).Figure 37When you run this application which resembles as shown in Figure 38.Figure 38The last part of this solution is to show how to create a master/detail oriented form. The first step is to create a form to display department data along with the associated employees using the master/detail concepts related to data binding. This approach is similar to the previous data binding tasks, the only difference is that you will base the binding on the DepartmentVO1 and its inside view EmployeeVO2 (see Figure 39).Figure 39After the form is created, we drag and drop the DepartmentVO1 onto the form and select Add Edit Form from the context menu (see Figure 40).Figure 40Then, in order to add a child entity in this case the employees associated to their department (the parent), drag and drop the EmployeeVO2 inside the DepartmentVO1 node onto the form and select Add Child | Table from the context menu. In order to navigate inside the table as well, we need to drag and drop the EmployeeVO2 inside the DepartmentVO1 node onto the form and select Add Child | Navigation Bar. Now let's test the application and see how it resembles as shown in Figure 41.Figure 41As you can see the last column of the table (showing the department number) is displaying a number and not the department name. We can solve this problem like we did before. Right-click on the Table control and select ADFm Binding Properties and then the Table Binding Editor appears. Then go to the Attribute Properties tab and select the Deptno and map it to a combo box. Finally, click on the configuration button, and the Editor Properties appears (see Figure 42).Figure 42By clicking on Create button, the List Binding Editor window appears, and we can configure the same way as we did in the employee form (see Figure 43).Figure 43The final step is to deploy the solution to the production environment using a Java Archive file (JAR). To create JAR in JDeveloper, you have to go to the client_presentation project, right-click over it and choose New from the context menu. In the New Gallery window, go to the Deployment Profiles node and select JAR file (see Figure 44).Figure 44Then a new profile with the specified name is created on the project and you have to edit it to customize your deployment. In order to create the JAR file from this customized deployment, you go to the project, right-click on the deploy extension file inside the Resources folder and select Deploy to JAR file option (see Figure 45).Figure 45ConclusionIn this article, I explain how to create data binding oriented applications using Microsoft Visual Studio.NET and Oracle JDeveloper. You can compare both solutions and apply this techniques to your own business scenario.
|
http://www.c-sharpcorner.com/UploadFile/john_charles/DatabindingtechniquesusingVisualStudioNETandJDeveloper12082008120229PM/DatabindingtechniquesusingVisualStudioNETandJDeveloper.aspx
|
crawl-002
|
refinedweb
| 2,592
| 54.42
|
Sencha Touch 2.1.0 not loading on iOS?
Sencha Touch does not seem to fully load up on iOS (but works fine on my Android devices). Here's a few examples of namespaces that are undefined:
Ext.Msg
Ext.Viewport
Ext.plugin
I'm using Sencha Touch 2.1.0 commercial (Build date: 2012-11-05 22:31:29, 08c91901ae8449841ff23e5d3fb404d6128d3b0b) and PhoneGap 2.1.0.
The following is a super simple template that can be used to recreate the issue. I used weinre to inspect the app.
Code:
<!DOCTYPE HTML> <head> <script type="text/javascript" src="./sencha-touch-all.js"></script> <script src=""> <!-- weinre --> </script> <link rel="stylesheet" type="text/css" href="./sencha-touch.css"> </head> <body> </body> </html>
RS
- Join Date
- Mar 2007
- Location
- Gainesville, FL
- 38,458
- Vote Rating
- 1112
It's working for me. I don't have the <script> for the localhost script which if you are within PhoneGap I can see that thinking an issue with PhoneGap then? Sigh. Thanks for testing that.
RS
I have the same problem. Sencha Touch 2.1.0 Commercial, Safari 6.0.2, OSX 10.8.2, All caches emptied. Restarted Safari.
I am using Sencha provided example files and nothing loads. White blank page, no error messages in Inspector.
|
https://www.sencha.com/forum/showthread.php?249179
|
CC-MAIN-2015-32
|
refinedweb
| 212
| 79.97
|
structs - Struts
structs I am using structs dyanmic tags for the frontend development... criteria .I am using Hi friend,
Plz give full details.../struts/struts2/struts2controltags/iterator-tag.shtml
Thanks
develop structs application - Struts
visit to :
Thanks...develop structs application hi
i am new to structs,how to develop structs application in netbeans ide
i need step by step process
plz answer
hint:theritacle dought in structs - Struts
flow.
The ActionServlet is responsbile for looking up the struts-config.xml... of struts Framework.It is the main ControllerComponent Action class contain....
------------------------------------
Visit for more information.
structs - Struts
struts ssl login How to create struts ssl login
Structs jar files
Structs jar files please Post required jar files for structs.
Thanks,
L.Mahesh Kumar
<html:text structs - Struts
how can i display a value from database on jsp using struts form. the value should be populated on jsp load. can any body help me in this ....
regards
aftab
Can you give me some good factory pattern examples?
Can you give me some good factory pattern examples? HI,
I am... towards some of the examples that would we very helpful.
Thanks
Hello,
Here are some links that you will find helpful, they have good factory pattern
Which is the good website for struts 2 tutorials?
for learning Struts 2.
Suggest met the struts 2 tutorials good websites.
Thanks
Hi,
Rose India website is the good...Which is the good website for struts 2 tutorials? Hi,
After
automate mails in lotus notes
need to open up the Lotus Notes client from a JSP page..
Currently in the JSP...(Outlook.Application)
Could someone please help us with this as soon as possible.
The from... directly i need to open the lotus notes page.there are some methods like sendto
Need help in completing a complex program; Thanks a lot for your help
Need help in completing a complex program; Thanks a lot for your help Hi,
I am currently working on one program which works in this way.
1... it?
Thanks a ton for your help
J2me notes - MobileApplications
/
Thanks.
Amardeep
HOW TO BECOME A GOOD PROGRAMMER
HOW TO BECOME A GOOD PROGRAMMER I want to know how to become good...:
CoreJava Tutorials
Here you will get lot of examples with illustration where you can learn java easily and make a command over core java to proceed further.
Thanks
Struts - Struts
Struts Is Action class is thread safe in struts? if yes, how it is thread safe? if no, how to make it thread safe? Please give me with good...://
Thanks - Java Beginners
Thanks Hi,
Yur msg box coding is good
Thanks Hi
Thanks & Regards
struts
can easily learn the struts.
Thanks...struts how to start struts?
Hello Friend,
Please visit the following links:
thanks - Java Beginners
thanks Sir , i am very glad that u r helping me a lot in all these things.... i thank you whole heartedly for this....
i got the concept of the answers of my queries...but
the program regarding twin prime was not able Tutorials
used in your jsp-pages
Struts has been designed to give you modularity and loose...
Struts Tutorials
Struts Tutorials - Jakarta Struts Tutorial
This complete reference of Jakarta Struts shows you how to develop Struts
Good tutorials for beginners in Java
in details about good tutorials for beginners in Java with example?
Thanks.
...Good tutorials for beginners in Java Hi, I am beginners in Java....
Thanks
structs doubts
structs doubts i tried the fileupload program which is published in roseindia i am getting fileupload page after that when select any file to upload then i click upload i am getting following error
struts - Struts
/struts/
Thanks...struts hi,
what is meant by struts-config.xml and wht are the tags...
2. wht is the difference b/w the web.xml and struts-config.xml
3. what
Struts - Struts
Struts Hello
I like to make a registration form in struts inwhich... compelete code.
thanks Hi friend,
Please give details with full....
Latitude and Longitude of Virgin Islands (US)
Latitude and Longitude of Virgin Islands (US) Hi,
What is the Latitude and Longitude on Virgin Islands (US)?
Thanks
Hi,
Latitude... on Virgin Islands (US) in other units.
Thanks
Can you suggest any good book to learn struts
Can you suggest any good book to learn struts Can you suggest any good book to learn struts
Top 10 Tips for Good Website Design
Designing a good website as to come up with all round appreciation, traffic... presence. Good website design tips reflect on the art of mastering the traffic... by the webmaster. Good website design is a continuous process that needs you to evaluate
login application - Struts
login application Can anyone give me complete code of user login application using struts and database? Hello,
Here is good example... it at
Thanks
struts - Struts
class.It is having three values:
0- It does not give any debug information.
1....
Thanks
Struts Interceptors - Struts
Struts Interceptors Can any one give an full example of Custom Interceptors? Thanks in advance
struts validations - Struts
_struts_validator.shtml
Thanks...struts validations hi friends i an getting an error in tomcat while running the application in struts validations
the error in server internationalisation - Struts
to :
Thanks...struts internationalisation hi friends
i am doing struts iinternationalistaion in the site
Lotus notes - Hibernate
Lotus notes In Lotus notes to csv file conversion--> can we use two delimiters?
like
Struts
Struts Tell me good struts manual
Testing Struts Application
Testing Struts Application
It will be noticed that there are a lot of 'system.out.println's..., it
aids in diagnosis greatly.It also gives us a clear understanding Architecture - Struts
Struts Architecture
Hi Friends,
Can u give clear struts architecture with flow. Hi friend,
Struts is an open source.../StrutsArchitecture.shtml
Thanks - Framework
/struts/". Its a very good site to learn struts.
You dont need to be expert... knowledge of JSP-Servlet, nothing else.
Best of Luck for struts.
Thanks...Struts Good day to you Sir/madam,
How can i start Tag Lib - Struts
://
Thanks...Struts Tag Lib Hi
i am a beginner to struts. i dont have to understand the TagLib uri. Any body could you please give me some brief steps reg
Struts first example - Struts
the version of struts is used struts1/struts 2.
Thanks
Hi!
I am using struts 2 for work.
Thanks. Hi friend,
Please visit...Struts first example Hi!
I have field price.
I want to check
give the code for this ques///
give the code for this ques/// write a program in java in which there is a clss readline. the functionality of this class is to read a string from...+"!");
}
}
give the code for this ques///
give the code for this ques/// write a program in java which contains a class simple. this class contains 4 members variables namely a,b,c,and d...[]args){
Simple s=new Simple(0,0,0,0);
s.show();
}
}
Thanks
with good Struts skills also will learn how key Struts concepts relate to Spring..., using the Struts Portlet Framework
Having a good design... the lines of comparing Struts to JSF. I thought it would be a good idea to compare
MVC - Struts
MVC CAN ANYONE GIVE ME A REAL TIME IMPLEMENTATION OF M-V-C ARCHITECTURE WITH A SMALL EXAMPLE...... Hi friend,
Read for more information.
Thanks
struts tags
struts tags I want develop web pages using struts tags please help me,but i searched many sites but that sites doesn't give correct information.
examples of struts tags are
how to create modules i structs applications?
how to create modules i structs applications? how to create modules i structs applications
java - Struts
of questiond they may ask.i have scjp and scwcd and good knowledge in struts,hibernate...java good morning sir.i have completed my mca at 2009.now i want...:// Books
applications in J2EE. A lot of books have emerged to satisfy the appetite of avid Struts.... The book starts with an explanation of why Struts is a "good thing" and shows... (not as good but bigger) struts book and the two complement quite well. Go
validation - Struts
information,
Thanks...validation Hi,
Can you give me the instructions about validations on server side in struts.i have done client side validations for login
Struts - Framework
on struts visit to :
Thanks...Struts Good day to you Sir/madam,
How can i start struts application ?
Before that what kind of things necessary
Struts Book - Popular Struts Books
;
Jakarta Struts For Dummies
As a Web developer, you?ve probably heard a lot...
Struts Book - Popular Struts Books
Programming Jakarta Struts
As popular as the Struts Framework for building web applications
Struts
developers, and everyone between.
Thanks.
Hi friends,
Struts is a web... developers, and everyone between.
Thanks.
Hi friends,
Struts...Struts What is Struts?
Hi hriends,
Struts is a web page
Struts 2 online tutorial
Struts 2 online tutorial Where to learn struts 2 online tutorial? Is there any good tutorials on roseindia.net for learning struts 2 online tutorial... gives you the links of latest Struts tutorials.
Thanks
How to give the value - JSP-Servlet
How to give the value How to give the value in following query..
"select * from studentinformation where studentid = '?'";
How to give.../combo.jsp?cid="+cid);
}
--Please Select--
Highlight a corresponding table row - Struts
.
Hope this would give a clear picture:
Please help!!! Hi friend,
Plz give specification on technology you want and give full source code.
Thanks Hi,
The technology that i have used here is struts tags
Developing Struts Application
us first see the details of the entry for 'query form'.The
struts...Developing Struts Application
If we are asked to give a very brief
struts 2 problem with netbeans - Struts
struts 2 problem with netbeans i made 1 application in struts2... for namespace / and action name login.) is not available.
here give two code what...
please give me acton mapping problem solution
Hi Friend,
Please
turorials for struts - Struts
turorials for struts hi
till now i dont about STRUTS. so want beginers struts tutorials notes. pls do
config
/WEB-INF/struts-config.xml
1
action
*.do
Thanks...!
struts-config.xml...="add";
}
}
please give me correct answer .
Hi friend
java - Struts
in which i have to give an feature in which one can create a add project template... give me idea how to start with Hi Friend,
Please clarify what do you want in your project.
Do you want to work in java swing?
Thanks
java - Struts
java When i am using Combobox.
when i am selecting the particular value.
how can i pass the value to the action.
please give me the suggestion... visit to :
Thanks
java - Struts
java where can define it ,The method getParameter(String) is undefined for the type HttpServletRequest Hi friend,
Plz give...
Thanks
java - Struts
and password ,but when i submit the page ,i give blank page...
one hint: error... ,struts-config.xml,web.xml,login form ,success and failure page also...
code is given below;plse...slove my problem....ok..thanks
If possible ple send u r
Struts2 - Struts
.
thanks a lot.../struts/struts2/struts2uitags/autocompleter-example.shtml
Thanks. hi i
Using radio button in struts - Struts
single selection). Hi friend,
Please give full details and full source code to solve the problem :
For more information on radio in Struts...-tag.shtml
Thanks
|
http://roseindia.net/tutorialhelp/comment/1517
|
CC-MAIN-2014-41
|
refinedweb
| 1,894
| 67.76
|
Accessing query parameters using @QueryParam
By Naresh on Feb 13, 2009
In this entry, we will use the HelloWorldWebApp created in the previous entry. We will modify the resource, so that it takes name of a person as a query parameter and greets him/her. If no name is provided, it will give the general Hello World! message.
And here are the steps:
- Overwrite the previously implemented sayHello method with the following:
@GET
@Produces("text/plain")
public String sayHello(@QueryParam("name") String name) {
if (name != null) {
// if the query parameter "name" is there
return "Hello " + name + "!";
}
return "Hello World!";
}
- Import the class javax.ws.rs.QueryParam.
- Redeploy the application and enter in a browser. You will see that response Hello Rama!. If the query parameter name is not specified the response would be Hello World!.
So how does this work?
Here we are using a new annotation @QueryParam. It is an annotation provided by the JAX-RS API. This annotation takes care of mapping a query parameter in a request to a method parameter.
In this example, we have used this annotation to map the query parameter name to the method parameter name. When a request is sent for the resource with some query parameter value for name, it gets set to the method parameter. For this to happen, the query parameter needs to be mapped to the method parameter. This is done by prefixing the method parameter declaration with @QueryParam and specifying the query parameter name as a string parameter for the annotation. In our example, it is achieved by doing this:
public String sayHello(@QueryParam("name") String name) {
Hello
I use your example with glasfish but queryPram give me this error :
Exception in thread "main" java.lang.NoSuchMethodError: com.sun.jersey.api.client.WebResource.queryParam(Ljava/lang/String;Ljava/lang/String;)Lcom/sun/jersey/api/client/WebResource;
Can you help me ?
Thank's
Christian
Posted by christian vial on April 13, 2009 at 11:16 PM PDT #
Yup, like the last guy, there is no such method as queryParam in webResource???? GRRRRR!!!!!
Posted by Confused coder on May 07, 2009 at 09:23 PM PDT #
I mean queryParams
Posted by Confused coder on May 07, 2009 at 09:25 PM PDT #
Which version of Jersey are you using?
The latest version does have this method.
Posted by Naresh on June 28, 2009 at 09:29 PM PDT #
I enter and it returns Hello World! meaning that name is null. why? i'm using netbeans 6.8 and server.log shows "Running GlassFish Version: GlassFish v3 (build 74.2)"
Posted by Jonathan Benoit on June 11, 2010 at 11:18 AM PDT #
Hey Jon,
are you sure you redeployed the app? I guess you might have missed doing this.
Posted by Naresh on June 11, 2010 at 08:25 PM PDT #
Hi Naresh,
I did redeploy, multiple times. I've tried Clean & Build followed by deploy, that didn't help, still behaved same. This was on Windows. I just tried on Solaris using netbeans-6.8-ml-solaris-sparc.sh and it worked when i entered so looks like i've either got a platform problem on windows or more likely some environment hiccup. i'll revisit my windows setup and see if i can 'start-over' to get past this behavior. i'll post where i end up for completeness. thanks for the feedback.
Jon
Posted by Jonathan Benoit on June 14, 2010 at 02:27 AM PDT #
Jon,
as you said, probably you might be you are hitting a platform specific issue with one of NetBeans/GlassFish/Jersey. Probably, you need to check with the Jersey user alias.
Posted by Naresh on June 14, 2010 at 03:24 AM PDT #
Following your TOI links, I first did [1] then i did steps in [2] followed by steps in this blog entry that i'm commenting on, namely [3]
[2] says:
\* Modify the @Path annotation given above the HelloResource class as follows:
@Path("hello/{name}")
public class HelloResource {
[2] works fine. next i move on and test [3]. i'm using project from previous example, namely [1] but it has been modified according to steps in [2] as described above. [3] says to modify method to use :
public String sayHello(@QueryParam("name") String name) {
instead of
public String sayHello(@PathParam ("name") String name) {
so when i access url listed in [3] () it won't work, instead i get :
HTTP Status 404 -
type Status report
descriptionThe requested resource () is not available.
This happens on Solaris and windows. If I change the @Path annotation for the HelloResource class as follows:
@Path("hello/{name}")
public class HelloResource {
back to:
@Path("hello")
public class HelloResource {
then url used in [3] works. Seems you have to reset project back to initial state as described in [1], before doing steps in [3]. If I do steps in [2] before [3], and I don't revert @Path annotation declaration, then it errors as described. Should you be allowed to change:
@Path("hello")
to:
@Path("hello/{name}")
and use :
public String sayHello(@QueryParam("name") String name) {
with:
Posted by Jonathan Benoit on June 16, 2010 at 05:55 AM PDT #
If I use:
@Path("hello")
public class HelloResource {
with
public String sayHello(@PathParam("name") String name) {
and access url
then i see just:
Hello World!
for method defined as:
@GET
@Produces("text/plain")
public String sayHello(@PathParam("name") String name) {
if (name != null) {
// if the query parameter "name" is there
return "Hello " + name + "!";
}
return "Hello World!";
}
which means name is equal to null.
If I just change sayHello method to use @QueryParam instead of @PathParam as:
public String sayHello(@QueryParam("name") String name) {
and access url
then I see:
Hello Jonathan!
which mean name is not equal null.
Lastly if i next change
@Path("hello")
public class HelloResource {
to:
@Path("hello/{name}")
public class HelloResource {
and use:
public String sayHello(@QueryParam("name") String name) {
accessed via url:
i encounter :
HTTP Status 404 -
type Status report
descriptionThe requested resource () is not available.
Is this all expected behavior?
Posted by Jonathan Benoit on June 16, 2010 at 07:03 AM PDT #
Jon,
yes the observations that you have made in the two earlier comments are correct.
1. As you mentioned in the previous comment, you would have to reset the project to the state it was in [1] before you can exercise [3], i.e., resent the @Path annotation at the HelloResource class from @Path("hello/{name}") to @Path("hello"). I should have mentioned this in the blog entry, sorry for the inconvenience.
2. As for your previous comment, here's what is happening:
@Path("hello")
public class HelloResource {
public String sayHello(@PathParam("name") String name) { ... }
}
When you access- you would get "Hello World!" since you are passing the name as query parameter and not as a path parameter, i.e., not as "/hello/Jonathan". Hence the path parameter is evaluated as null, and you get the "Hello World" instead of "Hello Jonathan".
So the mantra is-
if you try to access a variable "name" as path parameter, then you need to set the path as @Path("/hello/{name}"). However, if you want to access it as a query parameter, set it as query parameter in your request URL and change the path to @Path("/hello") and in your resource method fetch it using the @QueryParam annotation.
Posted by Naresh on June 16, 2010 at 02:02 PM PDT #
Hello, I want to know if the name is not ASCII char, how could we get the right string by using @QueryParam. Such like chinese char你好
seems @QueryParam could not set the decoding charset.
Posted by kevin_LV on September 15, 2010 at 08:24 PM PDT #
Kevin,
sorry I do not have much information regarding this particular use-case.
Probably, you should post it at the Jersey users mailing list, users@jersey.dev.java.net.
You can most likely get a solution to this problem there.
Posted by Naresh on September 15, 2010 at 10:37 PM PDT #
|
https://blogs.oracle.com/naresh/entry/accessing_query_parameters_using_queryparam
|
CC-MAIN-2015-40
|
refinedweb
| 1,339
| 63.09
|
packages get
Alternatively, your editor might support
flutter packages get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:flutter_location_plugin/flutter_location_plugin.dart';
We analyzed this package on Jan 15, does not exists. (-20 points)
We were unable to access at the time of the analysis.
Documentation URL is not helpful. (-10 points)
Update the
documentation property: Create a website about the package or remove the
documentation key.
Package is pre-v0.1 release. (-10 points)
While there is nothing inherently wrong with versions of
0.0.*, it usually means that the author is still experimenting with the general direction of the API.
|
https://pub.dartlang.org/packages/flutter_location_plugin
|
CC-MAIN-2019-04
|
refinedweb
| 112
| 52.26
|
Running Local GPUs in Keras
Machine Learning and Artificial Intelligence have made data analysis very easy. Almost all the big IT firms nowadays use AI or ML in some way or the other. Data is the fuel of the 21st century. The main problem beginners face while working with neural networks or any other algorithm is handling data.
Training your model on Huge Data sets can take a lot of time. Clearly, we need methods to train models at a faster speed. In this tutorial, we will learn how to use the Graphics Processing Unit, or GPU on our local machines with TensorFlow.
In this tutorial, we are going to see how we can run local GPU in Keras.
CPU vs GPU
Modern PCs along with the main CPU, also have a GPU, generally. Unlike CPUs, GPUs can perform thousands of operations at once. GPUs, although developed back in 1999, has gained importance just recently. Algorithms like Image recognition need very huge datasets. For example, suppose there are 1 million images in a data set. A CPU can take more than 48 hours to just train this. Whereas a GPU might be able to do it in less than 24 hours.
Undoubtedly GPUs have become very important for modern-day computing. Moreover, we can use these units on our local machines easily. To test if your machine can run GPUs:
- You should have Tensorflow Installed
- Install Anaconda and type “conda install keras-gpu”
- Use Google Colab if you have a good internet connection.
In addition to this you should run the following code:
import tensorflow as tf from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) #Check if GPU is visible to keras from keras import backend as K K.tensorflow_backend._get_available_gpus()
Finally, you will have this output:
You can see that the machine is running on “XLA_GPU” on Tesla K80 Computer. Keep in mind that GPUs can only be used with NVIDIA, and not with AMD. You need to add the following code if you are working on a local machine:
import keras #Assuming you have a 48 core CPU config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 48} ) sess = tf.Session(config=config) keras.backend.set_session(sess)
Tensor Processing Units
In addition to GPUs, models can also be trained on TPUs. This hardware accelerator was developed by Google. Without a doubt, these are the fastest circuits for neural network machine learning. To get started with Neural networks you can check out: Convolutional Neural Networks Using Keras.
Undoubtedly, TPUs have the highest rate of Data Transfer. They have a speed ranging from 180 to 240 Tera Flops. Does this mean they would perform best in any data set? They have the highest performance with large batches and CNNs. TPUs can be used in Google Colab by Changing Runtime type.
Differing from TPUs, it has been observed that GPUs show better flexibility and better performance for irregular computations. For Recurrent Neural Networks, CPUs show the best performance. Thus every platform has advantages based on the model characteristics.
If you have any doubt, you can ask in the comments section.
Machine learning is ❤️
|
https://valueml.com/running-local-gpus-in-keras/
|
CC-MAIN-2021-25
|
refinedweb
| 521
| 66.74
|
Mono-Repo Build With Gradle
Mono-Repo Build With Gradle
Want to learn more about the mono-repo build? Check out this post where we address challenges with the synchronization amongst builds in Gradle.
Join the DZone community and get the full member experience.Join For Free
Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.
Sometimes, we are faced with a project that is both open source and part proprietary. Here’s how I address the challenges of synchronization amongst builds.
When faced with a partly open-source and partly closed-source project, it is common to use a Git sub-tree to synchronize them. The open-source project is added in a folder of the closed-source project, and all development happens in that root project (alias the mono-repo). On top of that, we want our build tool to handle the sub-tree project as it is a part of the mono-repo.
This is the tricky part, as the sub-tree must be buildable and must be buildable from the mono-repo. In cases of multi-module projects, we also want to express dependencies between modules of those projects and have our IDE detect those dependencies.
One solution is provided by Gradle: it is called includeBuild. This solution works great but has a few drawbacks for this use case.
Problem With includeBuild
When using the
includeBuild method, if you run a gradle test at the root of the project, it will run tests only on projects "natively" in the root project. This can be all right when you only need to include libraries with their own life cycle, but in our use case, we want to have a single task to build and test everything.
With
includeBuild, we would have:
$ gradle run > Task :other-module:run com project: Hello World
Even if we have a task named run in one module of the sub-tree, only the task from module "natively" in the root is ran.
With our approach, all tasks with the given name will be launched.
$ gradle run > Task :other-module:run com project: Hello World > Task :my-project:module-b:run oss project: Hello World
You can check out the code from this example project on GitHub.
How it Works
The main idea is to include the settings.gradle of the sub-tree in the mono-repo project. However, in order to keep the name constant when declaring dependencies, we must play a little bit with the paths of the projects.
Setting Up the Sub-Tree
The sub-tree does not declare its projects in settings.gradle but in the other file; here it is oss-settings.gradle.
All declared projects are children of a new root project — here, :my-project and this project are also included.
The settings.gradle imports this file and changes the paths:
apply from: ‘oss-settings.gradle’ def fixPath fixPath = { project -> String relativeProjectPath = project.projectDir.path.replace(settingsDir.path, “”) project.projectDir = new File(relativeProjectPath.replace(“/my-project/”, ‘’)) project.children.each fixPath } rootProject.children.each fixPath
Dependencies between modules can be expressed as usual but it must include this new root project.
dependencies { compile project(‘:my-project:module-a’) }
Setting up the Mono-Repo
Once the sub-tree itself is set up, a few tweaks must be made to the mono-repo project.
Settings.gradle must apply the oss-settings.gradle, set the path correctly, include the root project of the sub-tree, and then add its own projects as usual.
apply from: ‘sub-tree/oss-settings.gradle’ def fixPath fix’
def fixPathfix’
Results
In this example project, running the run task in the sub-tree directory gives:
$ gradle run > Task :my-project:run oss project: Hello World
And, running the same task in the mono-repo gives us:
$ gradle run > Task :other-module:run com project: Hello World > Task :my-project:module-b:run oss project: Hello World
Plugins Sharing
We often use custom plugins directly in the
buildSrc to share build logic. This behavior can be kept using the following method.
In the sub-tree project, add your
buildSrc directory and add an extra build file to declare the plugin:
apply plugin: ‘groovy’ apply plugin: ‘java-gradle-plugin’ gradlePlugin { plugins { ossPlugin { id = “oss-plugin” implementationClass = “OSSPlugin” } } }
In the mono-repo, the
buildSrc project must include this project as a runtime dependency
build.gradle:
dependencies { runtime subprojects }
settings.gradle:
include ‘:oss-buildSrc’ project(‘:oss-buildSrc’).projectDir = “$rootDir/../sub-tree/buildSrc” as File
With this technique, plugins from the plugins of the sub-tree project can be used in the mono-repo projects, and the mono-repo can declare its own plugins.
When running the tasks from the sub-tree:
> Task :my-project:module-b:customOSSTask OSSPlugin is applied
When running the tasks from mono-repo:
> Task :other-module:customComTask ComPlugin is applied > Task :other-module:customOSSTask OSSPlugin is applied > Task :my-project:module-b:customOSSTask OSSPlugin is applied
Conclusion
This is the solution I found to handle this kind of use case. If you have encountered similar situations, I’d be very interested to know how you handled these kinds of issues. Feel free to let me know what you think in the comments below.
Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat.
Published at DZone with permission of Baptiste Mesta . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/mono-repo-build-with-gradle?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fjava
|
CC-MAIN-2018-51
|
refinedweb
| 932
| 54.22
|
Posted by: Sue Loh
No, no, no, before you even say it, I'm not writing this in response to any of Jack Crenshaw's columns. Actually this time it's more to augment them. You see his columns do make one very true point (more than one, but only one I'm commenting on here): People who call GetTickCount, such a trivial function at first glance, sometimes use it wrong. Because it's not quite as trivial as people take it for.
And actually for this post I owe the content to Sergio Cherskov, who is also on the Windows CE team. It seems Sergio is a bit of a guardian angel, and keeps an eye out for improper usages of this API within our team. Separately we've been discussing how to do this in a more automated fashion, but that's not trivial either. Anyway Sergio wanted to share some tips for using GetTickCount. He's also working to get this called out more explicitly in our documentation. The remainder of this post is his:
Can you please follow-up with another blog “addition” for GetTickCount() and truly explain the way we want EVERYONE (including our internal developers) to use this function.
Basically, the subtraction ALWAYS works, even if the rollover occurred, and ALWAYS gives the correct difference and number of clock ticks passed between two tick values. The return value is unsigned integer (DWORD) and that’s what gives it that nice property. What does NOT work is COMPARING tick values directly – one should always compare ONLY the differences. If developer sticks with comparing differences and is able to service difference before second rollover (i.e. before another 49.7 days come up), everything should be fine.
Sooo, here’s the code that ALWAYS works, even in the presence of the rollover (subtraction math still works, i.e. 0 – (-1) = 0 + 1 = 1 which in unsigned math amounts to pretty much the same thing: 0x000000 – 0xffffffff = 1.)
#define DELTA_TICKS some_value_here
// initialized somewhere in the code
DWORD dwStartTick = GetTickCount();
DWORD dwEndTick = GetTickCount() + DELTA_TICKS;
// fails at rollover (note, this was Sue’s sample)
BOOL bad_fn_comparing_direct_tick_values()
{
if ( GetTickCount() > dwEndTick )
return ( TRUE);
return (FALSE);
}
// ALWAYS works (we need a sample code like this evangelized to everyone)
BOOL good_fn_compares_tick_differences()
{
if ( (GetTickCount() – dwStartTick) > DELTA_TICKS)
return ( TRUE);
return (FALSE);
}
|
http://blogs.msdn.com/b/ce_base/archive/2005/06/08/426762.aspx
|
CC-MAIN-2015-35
|
refinedweb
| 386
| 60.14
|
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
International Gita Society The lesser known Anu-Gita is a part of the Ashwamedha Parva in the magnum opus Mahabharata and is a refresher and an add on to the teachings of the Bhagavad Gita. CHAPTER I Janamejaya said: What conversation, O twice-born one! took place between the high-souled Kesava and Arjuna, while they dwelt in that palace Arjuna, the son of Pându, having surveyed with delight that lovely palace, in the company of Krishna, spoke these words: ‘O you of mighty arms! O you whose mother is Devakî! When the battle was about to commence, I became aware of your greatness, and that divine form of yours. But that, O Kesava! which through affection (for me) you explained before, Arjuna. Vâsudeva said: From me, O son of Prithâ! you heard a mystery, and learnt about the eternal (principle), about piety in (its true) form, and about all the everlasting worlds. The Brâhmana said: O Krishna! O destroyer of Madhu! I will explain to you accurately what you, out of compassion for (all) beings, have asked me touching the duties (to be Performed) for final emancipation. It is destructive of delusion, O Lord! Listen to me with attention, as I relate it, O Mâdhava! A certain Brâhmana named Kâsyapa, who had performed (much) penance, and who best
understood piety, approached a certain twice-born (person), who had learnt the Scriptures relating to (all) duties, having heard (of him, as one) who had over and over again gone through all knowledge and experience about coming and going, who was well versed in the true nature of all worlds, who knew about happiness and misery, who knew the truth about birth and death, who was conversant with merit and sin, who perceived the migrations of embodied (souls) of high and low (degrees) in consequence of (their) actions, who moved about like an emancipated being, who had reached perfection, who was tranquil, whose senses were restrained, who was illumined with the Brahmic splendor, who moved about in every direction, who understood concealed movements, who was going in company of invisible Siddhas and celestial singers, marvelous man, the best of the twice-born, Kâsyapa, pleased the preceptor by his great devotion. That was all appropriate, (being) joined to sacred learning and correct conduct. And, O terror of your foes! he pleased that (being) by (his purity of) heart and behavior (suitable) towards a preceptor. Then being satisfied and pleased, he spoke to the pupil these words, referring to the highest perfection: Hear (them) from me, O Janârdana! The Siddha said: Mortals, O dear friend! by their actions which are (of) mixed (character), or which are meritorious and pure, attain to this world as the goal, or to residence in the world of the gods. Nowhere is there everlasting happiness; nowhere eternal residence. Over and over again is there a downfall from a high position attained with difficulty. Overcome by lust and anger, and deluded by desire, I fell into uncomfortable and harassing states (of life), in-consequence of (my) committing sin. Again and again death, and again and again birth.. I also suffered much from old age, continual ailments, and numerous misfortunes flowing from the pairs of opposites. Then on one occasion, being much afflicted with misery, I abandoned the whole course of worldly life, through indifference (to worldly objects), al, taking refuge with the formless (principle). Having learnt about this path in this world, I exercised myself (in it), and hence, through favor of the self, have I acquired this perfection. I shall not come here again; I am surveying the worlds, and the happy migrations of (my) self from the creation of beings to (my attaining) perfection. Thus, O best of the twice-born! have I obtained this highest perfection. From here I go to the next (world), and from there again to the still higher (world) – the imperceptible seat of the Brahman. Have no doubt on that, O terror of your foes! this hint to you. I am exceedingly pleased, O clever one! with your good conduct. Put (your) questions without uneasiness, I will tell (you) whatever you desire. I highly esteem your intelligence, and greatly respect it, inasmuch as you have made me out; for, O Kâsyapa! you are (a) talented (man).
CHAPTER II Vâsudeva? And how, being freed from the body, does he attain to the). The Siddha said: When those actions, productive of long life and fame, which a man performs here, are entirely exhausted, after his assumption of another body, he performs (actions of an) opposite character, his self being overcome at the exhaustion of life. And his ruin being impending, his understanding goes astray. Not knowing his own constitution, and strength, and likewise the (proper) season, the man not being self-controlled, does unseasonably what is injurious to himself. When he attaches himself to numerous very harassing (actions); eats too much, or does not eat at all; when he takes bad food, or meat,); or takes juicy food; or sleeps by day; or (takes food) not thoroughly prepared; (such a man) himself aggravates the disorders orders (in the body) when the time comes. By aggravating the disorders (in) his own (body), he contracts a disease which ends in death, or he even engages in unreasonable (acts), such as hanging (oneself). From these causes, the living body of that creature then perishes. Learn about that correctly as I am about to state it. Heat being kindled in the body, and being urged by a sharp wind, pervades the whole frame, and, verily, checks the (movements of all the) life-winds. Know this truly, that excessively powerful heat, if kindled in the body, bursts open the vital parts-the seats of the Soul.born! are seen abandoning (their) bodies; or entering the womb on the exhaustion of (their previous) actions. Again, a man suffers similar torments, having his joints broken and suffering from cold, in consequence of water. As the compact association of the five elements is broken up, the wind in the body, distributed within the five elements, between the upward and downward life-winds, being aggravated by cold, and urged by a sharp wind, goes upwards, abandoning the embodied (self) in consequence of pain. Thus it leaves the body, which appears devoid of breath. Then devoid of warmth, devoid of breath, devoid of beauty, and with consciousness destroyed, the man, being abandoned by the Brahman, is said to be dead. (Then) he ceases to perceive (anything) with those very currents with which the supporter of the body perceives objects of sense. In the same way, it is the eternal soul which
preserves in the body the life-winds which are produced from food. Whatever (part of the body) is employed in the collection of that, know that to be a vital part, for thus it is seen (laid down) in the Scriptures. Those vital parts being wounded, that (wind) directly comes out there from, and entering the bosom of a creature obstructs the heart. Then the possessor of consciousness knows nothing. Having his knowledge enveloped by darkness, while the vitals are still enveloped, the soul,. Its three descriptions of seats are here learnt from the Scriptures. This world is the world of actions, where creatures dwell. All embodied (selves), dwell, and which I shall describe truly. Hearing this, you will learn the highest knowledge, and decision regarding action. All (the worlds in) the forms of stars, and this lunar sphere, and also this solar sphere which shines in the world by its own luster, know these to be the seats of men who perform meritorious actions. All these, verily, fall down again and again in consequence of the exhaustion of their actions. And there, too, in heaven, there are differences of low, high, and middling. Nor, even there, is there satisfaction, (even) after a sight of most magnificent splendor. Thus have I stated to you these seats distinctly. I will after this (proceed to) state to you the production of the fetus. And, O twice-born one! hear that attentively from me as I state it. CHAPTER III There is no destruction here of actions good or not good. Coming to one body after another they become ripened in their respective ways. As a fruitful (tree) producing fruit may yield much fruit, so does merit performed with a pure mind become expanded. Sin, too, performed with a sinful mind, is similarly (expanded). For the self engages in action, putting forward this mind. And now further, hear how a man, overwhelmed with action, and enveloped in desire and anger, enters a womb. Within the womb of a woman, (he) obtains-as the result of action a body good or else bad, made up of virile semen and blood. Owing to (his) subtlety and imperceptibility, though he obtains a body appertaining to the Brahman, he is not attached anywhere; hence is he the eternal Brahman. That is the seed of all beings; by that all creatures exist. That soul, entering all the limbs of the fetus, part by part, and dwelling in the seat of the life-wind, supports (them) with the mind. Then the fetus, becoming possessed of consciousness, moves about its limbs. As liquefied iron being poured out assumes the form of the image, such you must know is the entrance of the soul into the fetus. As fire entering a ball of iron, heats it, such too, you must understand, is the manifestation of the soul in the fetus. And as a blazing lamp shines in a house, even so does consciousness light up bodies. And whatever action he performs, whether good or bad, everything done in a former body must necessarily be enjoyed (or suffered). Then that is exhausted, and again other (action) is accumulated, so long as the piety which dwells in the practice of concentration of mind for final emancipation has not been learnt. As to that, O best (of men)! I will tell you about that
Such is the ancient (tradition) heard (by us). but the other is immortal and indestructible. which protects people to eternity. by which all this is pervaded. wealth. and causing good to be done. who has abandoned piety. and absence of cruelty. and also tranquility.action by which. self-restraint. and likewise pleasure and pain. He who has no enemy. released from everything. who contemns no one. he is. becomes happy. is released who is equable towards both life and death. And that I shall now proceed to state. abandoning each previous (element). who has subdued his senses. But the devotee who is released is esteemed higher than these. not acting dishonestly even in thought towards (any) being in this world. Brahman. pity. sees one (principle of) consciousness in all beings possessed of consciousness. refraining from the appropriation of the wealth of others. one going the round of various births. verily. And as regards that. and which is known in the world as the highest. A man who is a friend of all. And Prajâpati. moving and fixed. adherence to prescribed regulations. who has no child. takes place after a long time. too. who is devoted to tranquility. For the deliverance from the course of worldly life of the man who acts piously and well. and from whom fear and wrath have departed. restraint of the senses. CHAPTER IV He who becoming placid. like (what may be said by) any talented person who has in a former birth perceived the self. may become absorbed in the one receptacle. he becomes indifferent to everything. From this is produced piety. Thus one should look (for it) among the good. a pair separately for each (species). and lust altogether. and (a rule) about migrations among (various) creatures. He who moves among all beings as if they were like himself. pure. What I say is all correct and proper. free from vanity and egoism. which I am now about to declare. (having) as regards the moving (creation). and about the return. is released. indeed. never comes to an evil end. who is free from the pairs of opposites. constant restraint of the organs. who has no kinsmen. who endures all. points out (what) piety (is). By this are people held in check from making a slip in the paths of piety. and whose self is free from affections. and (what is) agreeable and odious. He who acquires that. honoring preceptors. which is very difficult to cross. created the whole of the three worlds. the material cause of all embodied (selves). created all creatures and (all) the fixed entities. The practice to which the good adhere. O best (of men)! I will give you accurate instruction concerning it. And that is the sole cause by which he comes here (in a) degraded (form). the grandfather of all people. Learn from me exhaustively. He who understands the Pradhâna. From that he created the Pradhâna. he will cross beyond (all) bonds. (though) attacked by birth and death and disease. honoring deities and guests. released in every way. who is self-controlled. he is. life as a Brahmachârin. And among them dwells that (course of) action which constitutes eternal piety. who had been first created. This is what is called the destructible. Gifts. whose self is tranquillized by the exhaustion of the primary elements of the . indeed. and thinking of naught. Thus a creature always meets with (the effects of) the action performed (in a) previous (life). He who properly perceives pleasure and pain to be inconstant. the body to be an unholy aggregate. having made a body for himself. penance. the grandsire fixed a limit of time. he will cross beyond the fearful ocean of worldly life. compassion to (all) beings. O Brâhmana! the excellent knowledge concerning the eternal imperishable seat. and ruin to be connected with action. There is in the world a doubt as to what originally was the source from which he became invested with a body. who casts off (the merit or sin) previously accumulated. and who is self-possessed. purity. this is said to be the conduct of the good. and who remembers that whatever little there is of happiness is all misery. And he. and who has no desire. Then seeking after the supreme seat. is released. serving mother and father. and gain and loss. as he should act. for among them it constantly abides. He who is not pious and not impious. He who is not attached to any one.
than which there is nothing higher. Then freed from all impressions. Learn from me the paths by which one directing the self within the self perceives the eternal (principle). he sleeps at ease. indestructible. devoid of qualities. who is free from attachment. he is indeed released. then he forthwith ceases to feel any attachment to Indra himself. which consist in pain and grief. As a person having seen one in a dream. when (all) beings are afflicted. and casting aside old age and death. he is not afflicted by anything. nothing can be seen anywhere in the world happier than he. Abandoning by the understanding all fancies bodily and mental. seeing the self in the self by means of the mind. saying. He obtains various bodies as he pleases. When. I will impart instruction regarding it accurately. looks on this universe as transient. and of a tranquil mind. and who is free from the pairs of opposites. then there is no ruler over him. When (all) beings are destroyed. Leaving this human frame. like fire devoid of fuel. (and which teaches) how devotees concentrating (their minds) perceive the perfect self. Properly concentrating his self. Being self-restrained and self-possessed. should act on (the precepts of) the science of concentration of mind. void of color. so does a devotee see the self extracted from the body. searching for his own faults. Weapons do not pierce him. always full of birth. who is constantly practicing concentration of mind. meditating in that habitation. who has practiced penance. one should fix the mind on the self. he assumes bodies at pleasure. tranquil. he attains to the eternal Supreme Brahman. The body is called the Muñga. after extracting them from the Muñga. constant. If such a good man is able to concentrate the self on the self. and old age. and having no cause.. and always concentrating his mind.’ so does one who has achieved proper concentration of mind perceive the self. He who is free from all impressions. When an embodied (self) properly perceives the self concentrated. void of touch. he perceives the perfect one. void of sound. he who has achieved proper concentration of mind sees the self in the self. and having his senses subjugated. and unknowable. ‘This is he. unmoving. he attains to the inexhaustible Brahman. Restraining the senses. Now listen how one habituated to exclusive meditation attains concentration. like an Aswattha tree. void of taste. creates for himself even the divinity of the gods. After this I shall explain the science of concentration of mind. Thinking of a quarter seen before. But one who is practicing concentration should never become despondent. void of belongings. One who does no action. and abandoning the transient body. being habituated to exclusive meditation. free from the pairs of opposites. he procures the release of his self from bonds in no long time. he should practice concentration of mind for final emancipation. death. then he. he grieves not and exults not. He who sees the enjoyer of the qualities. he gradually obtains tranquility. he has no fear. the soft fibers stand for the self. The man who has acquired concentration of mind. recognizes him (afterwards). Then the talented Brâhmana. and who moves among the collection of organs with penance. he remains steady to the self. He whose self is concentrated. devoid of the qualities of the five elements. his mind should not in anyway wander outside. he should steady his mind within and not out of the city in which he dwells. This is the excellent illustration propounded by those who understand concentration of mind. Restraining the . since he is the lord of the triple world. And as one may show the soft fibers. he should place his mind both in its external and internal (operations) in that habitation in which he dwells. and having first performed rigorous penance. without belongings. When one who has properly achieved concentration perceives the self in the self. and who is self-restrained. and freed from old age and grief. perceives the self in the self. is released.body. is released. Seeing the self void of smell. is not shaken by the fearful effects of attachment and affection. and who has no desire. devoid of form. there is no death for him. he is released. Remaining within (that) city. Having his understanding always (fixed) upon indifference to worldly objects.
This whole mystery I have declared to you. O son of Prithâ! that this is not easily understood by a man who is confused. and faces on all sides. and likewise the seat of the heart. too. and the fruit of its full accomplishment. Only by the mind (used) as a lamp is the great self perceived. – went away as he pleased. even those who are of sinful birth. or who has not acquired knowledge with his inmost soul purified. He has hands and feet on all sides. so placing one’s mind in one’s body. And the gods are not pleased with a cessation of the mortal form. and abandoning his body. Vaisyas. and also the means for its acquisition. forsaking the body. O destroyer of Madhu! having been thug instructed by me. It is my belief. ‘O you of mighty arms! O restrainer of (your) foes! according to what (I had) heard. He should meditate on his teeth. Nor is it easily to be understood by (one whose) internal self (is) confused. dwelling in the self? And how does the soul moving about carry the body? And of what color and of what description (is it when) he leaves it? O sinless venerable sir! be pleased to state this accurately to me. O Brâhmana! according to your pleasure. neck. sitting in the chariot you heard this same (instruction). and muscles. I will go away. and (keeping) the passages confined. possessed of great penance. O Mâdhava! I replied. O son of Prithâ! these good words relating to the piety (required) for final emancipation. a mental smile. he should meditate on the perfect one within his body with a mind fixed on one point. That talented pupil. What I have spoken. As one placing any property in his store-room should fix his mind on the property. and how also to blood? And how. Being thus always assiduous and pleased in the self.’ Thus addressed by me. that best of Brâhmanas disappeared then and there. and throat likewise. he has eyes. does the strength develop? (And how is it also) about the removal of non-nutritive (substances). The world of the gods. do the flesh. final emancipation. nor by any of the senses. – with. distinctly? How. tongue. and determination regarding . ‘How does this food eaten from time to time become digested in the stomach? How does it turn to juice. The soul sees the self come out from the body. O son of Prithâ! with a mind (fixed) on (this) one point only? For on that occasion. Vâsudeva said: Having spoken to me. Adopting this doctrine. women. too. and also the heart. and Sûdras likewise. he perceives the self. heads. O chief of the descendants of Bharata! is a great mystery (even) among the gods. he attains in a short time to that Brahman. O sinless one! there is no other man than you worthy to hear it. and of the excretions. O Krishna! that pupil. too. For as to that eternal Brahman. O best of Brâhmanas! I will now take my leave. which is difficult to explain. He is not to be grasped by the eye. – that Brâhmana of rigid vows. What then (need be said of) Brâhmanas.group of the senses. in a forest free from noises and unpeopled. and bones – which all (form) the bodies for embodied (selves) – develop in a woman as that (self) develops? How. who are constantly intent on their own duties. Have you listened to this. O son of Prithâ! or well-read Kshatriyas. O son of Prithâ! that is the highest goal. attain the supreme goal. O son of Prithâ! For. And it has never yet been heard by any man in this world. where one. as it were. after perceiving which he understands the Pradhâna. he has cars on all sides. too. O son of Kuntî! is filled by those who perform actions. he attains final emancipation in me. he stands pervading everything in the world. proceeded further to interrogate (me) about the piety (required) for final emancipation. and marrow. and whose highest goal is the world of the Brahman? This has been stated with reasons. And then depending upon it thus. one should there look for the self and avoid heedlessness. reaches immortality and is ever happy. palate.’ Thus questioned by that Brâhmana. – holding it to be the immaculate Brahman. does he breathe inwards or outwards? And what place does the self occupy. and do you (too) go away.
and between the Prâna and the Apâna dwells the Udâna pervading (all). And therefore those who study the Brahman engage in penance of which I am the goal. and also that which is to be thought of. casts aside as unsubstantial the (whole) substance of this world. that which is to be seen. A Brâhmana’s wife. and is entirely beyond the senses of hearing. that which sees. depending on you as (my) husband. by act. that which is to be seen. but is to be apprehended by the mind. O son of Prithâ! who practices concentration of mind constantly throughout six months. there is nothing further than this. and likewise that which is to be heard. and on which it rests. that which touches. (It is that) from which (this whole) expanse (of the universe) proceeds. good or bad. (the seat) for which Brahman and others concentrating (their minds) worship that indestructible (principle). are destroyed by demons. Whatever action there is. The mortal. that which is to be touched. That is called the Udâna. and not to be tasted by the tongue. Concentration of mind comes to him. he forthwith attains the highest goal by these means. produce them in their wombs. and energetic. devoid of color and sound. seeing the Brâhmana her husband. blazes the Vaisvâna fire sevenfold. that can be caught (by the touch). spoke to him (thus): ‘What world. and the skin. seated in seclusion. and Udâna also proceed. (in the form of) a dialogue. CHAPTER V On this. the mind and the understanding. and into it they enter. Apâna. possessed of talents. and likewise that which is to . When that is asleep. that which is to be smelt. That which is to be smelt. It is not to be smelt by the nose. It is not to be touched by the sense of touch. O son of Prithâ! between a husband and wife. you who live renouncing (all) action. shall I reach. which occurred. that man of a tranquil self. That which smells. devoid of taste and touch. While the paths (of action). It is devoid of smell. or seen. In the interior. and who are harsh and undiscerning. does exist among (all) beings. From birth to the destruction of the body. who had gone through all knowledge and experience. that which is to be drunk. Samâna. that which cats. O chief of the descendants of Bharata! they relate this ancient story. and that which understands. O chief of the descendants of Bharata! there can be no other happiness beyond this. and that which is to be understood. The nose. We have heard that wives attain to the worlds acquired by (their) husbands. Vyâna. and the moon together with the fire. and their selves tranquil. From this the Prâna. having got you for my husband?’ Thus addressed. spoke to her with a slight smile: ‘O beautiful one! O sinless one! I am not offended at these words of yours. too. and the tongue. And mark this always.misery. and (observe) good vows. in which the materials are visible. the Prâna and the Apâna moved. that which thinks. or heard. that which is to be touched. in the midst of all these (life-winds) which move about in the body and swallow up one another. full of faith. these are the seven tongues of the blaze of Vaisvânara. And freedom from action is not to be attained in this world even for an instant. upholding (all) beings (as) the mover of the intellectual principle. as the life-winds are controlled (by it). verily. Those who are devoid of knowledge only lodge delusion in themselves by means of action. that only do the men of action engage in as action. O beautiful one! The learned sacrificers throwing (in) due (form) the seven offerings into the seven fires in seven ways. It cannot be conquered by the eyes. This is all that is to be said. (namely). and for which learned men have their senses restrained. these are the seven great officiating priests. and that which hears as the fifth. the Samâna and Vyâna also are absorbed. action. that which is to be drunk. and imperishable. indeed. those are the seven (kinds of) fuel for me. What goal. Between the Samâna and the Vyâna. shall I go to. and the ear as the fifth. I have perceived by means of the self the seat abiding in the self – (the seat) where dwells the Brahman free from the pairs of opposites. mind or speech. Therefore the Prâna and the Apâna do not forsake a sleeping person. O son of Pându! who. and the eye.
Becoming perfected by the perfect sacrifice. and into this the offering is thrown. The Brâhmana’s wife said: How did speech come into existence first. O lord!’ Thereupon the lord positively said to speech. From that is produced smell. these. they remain absorbed during (the time of) deluge. touch. verily. and the mind which is the Âhavanîya. which is the generator of all entities. O beautiful one! as you came personally to speak to me (in the way you did). But since you ask me a question regarding speech and mind. sun.’ CHAPTER VI The Brâhmana said: On this. moon. the movable is in your dominion. the two hands.’ The Brâhmana said: Know. and also that which is to be understood. O beautiful one! Objects of sense. But. and Vishnu also. That is called the movement of the mind. The ear. and the knower is the upholder of the body. yield (you) your desires. does not comprehend? What verily obstructs it? The Brâhmana said: The Apâna becoming lord changes it into the state of the Apâna in consequence. All the qualities which stand as offerings are absorbed into the mouth of the fire. verily. space. action. urine. O noble one! going with the Apâna wind. verily. and the anus. or letter. That upholder of the body is the Gârhapatya fire. and excrement. But inasmuch. from that is produced determination. from that is produced taste. Indra. seeing that words are uttered (after they have been) thought over by the mind? By means of what experience does intelligence come to the mind. The goddess speech. Both speech and mind went to the self of all beings and spoke (to him thus). Prajâpati. that (lord of speech) looks up to the mind. And the mind. The quarters. or tone goes to your dominion. though . (Thus) we have heard. I will relate to you a dialogue between themselves. Earth. immovable and also movable. ‘Mind (is superior). The ten organs are the makers of the offering. from that is produced color. And in that very (principle). The mind is within the body the upholder of the frame. water. verily. The immovable. the genital organ. these are the ten oblations. and (though) developed. O Sarasvatî! you shall never speak after (hard) exhalations. from that touch is produced. requires everything knowable (as its offering). that indeed is the movable mind. mind and understanding. are the fuel. and the discharge of semen. too. they were perfectly filled with light. that which is to be thought of. and the wealth is the pure. Whatever mantra. highest knowledge. therefore. and the mind runs after them. ‘I. and how did the mind come into existence afterwards. To that you are superior. verily. and they are offered up into the ten fires. and taste. from that doubt is produced. that (in) my (view). indeed. they relate this ancient story. First. are words produced. This (is what) they know as the sevenfold production. the tongue. the nose. Then the lord of speech was produced. and light as the fifth. and having dwelt within that dwelling are born in their respective wombs. wind. are ten sacrificial priests. which is the instrument of knowledge. O beautiful one! are the ten fires. from that another is produced. dwelt always between the Prâna and Apâna. earth and fire. was the universe duly divided. O beautiful one! Sound. are named wombs. words. verity. The mind is the ladle.’ But speech thereupon said to him. motion.be heard. the offerings are ten. ‘Say which of us is superior. destroy our doubts. these. and Mitra. color. Learn now of what description is the institution of the ten sacrificial priests. there are two minds. In this very way was it comprehended by the ancients. smell. and hence the mind is in need (of it). is with me. the two feet. speech. air. from that is produced sound. these seven.
the mind. (which shows) of what description is the institution of the seven sacrificial priests. O beautiful one! between the senses and the mind. with divine power. words could not be uttered? The Brâhmana said: The (speech) which is produced in the body by means of the Prâna. Observe the difference of (its) two subtle. do not apprehend (objects of) touch. mind and understanding. O you of a bright smile! is divine. The Brâhmana’s wife said: What did the goddess of speech say on that occasion in days of old. and the mind also. the eye apprehends them. the ear. and the goddess distinguished by reason of her being movable. too. dwelling (as they do) in a minute space? What are their natures. the skin. the skin apprehends them. she ran up to Prajâpati. do not apprehend tastes. And these never know the qualities of each other. and the eye. O beautiful one! they relate this ancient story. the skin. flowing (forms). It is always noisy or noiseless. Dwelling in a minute space. and which then goes into the Apâna. O venerable sir!’ Then the Prâna appeared again nourishing speech. Do you. and the eye. the mind apprehends it. the understanding. Hence the mind is distinguished by reason of its being immovable. The nose. do not apprehend doubt. And therefore speech never speaks after (hard) exhalation. Of those two. the ear apprehends them. and the understanding also. the ear likewise. the tongue. and then becoming assimilated with the Udâna leaves the body. saying. the mind likewise. do not apprehend smells. The nose. the ear likewise. O venerable sir? Tell me this. then (finally) dwells in the Samâna. the tongue.impelled. and the eye. the nose apprehends them. the eye. and the ear as the fifth. these are the seven sacrificial priests separately stationed. The Brâhmana’s wife said: How (is it) these do not perceive each other. and the understanding also. The tongue. and the skin. do not apprehend colors. and the understanding also. (in consequence of) being without the Prâna. CHAPTER VII The Brâhmana said: On this. The nose. (which are) seven according to (their several) natures. though (she was) impelled with a desire to speak. The nose. the skin. the skin. the ear. the noiseless is superior to the noisy (speech). do not apprehend sounds. verily. the tongue. they relate this ancient story. The nose. This cow-like speech. and with the Vyâna envelopes all the quarters. O lord! The Brâhmana said: Not knowing the qualities (of anything) is ignorance (of it). and the understanding also. ‘Be pleased. the mind. the skin. So speech formerly spoke. The nose. the tongue. the tongue apprehends them. the eye. and speaking of the Brahman it always produces the eternal (emancipation). the skin. when. yields milk. the mind. do not apprehend final determination. and the eye. The mind said: . On this. the tongue. – a dialogue. The nose. and next the eye. like a cow. and the tongue. This excellent (speech). the understanding apprehends it. and the understanding also. too. O beautiful one! learn about these sacrificial priests. the mind. they do not perceive each other. the ear likewise. the ear. Knowledge of the qualities is knowledge.
O beautiful one! (showing) of what description is the institution of the five sacrificial priests. you enjoy objects according to their natures by the mere operation of the mind. The wind prepared by the Vyâna works as the Udâna. Without me. when troubled by desire to enjoy. if you. then take in colors by the nose. And even after having carried on numerous mental operations. Without me. as a fire which is kindled (is extinguished) on the exhaustion of fuel. The senses said: This would be true as you believe. or like fires the flames of which are extinct. and the Udâna. You should accept enjoyments unenjoyed before. too. you have no perception. and granted that we have no perception of each other’s qualities. The Brâhmana’s wife said: My former belief was that the sacrificial priests were seven by (their) nature. and having acquired Vedic learning from him. that we have connections with our (respective) qualities. He shall be the greatest among us. For those who are powerful have no rules (to govern them). when our objects perform their functions. and said to him. The wind prepared in the Apâna then works as the Vyâna. or if when we are absorbed. both past and future. the senses never shine. the ear does not in any way hear sound. State how the great principle is that there are verily five sacrificial priests. always meets death. and so long no happiness can accrue to you. CHAPTER VIII The Brâhmana said: On this. ‘Tell us which is greatest among us. If again you think your power over our objects is constant. in sleep and likewise wakefulness. One entering upon enjoyments. without us. even with the senses exerting themselves.The nose smells not without me. Granted. If when we are extinct.’ Brahman said: . does run to objects of sense only. take in smells by the ear. like fuel half dried and half moist. Without me. you ought not to enjoy what has been tasted (by others). fail to apprehend qualities or objects. (there is) pleasure and support of life. life is seen to be supported. I am the eternal chief among all elements. As a pupil goes to a preceptor for Vedic learning. take in (objects of) touch by the tongue. The learned know this to be a great principle. the skin does not become aware of any (object of) touch. that the Prâna and the Apâna. so you treat as yours objects shown by us. and also (objects of) touch by the understanding. all beings. then what you believe is true. a creature. and objects are standing. They formerly went to the grandsire. Besides. and if you enjoy enjoyments. who was born first. enjoyed the enjoyments (derived from) our objects. on the exhaustion of the life-winds. and not connected with objects of sense. they relate an ancient story. And the wind prepared in the Udâna is produced as Samâna. the eye does not take in color. (which is) like entering a house without a door. and take in sounds by the skin. without us. rules are for the weak. and also the Samâna and the Vyâna. take in tastes by the eye. still. the tongue does not perceive taste. and indulged in dreams. like an empty dwelling. when creatures of little intelligence are distracted in mind. The Brâhmana said: The wind prepared by the Prâna afterwards becomes the Apâna. performs the directions of the Vedic texts. resulting from mental operations (alone). are the five sacrificial priests.
spoke to him. O Apâna! because the Prâna is subject to you. and the Samâna.’ The Prâna again moved about. owing to (their) specific qualities. O beautiful one! spoke these words. they again move about. and the Udâna. and all support one another. (which are) five. And the Prâna and Apâna. who being extinct. When I am extinct. because the Apâna is subject to you. verily.’ The Brâhmana said: Then Brahman. You are not the greatest among us. the lord of (all) creatures. and again moved about. See I am extinct! The Brâhmana said: Then the Prâna became extinct. O Vyâna! because the Samâna is subject to you. and on my moving about. Welfare be to you! Support one another. they again move about. said to them who were assembled together: You are all greatest. See I am extinct!’ Then the Samâna moved about. The Prâna said: When I am extinct. all the life-winds in the body of living creatures become extinct. Being friendly with one another.’ The Vyâna moved about again. they again move about. There is one unmoving (life-wind). See I am extinct!’ Then the Udâna became extinct. When I am extinct. The Apâna said: When I am extinct. (Now) go where (you) like. and not greatest. and the Samâna. ‘You are not the greatest among us. all the life-winds in the body of living creatures become extinct. spoke to him: ‘O Udâna! you are not the greatest. go away happily. all the life-winds in the body of living creatures become extinct. Then the Samâna and Udâna also. (but) accumulated in numerous (forms). all the life-winds in the body of living creatures become extinct. My own self is one only.’ CHAPTER IX The Brâhmana said: . and the Vyâna also. And the Prâna and Apâna. all the life-winds in the body of living creatures become extinct. I am the greatest. The Vyâna only is subject to you. When I am extinct. Hear the reason why. and again moved about. and on whose moving about. and the Samâna spoke again. You are all possessed of one another’s qualities.’ Then the Apâna moved about. And on my moving about. All are greatest in their own spheres. and pleasing one another. I am the greatest. There are others moving about. I am the greatest. See I am extinct! The Brâhmana said: Then the Vyâna and the Udâna addressed him who was speaking (thus): ‘You are not the greatest. ‘You do not pervade all this here as we do. all the life-winds in the body of living creatures become extinct.He. is the greatest. ‘I am the greatest among (you) all. and again moved about. Hear the reason why. they again move about. Hear the reason why. and the Apâna said to him. O Prâna. they again move about. I am the greatest. and the Udâna said to him: ‘I am the greatest among (you) all. See I am extinct!’ The Brâhmana said: Then the Vyâna became extinct. I am the greatest. and the Vyâna spoke to him: ‘I am the greatest among (you) all. they again move about. and on my moving about. and on my moving about. and on my moving about.
Hear me. or Apâna. indeed. and the eye. And the pairs of the life-winds should be understood. Day and night are a pair. The nose. and from the semen is produced menstrual excretion. that which is other than this first comes to him. which (move) upwards. First. or Samâna. or transversely. these. or Vyâna. The pair Prâna and Apâna go upwards and downwards. From the combination of the semen and the blood. between them is the fire. a dialogue between Nârada and the sage Devamata. Devamata said: When a creature is about to be born. in which the offering is thrown. Then the Vâmadevya for tranquility. The smoke of that (fire). That is the excellent seat of the Udâna as understood by Brâhmanas. the pleasure is produced from union. Those who understand the sacrifice understand the Samâna and the Vyâna as the principal (offering). The semen and the blood are produced by the Samâna and the Vyâna in common. This is the effect of the Udâna. the Samâna comes into operation again. they relate this ancient story. what comes into existence first. or downwards. the agent. hear me speak about that. their function is performed: then. and the . and tranquility is the eternal Brahman. the action. O you of a (pure) heart! are the four Hotris by whom this universe is enveloped. O good woman! state this wonderful mystery. and (the quality of) goodness is that in connection with it. That is the excellent seat of the Udâna as understood by Brâhmanas. This is the excellent seat of the Udâna as understood by Brâhmanas. or transversely. secondly. (its) ashes. CHAPTER X On this. which (move) upwards. From desire the semen is produced. It is the teaching of the Veda.On this. (appears) in the shape of (the quality of) darkness. the Apâna then comes into operation. and knowledge (of it) arises among Brâhmanas. they relate an ancient story (showing) of what nature is the institution of the Kâturhotra. and emancipation. Devamata said: By which (of the life-winds) is a creature produced? And which (of them) first comes to him? Explain to me also the pairs of the life-winds. between them is the fire. and between them is the fire. being accompanied by intelligence. or downwards. his Prâna. which is of excellent glory. That which exists and that which does not exist are a pair. and (it) is also produced from touch. and (it) is also produced from a sound. and (it) is also produced from smell. Nârada said: Pleasure is produced from a mental operation. (the quality of) passion. The two – good and evil – are a pair. The due performance of it in its entirety is now taught. and the Samâna and Vyâna are called the pair (moving) transversely. the Prâna comes first into operation. the Samâna and Vyâna. As to that which is distinct from these pairs. too. and (it) is also produced from color. Hear also the assignment of causes exhaustively. and the tongue. between them is the fire. (it) is also produced from taste. that the fire verily is all the deities. or else Udâna? Nârada said: By whichever the creature is produced. That is the excellent seat of the Udâna as understood by Brâhmanas. and the semen being developed by the Prâna. too. The instrument. That is the excellent seat of the Udâna as understood by Brâhmanas. The Prâna and Apâna are portions of the offering of clarified butter.
of which an illustration is stated. he who eats. and he who understands. There is one instructor. he who speaks.’ Hearing that. this. he who sees. being (himself) a ruler. And I am here devoid of qualities. the self the Adhvaryu priest. my fire of (high) qualifications. truth. in a single syllable. Impelled by that same (being). agreeable and disagreeable. O son of Prithâ! shine in heaven. I move as I am ordered. There is one enemy. and which is very beneficial on account of the abandonment of everything. and whatever is smelt by the nose. (and) the seven Rishis. together with those (senses) which with the mind are six. enjoy their own qualities. Taught by that instructor. these seven are causes of action. each in its own place. and sages. the Sastra. like water on a declivity. On that Sâman hymns.’ To them who were inquiring about the highest good. by Prajâpati. the Brahman. there is no second (different) from him. and destroying that food he is destroyed in return. My sacrifice of concentration of mind is in progress. I speak concerning him who abides in the heart. And not even a trifling obstacle arises to him from that food. these seven should be understood to be the causes of (the knowledge of) qualities. and the great sages . and the gods. there is no second (different) from him. He who smells. and he who hears as the fifth. He destroys the food. whatever is touched by the sense of touch. always enjoy the offering according to prescribed rules. whatever is spoken by speech. the director. said (to him): ‘Tell us the highest good. all snakes whatever are ever hated in the world. Living under that instructor. I speak concerning him who abides in the heart. and sages. and the snakes. I speak concerning him who abides in the heart. mind and understanding. (the self) whose hymn of praise is the offering. The gods had been engaged in gifts. dwells in the heart and directs (all creatures). The learned man. and touch as the fifth. he. there is no second (different) from him. are sung. they relate an ancient story. they ran away in (various) directions. too. There is one hearer. sound. On.skin. the qualities which are in the position of the deities. the Hotri priest. These. the Sastra of the Prasâstri. (about the) instruction of the snakes. and the Dakshinâ. On this. the inclination of the snakes to biting had been already formed. Rik verses are recited by the men who understand Nârâyana – the god Nârâyana to whom they formerly offered animal (offerings). being possessed of qualities. absorbing all these offerings from all sides. and color. final emancipation. Taught by him kinsmen are possessed of kinsmen. whatever is heard by the ear. the venerable one said. There is one kinsman. the object of the mental operation and the object of the understanding. destroying this food again produces it. (according to the proper mode of) living with an instructor. and taste. And cooking food for himself. When they were running for instruction regarding the self. these seven should be understood to be the causes of the agents. I speak concerning him who abides in the heart. is the upward life-wind. Whatever is thought by the mind. shines dwelling within the body. the Stotra in which. O modest one! understand that god Nârâyana. through the (feeling of this or that being) mine. whatever is seen by the eye. he who thinks. ‘Om. there is no second director. and drinking of intoxicating drinks also destroys him. the (feeling of this or that being) mine adheres. And among the learned who understand (everything). The natural inclination of the demons towards ostentatiousness had been formed. the downward lifewind. Taught by that instructor. Sakra acquired immortality in all worlds. The eating of that which should not be eaten. Thus these seven are the causes of emancipation. too. Smell. there is no second (different) from him. This being. all snakes whatever are ever hated in the world. I speak concerning him who abides in the heart. eating various (kinds of) food. who is the self of everything. is ruined. and the ear as the fifth. the performance of which yields the fire of knowledge. CHAPTER XI There is one director. is the counselor in all action. the Brahman priest in which. The gods. and the demons. approaching Prajâpati. To him who is not learned.
To him the Brahman itself is the fuel. merely adheres to the Brahman. That forest is filled with trees producing flowers and fruits of two colors. in which desire and anger are the obstructors. have no fear afterwards. The instructor. in various places. Such is this subtle life as a Brahmachârin understood by the wise. There is nothing smaller than that. and the demons. that. O very intelligent person! what are the trees (there). the gods. the twice-born do not grieve. That forest is filled with two large trees producing numerous flowers and fruits of undistinguished colors. the Brahman his origin. connected with the Brahman. when there is no distinction from it. And by his counsel does action afterwards take place. and do not exult. (namely) the five senses. in which delusion is the blinding darkness. He is rapt in the Brahman. in which intelligence is the tree. the Brahman water. the snakes. The qualities are the fruits. They are not afraid of anybody. and which has the Kshetrajña within for the sun. in which avarice is the beasts of prey and reptiles. there is no other instructor. full of brilliance. and mixed. in which grief and joy are cold and heat. owing to his desires. the learner. and fragrant. The seven (forms of) emancipation from them are the seven (forms of) initiation. being instructed by the Kshetrajña. That forest is filled with trees producing flowers and fruits of three colors. One hears what is said (to one) and apprehends it duly. Entering it. casting aside vows and actions. That forest is filled with trees producing flowers and fruits of four colors. and the guests eat the fruits. And there is fuel here. and what the rivers. But he who. the way to which consists in worldly objects. seven hermitages. the Brahman the instructor. the hearer. all engaged in different (pursuits). and the enemy. there is nothing larger than that. Acting sinfully in the world. In that forest are seven large trees. CHAPTER XII The Brâhmana said: I have crossed beyond that very impassable place. the great sages receive hospitality. the Brahman the fire. which has contentment for its water. and seven guests. he becomes (a man of) sinful conduct. And I have entered the great forest. which depends on knowledge. and having been instructed with one word. And when they have been worshipped and have disappeared. who. when there is a distinction from it. And he becomes a man of conduct according to his own desire. Its end cannot be perceived upwards or downwards or horizontally. he moving about in the world identifying himself with the Brahman. There is nothing more afflicting than that. with faces (turned) downwards. becomes a Brahmachârin. This is the description of the forest. There is nothing more subtle than that. and is to be crossed by one singly. and the hills and mountains. Having had one teacher. There always dwell seven females there. and causes of generation. is given up to the pleasures of the senses. That forest is filled with trees producing splendid flowers and fruits of five colors. There. There is one fire here. and having a good mind. another forest shines forth. That forest is filled with trees producing flowers and fruits of one color. Understanding it they practiced it. seven (forms of) concentration. the sages. in which fancies are the gadflies and mosquitoes. (but even) to one who inquires and extols highly. seven fruits. and which possesses shade (in the form of) tranquility. The Brâhmana’s wife said: Where is that forest. and at what distance is that forest? The Brâhmana said: There is nothing else more delightful than that. Acting virtuously in the world he becomes (a man of) virtuous conduct. and nobody is afraid of them. and of beautiful colors. are always within the heart. and emancipation the fruit. The good who attain to that. and seven (forms of) initiation. .in restraint of the senses. there is no other happiness equal to.
that refraining from slaughter (of living creatures) is (the duty) among all duties. mother. and again emerge from the same. The Ascetic said: If you perceive (that) good (will) result upon his life being severed (from him). nor even do I entertain any fancies. there is no taint on my natures. Apart from them. The Adhvaryu answered him (saying). (in the shape of) a dialogue between an Adhvaryu priest and an ascetic. being directed by the Kshetrajña. they relate an ancient story. Such. I perceive no tastes. and greatness. abide. Glory. praise tranquility. since the Vedic text is such.They absorb all the higher delights of people. CHAPTER XIII The Brâhmana said: I do not smell smells. too. On this. this goat will not be destroyed. (Our) proposition is no slaughter (of living creatures). Understand that. father. of this goat have gone to their sources. If I spoke further. Those whose wishes are reduced. I see no color. take him (to them) and consult (them). or old age. You ought to inquire of those who can give their consent thus. And aspiring to that forest. especially as he is dependent. too. We substantiate (this) from what is actually visible. In that same (principle) the seven perfect sages. brilliance. Desire and hatred are born from nature as the upward and downward life-winds. They are inconstant things appertaining to this constant (principle) which looks on various natures. then the sacrifice is for the goat. as there is no (taint) of a drop of water on lotuses. whatever in him is produced from water. and I do not touch. it would be possible to find fault with your proceedings in many ways. I am in no wise attached (to anything) through desire or anger. The teaching of the elders is. (the matter) will be fit for consideration. or death. indeed. they are born so as not to lose courage. Dwelling in that (self). after attaining to the bodies of living creatures. We maintain that that action should be performed which involves no slaughter. the net of enjoyments does not attach itself to it. There is no offence on my part. I see the individual self in the body. After hearing their consent. not hating any evil. censuring (the act) as destruction of life. (his) ear the quarters. victory. perfection. Not desiring any object of desire. that which is called an animal becomes the fuel. nature hates all (objects) which are hateful. and rivers and streams flowing with water produced from the Brahman. His eye (will enter) the sun. Although actions are performed. enlightenment. And understanding it. as understood by Brâhmanas. together with their chiefs. whence those who are contented in their own selves repair to the divine grandsire himself. For that part of him which is of the earth will go to the earth. and friend (of the goat) give you their consent. adhering (as I do) to the scriptures. The life-winds. we do not rely on what is not visible. and as the constant entity underlying them. . whose sins are burnt up by penance. Always refraining from the slaughter of all beings is what we approve. merging the self in the self. as inconstancy (absorbs) everything. Nature desires objects which are liked. and his life-winds likewise the sky. To those who wish to derive enjoyment from the slaughter (of a living creature). that will enter water. (This) creature will obtain welfare. Those people who understand the forest of knowledge. and I think only his unmoving body remains. is this holy forest. whose wishes are (fixed) on good vows. they act (accordingly). Hills and mountains also are there collected together. And there is the confluence of the rivers in the secluded place for the sacrifice. as the net of the sun’s rays does not attach itself to the sky. the unconscious body being comparable to fuel. an ascetic who was sitting (there) spoke to the Adhvaryu. what benefit (is it) to you? Let the brother. O glorious one! Seeing an animal being sprinkled at a sacrificial ceremony. devote themselves to Brahman. the richest. nor yet do I hear various sounds. and power – these seven rays follow after this same sun.
Of these the indestructible is the existent. my mind is enlightened. and I say (to you). said. Give them security. (these make up) the manifestations as individual entities. and who is released on all hands. freed from delusion. ‘O brave man! do not throw arrows (on me). The ocean. Say. you hear the sound produced in space. together with (the quality of) passion. who with his bow conquered the (whole) earth up to the ocean. the mind. they relate an old story. as we have heard. O tiger-like king! by the great arrows thrown by you. the ascetic thereafter remained silent. who is devoid of expectations. Thus Brâhmanas understand the very subtle emancipation to be of this nature. The Brâhmana said: With this explanation. the tongue. (There lived once) a king named Arjuna. And all these entities. O twice-born one? The Ascetic said The indestructible and the destructible. are being destroyed. the manifestation as an individual (entity) is called the destructible. who take shelter with me. . and understanding it. he was walking about near the sea. and showering hundreds of arrows on the sea. and the Adhvaryu also proceeded with the great sacrifice. Once on a time. being directed by the Kshetrajña. who has subdued his self. you think by the mind (on the objects of) mental operations. in the belief (that you are) the Lord. you see the colors of shining bodies. what shall I do for you? The creatures. (in the shape of) a dialogue. they act (accordingly). O venerable sir! I approach you. O king! you have heard of the great sage Jamadagni. who is alike to all beings. his son is (the) proper (person) to show you due hospitality. performing (as I have done) the rites performed by others. you drink watery juices. And to one who is free from these manifestations. a descendant of Kritavîrya. For having heard your opinion. such is the double manifestation of the self. The Adhvaryu said: O best of talented men! one should in this (world) dwell in company of good men only. O you of a pure heart! between Kârtavîrya and the ocean.The Adhvaryu said: You enjoy the earth’s quality of fragrance. you believe. The life-winds. and (the quality of) goodness. Or what do you think. you touch the qualities of the air. who is free from (the thought that this or that is) mine. who might stand against me in the field. O Lord!’ Arjuna said: If there is anywhere any wielder of the bow equal to me in battle. You have not (then) abstained from taking life. there is no fear anywhere. You are (engaged) in the slaughter (of living creatures). The ocean said: If. name him to me. who is free from the pairs of opposites. and with joined hands. have life. too. O twice-born one! there is no fault (attaching) to me. saluting him. CHAPTER XIV The Brâhmana said: On this. proud of his strength. There is no movement without slaughter (of living creatures). possessed of a thousand arms.
As by its unsteadiness. – having performed very difficult deeds. and taking swords and lances. dear friend. blazed forth. – he turned his mind to subtle (subjects). They will. all (his) kinsmen assembled together. with Rikîka as their head. Hearing that. burning the hosts of the enemy. hearing that (story). became Vrishalas. like antelopes troubled by a lion. Seeing him killed and fallen. his grandfathers. Look out for other arrows by which you may destroy me. whose power was unbounded. surrounded the descendant of Bhrigu. CHAPTER XV The Pitris said: On this. (Though) surrounded by enemies. and blew away the army of the king. ‘Desist. the Kshatriyas. not forgiving his father’s murder.’ The Pitris said: O best of victors! you ought not to destroy these kinsmen of Kshatriyas. he then spoke these words after consideration: – Alarka said: . whose penance was very great. I will cast very sharp-edged arrows at the mind. ‘O Râma! O Râma! desist (from this slaughter).Then the king. often troubled by fear of the son of Jamadagni. entered mountains and inaccessible places. you will die. I shall direct my arrows elsewhere. ‘You ought not to keep me back from this. Alarka said: My mind is become (too) strong. shot away volleys of arrows. spoke sweetly to Râma. turned to subtle (questions). and caused much trouble to the high-souled Râma. named Alarka. who understood duty. do you perceive. In company with his kinsmen. a bodiless voice from heaven. being a Brâhmana. Then some of the Kshatriyas. only pierce your own vital part. At the end of the twenty-first slaughter. said to those sages. Thus the Dravidas. likewise said to the high-souled (Râma). Paundras. went away. O best of the twice-born! you should act accordingly. too. in taking away the lives of these kinsmen of Kshatriyas over and over again?’ Then. that conquest is constant in which the mind is conquered. Râma also taking up a bow. O Alarka! will not penetrate through me at all. too. to make all mortals perform action. O lotus-eyed one! And then Râma. together with the Sâbaras. Then when the heroic (children) of Kshatriya women were destroyed again and again. to slaughter these kings. What good. There was (once) a royal sage. abandoning (those) great deeds. hacked away that man of the thousand arms in battle. Âbhîras. who were produced by the Brâhmanas. became Vrishalas. and very firm in his vows. and your vital part being pierced. and arriving at that hermitage approached Râma only. The mind said: These arrows. O noble one!’ But Râma. were also destroyed by the son of Jamadagni. taking up his axe. full of great wrath. they relate an ancient story. who was veracious. Then the power of Râma. While he was sitting at the foot of a tree. it wishes. owing to the abandonment of their duties by Kshatriyas. he did many (acts) disagreeable to Râma. Having with his bow conquered this world as far as the ocean. high-souled. and hurriedly mounting a chariot. And the subjects of those (Kshatriyas) who were not performing their prescribed duties through fear of him. which was heard by all people. owing to the disappearance of Brâhmanas. O you of great intelligence! his thoughts. It is not proper for you. like a tree of many branches.
and your vital part being pierced. Therefore I will cast sharp arrows at the tongue. Look out for other arrows by which you may destroy me. Hearing that. Hearing that. Therefore I (will) cast sharp arrows at the ear. They will only pierce your own vital part. Look out for other arrows by which you may destroy me. and your vital part being pierced. he then spoke these words after consideration: – Alarka said: Touching various (objects of) touch. and then you will lose (your) life. The skin said: These arrows. The nose said. Hearing that. O Alarka! will not penetrate through me at all. O Alarka! will not penetrate through me at all. you will die. The tongue said: These arrows. Therefore I will cast sharp arrows at the nose. he then said after consideration: – Alarka said: Hearing various sounds.Smelling very many perfumes. These arrows. They will only pierce your own vital part. O Alarka! will not penetrate through me at all. Therefore I will tear off the skin by various feathered arrows. Therefore I will destroy the eye with sharp arrows. and your vital part being pierced. the eye hankers after them only. you will die. the (ear) hankers after them only. Look out for other arrows by which you may destroy me. he then said after consideration: – . the skin hankers after them only. and your vital part being pierced. you will die. O Alarka! will not penetrate through me at all. Hearing that. The ear said: These arrows. They will only pierce your own vital part. Hearing that. he then said after consideration: – Alarka said: Seeing numerous colors. O Alarka! will not penetrate through me at all. this (tongue) hankers after them only. you will die. They will only pierce your own vital part. Look out for other arrows by which you may destroy me. Look out for other arrows by which you may destroy me. he then spoke these words after consideration: – Alarka said: Enjoying savory tastes. one hankers after them only. The eye said: These arrows. They will only pierce your own vital part.
’ Do you understand this too. and being troubled by desire. understands (nothing) while running into ditches. Perform a fearful penance. free from sloth. is energetic about subjugating others. For from avarice is born desire. and entering the self by means of concentration of mind. these three are qualities appertaining to the quality of goodness. he. The Brâhmana said: Then Alarka even there employed himself in a fearful penance difficult to perform. Exultation. of great glory. a courageous man. you will die. could not arrive at anything better than concentration of mind. again with his body dismembered and scattered about. owing to these qualities. and he who desires. that being possessed of a desire for enjoyments. And (then) the brave man forthwith destroyed the senses with one arrow. the noble son of Jamadagni engaged himself in fearful penance. but there is one. When vices were in the ascendant. Thus spoken to by (his) grandfathers. he mostly acquires qualities appertaining to the quality of darkness. is born again and again. attained high perfection. these are stated to be qualities appertaining to the quality of passion. and delusion. Then that king deliberated with a mind very intent on one (subject). these three qualities are qualities appertaining to the quality of darkness. the best of talented (men). persistent hatred. and again birth. he became steady. The understanding said: These arrows. thence you will obtain the highest good. and your vital part being pierced. O Alarka! will not penetrate through me at all. Look out for other arrows by which you may destroy me. And the royal sage. wrath. On this. and after deliberating for a long time. Cutting these off by multitudes of arrows. and applied himself to concentration of mind. They will only pierce your own vital part. a man even does what ought not to be done. Obtaining those. being impelled by which. and attained that perfection which is difficult to reach. having a tranquil self. That avarice – cut (it) off. O best of the twiceborn! Alarka. forcibly possessed himself of the kingdom. we should have devoted ourselves before now to sovereignty! I have now subsequently learnt that there is no higher happiness than concentration of mind. ‘O! Alas! that we should have engaged in all external (matters). Therefore. sloth. properly . joy. destroyed all foes. amazed. but he did not obtain any arrows for these seven by his devotions. CHAPTER XVI The Brâhmana said: There are. Grief. and engages in action. vice which should be destroyed and which I have not destroyed – that (vice). being impelled by which. a creature does not attain freedom from desire. And at the expiration of life. mostly acquires qualities appertaining to the quality of passion. three foes in (this) world. When the bodily frame is destroyed. and honoring good men. Therefore I will cast sharp arrows at the understanding. O Râma! and do not kill Kshatriyas. he meets death. pleasure. and sang these verses: ‘I have conquered most vices. then anxiety comes into existence. verily.Alarka said: This (understanding) forms various determinations by its operation. and senses controlled. and good (men) were oppressed. he reached the highest perfection. He (then) restraining his own vices. cut (it) off with sharp swords. (that vice). and they are stated to be (divided) ninefold. Sleep. then uttered this verse. Then directing his mind to one point. the greatest. people who know about ancient times celebrate verses which were sung of old by the king Ambarîsha. according to qualities. Ambarîsha. who had become tranquil (in mind).
as the planet upon the sun. Now hear the conviction.’ Thus spoken to. said to a Brâhmana who had fallen into some offence: ‘You should not live within my dominions. I do not desire for myself even smells existing in the nose. I looked for Mithilâ. though this country. Therefore the earth being conquered is a ways subject to me. I have got rid of (the notion that this or that is) mine. or the whole earth is mine. (Considering) whose this was. so (is it) that of others too. While that king of unbounded power was seated. the Brâhmana then replied to that best of kings: ‘Tell me. Then on the expiration of the delusion. which is the kingdom of your father and grandfather. they relate this ancient story (in the shape of) a dialogue. (I thought of) the Vedic text about anybody’s property. O best of the twice-born! Live (here. The self properly understood is itself the sovereign. a delusion suddenly came upon him. I do not desire for myself sounds even though existing in the ear. therefore) while you desire. which is the kingdom of my father and grandfather. too. Even this self is not mine. (hence) I could not find by my intelligence anything that should be (called) mine. the king recovered himself. Therefore light being conquered is always subject to me. Now I think that there is no domain (of mine). or all as your domain? Janaka said: I understand (all) conditions here. Resorting to this conviction. I looked for my own offspring. I do not desire for myself tastes even dwelling in the mouth. and after a short while spoke these words to the Brâhmana. searching through the (whole) earth. When I did not find it among them. is subject (to me). The Brâhmana said: Tell me. when I did not find it in Mithilâ. Therefore water being conquered is always subject to me. to be terminable. and. avarice. by which. there is no other sovereignty here. who destroyed the one (chief vice). is subject to you.perceiving this. the king then heaved frequent and warm sighs. intelligence again came to me. I do not desire for myself the (feelings of touch) which exist in the skin. I believe. CHAPTER XVII The Brâhmana said: On this. Therefore air being conquered is always subject to me. what belief you have resorted to. engaged in meditation. I do not desire for myself the mind always within me. by way of punishment. holding which. and enjoy while you live. King Janaka. you have got rid of (the notion that this or that is) mine. O you of a pure heart! between a Brâhmana and Janaka. then came the delusion on me. Janaka said: Though this country. When I did not find it on the earth. I wish. by the glorious Ambarîsha.’ Thus spoken to by that glorious Brâhmana. my domain (appears to me to be) everywhere. Then when the delusion had gone off. and said nothing in reply. Therefore the mind being conquered is always . and restraining avarice by courage. hence I could not find anything that should be (called) mine. one should wish for sovereignty in the self. in all affairs. O Lord! to live in the dominions of another king. This is sovereignty. What conviction have you adopted. O king! how far (extend) the dominions which are subject to you. I cannot find my domain. O master of the earth! I wish to do your bidding according to the Sâstras. And as mine. I do not desire for myself the color (or) light appertaining to the eye. or that everything is my domain. Therefore sounds being conquered are always subject to me. by which verily you consider your whole domain as not (your) domain.’ Such were the verses sung with regard to the great sovereignty.
the instructor is the upper Arani. O beautiful one! as you see me with the eye. by which it is capable of being comprehended? The Brâhmana said: He is without symbols. you have guessed. I am emancipated. to households. and the body is tied down by action. This is the path of the Brâhmanas. is perceived as by bees. that a certain thing should be done. by which that (entity). where. and my intelligence is very frivolous. Whatever creatures there are in the world. by which those who understand that proceed. I am not such. and which does not turn back.subject to me. not by the body. Tell me the means by which this knowledge is acquired. it is not laid down. I pervade every single thing that is in this world. you will certainly come into my self. And those who. the spoke the understanding. the Bhûtas. (namely) for the gods. which has the symbols (useful) for knowledge attributed to it through ignorance. and a certain thing should not. or else this knowledge. and confused. movable or not moving. go to the single entity as rivers to the ocean. action and knowledge. This path is traversed by the understanding. and even over heaven. Hence. dwelling with preceptors. A good means is found. Then the Brâhmana. I (wish to) learn from you the source from which that knowledge proceeds. and which is checked by the quality of goodness as its circumference. and narrow. smiling. namely. or by one whose self is not refined. together with guests. (of these two) knowledge is my only wealth.’ CHAPTER XVIII The Brâhmana said: O modest one! I do not move about in this world in the way which. and I likewise perform the duties of a householder. is (to be found) a description of it. Sovereignty over the whole world. Penance and sacred learning cause the attrition. nothing exists that is a cause of him. the Pitris. for this purpose. adhering to various symbols and Âsramas. the nave of which is the Brahman. that. With your heart intent upon the real entity. All these actions of mine are. or residence in forests. O beautiful one! You (need) have no fear occasioned by the other world. or among mendicants. according to your own understanding. I am a Brâhmana. and also without qualities. again said to Janaka: ‘Know me to be Dharma. CHAPTER XIX The Brâhmana’s wife said: This is not possible to be understood by one whose self is frivolous. In the (rules for) final emancipation. indeed. I am a forester. have their understanding full of tranquility. and from that the fire of knowledge is produced. I will only state the means by which he can be comprehended or not. observing vows. You are the one person to turn this wheel. Actions have a beginning and an end. But the knowledge of the things beneficial to the self is produced in one who sees . know me to be the destroyer of them as fire is of wood. With numerous unconfused symbols only one knowledge is approached. come here today to learn (something) about you. or. verily. The Brâhmana said Know that he who devotes himself to the Brahman is the (lower) Arani. The Brâhmana’s wife said: As to this symbol of the Brahman which is denominated the Kshetrajña.
O terror of your foes! asked a Brâhmana preceptor of rigid vows. O son of Prithâ! said to the pupil who spoke thus: ‘I will explain to you everything. Listen to that. between a preceptor and a pupil. and know my understanding to be the Brâhmana’s wife. O venerable Brâhmana sage! O you of excellent vows! do you be pleased to explain correctly. they relate an ancient story (in the shape of) a dialogue. (when he was) seated. ‘whose goal is the highest good. all of various descriptions. And there exists none else but you who can destroy all doubts. O you of great intelligence! The pupil said: Whence am I. O Brâhmana? What are called the qualities by the good? And what paths are happy? What is pleasure. (which are) means of direct perception. after the destruction of the Kshetrajña. as may here be practicable – unperceived.’ The preceptor. O Krishna! is that Brâhmana’s wife. ‘I’ (he said). Speak. who was possessed of (the . Arjuna said: Where. O twice-born one! on which you verily have any doubt. A talented pupil. The Deity said: Then the mind of the Brâhmana’s wife. likewise. indeed. O undegraded one! The Deity said: Know my mind to be the Brâhmana. I pray of you with (bowed) head. am come to you (who are) venerable.’ Thus addressed by the preceptor. O son of Prithâ! O chief of the family of the Kauravas! O restrainer of foes! duly explained all those questions to that pupil. connected with final emancipation. for by your favor my mind is much interested in (these) subtle (subjects). and where is that chief of Brâhmanas. You are celebrated in the worlds as skilled in topics connected with the piety (required for) final emancipation. Vâsudeva said: That talented preceptor. and also desirous of final emancipation. And he. and what is the limit of their life? What is truth. too. who preserved (all) vows. There is none else here who can explain these questions. CHAPTER XX Arjuna said: Be pleased to explain to me the Brahman which is the highest object of knowledge. and accurately. Then one reaches near that beyond which nothing exists. who had approached him (for instruction). who put (his) questions properly. in hundreds and in thousands. O best of the Kauravas! he who was devoted to the preceptor. and whence are you? Explain that which is the highest truth. something about the highest good. put (his) questions with joined bands. turned to that which is beyond (all) Kshetrajñas by means of a knowledge of the Kshetra. And we. O Brâhmana! that you should explain to me what I ask. and those whose form is perceived. Vâsudeva said: On this. O Dhanañjaya! who has been spoken of as the Kshetrajña. truly. what penance.and hears. and what sin? These questions of mine. by both of whom this perfection was attained? Tell me about them both. From what were the movable and immovable entities born? By what do entities live. are afraid of worldly life. is I myself. O best of those who understand piety! I feel the highest curiosity (in this matter). One should adopt as many of these things.
which ought to be apprehended. becomes eligible for assimilation with the Brahman. when thus spoken to by the sages. Bharadvâja. And he who understands determinately the true object of knowledge which is inexpugnable – the self abiding in all entities – and who can move about anywhere. from whom (all) sin has departed. which is understood by the multitudes of Siddhas. and is eternal. after having traveled over all paths. and of the four orders. and renunciation as the best penance. is esteemed highest. Listen (to that) O pupil! Brahman said: From the truth were the entities movable and immovable produced. Having saluted that high-souled one who was sitting at ease. is released from misery. desire. asked him this momentous (question) concerning the highest good: ‘How should one perform good action? How is one released from sin? What paths are happy for us? What is truth and what vice? By what action are the two paths southern and northern obtained? (And what is) destruction and emancipation. who is devoid of (the thought that this or that is) mine. Understand that. and who is devoid of egoism. He who does not desire anything. the sages. and also Kâsyapa. Brihaspati. met each other. who understands the creation of all entities. in the holes of which are the sprouts. and wealth. always possessed of flowers. and likewise of the castes. who are the establishers of the bridge of piety. the senses. and which is cultivated by the chief sages. and the seed of which is the Brahman. namely. and becoming wearied of their own actions. which is always possessed of leaves. which is eternal. from whom anger and vexation have departed. I will state to you. We consider knowledge only as the highest thing. . penance is the truth. O highly talented one! the true conclusion about the past. who are possessed of knowledge. in Brahman’s mansion. Therefore Brâhmanas whose final goal is always concentration of mind. and the severance also. I will state to you today. the universe consisting of (all) creatures is the truth. of which the great elements are the flower-bunches. on which all entities subsist. Accurately understanding the great (tree) of which the unperceived is the sprout from the seed. and casts off birth and death. and so forth. the gross elements the smaller boughs. Formerly. desiring knowledge. there is no doubt of that. And those twice-born (sages). the future. and from which pleasant fruits are always produced. For the truth joined with the qualities is invariably of five varieties. and understanding which talented men have here attained perfection. O you of excellent vows! By their own action they remain transcending their own source. Gautama. who was like (his) shadow. and Visvâmitra. even while dwelling in this world. the great sages. Prajâpati also is truth. and likewise Bhârgava. and Atri also. and who was a self-restrained ascetic and a Brahmachârin. I will speak about those (Brâhmanas) who are restrained by one another.necessary) qualifications. The Brahman is the truth. who conducted himself in an agreeable manner. The preceptor said: All this. and cutting it with that excellent sword-knowledge – one attains immortality. saw Brahman. which consists of the understanding as its trunk. is emancipated. The learned man who perceives the abiding together. They live by penance. the present. Vasishtha. which is connected with the knowledge of the Vedas and involves a consideration of the real entity. and likewise unity and variety. which belongs to olden times. the birth and death of entities?’ What the grandsire said conformably to the scriptures. who was tranquil. the branches of which are the great egoism. and has no egoism about anything. are full of the truth. full of humility. and who are invariably devoting themselves to piety. was declared by Brahman. He who knows the truth about the qualities of nature. and piety. giving the lead to the old sage Ângirasa. the entities are born from the truth. I will speak of the four (branches of knowledge. and who are the constant creators of the people.
takes up any one of these modes of piety separately. one sees not these. next after that is that of foresters. The talented ones speak of piety as having faith for its characteristic. and of the understanding as ruler. and darkness the match of goodness. immaturity (of intellect). attains to all the spotless worlds. and which are bridges of piety. now speaking exhaustively. ignorance. fear. while one does not attain to the Adhyâtma. Its characteristic is also impiety. among all beings. It has three qualities. (the order) of the sages who dwell in forests and live on fruits roots and air. and are joined to one another. Light. sleep. lightness. Passion is said to consist in activity. Light. and of the highest seat. Where passion is restrained. learn those accurately. and also all the deities. want of discrimination. finding fault with good acts. which you should understand. The order of foresters. and is called delusion. and which has been invariably traveled over by talented men in old days for (obtaining) assimilation with the Brahman. The number of the elements is celebrated as being twenty-four plus one. O noble ones! from me. and those three channels run on. . and goodness. indecision about actions. Now I shall state with accuracy and with reasons. Prajâpati. nihilism. being constituted by the three qualities. violation of (the rules of) conduct. And the talented man who understands the production and dissolution of (all) elements. everlasting. (but) having four quarters. he. Darkness should be understood to consist in obscurity. The wise always speak of piety as one. He who. of that highest path which is difficult to understand. The true nature of their characteristics. And the five constituent principles (are made up of) the three qualities. The three currents which are within this (city) support (it) again and again. and likewise serve one another. and getting rid of all bonds. the highest step must be understood to be that relating to the Adhyâtma. CHAPTER XXI Brahman said: That unperceived (principle). passion there prevails. its characteristic. and is the cause of successive (acts).distinctly. faith. grief. which depend on one another. sun. I will speak to you. it also appears combined (with others). The great self. want of liberality. air. appears to be production. O twice-born ones! of the happy path. haughtiness. and it is constant in sinful actions. as accepted by good men. which are all coupled with one another. blindness. He who accurately understands the elements. and goodness is also the match of passion. the whole of the qualities. Goodness is the match of darkness. consisting of mind as the distinguishing power. The first step is said to be the order of Brahmachârins. Darkness. eleven. Delusion. always comes in time to perceive the production and dissolution of (all) entities. Indra. rigid in his vows. which is in a state of equilibrium. of all beings. the unperceived likewise. and the five great elements. passion. and immutable. want of memory. all the elements which abide in parts in all objects. such is the eternal creation. I will subsequently state the means to that. such is stated to be the nature of goodness (prevailing) among all beings. will now be stated together with the reasons. should be understood (to become) the city of nine portals. which are occupied by good and talented men by means of their actions. which is productive of pleasure. This is the nature of darkness. When it prevails. and attend on one another. and the specific characteristics of the five elements. and next after that too. and passion is the match of goodness. The order of householders is prescribed for all castes. casting aside sin. all-pervading. avarice. the ten senses and the one (sense). and likewise also egoism. is prescribed for the three twice-born (castes). space. encircled by the. Thus have I described to you the paths leading to the gods. never comes by delusion. and five constituent principles. consisting of three qualities. Learn. these are called the three qualities. in aggregation and separation. goodness there prevails. this is (an aggregate made up of) eleven. the second is that of householders. Where darkness is restrained.
wrath. and all quadrupeds. deaf and dumb men. they are all held to be dark. unfriendliness. Constant talk in disparagement of gods Brâhmanas and Vedas. fierceness and cruelty. lassitude. that one sees the real in what is unreal. stolidity. sink into darkness. The qualities of darkness have been described to you in many ways. and also creatures born from eggs. the great obscurity called anger. abuse . exercise and quarrel too. the thought (that this or that is) mine. These dark. perceives this properly? The definition of the essence of darkness is. harboring evil thoughts. doers of sinful acts. Attachment to objects of desire is laid down to be the great delusion. vindictiveness. (or become) the immovable entities. the current of whose (thoughts) is downwards. and whatever others are attacked by diseases generated by sin. anger. delusion. who are sunk in darkness. pride of performance without (actual) performance. delusion. and growing old in their own duties. pleasure and pain. bonds. endurance. who bear the marks of their own actions. the great delusion. beauty. and growing old in (good) actions. want of faith also. sages and saints and gods become deluded. Resorting to a contrary (course of life). in full and accurately with reference to its nature. O noble ones! the action of the quality of passion. animals. they attain to the worlds of those who perform good acts. peace. want of faith. wishing for pleasure.behavior of the lowest quality. how. to be born in the lower hell. O Brâhmanas! are celebrated as being dark. insects. And whatever other states of mind. vanity. I will now proceed to state their improvement and ascent. piercing. and vain eating. want of knowledge (of the subtle principle). all these qualities. slaughter. vanity. and also animosity towards people. animosity. are found in various places in this world. who break through (all) regulations. or deaf. backbiting. valor. by cutting. going beyond the Sûdra womb. and want of forgiveness. Injuring (others). they attain to higher and higher castes in order. they exert themselves. pride of knowledge without (actual) knowledge. thinking of (this) world. birds. and also its source. Resorting to a contrary (course of life). Learn. or lisping men. and worms. And darkness in its higher and lower (forms) has been accurately stated. There. I have now duly described to you. touching other people’s weak points. toil. desire. CHAPTER XXII Brahman said: O best (of men)! I will explain to you accurately the quality of passion. indeed. evil disposition. and through the ceremonies (performed for them) by benevolent Brâhmanas devoted to their own duties. repining. buying and selling. I will state the wombs appointed for these (men) of sinful actions. demons. (namely) the brute (species). They go to the hell. argument. want of liberality. becoming men of meritorious actions. want of forgiveness likewise. strength. want of straightforwardness. and idiots. animosity. indeed. who. and also its qualities. they go upwards to the same world (as the Brâhmanas) – the heaven of the gods. And whatever such people there are in this world. Coming to a sinful womb. vilifying. all these are dark qualities. this is considered to be dark conduct. battle. that is considered to be dark conduct. going into inferior ways. and (beyond) whatever other dark qualities there are which abide in the quality of darkness in the current (of this world). war. evilconducted men. beasts of burden. anger is called the great obscurity. breaking. as Chândâlas. sinful action. Reviling. deluded convictions. Whatever vain actions (there are). Darkness. pointing out others’ weaknesses. frenzy. Such is the Vedic text. Who. and death the blinding obscurity. this is considered to be dark conduct. want of self-restraint. preservation. they become men in this world whose nature is to return. and serpents. O Brâhmanas! this quality of darkness. affliction. want of knowledge. power. cold and heat. connected with delusion. understands this properly. and whatever vain gifts. The man who always understands these qualities gets rid of all dark qualities.
Getting rid of all sins. for articles. learning vain. and to be gods. O Brâhmanas! are described as passionate. devotion to dancing. Thus. wealth. and wish for the fruit appertaining to the life after death and that appertaining to this world also. and also sacrificing and study. and having gone to heaven they verily change in various ways. indifference. he attains the highest in the next world.’ affection generated by the qualities. purity. devoid of expectations. The man who always understands these qualities. those talented men reach heaven. He who possesses the piety of concentration of mind. association with women. and attachment also. and lust also – who acting under (the impulse of) desires exult or the success of all their desires. They are said to have their currents upwards. Devoid of (the notion that this or that is) mine. belongings. and the action of the quality has also been stated accurately. absence of cruelty. The qualities of passion have been described to you in many ways. self-restraint. freedom from delusion. enlightenment and happiness also. theft. laudation. they rejoice. absence of wrath. the wish ‘this may be mine and that may be mine. boasting. forgiveness. joy. and unblamable. harmlessness. and free from grief. (holding) knowledge to be vain. Confidence. absence of calumniation. these those high-souled ones make (for themselves) by (the operations of their own) minds like the gods dwelling in heaven. and the various decorations which prevail in this world. for living creatures. who are always devoted to the triad – piety. liberality. (to be) such is the eternal duty of the good. modesty. management. and labor vain. devotion. joviality. praise. all these qualities. expiations. absence of backbiting. forgiveness. They obtain and divide whatever they desire. defiance. perceive (everything) aright. and instrumental or vocal music. minuteness. O chiefs of the twice-born! have I described to you the conduct of the quality of goodness. and actions with expectations. pleasure. pleasure and delight. harboring desire. vexation. common scandal. Those talented Brâhmanas in this world. contentment. faith. salutation. by means of nature. and make Tarpana. (good) conduct vain. doubt.uttering falsehoods. CHAPTER XXIII Brahman said: Now I shall proceed to describe the third – the best – quality. abiding in the seat of the Brahman. disrespect and respect. have (their) currents downwards. who are enveloped by passion. penance vain. equability. gets rid of all passionate qualities. prowess. vows vain. and future entities in this world. obedience. gambling. service. freedom from (the notion that this or that is) mine. bad gifts. present. The power of governing. contumely. service vain. Born again and again in this world. sacrifices vain. courage. nobility. freedom from laziness. humility. unbroken piety. the duty of the good. vexing (oneself). (on another). The . and also sacrifice. Understanding this according to rule. and also want of faith. contentment. straightforwardness. absence of fear. the ceremony of Vashat. joy. for men. dexterity. the ceremony of Svadhâ. whose conduct is of this description. The men who meditate on past. righteous feelings. for women. haughtiness. one obtains whatever one desires. abandonment on all hands. piety vain. who adhere to the quality of goodness. not full of desires. receipt of gifts vain. slaughter. (holding that) gifts (are) vain. attendance. gifts and acceptance of gifts. auspicious rites. valor. life as a Brahmachârin. absence of stinginess. and for houses. and create (various) bodies. treachery and likewise deception. both officiating at sacrifices and imparting instruction. freedom from expectations. good behavior. They give and receive. ostentation. devoid of egoism. beneficial to all creatures. policy. heedlessness. censure. and of the quality of goodness. these men. and the various acts of public charity the ceremony of Svâhâ. purity. emancipation. equable everywhere. purity in all action for (acquiring) tranquility. wakefulness. vows and regulation. compassion to (all) creatures. truth. disgust.
and passion also. the men of the quality of darkness. The three qualities abide in the three castes thus: darkness in the Sûdra.qualities of goodness have been specifically described. the passionate remain in the middle. that as long as there is goodness so long darkness exists. and the oleaginous property is of the quality of goodness. in the lower entities. CHAPTER XXIV Brahman said: The qualities cannot be explained altogether distinctly (from one another). the unperceived. not developed. destruction. and its pure operations. passion. Even from afar. immutable. For they act with cause or without cause. there darkness should be understood to be little. but is not attached to the qualities. passion in the Kshatriya. and the enlightener. threefold are the worlds. feel the warmth. And they act by turns in the several places in several ways. and its eclipse on the Parvan days must be understood to be of the quality of darkness. We have never heard of them (as existing) separately. Threefold are the gifts given. threefold the sacrifices performed. They are attached to one another. evildoers are alarmed. Darkness. freed from the body. abiding in those of the upward current. holy. The creation of the qualities is eternal. evil-doers likewise are darkness. and the Udâna. suffering trouble from the heat. The past. and being free from all misery. unborn. and the qualities. and lust. understanding the truth about (all) distinctions. years. Where darkness is increased. eternal. are seen to have been together and moving about collectively. is said to be. and darkness likewise are seen mixed up (with one another). Where passion is developed. They perform their journey together. piety. the qualities of passion are variable. Pradhâna. there passion should be understood to be little. seasons. these are the three qualities. there darkness should be understood to be little. and passion likewise to be less. the increase and diminution will now be stated. and threefold the path. There is no doubt of this. Passion. is released from all qualities. The sun is goodness developed. wealth. and the future. all that is (made of) these three qualities. The day should be understood to be threefold. the heat is the quality of passion. so long is passion said (to exist) here. in the Brâhmana. and likewise months. change. and travelers. and the heat to the travelers is said to be a property of passion. Goodness is the cause of the modifications in the senses. abiding. and the highest. the Prâna. These names should be learnt by men who ponder on matters relating to the self. being connected with the lowest quality. For there is no other higher duty laid down than goodness. the Apâna. moving in a body. the night is stated to be threefold. and the conjunctions. And as long as goodness and darkness. immovable. And where goodness is developed. . unperceived. enjoys the qualities. The three qualities – goodness. Among immovable entities. and moving about collectively. the present. They all depend on one another. goodness. they feed on one another. existent and also non-existent – all these. womb. and likewise follow one another. and darkness also – are always acting unperceived. The light in the sun is goodness. Of all these acting with one another. and goodness likewise to be less. So in all shining bodies. darkness is in the form of their belonging to the lower species. he. go down. abiding in those of the middle current. production and absorption. Those who adhere to (the ways of) goodness go up. and goodness likewise to be less. (consisting) of the three qualities. He who understands correctly all the names of the unperceived. and the operation of the qualities has been accurately stated. but differing in development. threefold the gods. And whatever there is in this world. constant. half-months. in union. there: exist three qualities. nature. The man who always understands these qualities. not small. darkness. goodness. threefold the (departments of) knowledge. Seeing the sun rising. unshaking. goodness.
taste. Sound. it stands pervading everything in the world. and whose senses are subdued. taste. the operations (connected with these) have causes. of universal form. By consciousness of self one enjoys the qualities. whose minds are clear. That egoism is stated to be the source of all entities. who are devoid of egoism. and their name is delusion. who are not avaricious. the final dissolution approaches. who are constant at concentration of mind. Caused by the production of avarice. and as that from which the changes take place. and likewise cognition. and are dissolved in the reverse order. That great self is signified by these synonymous terms – the great self. the understanding. ancient being. means of knowledge. It is a deity. O talented one! a great danger for all living beings arises. the great self. the supporter of consciousness. air. CHAPTER XXVI Brahman said: That Mahat which was first produced. it is said to be the first creation. and light as the fifth. it is the creator of the three worlds. who are devoid of (the thought that this or that is) mine. touch. That which feels thus – ‘I am all this’ – is called (by) that (name). not different from one another. Brahma. Then when every entity. creatures are deluded. Minuteness. is (afterwards) called egoism. inexhaustible. heads. It has hands and feet on all sides. and insignificant. the light. intelligence. creates (them). The being of great power is stationed in the heart of all. at the termination of the destruction of the great elements. and smell as the fifth. and who are perfected by sacred study and sacrifice. color. who are true to their promises. and likewise color. who practice meditation. memory. the transcendent. in the operations of (perceiving) sound. it causes all this to move. attain greatness. verily. the valiant. and are inconstant. when it is born as (the feeling itself) I. who are talented. who are possessed of knowledge. and golden. CHAPTER XXVII Brahman said: From egoism.CHAPTER XXV Brahman said: From the unperceived was first produced the great self of great intelligence. the source of all qualities. these being emancipated. it has eyes. space. the Prajâpati. the producer of the entities. it likewise charms the world. the talented men who possess a (good) memory are not dissolved at all. means of perception. Knowing that (great self). and who are always possessed of a good heart. That eternal world is for those sages who are contented with knowledge relating to the self. who have pondered on the self. he is the governor. Now people who comprehend the understanding. a learned Brâhmana comes not by delusion. has been dissolved. Sambhu. movable or immovable. courage. it is that from which the people are produced. it is full of light. And he who thus knows the lord lying in the cave. They are born one from the other. the highest goal of those possessed of understanding. touch. and faces on all sides. that talented man. he among all people comes not by delusion. and thus that source of all entities. water. The self-existent Vishnu is the Lord in the primary creations. In these five great elements. When. abides transcending the understanding. who have subdued wrath. the producer of the deities. and of the mind. and by its own light. and smell. connected with . that from which the changes take place. Every entity is dissolved into that from which it is produced. were the five great elements born – earth. (the power of) obtaining (everything) (are his). And the talented man who understands that high and holy goal. Vishnu. lightness. that is said to be the second creation.
and the presiding deity there is the sun. This is said to be the . as connected with the self it is the nose. There are three seats for all entities – a fourth is not possible – land. the tongue. excluded from the self. As connected with the self. As connected with the self. The Prâna and the Apâna. and the organ of generation. as connected with objects likewise it is smell. and depending upon one another. tongue. who perceive the truth. Thus have been stated the eleven organs in order. as connected with the self it is called the ear. as connected with objects that which is to be understood. The fourth (entity) should be understood to be water. the cause of the whole course of worldly life. they mention the understanding impelling the six senses. as connected with objects it is taste. it is known as the skin as connected with the self. those born from germs. self-consciousness. he attains to that holy Brahman than which nothing greater exists. the organ of excretion. and worms of the like description. mind. as connected with objects it is excretion. water. likewise as connected with objects (it is) sound. and speech are restrained. And the (mode of) birth is fourfold. And all the rest are without distinction connected with action. The Apâna wind. Insects are said to be born from perspiration. and together with speech. the mind is the eleventh. the Udâna. and the presiding deity there is the quarters. as connected with the self it is called the tongue. and those born from wombs – such is the fourfold (mode of) birth of the group of living beings. as connected with the self. and the presiding deity there is Brahman. The fifth entity is earth. as connected with objects (it is) the object of touch. and the presiding deity there is Soma. and whose mind is pure. as connected with the self. and five the organs of action. The second entity is air. Thus are the five entities stated to be divided among the three. these five winds are also joined to the inner self.flesh and blood. as connected with objects it is the mental operation. the feet are mentioned by Brâhmanas. and the presiding deity there is Prajâpati. the two hands. O twice-born ones! I will describe specifically. The third (entity) is said to be light. the presiding deity there is Vishnu. the presiding deity there is the Moon. and understanding unswerving. the motion of which is downward. and the understanding is the twelfth. and the presiding deity there is Mitra. and space. Those should be understood to be born from eggs. is speech which relates to all the gods. the producer of all beings. and the presiding deity there is lightning. The mind should be understood to be among both. those born from perspiration. Understanding these. the skin. and the presiding deity there is the wind. Five (of these) are called the organs of perception. Then first. the two feet. which are stated as having been produced from egoism – these. as connected with objects it is the semen. as connected with objects it is actions. ear. next as connected with objects (it is) color. The ear. and the presiding deity there is fire. learned men think they have accomplished (everything). The five beginning with the ear are truly said to be connected with knowledge. and understanding make the eight constituents of the universe. as connected with objects it is motion. these are helpless and powerless. He whose skin. and the Vyâna also. Space is the first entity. As connected with the self they mention the mind. such is the group of organs. nose. the nose also as the fifth. the Samâna. eye. as connected with objects it is what is spoken. is called the organ of excretion. as also all reptiles. then the Brahman shines (before him). Likewise (there is) egoism. the presiding deity there is Rudra. I will now proceed to state all the various organs. and whose mind is never burnt by these eight fires. which follows after the five entities. Now there are the inferior beings and likewise those moving in the air. Men who understand the Adhyâtma speak of the two hands as connected with the self. Those born from eggs. This group one should subdue first. as connected with the self. and the presiding deity there is Indra. as connected with objects. and speech as the tenth. I will now proceed to state all the various organs. And the eleven organs. the two eyes. As connected with the self the generative organ is mentioned. as connected with the self it is called the eye.
which has nine passages and two deities. this same (body). and which is full of the Brahman. Space is the first entity. which is surrounded by the five currents. and is sanctifying. The third is called light. as connected with the (individual) self it is called the ear. and released from everything.) the senses. as connected with objects it is the object of touch. so the great self shines forth through the restraint of the senses. and hold them by the mind. having his cravings destroyed. unfit to be seen. the hideous holder of the mud is earth. then being self-illumined. pleased with contacts. (namely) sacrifice. curtail it. (viz. the pleasures of (worldly) life are not esteemed. The world. Thus have I accurately described to you the creation as connected with the (individual) self. Action should be understood to be of various descriptions. and full of delusion. for (every one) who is born. as connected with objects likewise it is called sound. made up of three qualities and of three constituent elements. too. as connected with objects it should be understood to be taste. When everything is absorbed into the mind. should cast it aside.second (mode of) birth. Such is the doctrine of the learned. as connected with the (individual) self it is called the nose. and than which there is nothing higher. becomes possessed of concentration of mind. that he is released from all sins. The fire of the Adhyâtma is kindled in a sage by his abandoning the country. as connected with the (individual) self it is laid down to be the eye. The learned (men) whose understandings are possessed of knowledge esteem the pleasure derived from that. When one with a tranquil self perceives all entities in one’s own heart. is ever happy. Now I shall proceed to describe that discarding of all entities by (means) gentle and hard. Those beings. as connected with objects likewise it is called smell. and restrain it. and likewise the sound is space. which is full of passion. he becomes fit for assimilation with the Brahman. and the five great elements. and the presiding deity there is the quarters. It is settled. O chief of the twice-born! and know. as connected with the (individual) self it is stated to be the tongue. as a tortoise (draws in) his limbs. Understand about them also. He who duly understands this. which is difficult to move in this mortal world. which is pervaded by disease and sorrow. and friendly and affectionate to all beings. O ye who understand piety! is here obtained by those who possess knowledge. . the flowing (element) water. together with the immortals. and the feeling of touch is air. fearful and unfathomable. bursting through the earth. the presiding deity there is Soma. The fourth should be understood to be water. which is made up of the five elements. the presiding deity there is Vâyu. O best of the twiceborn! Beings of two feet or more than two feet. which produces attachment to subtle (topics). It is a great ocean. The learned man who absorbs objects of desire from all sides. As fire kindled with fuel shines forth with a great blaze. and sacred study. A knowledge of this. One should place all these together. and is named delusion. which are born after the lapse of some time. that the body in which the color is fire. and who is devoid of passion. is the very wheel of time which rotates in this world. is called happiness (dwelling) in one aggregate. and which rests on the real (entity). Such is the teaching of the ancients. gift at a sacrifice. the objects of the senses. and being concentrated in mind. as connected with the (individual) self it is called the skin. The (mode of) conduct in which qualities are not (treated as) qualities. The second entity is air. and those which move crookedly. however. the presiding deity there is the sun. and the presiding deity there is the lightning. and by the restraint of all the senses which hanker after objects of sense. are the beings born from wombs. O best of men! The eternal seat (where) the Brahman (is to be attained) should be understood to be twofold-penance and meritorious action. one attains to that which is subtler than (the most) subtle (thing). in which one lives alone. The fifth element is earth. which is free from attachment. are said to be born from germs. Restraining objects of desire within the self. which is uninterrupted. next as connected with objects it is color. and inferior.
The great Vishnu full of the Brahman is the king of kings over all. and Pitris. and the moon among the Nakshatras. concentrating the mind within the mind. he sees the self with the self in all entities as one. among cattle also the bull. and the creator. who am full of the Brahman. And he who in this world has vanquished the three qualities and the five constituent elements. and Rakshasas. and . Understand him to be the ruler. among all sacrificial animals the sheep. demons. Purandara of (all) deities. the Sveta. the Trikûtavat. sacrifice of (all) initiatory ceremonies. Likewise the Maruts are (the princes) among the Ganas. the Pâriyâtra. treachery. and also gods. and among females a male. He is the lord whose faces are in all directions. these are the princes among mountains. and likewise the Mâlyavat mountain. and Indra is said to be (the king) of the Maruts. the Nîla. CHAPTER XXVIII Brahman said: Among men the royal Kshatriya is the middle quality. the creator. Crossing the river of which the five senses are the lofty banks. The Nyagrodha. Agni. he then perceives that highest (principle). and great. and Brâhmanas are the bridges of piety. and among the dwellers in holes the snake. For he is the ruler of men. ever extol. changing from time to time. and Mitra. and the bands of Rakshasas. likewise. Yama is the prince among the Pitris. Understanding everything. Arka is the king of hot (bodies). and Varuna. Among all those who are followed by (men) full of desires. which are difficult to get rid of. and likewise the Sâlmali.Desire. and likewise the bamboo and willow. and go into wrong paths after death. of gods. Vishnu is the chief among the strong. Among women who are (a source of) happiness. the good do get rid of by restraint of the senses. and Prajâpati. the agitation of mind the mighty waters. (am lord). these are the princes among trees in this world. He verily is Vishnu. Him. and Siva is the ruler of (all) creatures. and among all vipras the powerful king Soma. obtains the highest – the infinite-seat in heaven. among vehicles the elephant. lose all their qualifications. the brilliant Apsaras (are chief). and also all the great sages. Know the goddess Umâ to be the best and (most) holy of (all) females. avarice. and of all entities whatever I. Understand this. Tvashtri is the prince of the Rudras. and attain the infinite (seat) after death. and the bands of Bhûtas. snakes. and the Koshthavat mountain. likewise. and delusion the reservoir. and Nâgas. Non-destruction is the highest piety. the Jambu. of Gandharvas. one should vanquish both desire and wrath. and demons. wrath. and Yakshas. and Yakshas. the Sinsapâ. there is no doubt of that. and Indu is said to be (the king) of shining bodies. Kubera (is lord) of all jewels. Soma is the lord of herbs. the sun is the prince among the planets. who has beautiful eyes. the uncreated Hari. Kinnaras. and seeing the self within the self. (all these). and also as various. (In him) the great self – the heart of all beings – is resplendent. fear. O chiefs of the twice-born! I shall now proceed to state the invariable characteristics of piety. Therefore a king should always endeavor to protect the twice-born. and the Meshasringa. There is no higher being than myself or Vishnu. Prajâpati (is lord) of all peoples. the Vindhya. the Guruskandha. the Bhâsa. and Pisâkas. the Sahya. the Mahendra. Kings desire piety. (the chief) is the great goddess Mâhesvarî. Varuna is the king of the waters. But those highsouled kings in whose dominions good men are protected. rejoice in this world. The Himavat. He is the supporter. Freed from all sins. and birds. and Maghavat likewise of the gods. and the ocean among rivers. the Pippala. Such is the highest creation among all entities. She is called Pârvatî. Those kings in whose dominions good men lie low. and falsehood also. He can always perceive (numerous) bodies like a hundred lights from one light. and among denizens of the forest the lion. all companies of Brâhmanas. Fire is ever the lord of the elements. the north among the quarters. and Brihaspati of Brâhmanas.
words are the characteristic of speech refined into vowels and consonants. And all the quarters residing in the ear are celebrated as (being appointed) to the knowledge of sound. to be created and tied down to a beginning. the essence of water. a determination is here formed by (that) understanding about objects which have been thought over by the mind. then enters into the Kshetrajña. to the truth. and that is comprehended by the ear. and hear it.destruction is of the nature of impiety. who resides in the tongue. To (this) positive comprehension. and knowledge. the supporter of all beings. abandoning qualities. The characteristic of mind is meditation. do not know themselves. and transcending the qualities. and having his sins destroyed. he is the Supreme Lord. and about the means for its comprehension. Enlightenment is the characteristic of gods. And the Kshetrajña likewise perceives all the operations of the qualities. The characteristic of devotion is action. know. which is void of symbols. the Nakshatras Sravana as the first (among them). I will now proceed to explain properly the comprehension of the qualities. verily. Thought is the quality of mind. which is in its essence devoid of qualities and eternal. is appointed to the knowledge of taste. and the seasons the winter as the first (among them). The earth is the source of . As to the smell of the earth. The quality of space is sound. the unperceived (is appointed). transcendent. and that is comprehended by the understanding. belonging to the air. The Kshetrajña. there is no doubt of that. and the characteristic of a good man is (living) unperceived. The (sensation of) touch. The supporter of consciousness residing in the heart is appointed to the knowledge of mind. Taste. And I always see. and homeless. Only the Kshetrajña attains. giving prominence to knowledge. CHAPTER XXIX Brahman said: I will state truly all about that which has a beginning. is not to be comprehended by any symbols. The unperceived is stated to be the Kshetra in which the qualities are produced and absorbed. (else) attains. in this world. action the characteristic of men. It is stated that day was first and then night. is perceived by the skin. Likewise as to what is described here as understanding. Therefore the characteristic of the Kshetrajña. The understanding (is comprehended in the form of) determination. the characteristic of earth. The quality of light is color. together with names and characteristics. Therefore a man of understanding should practice renunciation. and the Mahat of knowledge. the characteristic of renunciation. The qualities created again and again. is smell. the characteristic of mind is thought. and the creation. middle. and the wind likewise residing in the nose is a pointed to the knowledge of smell. that months have the bright first. middle. One who is free from the pairs of opposites. And crossing beyond darkness. free from the ceremony of salutations. (the sensation of) touch is the characteristic of air. color is the characteristic of light. sound is the characteristic of space. no one. and the sun residing in the eye is appointed always to the knowledge of color. who is unmoving. And the moon likewise. and end. and from the svâhâ ceremony. and transcending death and old age. which is great. The renouncer possessed of knowledge attains the highest goal. is always comprehended by the tongue. he repairs to that which has no second. and that is comprehended by the eye. therefore is he called Kshetrajña. Thus have I duly spoken to you concerning the characteristic of piety. and end. is the Kshetrajña. And there is no doubt of this that determination is the characteristic of the understanding. that is comprehended by the nose. taste is the characteristic of water. Hence a man who understands piety. and the wind residing in the skin is always appointed to the knowledge of (the objects) of touch. The Purusha knows it. (though) concealed. and beyond the qualities and the entities (produced) from the qualities. being nonintelligent. is purely knowledge.
selfexistent Vishnu is stated to be my own self. which moves in the midst of disease and misfortune. a wheel of which the spoke is the understanding. whose senses are subjugated. gift. Sâvitrî of all branches of learning. Dânavas. . the goat is mentioned (as the first). and Yakshas. which is lit up by the great egoism. the rotations of which (constitute) day and night. which is ever revolving and void of consciousness. Îsvara is the lord.smells. Among all things to be eaten or swallowed food is the highest. and among all reptiles. there is no doubt of that. there is no doubt of that. water is the best. Of all orders. all this ends in destruction. too. The unperceived is the source of the worlds. of which the outer rim is the five great elements. the wind is stated to be the source of (the feelings of) touch. the ever holy field of Brahman. observances. Of all mountains. is the source of the entire universe. of which the environment is home. Now I shall proceed to state the highest and first of all entities. there is no doubt of that. Likewise the Gangâ going in three paths is stated to be the first-born among rivers. and regulations. and among vegetable (products) likewise the barley seed. who is devoid of egoism. The great Vishnu. study. which moves through (all) the worlds. of all words. And the unthinkable. Prajâpati of deities. the mud for which is penance and regulations. whatever is prescribed in this world. Sacrifice. is stated to be the first. water of tastes. which is enveloped in the fearful waters of delusion. The Syena is first among birds. is everchanging. that of householders (is the first). and Rakshasas. the fastenings in which are vexations. There is no end for knowledge. And among all quarters and sub-quarters. of which the bonds are the group of the senses. These are the qualities of the elements. the great Meru is stated to be the first-born. which revolves in the midst of grief and destruction. all ascents end in falls. and than whom there is no higher being in these three worlds. the offering (into the fire) is the best. likewise. which is measured by months and half months. I. snakes. Bhûtas. The Gâyatrî is the first among meters. gold (is the first). the noise of which is trouble and toil. all that is called Sâvitrî. and the twice-born among men. Pisâkas. the night ends with (the sun’s) rising. O best of the twice-born! the snake is the highest. fire is said to be the first of the elements. without distinction. Cows are the first among quadrupeds. among sacrifices. who is devoid of (the idea that this or that is) mine. All accumulations end in exhaustion. and of men. the end of pleasure is ever grief. which staggers in the opening or closing of an eyelid. all associations end in dissociations. The sun is the first among shining bodies. who is full of the Brahman. which rotates in space and time. And among all immovable entities. is released from all sins by pure knowledge. the end of grief ever pleasure. which is full of actions and instruments of action. and hunger and thirst the nails fixed into it. (am the first) among all the patriarchs. the ocean is the first-born. Among all precious things. Therefore one whose self is tranquil. CHAPTER XXX Brahman said: The wheel of life moves on. among (sacrificial) animals. and life ends in death. the syllable Om of all the Vedas. Days end with (the sun’s) setting. which is encircled with cold and heat of which pleasure and pain are the joints. (everything) movable or immovable in this world is ever transient. and the Prâna lifewind. And likewise of all wells and reservoirs of water. the mover of which is the force of the quality of passion. the light (of) the sun is the source of colors. penance. of which sunshine and shade are the ruts. death is certain for whatever is born. which abounds in old age and grief. and the same is also the end of everything. And of all gods. Kinnaras. which is sustained by the qualities. likewise space is the source of sound. Of all ages the Krita is the first. All action ends in destruction. the eastern quarter is the first. the Plaksha. and of all liquid substances which are to be drunk. of which the pole is the mind.
and equable to all creatures. or of cotton. which is produced by ignorance of various (matters) which is attended upon by fear and delusion. with the permission of the preceptor. he should have matted hair. who is self-restrained. and be of pure vows. which is rendered unsteady by avarice and desire. one should perform the five sacrifices in this world. this has been celebrated from ancient times. and also the beggar. the imperishable source (of all). and which is extended by means of attachments. who applies himself to what is agreeable and beneficial to the preceptor. One should always have the sacred thread and a clean cloth. the speed of which is like that of the mind. and who understands the Vedas. conquers heaven. There should also be a girdle of muñga. should be kind. or a cloth entirely (dyed with) reddish color. to such a one the (word) good applies. and should stand. who is not thoughtlessly active with the hand or foot. which is made up of (the entities) beginning with the Mahat and ending with the gross elements. should. the sage who understands piety. should eat (the leavings) of sacrificial offerings. and should give and receive gifts. who is thus devoted. is never deluded. who is devoted to Vedic rites. should avoid heedlessness. who always accurately understands the movement and stoppage of the wheel of life. all these four orders are stated to have the order of householder for their basis. and take exercise (duly). being (born) in a caste of (high) qualifications. released from all impressions. kind. And as to the other remaining three duties. and which is the cause of the delusion of all beings. one who is devoted to his own duty and learned. The clothing of the twice-born (man) should be of linen. and constant in veracity and piety. should sacrifice twice to the fire after becoming clean and with a concentrated (mind). – (thus) one should adopt the sixfold mode of life. which has desire and wrath as its appurtenances. one should restrain one’s lust and hunger. Know that three (of these) duties are the means of livelihood for Brâhmanas. Always devoted to his own wife. the two teaching and officiating at sacrifices. (That) sage. and should always bear a staff of the Bilva or Palâsa (wood). and check. who duly performs sacrifices and gifts according to his means. and keep a bamboo stick and a water-pot filled with water. possessed of forgiveness. and full of faith. study. and alms.which is large. and sacrifice. should likewise perform sacrifices and officiate at others’ sacrifices. and which is devoid of consciousness. in the way above stated. abridge. The householder. which is associated with the pairs of opposites. and the Brahmachârin. and likewise always (carry) water (with him). all the world. and likewise living as a Brahmachârin. That man among all creatures. The Brâhmana householder. The sage who eats what remains after (offerings) to deities and guests. He who has been first refined by ceremonies. behaving like good men. take food without decrying it. and who is not thoughtlessly active with his speech or any of his limbs. and should always associate with good men. and released from all sins. This wheel of life. transcending all pairs of opposites. together with the immortals should cast away. With regard to those three duties. who is a sage with all his senses restrained. should behave like the good. which moves towards joy and pleasure. CHAPTER XXXI Brahman said: Thus duly studying to the best of his power. with his senses restrained. should return (from his preceptor’s house). and also receiving untainted gifts. One should learn and teach. or also a deerskin. discharging all these duties as much as is in his power. they are pious duties. and which is (never) fatigued. and who has duly observed vows. Whatever system of rules is prescribed in this world. and self-restrained. attains the highest goal. and with one’s external organs restrained. making gifts. who is pure. gift. who is of rigid vows. who is not thoughtlessly active with the eye. which is unchecked. the forester. and have his sacred . sit. to follow it is good.
he should not taste any articles of food which have been eaten by others. he may dwell in one place. his path being pointed out by the sun. He should not wish for earnings in common with another. always dexterous. He should move about the world like a worm. and reaching the highest seat. and restrained in all his senses. astringent. or a Brahmachârin. freedom from anger. and devoted to veracity and piety. And the man who understands final emancipation should verily do all acts which he has to do. and he should walk with circumspection over the earth out of compassion to all beings. and which have come spontaneously. addicted to sacred study. And with his senses restrained. or a river likewise. and should also give them shelter at (the proper) time. always with clean water. be engaged in sacred study. air. eating little. He should not make any accumulations. and should eschew dwelling with friends. always making offerings likewise of pure water to satisfy the deities. kind. who is concentrated in mind. should not enter a town again. He should without sloth feed on water. does not return to birth. full of forgiveness. He should always practice a sinless (mode of) conduct. or bitter. One who understands final emancipation should seek for a livelihood without obstructing (other) creatures. and likewise living as a Brahmachârin. A householder. the sage should become free from all action. and free from attachment should always make one who comes (as a guest) take a morsel of food. He should honor guests. in accordance with the (regulations at his) initiation. He should eat just enough for livelihood – for the support of life. nor should he eat when honored. When eating. and of rigid observances. conquers heaven. he should bathe (every) morning and evening. or again a forester. and likewise no sweet juices. pure in body. He should not parade (his) piety. One who is thus devoted.thread. in order. he should go about for alms with a concentrated mind. and all forest-products down to grass as they come. a sage who has renounced (all) should go out of towns and dwell in forests. Restraining the external senses. Offering safety to all beings. and be agreeable to all beings. A man should always bathe in clean water. or the cavern of a mountain. seeking merely to sustain life. or which are pungent. and always living within the forest. Refined by means of all ceremonies. preserving his hair and moustache. He should also eat always after the deities and guests (are satisfied) and with his speech restrained. and when he goes about for alms. always in forests. and should not . And he should always without sloth give alms out of whatever he has for food. or the foot of a tree. and should not be dejected if he does not obtain (alms). and continent. restraint of the external organs. and concentrated in mind. and also straightforwardness. being restrained in mind. he should devote himself to these eight observances – harmlessness. And he should eat (only) what has been obtained with piety. (Such) a Brahmachârin. fruits. he should move about in a secluded place. – a forester whose senses are subdued and who is thus devoted conquers the worlds. and free from avarice. One who understands final emancipation should seek to obtain alms after the cleaning of the vessels (used for cooking). (he should pass) but a single night in a town. life as a Brahmachârin. looking out for the (proper) time. performing sacrifices. He should eat just enough for his livelihood – for the support of life. Nor should he beg for too much alms. and should not rejoice if he obtains. having a mind free from envy. and depending on the deities. not deceptive and not crooked. is esteemed. living on fruits and leaves. veracity. and in the rains. for an ascetic should be averse from all earnings (accompanied) with honor. Eating only a little. who wishes to apply himself to final emancipation should adopt the best (line of) conduct. and roots and Syâmâka grain. or a forest. In summer. in a place free from smoke and where people have already eaten. he should not go following after another. and habitual freedom from (the habit of) backbiting. by (giving him) water accompanied with roots. He should honor a guest who comes. Wearing a skin or the bark of a tree. He should make a fire and feed on the alms (obtained) without asking and without trouble. kind. and leaves. free from passion. freedom from (the habit of) carping. He should resort for shelter to an empty house.
He should perform piety. One who knows the truth. nor penance. nor valor. who is free from attachments to any entity. a wise man should always share (with others). who is free from egoism. without a head. depending on none. or the mind. He should not accept anything at all other than food and clothing. Nor. mind. untainted. and also devoid of sound. or by speech. He who is trusted by all beings is said to be the foremost among those who understand final emancipation. and who is free from salutations. which is free from the operations of the qualities. Freed from all attachments. . nor worlds. who is free from expectations. and the five great elements. and stable. nor should one wish for gold. being released from all bonds. which is free from anxiety. The senses. behaving so that others would always disrespect him. pebbles likewise. should not teach. One who draws in the senses from all sides as a tortoise (draws in) his limbs. and should be void of (all) belongings. one should disregard the present. nor should he do anything wrong openly or in secret. water. and the Purusha likewise. not finding fault with piety. nor the senses. nor should one be perturbed by any other (person). flowers. any action involving expectation of fruit. by an accurate determination about the truth. devoid of smell. and without fixed appointments with people. or the assemblage of people. Though undeluded. One should not think of what is not come. and who understands the truth. Rejecting all things. always dwelling in all entities. one attains heaven. they never die. He should not defile anything by the eye. Therefore the learned man who knows (the) property of being void of symbols. nor reflect on that which is past. or back. and who is dependent on none. and which is also devoid of flesh. who is free from desires. understanding these same (entities) at the time of the termination (of his life). or cause to be performed. nor Vedas. There the understanding reaches not. Those who perceive the self. nor should he ever give to others. like the atmosphere dwelling in space. And he should accept as much as he eats and no more. One should not live by the occupation of an artisan. and then. and self-controlled. and who is free from (the thought that this or that is) mine. devoid of taste or touch. there is no doubt of that. and being equable to all beings. understanding. imperishable. is emancipated. One should not perform. and resorting to concealed piety should adopt the mode of life (necessary) for experience. which is unattached. nor the deities.follow his own (mere) desire. absolute. after understanding all these. He should not receive from others. and free from distress. the attainment to it of those who are possessed of knowledge is stated to be without comprehension of symbols. divine. foot. sacrifices. and understanding are absorbed. with his accumulations exhausted. he gets emancipation. the unperceived. he should act in the manner of the deluded. who is attached to the self. One should eat what is consecrated by faith. That sage is said to be the best who has adopted this (line of) conduct. One should not perturb any other (person). devoid of color. He should not appropriate another’s riches. should be free from attachment. one should become an ascetic with small belongings. being concentrated (in mind) and indifferent to time. and in whom the senses. which is to be understood. and should not take (anything) unasked. who understands all truth. who is free from the pairs of opposites. who is free from anxiety for new acquisitions or protection of old acquisitions. after enjoying any object should one become afterwards attached to it. and fruits which are not secured (by anybody). without a stomach. he attains to the highest seat. and though dwelling in a house. exclusively pondering on one point. or involving any destruction of life. egoism. One who has anything to do should take earth. and mind. which is without hands. and should not find fault with the ways of the good. and should avoid (all) controversies. should act without a purpose. as they come. verily. One should not hate. should meditate. and leaves. and the objects of the senses. But owing to the helplessness of people. and from the ceremony of svâhâ. being devoted to pious conduct. moving and unmoving.
even for (the space of) a wink. is emancipated. and understand the Brahman and wish for the supreme. The men of talent. of unthinkable qualities. association and dissociation. There are these two birds. devoid of qualities. developed from the qualities. becomes fit for immortality. (correct) conduct is the means to piety. is emancipated. attains to that everlasting (principle) which is free from the pairs of opposites. free from (the ceremony of) svadhâ. (which are) unchanging. He who desires nothing. Abandoning all action. He who even for (the space of) a (single) exhalation. and devoid of qualities. is released from misery. The learned man who perceives. death. and abandoning both truth and falsehood. who are pure. Cutting and piercing this (tree) with the sword of knowledge of the truth. The great tree of Brahman is eternal. then understanding the Kshetra. and old age. and some (think of) the Brahman as unperceived. But as to that other who is above them. and transcending the qualities he is released from all sins. and renunciation the best penance. and despises nothing. whose collection of boughs is the great egoism. and abandoning the bonds in the shape of attachment. which cause birth. a wise man who is free from (the thought that this or that is) mine. becomes eligible. and which should also be known to be unintelligent. and being untainted. there is no doubt of that. Penance is said to be a light. Restraining the self in the self. some (think of) the Brahman as a great forest. he is called intelligent. there is no doubt of that. at the time of the termination (of life) becomes equable. whether agreeable or disagreeable. transcending passion. for assimilation with the Brahman. even dwelling in this world. go to the happy path by penance. and they think all this to be produced from and absorbed into the unperceived. knowledge verily should be understood to be the highest. perceive that supreme (principle) by means of knowledge and penance. understands that which is beyond nature. there is no doubt of that. and who is devoid of egoism. devoid of knowledge of nature. and (the attainment of it) depends on Vedic knowledge. by tranquility only. everlasting. it is free from the pairs of opposites. and whose minds are refined. he is laid down (as being able) to move everywhere. and understands the Pradhâna of all entities. who is free from (the thought that this or that is) mine. and free from egoism. he repairs to the inexhaustible acquisition of those who have knowledge. attaining to the self. through the tranquility of the self. One who is free from the pairs of opposites. in which agreeable and disagreeable fruits are always produced. which is always possessed of leaves. and likewise unity and diversity. He who understands determinately the self which is unperturbed. and which is the essential element in knowledge. a tree which is produced from the unperceived as the seed. and the Brâhmanas dwelling in the seat of the Brahman understand knowledge to be concerned with the Brahman. always possessed of flowers. He who knows the truth about the qualities of Pradhâna. Those who are constantly devoted to renunciation. the sprouts within which are the senses.CHAPTER XXXII Brahman said: The ancients who perceived the established (truth) call renunciation penance. and (as it were) non-intelligent. And restraining the life-winds again and again . and some as transcendent and without misery. CHAPTER XXXIII Brahman said: Some (think of) the Brahman as a tree. (When) the inner self. free from the (ceremonies of) salutation. and which is fed upon by all creatures. and the side branches the objects of sense. a creature is emancipated. the great branches of which are the great elements. The highest Brahman is very far off. and with an understanding comprehending all. which consists of the understanding as its trunk. which abides in all entities. and supreme.
and (others) that it exists not. equability. and others tranquility. too. The preceptor said: Then those Brâhmanas. and others say that is not so. straightforwardness. and others that that is not so. other Brâhmanas (say) sacrifice. and others (that it is) mixed. and others. knowledge. Thus addressed by those Brâhmanas. O best of the twice-born! Forgiveness. but others extol penance. and some given up to destruction. holy. and some for pain. By inference we understand the (attainment to the) being to depend on goodness. of ten or twelve (modes). others are intent on fasting. courage.by control of the life-winds. O best of the gods! piety being thus confused and abounding in contradictions. some knowledge. believe it to be one. Some (say) everything is doubtful. be obtains whatever he desires. and some (are) clean-shaven and without covering. Between the gnat and the udumbara there is observed unity and diversity also. some are for merit and glory. and also renunciation are laid down as (constituting) conduct of the quality of goodness. and renunciation. Unity and diversity are likewise laid down. Some Brâhmanas. some say that is not so. this is good. the venerable. Be pleased now to proceed to state what is (so) mysterious. others distinct. Such is the doctrine of the learned. Some have matted hair and skins. People are acting. That they are always distinct (from one another) is also (said) without (due) consideration. It is not possible otherwise to attain to that being. who know the Brahman and perceive the truth. such is their relation. that fits one for immortality. The men of knowledge extol nothing else beyond goodness. (such is) the relation of the drops of water with the leaf of the lotus. others that that is not so. and what is the cause of the connection between the Kshetrajña and nature. And. Some (say it is) of one form or twofold. assert the unity of the Kshetrajña and nature. Some extol everything. some various kinds of enjoyments. But that is not correct. Thus having first a tranquil self. Some are for taking food. CHAPTER XXXIV The sages said: Which (form of) piety is deemed to be the most worthy of being performed? We observe the various modes of piety to be as it were contradictory. some are in the midst of doubts. Some people (say) meditation. Some (say) means should be resorted to. and others nothing. (saying) this is good. O best (of beings)! to be informed of what is good. we are deluded. too. Some are devoted to goodness. By this very inference the wise verily believe in the Being and nature as one. Here (therefore) our understanding breaks down. some are for pleasure. (he repairs to) that which is beyond the twenty-four. and our mind is distracted. who are devoted to knowledge. Some people are for bathing. and come to no determination. gifts. Distinction and also association should be accurately understood. and other persons sacred study. some wish for riches. having again felt doubts. and talented creator of worlds told them accurately (what they asked). As a fish is in water distinct (from it). always esteems that. nature. truth. Some extol final emancipation. who were the best of sages. that it exists. harmlessness. some for the omission of bathing. and those who ponder on the element. there is no doubt of that. and others again (that it is) manifold. When the quality of goodness predominates in the unperceived. abandonment. We wish. Some are devoted to harmlessness. And he who is attached to a certain (form of) piety. Some say (it remains) after the body (is destroyed). and others indigence. Some say both time and space (exist). and others. interrogated the grandsire of the people who spoke to them thus. . and others that there is no doubt. Some learned men. Some say the permanent (principle) is impermanent. Some people extol action.
but the flame is extinguished when the oil and wick are exhausted. being born again and again. and who knows about the qualities. and having crossed (it) goes to the other shore. Nature which is non-intelligent knows nothing. Those who without sloth perform actions with expectations. For a man to see within (his) self what is agreeable and what is disagreeable to him is good. And one who is possessed of knowledge enhances (his) happiness even with a fourth share. such is the progress of the men of understanding. and who entertain avarice and delusion. comprehending the gradations one above the other. throwing aside the boat. But those wise and talented men. travels with great discomfort. This is the highest seat. And as one who is devoid of a perception of the truth rashly travels on foot by a long way unseen before. undoubtedly wishes for destruction. and is connected with (all) knowledge. and in essence free from the qualities. that by action the fruit is or is not produced. And those who are constantly engaged in destruction. and soon crosses the reservoir. Now I will proceed to. Even brought into contact with all qualities. though it is the object of enjoyment. Hearing it all. and to be constituted of the qualities. while (another) goes by the same way in a carriage drawn by horses. O Brâhmanas! Well now. go verily to hell. As far as there is a carriage-path. As a man traveling along some way without provisions for the journey. Having climbed up a mountain one should not look at the surface of the earth. free from any connection with expectations. where the carriage-path stops. This has been already explained by the parallel of the . and void of intelligence. Understand this. While there is oil and wick. For the talented man who knows (these) means. afflicted by reason of the chariot. the being is laid down (as being) unperceived. And the relation of the two is like that of matter and the maker. and going swiftly. devoid of parts. and nature is stated to be the object. state how the association and dissociation of Kshetrajña and nature (take place). free from vexation and holy in character. Thus nature is perceived. rejoice in this world. a learned man remains untainted. He abides in everything alike. and devoid of (the thought that this or that is) mine. that is deemed to be the greatest duty. The ancients who perceived the established (truth) call knowledge the highest happiness. Thus should one understand the accomplishment of piety by (apt) means. so should one understand. Learn that. as (having the relation) of the gnat and the udumbara. perceive correctly. through delusion. attains supreme happiness. The subject is always the being. O best (of men)! The relation here is said to be that between the object and subject. he goes in the carriage. who understands the procedure respecting (knowledge of the) truth and devotion. As one goes into (a) dark (place) taking a light (with him). So travels the talented man. It is established that nature is the property of the being. while a wise man likewise knowing distinctions and having a boat with good oars. who perform actions with faith. O best (of men)! Learn what a preceptor told a pupil who went to him. As one who without a boat dives into the ocean with his arms only. Therefore by pure knowledge one is released from all sins. the Kshetrajña is free from the pairs of opposites.CHAPTER XXXV Brahman said: Well then. Non-destruction of all creatures. I will tell you something more. There is no doubt that the being is unattached just like the unsteady drop of water placed upon a lotus-leaf. and who are infidels in their conduct. One who has a bad understanding does not acquire knowledge even with a thousand (admonitions). and may even be destroyed on the way. I will declare to you what you ask of me. and he always enjoys nature as a lotus-leaf (enjoys) water. a learned man goes on abandoning the carriage. goes in the water without fatigue. Nature is said always to abound in the pairs of opposites. One sees a man traveling in a chariot. the light shines. deliberate on it properly. It has been explained in the above mode. Who enjoys and what is enjoyed is learnt from the Sâstras. so those who wish for the supreme go with the light of nature.
– thus should smell. and grey likewise. so does it result to them. glutinous. I will speak at length of the numerous qualities of sound. and are conversant with piety. the great elements. thus is light said to have three qualities. square. Taste is stated to be of numerous descriptions. sour. and above that understanding is the self. Rough. and smell as the fifth – these. red likewise. who are conversant with piety and perceive the truth. and smell is stated to be (of) numerous descriptions. touch. O best of the twice-born! should be understood to be the five qualities of earth. and touch is stated to be of numerous descriptions. green. And likewise one cannot move in water after entering a carriage. and of the elements respectively. slippery. is of four qualities. a development of the unperceived is the Mahat. sour. it is said that light has three qualities. and color likewise. and saltish likewise – thus are the forms of taste. which is produced in space. broad. Egoism is of the nature of seed and a product also again and again. who speak the truth. black. air is said to have two qualities. Smell is agreeable or disagreeable. yellow. The quality of light is color. and color is stated to be of numerous descriptions. Thus sound. Madhyama. and above the unperceived is the being. abounding with movables and immovables. should be understood to be of five qualities. sharp. Sound. Space is the highest element. and also productive in its essence. cold and hot likewise. smooth. to be of twelve descriptions. touch. Now space has one quality. Thus there are various actions in regard to different objects. above that is the unperceived. that is called the Pradhâna. air is said to have (these) two qualities. and taste. namely. sweet. adheres to that like a fisherman to his boat. One who knows which is superior and inferior among entities. And touch is the quality of air. Smell always belongs to the earth. and circular-thus is the color of light said to be of twelve forms. Learn about their properties. Sweet.carriage and pedestrian. be understood to be of ten descriptions. short long. and who identifies himself with every being. and clear also. Now space has one quality. said to be of six descriptions. The unperceived is of the nature of seed. full of examples of agreeable and disagreeable (things). and bitter likewise. hard. together with Gândhâra. which belongs to the earth. which is a development of water. soft. Sound. are stated to be the qualities of water. and earth. I will now give (some) information about taste. repairs to the imperishable self. astringent. It should be understood by aged Brâhmanas. Shadga. but they do not yield products. and likewise color. objects of sense are verily stated to be the development. diffusive and compact also. and a development of the Pradhâna (when it is) become Mahat is egoism. being overcome by (the thought that this or that is) mine. The objects of the five elements are of the nature of seed. hurtful. which is void of any smell whatever. It is not possible to move on land after embarking in a boat. bitter. egoism is above that. And the five great elements are verily of the nature of seed and products. and who knows the proper procedure in all actions. That which sages by their understanding meditate upon. narrow. tender and clear also. color likewise. touch. White. One who has come by delusion through affection. void of taste. too. From egoism is produced the development. And we have heard that the great self is of the nature of seed and a product. or sound. and soft – thus the quality of air is properly said by Brâhmanas who have reached perfection. and beyond these should be understood to be Nishâda and Dhaivata likewise. CHAPTER XXXVI Brahman said: . agreeable and disagreeable sound also. Sound and touch also should be understood. and of (many) ingredients. above egoism is understanding. should be understood to be of ten descriptions. I will state at length the numerous qualities of smell. the divine source of all entities. and that is stated to be sound only. Rishabha. taste. Sound. and likewise Pañkama. compact. And as action is performed in this world. and rough. and water. touch. Now that Pradhâna is unperceived. and void of color.
and having their minds always tranquil. is released from. and in which the understanding is the drag. in (the matter of) absorbing or bringing (them) forth. and resorting to the pure (quality of) goodness. they go near Prajâpati. is adorned with planets and nakshatras. which is the unperceived. always reach perfection by penance. all that can be accomplished by penance. Whatever is difficult to obtain. and ends with the gross objects. That which begins with the unperceived . and the understanding are always joined to the Kshetrajña. has the mind for a charioteer. (who are) constantly devoted to penance. and it is called the Kshetrajña. even from those five elements. and is decked on all sides with nets of rivers and mountains. Those who are free from (all thought that this or that is) mine. Pitris. (He) necessarily (becomes) that on which his mind (is fixed). The Lord Prajâpati created all this by the mind only. gods. one who destroys an embryo. The great elements are in every way (beyond) the elements that make up the world. a sage should sit down self-restrained. the mind. This forest of the Brahman begins with the unperceived. the creators of the world. The senses. and abandons everything as fruitless. and getting rid of the (qualities of) passion and darkness. Born from that same unperceived (principle). and (after) these developments. receives light from the radiance of the sun and moon. and always beautified likewise by various (descriptions of) waters. by means of a pure concentration (of mind) on contemplation. difficult to learn. And he who is released. like billows in the ocean. enter into the unperceived accumulation of happiness. (sacrificial) animals. And in like manner. Those who best understand the self. Gandharvas. obtain the great and highest world. The understanding proclaims its power. In this the Kshetrajña always moves about. that sin only by penance well performed. all the elements. difficult to vanquish. and the understanding for a drag. a man gets rid of all sins. again acquiring knowledge. and includes movables and immovables. These Brâhmanas. For all acquisition has penance for its root. for penance is difficult to overcome. and being full of egoism. And whatever is produced from them is dissolved in due time in those very five great elements. who have acquired concentration by a course of penance. and the various sciences are all acquired by means of penance alone. goes to the highest goal. one who violates the bed of his preceptor. and difficult to pass through. nor by a cause. movable or immovable.Since the mind is ruler of these five elements. Medicines. Those who without sloth perform actions with expectations. and next the developments produced from the elements. That individual self. the mind itself is the individual self. they are the very first to be dissolved. He who understands him understands the Vedas. That learned and talented person verily. The mind yokes the senses as a charioteer (yokes) good horses. and who likewise feed on fruits and roots. And in like manner the noble(-minded) gods went to heaven. And in the same manner the sages attained the godhead by means of penance. The mind always presides over the great elements. those who have achieved perfection. perceive the triple world here by penance. and devoid of egoism. enter the highest world of the great. and all other creatures movable or immovable. attaining concentration (of mind) on contemplation. Withdrawing from the mind the objects of mental operations. One who drinks spirituous liquors. drives about on all sides the great chariot which is pervaded by the Brahman. one who kills a Brâhmana. Râkshasas. not by actions. are born here again and again. He should be understood to be the Kshetrajña. has the group of the senses yoked (to it). Those high-souled ones who are devoid of (the thought that this or that is) mine. and it is the goal of all living creatures. This is the eternal mystery. beasts and birds. men. Gods. one who steals. comes not by delusion in the midst of all entities. it is (the means of) subsistence for all entities. and who are free from egoism. all have been created by nature. Whatever entities (there are) in this world. (Those) men. and herbs. mounting the chariot to which big horses are yoked. Asuras. Pisâkas. Such is the upward gradation among entities. who always understands thus the chariot pervaded by the Brahman. attaining concentration (of mind) on contemplation.
O supporter of the family of the Kauravas! then having heard this (instruction) relating to the self. O Krishna! and who the pupil. he understands that holy Brahman. O Phâlguna! Vaisampâyana said: . O Janârdana! If this verily. This is the uncensored (mode of) conduct. Two syllables are death. is fit to be heard by me. which is uncreated. This goal can be reached by one who is alike to all beings. too. than which nothing greater exists. I wish to see him. Knowledge brings forth the being. Then will you attain perfection. he dies not. And when the understanding is clear. attained to that seat. And the nature of tranquility is as when one sees a dream. changeless. those high-souled sages acted accordingly. And the pupil. and then attained to the worlds. The self-restrained man who thus understands the immortal. He who thus understands the self to which there is nothing prior. The preceptor said: Thus instructed by the preceptor Brahman. O noble person. O you of mighty arms! Therefore fix your mind on this. he attains tranquility. Then when this piety is duly practiced. If you have love for me. and ever indestructible and unattached (principle). and that is acceptable and constitutes immortality. indeed. who is without expectations. This is the goal of those who are indifferent (to the world). Expelling all impressions. always duly act (according to it). I have now declared everything to you. O Dhanañjaya! I have related this mystery to you out of love for you. who is without attachment. he certainly becomes immortal and not to be restrained. changeless. having done all he should have done. three syllables the eternal Brahman. Vâsudeva. And now. incomprehensible. O best of Brâhmana. By action a creature is born with a body and made up of the sixteen. Some men of dull understandings extol action. This is the eternal piety. did everything (accordingly). with your consent. not full of action. you will attain the absolute final emancipation. unmoving. O son of Kuntî! and then attained final emancipation. This being is stated to be full of knowledge. But (you should) learn that whose nature is devoid of qualities. Arjuna said: Who. which is incomprehensible (even) to those who feed on nectar. and not mine is the eternal. Mine is death. O Lord! then tell it me. and restraining the self in the Self. Do you. was that Brâhmana. O supporter of the family of the Kauravas! going to which one grieves not. Therefore those who are far-sighted have no attachment to actions. And. And they see all the movements which are produced by development. O you of mighty arms! And know the mind to be my pupil. in consequence of these means. Vâsudeva said: I am the preceptor. But as to the high-souled ancients they do not extol action. getting rid of all sins. This is the goal of those emancipated ones who are intent on knowledge. of pure self! duly act according to the words of Brahman which I have stated. said: That pupil thus instructed in the highest piety by the preceptor. This is what is acquired by men of knowledge. O chief of the descendants of Bharata! it is long since I saw the lord my father. It was this same thing I stated to you before when the time for battle had come.and ends with the gross objects is stated to be of the nature of ignorance. sages! Act thus forthwith. then you will acquire perfection. and who looks alike on everything.
’ Om Tat Sat . and after taking leave of him to go to your own city. Dhanañjaya replied (saying). ‘O Krishna! let us verily go today to the city of Gagasa. Be pleased. who is of a devout heart.When Krishna spoke these words. O you who understand piety! to see there king Yudhishthira.
|
https://www.scribd.com/doc/118729277/Anu-Gita-Eng
|
CC-MAIN-2018-22
|
refinedweb
| 27,378
| 80.88
|
A recent blog post "If you don't like exceptions, you don't like Python" has made rounds lately, and compelled me to write a partial rebuttal. It is not like that blog post is completely wrong, but it is not the be-all and end-all of this topic. And if I may add, it is kind of opinionated.
The original article states that exceptions are central to Python, that the common advice "exceptions should only be for errors, not for normal flow control" is wrong, goes on, explaining that exceptions are used in core implementations, such as the iterator protocol, and attribute access, thus that they are a central feature of the language. Some longer parts of the blog posts are concerned debunking commonly held misconceptions by Java and C++ programmers.
Roughly speaking, exceptions in this article are portrait very favourably, with all that praise, all criticism and questions regarding their use are eclipsed.
Use exceptions for error handling
This is a point where I just whole-heartedly agree with barnert. Errors should be propagated using exceptions, so
def min(*lst): if not lst: raise ValueError("min(..) requires a list with at least one element") minimum = lst[0] for item in lst: if minimum > item: minimum = item return minimum
is a perfectly fine usage of exceptions, and callers should check for these exceptions if their code does not guarantee that the argument is a list of length above 0.
Exceptions are dissociated from values and variables
Sometimes I stumble over code that uses a pattern like this:
result = [] result.append(dosomething(bar)) try: foo = bar[key][anotherkey] res = dosomething(foo) result.append(res[evenanotherkey]) except KeyError: .... finally: return result
This snippet has many exception-related issues and shows how not to use exceptions. First of all, it is unclear which key-access in the try block does raise the exception. It could be in bar[key], or in _[anotherkey], then in res[evenanotherkey], or finally it could happen in dosomething(foo). The exception mechanism dissociates error handling from the values and variables. My question is: can you tell whether catching KeyErrors from dosomething() is intended?
So when using exceptions, one has to be really careful about which exceptions are caught and which aren't. With defensive programming (i.e. haskey())-style checks, it is unambiguous and hardly as "intrusive" to the code as writing out individual try-catch blocks for each indexing operation.
Exceptional Dangers
So there are basically two risks when using exceptions:
- An exception that should be caught is not caught
- An exception is caught wrongfully
The first risk is definitely a risk, but one that I don't worry too much about. The second is a risk I definitely fear. How many functions in your code can throw KeyErrors, ValueError, IndexError, TypeError, and RuntimeError can your code throw?
Exceptions as Pythonic gotos
Exceptions can emulate goto statements. Of course they are jumps to upper levels on the stack, but also within statements. In C code, goto's are a primary means of function-local control flow and error handling (and for error-handling, they are rather uncontroversial):
int max_in_two_dim(double * array, size_t N, size_t M, double *out) { if (N * M == 0) goto empty_array_lbl; double max = array[0]; for (int i=0; i < N; ++i) { for (int j=0; j < M; ++j) { double val = array[j * N +k]; if (val != val) // NaN case goto err_lbl; if (max < val) max = val; } } return 0; nan_lbl: fprintf(stderr, "encountered a not-a-number value when unexpected"); return -1; empty_array_lbl: fprintf(stderr, "no data in array with given dims"); return -2; }
You can model this usage with exceptions in Python. I have seen such code in the wild.
def whatever(arg1, arg2): try: for i in range(N): for j in range(M): # .. if ...: raise RuntimeError("jump") return out except RuntimeError: # cleanup # ..
In most cases there are ways to avoid this pattern that are preferrable. Python's for loops have an optional else branch that helps avoiding such jumps. Nevertheless, this pattern can go awry with a RuntimeError happending at some other place in the loop, etc.
Meta: Ingroup, Outgroup Thinking
What I disklike the most about barnert's article is probably mostly what one can read in the title: "If ..., you don't like Python". It is in line with a lot of talk I hear about code/software/solutions being "Pythonic". What this seems to imply is, that must take sides: Either you are in line with an orthodox Python community, or you are an outsider, someone who is not "Pythonic" enough. All of this is not helpful for improving code.
Conclusion
Exceptions are a central and powerful tool in Python. But use them with care and caution. Do not pretend that they are like a magic wand, don't use them to show your love for python. Use them when the individual situation calls for exception usage.
|
http://www.holger-peters.de/exceptions-the-dark-side-of-the-force.html
|
CC-MAIN-2016-44
|
refinedweb
| 821
| 61.26
|
Compute the standard error of the mean of list elements in Python
The standard error(SE) measures the spread of the data. The bigger the SE, the more spread the data have. The standard error (SE) of a statistic is the standard deviation of its sampling distribution or an estimate of that standard deviation. If the statistic is the sample mean, it is called the standard error of the mean (SEM).
The formula for the standard error of the mean:
If a statistically independent sample of n observations x1, x2, …, xn is taken from a statistical population with a sample standard deviation of σ, the standard error of the mean of the sample is given by
To compute SEM, you can use either scipy or numpy Python package.
Using scipy:
The scipy.stats module has a function sem() that calculates the standard error of the mean (or standard error of measurement) of the values in the input array. The format of the function is as follows:
scipy.stats.sem(a, axis=0, ddof=1, nan_policy='propagate')
In the following code, I am randomly generating 10 numbers to compute SEM. To use the following code, you can replace list ‘a’ with your list of values.
from scipy import stats as st a=np.random.random(10) se = st.sem(a)
Using numpy:
If you are not interested in the sem() function of scipy, you can compute the sample standard deviation for the values in the list and divide the sample standard deviation by the square root of the number of values in the list. The default ddof value for the numpy std() function is zero, which computes population standard deviation. You need to use ddof=1 to compute the sample standard deviation. The format of the numpy std() function is as follows:
numpy.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)
In the following code, I am using the same list ‘a’ and have set ddof to 1.
se = np.std(a, ddof=1)/np.sqrt(len(a))
Output
List ‘a’ had the following values:
array([0.23840975, 0.68159684, 0.747814 , 0.27296423, 0.07580225,
0.8901718 , 0.83292882, 0.03398631, 0.29072783, 0.22097503])
The value of SEM was 0.10247672761861855
Please let me know if you have any queries related to the above Python codes.
References:
|
https://www.bitsdiscover.com/compute-the-standard-error-of-the-mean-of-list-elements-in-python/
|
CC-MAIN-2022-40
|
refinedweb
| 396
| 61.97
|
Method Signature in Java with example
In this article, we are going to learn about the method Signature in Java. As we all know, Java is used for various applications due to its vast number of flexible modules, let us dive deep into one of its interesting features.
Definition – A method signature refers to writing the method name with its parameters without the return type of the method.
Passing parameters in Java is an essential chore for programmers.
For example, the Java method signature of the below example is:- method_name(int, int).
public class sampleclass{ public void method_name(int a,int b) { //method_definition } }
If we declare a different parameter for the same method, its method signature changes.
for example, for the below code, the method signature is:- method_name(double).
public class sampleclass{ public void method_name(double a) { //method_definition } }
Since the method signature does not allow return type, class methods can be overloaded. Method overloading includes no return type and only the type of arguments, method signature eliminates the error of different return types for the same function and support method overloading.
For example, in the below code, the function sample() is overloaded due to different parameters.
public class sampleclass{ public void sample() { //method definition } public int sample(int a) { //method definition } }
In the above code, since the method signature does not include return type, i.e, void, and int, function overloading in Java can be achieved based on the types of parameters. The method signatures of sample() are sample() and sample(int).
I hope this article is helpful, please put a comment in case of any query.
|
https://www.codespeedy.com/method-signature-in-java/
|
CC-MAIN-2021-10
|
refinedweb
| 267
| 52.7
|
Hi, I managed to get dvd+rw tools to build with a small change to the existing pkgsrc patches (to exclude the call to mlockall for DragonFly as well as for NetBSD). Unfortunately it fails to work exiting with the error message: :-( failed to create thread: Resource temporarily unavailable Which implies pthread_create failed with an EAGAIN error. This is on 1.5.0-PREVIEW. From my (admittedly limited) understanding of pthreads the code and the compile options seem to be correct. The simple patch for patches/patch-ac that got it to compile is: --- patch-ac 1 Feb 2006 12:51:27 -0000 1.3 +++ patch-ac 5 Mar 2006 15:48:08 -0000 @@ -24,7 +24,7 @@ nice(-20); /* I'd rather do it right after I allocate ring buffer and fire off * threads, but I'll be running without extra privileges by then:-( */ -+#ifndef __NetBSD__ ++#if (!defined (__NetBSD__)) && (!defined (__DragonFly__)) mlockall(MCL_CURRENT|MCL_FUTURE); #endif -- C:>WIN | Directable Mirror Arrays The computer obeys and wins. | A better way to focus the sun You lose and Bill collects. | licences available see |
|
http://leaf.dragonflybsd.org/mailarchive/users/2006-03/msg00023.html
|
CC-MAIN-2013-48
|
refinedweb
| 181
| 61.87
|
There’s a saying amongst programming language designers that every language is a response to previous languages; the designers of C# were, and still are, very deliberate about learning from the mistakes and successes of similar languages such as C, C++, Java, Scala and so on. One feature of C# that I have a love-hate relationship with is a direct response to a dangerous feature of C++, whereby the same name can be used to mean two different things throughout a block. I’ve already discussed the relevant rules of C# at length, so review my earlier posting before you read on.
OK, welcome back. Summing up:
- C++ allows one name to mean two things when one local variable shadows another.
- C++ allows one name to mean two things when one usage of a name refers to a member and a local variable of the same name is declared later.
- Both of these features make it harder to understand, debug and maintain programs.
- C# makes all that illegal; every simple name must have a unique meaning throughout its containing block, which implies that the name of a local variable may not shadow any other local or be used to refer to any member.
I have a love-hate relationship with this “unique meaning” feature, which we are going to look at in absurd depth in this series.
On the “love” side, this really does address a real source of bugs. I have myself accidentally-and-not-on-purpose introduced a local variable in one scope that shadows another and it took me literally hours of debugging to discover why it was that what I thought was one variable was suddenly changing values halfway through a function. On the “hate” side, based on my mail and questions on StackOverflow, misunderstanding what the feature is and why C# has this limitation is a frequent source of user confusion. It was also a rich source of bugs in the original C# compiler, spec problems and design problems in the Roslyn compiler.
But what makes it far, far worse for users is that the error messages given when a program violates these rules of C# are… well, you can see for yourself. Let’s start with the simplest possible case: a local variable which shadows another.
class C { static void M1() { int x2; { int x2; } }
This gives the error on the inner
x2:
error CS0136: A local variable named 'x2' cannot be declared in this scope because it would give a different meaning to 'x2', which is already used in a 'parent or current' scope to denote something else
Um… what?
It is no wonder I get mail from confused programmers when they see that crazy error message! And while we’re looking at this, why is
'parent or current' in quotes, and why doesn’t the compiler differentiate between whether it is the parent scope or the current scope? This is already weird, but don’t worry, it’ll get worse.
What if we cause the same bug the other way? Remember, a local variable is in scope throughout its block, not at the moment where it is declared; this means that you can move the location of a declaration around without changing the legality or meaning of the program, so we should expect this to be the same error:
static void M3() { { int x4; } int x4; }
This gives the error on the outer
x4:
error CS0136: A local variable named 'x4' cannot be declared in this scope because it would give a different meaning to 'x4', which is already used in a 'child' scope to denote something else
Aha! This is still terrible but at least now the silly quoted string is making some sense; the compiler is filling in either “parent or current” or “child” into the error message, and whoever wrote the error message felt that such a substitution ought to be called out in quotation marks for some reason.
It’s still weird that they went to all that trouble to differentiate between “parent or current” and “child” but didn’t bother to differentiate between “parent” and “current”. (And it is also weird that apparently scopes have a parent-child relationship; when a mommy and a daddy scope love each other very much… no, let’s not even go there. I think of scopes as having a container-contained relationship, not a parent-child relationship, but perhaps I am in a minority there.)
Another subtle thing to notice here: the error message is given on the second usage of the simple name in both cases; is that really the best choice? Ideally an error message should be on the line that needs to change. Which is more likely, that the user will wish to change the
x4 in the inner scope or the outer? I would guess the inner, but here the error message is on the outer.
And finally: “something else” ?! Really, C#? That’s the best you can do? The compiler knows exactly what this conflicted with; if it didn’t then it wouldn’t know to make an error! Let’s just make the user guess what the conflict is, why don’t we? Yuck.
OK, that deals with local variables conflicting with other local variables. Next problem: a local variable conflicts with a simple name that was used to mean something else:
static int x5; static void M6() { int x7 = x5; { int x5; } }
This gives the error on the declaration of the local:
error CS0136: A local variable named 'x5' cannot be declared in this scope because it would give a different meaning to 'x5', which is already used in a 'parent or current' scope to denote something else
Ah, same thing. This error message makes a lot more sense for this scenario than it does for the “hiding a local with a local” previous scenario. And of course if we reverse the order, putting the nested-block local before the field reference…
static int x8; static void M9() { { int x8; } int x10 = x8; }
We get this error on the initialization of
x10:
error CS0135: 'x8' conflicts with the declaration 'C.x8'
WHAT!?!?!?!?!? Why on earth did we not get the same message as before with “child” substituted in?!!?
This error message makes no sense at all; even an expert on the C# specification would be forgiven for not knowing what on earth this means.
So far I’ve shown cases where a local variable declaration conflicts with something else. Next time we’ll look at scenarios where the same simple name is used to mean two different things, but no local variable (or local constant, formal parameter or range variable) is involved. It might not be immediately obvious how it is possible that one simple name can be used to mean two completely different things without introducing a new name in a local scope, but it is possible. Your challenge is to find one that produces a compiler error before the next episode!
Oh no! C# forces you to name variables properly!
encourages..*
Hey, I just made variables called x2, x4, x5, x7… no one forced me to call them something sensible!
In some cases, there would be no more concise way to describe a variable than to describe the code used to compute its value. If the variable will only be used in the immediate vicinity of its assignment, I would posit that a “meaningful variable name” would represent visual clutter and be semantically less helpful than a short name which would cause someone reading the code to look up a few lines and see where the variable was actually assigned. Compelling people to come up with unique names for such “throwaway” variables isn’t helpful, IMHO. Better would be to have a nice mechanism for tagging them as “throwaways”.
“I think of scopes as having a container-contained relationship, not a parent-child relationship, but perhaps I am in a minority there.”
This is somewhat common in the IT industry.
For example on a WPF UI controls do have an obvious container-contained relationship while the Panel class has Parent and Child properties.
As for XML, elements do have an obvious container-contained relationship while XPath have axis specifiers like children, parent, sibling etc.
Maybe because the logical model of these constructs are usually based on trees (only the representational model shows the container-contained relationship).
Scopes do have and enforce such a relationship, but useful variable lifetimes do not. It’s not uncommon to create a couple of temporary variables, use their values to determine the value for a “real” variable, and then abandon the temporary ones. The useful lifetime of the real variable starts between the creation and abandonment of the temporary variables; if the real variable is only assigned in this one place, its lifetime should begin when it is assigned, but C-style scoping structures do not allow such overlapped lifetimes even though, interestingly, some assembly languages did.
Be careful when using the word “lifetime” in a language where closures exist.
But hey, I assume you meant (lexical) scope. And you can always introduce a scope, e.g. like this:
int result;
{
int part1 = // …
int part2 = // …
result = part1 * part1 + part2 * part2;
}
// use result here
If a variable is only going to be written once, it’s useful to be able to specify that. Java allows the syntax `final int x=y;` or `final int[] foo = new int[4];` to simultaneously declare and initialize a write-once variable. Although C# does not presently allow `readonly` to be applied to locals, such a declaration would allow better closure semantics since they could be passed by value rather than aliased. Unfortunately, there would be no way to say “readonly int result=part1*part1 + part2*part2;” and have that variable outlive “part1” and “part2”.
PS–I find it curious that the makers of C# decided to have it automatically hoist mutable variables into a closure without any special declaration. Given `int x; … StartAction( () => DoSomething(x) ); … ` I would consider it far from obvious that the programmer intends any changes to “x” between the time StartAction executes and the time DoSomething(x) executes to alter the value passed to DoSomething(). I would have liked to see a requirement that variables used within a closure must be marked either at the closure or at their declaration to indicate how they should interact with closures.
I would like “readonly” local variables as well; it has never made it to the top of the list.
I think it is safe to say that many people have regrets about how anonymous methods and lambdas evolved; whether they close over variables or values is certainly part of that. I find it somewhat distressing that “
query = from c in customers select c.Name == name;” changes its result set when variable
nameis changed and changes when the contents of collection
customersis changed, but does not change when variable
customersis changed! The query stays bound to the original reference stored in
customers, not the current value, but is bound to the current value of
name, and that’s weird.
It’s too bad `readonly` variables didn’t get added to the language with closures; Java won’t allow variables to be closed over unless they’re `final` [the language’s equivalent of “readonly”]. While there are some occasions when it’s useful to close over mutable variables, I suspect cases where one wants the variable to be mutable are *much* rarer than those where one doesn’t want a closure to ever see any value other than the one a variable had when it was created. Is it possible for the compiler to notice that a variable will never be written after a closure is generated, and refrain from hoisting the variable in that case? If so, do you think it might be reasonable for code validation tools to define a hoist-related attributes, and squawk if a variable is hoisted as mutable when it doesn’t have a special attribute indicating such intention?
What would you think of loosening the rule in such a fashion as to permit multiple declarations only in those cases where they would have no “direct” semantic effect, but could serve as a sort of assertion that the variable was not used in such a way that the redeclaration would have an effect? Essentially, allow redeclarations in those cases, and only those cases, where the exact same semantics would be achieved:
1. If every redeclaration created a new variable and bound the name to it until the end of the current scope, or
2. If all declarations of variables were hoisted to the tops of their scopes, and any duplicates were simply ignored.
In cases where the two styles of compilation would yield different semantics, I don’t think evidence of programmer intent would be sufficient to silently favor one over the other and thus the compiler should quite rightly squawk. On the other hand, in cases where both styles of compilation would yield the same result, allowing redeclaration would serve as a means of drawing a “barrier” that would effectively assert “no value assigned to this identifier above this statement in the source code may be read beyond the end of it, and no value assigned in or below this statement will be used above.” In some situations it might be helpful to have a syntax for explicit barriers [e.g. if `varName` is a variable of any type, have “unassign varName;” statement indicate that if it is reachable at all, the following statement will be reachable with “varName” not holding a value] and possibly even have an explicit means of requesting C++ style scoping [e.g. have `hide varName;` and `unhide varName;` statements, require that “unhide” appear following “hide” in the same scope, and provide that an inner scope located entirely between the “hide” and “unhide” may use the identifier as it sees fit. Note that the requirement to pair “hide” and “unhide” should make them safe for use as context-sensitive keywords, since the only existing meaning for “hide foo; unhide foo;” would be to declare “foo” as type “hide” and again as type “unhide”, which should not be legal in any case.
Honestly, I don’t ever recall being confused by this message even the first time I saw it.
I believe it says ‘parent or current’ because technically the ‘current’ scope is really a conglomeration of all current scopes (that is, the deepest ‘current’ scope and all if its parent scopes). While it is possible to split this further into ‘a parent scope’ and ‘the xxxxx scope’, what do you replace xxxxx with? You can’t say ‘current’, because as I already mentioned the current scope is the same level and all levels above. ‘Sibling scope’ makes no sense because it’s not a sibling and ‘self scope’ is just a “Wtf?” moment. Since there’s no good term that I (or the author of this error message) could come up with to call the deepest sub-scope of the current scope, they used the relative definition of the script instead. xxxxx = current scope – all parent scopes a.k.a. ‘parent or current scope’.
In summary, it could simply say ‘current scope’, but that’s more confusing to someone who doesn’t have a full understanding of nested scopes (and thereby knows that the current scope includes all parent scopes) than simply saying ‘parent or current scope’.
“immediate scope”
what do you replace xxxxx with?
AFAIK, all scopes apart from those created by {} blocks inside a method are created by things that have names: packages, classes, methods. A better error message would be to use that name, when available. If not, say “elsewhere in this method” or something.
Not that I’m complaining. I’ve never had difficulty figuring out the problem from the error message. It’s so much better than C++, where the first error is often the only one worth reading, but frequently it only usefully means “an error of some sort was detected at this point”, which is sadly a lot less helpful than “there is an error of some sort at this point”.
I have had problems with classes named the same in different packages or named the same as a package; the latter I learned quickly not to do, the former I’m stuck with because SOAP code generation. It seems that class lookup is one place where C# does differ from Java.
There are definitely some crazy error messages around. And I’m looking forward to the rest of the series and the deconstruction of said error messages.
That said, I am so glad that these errors exist. It’s one of the things I love about C#, the way that the designers have addressed many of these oh-so-common scenarios where C/C++ lets you do some crazy thing that is almost certainly wrong, with nary a peep.
Another of my favorite C# features is the lack of conversions between bool and numeric types, pretty much completely eliminating the “oh, I accidentally typed = in my if-statement expression when I meant to type ==”.
Just a little nit from the editorial desk…
“whomever wrote the error message”
Nominative case, please. “Whoever”.
For what it’s worth, possibly confusing error messages and all, this is one of my favorite “you never really notice it” features of C#. I’ve been burnt in the past by the C++ problem of having multiple variables having the same name in the same method. That I can’t do that in C# is a huge, if largely invisible, advantage.
Yeah, the error messages could be clearer, but, it’s the kind of thing I look at and say “huh?” at first, but then quickly: “oh, I’m using x2 in two places with two different meanings”.
Thank you C# language designers.
I agree
Eric, I have posted on my blog talking about what I was thinking as I went through your post, figured I would let you know. I haven’t read all of your posts, but I do take notice when I see a new post, hoping that I can learn more than what I already know.
thanks for taking time out of your day to write these blog posts.
Might help if I left the link huh?
Even with somewhat unclear error messages, I much prefer the behavior of C# in this regard over that of C++ (or, heaven forbid, Javascript’s hoisting nonsense).
There are C# Design Notes which discuss the same feature: , specifically under Removing the shadowing restriction. Mads Torgersen is also describing a love-hate relationship:
Also, thanks for writing another “absurd depth” series!
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1703
I find this variable name conflict especially annoying in switch case situations
var i= 10;
switch(i) {
case 10: int myVar; break;
case 20: int myVar; break;
}
Error A local variable named ‘myVar’ is already defined in this scope
In that case I tend to give each case its own block:
var i= 10;
switch(i) {
case 10: {
int myVar;
break;
}
case 20: {
int myVar;
break;
}
}
Sure, so am I, but this is not elegant.
pro tip: don’t declare it the second time.
var i = 10;
switch (i)
{
case 10: int myVar = 1; break;
case 20: myVar = 2; break;
}
An Ugly protip you got there. It looks like the variable is used without ever being assigned in the second case… Why on earth does the compiler (and the specs) allow such an ugly thing?
far better to declare the variable once, then assign it when relevant
var i = 10;
int myVar;
switch (i)
{
case 10: myVar = 1; break;
case 20: myVar = 2; break;
}
Why is it that function parameters don’t follow the same rules?
For example:
class C
{
int x;
void F(int x)
{
}
}
Is allowed.
Because that is solved by the dreaded “this” keyword
Inside of F if you access x, it will be the parameter. To access x of C, you need to do this.x. I absolutely loathe the this keyword. I also loathe when people use it for constructor injection.
Suppose you can void F(int x) to just C(int X) { this.x = x } at some point a person is going to do { x = x } and unless you have resharper it will go unnoticed until you have runtime exceptions.
Actually, I like the “this” keyword quite a lot. It makes it crystal clear when something is a variable (or argmument) and when something is a member.
I do think it is unfortunate that you can hide a member with a parameter, though.
Count me in: +1 for the “this” keyword. For me at least, it increases reviewability of my own or someone else’s code a lot..
You don’t need Resharper to be warned about the x = x; redundant assignment.
Shows up as a compiler warning for me. “Assignment made to the same variable; did you mean to assign something else?”.
The rule is not “No name must ever shadow anything in any outer scope”. The rule is that every use of a name within a local scope must consistently refer to the same thing.
it’s a function parameter and not a variable, so a variable isn’t being declared in the declaration of the function.
A function parameter is a variable.
It’s interesting and ironic that VB apparently does not have this same restriction, because this feels like the same category of rule as “Don’t allow names to differ only by case.”. You’d think they would go together.
VB’s rule is a little different, though you bring up an interesting point: I wish languages would simultaneously require that variables be written using the same case as their declaration but *also* have variables shadow the declarations of outer-scope variables which differ only in case. If an outerscope declares `Foo` and an inner scope `foo`, then within the inner scope the identifier `Foo` should refer *neither* to the outer scope’s `Foo` nor the inner scope’s `foo`.
If a language allows `foo` and `Foo` to be used in the same scope with different meanings, then anyone who reads code aloud must explicitly distinguish uppercase and lowercase variable names. If names must differ in some fashion other than case, then someone who is reading code which is known to compile need not worry about variable case outside of string literals. But if variables which differ only in case can mean different things then it will be necessary about the case of everything. A massive increase in cognitive load, for a relatively minimal payoff.
Pingback: Dew Drop – September 26, 2014 (#1864) | Morning Dew
Your first examples for error CS0136 are all dead obvious. I see absolutely nothing confusing at all.
Now error CS0135, that one makes no sense at all.
dotnetchris I agree,
I’m pretty sure the answer to the challenge involves namespaces… I’m curious if there is another case.
This produces an error saying that “MyClass” is ambiguous; you’ve used a name once and it means two things. The challenge is to find a case where you use the same name twice and it means two different things.
What about this:
You’ve used the same name to mean two different things, but this is not an error. (Additional challenge question: why not?) The challenge question was to find a case where the same name means two different things that is an error.
I must be misunderstanding the quiz because this seems pretty obvious and it’s a compile time error: `public class Foo { public int Foo { get { … } } }`
The problem is to make two instances of the same name mean two different things in a local scope, such that an error is produced. Your example is not in a local scope, it’s at class scope. Here’s another way to characterize the problem: if either of the two usages is removed, then the program is correct, but using both is an error.
Again, let me state the rule: a simple name that is used multiple times in a local scope (including times where the usages are in nested scopes) must have the same meaning for every usage. The challenge is to find a program which violates this rule and thereby produces an error, but without one of the conflicting names being due to the introduction of a new local, lambda parameter or range variable.
By error you mean run-time error not compile-time error then?
I mean a compile-time error.
Would an answer consisting on some contrived use of a “contextually reserved keyword” qualify?
No, because then one of the uses would not be a simple name. The problem is to find two uses of the same simple name that mean two different things and produces an error.
The following code generates error CS0135 (‘M’ conflicts with the declaration ‘A.B.M’) but compiles successfully if either M() or M = 0 is removed:
You got it!
How is this a valid answer to the quiz? Either it is not or the quiz is unintentionally misleading considering part one of this series. M doesn’t mean two different things in this code. The compiler resolves M to a method group and sticks with it. There is no ambiguity here. In the examples in part one, the compile time error is thrown because the compiler has no way to decide to which x1 the code is referring to, so x1 can be either definition. In this example M will always resolve to the inner class definition (closest). There is a subtle but important difference. The compile time error gives it away; it tells you you are using M the wrong way, it doesn’t tell you it is not able know what M you are referring to. (maybe thats the whole point of part 2?)
Digging a little deeper, could the issue be that the ideal behavior of the compiler should have been to disallows this due to the deeper reason? That is, the possibility to use M to mean two things? This would be a subtly compiler bug with no solution as it would imply a breaking change: this same code but with the variable and method definitions switched (method M() declared in outer clas) compiles correctly.
Your statement “the compiler resolves M to a method group and sticks with it” is false. Extra credit challenge: justify why that is true with a quotation from the specification.
Well I’m not sure what the spec says, but intellisense its telling me M is void B.M() when I hover over either statement so I must deduce that the compiler is resolving M to the method group. (VS 14 CTP 3 by the way)
Your statement “in the examples in part one the compile time error is thrown because the compiler has no way to decide to which x1 the code is referring to” is false. The lookup algorithm unambiguously chooses the closer x1 in these cases. The error is not that x1 is ambiguous, the error is that the same name has been used to mean two different things.
Which in my book means x1 is ambigous. If it weren’t the compiler woildnt have any issues. If it could resolve what x1 you are referring without a doubt then the issue is moot. The fact that x1 is an ambiguos identifier is the problem.
Your statement “in the example M will always resolve to the inner class definition” is false.
Try removing each usage of M in turn, and you’ll see that there is no error, and that each one resolves to a different M.
I did, and M = 0 is always a compile time error, even if I remove M(). Again, this is VS 2014 CTP 3. class Outer
{
public static int M;
class Inner
{
public static void M()
{
}
public static void F()
{
M = 0; //Cannot assign to ‘M’ because it is a ‘method group’
}
}
}
Am I misunderstanding something?
class A
{
static void M() { }
class B
{
static int M;
void N()
{
M();
M = 0; // CS0135
}
}
}
Ok, the isse is that in VS 2014 this is not a compile time error. The code I was running is switching the place where M and M() are declared wich is a compile time error and to what I am referring to in my posts.
Yeah, I think that’s a mistake in VS2014, which is weird, because Roslyn does it correctly.
I note that this code compiles perfectly fine in VS 2014 CTP3 (must I understand that the compiler’s current behavior is a bug?). Also I am interested in knowing why the compiler behaves completely different if variable M and method M() declarations switch places.
I tried it out and you’re right, VS14 CTP3 does not give an error. But Roslyn does. I’ll enter a bug!
Surprisingly, this isn’t a bug in the compiler. The behavior is specified by the member lookup algorithm in §7.4 of the spec: if a member is invoked, then non-invocable members are removed from the candidate set before members hidden by other members are removed. So the M in M() resolves to A.M because the compiler drops B.M from consideration before it sees that B.M hides A.M. The behavior is different if A.M and B.M are swapped because there’s no corresponding rule to ignore invocable members when a member is not being invoked.
Eric, will you be explaining why the algorithm was designed this way? I think it would be much more intuitive if hiding were considered before invocability. Even ReSharper 7.1.3 gets this wrong!
The error of “static void M3() { { int x4; } int x4; }” kind really got me when I first ran into it. Because, um, the second x4 is not even shadowing anything?
All in all, this error is particularly annoying in lambdas:
var frob = frobList.Where(frob => frob.isFizzy()).FirstOrDefault();
Nope! Can’t do this, name the argument “x” or something.
The second x4 is in scope throughout the block, not just from the point where it is declared. Remember, the point of this is to ensure that you can make simple refactorings such as moving a declaration from the middle to the top of a block without changing its meaning.
class Program
{
static void Main()
{
int x;
int x;
}
}
A local variable named ‘x’ is already defined in this scope
Pingback: Confusing errors for a confusing feature, part two | Fabulous adventures in coding
Pingback: Confusing errors for a confusing feature, part three | Fabulous adventures in coding
|
https://ericlippert.com/2014/09/25/confusing-errors-for-a-confusing-feature-part-one/?replytocom=23532
|
CC-MAIN-2019-43
|
refinedweb
| 5,139
| 66.78
|
30 Golang Interview Questions and Answers for Your Next Job Interview
Google has created the Go programming language (referred to as Golang) to solve “Google-size” problems. And it has a strong chance of becoming the next enterprise programming language.
In a nutshell, Golang provides high performance (like C and C++) and super-efficient concurrency handling (like Java), while also being fun to code (like Python).
According to the StackOverflow survey for 2020, Golang is the second-highest paying technology in the USA and around the world. As more and more companies are using Golang, the demand for professionals in the area is growing fast.
Let’s take a look at some of the most common Golang programming interview questions, as well as how to best respond to these questions in an idiomatic way.
Last Updated August 2022
Google’s Go (Golang) from Beginner to Pro. Become a Professional Golang Programmer from Scratch.With Hands-On Exercises! | By Andrei Dumitrescu, Crystal Mind AcademyExplore Course
Question 1: How can you format the Go source code in an idiomatic way?
The Golang standards do not insist on a coding style as Python does, for example. Instead, the standards do recommend certain styles.
gofmt (golang formatter) will format a program’s source code in an idiomatic way. This makes it easy to read and understand. This tool is built into the language runtime, and it formats the Go source code according to a set of stable, well-understood language rules.
We can run it by typing the command at the command line or we can configure the IDE to run gofmt each time we save a file.
For example, gofmt -w main.go will format the source file main.go according to Go Programming Language style recommendations. The -w option writes the results back to the source file.
If we want to run gofmt on all files in a specific directory, we run: gofmt -w -l directory/
You can also run the go command with the fmt argument. It will execute goftm -l -w behind the scenes and format all source code in each file in the current working directory.
Question 2: You have developed a Go program on Linux and want to compile it for both Windows and Mac. Is it possible?
Yes, it’s possible to compile a Go application for different operating systems.
Question 3: How can you compile a Go program for Windows and Mac?
To compile the program, move to the application’s directory. Then execute the following commands in the terminal.
Compile the application for Windows and 64bit CPUs:
GOOS=windows GOARCH=amd64 go build -o my_go_program.exe
Compile the application for Mac and 64bit CPUs:
GOOS=darwin GOARCH=amd64 go build -o my_go_program
Note that for Linux and Mac it’s not necessary to use a file’s extension.
Question 4: Starting from an empty file, how would you create a Go program’s basic structure? Annotate the most important parts of the source code using comments.
// a package clause starts every Go source file
// main is a special name declaring an executable rather than a library (package)
package main
// import declaration declares packages used in this file
// fmt is a standard library package used to print to standard output (console)
import “fmt”
// function declaration. main is a special function name
// it’s the entry point for the executable program
func main() { // local scoped variables and constants declarations, calling functions etc var age int = 20 var today string = "Monday" // Println() function from fmt package prints out a line to stdout fmt.Println("Today is", today) // => Today is Monday fmt.Println("Your age is", age) // => Your age is 17 }
Question 5: What is the string data type in Golang, and how is it represented?
A string is a series of byte values. It’s a slice of bytes, and any byte slice can be encoded in a string value. So we can encode anything in a string, even beyond just Unicode text, like images or binary applications.
Golang doesn’t have a char data type. It uses bytes and runes to represent character values.
Question 6: Explain byte and rune types and how they are represented.
Golang has two integer types called byte and rune that are aliases for uint8 and int32 data types.
The byte data type represents ASCII characters, and the rune data type represents Unicode characters that are encoded in the UTF-8 format by default.
In Golang, we express characters or rune literals by enclosing them in single quotes such as ‘a,’ ‘b,’ ‘m,’ ‘x,’ or ‘\n.’ A code point is a numeric value that represents a rune literal.
The Golang terminology for code points is runes (rune is a term introduced in Golang specification for code point). Most of the time, we say “rune” instead of “code point.” A rune represents a single Unicode character. For example, rune 0x61 in hexadecimal represents the rune literal ‘a.’
Question 7: Can you change a specific character in a string?
No. Strings are immutable (read-only) data types and you cannot change them. If we try to change a specific character in a string, we’ll get a runtime error.
Question 8: How can you concatenate string values? What happens when concatenating strings?
To concatenate strings, we can use the addition operator (+). Note that each time we concatenate to a string value, Go creates a new string. That’s because strings are immutable in Go, making this inefficient.
There is an efficient and recommended way to concatenate string values and that is to use the strings.Builder type, which was introduced in Go 1.10.
Question 9: Explain array and slice types and the differences between them.
Golang has two data structures to handle lists of records: arrays and slices.
An array is a composite, indexable type that stores a collection of elements.
An array has a fixed length. We specify how many items are in the array when we declare it. This is in contrast to a slice that has a dynamic length (it can shrink or grow at runtime).
The array length is part of its type.
Every element in an array or slice must be of the same type.
Slices are a key data type in Golang and are everywhere.
Question 10: Give an example of an array and slice declaration.
Here’s an example of declaring and initializing an array of type [4] string using the short declaration syntax.
friends := [4]string{“Dan”, “Diana”, “Paul”, “John”}
Here’s an example of declaring and initializing a slice of type [] int using the short declaration syntax.
numbers := []int{2, 3, 4, 5}
Question 11: Explain the backing array of a slice value.
When we create a slice, Go creates a hidden array behind the scenes, called backing or underlying array, and the new slice type variable refers to it. The backing array stores the elements, not the slice.
Go implements a slice as a data structure called slice header, which is the runtime representation of the slice.
It contains three fields:
- The address of the backing array (a pointer to the first element of the backing array).
- The length of the slice. The built-in function len() returns it.
- The capacity of the slice which is the size of the backing array after the first element of the slice. It’s returned by the cap() built-in function.
Note that a nil slice doesn’t have a backing array, so all the fields in the slice header are equal to zero.
Question 12: What will the following Go program print out?
package main import "fmt" func main() { n1 := []int{10, 20, 30, 40} n1 = append(n1, 100) fmt.Println(len(n1), cap(n1)) }
The program will print out 5 8
The append() function creates a new backing array with a larger capacity. This avoids creating a new backing array when the next append() is called.
Question 13: Explain the Golang map type and its advantages.
A map is a collection type like an array or a slice and stores key:value pairs. We can think of a map being like a dict in Python or an Object in JS.
All the keys and values in a map are statically typed and must have the same type. Keys and values don’t have to be of the exact type, but all keys must be of the same type, and all values in the map must be of the same type. For example, all keys are of type string and all values are of type int.
We can use any comparable type as a map key. A comparable type is that type that supports the comparison operator. This is the double equals sign (==).
The main advantage of maps is that add, get, and delete operations take constant expected time no matter how many entries are in the map. They offer very fast lookups because maps are backed by HashTables.
Maps are unordered data structures in Golang.
Question 14: What is the recommended Golang package for basic operations on files? What other Golang packages are used to work with files?
The os standard library package provides a platform-independent interface. We use it for system functionality when working with files.
The os interface is intended to be uniform across all operating systems. So the programs we create work the same on Windows, Linux, or Mac.
There are other Go standard library packages, such as io, ioutil, and bufio. They work with files and provide more functionality.
However, for basic operations on files, they are not necessary. os package is all we need.
Question 15: Explain the Object-Oriented Architecture of Golang.
Unlike traditional Object-Oriented Programming, Golang does not have a class-object architecture. Rather structs and methods hold complex data structures and behavior.
A struct is nothing more than a schema containing a blueprint of data that a structure will hold. Structs are useful to represent concepts from the real world like cars, people, or books.
Question 16: What is a struct type? Can you change the struct definition at runtime?
A struct is a sequence of named elements called fields. Each field has a name and a type. We can also think of a struct as a collection of properties that are related together. They are useful for grouping data together to form records.
This blueprint is fixed at compile time. It’s not allowed to change the name or the type of the fields at runtime. We can’t add or remove fields from a struct at runtime.
Question 17: What are anonymous structs and anonymous struct fields? Give an example of such a struct declaration.
An anonymous struct is a struct with no explicitly defined struct type alias.
Example of an anonymous struct:
diana := struct { firstName, lastName string age int }{ firstName: "Diana", lastName: "Zimmermann", age: 30, }
We can define a struct type without any field names. We call them anonymous fields. All we have to do is mention the field types and Go will use type as a field name.
Example of a struct with anonymous fields:
type Book struct { string float64 bool } bestBook := Book{"1984 by George Orwell", 10.2, false}
Question 18: Explain the defer statement in Golang. Give an example of a deferred function’s call.
A defer statement defers or postpones the execution of a function. It postpones the execution until the surrounding function returns, either normally or through a panic call.
We use defer to ensure that a function call is performed later in the program’s execution, usually for cleaning resources.
For example, let’s say that we want to create a file, write to it, and then close when we’re done with it.
Immediately after creating the file variable, we defer the closing of that file. The function that closes the file will be executed at the end of the enclosing function (main) after the operation of writing to the file has finished.
file, err := os.Open("main.go") if err != nil { log.Fatal(err) } defer file.Close()
Question 19: Explain the pointer type.
A variable is a convenient, alphanumeric nickname or label for a memory location. A pointer is a variable type that stores the memory address of another variable.
A pointer value is the address of a variable, or nil if it hasn’t been initialized yet.
The pointer points to the memory address of a variable, just as a variable represents the memory address of a value.
For example, if variable bb has value 156 and is stored at memory address 0x1040a124 then the variable aa holds the address of bb (0x1040a124). Now aa is set to point to bb or aa is a pointer to bb.
Question 20: Write a Golang program that declares a string variable, prints the address of the variable, declares another int variable, and a pointer to it.
package main
import “fmt”
func main() { //Go provides the & (ampersand) operator also known as the address of operator. lang := "Golang" fmt.Println(&lang) // -> 0xc00010a040 var x int = 2 // -> int value ptr := &x // -> pointer to int fmt.Printf("ptr is of type %T with value %v and address %p\n", ptr, ptr, &ptr) }
Question 21: What are the advantages of passing pointers to functions?
Golang is a pass by value language.
If we pass a non-pointer variable type to a function, the function will create a copy of the variable. Any change to the variable, so to the function’s argument, will not be seen to the outside world.
Pointers have the power to mutate or change the data they are pointing to. So if we pass a pointer to a function, and inside the function we change the value the pointer is pointing to, then the change will be seen outside the function.
In a nutshell, we pass pointers to functions when we want to change the values of the variables inside the function’s body.
Question 22: What are Golang methods?
Golang doesn’t have classes, but we can define methods on defined types. A type may have a method set associated with it which enhances the type with extra behavior.
This way a named type has both data and behavior, and represents better a real-world concept.
Methods are also known as receiver functions.
Question 23: Create a Go program that defines a named type and a method (receiver function) for that type.
package main
import ( "fmt" ) // declaring a new type type names []string // declaring a method (function receiver) func (n names) print() { // n is called method's receiver // n is the actual copy of the names we're working with and is available in the function. // n is like this or self from OOP. // any variable of type names can call this function on itself like variable_name.print() // iterating and printing all names for i, name := range n { fmt.Println(i, name) } } func main() { // declaring a value of type names friends := names{"Dan", "Marry"} // calling the print() method on friends variable friends.print() // another way to call a method on a named type names.print(friends) }
Question 24: What is a goroutine? Go deeper into it.
A goroutine is a function that is capable of running concurrently with other functions. It’s a lightweight thread of execution.
When a Go program is running, the main goroutine is created and launched. Other goroutines are created using the go keyword. So any function that is called using the go keyword before its name becomes a goroutine.
The difference between OS threads and goroutines is that OS threads are scheduled by the OS kernel. And this is a slow operation due to the amount of memory access required.
The Go runtime contains its scheduler to schedule goroutines.
A goroutine is very cheap. It’s practical to have thousands, even hundreds of thousands, of goroutines.
Question 25: Explain why concurrency is not parallelism?
Concurrency means loading more goroutines at a time. These goroutines are multiple threads of execution. If one goroutine blocks, another one is picked up and started. On a single-core CPU, we can run only concurrent applications, but they are not run in parallel. They run sequentially.
On the other hand, parallelism means multiple goroutines are executed at the same time. It requires multiple CPUs.
Concurrency and parallelism are related but distinct concepts. Concurrency means independently executing processes or dealing with multiple things at once, while parallelism is the simultaneous execution of processes and requires multiple core CPUs.
Question 26: What is a data race?
Executing many goroutines at the same time without special handling can introduce an error called “Race Condition” or “Data Race.”
A Data Race occurs when two goroutines are accessing memory at the same time, one of which is writing. Race conditions occur because of unsynchronized access to shared memory. They are among the most common and hardest to debug types of bugs in concurrent systems.
Question 27: How could you detect a data race in Go code?
Starting with Go 1.1, a new tool called race detector for finding race conditions in Go code was made available.
Using the race detector is simple. We just add a -race flag to our normal Go command-line tool.
When the -race command-line flag is set, the compiler inspects all memory accesses with code that records when and how the memory was accessed. In the meantime, the runtime library watches for unsynchronized access to shared variables.
Example of running a Go program with the race detector: go run -race main.go
Question 28: What is Go Channel? What operations are available on the channel type?
A channel in Go provides a connection between two goroutines, allowing them to communicate.
The data we are sending through or receiving from a channel must always be of the same type. This is the type specified when we’ve created the channel.
Question 29: What operations are available on the channel type?
A channel is a 2-way messaging object that has two principal operations: send and receive.
A send statement transmits a value from one goroutine to another goroutine. It executes a corresponding receive expression. The transmission goes through the channel. Both operations are written using the channel operator(<-).
Channels are used to communicate in between running goroutines.
Question 30: Write a simple Golang program that uses a goroutine and a channel.
package main
import “fmt”
func func1(n int, ch chan int) { //sending into the channel ch <- n } func main() { // declaring a bidirectional channel that transports data of type int c := make(chan int) fmt.Printf("%T\n", c) // starting the goroutine go func1(10, c) //receiving data from the channel n := <-c fmt.Println("Value received:", n) fmt.Println("Exiting main ...") }
Final Thoughts
I hope you’ll find these interview questions useful. The answers to them and many other questions can be found in my course Master Go (Golang) Programming: The Complete Go Bootcamp. The course covers the Go programming language in depth.
Keep in mind that the only way to learn how to code is to write code so exercise as much as possible until you feel confident in your abilities as a Golang programmer.
Recommended Articles
9 Awesome Python Project Ideas That You Can Make at Home
Top courses in Go (programming language)
More Go (programming language) Courses
Go (programming language) students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.
Courses by Andrei Dumitrescu
Courses by Andrei Dumitrescu
|
https://blog.udemy.com/golang-interview-questions/
|
CC-MAIN-2022-33
|
refinedweb
| 3,268
| 65.93
|
Interactively analyse 100GB of JSON data with Spark
Do you know what is the heaviest book ever printed? Let’s find out by exploring the Open Library data set using Spark in Python.
The purpose of this tutorial is educational, originally posted by Dr. Valentin Dalibard and Dr. Raoul-Gabriel Urma:
You will get a taster of some of the operations available in Spark and how you can use them to interactively explore a dataset that would be inconvenient (because of size and structure) to work with in simpler tools like Excel. You will also see how MapReduce operations can easily be expressed in Spark. Note that we use Spark to run an ad-hoc analysis in a convenient manner. There are alternatives to analyse this dataset such as using Impala.
In this tutorial you will learn:
- how to get started with Spark,
- how to use the
map,
flatMap,
filter, and
reducepatterns, and
- how to use the
groupByKeyand
reduceByKeyfunctions.
Data Set
The Open Library is an initiative intended to create “one web page for every book ever published.” You can download their dataset which is about 20GB of compressed data using the following command in your terminal. The
--continue flag lets you download the data in several go.
wget --continue
You can then extract the data — you need about 100GB of free space — using the following command:
gunzip -k ol_cdump_latest.txt.gz | cut -f 5 > ol_cdump.json
To use the dataset on EC2, upload it to Amazon S3. Use the following command, with your S3 bucket name, the upload the data to an S3. Like the three previous steps, this one takes time to complete.
aws s3 cp ol_cdump.json s3://my_bucket
Alternatively, if you want to work with a smaller data set to save time, you can download a sample of the data from The techniques below will work, but the results will differ.
If you want to analyse the data locally you can install PySpark on your own machine, ignore the Amazon setup and jump straight to the data analysis.
Starting Amazon EMR
If you would like to get started with Spark on a cluster, a simple option is Amazon Elastic MapReduce (EMR). It gives you a cluster of several machines with Spark pre-configured. This is particularly useful if you quickly need to process a large file which is stored over S3.
Here is a youtube video to show you how you can get started:
Starting a Zeppelin notebook
Amazon EMR Spark instances come with Zeppelin notebooks: an alternative to jupyter notebooks which run directly on top of Spark. Open a Zeppelin notebook by clicking on the Zeppelin link on Amazon EMR.
Zeppelin allows for multiple languages to be used within the same notebook. Use
%pyspark at the top of a cell to run Python commands.
%pyspark
print("Hello")
Alternatively, you can execute shell instructions:
%sh
echo "World !"
Importing the dataset
The first step is to load the dataset in a Spark RDD: a data structure that abstracts how the data is processed — in distributed mode the data is split among machines — and lets you apply different data processing patterns such as filter, map and reduce. To learn more about RDDs as well as the rest of the topics of this tutorial, check out our big data bootcamp.
You can read the file and turn each line into an element of the RDD using the operation
textFile.
path = "s3://my_bucket/ol_cdump.json"
raw_data = sc.textFile(path)
Note that if you are working with a local copy of the file, you can just pass a standard file path (e.g.,
ol_cdump.json) to the function.
Each element in the RDD is a single string representing a json value. Thus, the second step turns each of these elements in a Python dictionary so they can be analysed more easily. The
json.loadsfunction parses a JSON value into a Python dictionary. And the method
.map(f) returns a new RDD where
f has been applied to each element in the original RDD. Combine the two to parse all the lines of the RDD.
import json
dataset = raw_data.map(json.loads)
dataset.persist()
Note that the code also calls the method
.persist() to cache the RDD in memory so it can be reused directly later.
Each element in the RDD dataset is now a dictionary mapping keys to values.
Exploratory Data Analysis
You can start by finding out the number of entries:
dataset.count()
This returns 126,107,177. Not bad, quite a lot of books!
You can take a sneak peak at the data using the
first operation to return the very first element. Alternatively,
take(k) returns a list of the first
k elements
dataset.take(10)
The output is quite long. But you will see that the entries returned contain book attributes such as
number_of_pages,
title,
weight,
isbn_10, etc.
In order to understand the shape of the data you have, you can extract all the distinct keys available in the dictionaries. You may be tempted to use the
map operation again, but you have to use
flatMapinstead. Indeed, for each dictionary, you extract a list of keys, so
map would produce an RDD of lists of keys. Using
flatMap, all the keys are collapsed into a single, flat RDD. One way to think about
flatMapis that it lets you apply a one-to-many transformation for each element instead of one-to-one like
mapdoes.
On this RDD of keys, you can use
distinct to remove duplicate keys. Finally, use the
collectoperation to extract this RDD of unique keys into a Python list.
keys = dataset.flatMap(lambda d: d.keys()).distinct().collect()
len(keys)
There are 504 unique keys! That is quite a lot of different attributes for a book.
In practice not all JSON objects have the same attributes: there are often missing attributes. E.g., the database may mention the number of pages in a book but not necessarily its printed dimensions. That is what you get with real-world data. In the Open Library dataset you find a lot of diversity! To explore that diversity, you could group the number of attributes for each element using
groupByKey:
groups = dataset.map(lambda e: (len(e.keys()), e)).groupByKey()
But hold on! This actually not good practice at all! You could have a most common number of keys with a lot of data associated with that key, say 20GB. In that case, you would create a 20GB Python list which would crash your machine or cause swapping.
A better way of computing the same result is by using
reduceByKey:
count_per_key = (
dataset
.map(lambda e: (len(e.keys()), 1))
.reduceByKey(lambda x, y: x + y)
.collect()
)
The
reduceByKey operation adds up the
1s generated for each key, which ends up returning the count per number of attributes. Zeppelin is quite useful here as it lets you visualise the result directly through its interface:
print("%table")
for e in count_per_key:
print("%d\t%d" % (e[0], e[1]))
Tell me about the weight
You managed to get some insights about the data. How about something more fun which you can bring up during fancy dinner parties? You are in luck. One of the JSON attribute is the weight of each book. Are you curious to find out what is the heaviest book? Let’s hope it is an interesting book at least. When you explored the dataset you will have noticed that there are different units for the
weightattribute: kg, g, ounces, pounds, etc. It is all very messy! You will need a function that can normalise the weights so you can compare each book:
def sanitizedWeight(weight_str):
w = convertToKilograms(weight_str)
if w > 1e6: #books above 1e6 kg are errors
return 0.0
else:
return w
def convertToKilograms(weight_str):
result = weight_str.split()
if(len(result)) != 2:
return 0
try:
number = float(result[0])
except ValueError:
return 0
if(result[1] == 'pounds' or result[1] == 'lb' or result[1] == 'lbs'):
return number * 453.592 * 1e-3
elif(result[1] == 'ounces' or result[1] == 'oz' or result[1] == 'oz.'):
return number * 28.35 * 1e-3
elif(result[1] == 'grams' or result[1] == 'gms' or result[1] == 'g'):
return number * 1e-3
elif(result[1] == 'kilograms' or result[1] == 'kilo' or result[1] == 'kg'):
return number
else:
return 0
Note that there are still a few books with weight attributes that are ignored by this function. Some weights appear with no space between the number and the unit, some with unusual capitalisation (GM, KGms), some with typos (“ounds”), some with other oddities. Let’s keep a focus on analysing the dataset — but feel free to improve this parser if you want.
To find the heaviest book, you simply need to iterate through the data and reduce it, selecting the heaviest book each time.
heaviest_book = (
dataset
.filter(lambda e: "weight" in e and "title" in e)
.map(lambda e: (e, sanitizedWeight(e["weight"])))
.reduce(lambda x, y: x if x[1]>y[1] else y)
)
So what is the answer? Unfortunately it is a bit of a let down, the output is a book of 200,000 pounds(just over 90 metric tons) with a strangle title!
({… u'weight': u'200000 pounds', …, u'title': u'u fool,stupid', …}, 90718.40000000001)
Clearly someone inserted a dummy entry in the database! This is a bit of let down.
How about getting a visualisation of when books were published? You can use the operations you’ve learnt to produce the following query:
booksWithDate = (
dataset
.filter(lambda e: "publish_date" in e)
.map(lambda e: (e["publish_date"], 1))
.reduceByKey(lambda x, y: x + y)
.collect()
)
def is_int(s):
try:
t = int(s)
return True
except ValueError:
return False
booksWithDate = (
dataset
.filter(lambda e: "publish_date" in e)
.filter(lambda e: len(e["publish_date"]) >=4)
.filter(lambda e: is_int(e["publish_date"][-4:]))
.map(lambda e: (int(e["publish_date"][-4:]), 1))
.reduceByKey(lambda x, y: x+y)
.collect()
)
Again, you need to process and clean the data before you can work with real years. You can now use the visualisation feature in Zeppelin to get a nice distribution:
print("%table")
for r in d:
print("%d\t%d" % (r[0], r[1]))
If you are interested more about Spark and big data systems, check out our upcoming webinar series:
And in the meantime you can test your Spark skills trying to find answers to these questions:
- Which author has written or co-written the most books in the dataset?
- Which category of books is the most popular in the dataset?
|
https://medium.com/towards-data-science/interactively-analyse-100gb-of-json-data-with-spark-e018f9436e76
|
CC-MAIN-2017-43
|
refinedweb
| 1,759
| 65.32
|
FAQs
Search
Recent Topics
Flagged Topics
Hot Topics
Best Topics
Register / Login
Dave Landers
Ranch Hand
401
1
Threads
0
Cows
since Jul 24, 2002
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
Ranch Hand Scavenger Hunt
Number Posts (401 (401/10)
Number Threads Started (1/10)
Number Likes Received (0/3)
Number Likes Granted (0/3)
Set bumper stickers in profile
Set signature in profile
Set a watch on a thread
Save thread as a bookmark
Create a post with an image (0/1)
Recent posts by Dave Landers
With global variables, threads, and a really sore head! :)
Each request is processed by a thread. This just means that many requests can be processed at the same time.
Also, the servlet spec says that the servlet container can use any instance of the servlet object for these multiple threads. That lets the servlet engine be more efficient (fast).
The result for servlet developers is that we can not put read/write shared data in fields of the servlet object. The object can be reused by multiple threads at the same time, so this data will be "stomped on" by other threads. All data must be maintained as method-local variables.
So when you are writing your servlet, it all starts with the service method (or doGet or doPost or whatever). If you call other methods from there, you need to pass all the data around as method arguments and do not save it in the servlet object.
In this regard, the request and response objects are no different than any other value - don't save them as fields of the servlet object.
There are several ways in which you can save data for a single user or request - you can use the HttpSession to save user data between requests or you can use the Attributes on the request to save data for the duration of a single request.
The servlet API does have a SingleThreadedModel interface. If your servlet implements this interface, it instructs the servlet container not to share instances between threads. You can use this if you absolutely must put fields on your servlet object. But it is better not to do that as this really limits the performance of your server.
show more
15 years ago
Servlets
Question regaring Singleton.
You did not create two instances, only one.
You have two variables which reference the same singleton instance.
You can test that by checking that instance==instance1.
The reason they both have the same contents is because they are the same object.
show more
15 years ago
Java in General
ClassCastException Help!!!!!!
I think what may be happening is that WebLogic is not Serializing the collection. WLS will serialize things if it can't see the same class from both ClassLoaders.
Maybe because the Collection is in java.util it is not actually serializing that object, so its contents (your Value objects) are not being serialized and thus you get the ClassCastException.
I can think of three ideas. You can force the serialization with a switch in the weblogic-ejb-jar.xml (I forget exactly, but check e-docs.bea.com).
Or you could put your value class in system classpath.
Or you could create a subclass of the Collection that you put in your ejb jar and client jar in the webapp. Pass the "MyCollection" rather than the java.util.Collection and maybe WLS will be "tricked" into serializing the thing. It could be as simple as
public class MyHashSet extends HashSet {}
I think the force serialization switch is probably the best bet.
[ November 22, 2002: Message edited by: Dave Landers ]
show more
15 years ago
EJB and other Java EE Technologies
state in stateful session bean
Right.
show more
15 years ago
EJB and other Java EE Technologies
Is thread-safety a concern for constructors?
OK, to clarify what I meant.
In order for an object to be constructed (and thus have some combination of constructors invoked) somebody has to make a call to new.
While that is going on, other threads can not get a reference to that object until it is constructed (exception -see below). And in any case when another gets the instance, it can not invoke the constructor. A second threads can not invoke any constructor on the same object instance.
Therefore the constructors themselves are "thread-safe", and the only concern is the thread safety of objects that are used by those constructors.
Exception: What I said above about "other threads can not get a reference till it is constructed" is not strictly true. It is true enough for the explaination above, but it still has a hole. The reason is all wrapped up in the Java Memory Model. Its the same reason that Double Checked Locking doesn't work in Java. Don't need to go into that into too much detail here.
show more
15 years ago
Threads and Synchronization
Class-Path reference is not working on EAR file.
The manifest format is very picky. Use
Class-Path: depend.jar
That's a colon (
not an equals (=).
Also, I think the space after the colon is important.
Make sure, if this is the only thing in your MANIFEST.MF, that it also ends in a newline.
And this goes in the manifest of the EJB jar, not anywhere else.
[ November 22, 2002: Message edited by: Dave Landers ]
show more
15 years ago
BEA/Weblogic
Is thread-safety a concern for constructors?
Note that some code somewhere has to call something like:
new TheObject()
for the constructor to be run.
Since a constructor is only run while the object is being created, thread safety of the constructor itself is not an issue. This is because two threads can't create the same object. If they are creating objects, they will create different ones.
Thus it does not make sense to have a synchronized keyword for a constructor.
Now what the constructor is doing is another matter. If it is accessing some common resource (another object or static methods/fields) then there could be a problem. But this is no different than any method's access of those resources. Those resources should be protected in either case.
show more
15 years ago
Threads and Synchronization
JSP Problem
You probably need tools.jar in your classpath. You should find it in your JDK's lib directory.
show more
15 years ago
EJB and other Java EE Technologies
state in stateful session bean
The state for a stateful session bean is maintained as fields in the object.
public class MySSB implements SessionBean { // the state private String foo; private int bar; // etc... }
If the container has to passivate the bean (maybe it has to make "room" for other more active beans), it might serialize the thing to a file on disk. Before the client uses it again, it will be deserialized and the bean activated. But all you care (as the developer) is that you wrote an object and the data is referenced by fields.
But think about why you are using stateful session beans. They can be misused and put a burden on the server.
Just because it has "session" in its name does not mean it is anything at all like the http session object. It is not a replacement.
I usually prefer to keep the ejb's api stateless, and let the client keep the state. If the client is a webapp, this means the client's state is in http session. If the client is a java program, it means keeping the state in that program's memory.
show more
15 years ago
EJB and other Java EE Technologies
weblogic server certification has a new approach
Chris,
I understand what you're saying.
First, I must say that anyone who can sleep thru 11 days of training deserves
some
kind of award (or the instructor does).
Although I have sat thru portions of some older versions (3.x, 4.5.1) of these courses and they weren't very exciting - but I had practical experience at the time and so the material was nothing new. I also beta-tested the first (4.5.1) cert test. Got a polyester shirt -
woohoo.
Seems to me the training option is not a bad one, especially for folks that can swing it. But maybe it would make sense to require a passing grade on a quiz to get the cert. They still have the same cert exams, and some kind of test-out of the course work, I think. So just more options.
Maybe it does change the value of the cert, but I'm not convinced.
Anyway, it doesn't really matter to me. I am not big on certs. I know lots of folks on JavaRanch are. Maybe I just thought I'd push a couple of JavaRanch Pro-Certification buttons
To me, the important thing is what you know and what you can do, not what papers you have pinned to your cubical wall.
If you have the opportunity to gain knowledge thru training (or thru any opportunity), then grab it. If you can get a piece of paper and a shirt outta the deal then great.
But know that neither the course work nor the test will really tell anyone if you can
apply
the knowledge that the paper claims you "learned".
show more
15 years ago
BEA/Weblogic
Simple questions on arrays
an array is an Object.
Prove it to yourself:
int[] array = new int[100]; Object o = (Object) array;
show more
15 years ago
Beginning Java
Timeouts in ejb
In weblogic-ejb-jar.xml in the weblogic-enterprise-bean section, set:
<transaction-descriptor> <trans-timeout-seconds>60</trans-timeout-seconds> <transaction-descriptor>
Default is 30 seconds.
show more
15 years ago
BEA/Weblogic
weblogic server certification has a new approach
So a minimum of 11 days of training at a cost of over $6000 is "watered down" when compared to a 2 hour multiple choice test?
show more
15 years ago
BEA/Weblogic
Converting an String to bytes
Did you try JDK 1.4? The character encoding stuff is much improved in 1.4.
show more
15 years ago
Java in General
Cannot load driver class: com pointbase jdbc.jdbcUniversalDriver
pointbase driver should be in the pointbase eval directory. I forget exactly where it was in 6.1, but something like weblogic/samples/eval/pointbase/lib/pbserverXX.jar
show more
15 years ago
BEA/Weblogic
|
https://coderanch.com/u/33823/Dave-Landers
|
CC-MAIN-2018-22
|
refinedweb
| 1,781
| 72.66
|
Creating shared libarary
How to create dll file which includes qml files and how to use the same in another qml file.
@jayshetti
Here you go
@raven-worx i have seen this example i'm able to create dll file but unable to use it in other project,
need some step by step guidelines.
@jayshetti
what is the error, what isn't working exactly?
Note that you can only load dbeug libraries in debug builds and the same respectivly for release.
Also when place the DLL and the qmldir file in the Qt dir (e.g.
C:\Qt\Qt5.7.0-msvc2015\5.7\msvc2015\qml\MyModule) it will be loaded by Qt automatically.
@raven-worx i'll tell you what i exactly want to do
i have created QT quick2 extension plugin library project in this project i have to have one qml file that draws one simple circle
i have to use the plugin i.e generated by extension plugin into other qt quick application to draw the circle
How to achieve this task if you give me step by step guidelines it would be helpful.
@jayshetti
did you read the link i've already posted? This actually contains everything to know.
As i already said, once the plugin is built copy it to your Qt's qml directory and it can be loaded by other applications.
I wont post a step-by-step guide, when there is everything already in the docs. If you have a specific question ask it.
@raven-worx i'm able to load the plugin successfully but i'm facing problem in loading qml component in this link they have used Clock.qml and plugins.qml how should i access that Clock.qml file in my application through plugin if i simply used Clock as component it showing me an erorr.
@jayshetti
in this example the Clock.qml is located in the file system.
Place your QML files in a qrc file and compile it into the plugin.
Then in your qmldir file you can also specify a qrc:// url, to make it look like this:
module MyModule plugin mymodule MyType 1.0 qrc:///path/to/MyType.qml
or leave out the list of QML files in the qmldir file and register the types in the plugins
registerTypes()method:
void registerTypes(const char *uri) { Q_ASSERT(uri == QLatin1String("MyModule")); qmlRegisterType( QUrl::fromUserIntput("qrc:///path/to/MyType.qml"), uri, 1, 0, "MyType"); }
Then use
import MyModule 1.0to load your plugin.
@raven-worx Thank you it worked nw
|
https://forum.qt.io/topic/74075/creating-shared-libarary
|
CC-MAIN-2017-43
|
refinedweb
| 423
| 64.61
|
Stan Algorithms: Where to Start?
We’re starting the work that’s involved with Reimplementing the Inference Algorithms in Stan. Before we can get to any reimplementation, we need to understand what’s going on. The first steps are to identify the entry point into the code, instantiate the existing tests, and take inventory of what’s there.
I have Michael Feathers’ book “Working Effectively with Legacy Code” open while I’m working on this. I feel like we’re at “Chapter 16. I Don’t Understand the Code Well Enough to Change It.” The goal of this post is to get us collectively past that point.
For some additional background, please see a series of posts written by Juho Timonen about Understanding the Stan Codebase: Part 1: Finding an entry point and Part 2: Samplers. The technical focus of this post is somewhere between the two.
If you’d like to run code rather than only inspect the code, jump down to the section called “Running the Tests” to get set up.
Note: the link to Michael Feathers’ “Working Effectively with Legacy Code” is an Amazon Affiliate link. I might make a few dollars off it if enough people click through. I’ve personally bought and handed out multiple copies of the book over the years.
The Starting Point: A Unit Test
We’ll start with the unit test for the default MCMC algorithm used in Stan. The default MCMC algorithm in Stan is:
template <typename Model> int hmc_nuts_diag_e_adapt(...)
located at
src/stan/services/sample/hmc_nuts_diag_e_adapt.hpp. This function is responsible for running MCMC for a model that’s provided, with the arguments that control the MCMC algorithm including number of iterations, and output the iterations. The output of the function is handled through callbacks, so it’s all through side-effects. The configuration of “which model?” is not part of the responsibility of this function; this function is handed a valid model.
The unit test is located at
src/test/unit/services/sample/hmc_nuts_diag_e_adapt_test.cpp and this can be run from a terminal from the Stan working directory:
> ./runTests.py src/test/unit/services/sample/hmc_nuts_unit_e_adapt_test.cpp
Breaking Down the Unit Test
Even with a familiarity with C++, if you’re not familiar with Google Test, the unit test code may look pretty foreign. I’ll try my best to demystify how everything connects within the test listed above.
Note: there is no
int main() function in this test file. There is a separate C++ header file that is provided by Google Test that contains the
int main() function that is linked in when compiling this test file. The Stan make process handles the compiling and linking and generates the executable
test/unit/services/sample/hmc_nuts_unit_e_test.
1. Include Statements
The include statements are L1–6 in the test file. Line 4 includes the header file generated by the Stan compiler:
#include <test/test-models/good/optimization/rosenbrock.hpp>.
Stan’s build process (using make) generates the C++ header file from the Stan program,
rosenbrock.stan, automatically. For understanding this test, the model choice is not important. We just need to know that this header file is where the model is declared and defined. (What exactly is generated will be covered in future posts.)
2. Google Test: Test Fixture
Lines 8–17 define a test fixture. This provides variables and an initial state prior to each of the 4 tests.
class ServicesSampleHmcNutsDiagEAdapt : public testing::Test {
public:
ServicesSampleHmcNutsDiagEAdapt() : model(context, 0, &model_log) {}
std::stringstream model_log;
stan::test::unit::instrumented_logger logger;
stan::test::unit::instrumented_writer init, parameter, diagnostic;
stan::io::empty_var_context context;
stan_model model;
};
Most of it is straightforward and uses default constructors to create objects.
stan::test::unit::instrumented_logger and
instrumented_writer can be found in
src/test/unit/services/instrumented_callbacks.hpp and provide a way to inspect the outputs programatically.
The variable
stan_model model is the fully instantiated Stan program and its construction happens with the construction of the test fixture itself:
model(context, 0, &model_log). The constructor is defined in the generated C++ and the arguments are 1) container for data, 2) random seed, 3) output messages from initialization. The Stan program defined in
rosenbrock.stan contains no data; the
empty_var_context is an object that derives from the right class and contains no data.
We can dig into the C++ interfaces more, but with the current information, we can get into the test itself. We just have to know that the
model variable has the instantiated Stan program that we want to run MCMC on.
3. The First Test: check that it instantiates properly
Lines 19–55 contain the first test called
call_count. In Google Test, we write assertions to verify behaviors. This test checks that output callbacks are called and the correct number of times.
Algorithm Parameters
Lines 20–37 define parameters that need to be passed to the function to control the MCMC algorithm:
unsigned int random_seed = 0;
unsigned int chain = 1;
double init_radius = 0;
int num_warmup = 200;
int num_samples = 400;
int num_thin = 5;
bool save_warmup = true;
int refresh = 0;
double stepsize = 0.1;
double stepsize_jitter = 0;
int max_depth = 8;
double delta = .1;
double gamma = .1;
double kappa = .1;
double t0 = .1;
unsigned int init_buffer = 50;
unsigned int term_buffer = 50;
unsigned int window = 100;
First Assertion
Lines 38–39 is our first assertion.
stan::test::unit::instrumented_interrupt interrupt;
EXPECT_EQ(interrupt.call_count(), 0);
Technically, we don’t need to include this test, but we include it just to make sure we start at 0. Every time the functor
interrupt() is called, there is an internal counter that increments. The state can be retrieved using the
call_count() function.
Call the Algorithm!!!
Line 41 calls the MCMC function,
hmc_nuts_diag_e_adapt(...)!
int return_code = stan::services::sample::hmc_nuts_diag_e_adapt(model, context, random_seed, chain, init_radius, num_warmup, num_samples, num_thin, save_warmup, refresh, stepsize, stepsize_jitter, max_depth, delta, gamma, kappa, t0, init_buffer, term_buffer, window, interrupt, logger, init, parameter, diagnostic);
This line is where all the algorithmic work happens. We have provided the function with a
model, arguments to control the algorithm, and a handful of callback objects to get the output back. This is the entry point!
Check Results
The rest of the test, lines 47–54, check the results of running the function.
EXPECT_EQ(0, return_code);
int num_output_lines = (num_warmup + num_samples) / num_thin;
EXPECT_EQ(num_warmup + num_samples, interrupt.call_count());
EXPECT_EQ(1, parameter.call_count("vector_string"));
EXPECT_EQ(num_output_lines, parameter.call_count("vector_double"));
EXPECT_EQ(1, diagnostic.call_count("vector_string"));
EXPECT_EQ(num_output_lines, diagnostic.call_count("vector_double"));
I won’t get into the details of these assertions right now; we can dig into them later. For right now, it’s important that we’ve gotten far enough to:
- set up the model
- run the algorithm code
- check the output
That’s plenty for now.
4. Tests 2–4
Tests 2 (
parameter_checks), 3 (
output_sizes) and 4 (
output_regression) are structured identically to the first test!
We Found the Entry Point!
If you got this far, we found out how to instantiate the algorithm code. There’s a lot more we need to dig into going forward, but this is gets us to the starting point.
Running the Tests
Before getting into the depths of C++ interfaces, let’s start with getting tests instantiated and running.
Clone the Repo
git clone
Change directories into the
stan-algorithrms folder.
Update Git Submodules and Download the Stan Compiler
Option 1: Use the script in the repo
Note: this only works for Linux and Mac. If you’re on Windows, follow Option 2 below. (If enough people reach out, I’ll update the script to be cross-platform.)
./setup.sh
This does two steps, described below. If you’ve run this, skip down to the “Run the Tests” subsection.
Option 2: Manually update git submodules and download the Stan compiler
Step 1: update git submodules.
git submodule update --init --recursive
Step 2: download the v2.18.1 version of the Stan compiler
On Mac:
mkdir -p stan/bin
curl -L "" -o stan/bin/stanc
On Linux:
mkdir -p stan/bin
curl -L "" -o stan/bin/stanc
On Windows:
Download and put in
stan/bin/
Run the Tests
./test.sh
This will compile and run all the relevant algorithm tests. In this post, we looked at one of the many tests that are run using this script.
|
https://bayesianops.medium.com/stan-algorithms-where-to-start-e6103c778d12
|
CC-MAIN-2022-33
|
refinedweb
| 1,371
| 56.86
|
Last week I was doing some Test Driven Development training and overheard someone mention another programming language that had a test runner that you could set up to watch your project directory and run your tests when the files changed. I thought that was a neat idea. I also thought I could easily write my own Python script to do the same thing. Here’s a pretty rough version:
import argparse import os import subprocess import time() def watcher(test_path, project_path=None): if not project_path: project_path = os.path.dirname(test_path) f_dict = {} while True: files = os.listdir(project_path) for f in files: full_path = os.path.join(project_path, f) mod_time = os.stat(full_path).st_mtime if full_path not in f_dict: f_dict[full_path] = mod_time elif mod_time != f_dict[full_path]: # Run the tests cmd = ['python', test_path] subprocess.call(cmd) print('-' * 70) f_dict[full_path] = mod_time time.sleep(1) def main(): args = get_args() w = watcher(args.tests, args.project) if __name__ == '__main__': main()
To run this script, you would need to do something like this:
python watcher.py --test ~/path/to/tests.py --project ~/project/path
Now let’s take a moment to talk about this script. The first function uses Python’s argparse module to make the program accept up to two command line arguments: –test and –project. The first is the path to the Python test script while the second is for the folder where the code that is to be tested resides. The next function, watcher, will loop forever and grab all the files out of the folder that was passed in or use the folder that the test file is in. It will grab each file’s modified time and save it to a dictionary. The key is set to the full path of the file and the value is the modification time. Next we check if the modification time has changed. If not, we sleep for a second and check again. If it has changed, then we run the tests.
At this point, you should be able to edit your code and tests in your favorite Python editor and watch your tests run in the terminal.
Using Watchdog
I looked around for other cross-platform methods of watching a directory and came across the watchdog project. It hasn’t been updated since 2015 (at the time of writing), but I tested it out and it seemed to work fine for me. You can install watchdog using pip:
pip install watchdog
Now that we have watchdog installed, let’s create some code that does something similar to the previous example:
import argparse import os import subprocess import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler() class FW(FileSystemEventHandler): def __init__(self, test_file_path): self.test_file_path = test_file_path def on_any_event(self, event): if os.path.exists(self.test_file_path): cmd = ['python', self.test_file_path] subprocess.call(cmd) print('-' * 70) if __name__ =='__main__': args = get_args() observer = Observer() path = args.tests watcher = FW(path) if not args.project: project_path = os.path.dirname(args.tests) else: project_path = args.project if os.path.exists(path) and os.path.isfile(path): observer.schedule(watcher, project_path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() else: print('There is something wrong with your test path')
In this code, we keep our get_args() function and add a class. The class subclass’s watchdog’s FileSystemEventHandler class. We end up passing in our test file path to the class and override the on_any_event() method. This method fires on any time of file system event. When that happens, we run our tests. The last bit is at the end of the code where we create an Observer() object and tell it to watch the specified project path and to call our event handler should anything happen to the files there.
Wrapping Up
At this point, you should be able to start trying out these ideas on your own code. There are also some platform specific methods to watch a folder as well (like PyWin32) but if you run on multiple operating systems like I do, then watchdog or rolling your own might be a better choice.
Related Readings
- StackOverflow: How do I watch a file for changes using Python?
- Watch a Directory for Changes
|
http://www.blog.pythonlibrary.org/2017/03/14/how-to-run-python-tests-continuously-while-coding/
|
CC-MAIN-2018-13
|
refinedweb
| 706
| 66.84
|
concept
A struct is a type of construction that consists of several members. The member can be a basic data type or another struct.
Declaration structure
struct 结构体名{ 成员列表};
The structure name represents the type name of the structure.
Declaring a structure means creating a new type name (custom data type) and then defining variables with the type name.
struct Product { char name[10]; char shape[10]; char color[10]; float price; }
There are three ways to define variables using structures
The first: declare the structure type, and then define variables
struct Product p1; struct Product p2;
p1 and p2 are structure variable names, these two variables have the same structure
analogy:
类型名变量名int a; | | struct Product p;
struct Product as a whole represents a data type
After the structure variables are defined, the system allocates memory units for them
The second type: when you declare the structure type, define variables at the same time (you can define multiple variables)
struct 结构体名{成员列表} 变量名列表;
example:
struct Product { char name[10]; char shape[10]; char color[10]; float price; } p1, p2;
The third type: directly define structure type variables (anonymous structure, no structure name)
struct {成员列表} 成员变量;
example:
struct { char name[10]; char shape[10]; char color[10]; float price; } p1, p2;
Types and variables are different:
- Can only be assigned to a variable, not a type
- Type does not allocate space, only allocates space for variables
Structure members can also be structure type variables:
struct date { int year; int month; int day; }; struct student { char name[20]; char gender; int age; // 结构体类型变量struct date birthday; };
Structure variable references
结构体变量名.成员名
example:
p1.name = "IceBox"; p2.price = 2000;
If the member itself is of another struct type, you need to use multiple member operators
struct student s; s.birthday.year = 1986; s.birthday.month = 11; s.birthday.day = 6;
You can reference not only the addresses of structure variable members, but also the addresses of structure variables
scanf("%d", &p1.price); printf("%O", &p1); // 输出p1的首地址
Structure type initialization
struct Student { char name[10]; char gender; int grade; } student = { "Felix", "m", 4 };
Note: Each data must be in the same order as the member list of the structure.
Defining a structure array
struct 结构体名{成员列表}数组名;
example:
struct Student { char name[20]; int code; char gender; int grade; } student[5];
This way is to define a structure array while declaring the structure type. You can also declare the structure type before defining variables
struct Student student[5];
Or directly define the structure array:
struct { char name[20]; int code; char gender; int grade; } student[5];
The above defines an array where the elements are data of type
struct Student , and each data has 4 member variables. Look at the picture:
Structure array initialization
struct 结构体名{成员列表} 数组名= {初始值列表};
example:
struct Student { char name[20]; int code; char gender; int grade; }} };
When initializing an array, the outermost curly braces list the elements of the array. Because each element is a structure type, each element also uses curly braces, which contain data for each structure member.
When defining a structure array, you can also declare the structure type before defining the structure array.
struct Student} };
Structure pointer
A pointer to a variable representing the starting address in the memory occupied by the variable. If a pointer points to a structure variable, the pointer points to the starting address of the structure variable.
Define the structure pointer:
结构体类型*指针名;
example:
// 指向struct Student结构类型的pStudent指针变量struct Student *pStudent;
There are two ways to access members using pointers to struct variables:
The first: use the dot operator to reference structure members
// 一定要使用括号,因为点运算符的优先级最高(*pStudent).成员名// example (*pStudent).code = 9837849;
The second type: use the pointing operator to refer to structure members
pStudent->成员名; // example pStudent->code = 393848;
If
student is a structure variable and
pStudent is a pointer to a structure variable, the following three effects are equivalent:
student.成员名; (*pStudent).成员名; pStudent->成员名;
Pointer to structure array
The structure pointer variable can not only point to a structure variable, but also to a structure array, and the value of the pointer variable is the first address of the structure array.
The structure pointer variable can directly point to the element in the structure array. In this case, the value of the pointer variable is the first address of the structure array element.
// 假设:struct Student student[5]; struct Student *pStudent; // 指向数组的首地址pStudent = student;
When an array does not use a subscript, it represents the address of the first element of the array, so the pointer points to the first address of the array. If you want to use the pointer to point to the third element, append the index after the array name, and then use the address symbol & before the array name
pStudent = &student[2];
Structure as function parameter
There are three forms of using structures as function parameters:
- Use struct variables as arguments to functions
- Use members of structure variables as function parameters
- Use a pointer to a structure variable as a function parameter
The first type: using a structure variable as a function parameter <br /> When using a structure variable as the function's actual parameter, "value passing" is adopted, and the content of the memory unit occupied by the structure variable is passed in all order The parameter must be a structure variable of the same type.
void display(struct Student stu);
Structure variables are used in the formal parameter position, but during the function call, the formal parameter also takes up a memory unit. This transfer method has a large space and time overhead.
According to the function parameter passing method, if the value of a member in a variable is modified inside the function, the changed value will not be returned to the calling function.
The second type: using a pointer to a structure variable as a parameter <br /> When using a structure variable as a parameter of a function, the space and time are expensive during the value passing process. You can use the pointer of the structure variable as a function parameter to pass .
When using a pointer to a structure variable, only the first address of the structure variable is passed, and no copy of the variable is passed.
void display(struct Student *stu);
Because the variable passed here is the address, if the data in the member is changed in the function, the variable will change when it returns to the calling function.
#include <stdio.h> struct Student { char name[20]; float score[30]; } student = { "刘备", 98.39f, 89.0, 93.5f }; void display(struct Student *s) { printf("-------------以下是学生信息-------------\n"); printf("姓名: %s\n", s->name); printf("数学成绩: %.2f\n", s->score[2]); // 修改了数组元素的值s->score[2] = 90.2f; } int main(int argc, char const *argv[]) { struct Student *pStudent; pStudent = &student; display(pStudent); // 也可以直接传递结构体变量的地址作为参数// display(&student); // 主调函数中,结构体成员的值发生了改变printf("修改后的数学成绩: %.2f\n", pStudent->score[2]); return 0; }
|
http://www.itworkman.com/75100.html
|
CC-MAIN-2020-45
|
refinedweb
| 1,143
| 52.12
|
At Liberty
by Jesse Liberty
This is the first of a series of monthly columns on Programming for the Microsoft* .NET* platform. For the first few months, I'll concentrate on Microsoft's new object oriented programming language: C#* (C-Sharp).
No column can substitute for a good primer on the language, but in this series I hope to focus in on some of the more interesting aspects and challenges facing the novice C# programmer. Along the way I will talk about object-oriented analysis and design, good programming practice, and the ins and outs of producing, debugging, and shipping high quality software.
Programmers will come to Microsoft* C# from various backgrounds. Some will come from C++* or Java*, confident in their understanding of object oriented programming and at home in the C-family syntax. For these programmers, the transition to the C# syntax will be very easy.
Many Visual Basic* 6 programmers are realizing that the move to Visual Basic .NET is a giant leap. (In fact, it is so great a transition that some VB6 programmers have started calling the new language VB.NOT!) Many of these programmers tell me that they are going to switch to C# because they are convinced that the transition from VB6 to C# will be no more difficult than the transition from VB6 to VB.NET, and they believe that C# programmers will earn more in the market. No one is certain if these earnings predictions are correct, but there is no mistaking the fact that many VB6 programmers are in fact learning C#.
Finally, some programmers will come to C# with little or no related experience, and they will have to learn all of it at once: C#, object oriented programming, Windows* and Web development, and the .NET platform itself.
Whatever your background, the common theme of all C# programming is this: the language exists to facilitate .NET development. Thus, any discussion of C# must always return to the issue of building .NET applications. This will be the focus of this and future columns.
Every ten years or so the world shifts under our feet, and we either adjust or we get left behind. In the 1980s I was programming in Unix using C. We were doing great things, building on-line services hosted on Intel® 286 processor computers. Unix* offered a multitasking environment not then available under DOS.
In the early 1990s I switched from C to C++ and from Unix to Windows. Suddenly I was writing event-driven programs for Graphical User Interfaces (GUIs), and C++ was a much better fit. In C++ you could create new user types to represent the various controls and widgets drawn on the console (such as buttons, list boxes, windows, and so forth).
I wrote a lot of books on C++ and I think it is a great language, but I can read the handwriting on the wall. The next platform is .NET and the language of choice for .NET development is C#.
The .NET platform is virtually a new operating system. Rather than creating an object oriented operating system and all the tools for it, all at once, Microsoft has released the .NET platform to sit on top of its existing Windows operating systems. I would not be at all surprised to see the .NET platform merged into the next release of Windows; in fact, I'd be surprised if that didn't happen. The advantages of .NET development are so clear and convincing that it is not surprising that Microsoft has put all its chips on .NET.
.NET is built on a Common Language Runtime that acts as the interface between your programs and the underlying operating system. The CLR provides just-in-time compiling of your C# programs (explained later in this article), as well as the bedrock support for exception handling, type checking, and so forth.
The .NET Framework Base Class Library (BCL) is built on top of the CLR and offers a rich set of classes to provide the plumbing for Windows and Web development. The BCL includes classes for I/O, security, threading, collections, and so forth.
On top of the BCL, .NET offers ADO.NET*-an object oriented model for database development. I'll devote a future column to ADO.NET; this is the next generation model for interacting with databases.
You build your applications atop this infrastructure. Typically, you'll create one of three types of programs: a Web application, a Web Service, or a Windows desktop application.
In the 1990s, Microsoft offered what has become one of the most popular platforms for Web development: Active Server Pages (ASP). The successor to ASP is ASP.NET. I'll explore ASP.NET in detail in a future column, but the short story is this: ASP.NET improves on ASP in every way; separating HTML from the compiled code that supports it. Most important, from our perspective, the code behind ASP.NET pages can be any .NET language, including C#.
Web Services are, essentially, Web applications with no user interface. A Web Service offers a service to another program, over the Web. This allows for distributed processing using standard Web protocols.
The canonical Web Service is one that takes a stock symbol and returns a quote. You can imagine Web Services that offer stock quotes, message forwarding, or other support services. Microsoft's new My Services (formerly Hailstorm) product builds Web Services as commercial offerings.
You can also, of course, build traditional desktop applications in C#, using Windows Forms. Windows Forms are very similar to Web Forms. It is my personal prediction that one day (soon?) Microsoft will combine Web Forms and Window Forms, but for now they are two similar but distinct technologies.
What Microsoft really did was to create a new unnamed language for .NET, which is detailed in the Common Language Specification (CLS)-the specification for all .NET languages. This allows Microsoft (and other vendors) to provide a plethora of syntaxes for their single common language. Thus, C# and VB.NET are really the same language with different faces!
All CLS languages must support the Common Type System (CTS) , ensuring that types used or created in VB.NET are compatible with types used or created in C#. In fact, the CLS is so well defined that you can create a class (user defined type) in C# and derive from it (specialize it) in VB.NET! You can throw an exception in a VB.NET method and catch it in a C# method! (I'll define all these terms and talk about how to create classes and manage exceptions in future columns.)
Neither C# nor Visual Basic .NET produces executable programs. Instead, all CLS languages produce Microsoft Intermediate Language (MSIL-often shortened to IL) code. The Just In Time compiler built into the CLR compiles the IL code when your program is run (and caches it in memory so that it need only be compiled once). C# programs and VB.NET programs produce virtually identical IL code; again, they really are just about the same language with different syntax.
Okay, I won't duck the question: if C# and Visual Basic .NET produce the same code, why would you choose one over the other? While there are minor differences in the capabilities of the languages, there is no good technical reason to prefer one to the other, in a vacuum. That is, from a purely technical viewpoint, these languages are virtually interchangeable.
But you are not programming in a vacuum and there are a few good non-technical reasons to choose one over the other.
First and foremost, you might decide to go to C# or VB.NET based on your existing comfort with one or another syntax. Arguably, if you are a Java or C++ programmer, the transition to C# will be easier for you. Similarly, if you are a VB programmer, the transition to VB.NET will be smoother.
The second consideration is purely mercenary. Historically, C++ programmers have earned more than VB6 programmers. Setting aside whether or not this was justified, it was the market reality for most programmers. Many managers tell me they expect more skill (analysis, design, and so forth) from their C++ programmers. Thus, when hiring for .NET, these same managers expect to pay C# programmers more than they will pay VB.NET programmers. This may change over time, but it may not; if it turns out that VB.NET programmers were VB6 programmers, and C# programmers were generally C++/Java programmers, the disparity may continue.
Given that the transition to VB.NET is difficult (as noted previously), many VB6 programmers will opt to transition to C# now, in the hope that C# will offer higher compensation. In addition, there are currently many more VB than C++ programmers, and so there is some expectation that C# programmers may be in relatively scarce supply for a while; again driving up their earnings potential.
Caveat: I have a vested interest in millions of VB programmers switching to C# and so my perspective may not be objective.
The best way to get a handle on C# is to write a program. Let's write three: a console application, a Windows application, and a Web application. Because this is a column and not a primer, I'll skip over lots of details and focus on the key issues. In this case, the key issue is this: programming in C# is a blast!
Let's get started. I'll assume you ha ve installed .NET Beta 2 or the release candidate, and that you've installed Visual Studio* .NET and IIS. If not, please do so now. I'll wait...
Good. Fire up Visual Studio* .NET and click New Project. In the Project Types window, click Visual C# projects. In the Templates window, click Console Application. Set the location to a reasonable directory (you may want to click Browse to set this), and in the name field type HelloWorldConsole, as shown in Figure 1.
Figure 1. Creating the Console Application
Click OK. The new console application opens for you. Visual Studio .NET tries to be helpful. It creates a new file named Class1.cs and in that file it puts the following code:
There is a lot going on here. I'll cover all of it very briefly. The first line:
tells the compiler that you'll be using the System namespace. Namespaces are just a way to divide the world of identifiers (method names, and so forth) so that my Class1 doesn't conflict with a Class1 I might purchase from a vendor.
The program begins by creating a new namespace for my program:
This is optional but convenient. It isolates the names of all the classes and methods I create within the HelloWorldConsole namespace.
The three slash comments:
are XML documentation-a topic I'll try to cover in a later column. For now, you can ignore them or delete them; it won't matter either way.
The heart of this program is the creation of the class Class1. You are, of course, free to change the name of the class (and the file that holds it), but for now let's leave it as it is.
Within the class definition is the method Main. Main is the entry point for the console application: that is, execution starts here. Let's skip over the characteristics of Main (that it is static, returns void, takes a parameter named args) and just accept for now that this is how Main is created. We'll come back to these particulars in the future.
Within Main is a comment:
C# supports three types of comments:
- XML documentation comments (///).
- C++ style comments (//). Anything from the // comment mark to the end of the line is ignored by the compiler.
- C style comments (/* */). Anything between the opening comment mark /* and the closing comment mark */ is ignored by the compiler.
Comments are, essentially, programmer notes; added to the code to remind you of what you were trying to accomplish. I could write an entire column on using comments well; for now I'll restrict myself to this: comment often, and don't say what you are doing, say why.
Remove the comments here, and replace them with this line:
C# is filled with classes and objects. Again, this is a big topic, but in short, a class defines a new type, and an object is an instance of that type. Thus, int is a type, 5 is an instance of the type int. Dog is a class, my dog Milo is an object: instance of Dog.
Console is a class that represents your output console (typically your monitor). Console has a method WriteLine. Here you are invoking that method and passing in the string Hello Intel!. The net effect is that this line will be written to your monitor.
(Object oriented programmers please note, in C# static methods are called on the class and instance methods are called on objects. In this case, WriteLine is a static method of Console and thus is called on the class. Non-object oriented programmers, don't fret, all will be made clear in time.)
Compile and run your program by pressing F5. The output should look like Figure 2.
Figure 2. Output from Console Application
To see what creating a Windows application is like, close the current solution and click New Project again. This time click Windows Application in the Templates window, and set the name to HelloWorldWindows.
Visual Studio .NET puts you into the development environment. Depending on how you are set up, you may see the Toolbox on the left, the Form Designer in the middle, the Solution Explorer on the right with the Properties window below it and a series of tabbed windows below the designer, as shown in Figure 3. If you don't see the windows you expect, click View or Debug to open the various windows. If the Toolbox does not stay open, click its tab and then use the push pin to pin it in place.
Figure 3. The Form Designer and Associated Windows
(click for larger image)
There is much to explore here, but we just want to get a quick feel for what is involved. Drag a Label onto the form, and then use the Properties window to set its Name to lblOutput and its Text to "Hello Intel!" Click the Font property to set the font size to 14, and click the label itself to show its resizing handles. Resize to fit.
Drag a button onto the form below the label. Set its Name property to btnChange and its text property to Change!. Click its Font property to set the font to bold and feel free to set other properties to change the background color or otherwise make the button more attractive.
Add another button next to it named btnExit with the text Exit. Shift-click the two buttons to select them both, and then use the menu choice Format / MakeSameSize / Both to make the buttons the same size.
Click the label and shift-click the Change button to highlight them both. Choose Format / Align / Lefts to align the label with the left side of the left button. Now resize the label (click it and drag the handle) to as wide as both the buttons combined.
Shrink the form to fit by clicking the form and resizing. Your form should look similar to Figure 4.
Figure 4. The Resized Form
It is time to wire the event handlers to the buttons. When a button is clicked, an event is raised. Event handling is a rather complex subject, but you can ignore all the details for now and let Visual Studio .NET do the work for you. Double-click the Exit button. VS.NET will create an event handler; you just supply the code.
You should find yourself with the cursor inside the btnExit_Click method. Add the following line of code:
That's it for that handler. Click the Design tab to return to the form, and then double-click the Change button. Again you are in the event handler. Add this line:
When you type the period after lblOutput, VS.NET will pop up a list of all the properties and methods of the label object. You can choose Text. and then continue typing.
Be careful-C# is case sensitive. You must type lblOutput exactly; if you type LblOutput or lbloutput, C# will not recognize your label.
Run the application. Click the Change button. You should see the new message displayed, as shown in Figure 5.
Figure 5. Testing the Windows Application
That's it! You have a working Windows application. Click the Exit button to exit the application.
There is much more to say about Windows programming, of course, but you see how easy it is to bang together a simple application. Before I end for this month, let's do the same thing with a Web form.
Close the Windows solution and create a new project, this time choosing ASP.NET Web Application from the Templates window. Name the application HelloWorldWeb. Visual Studio .NET creates a Web site for you. The Web pages are in the directory you choose on the opening dialog, and the solution files are stored in a directory under the default project location.
The Designer that opens in VS.NET is similar to the one for Windows development, as shown in Figure 6.
Figure 6. The Web Development Environment
(click for larger image)
Once again drag a label onto the form and use the Properties window to set its name to lblOutput and its text property to "Hello Intel!" Click the + sign next to the Font property to expand the font attributes, and set the size to larger. Stretch the label to hold the Goodbye Intel! phrase. Notice that you can place the label exactly where you want it; the default view of the form uses absolute positioning.
Add just one button this time. Set the Name to btnChange and the Text to Change!. Again, you can use the font to set the text to bold.
Click the HTML tag to look at the HTML this page is using. There is a lot going on here. I'll save a detailed explanation for a future column, but the important fact is that the designer is just using HTML. You can write this entire HTML page without the designer, just as you could write the entire Windows page without Visual Studio .NET, but it is far easier to use Visual Studio .NET.
Go back to the Design view and double-click the button. VS.NET displays the code behind page. This is a separate file that will be compiled, providing code support for server side processing for your controls. In this case you are in the event handler for the button's click. Add the same code you used in the previous example:
Press Ctrl-F5 to compile and run the program. Your page should open in a browser. Click Change. The page is posted back to the server and a new page is sent with the new text as shown in Figure 7.
Figure 7. The Web Application
Before you close this application, click View/Source. Examine the source code sent. The important thing to note is that what is sent to the client is just HTML. Nowhere do you see the code supporting the page; that is held on the server. ASP.NET pages are just HTML and thus can be viewed with any browser.
We've just scratched the surface with C#, and in future columns I hope to dive into more detail.
I'm very much looking forward to writing this column and to receiving your feedback, inquiries, and concerns. To give me feedback or to ask questions, please go to my Web site:.* You'll find a link to information about this column. Also, be sure to check out my support discussion group on*, where you'll find a folder for questions and issues about this column.
Thanks.
Jesse Liberty is the international best selling author of Programming C# and Programming ASP.NET (O'Reilly), as well as Teach Yourself C++ In 21 Days (SAMS), Clouds To Code (Wrox) and a dozen books on object-oriented Web and applications development. Jesse is the president of Liberty Associates, Inc., (*) where he provides on-site training in .NET development, as well as custom programming and consulting.
For more complete information about compiler optimizations, see our Optimization Notice.
|
http://software.intel.com/en-us/articles/programming-net-with-c/
|
crawl-003
|
refinedweb
| 3,432
| 74.39
|
❮ PreviousNext ❯ In this tutorial, we will learn how to write first perl program and run it on various Operating Systems. First Perl Program: Hello World This is a simple perl program that prints Hello World!! on the screen. #!/usr/bin/perl #this is a comment print “Hello World!!”; Here first instruction #!/usr/bin/perl tells Operating systems […]
Installing Perl on Windows, Mac, Linux and Unix
[…]
Perl Tutorial for beginners
Perl […]
Java – Find files with given extension
In this tutorial, we will see how to find all the files with certain extensions in the specified directory. Program: Searching all files with “.png” extension In this program, we are searching all “.png” files in the “Documents” directory(folder). I have placed three files Image1.png, Image2.png, Image3.png in the Documents directory. Similarly, we can search […]
Lambda Expression – Iterating Map and List in Java 8
I have already covered normal way of iterating Map and list in Java. In this tutorial, we will see how to iterate (loop) Map and List in Java 8 using Lambda expression. Iterating Map in Java 8 using Lambda expression package com.beginnersbook; import java.util.HashMap; import java.util.Map; public class IterateMapUsingLambda { public static void main(String[] args) […]
Swing – BorderLayout in Java
Borderlayout has five areas where we can add components, the areas are: 1) PAGE_START 2) PAGE_END 3) LINE_START 4) LINE_END 5) CENTER In this screenshot we have five buttons that are added to each area of a container. The container has BorderLayout. Button names are same as area names for better understanding, they can be […] […]
Java – FlowLayout in AWT
Flow layout is the default layout, which means if you don’t set any layout in your code then layout would be set to Flow by default. Flow layout puts components (such as text fields, buttons, labels etc) in a row, if horizontal space is not enough to hold all components then Flow layout adds them […]
Nested or Inner interfaces in Java […]
- « Previous Page
- 1
- 2
- 3
- 4
- 5
- …
- 67
- Next Page »
|
http://beginnersbook.com/page/3/
|
CC-MAIN-2017-17
|
refinedweb
| 339
| 55.03
|
Created 1 May 2016
This is a presentation I gave at PyCon 2016 in Portland.
You can read the slides and text on this page, or watch the video, or open the
actual presentation in your browser
(use right and left arrows to advance the slides).
Python is a great language. We love it for its flexibility and dynamism.
With discipline, we use Python in ways similar to stricter languages, and build
large systems successfully.
But at heart, Python is simpler and more fluid than other languages.
Sometimes you want this fluidity, but usually you don't. Dynamic typing means
that names may have values you don't expect. Where other languages offer
access control over the internals of objects, Python lets you examine and
change anything. All of your program's data is on the heap, and can be used
throughout your program.
All of this flexibility can be a powerful tool, but sometimes, things go
wrong. The flexibility comes back to bite us, and causes problems that we have
to debug.
OK, Python's lack of rules got us into a mess. Let's use that freedom and
power to figure out what's going on, so we can solve the problem.
We'll look at a few real problems that cropped up in real projects. We'll
debug the problem using dirty tricks to get at the information we need. Along
the way, we'll examine how some Python mechanisms work.
These techniques are not for use in real programs! They are temporary hacks
to get you out of a tight place. When you are in a jungle, a machete is a very
good way to get out, but for real work, you should build real paved roads with
signs and painted lines.
Ideally, you'd prevent these bad situations from happening in the first
place. I'm mostly not going to talk about how to avoid the problems: there are
lots of talks out there that can help you build properly from the start. This
talk is about using Python's flexible power to untangle yourself once you've
gotten into trouble.
All of the code in this talk is meant to be used, and then discarded. Once
it has served its purpose of getting you the information you need to understand
the problem, it should be deleted. It is all hacky, and all "wrong" on some
level.
By the way, a few of these cases I've written up in more detail on my blog.
I'll provide links to those posts as we go.
We had a problem where our modules were being imported more than once.
Since they contained class definitions, this meant our classes were being
defined twice. It's never been a good idea to live with this situation, but
Python won't complain about it, and often, it doesn't cause any issues. But
recent versions of Django complain about it, which is how we discovered it was
happening.
When you import a module, the .py file is found, and executed, and the
results become the attributes of the module.
Modules are only executed once, because the sys.modules dictionary keeps
track of all the modules that have been imported. Once a module has been
imported, subsequent import statements simply find the module in sys.modules,
and return it, rather than executing the file again.
The first time a module is imported, Python has to find a .py file for the
module. sys.path is a list of directories that Python uses to look for .py
files. Each directory is examined for the .py file. When the file is
found, it is executed, a module is made from the result, and the module is
stored in sys.modules.
With all this machinery to ensure files are only executed and imported once,
how are ours being imported twice? We could read the code, or use grep to look
for reasons. But one of the consequences of Python's dynamic nature is that
static analysis like that is difficult.
So instead of static analysis, we'll use dynamic tools. Let's run the code,
and get it to tell us what's going on. This theme runs through all of the
cases we'll look at: rather than try to analyze the code, we'll run code to
understand it.
To find the problem, we'll take advantage of the fact that importing a
module really executes the code in the module. Classes and functions are
defined in a module because the class and def statements in the .py file are
executed. Often, it's easy to think of modules as just containing classes and
functions, but they are really executable statements that define classes and
functions.
Whatever code you put at the top-level of a module, it will execute when the
module is imported. There is no special "just define classes and functions"
mode that imports your module. The code is really run, and any statement can
be in a module.
So if we put code into one of our double-imported modules, it will run,
twice. The code we put in uses inspect.stack to examine the current state of
the call stack. This will tell us who is importing the module.
If you haven't looked at the inspect module, go take a peek. It has lots of
interesting functions for getting information about all kinds of things.
inspect.stack returns a list of tuples, one for each frame in the call stack.
The tuples include the name of the function, the filename and line number, and
a list of source lines around the call site. It's a great way to pinpoint where
you are in your program.
Here I'm formatting the function name, file name, and line number, into one
line for compact output.
I'm also opening a temporary file for output, and writing the results to it.
I do this so I don't have to worry about whether stdout is being captured, or
where it is going. By opening a specific file, for appending, I can be sure
about where my output is going.
This is the "wrong" way to log, but I don't care. I didn't want to fiddle
with the right ways, and this code is only temporary.
The results look like this. The way I've formatted the stack, the function
name is to the left of the colon, and the file name and line number are to the
right. In this case, the function name isn't that useful, since what we're
looking for is the file that is importing the doubly-imported module. The
import statements won't be inside a function, so it's reported as <module>
instead.
With these results, we have two files to examine, the last one in each stack
trace: second/summary.py and first/admin.py.
Once we looked at those two imports, we could see what was wrong. This slide
shows a simplified version of the problem.
In our source tree, we had files that were accessible through two different
entries in sys.path. The asterisks show the directories that were in sys.path.
The file that was being imported twice was project/thing/apps/first/models.py.
In one file, it was imported as "thing.apps.first.models", and was found via
the "project" sys.path entry. In the other file, it was imported as "first.models"
and was found via the "project/thing/apps" sys.path entry. The first import created
a "thing.apps.first.models" key in sys.modules. The second import looked for a
key of "first.models", didn't find it, and then imported the same file again.
The fix was to choose one style of import, and stick with it throughout the
code.
Some things we took advantage of here:
Many of our tests create temporary files or directories. The good tests
properly clean them up at the end of the test run. (By the way: if you are
using unittest to write your tests, definitely use addCleanup, it's much better
than tearDown.)
The bad tests weren't cleaning up their temporary files and directories.
Finding those tests was difficult, because they weren't written as simply as
the example here. The temporaries were created in helper functions, making it
harder to find the places where a temporary was being made but not cleaned
up.
We want information about who creates the files. One way would be to note
the name of each temporary file created, along with the call stack that made
it. Then when the test suite finishes, we could look up the names of the
marooned files to see where they came from.
I took a different approach: since we only care about the files that remain
when the tests are done, what if we write the information we need into the
files themselves? We can't write our own data into the content of the files,
since the content is being used by the tests. But the file names are
essentially arbitrary anyway, so we can write information there.
To do anything special during the creation of temporary files, we'll
monkeypatch functions in the tempfile module. Monkeypatching is the colorful
name for changing someone else's code at runtime by injecting your own code
into their namespace.
For example, to change how mkdtemp works, we can define our own function
with the same calling signature, and then assign it to tempfile.mkdtemp. Now
unsuspecting product code that calls tempfile.mkdtemp will actually be running
our function, rather than the code in the standard library.
This works because no names are special in Python: mkdtemp is an ordinary
attribute of the tempfile module, and can be reassigned just as any other name
can be. This may seem odd: the standard library feels like it should be
unchanging, the rock on which we build our programs. But the standard library
is made of Python modules like your own code is. Any name can be
reassigned.
Monkeypatching can be very powerful, since you can hijack any name that
other parts of your program are using. It can also be dangerously chaotic.
One of the things that can be tricky to get right when monkeypatching is
what exactly to patch. In our case, there are a handful of different tempfile
functions that could be involved. And we don't want to take over the entire
function, we just want to change what names the files get.
Reading the source in tempfile.py, it turns out that all of the functions
that create temporary files or directories make use of the same helper,
_get_candidate_names. This function generates a sequence of possible file
names. It's responsible for the typical random names you see in temporary
files. The functions then try each name in turn, looking for one that isn't
already being used.
If we monkeypatch _get_candidate_names, we'll have killed two birds with one
stone: we'll centrally affect all of the functions that can create temporary
files, and we'll only affect the file names they create, not how they create
the files, or what details they return.
Another factor that complicates monkeypatching is that you have to patch the
function before it gets called. You might also need to patch the function
before it is imported, depending on how it's imported. For the most effective
monkeypatch, you want to run your patching code before any other code in the
program.
Ideally, we'd have a way to run the monkeypatch before the main program.
But Python doesn't have a feature for running a preamble before the real
program. Luckily it has a way we can sneak code into the startup of the
interpreter.
One of the ways that installed packages are referenced is by a
Python-specific form of symbolic link called a .pth file. These small files
usually just contain the name of another directory to include when searching
for packages.
But if a line in a .pth file begins with "import", then the line is
executed! We can use this, along with the knowledge that code in imported
modules is truly executed, to get code to run as early as possible in the
program.
We create a file called first_thing.py, and put in it all the code that we
want to run first thing. Then we create a file in the site-packages directory
called 000_first.pth. It imports first_thing. We name the file 000_first.pth
because .pth files are processed alphabetically. Our name will ensure that our
code is run even before other .pth files are processed.
Now that we have a way to run code on startup, here's the patch itself. We
define my_get_candidate_names to yield possible names for the temporary file.
We save the original _get_candidate_names function so that we can use it as
part of our function. Our function uses our old friend inspect.stack,
concatenating the last few source file names and line numbers into something
compact enough to fit in a file name.
We monkeypatch tempfile._get_candidate_names, and now any tempfile function
that makes temporary files will have our stack traces in their file names.
Lessons:
More detail on this case is in my blog post
Finding Temp File Creators.
At one point, our test suite was failing because the wrong module was being
imported. We had "import xblock", intending to find "apps/xblock.py", but we
were importing "lib/xblock.py" instead. But "lib" wasn't on the path, so how
was it being imported?
Examining sys.path where the import was happening (by just adding a print
statement before the import!), there was a new incorrect entry that had been
added to sys.path. What put it there?
We already knew we had sys.path manipulation that we were not proud of, so
maybe there were others to find. A check of our sources proved that we weren't
doing it. Some third-party code must be at fault. We couldn't grep all of the
third-party modules we were using. How to find the culprit?
What would be great is a way to break into the debugger when a certain piece
of data is changed. In this case, the incorrect entry in sys.path was being
added as the first element, and it ended with "/lib". We want to stop in the
debugger when a condition is true: sys.path[0].endswith("/lib").
The standard Python debugger, pdb, doesn't have this feature. You can set a
breakpoint at a particular line, with a condition. But we wanted a condition
untethered from a line of source code. We wanted to stop in the debugger when
the condition became true, no matter what line of code was running.
Python debuggers (and other tools, like coverage measurement) are built on a
feature called the "trace function." This is a Python function that is called
for every line of running program. Every time a new line is executed, the
trace function is called to track the program's progress.
Since our condition is so simple, it's easy to write a trace function to do
what we want: check the condition, and if it's true, break into the
debugger:
def trace(frame, event, arg): if sys.path[0].endswith("/lib"): pdb.set_trace() return tracesys.settrace(trace)
To be honest, I wasn't sure what would happen if I tried to start the
debugger from inside a trace function. That seemed particularly twisty, but
this trace function was simple enough to write and try, I figured I'd give it a
shot. This is classic machete-mode style: there was a good chance this wouldn't
work at all, but it was easy to try.
It worked great: with this trace function in place, the test suite ran
(really slowly!), and revealed that our test runner, nose, was adding the entry
to sys.path. A little more investigation revealed that this was configurable,
so it was easy for us to disable.
More detail on this case is in my blog post
Ad-hoc Data Breakpoints.
We run Python code as part of presenting problems to students. We
randomize some components of the question so that different students get
different problems. But we seed the random number generator with a
student-specific seed so that if a student revisits a problem, they will see
the same problem each time.
We were seeing that the first time the problem generation ran, it would get
one set of values, but then subsequent runs would get different, but consistent
values.
The "first is different than the rest" factor made me think that something
was happening during import. Remember that modules are executed when they are
first imported, but subsequent imports just use the stored module object.
There were two ways the random sequence could be changing: either something
was re-seeding the random number generator, or something was eating some random
numbers from the sequence.
A little experimentation in the interactive interpreter showed that one
value was being consumed from the sequence. But where?
Again, we'll use monkeypatching to find the problem. This time though,
instead of providing a useful new implementation of the function, we're
planting a booby trap.
We replace random.random with a function that will raise an exception when
called. Then we can run the code, and examine the traceback to see what is
consuming the random number.
The code is very simple: 1/0. Dividing one by zero will raise a
ZeroDivisionError. This is extremely handy. It's easy to drop into some code
when you want to see if it executes. The ZeroDivisionError it raises is an
unlikely exception, so you can be sure it's yours.
Here we run the code again, and our one-over-zero finds the problem quickly.
One of our third-party libraries was importing its test-case code. The
constructor had a default argument with a random value. Default values are
evaluated once, when the function is defined. So this random.random() call
happened during import.
This library shouldn't be doing this, but as an extra bonus, that default
value is never used, because the constructor was always called with an explicit
value for that argument.
More detail on this case is in my blog post
Hunting A Random Bug.
When your program is misbehaving, you need to get information about what is
happening. You can do things wrong temporarily to get what you need, and then
clean it up afterwards.
All of the techniques here have been dynamic analysis: getting information
from actually running the code. This cuts through all of the dynamism that is
hard to analyze statically.
Understanding how Python works gives you leverage against problems like
this, and can help you find techniques to solve them.
By the way, if you have liked these cases, you might also like my blog post
about Stack Ninjas,
which uses similarly subversive techniques.
Thanks for your attention, I hope this has been helpful.
Great talk, thanks!
Although it might have made this talk almost "all monkey-patch, all the time", would it have worked to monkey-patch sys.path with an object of a class that does that value check on every mutation?
Seems to me that would take a bit (maybe a lot?) more code, but it would be a lot faster at runtime. I guess it depends on how long it would take to run your tests if 'nose' wasn't imported early in the process...
I'm curious why you use the inspect module instead of the traceback module to look back into the call stack. traceback.extract_stack will give you the current stack frame list. I think traceback is the more current module, leading me to believe it is some improvement over inspect. As for double-importing, I had my own variation on this theme when upgrading to Python 2.6, it seems that super() is picky about what instances can super() to what classes, and I clobbered my class definition using imp.load_module. I blogged about it here:
@Mike: I got asked this at the conference also, about replacing sys.path with my own object. I feel like I would have tried this, and it didn't work for some reason, but I haven't gone back to try it again.
@Paul: I don't have a reason to prefer inspect over traceback (any more than the stdlib has a reason to have the same functionality in both places!) I think of inspect first because it offers what I need in the way I need it, without extra functions, and it offers a broader array of functions offering useful information.
2016,
Ned Batchelder
|
http://nedbatchelder.com/text/machete.html
|
CC-MAIN-2017-09
|
refinedweb
| 3,486
| 73.88
|
route2 0.1.1
route2: ^0.1.1 copied to clipboard
A client + server routing library for Dart 2.x
Use this package as a library
Depend on it
Run this command:
With Dart:
$ dart pub add route2
This will add a line like this to your package's pubspec.yaml (and run an implicit
dart pub get):
dependencies: route2: ^0.1.1
Alternatively, your editor might support
dart pub get.
Check the docs for your editor to learn more.
Import it
Now in your Dart code, you can use:
import 'package:route2/client.dart'; import 'package:route2/pattern.dart'; import 'package:route2/server.dart'; import 'package:route2/url_pattern.dart';
|
https://pub.dev/packages/route2/install
|
CC-MAIN-2021-17
|
refinedweb
| 110
| 70.9
|
Details
Description
Issue Links
- blocks
-
-
- depends upon
-
- is blocked by
-
- requires
-
Activity
- All
- Work Log
- History
- Activity
- Transitions
Hey Grant:
Sounds good, but how are you going to deal with the field types that need multiple fields (i.e.
SOLR-1131)?
Heh, I wasn't. I was just starting with GeoPointField, and was going to start indexing it as e.g., a single String value, in georss:point format. I thought about the whole 2-field approach, i.e., to do a double lat, double lon thingeee, but I just wanted to start simple, with what exists, and see where it leads me. Sound OK?
Cheers,
Chris
I'm not sure what good that does to put a lat/lon in a single String in georss:point format. What's your intent for searching/sorting/faceting?
Good question: I'm not sure what my intent is yet either. Sorting on a lat,lon pair is different depending on which lines you are trying to follow (North, South, etc.), so it's not entirely clear to me the best way to do that. As far as searching my guess is that, at least in the beginning, like requiring the user to input Dates in ISO 8601, maybe we start out asking the users to input georss points, but then get smarter as we understand more. Dunno, just a thought.
Hey Grant:
what you are proposing doesn't get you anything over just using StrField.
I sort of get this, but then I don't. The outlier is DateField – what does it get you other than some magic around ensuring that dates are stored as ISO 8601 dates? In the end, it's just a special type of StrField though too, right? Not trying to be difficult, just trying to understand.
In any case, I'll focus on GeoHashFieldType for now, regardless...
Cheers,
Chris
- patch only includes GeoField, and doesn't do any fancy multi-field stuff yet, as discussed. However, the parts about writing its output in georss is probably still useable in its current form. Note to test this patch, post.sh the example doc I'm attaching to your solr instance using the mods to the example schema I've attached. Then, do a default solr query to get the doc back, and then observe a georss:point field coming back
- note check out this patch: I messed up the copyrights on the other one I included (Eclipse threw my work copyright ones in there rather than Apache)...
Hey Chris,
I'm not sure we want to bring in the actual namespace for georss. That seems like overkill, but I'm open to hear what others think.
Also, where does this patch actually encode the Geohash value? The Lucene spatial contrib JAR has GeoHashUtils for just this. See the GeohashFunction for usage.
Hey Grant:
It doesn't encode the geohash, I was working on that. What's hilarious is that I was reading up on Wikipedia on how to implement Geohash:. I noted that it needed a Base32 encoder/decoder as part of this. So, of course I went over to commons-codec and looked for it there:. I saw
CODEC-88 and said oh, no one has implemented an ASL base32 encoder: I guess I'll implement one as part of this issue and then contribute it back to commons-codec. However if you are saying this exists already in the spatial contrib jar, acccck!!!! What's more if that implements the whole GeoHash thing then double acccck!
I'll have a patch up in 30 minutes if that's the case. However, if it is the case, then I'm sad because I just got my Base32.encode function to work:
Cheers,
Chris
sniffle, found the geohash in spatial contrib
Uh uh I mean, yes!
Patch, attached...
another Eclipse copyright snafu (I took it out back though and I don't think this will be happening again), please use this latest patch...
we should have the ability to output those fields as georss per ryan's suggestion
Ryan can correct me if I am putting words in his mouth, but I don't think he literally meant we needed to use those exact tags. I think he just meant the format of the actual values.
Hey Grant:
Ryan can correct me if I am putting words in his mouth, but I don't think he literally meant we needed to use those exact tags. I think he just meant the format of the actual values.
Ah no worries – I think it would be a nice feature to actual output using those exact tags. That's the point of a standard, right? With the tags comes namespacing and all that good stuff, which I believe to be important.
Also, since XmlWriter is even more flexible per
SOLR-1592, then I see no reason not to use those tags in the output?
Cheers,
Chris
FYI, see the
SOLR-1131for an implementation of a Point Field Type.
Sure, I'll take a look @ it and try to bring this patch up to speed w.r.t to that. Independently though, the geohash implementation i put up should be good to go right now. Please take a look and let me know if you are +1 to commit. I included an example doc to test it out with.
Cheers,
Chris
Can you put a patch containing just the geohash stuff?
updated patch containing only the geohash goodies.
Okay, so I gave up on outputting georss in the SOLRXmlResponse (sniffle). Instead, here's the 1st of 2 patches. This one outputs the point as a double array. I'm torn. It's probably more conceptually correct, but it's weirder from a I put in a string delimited by a whitespace and got out a point as an array. Nevertheless, I'm attaching it. Next one will just be a string.
, and #2, the string version. My +1 for this in the end.
Here's a patch for Geohash along w/ tests and support in the examples.
Grant:
Thanks! +1 on the patch – I think it's pretty much ready to go.
Cheers,
Chris
Should have a CartesianTier field type patch today.
Hi Grant,
Are you building the CartesianTier field type against the existing CartesianTier API?
For better or worse, yes. It's either that, or it needs to be duplicated here until Solr is on 3.x of Lucene and can incorporate your changes there.
Here's a patch with both geohash and Cartesian Tier.
Note, the test for Cartesian Tier (in PolyFieldTest) is not yet correct even though I think the underlying functionality is. (In other words, the test itself is not right).
One of the interesting things for Cart Tier is what the notion of a field query and range query are. See my thoughts in the comments. Also, I currently am throwing an UnsupportedOpException in getValueSource in Cart Tier stuff. Not sure if it is meaningful or not to allow functions to operate on the whole tier.
- updated Grant's patch with more javadocs
- formatting updates
- fixed bug about referencing StrFieldSource via SOLR-1688
I get errors on the following tests:
[junit] Tests run: 2, Failures: 1, Errors: 0, Time elapsed: 2.473 sec
[junit] Test org.apache.solr.search.function.distance.DistanceFunctionTest FAILED
[junit] Tests run: 5, Failures: 1, Errors: 0, Time elapsed: 6.32 sec
[junit] Test org.apache.solr.schema.PolyFieldTest FAILED
Which I think Grant noted in his prior comment.
The DistanceFunctionTest failure is unrelated and has been fixed. The PolyFieldTest failure is expected.
The problem w/ the PolyFieldTest is that the CartesianShapeFilterbuilder automatically picks the "best fit" tier w/o knowing what tiers were actually indexed. So, it picks tier 15 when the test only sets up tiers 4-10.
One of the interesting things for Cart Tier is what the notion of a field query and range query are
Hmmm, why is there even a fieldType for cartesian tier?
How will it be used? I don't see any examples of end-user config and query syntax this is meant to support.
Hi Grant:
What's the bug here?
Your last patch referenced StrFieldSource in the GeoHashField class we developed:
+ @Override + public ValueSource getValueSource(SchemaField field, QParser parser) { + return new StrFieldSource(field.name); + } +
Of course, StrFieldSource is a private class defined in StrField in the o.a.solr.schema package. This led me to take a look and realize that the FieldSources are really defined inconsistently (check out SOLR-1688, patch available).
Cheers,
Chris
How will it be used?
It's a common GIS technique for reducing the number of terms/space to enumerate in a single field by dynamically selecting the appropriate tier based on the lat/lon input and a distance. It's mainly used for creating filters.
Once
SOLR-1568 is converted to use this field type, then it will be fully supported.
Of course, StrFieldSource is a private class
No it's not. It's package private. Is there something that isn't working?
No it's not. It's package private. Is there something that isn't working?
Interesting. Eclipse was giving me an error on using StrFieldSource in GeoHashField, right on that line I pasted above. It said StrFieldSource not found, and so taking a look it looked like StrFieldSource was an inner class (hard to see that little "}" at the end and whether it was defined inside of StrField or not). So I thought you were referencing an inner (private) class from StrField external to it. Funny now though after an Eclipse rebuild, Eclispe seems to be OK with StrFieldSource and its referencing in GeoHashField (which it should since they are both in the same package).
Regardless though, this illustrates my point on SOLR-1688 – these FieldCacheSources should be defined a bit more consistently – when looking at a bunch of code, it's hard to see whether it was an inner class or a separate class defined in the same java file.
> How will it be used?
It's a common GIS technique
I meant as it pertains to Solr... what will one put in their schema and then what will an example query look like that does both a filter and a sort by distance? Or is that out of scope for this issue?
There is an example of what goes in the schema on this patch:
<!-- A CartesianTier is like a set of zoom levels on an interactive map (i.e. Google Maps or MapQuest). It takes a lat/lon field and indexes it into (endTier - startTier) different fields, each representing a different zoom level. This can then be leveraged to quickly narrow the search space by creating a filter, at an appropriate tier level, that only has to enumerate a minimum number of terms. See --> <fieldType name="tier" class="solr.CartesianTierField" start="4" end="15" subFieldSuffix="_d"/>
I think the filter question is best answered on
SOLR-1568, but I'll give a brief thought. Something like:
&fq={!tier dist=20}location:49.32,-79.0
or it could be:
&fq={!tier lat=49.32 lat=-79.0 dist=20}
I'm not sure which I prefer.
Renamed CartesianTierFieldType to SpatialTileField and renamed the other nomenclature to be called a SpatialTileField as I think the "tile" name is much more commonly used in the GIS communities.
The reason why I was asking about interface examples is that it looks like filtering is being considered separate (i.e. it would be up to the user to correlate the point field with the tile field). While it's fine to allow the explicit creation of a tile filter, it doesn't seem like we should require clients to know all the details.
#gfilt short for geo-filter?
q=foo&fq=
&sort=gdist(store_location,10,20)
So it would be really nice if the same request would work regardless of which point field was being used (trie based, spacial tile, or geohash).
Committed revision 894301.
Unlike PointType, it seems odd that a user would need to understand and declare any kind of subFieldTyp/Suffiix for SpatialTileField... seems like this one we really want to be an implementation detail somehow... and ultimately it seems like we want to allow the SpacialTileFIeld to be an implementation detail as well. It would be nice to just define a SpacialTilePoint and just use it for everything (filtering, distance calculations, etc).
Unlike PointType, it seems odd that a user would need to understand and declare any kind of subFieldTyp/Suffiix for SpatialTileField... seems like this one we really want to be an implementation detail somehow..
I suppose they could just always be a DoubleField subtype, but how do you guarantee it is registered in the schema? I suppose it is 99.99% likely it will be there, so we could just assume it. I can change it to do this.
and ultimately it seems like we want to allow the SpacialTileFIeld to be an implementation detail as well. It would be nice to just define a SpacialTilePoint and just use it for everything (filtering, distance calculations, etc).
I'm not sure I see how to use a tile for anything other than filtering (is the point in the box or not). I suppose it could be used for vary crude distance calculations, but that doesn't seem all that useful. I think there may be too much of a goal to hide all the details from the application. The choice of the data structure is going to depend on the application, just as one chooses to use int, float or double depending on their application needs. Many applications will do just fine using PointType with a double, even for range queries. Others may specifically want a tile approach as it best solves their problem.
I'm not sure I see how to use a tile for anything other than filtering
That's the point though - as a casual user, I want a point field. I want to be able to do efficient spacial search on that field and not worry about all of the details. See the example I gave above... it's doing everything spacial-related on the same field. So a higher level SpatialTilePoint would be a point field (i.e. it would still have lat/lon separately) that used tiles under the cover for efficient bounding box / filters.
edit: don't get me wrong, I think it's also good to also enable the use of SpatialTileField separately (as this issue does). It's the overall spacial-solr capabilities I'm talking about.
The choice of the data structure is going to depend on the application
There will often be many applications / clients. One should be able to change the underlying implementation and use the same requests. We can do this today with range queries on any type of numeric field... we should be able to do it with a bounding box or distance filter.
A tile is not a point. A tile is a box containing lots of points and is used as a quick substitution for all of those points in the box. It's basically an indexing time optimization that precalculates the bounding boxes ahead of time.
A tile is not a point.
Then we're talking past each other a bit. I understand what a tile is.
A tile can also be viewed as an implementation detail to speed up spacial querying / filtering. So we could have a SpatialTilePoint that is a point, and under the covers, it also does stuff (like index spatial tiles) to speed up filtering.
I'm not suggesting changing SpatialTileField... I'm suggesting that in the overall scheme of things, it's not the highest level abstraction we want.
A tile can also be viewed as an implementation detail to speed up spacial querying / filtering. So we could have a SpatialTilePoint that is a point, and under the covers, it also does stuff (like index spatial tiles) to speed up filtering.
Yeah, I debated whether we wanted the SpatialTileField to also index the point (as in deferring to PointType) but decided this was easily enough done via a copy field. If you think there is value there, though, it would be trivial to implement the combination of PointType and SpatialTileField.
FWIW, I think
SOLR-1568 will take care of hiding the details sufficiently from the user.
Hi,
I'm not entirely clear of the outcome of the discussion re the SpatialTilePoint, but I would really recommend keeping this as far away from the user as possible. Ideally they shouldn't have to know about it at all since it seems that the implementation of the spatial tiling is still heavily in development. Alternatives have even been suggested that would make it redundant.
I agree with the idea that to the user they should only be concerned about their documents have a Point. It then frees us up to do all kinds of changes to the underlying logic, without the definition of their documents having to change.
Yep, the user still simply adds a Point to the document, that side of the coin won't change. How the tile is implemented underneath the hood is in fact one of the benefits of doing it as a FieldType. At some point, though, if a app designers does wants a tile-based system, they need to declare as much.
Alternatives have even been suggested that would make it redundant.
Would be good to provide a reference if you have it handy, just so it is recorded here.
The alternatives I'm alluding to are the use of TrieRanges to do an efficient bounding box style filter instead of the tiling system. In
SOLR-773 this was touched on, but I never saw an outcome to that discussion. I think it is a worthwhile thing to explore, even as part of the work being done here in Solr.
Do you mean TrieFields (not familiar w/ TrieRanges)? Assuming you do, Trie Fields can be used, but their downside is they require searching two fields instead of one. They are already supported out of the box by Solr.
Ah yes sorry TrieFields. I don't see searching 2 fields as a downside since that's just an implementation detail like the Spatial Tile (which requires you to have upto 15 fields). Assuming you can use the Point FieldType to index an x and y field, then it just becomes another option like Spatial Tile. The fact they are supported out of box is part of the attraction, as it would reduce how much custom code has to be maintained.
I don't see searching 2 fields as a downside since that's just an implementation detail like the Spatial Tile
Searching 2 fields instead of one can be significant. AIUI, the big problem comes in when you have really dense areas that are used by high traffic sites, such as Manhattan or somewhere similar and could have a million lat/lon pairs all in a 5 mile radius.
If its not something we want to support, then thats fine. Particularly given the stats Patrick has, its been clear that in those high density environments its not a good choice. My original point was that this aspect of the spatial search is still heavily in development and I was advocating trying to reduce the visibility of the Spatial Tile implementation so that we are freer to do that development.
My original point was that this aspect of the spatial search is still heavily in development and I was advocating trying to reduce the visibility of the Spatial Tile implementation so that we are freer to do that development.
+1
One could also imagine future implementations that allow varying resolution depending on the area to help fix the dense city issues.
Also, an implementation based just on trie range queries might be nice, as a reference to test other implementations against. As Patrick points out, the only missing code is that to determine the bounding box so that range queries can be created.
Sounds good. I'm open to specific suggestions on how to do that. I think the key lies in the QParser, which will completely hide it from the app other than the schema designer needs to make the choice about setting up a field to index it. I don't see it as something that would work as an attribute on the generic PointType, but we could have a derived 2D PointType that specifically captures both the point capabilities and the Tile capabilities.
I also don't feel like having a SpatialTileField necessarily ties our hands dev. wise. We can still change the underlying implementation (heck, it could likely all be done in a single field w/ payloads. I'd like to see the performance characteristics of that) The user is still just passing in a lat/lon pair against that field.
Sounds good. I'm open to specific suggestions on how to do that. I think the key lies in the QParser
Right - I've mentioned a spacial base class a few times and this is why. It allows the implementation to be hidden, while also allowing custom classes to plug right into it. The QParser for "sfilt" would simply delegate to a method on the spacial base.
I don't see it as something that would work as an attribute on the generic PointType, but we could have a derived 2D PointType that specifically captures both the point capabilities and the Tile capabilities.
Yep, that's what I had in mind.
Correcting Fix Version based on CHANGES.txt, see this thread for more details...
Bulk close for 3.1.0 release
For reference, I'm going to put up a patch (or series of them) on this issue that implements Ryan McKinley's suggestion (from
SOLR-773):
|
https://issues.apache.org/jira/browse/SOLR-1586?focusedCommentId=12787115&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
|
CC-MAIN-2016-07
|
refinedweb
| 3,666
| 72.36
|
By Gary simon - Feb 12, 2018
Note: This tutorial is a part of our free course: Vue Tutorial in 2018 - Learn Vue.js by Example
Vue offers vue-router, which is their own router library that you can use to set up page paths and routes within your Vue application. In this tutorial, we're going to integrate the vue-router and setup a simple navigation with two different components.
Let's get started!
Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.
When we used the Vue CLI to start our project, we did not include the vue-router package. This is an option that you're able to specify while starting the project by selecting the manual configuration option.
No worry, though, we can add in the vue router ourselves.
First, visit the project folder within the console and run the following command:
> yarn add vue-router
Note: Our project is using yarn, but if you're using npm, you can install it with npm install vue-router --save
Next, we have to create a /src/router.js file with the following contents:
import Vue from 'vue' import Router from 'vue-router' import Skills from './components/Skills.vue' import About from './components/About.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'skills', component: Skills }, { path: '/about', name: 'about', component: About } ] })
This imports our Skills.vue component, along with an About component, which doesn't yet exist.
Go ahead and create that file real quickly and paste in the following contents:
<template> <div class="about"> <h1>This is an about page</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna ali...</p> </div> </template>
Next, visit /src/main.js and add the following:
// other imports removed for brevity import router from './router' new Vue({ router, // Add this line render: h => h(App) }).$mount('#app')
Next, visit the /src/App.vue file and modify the <template> section as shown:
<template> <div id="app"> <nav> <router-linkHome</router-link> <router-linkAbout</router-link> </nav> <router-view/> </div> </template>
We're adding a nav element with two links using the Vue component router-link.
We've also added another Vue component router-view which denotes where the views will be placed when the user clicks on a nav item.
While we're here in App.vue, let's give our nav some style in the styles section of the component. Also, modify the body selector so that our UI is no longer centered vertically:
body { background-color: #EEEEEE; font-family: 'Montserrat', sans-serif; display: grid; grid-template-rows: auto; justify-items: center; padding-top: 50px; } nav { padding: 20px 20px 20px 0; } nav a { padding: 10px; text-decoration: none; background: #fff; border-radius: 3px; color: rgb(0, 110, 255); font-weight: bold; margin-right: 15px; }
Great!
Save it, and this should be the result in the browser:
Simple!
At times, you may need to grab data from the URL of your Vue app. Let's pass along a URL parameter called name to the about page.
Open up /src/router.js and modify the following:
{ path: '/about/:name', // Add /:name here name: 'about', component: About }
Next, visit the /src/components/About.vue file and modify the template section to show a their_name property we will define shortly:
<h1>Hello {{ their_name }}, this is an about page</h1>
Then, add a <script> section beneath the template section:
<script> export default { name: 'About', data() { return { their_name: this.$route.params.name } } } </script>
You use the this.$route.params.name_of_router_param property to access the router parameter name that we specified in the /src/router.js file.
Save the project and visit /about/AnyNameHere and you will see that value displayed in the template!
Easy!
It slightly bothered me that our list app did not have a way to remove items, so, if you're interested in that, here's how you can integrate that feature.
In /src/components/Skills.vue, modify the list item within the transition-group component wrapper to the following:
<li v-</i> </li>
We're just using the v-on directive to call a method on click remove().
Let's define that method in the component logic:
methods : { addSkill() { // Removed for brevity }, remove(id) { this.skills.splice(id, 1); } }
Next, we'll import FontAwesome for the icon referenced in the template. At the top of the styles section add:
<style scoped> @import "";
And that's it!
Now, you can add and remove list items:
Hopefully, you now have a good understanding of Vue router basics!
This concludes our free beginner's crash course to Vue 2! Please use our search bar at the top to search for more Vue 2 tutorials and courses.
Note: This tutorial is a part of our free course: Vue Tutorial in 2018 - Learn Vue.js by Example
|
https://coursetro.com/posts/code/139/Vue-Router-Tutorial---Using-Vue's-Router-Library
|
CC-MAIN-2020-29
|
refinedweb
| 816
| 62.48
|
Feedzirra
I’d like feedback on the api and any bugs encountered on feeds in the wild. I’ve set up a google group here.
Summary
A feed fetching and parsing library that treats the internet like Godzilla treats Japan: it dominates and eats all.
Description
Feedzirra is a feed library that is designed to get and update many feeds as quickly as possible. This includes using libcurl-multi through the taf2-curb gem for faster http gets, and libxml through nokogiri and sax-machine for faster parsing.
Once you have fetched feeds using Feedzirra, they can be updated using the feed objects. Feedzirra automatically inserts etag and last-modified information from the http response headers to lower bandwidth usage, eliminate unnecessary parsing, and make things speedier in general.
Another feature present in Feedzirra is the ability to create callback functions that get called “on success” and “on failure” when getting a feed. This makes it easy to do things like log errors or update data stores.
The fetching and parsing logic have been decoupled so that either of them can be used in isolation if you’d prefer not to use everything that Feedzirra offers. However, the code examples below use helper methods in the Feed class that put everything together to make things as simple as possible.
The final feature of Feedzirra is the ability to define custom parsing classes. In truth, Feedzirra could be used to parse much more than feeds. Microformats, page scraping, and almost anything else are fair game.
Installation
For now Feedzirra exists only on github. It also has a few gem requirements that are only on github. Before you start you need to have libcurl and libxml installed. If you’re on Leopard you have both. Otherwise, you’ll need to grab them. Once you’ve got those libraries, these are the gems that get used: nokogiri, pauldix-sax-machine, taf2-curb (note that this is a fork that lives on github and not the Ruby Forge version of curb), and pauldix-feedzirra. The feedzirra gemspec has all the dependencies so you should be able to get up and running with the standard github gem install routine:
gem sources -a # if you haven't already gem install pauldix-feedzirra
NOTE:Some people have been reporting a few issues related to installation. First, the Ruby Forge version of curb is not what you want. It will not work. Nor will the curl-multi gem that lives on Ruby Forge. You have to get the taf2-curb fork installed.
If you see this error when doing a require:
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- curb_core (LoadError)
It means that the taf2-curb gem didn’t build correctly. To resolve this you can do a git clone git://github.com/taf2/curb.git then run rake gem in the curb directory, then sudo gem install pkg/curb-0.2.4.0.gem. After that you should be good.
If you see something like this when trying to run it:
NoMethodError: undefined method `on_success' for #<Curl::Easy:0x1182724> from ./lib/feedzirra/feed.rb:88:in `add_url_to_multi'
This means that you are requiring curl-multi or the Ruby Forge version of Curb somewhere. You can’t use those and need to get the taf2 version up and running.
If you’re on Debian or Ubuntu and getting errors while trying to install the taf2-curb gem, it could be because you don’t have the latest version of libcurl installed. Do this to fix:
sudo apt-get install libcurl4-gnutls-dev
Another problem could be if you are running Mac Ports and you have libcurl installed through there. You need to uninstall it for curb to work! The version in Mac Ports is old and doesn’t play nice with curb. If you’re running Leopard, you can just uninstall and you should be golden. If you’re on an older version of OS X, you’ll then need to download curl and build from source. Then you’ll have to install the taf2-curb gem again. You might have to perform the step above.
If you’re still having issues, please let me know on the mailing list. Also, Todd Fisher is working on fixing the gem install. Please send him a full error report.
Usage
A gist of the following code A gist of how to do updates on feeds
require 'feedzirra' # fetching a single feed feed = Feedzirra::Feed.fetch_and_parse("") # feed and entries accessors feed.title # => "Paul Dix Explains Nothing" feed.url # => "" feed.feed_url # => "" feed.etag # => "GunxqnEP4NeYhrqq9TyVKTuDnh0" feed.last_modified # => Sat Jan 31 17:58:16 -0500 2009 # it's a Time object entry = feed.entries.first entry.title # => "Ruby Http Client Library Performance" entry.url # => "" entry. # => "Paul Dix" entry.summary # => "..." entry.content # => "..." entry.published # => Thu Jan 29 17:00:19 UTC 2009 # it's a Time object entry.categories # => ["...", "..."] # sanitizing an entry's content entry.title.sanitize # => returns the title with harmful stuff escaped entry..sanitize # => returns the author with harmful stuff escaped entry.content.sanitize # => returns the content with harmful stuff escaped entry.content.sanitize! # => returns content with harmful stuff escaped and replaces original (also exists for author and title) entry.sanitize! # => sanitizes the entry's title, author, and content in place (as in, it changes the value to clean versions) feed.sanitize_entries! # => sanitizes all entries in place # updating a single feed updated_feed = Feedzirra::Feed.update(feed) # an updated feed has the following extra accessors updated_feed.updated? # returns true if any of the feed attributes have been modified. will return false if only new entries updated_feed.new_entries # a collection of the entry objects that are newer than the latest in the feed before update # fetching multiple feeds feed_urls = ["", ""] feeds = Feedzirra::Feed.fetch_and_parse(feed_urls) # feeds is now a hash with the feed_urls as keys and the parsed feed objects as values. If an error was thrown # there will be a Fixnum of the http response code instead of a feed object # updating multiple feeds. it expects a collection of feed objects updated_feeds = Feedzirra::Feed.update(feeds.values) # defining custom behavior on failure or success. note that a return status of 304 (not updated) will call the on_success handler feed = Feedzirra::Feed.fetch_and_parse("", :on_success => lambda {|feed| puts feed.title }, :on_failure => lambda {|url, response_code, response_header, response_body| puts response_body }) # if a collection was passed into fetch_and_parse, the handlers will be called for each one # the behavior for the handlers when using Feedzirra::Feed.update is slightly different. The feed passed into on_success will be # the updated feed with the standard updated accessors. on failure it will be the original feed object passed into update # You can add custom parsing to the feed entry classes. Say you want the wfw:comments fields in an entry Feedzirra::Feed.add_common_feed_entry_element("wfw:commentRss", :as => :comment_rss) # The arguments are the same as the SAXMachine arguments for the element method. For more example usage look at the RSSEntry and # AtomEntry classes. Now you can access those in an atom feed: Feedzirra::Feed.parse(some_atom_xml).entries.first.comment_rss_ # => wfw:commentRss is now parsed! # You can also define your own parsers and add them to the ones Feedzirra knows about. Here's an example that adds # ITunesRSS parsing. It's included in the library, but not part of Feedzirra by default because some of the field names # differ from other classes, thus breaking normalization. Feedzirra::Feed.add_feed_class(ITunesRSS) # now all feeds will be checked to see if they match ITunesRSS before others # You can also access http basic auth feeds. Unfortunately, you can't get to these inside of a bulk get of a bunch of feeds. # You'll have to do it on its own like so: Feedzirra::Feed.fetch_and_parse(some_url, :http_authentication => ["myusername", "mypassword"]) # Defining custom parsers # TODO: the functionality is here, just write some good examples that show how to do this
Benchmarks
One of the goals of Feedzirra is speed. This includes not only parsing, but fetching multiple feeds as quickly as possible. I ran a benchmark getting 20 feeds 10 times using Feedzirra, rFeedParser, and FeedNormalizer. For more details the benchmark code can be found in the project in spec/benchmarks/feedzirra_benchmarks.rb
feedzirra 5.170000 1.290000 6.460000 ( 18.917796) rfeedparser 104.260000 12.220000 116.480000 (244.799063) feed-normalizer 66.250000 4.010000 70.260000 (191.589862)
The result of that benchmark is a bit sketchy because of the network variability. Running 10 times against the same 20 feeds was meant to smooth some of that out. However, there is also a benchmark comparing parsing speed in spec/benchmarks/parsing_benchmark.rb on an atom feed.
feedzirra 0.500000 0.030000 0.530000 ( 0.658744) rfeedparser 8.400000 1.110000 9.510000 ( 11.839827) feed-normalizer 5.980000 0.160000 6.140000 ( 7.576140)
There’s also a benchmark that shows the results of using Feedzirra to perform updates on feeds you’ve already pulled in. I tested against 179 feeds. The first is the initial pull and the second is an update 65 seconds later. I’m not sure how many of them support etag and last-modified, so performance may be better or worse depending on what feeds you’re requesting.
feedzirra fetch and parse 4.010000 0.710000 4.720000 ( 15.110101) feedzirra update 0.660000 0.280000 0.940000 ( 5.152709)
Next Steps
This thing needs to hammer on many different feeds in the wild. I’m sure there will be bugs. I want to find them and crush them. I didn’t bother using the test suite for feedparser. i wanted to start fresh.
Here are some more specific TODOs.
- Fix the iTunes parser so things are normalized again
- Fix the Zlib deflate error
- Fix this error:
- Convert to use Typhoeus instead of taf2-curb
- Make the entries parse all link fields
- Make a feedzirra-rails gem to integrate feedzirra seamlessly with Rails and ActiveRecord.
- Create a super sweet DSL for defining new parsers.
- Test against Ruby 1.9.1 and fix any bugs.
- Clean up the fetching code inside feed.rb so it doesn’t suck so hard.
- Readdress how feeds determine if they can parse a document. Maybe I should use namespaces instead?
LICENSE
(The MIT License).
|
http://www.rubydoc.info/gems/orend-feedzirra/frames
|
CC-MAIN-2017-13
|
refinedweb
| 1,714
| 66.84
|
Introduction to Kotlin takeIf
Kotlin takeif is one of the default functions that can be used to filtering the data for a single object. it will return null if the specified condition is not satisfied so that it can be named as the safe call or null check it is called like ‘T’ or other predefined objects itself called directly to the takeif. so the specified object as the parameter arguments takeif() called any non-null object that takes some predicate as the argument. if the predicate condition is satisfied then the subject is returned otherwise the null value is returned.
Syntax:
In kotlin language has many default classes, methods, and keywords used to implement the mobile-based application. Like that takeif() is one of the default methods and it is mainly used to filterate the data. It has its own syntax below.
fun functionName(parameters) { val varaiableName:datatype? = kotlinNullable.takeIf(predicate) -----some logic codes--- }
The above codes are the basic syntax for using the teakeIf() method in the kotlin codes. It can be called upon the parameter values and their methods based on the predicate conditions. If the condition is satisfied it continues else it returns the null value.
How takeIf work in Kotlin?
In kotlin language, it has many defaults and standard libraries contain the functions like takeIf, and these functions are let you combined and the value is embedded with checks of the object state and its status. The object state infrequent call chains the called objects with the predicate condition provided and takeIf it returns the object if it is matched with the specified conditions. Else it will return the null values so that the takeIf() method as the filtering function for every single object. If returns the object and if it does not match the predicate condition the null value if it is does also the object is to be called and available as the lambda argument(it). While chaining other functions like after takeIf and other default functions like takeUnless is also to be performed with the null checks conditions and the safe call like ‘?.’ Operator because the return value is null. The takeIf() function is specially used together with the scope functions so that the chaining link is checked with them for running the code blocks on the specified object that can be matched with the given predicate conditions. We can do this and call the takeIf() method it returns the null and other local variable types like ‘var’ and ‘let’ are not be invoked.
Example #1
abstract class Fans(fans:String){ abstract var fansname: String abstract fun fandetails() init { println("Fans fansname is: $fansname") } fun demo(){ println("Thank you the Fans fansname is") } } interface Crompton{ var vars: String fun demo1():String fun details2() { println("Have a Nice day users") } } class Havelles : Crompton { override var vars: String = "Welcome To My Domain its the first example taht related to the kotlin takeIf() method" override fun demo1() = "Thank you for choosing the Havelles fan" } class Bajaj(fans:String): Fans(fans) { override var fansname: String = "Thank you for choosing the Bajaj fan" override fun fandetails() { println("Thank you users your Fan name is $fansname") } } sealed class Usha { class demo : Usha() { fun show() { println("Welcome To My Domain its a Usha example regarding kotlin sealed class combined with the takeIf() method") } } class demo1 : Usha() { fun show() { println("Its a child sealed class so it cant change and its a fixed thing") } } } fun main() { fun firstExample(strinp1: String, strinp2: String) { strinp1.indexOf(strinp2).takeIf { it >= 0 }?.let { println("The substring $strinp2 is found in $strinp1.") println("Its start position is $it.") } } firstExample("010000011", "1") firstExample("110000011", "2") firstExample("011000011", "3") firstExample("110000011", "4") val eg = Usha.demo1() eg.show() val eg1 = Usha.demo() eg1.show() val m2 = Bajaj("June Month") println("Your curent Fans is : ${m2.fansname}") m2.fandetails() val j = Havelles() println("Your latest Fans is = ${j.vars}") print("Keep on spent your valuable time time with our application: ") j.details2() print("Nice day users please try again ") println(j.demo1()) }
Output:
The above example is the basic example we used for the takeif() method in kotlin classes.
Example #2
import kotlin.random.* enum class TV(val exam: Boolean = true){ Samsung, Sony, Onida, Philips, Vu, Airtec, Airtel; companion object{ fun TVDetails(obj: TV): Boolean { return obj.name.compareTo("Sony") == 0 || obj.name.compareTo("Vu") == 0 } } } fun details(tv: TV) { when(tv) { TV.Samsung -> println("Samsung") TV.Sony->println("Sony") TV.Onida ->println("Onida") TV.Philips ->println("Philips") TV.Vu -> println("Vu") TV.Airtec -> println("Airtec") TV.Airtel ->println("Airtel") } } fun main() { val num = Random.nextInt(5) val evn = num.takeIf { it % 2 == 0 } val odd = num.takeUnless { it % 2 == 0 } println("The given number is even: $evn") println("The given number is odd: $odd") val i=2 var flag=false while(i<=num/2){ val prm=num.takeIf{it % i == 0} flag=true break ++i } if(!flag) { println("The given number is prime number") } else { println("The given number is not prime") } println("Welcome to my domain its a second example regarding the kotlin takeif() function") val out = mapOf(123 to "Samsung", 345 to "Sony", 678 to "Onida",901 to "Philips",213 to "Vu",141 to "Airtec",516 to "Airtel") println(out) println("Thank you users have a nice day please keep and spent time with our application") }
Output:
Here, we used enum, companion classes with the takeif() method for users to calculate the prime and odd, seven numbers.
Example #3
fun main() { fun ThirdExample(num1: Int, str2: String) { num1.takeIf{it >= 0 }?.let { println("Welcome User Integer is the first input and string type is the second input.") println("$it.") } } val colmap = HashMap<String, String>() colmap["Model Name"] = "Lenovo" colmap["Model Price"] = "8000" colmap["Model ID"] = "1456" for ((k, v) in colmap) { println("Thank you users your inputs are $k = $v") } val news = mapOf("Model Name" to "HP", "Model Price" to 8032, "Model ID" to 1678) println("Your input Keys are:" + news.keys) println("Your input Values are:" + news.values) println("Thank you users have a nice day please keep and spent time with our application") ThirdExample(13, "Siva") ThirdExample(14, "Raman") }
Output:
In the final example, we used the collection class additionally with the takeif() class.
Conclusion
In kotlin language has many default methods for implementing the application logic and its operations which is needed on the user requirement. The takeif() method is one of the built-in methods for validating the condition like if to execute the chain-link condition if the condition is true it returns the object else it returns a null value.
Recommended Articles
This is a guide to Kotlin takeIf. Here we discuss the Introduction, syntax, How takeIf works in Kotlin?, examples with code implementation. You may also have a look at the following articles to learn more –
|
https://www.educba.com/kotlin-takeif/?source=leftnav
|
CC-MAIN-2022-40
|
refinedweb
| 1,138
| 61.77
|
Sometimes, while doing programming, we need to go through some audio processing stuff. Some of the most used audio processing tasks in programming include – loading and saving audio files, splitting and appending the audio files into segments, creating mix audio files using different data, manipulating the levels of sound, applying some filters, and generating audio tuning and maybe more.
All of these kinds of stuff can be achieved with Python. Python is a flexible language; it provides libraries for almost every task you have ever heard of. For Audio Processing, Python provides Pydub, which is a very simple, and well-designed module.
Installing Pydub
Just like all other modules in Python Pydub also can be easily installed by using a simple command – pip install pydub.
Also Read: 10 Machine Learning Projects to Boost your Portfolio.
Audio Processing: Loading and Playing
AudioSegment is the parent class in Pydub. It plays the role of a container that can load, manipulate, and save audio files. Let’s create our first audio with python. For this, we will need a test file, which could be in any format like WAV, MP3, or anyone. In this article, I will download an audio file just like we scrape data from the web:
Code language: Python (python)Code language: Python (python)
import urllib.request from pydub import AudioSegment from pydub.playback import play # Download an audio file urllib.request.urlretrieve("", "metallic-drums.wav") # Load into PyDub loop = AudioSegment.from_wav("metallic-drums.wav") # Play the result play(loop)
Basic Audio Processing
As we have loaded our audio, now we can perform various types of audio processing, let’s start from some necessary steps by repeating an audio file:
Code language: Python (python)Code language: Python (python)
# Repeat 2 times loop2 = loop * 2 # Get length in milliseconds length = len(loop2) # Set fade time fade_time = int(length * 0.5) # Fade in and out faded = loop2.fade_in(fade_time).fade_out(fade_time)
Layering Audio
Above we simply repeated the audio, now let’s layer and mix different audio segments with different levels of manipulation:
Code language: Python (python)Code language: Python (python)
# Download another loop urllib.request.urlretrieve("", "beat.wav") # Load into PyDub beat = AudioSegment.from_wav("beat.wav") # Mix with our original loop mixed = beat[:length].overlay(loop2)
Audio Processing: Applying Filters
Now, let’s move further with bringing everything together by applying filters and reversing audio effects:
Code language: Python (python)Code language: Python (python)
# Filter the beat at 3kHz filtered = beat.low_pass_filter(3000) # Mix loop2 with a reversed, panned version loop = loop2.reverse().pan(-0.5).overlay(loop2.pan(0.5)) # Mix our filtered beat with the new loop at -3dB final = filtered.overlay(loop2 - 3, loop=True)
Now if you want to save your audio file, you can easily do it as below:
Code language: Python (python)Code language: Python (python)
final.export("final.mp3", format="mp3")
Synthesizing Tunes
Apart from all the steps of manipulating the sound we have covered above, we can also synthesize new tones. These tones can be sine, square, manipulating waves at any frequency. We can also perform white noise. In the example below, I will show the sine method to produce sine tuning for the initial 15 intervals in a harmonic way:
Code language: Python (python)Code language: Python (python)
# Create an empty AudioSegment result = AudioSegment.silent(duration=0) # Loop over 0-14 for n in range(15): # Generate a sine tone with frequency 200 * n gen = Sine(200 * n) # AudioSegment with duration 200ms, gain -3 sine = gen.to_audio_segment(duration=200).apply_gain(-3) # Fade in / out sine = sine.fade_in(50).fade_out(100) # Append the sine to our result result += sine # Play the result play(result)
Also Read: Face Landmarks Detection with Deep Learning.
I hope you liked this article on Audio Processing with Python. Feel free to ask your valuable questions in the comments section below.
|
https://thecleverprogrammer.com/2020/07/22/audio-processing-with-python/
|
CC-MAIN-2021-43
|
refinedweb
| 642
| 53.92
|
I have a shapefile where I have polylines and their fields are:
- length
- area into which they fall in
Now I need 3 longest lines from each area. I have 3 areas and 50 polylines, so I should get 3*3=9 records as a result. What I try to do is:
import arcpy myFile = somePath sql = ('TOP 3', 'ORDER BY "length" DESC GROUP BY "area_id" ') cursor = arcpy.da.SearchCursor(myFile , "*", None, None, False, sql) with cursor: for r in cursor: print r
I get all of 50 records here. The same happens when I set `sql` to just `('TOP 1', None) or anything else.
Is the syntax wrong here?
Solved! Go to Solution.
Since you don't know the specific glac_id, it might work to read the data from a SearchCursor into an array or dictionary and process the results from there. Untested code:
sourceFC = r"C:\Users\adam\Desktop\testarcpy\cont_int.shp" sourceFieldsList = ["glac_id", "length"] # Use list comprehension to build a dictionary from a da SearchCursor valueDict = {r[0]:(r[1:]) for r in arcpy.da.SearchCursor(sourceFC, sourceFieldsList)} for k, v in valueDict.items(): print k, max(v)
Are you using a file geodatabase? Or an SQL server? Some commands do not work with a file geodatabases.
TOP is only supported by SQL Server and MS Access databases.
See: SearchCursor
Thanks. I am iterating over a simple shapefile, and if I stop using TOP and change clause to eg. `sql = (None, 'ORDER BY "length" ')`, I still get every record.
Perhaps something like (to get only first row):
OID = arcpy.da.SearchCursor(myFile, ["OBJECTID","length"], where_clause = "area_id = 'some_code'", sql_clause = (None, 'ORDER BY length DESC') ).next()[0] # use [0] to return just OBJECTID, remove for tuple
As rvburton points out, TOP is not supported with shape files. The expression, ORDER BY "length", won't limit the number of records returned, it just sorts them. If TOP isn't supported and ORDER BY only sorts records, it is expected the cursor will return all of the records. That said, you can use Python to grab the first three records, representing the longest three lengths by area, or are you wanting/hoping for an SQL only solution?
Thanks Joshua Bixby and Randy Burton, I know how TOP and ORDER BY should work, but the point here is that none of example queries in `sql_clause` work, I couldn't get any ORDER BY or GROUP BY to work, or anything else. This is the code I tried right now:
import arcpy arcpy.env.overwriteOutput=True testVector = r"C:\Users\adam\Desktop\testarcpy\cont_int.shp" fields = ["glac_id", "length"] sql = (None, 'ORDER BY length DESC') # One method (get ordered list) with arcpy.da.SearchCursor(testVector, fields, None, None, False, sql) as cursor: for r in cursor: print r # Other method (just give me longest one) OID = arcpy.da.SearchCursor(testVector, fields, sql_clause = sql).next() print OID
With above I always get unsorted values from the table. Even if 'length' was a string (which is not, it's a float), it is not ordered in any way, I get rows in the same order as they are in attribute table in ArcMap. There are no duplicate columns in the file obviously, no Nulls, nothing special really. I also tried ordering by SHAPE@LENGTH with no luck (same result again). Path to file is correct (I've just triple-checked it), column names are fine.
I also tried with a test WHERE clause: 'length > 100.0' with no luck again. Very same results.
I hoped this was a simple syntax error I just couldn't spot, but it looks like a bigger issue now.
In your original question, you were wanting to "group by" area_id. My thoughts were to use the 3 area_id values to feed the where_clause in 3 SearchCursors. You would use only the first row of each search.
This is correct and it would be the next step I did, but I cannot even get to this point, because ArcPy doesn't honour any ORDER BY clause. What more, trying to put `'glac_id = "G012039E78878N"'` as `WHERE` clause doesn't modify results at all either.
Try this for the where clause (double quotes around entire where clause, single quotes only around the id code):
where_clause = "glac_id = 'G012039E78878N'",
This one works! Partly though. I can get correct result if I specify where_clause for a given area, but not a general highest result. When I don't know exact area IDs, this method will be hard to use. Without specifying WHERE, the sql_clause does not give any effect.
|
https://community.esri.com/t5/python-questions/why-sql-clause-is-not-respected-in-da-searchcursor/td-p/320879
|
CC-MAIN-2022-21
|
refinedweb
| 762
| 73.47
|
This post provides a brief introduction to Switchyard, what it is, and how to use it to build a service-oriented application.
This post also provides a hands-on introduction to the new SwitchYard graphical editor. We’ll build an application from scratch, but our focus will be on the tools that SwitchYard provides you, and not on the business logic of our application.
(Please note, that this post was written with the "nightly" build of Switchyard 0.5 in June 2012. The eclipse based tooling introduced in this post will be released in version 0.5 of SwitchYard.)
The post is divided into 10 sections. Let’s get started in the first section with a question, actually a few questions.
Section 1: Starting with a few Questions
Just what is Switchyard? Is it another Enterprise Service Bus (ESB)? How can I use it? Better yet, why do I want to use it? And, did I mention that I’m in a hurry? Don’t waste my time - I’ll give you 15 minutes to get me the answers.
The top level page at defines SwitchYard as:
‘...a lightweight service delivery framework providing full life-cycle support for developing, deploying, and managing service-oriented applications...’
Hang on for a minute! That’s a pretty heavyweight sentence for a lightweight framework. Let’s dissect that sentence into smaller bites to see if we can better understand SwitchYard:
- Service-oriented applications - OK, we’re talking about Service Oriented Architecture or “SOA.” In this type of architecture, we want to design our applications around performing discrete services. Each service performs one or more functions. The services, which can be local or remote, communicate by delivering messages between each other and to and from external applications. But, SOA has been around for a while and it is supported by several large frameworks and products. What makes SwitchYard so different?
- Lightweight service delivery framework - How lightweight is it? For other frameworks, your main task can be redesigning (shoehorning?) your application to fit the form that the framework needs. In other words, the most important element is where your service runs. SwitchYard is different and lightweight in that it enables you to better focus on the task that you want your service to performed. SwitchYard achieves this through its modular design - instead of “plugging” your service into a standardized “plug” in the whole framework, SwitchYard enables you to embed only those pieces (services) of the Swithyard framework that your service needs. It’s like a cafeteria, you pick only what you want.
- Providing full life-cycle support - Let’s take each of these next three subjects separately:
- Developing - What kind of support do you need when you are developing an application? Well, you will want to work in an IDE such as eclipse, so some wizards to create new projects and services would be nice, but what else? How about tooling to help you to create new projects and automatically set up all the framework services (for example, CDI/Bean Services, BPM Services, Rules Services, or Camel Services) that your application needs? SwitchYard uses JBoss Forge () to do this. We’ll walk through an example later in this post.
- Deploying - Applications really don’t do very much until you get them onto a server where they be run. SwitchYard applications can be hot-deployed and the SwitchYard eclipse tooling supports deploying your applications to your servers, and starting, stopping and managing those servers. And, SwitchYard full supports the new JBoss AS7 server.
- Managing - Once you have your application deployed, you have to be able to keep an eye on and keep it out of trouble. SwitchYard includes a new web-based management console for you to manage applications, services, and the server itself.
Section 2: What About JBoss ESB?
So far so good, but if we’re talking about a JBoss framework for SOA, aren’t we talking about JBossESB? Does SwitchYard mean that JBossESB is dead?
No, JBossESB is not dead. JBossESB is alive and well. A new update (version 4.11) scheduled for this week. The community is growing and as vibrant as ever. There’s even a beautifully written new Beginner’s Guide (). (Full disclosure, I’m one of the books authors.)
Well, if JBossESB is not going away, If I want to build a new SOA application starting today, should I use ESB or SwitchYard?
The answer to this question is, “it depends.”
At this point in time, SwitchYard is very much a work in progress. It’s design and implementation are evolving and will evolve significantly in the future months as it grows toward its 1.0 release. JBoss ESB is more mature, and is undergoing primarily incremental changes and improvements.
So, if you are building an SOA application that you want to go into production in the near future, you should look at JBoss ESB. Actually, if you need enterprise level support, you should really buy a subscription for the JBoss SOA Platform (), which has at its core JBoss ESB.
For the longer term future, you should look at some of the ways in which SwitchYard will make some aspects of SOA application development easier.
Section 3: Making Your SOA Life Easier with SwitchYard
The primary ways in which SwitchYard differs from a traditional ESB highlight some of the ways in which SwitchYard can make SOA application services development easier:
- Install only the Services that you Need - One drawback of a traditional ESB is that while you may only want to use some services provided by the ESB (for example, data transformation), you have to deploy the ESB’s entire framework, including services that you don’t need. The result is a larger installation footprint (both memory and disk usage) that would be necessary if you could use only the ESB services that you require. In contrast, SwitchYard enables you to configure and then utilitze only those services that you want.
- Run your Services Anywhere you Want - Another aspect of a traditional ESB is just where it enables you to run your services. With an ESB, you deploy your services into the ESB. Part of the logical visualization of an ESB mirrors that of a hardware bus in that you “plug” your services into the bus. Your services communicate via messages sent over the bus. The messages sent over the bus are said to be “ESB-aware” in that they conform to the message format required by the ESB. Messages are “on-boarded” from external sources to the ESB through adapters that translate the message formats into ESB-aware messages. In contrast, SwitchYard lets you run your services in your own application, inside unit tests, or deployed to your own application server.
- Focus on Writing your Services’ Code, Not the Code to get your Services to Run - One of the most helpful features of JBossESB is the extensive library of predefined actions that it provides. These “out of the box” (OOTB) (see:) actions perform tasks such as message routing, business process management integrations, integrations with scripting languages, and others. One advantage that using these OOTB actions should appeal to your interests in building reliable services. If you had to construct your services only using new new code that you create, you would have to debug and test that code thoroughly. The OOTB actions have already been thoroughly tested and documented by the JBossESB community, so you can use them with confidence. Another advantage should appeal to your lazy programmer interests. By using the OOTB actions, you can build reliable services without having to write that much new code. This model, however, reaches its limits with some operations such as message transformation. With JBoss ESB, the transformation of data fro one form to another is a procedural operation. SwitchYard, however, supports declarative transformation, where all you have to do is to define the transformation and the types to which you want it performed, and Swithyard does the rest.
- Compose your Services with CDI - With traditional ESBs, you have to adapt your service design to fit the form that the ESB wants. In contrast, SwitchYard uses Context Dependency Injection (CDI) provided by the JBoss Weld () project to enable you to easily create services from Java beans through annotations. You can convert a bean to a service just by adding the @Service annotation. When it sees this annotation, SwitchYard registers them as services at runtime. Within a service, references to other services can be injected as other CDI beans with the @Inject annotation.
- Take Advantage of Integrations - One of the great strengths of JBossESB is its rich set of integrations with other technologies such as jBPM () for business process orchestration. SwitchYard carries on that tradition and expands JBossESB’s integration with Apache Camel (). With Camel, SwitchYard enables you to use Camel components () as gateways to integrate applications and services with your services.
- Forge Ahead, with Forge - Sometimes the hardest thing to do is to start a new project. Copying an existing example is a common route, but you end up having to edit files to match your new application and services. SwitchYard ships with built-in Forge () plugins to help you to build Maven () based applications easily.
- Testing, and Not as an Afterthought - As a QE engineer, it can sometimes seem like testing is never a primary concern when a new technology is introduced. (Or maybe it’s just that when you spend your days finding bugs, you develop a certain form of paranoia. ;-) SwitchYard includes unit test support out of the box, so you can build tests for your services while you build the services.
Section 4: Visualizing SwitchYard?
It’s easy to visualize an ESB. You just think of a bus with services “plugged” into it. But what about SwitchYard. What does SwitchYard “look like?”
An ESB, and in this context, SwitchYard is an ESB, is really a means to an end. It’s a tool for creating service-oriented applications. To create a service-oriented application you look inward at your application architecture, not outward at the runtime architecture of the bus. Your concern and your focus in on the application that you’re building and not on the runtime and tooling. SwitchYard is the tooling and runtime for your service-oriented applications.
It’s a little more difficult to draw a picture of SwitchYard, as one of its main goals is to enable you to focus on what your application looks like!
The contents of a SwitchYard project however do have a different configuration than JBoss ESB project. We’ll take a look at these differences next.
Section 5: Anatomy of a SwitchYard Project Configuration
Unlike traditional ESBs, the configuration requirements imposed by SwitchYard are minimal. Let’s use JBossESB as reference point. A service-based application deployed to JBossESB requires configuration files to define the JMS topics and queues on which it depends. It also requires a “jboss-esb.xml” file to define the resource providers (such as JMS) on which the services depend, the services themselves, the gateways through which messages are “on-boarded” to the ESB and the notifiers through which messages are sent off of the ESB, and the “pipeline” of actions that perform the tasks that comprise the services. Creating and maintaining a jboss-esb.xml file for a services-based application can be a difficult and time-consuming task.
A SwitchYard application has two primary configuration files:
- beans.xml - This file simply indicates that an application is making use of Context Dependency Injection (CDI).
- switchyard.xml - This file defines the service implementations, gateways, transformations, validations, and deployment dependencies.
At first glace, this may seem like a trivial change from jboss-esb.xml to switchyard.xml. What’s the big deal, only the file name changed, right?
The major difference is that the elements defined in switchyard.xml conform to the OASIS Service Component Architecture Assembly Model Specification (). The Service Component Architecture (SCA) model provides standards for building SOA applications.
Why was this standard selected as the lingua franca of SwitchYard configuration? What advantages does using this standard give us? There are multiple levels of advantages:
- SwitchYard wanted to get away from the model followed by jboss-esb.xml where the service implementation details are closely tied up with the gateway definition details. We're trying for a more modular approach that makes it easier to define and maintain a service's configuration. A switchyard.xml can contain binding info in the same file as the service implementation, but SCA also supports recursive composition, so that one service with just implementation details, can be included inside another. This level of modularization is not possible in JBoss-ESB.xml. We’ll take a look at the SCA files and pictures that Swithyard tooling makes easy to create and maintain.
- SwitchYard also wanted to make service interface (or the service "contract") information more explicit, and therefore easier to find. JBossESB does this to some extent with EBWS (ESB enhanced Web Services).
- Finally, the SwitchYard team had a choice. They could create a new configuration syntax, or they could try to use something that already existed, was an accepted open standard, and was supported by a vibrant community. Not A tough choice. ;-) Also, SCA is a well-known model for service-oriented applications. But, it's important to not get too hung-up over the underlying configuration model. The capabilities that the model makes possible, such as modularity, are more important. And, another reason to not worry too much about the configuration model is that SwitchYard provides you with tools such as Forge scripting (and someday soon a SCA editor) to make it easier to create and maintain services' configurations.
It’s also important (as we’re all lazy programmers who want to avoid error-prone manual tasks, after all) that SwitchYard provides tools to automatically populate the contents of switchyard.xml. We’ll see these tools in action in a bit.
Section 6: Services
When we talk about SwitchYard services, we're concerned with how we can create a service, and then how that service can be used (or "consumed") by other services.
How exactly do you create a SwitchYard service? Watch closely because SwitchYard makes this simple:
- You start with a Java POJO (plain old Java object) and add a “@Service” annotation.
- The you create a Java interface representing the “contract” (in other words, the signatures of the methods used to interact with the with that object)
- Then you create a Java class implementing the interface
And that’s all folks. You’ve got a service. Yeah, SwitchYard tries to keep this simple.
Here’s an example (thanks to Keith Babo - as I’m borrowing this code from his demo):
1) Start with a POJO:
public interface OrderService {
OrderAck submitOrder(Order order);
}
2) Create an interface:
public class OrderServiceBean implements OrderService {
public OrderAck submitOrder(Order order) {
...
}
}
3) Annotate the POJO - and it’s a service!
@Service(OrderService.class)
public class OrderServiceBean implements OrderService {
public OrderAck submitOrder(Order order) {
...
}
}
Once you have a service, how do you access/consume it? Through Context Dependency Injection (CDI) in three more steps:
(1) Add an @Reference and @Inject annotation
(2) Add a field representing the consumed service
(3) Invoke methods on the injected reference
@Service(OrderService.class)
public class OrderServiceBean implements OrderService {
@Inject @Reference (1)
private InventoryService inventory; (2)
public OrderAck submitOrder(Order order) {
Item orderItem = inventory.lookupItem(order.getItemId()); (3)
…
}}
What types of services does Switchard support?
- Bean Services - Such as the example we just mentioned.
- BPM Services - Where bean services can be invoked from a BPMN2 process.
- BPEL Services - Where you can access WS-BPEL business processa exposed as services through their WSDL inteface.
- Camel Services - Camel enables you to integrate systems together, even if they each a speak a different API. Camel provides a flexible message routing and mediation engine (in this context, “mediation” refers to the processing of messages, for example examining or modify message contents on the fly). Camel supports a large set of “components” () that enable you to tie together technologies such as EJBs, with transports such as http or ftp, messaging, and many others. SwitchYard uses Camel as a Swiss Army knife sort of framework to perform many tasks by re-using Camel components, instead of having to write the integration code yourself.
At this point, let’s switch into to a hands on mode and perform some tasks with SwitchYard.
Section 8: Getting SwitchYard
When I first started working with JBoss software, I asked a co-worker, how do I perform an installation? His response was a blank stare for a few seconds, after which he said, “You download the .zip and unzip it.”
It might sound trivial, or obvious, but the ease, and low entry cost (you can’t get cheaper than free!) with which you can get started using JBoss projects is a great feature. You can download whatever projects you want and try them out at no cost.
To get a copy of SwitchYard, the steps you have to do are:
Go to this page: - you’ll see a display similar to this:
Your download choices are:
- SwitchYard Tools - These are Eclipse plugins that support operations for working with SwitchYard projects. We’ll talk about how to install and use these plugins in a later section of this post.
- SwitchYard Source Distribution - Like the name says, download gets you all source code for SwitchYard.
- SwitchYard Installer - This distribution contains all the bits you need to deploy SwitchYard to a JBoss AS7 server. But, since we’re in a hurry, we’ll use the next one.
- SwitchYard AS7 Distribution - This distribution is the easiest to use as it includes SwitchYard deployed to a full JBoss AS7 server distribution. All we have to do to use this distribution is to download it and unzip it.
For the purposes of this impatient discussion, we’ll use the SwitchYard AS7 Distribution.
Section 9: Running SwitchYard and the JBoss AS7 Server
The JBoss AS7 () server is JBoss’ newest application server release. AS7 is compliant with the Java Enterprise Edition 6 specification, and is the preferred deployment platform for SwitchYard.
(Note that by the time you read this, SwitchYard 0.5 will probably be available as a download.)
To install the SwitchYard AS7 Distribution, simply select a directory where you want to run the server, and unzip the file into that directory.
In this post, we’ll use the /opt/SwitchYard directory:
mkdir /opt/SwitchYard
cd /opt/SwitchYard
unzip switchyard-as7-0.4.0.Final.zip
Let’s jump right in and start up the server:
cd switchyard-as7-0.4.0.Final/bin
sh ./standalone.sh
After a very short time (Did I mention how fast JBoss AS7 is? It starts up and runs very quickly!), you’ll see logging messages that look like this that indicate the server is up and running:
23:05:13,608 INFO [org.apache.coyote.http11.Http11Protocol] (MSC service thread 1-3) Starting Coyote HTTP/1.1 on http--127.0.0.1-8080
23:05:13,718 INFO [org.jboss.as.connector] (MSC service thread 1-5) Starting JCA Subsystem (JBoss IronJacamar 1.0.3.Final)
23:05:13,775 INFO [org.jboss.as.connector.subsystems.datasources] (MSC service thread 1-7) Bound data source [java:jboss/datasources/ExampleDS]
23:05:14,173 INFO [org.jboss.as.deployment] (MSC service thread 1-2) Started FileSystemDeploymentService for directory /opt/local/SwitchYard/SwitchYard-as7-0.3/standalone/deployments
23:05:14,192 INFO [org.jboss.as] (Controller Boot Thread) JBoss AS 7.0.2.Final "Arc" started in 2137ms - Started 97 of 152 services (55 services are passive or on-demand)
Section 10: Creating a New SwitchYard Project From Scratch
Now that we have SwitchYard running, let’s create a new project. We’ll do this the easy way and take advantage of some new JBoss eclipse-based tooling, the SwitchYard Graphical Editor. Note that as of this writing, the editor has not been released. It will be released in SwitchYard 0.5
First, we need to install a few things:
- Eclipse - We’re using version 3.7 (Indigo) in this paper. You can get your free copy here:
- JBoss Tools - JBoss Tools () is a great collection of development tools, all packaged and tested together. We’ll want to install JBoss Tools to get JBoss AS support tools such as a server runtime detector. The tools that we want to install are packaged as “JBoss Tools Abridged.”
- The GEF Graphical Editing Framework (). This is needed by the SwitchYard graphical editor.
- And finally, the Graphical Editor -
Once all the tools are in place, we can create a new SwitchYard project. Before we do that, however, let’s think about the application that we want to build, and the steps that we have to perform.
The application exposes a simple web service implemented in a Java bean. The service accepts a string, and prefixes the world “hello” to it. That’s right, if we pass the word “world” to the service, it returns “hello world.” We’ll access the service by sending it a SOAP message. For our “client,” we’ll use soapUI ().
The function performed by the application is not the important thing. What’s important is how you can build it with the SwitchYard tooling, especially the new SwitchYard graphical editor.
The major steps that we’ll perform are:
- Create a new SwitchYard project, configure the project with the bean and SOAP facets. We’ll need these facets to support the bean where we implement the web service and for the SOAP access to the service.
- Create a composite service
- Then create the component service, including the service interface and implementation bean.
- Connect the composite service to its component service.
- Create the SOAP binding for the service.
- Add a transformer to convert the messages from between SOAP XML to a String that the service can manipulate.
OK, let’s begin!
Note: This article was originally written in July 2012. The following sections are an update to the article using the latest release (0.7) of SwitchYard as of March 2013. The UI has changed and improved a great deal since July 2012. The screenshots that are used in the following sections reflect the current (0.7) UI.
The steps that we'll follow are:
- Create a new SwitchYard project
- Create a bean component, and in the course of doing so, create its contract (interface)
- Fill in the business logic of the bean and the details of the contract (interface)
- Promote the service so that it is visible as a web service, and in the course of doing so generate the service's WSDL, and create the necessary transformations
- Create a SOAP binding
- Deploy the service
- Invoke the service
Let's take these steps one-by-one:
Create a new SwitchYard project
To create a new SwitchYard project, select File->New->Project->SwitchYard->SwitchYard Project
We can accept most of the default settings for this project, the exception being that we have to set the bean and SOAP facets:
When the new project wizard completes, we access the new SwitchYard graphical editor by double-clicking on the SwitchYard icon in the project explorer:
And the editor is opened.
The editor consists of:
- The canvas (displayed in blue on the left of the screen) - The canvas is workspace where you create and manipulate project elements.
- The palette (displayed on the right margin) - The palette contains the elements that you can add to your project.
Create a bean component, and in the course of doing so, create its contract (interface)
To create a new bean component, select the Bean implementation icon from the palette and drag it onto the canvas. The Bean definition dialog opens:
To create the corresponding contract (interface) click on the blue "Interface:" text and this dialog opens:
After we select "Finish" to save the definition, we see the bean component on the canvas:
Fill in the business logic of the bean and the details of the contract (interface)
At this point, we need to fill in the code for the bean and its interface:
Promote the service so that it is visible as a web service, and in the course of doing so generate the service's WSDL, and create the necessary transformations
Next, we promote the service to make it visible (right-click on the service's green icon):
We want to make the service visible as a web service, so we'll select WSDL as the interface type - and the UI will generate a WSDL for us, based on the contract (interface) that we defined earlier:
Note that we selected to not use wrapped messages, so that our transformations can access only what is inside the elements they receive.
Our service has to transform data between objects and strings, so we next have to generate transformations:
Our (Java) transformers are quite simple:
We're almost done!
Create a SOAP binding
Now, we create a SOAP binding:
Note that you can always view/edit the binding after it's created by accessing its properties:
OK. It’s time for action. Let’s deploy our application:
And fire up soapUI, we can easily create a request by accessing the deployed service’s WSDL:
And there it is, the output from our very small SwitchYard service.
Section 11: What’s Next?
Well, that’s a brief (impatient) introduction to Switchyard, where to get it, how to install it, and how to build a service from the bottom up. What’s next? In a followup post, we’ll take an in-depth look at the services Switchyard provides by examining some of the SwitchYard quickstarts in detail.
There are a number of great demos of SwitchYard available at the SwitchYard video channel - check it out!
Acknowledgements
I’d like to thank Keith Babo, Tom Cunningham, Rob Cernich, and Brian Fitzpatrick for their (never impatient) review comments and suggestions on writing this post!
|
https://community.jboss.org/en/switchyard/blog/2012/06/22/an-impatient-newbie-user-s-introduction-to-switchyard
|
CC-MAIN-2015-32
|
refinedweb
| 4,333
| 62.78
|
Mohsen Agsen - C++ Today and Tomorrow
- Posted: Jun 09, 2011 at 8:00 AM
- 92,384 Views
- 63 Comments
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
The last time we got the chance to talk to Mohsen Agsen, a Microsoft Technical Fellow who runs the Visual C++ engineering team, he put forward the notion of a renaissance taking place in the native world. Shortly thereafter, we created the catchy C++ Renaissance mantra. (Mohsen is great at building metaphors in real time. See if you can identify a few new ones in this conversation!) The reception to C++ Renaissance message has been great (and, in some sense, unexpected). Now that some time has passed, let's revisit this meme and get a sense of what Mohsen really meant by a renaissance taking place in the native world, and C++ specifically. Is this renaissance taking place in the industry at large, or was Mohsen focusing on what's going on inside of Microsoft? Maybe it's both (at least from the native perspective, given Obj-C, C, and C++ usage outside of Microsoft).
Mohsen works in the Microsoft Hawaii office, located in Honolulu on the great island of Oahu. I was recently in Hawaii for the ICSE 2011 conference in Waikiki, so I was able to visit Mohsen to continue our conversation from a few months back.
It's really easy to talk to Mohsen—he's passionate, engaging, curious, and, most importantly, honest and open. There's no marketing in Mohsen. He's all engineer. When I asked him about what he thinks is needed in C++ and VC++, specifically, he answers, but he also asks YOU for your opinions on the matter -> How do you use C++ today? Are you interested in using C++ for building high-level UI-centric and data snacking apps? What do you want the VC team to focus on? Please answer these questions in this post. Mohsen and the VC product team will be looking for your answers here, so speak up! And thanks for asking, Mohsen. Very cool.
Tune in. Enjoy. (And remember to tell Mohsen what's on your mind regarding what he asks you in this conversation.)
Questions/Topics (click the link to navigate to the topic/question):
What does your team do at the Microsoft Hawaii office?
On the C++ Renaissance...
Mohsen asks you -> How are you actually using C++ today?
Mohsen asks you -> How do you think about the breadth of the language for mainstream scenarios (web services, data access, data snacking applications, etc)? Are you using C++ for these types of things? How broad should we think about the language beyond systems?
How do you allocate resources on the VC team (so, how do you determine where to place human investments)?
Do you have a sense of how many VC++ developers actually use any of the other language tools inside of Visual Studio—so, would VC be able to ship faster if it wasn't bound to VS? (Yes, a weird Charles question born in situ during the conversation!).
How you feel personally about the state of the C++ language (were you upset that Concepts didn't make it in to C++11, for example?) ?
What do you think of the language Go?
Error reporting quality, templates and exceptions...
What do you want to see added to (or what's missing today in) the C++ language/libraries/tools? (Mohsen asks you -> What existing libraries should become de facto standards like news about the Data Parallel Extensions for C++ ? I remember Stephen Toub or somebody in TC group has talked about it for several times.
a seperate release for C++ ? if its still VS and can be integrated into the full VS then OK, if its something like WebMatrix then not so good. I am a mixed-mode developer and coding many different things, my sln always has csproj and vcproj in it. the 'Windows C++' (by MJF) should always be the "Windows SDK" right ?
p.s. its a good chat but not really that 'deep' huh, should be a post instead of this show IMHO.
@felix9: Going Deep does not require a whiteboard - the focus of the "show" must always be below the surface, which could mean breaking apart the Windows kernel or breaking apart the history that's led us to where we are today with technology x and how today's decisions will lead us into the future. In my opinion, this conversation effectively accomplishes the latter with respect to native code (not just C++). That said, if you want a deeper technical foray into specific C++ subject matter, then watch Herb's latest Q&A.
We're going to continue to go very deep into the native world on C9, to be clear (whiteboards, code, etc - like STL's great lectures, but beyond the STL).
Conversations like this one with Mohsen are important to a) showcase the thought leaders who drive technical direction and b) provide you with high quality conversational content that focuses on technical subject matter. In this case, it's great to hear Mohsen's perspectives on C, JavaScript and even Go. Most of the time is spent talking about C++, of course, and there are some excellent nuggets of deep wisdom and information here.
C
PS: Please remember to answers Mohsen's questions! He wants to hear from you.!
>>IMAGE
Using it for a large Windows Application that is mixed mode. Our UI is all native and MFC based, but would like to slowly evolve into using WPF so our application could be "prettier". There was a lot of discussion about that years ago, but all I have seen is very simple examples. I know you have learned a lot when transitioning Visual Studio itself to use WPF, is there any additional wrappers to help MFC people make that transition?
Also looking to add more async in my application and would like to see more async built into the language, like in the future version of C#.
Misc: Spatial Libraries and operations in native C++. Would like to create better reports for my users and would like a framework for this. Direct2d wrappers like mentioned by previous poster.
So for me Visual C++ needs to be with Visual Studio as a whole, because my application is mixed mode and I also have other managed applications too.
Thanks for the C++ videos
I have used C++ for a business application on the server end, that just needed to handle lots of requests for lots of different clients. This talked to a database and did some mathematical calculations, plus it parsed various scripts (Python etc) from clients.
So this really wasn't a special C++ requirement type project, however I do think it had benifits from the extra control factor you have in C++ over managed languages.
I enjoy writing C++ a lot, more then .NET coding, which is where I started. :) Love to see loads more content on the C++ front. :)
Thanks for the nice video's seen so far :)
From my side, I use C++ more for (self included) learning and teaching core language/STL, parallelism and graphics (GL, DX, CL), so I still on my old post on the Goodhew interview: a minimum Visual C++ IDE with Extensions enabled (one step further Express), plus a better modularized/decoupled Windows SDK, so we don't have more (or mitigate) the crashes with handling many versions of WSDK (like the headache we had with the latest SP1 for VS+WSDK).
A simple UI with direct2D would be awesome, but if you guys improve the interoperability already existent in Ribbon would already begood.
Am I interested in using C++ for UI or data-driven apps? Why yes, I am. Am I going to start using MFC for it? No. If there was a UI library of the quality of the new PPL, then I would be one very happy bunny. Double points if it can take my Direct3D9/10/11 Device for hardware rendering.
The thing about WPF interop is that it brings what you want to interop it with into managed code. That's great- if you want to write a managed app, extended by <insert technology here>. But I'd really rather just write a native app extended by WPF, because the only UI library provided is MFC, and it's really past it's expiry date. When you go into WPF then you lose control- you don't write your own main loop, WPF tells you when to render, etc etc, which is definitely not what I'm looking for as a native developer to structure my whole application that way, because I need a UI library.
What I'd like from a UI library is, not just a new naming scheme and new interfaces (like no HRESULTs), but also control. Here, process Window messages. Now render the controls, because I rendered my 3D content and I'd like you to render on top.
In my opinion, definitely the biggest problem with the Standard is that it tries to be compatible with too many people and too many platforms, and consequently, it just doesn't have the breadth of platform-specific features that I'd like. For example, if I want an unordered_map, it's great that it's in the Standard, but really, I could have just grabbed it from Boost. I'd much rather that the Standard focused on providing facilities that aren't already generic- like directory and other filesystem support, or UI, or networking - where you'd have to re-write for every target platform. The new Standard thread support is a good example.
As for language, definitely the biggest thing I'd like to see from the language is the removal of header files. I used to write a lot of template-heavy code, and it was sweet, but eventually I just stopped because making the declaration and definition orders work was just too much hassle. Not to mention the duplication of having to write the class prototype twice, and having to keep them in-sync, and the nasty readability penalties of having the code out-of-line. I'd rather see something done to eliminate the compilation model than have Concepts, or even variadic templates and rvalue references.
The current error message system, I think, could be improved upon by judicious use of static assertion and type traits. For example, attempting to use a std::map with a non-comparable key type will give a nasty and only very vaguely readable error right now. However, it's trivial to write a static assertion that will cleanly error- actually in VC10, not just in a theoretical up-to-date perfectly compliant implementation.
Oh one thing I forgot: Definitely minus points for not being forwards compatible. Like Direct2D. Come on, guys- Direct3D 11 will still compile your Direct3D10 shaders and all the rest of it.
Firstly thanks for reaching out to the community. I hope the reach can extend out to the trenches. Do appreciate the C++ weekly.
I wouldn't view response or lack of here as any indication as to the size/strength of the C++ community. I'm not sure how many really know about this area and still the magazines are all about managed. I too miss the glory days of VC6. I hope some effort is spent to exceed the UI performance that was back then. Can't really use the IDE on a laptop on battery power due to high power consumption. I'm hopeful vNext can have C++ tooling that actually works. Have been unable to use (on x64 OS) Sampling Performance analysis on 32-bit (doesn't work). Instrumentation flat out fails (both 32/64).
To answer some questions. I use C++ is used for application development. Not simple apps, but real down to the metal powerful applications that are highly responsive and mature. CPU power is available where it's needed, namely for audio processing/synthesis and the like and not on higher level language interpretation.
Having recently coded a fun application in C++, I had ported it to Javascript to run in the browser and essentially consumed a lot more power in the process. For efficiency and performance it still needs to be C++.
Yes there are cases for web applications, etc. where using javascript/html5/etc. are efficient and quick. Yes we're seeing the trend for simple/basic things that are good on phones/tablets, It makes sense to use the appropriate language for those cases. Still someone has to code the managers in managed code or interpreted languages
Thanks for the opportunity to say this.
K
Every modern C++ library should use exceptions. I wrote an ODBC wrapper library for the company I work for now and by switching to that from various C style wrappers, we found old SQL that had never even run before due to syntax errors... It's well known that most people just don't check return values and that just confirmed it for me.
The C++ standard needs some serious library work. It's great that threads etc. got attention for C++0x, but boost::asio really needs to become a standard library as soon as possible. It's just plain embarassing that C++ doesn't have a built in networking library yet.
I strongly agree with DeadMG above regarding static_assert usage. All these kind of tricks should be used now, to make error detection easier and faster.
Thanks for the answers. Keep them coming! The VC++ team is watching this thread.
C
I would love to be able to build for Windows XP RTM, and Windows XP SP1, while not giving up the newer C++ features. That's not really language specific, I guess.
First of all, this is what we do: we are developing applications that control sophisticated, laser based, optical measurement systems that acquire 100 MBytes/s and more of data, processing it real time, storing, analyzing and visualizing it. We currently use DirectShow (for dataflow parallelism of the data acquisition), DirectX (for live video and overlay), ATL (for component based architecture), MFC, boost, OpenGL (for 3D visualization) and .NET (interop via COM).
I appreciate the work that was already done for VS 2010 like lambdas, rvalue references, the update of the STL to use move semantics, ConCRT, PPL and the agents library, debugging (parallel threads, tasks, profiler). This is great stuff! We are currently looking into using ConCRT and PPL of off-load work from the UI thread and maybe agents to replace DirectShow for the acquisition part. And we are looking into replacing the UI part written in MFC by C# WindowsForms
or WPF.
Comparing development in C# / .NET with native C++, our experience is, that productivity in C# / .NET is much higher (1.5 x to 2 x) because of tools and libraries.
What we miss most in VC++ 2010 is: code coverage, unit tests, refactoring, support for XML comments, code metrics. I know that for most of these there are third party solutions but having it all at your fingertips and fully integrated like in C# is a great benefit. I hope the rumors are right, that VS next is addressing some of these and I hope it will be available in VS professional and not only in ultimate, which is unaffordable.
The other topic, which is at least as import, is libraries. Mohsen's statement (joke?) about BCL == STL touches the core issue: STL provides great containers and algorithms that are comparable to or even better than the BCL versions. But what we need is much more. Look at code created by the MFC app or ATL simple COM object wizards and compare it to C# code (Windows Forms, COM visible objects). The C++ version is not C++ (at least not modern C++). It is cluttered by macros (MESSAGE_MAP etc.), unsafe types (WPARAM, LPARAM, BSTR, SAFEARRAY), needs a separate language (IDL) and lots of boilerplate code. In contrast the C# version is succinct, seamless and uses the CLI types (string, arrays) decorated with few attributes. Writing COM objects in C# is much more productive than doing the same with ATL / C++, set the non deterministic destruction and deployment (where to put the type library, reg-free COM) aside. The same is true when comparing Windows Forms and MFC.
To do Windows application development in VC++ we have to deal today with std::string, BSTR, _bstr_t, CComBSTR, CString, CAtlString, LPCTSTR, OLESTR, char*, wchar_t*, TCHAR*, _T(). Arrays: SAFEARRAY, CComSafeArray, built-in arrays, std::vector, raw pointers, etc. Error handling is another example: HRESULT, _com_error, IErrorInfo, GetLastError(), DWORD, BOOL, INVALID_HANDLE, exceptions, etc. Resource management: new, delete, DEBUG_NEW, ::SysFreeString, ::CoTaskMemAlloc, ::GlobalAlloc, etc.
This is insane!!!
What is desperately needed are STL / PPL / boost like libraries that use RAII for resource management, exceptions for error handling, containers that are STL compatible and that are named consistently.
You have invested lots of resources for designing the .NET framework. Why not take this investment and port parts of the framework to native C++? I am not talking about interop or wrapping it, I am talking about native C++ libraries with modern interfaces that do the same thing and use similar names for classes and types.
Top priority list would be:
Instead of the .NET reference types use C++ pImpl pattern with std::shared_ptr to the mplementing class (like task<T> of the ConCRT extras sample pack). Then we get performance, safeness and deterministic destruction for free.
Speaking of task<T>: throughout the framework use a consistent model for asynchronous method calls, like TAP for .NET. Implement a full blown task<T> type like .NET's Task<T> (the version of the ConCRT extras pack 0.4 is a step in the right direction but error handling, proper cancellation support and support for scheduling continuations on the UI thread are missing). Implement all asynchronous methods by returning task<T>.
That would be a huge productivity boost! And having that library on Windows Phone, and
Windows XP - Windows 8 would allow developers learning it once and apply it everywhere.
Sorry for the long post, but that had to be said.
Best regards,
Bernd
Couldn't agree with you more Bernd!
@Bernd: It already exists and is called Qt.
Joking aside, you are correct. It would be quite possible to create a more up to date library in modern C++ that follows .Net design, but I guess it is not in Microsoft plans.
Since I haven't not seen it, I guess someone needs to again make the issue that Microsoft is the only C and C++ compiler vendor that does not implement any C99 features.
And regarding C++ I am really happy that Microsoft has realized that C++ still drives the world and many programmers use it every day.
Still it would be nice if C++ would get the same attention as the managed languages in Visual Studio.
C + + needs a decent graphics library, which is really object oriented, unlike that monster now called MFC. To take advantage of the knowledge that many developers have Visual C + + using MFC, could be created a new version of MFC, MFC a really OO.
Visual C + + RAD also needs resources and drag and drop.
Great feedback/answers! Keep them coming!
I'm not seeing many responses to How do you think about the breadth of the language for mainstream scenarios (web services, data access, data snacking applications, etc)? Are you using C++ for these types of things? How broad should we think about the language beyond systems?
In some sense, the question can also be asked this way: Would you use C++ to build relatively simple client applications?
C
We use c++ for our very large desktop MFC app. Whilst I love the new C++ features in vs2010, the biggest issue for me is the performance of the app. It just feels really, really sluggish and is a productivity killer. Not sure if farming off VC++ would help, but I'd love to see VC++ get back to the VS6 performance.
In terms of the breadth of the language, database access still isn't as easy in C++ as it is in C#. it would be absolutely fantastic to have something like LINQ available natively (as long as it was quick)..
@Charles:Well, I give a test drive to WWS, it's nice and all but with the trouble with SP1 I rolled back the WSDK and not installed it again
Would be nice some more text about it, the examples that come along are good, but need a bit more insight on the documentation. More propaganda would help WWS widespread (like examples involving WWS and Windows Phone, sure it will be like honey for bring peoples attention
)
But for teaching, I end up using direct sockets plus simple messages, lightweight html/cgi handlers. I'm looking forward for use WWS and OData on server side and HTML5+Javascript on client side for newly courses. The boost have some nice tools to, if VS.next include some tool or help establish a mapping for C++ data serializing and xml binding well be greatly welcome.
(Of course, all implemented in modular way, for the sake of clean VS.next Standard edition, augumented only with the modules you buy/download from VS Module Market
(yeah!, like app market))
@Charles: Up until I learned about the new C++0x features, I would never consider using C++ for things like web services or data access layers (the legacy code I have had to work on, which does perform data access is horrible next to ADO.NET, for example), however, I've certainly been considering it lately. I'm not sure if it's necessary, but should you be able to? Yes.
As much as I like C++, the only situation I seem to be using it lately is where we're either on a non-Microsoft platform, or we're doing stuff that involves too much interop (and we switch to C++/CLI), or is downright impossible in .NET (debugger extensions, device drivers).
I would love to see a boost-like (read: mostly header-only) library on top of win32. Also, I wouldn't say no to a mechanism that gives me the same sort of alloc/dealloc performance as .NET (where allocation is superfast and deallocation depends on principle of locallity -- and a bunch of heuristics). IOW: I do not want to be drilling into a 7x24 service to find that it's spending near 100% on its heap due to fragmentation.
Testability (easy to use unit testing/mocking framework) would make for a good 3rd on my list, I guess.
Oh, and please, make anything you add fluent and addaptable (by (template) argument ?).
Thanks,
-- Henkk
I want the speed of VC6 back again. I've delayed our move to a new version of VC because the environment is so much slower now.
I would love to see tooling for WebServices, a native version of WCF.
@BartoszMilewski: Remember that VC10 can only be implemented to the draft Standard- as it was at least two years ago. What's likely is that that part of the Standard wasn't ready.
You know, the other thing I wanted to talk about is C. The Visual C compiler doesn't even implement C99- so why are all the new things like WWS ugly C interfaces? I mean, I get that you might want to have one because C++ interfaces like to break, or for language compatibility, but a couple of C++-only headers making it more palatable would make a big difference to me. After all, it's probably not a lot of time to wrap a single library, but when it's every native library, then it gets old fast.
I'm a university student whose major is computer science.So it is a must that we all have to learn C++.Until now,we still code with it.In my opinion,it's quite great and I some kind of like coding with it.(Freaking out!)But I didn't learn it so well so I decided to study it more in my coming summer vacation.In order to find an ideal job,I think C++ is a must.
Maybe this question is a little deep.I think computer language is just the same as foreign languages.As long as we know the grammer we can use it.All we need to do is practice again and again.And after that we can grab its soul and make full use of it.
We have two major engineering/science-oriented applications that we deliver to our clients. Complicated custom ui-elements, 2D graphics (printing etc), 3D graphics. We use(d) win32 - Api and MFC. And let me tell you it has not been a childs play. Lot of pain because of insufficient documentation and trying to hack away the anomalies. We've been satisfied with MS ides though, for example Fortran-compilers and other 3'rd party tools integrate smoothly.
So C++ ui - creation has been a pain....untill we found Qt. I'll have to say that since that, we,ve truly enjoyed the ui-creation. Qt gives us more than we ever could have imagined, nice set of ui-elements that are easy to extend and customize, a sophisticated 2D and 3D graphics programming capabilities, database support, support for xml-stuff and lots more. It is truly object oriented. Nice programming paradigma of signals and slots to allow ui-monsters to communicate. Nice set of tools to produce different language versions of programs. Etc. etc...
So Qt is a new "MFC" for us, we've been porting our programs to Qt and will be ready to start shipping soon. Just keep the visual studio language and standards compliant and you'll give us programmers a chance to use tried and tested libraries to keep our productivity high :).
Thanks.
I'm an OS-level developer, who uses C and some C++ for driver development on Windows. I've also written applications using MFC.
The problems inherent in a language like C or C++ are legion. Bad string handling, lack of pointer validation... THIS is why we have security issues and crashes in Windows. Things like SAL notations are, at BEST, a big fat hack to try to make C++ "safer."
We need to move beyond C++ to languages that enforce safe data environments. That's what C# does... and in my opinion (ignoring the whole .Net part of the language) the C# is a *much* improved version of C++ (more consistent, cleaner, clearer).
WHY prolong the life of C++? It's time to move beyond 1970's computing ideas to the future. Spec# is an even better C#. C++? Wow, dude, that's sooooo yesterday.
Fred
I think rab36 nailed it. XML serialization and WCF are tops on my list.
A little off topic... has anyone worked with Objective C (iPhone dev)? Is it even possbile to think that something can be done to kill object C?
@fredBed:
It's not about the language itself, it's more about ready to use libraries. There are no silver bullets, instead tools that are more or less suitable for the task you are facing. Think about it...it would be total madness to rewrite all those tried and tested C++ libraries in C#, not to mention LAPACK etc. C++ also co-operates almost transparently w libraries, written in FORTRAN etc. And considering evolving nature of C++, new features are being added, language improved I'd say that C++ is a strong keeper for years to come.
Ever given a try for the Qt? I'd say that you will fall in love. You'll also get that unicode string handling goodness. Just brilliant, the best of the best, documentation. And as a bonus...your programs will run on multiple platforms.
So would I use C++ for data snacking applications? No, C# works nicely for that.
C++ for WebService as a Client - Yes, my C++ client hooks to Webservices and I think it was in VS 2003 you could import a WSDL and a C++ wrapper would be generated. Now we are forced to use C# in our C++ app in order to take advantage of the import.
C++ for WebService as a Server - Like someone mentioned C++ - WCF sounds like a great idea.
C++ Data Access - YES!! - Most applications at some point have to access a database on the client or elsewhere even if the application is doing a lot of operations, and .NET type data access is quite nice.
Thanks.
Everything Rab36 said - even to the fact we develop apps for real time data acqusition systems - but ours are radar.
What about Qt ,it is now in Open Governance so MS could get involved (of course Qt is cross platform and they won't like this aspect)
Thank you for the long post and for speaking your mind. This is always welcome.
C
I also think that rab36 is right on the money. I use C++ for a lot of performance based projects that are consumed by .NET projects, many dealing with video, graphics, multimedia, etc. A large majority of these projects would have been better suited being all C++, but with a need for a large amount of (consistant) tooling and libraries, these projects have been .NET centric. It always comes to a line in the sand that a team must choose between productivity (libs and tooling) and performance. I want to believe we can have both.
If I'm reading some of the hints on the VC++ blog correctly about "bringing native to parity with managed", maybe this is where you guys are going. I cry a little each time a customer has a large C++ codebase and they have to pull in a CLR dependency just to create a rich UI. I think there is a huge desire for a modern "high level [rich] UI" for native developers. Not having one, IMO, has seriously stunted the growth of high performance, rich consumer applications on the Windows desktop. If there is a high level rich UI in the works, one should only worry with, "How high level?" Nothing limits the ability of UI platform more than being "too retained" (see: WPF/SL) and/or "too slow at rendering" (see: WPF/SL). In other words, let the developer choose if they wish to participate in how (immediate mode hooks) the UI is rendered.
I am truely excited to see what you guys have in store. I think you guys got a tough job ahead after a decade of downplaying C++ by upselling .NET...but I have a blog ready to sing praises if my current excitment ends up matching reality
-Jer
Moré focus on the parallel programming aspect of the language.
Code templates inside the IDE (both C# an VB have it, C++ does not).
Make the IDE faster. 2010 ide is at least twice as slow as the 2008 one.
Allow easy integration with Internet explorer. Emphasis on easy, this allows developer to focus on the application while letting a designer to work in parallel on the interface. Of course require applications to be signed.
Things I would like to see for VC++ and C++ in Windows:
Keep it coming!
C
@PhrostByte:. I think what you want is support for vectorization/vectorization library. Yea, vectorization support are nice but the ones I see around (gcc, Intel) still very close to C + compiler extensions. I hope things begin to get better after the C++ and GPU talk in the C&B and in the AMD Fusion Developer's Conference.
Actually I love the intrinsic header files (and it is the only way mix assembler code from 64bit), but I'm suspect to talk about it (I'm that type of crazy dev who like to "brush bits" sometimes
)
Sadly most existing libraries are too inflexible or require you to jump out of C++ and use some other language to define the vector bits.
I'm not convinced GPU stuff like AMP will help at all for SIMD on the CPU -- GPU and CPU design are just too different. CPU requires a much more careful design, where an algorithm might look completely different between SSE2, SSE4, and AVX instruction sets. GPU still requires a careful design, but in wildly different areas.
[offtopic]
@PhrostByte: I don't see much difference between CPU and GPU with respect to SIMD, at least in the view of the bare metal (1 execution/shader unit :: 1 CPU; VLIW4/5 :: AVX register/instruction; GPGPU thread grid dispatcher :: Multicores and NUMA nodes). But the programming paradigm yes, this is quite different as it give you direct control over what is put in the cache levels (but that is something they want turn optional).
The Intel OpenCL SDK are a cool as they are providing an off-line visual LLVM compiler, where you can inspect how the code are generated in x86 SIMD (SSE4 and AVX).
My faith on those GPU talks is cause the Khronos, and others, are very interested in migrate from C for GPU do C++, but a C++ suitable for GPUs and CPUs at same time, CUDA already providing Unified Memory Address (pass pointer direct, no more host_ptr and device_ptr), lets see next version of OpenCL
I'd love to see improved Debugger that helps me find critical errors while coding. Maybe detect typical C++ problems (help me with pointers).
Talking on improvements for the compiler/IDE, C++ Accelerated Massive Parallelism,
(bad side: another GPGPU/CPU Tool to the portfolio)
Plus I see Herb Sutter: Heterogeneous Computing is on MSDN Blogs and here
Now we can back to our other desires for V.next: a new C++ friendly UI library, Native Webservices Binding Tools (WWS++), and Improved Debugging (Carlos P).
@BartoszMilewski: GCC focused on different areas first- they didn't have lambdas or rvalue references for quite some time. In addition, they both release faster, *and*, sure- atomics libraries have been around for some time. That doesn't mean that they were Standard for some time.
MSVC could only have implemented them if and only if they were guaranteed to be in the final Standard in a form very close to the form they were in now. If they weren't up to that scratch, then it couldn't be done- period. What GCC can do is irrelevant.
@fredBed: If you're being bitten by bad string handling in C++, then, well, you just don't know how to use it. There's no two ways about it. The Standard provides a value-typed, perfectly safe string type. Use it. Along with all of the other type-safe, bounds-checking, programmer-friendly high-performance classes that manage resources completely safely. I'm not completely sure why you're talking about coding ideas from the 1970's- C++ was only Standardised in 1998, with another Standard in 2003, and a major new Standard this year. Guess what it includes? Why, it just might be - pointers that manage their own memory. That one that's been around in Boost for a long time.
Your post just makes me think that you haven't updated your coding practices or checked around for how to use C++ for, well, since pre-Standardisation.
Strings in C++ are too generic, some classes specialized in encodings like UTF-8 would make things easier to use.
About me: been programng since 1980's. laguages used over the years: basic, qcasic, pascal, fortran, cobol, perl, c, c++, c#, F#, plus scripting laguages galor. I have come to think of programing languages like tools, with that said C++ is like any other language is a toolbox. There are things C++ is good at and are easy to do and there are others i would rather have my balls in vise than write them c++. There is a paradox that goes with that being the nicest part of a language is the hardest part to truly understand.
For example regular expresions = perl, yet they can be the hardest prt to fully understand their use.
Likewise example: c++ string types. it can really be a pain and once your make mistake it takes al kinds time and or code the figur it out.
Another example: There are math programs in fortran i woud never attempt to write in C++, the balls in a vise come to mind.
With that said the web serivices and financial componenets have been talked about in the c++ world for quit somtime. When does it start to become too late, about 8-10 years ago. Yes there are libraries like Qt, but CORBA comes to mind.
I still write somethings in c++ because of libraries, upon libaraies, upon libraries etc. and I like it and i am lazy. Is it c# no. Is it f# (camle), hell no. Is it slow in evolving yes because of a global committee. Whenever you want to slow something down put it in committee. The lack of change in base can be seen in two ways. A strong base or stubberness to the ideal of write your own object and leave core allown.
I would like the MS c, c++ to the work seamlessly with .net simular to PhrostByte statement. I have written programs in c# just because the .net in c++ had to be marshelled or some other wierdness. The whole thoery of c++ is that if it is not there you write your own object. Then it can be resused, which is what .net is all about.
Thus, having to be play with or workaround to make those objects work in c++ is am upsetting thought. I do not want to hear about what should be in the standard, I want to hear about the linq working seamlessly with the ms c++. I do not wish to be asked if db and data manipulation should be in the stanadard i want to read about how it works in the ms version of the libararies. I also wish to be able to make 2d objects act like 3d objects like silverlight with simple chagne 45% which I can do in c#, but not c++.
Maybe I am rambling. I think i am and will now stop. sorry if i offended.
Support Windows Phone 7 +!!!!!!!
is a transcript available?
I almost agree with most posts here.
I've been working for different ISVs for several years on large C++ projects (tax paying software, Image editing, Financial, programming tools...)
One problem with existing C++ apps now is the UI, which is outdated. They share that problem with Delphi apps
. You know that battleship gray. I've spent lots of time trying to move (parts of) projects to Winform or WPF. This generally ends up with an awfull mix of C++, C++/CLI and C#. You know what I mean since you guys have ported Visual Studio UI to WPF ! This surely has been a huge amount of work.
If there would have been a modern UI C++ library, thing would have been far simpler. I've heard about DirectUI, and I can't wait to know more about what seems to be a native UI library.
Also I have participated to brand new WPF projects, in C#. For example an image editing app. One year after it started, the project is thrown away (10 men-year). WPF is too heavy, .Net has poor memory management, and the software was not compatible enough with previous versions of this project. Customers don't want a new app, they just want a better app which is able to reuse their old files/data.
What are all the C++ app developpers doing ? They have built their own UI framework and libraries years ago, sometimes based on MFC, or other libraries. (AFAIK MFC is not that bad, it is still used in many C++ apps, it is just old) They try to update the framework over the years. That's not easy, and requires a lot of resources. In the same time they have to update the applications. I bet the Office team at Microsoft has its own C++ framework. You can ask them what to do.
Since I've discovered .Net framework, I wonder why it is not also written in C++ native code. Maybe not the whole framework, but at least some core libraries, a powerfull UI layer, a fast database engine (I sometimes use SQLite in C++ client app)
Well, you know, just ask the guys who have ported Visual Studio to WPF, they will tell you what you need to do
Oh, and an important point: all developers have coding guidelines (or at least they should!). Many C++ ISVs ask their developers to write SIMPLE code. That means, avoid functors, use templates sparingly, etc. Don't use advanced C++ features if you can write simple code. Because simple code contains less bugs, and can easily been maintained. C++ is a powerfull language, and not all C++ developers can handle that power correctly.
I don't expect C++ language improvements, C++ is fine. But please, give us the equivalent of a light .Net framework, written in native code. That would be heaven.
Things I'd love to see from Microsoft on C++:
- A sane, modern, well-designed UI library designed for C++. MFC is painful, first because it's basically C with classes, second because it's a framework that pretty much tries to take ownership of the entire application, rather than being a library I can call into at my leisure. And plain Win32/GDI? Ick. Perhaps a higher level abstraction layer on top of Direct2D would be an option. Perhaps something like a C++ equivalent to WPF (although I'd prefer something with less internal complexity, and less black-box magic, and less XML/configuration which cannot be debugged. Maybe it's just me, but it could also be a general C++ thing: I want some level of transparency: I want to know what my UI library is doing, even if that means having to write 30% more code.
- Perhaps as a generalization of the above: clean up your APIs. How about a Windows.hpp header? One which gets rid of the macro hell of windows.h? One which compiles as ISO C++, without relying on proprietary extensions? One which utilizes namespaces? How about offering modernized C++ wrappers for your most commonly used APIs? WinSock, UI widgets, text encoding/processing and so on. Feel free to reuse the "traditional" win32 APIs under the hood, just wrap them so we don't have to suffer that amalgamation of 25 years of bad API design. And then, perhaps as a part of Windows, perhaps as separately maintained and released libraries, provide higher-level abstractions on top of these. But in terms of libraries, I really would love to see better ones for interfacing with your own components: the Windows API, extensibility for your various products and so on.
- As Charles mentioned in the interview, Faster/more agile releases of Visual Studio. When STL mentions that the <thread> header has been implemented internally, why do we have to wait 18 months before we can use it? When bugs are fixed, why don't we get to see them before the next major release? When we are asked for feedback, ostensibly to improve the product, why do we not get to see the improved product? I don't need a new release of Visual Studio every 3 months. But I absolutely want new features added, bug fixes released, components updated. The current schedule is inexcusable. Clang, GCC and all the other major compilers release new versions all the time; Visual C++? Once every 24-30 months. Because it has to tie in with a major Visual Studio release. Better debugger features? Again, only as part of a major release.
- And since Microsoft has a long history of applying insane amounts of effort, time and skill at solving complex problems in absurdly complicated ways, I want to see you doing some of that with the really tough problems of C++ and your IDE: You have no support for debugging templates. Give me a "compile-time" debugger where I can step through template instantiations. How about a kind of REPL loop for C++, so that I can, both "offline" and while my code is running, inspect types as well as values, instantiate templates, do all those complex tasks that C++ can do, but your actually-designed-for-C IDE and debugger currently cannot? This could even, to a large extent, replace Intellisense which you're perpetually struggling with. If I could just ask the compiler "ok, so of I instantiate a vector of ints, what does its iterator look like?", or "can I legally instantiate this template with that type?", without compiling my entire application, *that* would really boost productivity. Or how about allowing me to compile just part of an application? Say I'm in the middle of refactoring some code, and a bunch of my unit tests currently won't compile. But I still want to be able to run the remaining ones. Give me a simple way to compile the *rest* of them then. Perhaps I could just select a snippet of code, right click and select "build". Perhaps a more flexible project model in which I can easily build using just some of the .cpp files, or perhaps some entirely different option. Think outside the box to solve some of the pain points associated with C++ being such a static language, and one where build times can be, well, non-trivial.
- and in the same "absurdly complicated" (and probably even more so) category, how about solving the problem of compile times. Yes, when we follow the same 30-year-old compilation model, there's very little we can do to speed things up (although your linker performance is miserable compared to your competitors). So think outside the box. Precompile *all* headers, implicitly and separately, without making it a project setting, just as invisible caching done by the compiler. Yes, it'll require a lot of complex hacking and some very flexible data structures in the compiler, and yes, it'll rely on heuristics that might break occasionally, but then let the compiler fall back to "naive" per-translation-unit compilation for those cases. But 99% of the time, we can make a lot of of assumptions about the context in which headers are included, and the compiler could conceivably use these assumptions to compile those headers once, in isolation, and then reuse the result anywhere it is included. Again, Microsoft has come up with some absurdly complex solutions to problems before. Let's see you apply those skills to this extremely complex problem!
Finally, echoing what others have said, a separate "not-part-of-the-big-monolithic-VS" release of C++ tools would be interesting. VS is huge, it's bloated, and it's overflowing with very nice features for managed code, which are just useless in a C++ context. To be honest, most of the VC++ IDE has very little value to me. I need a build system (and I wish more of the flexibility of the underlying MSBuild was exposed, rather than the rigid project model used by VS), and I love the debugger, and the compiler is pretty decent too. But most of the IDE just gets in my way, not because I'm an anti-IDE fanatic, but because it's so slow, and so clumsy, and so obviously tailored at a whole different world: managed code.
Make us love C++ again!
I echo those who are calling for a return to the VC6 days when VC++ was the most productive programming environment for developing practical programs. People love VC6. Less so VC2010. Hint: the standard of vNext should be "how much faster than VC2010 is it?" Not, "how much slower is it than VC2010" which was the release criteria of VC2005, VC2008, and VC2010. (In all cases, if the performance only degraded a few percentage points, it was fast enough.) That doesn't work for VC, any better than it worked for Vista.
Kudos to those calling out Qt to be the reference of a modern C++ UI framework that you instantly fall in love with.
OTOH, the MS-recommended libraries suck. STL is a very poor library that was designed by a mathematician and not a programmer, and it shows. I can't believe Moshen says "just use that for modern C++" with a straight face. For one thing, the string class is horrible.
Same for XmlLite and all the other COM-based libraries that force the horrendous number of string and variant types as rab36 says. We don't need "no more of those!" QueryInterface() is even more quaint than MESSAGE_MAP. Why do C++ programmers get stuck with glue code of COM when it is hidden to every other language MS supports? Is C++ not a first class language that we can get C++ types unaltered? Moshen says assembly language is officially obsolete, but dealing with COM crap like .idl, etc. is worse than assembly language.
Make tools, languages, and libraries that people love! (Hint: Qt would never think to make you do any of the above.)
So the answer for vNext is simple: bring back the love into C++. Unfortunately, with the focus on the niche reasons mentioned for using C++ in the video, such as to save battery power, it seems love has nothing to do with what motivates the VC++ team these days.
Moshen was interesting to listen to, but he gave no more reasons to believe in any "C++ Renaissance" in this video than he did in the previous one. I don't want to use the words "put up or shut up" but really, the time to blow us away with goodness is really past by some years! :-(
Great to see the feedback continue! Keep it coming
Cheers,.
Agree completely. I love Silverlight/.NET but WP7's memory/CPU constraints sometimes make me itch for some optimizations that just aren't possible in managed code.
In addition to the topics already mentioned, C++ is the only platform-independent tool existing to date. Recently, we created a new service for smart phones. For obvious reasons you want to support the iPhone and iPad, right? So this is where we started and it was fun. We used our existing classes for AES encryption, template classes for elliptic curve cryptography (ECC), network packet framing, etc. There was just a thin layer of Objective-C++ necessary to handle the UI, and it integrated seamlessly. We reused the same classes on our mating core service running on Windows Server. And when we decided to support Android, we used the same protocol processor classes, crypto system, etc. we had already up and running and carefully tested on iOS and Windows platforms. We just needed to add JNI wrappers and only the UI portion needed to be done in Java. So we ended up with a frame work of classes with some platform-specific parts (networking on BSD and Windows, timers) implemented via virtual functions. No duplicate code to maintain, very appealing design. Would have been a snap to add Windows Mobile support, if it had not disappeared from the market. Adding Windows Phone 7 support? Not with the curent and expected market shares. Nothing against the WP7 UI, but why the heck are you keeping native developers off the platform? Google tried the same with Android and was smart enough to add the NDK. Microsoft should do the same.
It's not that I am against managed code. I have to admit that I personally prefer C++, but we used C# and ASP.NET MVC 2 in the same project to implement our customer's web portal. Thank you for that framework, 1000 times better, cleaner, more productive, more readable and more maintainable than PHP, Python, Ruby... you name it. We also created the billing system as a Windows Service written in C# using LINQ.
But: Never would we have implemented the core networking service that way. Here is where performance counts. In terms of memory requirements per connection and CPU cycles per request. And in terms of deterministic behavior. I want full control over the lifetime of dynamic objects in such a volatile environment. shared_ptr gives me that in a safe, reliable and predictable way. I do not want a garbage collector to take decisions for me.
We used SQL server native client to access the data base shared by web portal, core networking service and the billing service. Besides the pain we experienced with supporting BLOBs (via IStream interfaces), we had to add spatial support, since we used geo-position on mobile devices and SQL server's powerful spatial queries. We also fixed a few bugs in ATL Server - yes it still exists :) - to be able to send e-mails properly. All in all, the effort was worth it. We created a very stable, responsive and deterministic solution.
And we even did the Client application running on Windows desktop (XP to Windows 7) using MFC 10 and the new classes introduced with the feature pack. I was struggling a while if we should use C#/WPF instead. Again, using SQL server native client we were able to make use of the service broker to establish a connection between multiple instances of the core service and multiple client instances. Was not sure if that was possible with C#/LINQ at all.
We could have used WPF, but we did not want to. I must admit that this might be due to the fact that I am using MFC since version 1.0 and this experience can compensate the benefits you gain with C# and WPF :) But honestly, with this approach we are able to move the client application to other platforms - if necessary.
I would also like to mention that we have developed an in-home display for "smart home" applications. When we first started, I was keen on using Windows CE (at that time 6.0 R3 with 7 preview). But having Microsoft drop native support on Windows Phone 7 made me fear that Windows CE was also going to be abandoned, or at least was going to suffer from the managed code hype. So we decided to use Linux and Android instead. And we are paying in terms of poor performance of Android (compared to native code on Windows CE), but again, that is worth it and will be compensated with a more powerful ARM processor (1GHz Cortex-A8 instead of 400 MHz ARM 9).
So guys, please keep your excellent work on native development up. Visual Studio is better than Xcode, Eclipse and all the other competitors that I have worked with - and always has been. Though VS2010 IDE performance and UI stability are really embarassing. And this affects very basic features. When I hit Ctrl+F to search for text why do I have to adjust the window size of the appearing docking toolbar window each time? Double clicking a source file in Explorer sometimes makes the OS think that the application has crashed. It won't always open the first time because VS2010 is taking so long to start-up.
Sorry for that lengthy post, but this again had to be said ;)
Cheers, Arasch
Language: order-independent compilation, so that header files go away. Yes, it would break code and you could not redefine macros anymore, but it would remove one of the biggest headaches in big projects.
IDE: more stable, faster, in particular faster and more stable Intellisense, really just the basics.
Other languages: Scala looks great, but is tied to the Java runtime and all-objects-on-heap with garbage collection.
Thanks for the great feedback, everybody! I wanted to assure you that all of this is being read by the right people who can make things happen
In terms of the ctrl+f bug in VS2010, I've been informed that it has been fixed in SP1.
Keep on posting,
C
I use C++ when performance is very important and that usually means realtime, e.g. gaming related stuff. Whenever it is possible to wait for the results for a bit longer, C# is a much better choice due to .NET framework. Like others have said, having a light version of .NET Framework for C++ would be awesome. The higher level abstraction of common tasks makes quickly getting a prototype ready so much easier.
I also use C++ for debugging related tasks, because it's easy to communicate with the winapi.
Regarding the IDE performance degradation, it is definetly easily noticeable. In fact from 2003 to 2008 the performance got so bad that the IDE froze everytime I typed ".", i.e. intellisense stuff. When I bought a brand new computer with a SSD, these problems went away. For the record, eclipse is still abnormally slow with a top tier SSD & quadcore CPU.
Nope, it's still there and it is easily the most annoying thing in VS.
@Strom: Thank you for the information. You're using VS10 SP1, right (re ctrl-f)?
By the way everybody, please also speak and vote your mind here. The votes count! Your voice matters.
VS General:
C++:-
C
Remove this comment
Remove this threadclose
|
http://channel9.msdn.com/Shows/Going+Deep/Mohsen-Agsen-C-Today-and-Tomorrow
|
CC-MAIN-2014-15
|
refinedweb
| 9,632
| 72.16
|
This at:
One of the big things I tried to tackle this time around was to finally do some performance improvements. Until now, the only performance considerations were in the design of compiled queries and the use of compiled LINQ expressions for materializing objects. Yet, when I looked at actual performance of compiled queries versus straight ADO, there was still a lot of overhead.
Where was the time being spent? As it turns out, even though I was compiling a LINQ expression to represent the execution plan and an explicit function to convert DataReader rows into objects, ideally making the writing of data into objects as fast as possible, there was still room for improvement. The problem was not the writing of data into objects, but reading the data from the DataReader. I wholely blame myself for this. In an attempt to simplify the IQToolkit source code way back in one of the original posts I chose to read data using the general DataReader.GetValue method. This has two undesirable side effects; 1) the value is returned typed as object, which mean all non reference types (mostly numeric and datetime types) are boxed, which is measurably significant, and 2) in order to make sure the value was in the correct form to write it into the object I now had to coerce it back (which immediately led to an unbox operation, equally as significant.)
I tried many variations of solutions. Ideally, the runtime code would simply know which field access method of the DataReader to call and to coerce the results only if necessary. Unfortunately, the translation engine does not track enough information to be 100% certain of the data type the provider will return. It can make a good guess, but if it is wrong then the query will die in a fiery exception that halts the program and sends your manager storming toward your office. The solution I chose was sort of a hybrid. Based on an expected value type a type specific helper method is now invoked. This method calls the equivalent DataReader method inside of a try-catch. I know, I hate having to use try-catch in this way, but the cheap cost of setting up the try-catch and the rare condition where the guess is wrong led me to the dark side. I will now change the color of my light-saber from blue to red. Here’s an example of the GetInt32 helper method.
public static class FieldReader
{ ... public static Int32 GetInt32(DbEntityProviderBase provider, DbDataReader reader, int ordinal)
{
if (reader.IsDBNull(ordinal))
{
return default(Int32);
}
try
{
return reader.GetInt32(ordinal);
}
catch
{
return (Int32)provider.Convert(reader.GetValue(ordinal), typeof(Int32));
}
}
...
}
As long as the expected type is correct, the faster DataReader.GetInt32 method is called. If that fails, then the fallback is to call the general GetValue method and coerce the result. This should rarely happen.
This is all it took to get the compiled query into very low overhead versus direct ADO calls; mostly less than 3%. I’ve added a performance test you can run to check it out on your set up. Of course, this will vary depending on the query, the hardware, the load on the server and the network latency.
“Why can’t the provider simply cache the queries for me.” I’ve gotten this request a lot. Sometimes from direct pleas in email, other times from those of you trying to do it yourself and asking for advice.
It seems natural to imagine that it would only take a little bit of work for a provider to determine if a query being executed now is the same or similar to one executed before, so why is the only way to re-use a query to specify one using the cryptic syntax of generic methods, lambda expressions and delegates? And why do I have to hold onto the thing myself, can’t some service do this for me?
Of course, my usual reaction is to give a heavy sigh in the privacy of my office and then craft a quite sensible fire-and-brimstone reply, complete with infallible logic and dramatic consternation, as to why and how you really are better off with the compiled query solution. But I’m tired of doing that, so instead of impressing you with my sound reasoning I’m going to show you how I went ahead and just did it. I like challenges, and there’s no better challenge than the impossible, or the sometimes impractical, or the generally ill-advised.
What I built is a new piece of code called the ‘QueryCache’. It is actually implemented to be generic enough that it will work with your own IQueryable provider. Yet its not currently integrated into any provider, though you may choose to embed it into yours. You can, however, use the cache as is to execute your queries and take advantage of its cache-y goodness. You don’t have to make delegates and invoke them, you simply have to give the cache your query and it will give you back the results.
var cache = new QueryCache(10);
var query = from c in db.Customers where c.City == "London" select c;
var result = cache.Execute(query);
Here’s how it works. The cache maintains a most-recently-used list of compiled queries. Every time you execute a query via the cache, the cache compares your query against the ones in the cache. If it finds a match, it simply uses the existing compiled query and invokes it. If not, it makes a new compiled query and adds it to the list.
Of course, that’s the easy part.
The hard part is figuring out how to compare an IQueryable query object against a list of compiled-query delegate objects and determine which ones can be reused. For example, are these two the same query?
var query1 = from c in db.Customers where c.City == "London" select c;var query2 = from c in db.Customers where c.City == "Seattle" select c;
Technically they are different expression trees, but if that’s the deciding factor then I might as well give up now. They are structurally similar and so it is logical to assume that a query compiled for one should be nearly identical to a query compiled for the other. If I were using compiled queries directly I would simply choose to make the name of the city a parameter to the compiled query delegate and invoke it with different values. So isn’t that just what I want the cache to do for me?
To do this I need a little tool that will take a look at a query tree and decide which bits should be considered parameters and then give me back a new query tree with the parameters in place of those bits. As it turns out this is not really all that hard since it seems obvious for the most generality that anything that appears in the query tree as a constant should be deemed a parameter. A trivial expression visitor can produce this.
If it also wraps the rewritten query tree in a lambda expression and gives me back the set of constants that it extracted then I have everything I need to make a compiled query and invoke it with an array of values. I also have what I need to find an already compiled query in the cache, since compiled queries hold onto their defining query trees. So if my first query in the example above is already in the cache, it already has a parameterized query tree defining it and that ought to look awfully similar to the parameterized version of the second query.
The only thing I need now is a way to compare two lambda expressions to see if they are similar. Fortunately, I wrote that ages ago. The ExpressionComparer does just this.
If I cobble all these parts together into a reasonable order I get my QueryCache. Now, I can use compiled queries without ever having to manually define them again! Huzzah!
Yet, if this is so grand, why haven’t I taken that one last step and simply plugged into the base DbEntityProvider class?
Unfortunately, reality is not as rosy and I would hope.
There are a few problems holding me back. The most significant is the silly act of parameterizing itself. The problem with the cache is that it doesn’t know which constants in the query should be made into parameters, so it turns them all into parameters. Yet, as much as I’d like it to be otherwise, databases don’t treat all parameters equally. Sometimes a parameter is terrific for performance; a database like SQL Server optimizes by storing parameterized query plans so you basically get the same benefit client and server. Yet, sometimes, for some bits of SQL, for some back ends, parameters either cannot be used or have crippling effects on speed. So it's usually the best policy to be explicit and judicious when using parameters, something the cache in all its glory cannot chose for you.
So I leave the cache, for now, as something you can explicitly opt-in to using, per query.
Please, give it a try. Feedback is welcome.
Sometimes you may want to execute expression trees as code without actually turning it into true runtime code. You may be running on a platform that does not currently support the Expression.Compile() method (or the ability to use Reflection.Emit to generate IL at runtime) like Windows Mobile. I’ve been encouraged by folks here at Microsoft to think about this from time to time, so I set out to explore this space and the result is a whole mess code called the ExpressionEvaluator, which is an expression tree interpreter. I added my experimental solution to the toolkit in case it is beneficial for someone. It is a lot of code, so it doesn’t compile into the library by default. You have to enable it with a specific #define, NOREFEMIT. This will also switch over all direct uses of Reflection.Emit in the toolkit to using this evaluator.
It has a hefty performance overhead, so I would not consider it a viable alternative to Reflection.Emit. I’ve even added many tricks to avoid calls to reflection and boxing. This has made it a lot faster than a naive solution, but still it pales in comparison to real IL. However, in cases where there is no alternative, its probably the best you are going to get.
In keeping with the spirit of making changes for no good reason, I’ve unbundled the base set of toolkit code from the ADO provider specific bits. So now if you are using IQToolkit to build your own non-ADO based provider you don’t have to be dragging the rest of it along for the ride. All the SQL translation and DbEntityProvider goodness is now in its own DLL, IQToolkit.Data.dll. This means you’ll probably have to tweak your projects to include this new DLL, but that’s about all.
The DLL list is now:
Of course, as always, you only need around the ones you are using, or none of them if you are simply lifting the code out as source.
I’m sure there are many more wonderful nuggets of goodness I added but forgot to mention. If you discover any of them please file a full report at.
|
http://blogs.msdn.com/b/mattwar/archive/2009/09/15/building-a-linq-iqueryable-provider-part-xvi-iqtoolkit-0-16.aspx?Redirected=true
|
CC-MAIN-2014-15
|
refinedweb
| 1,925
| 70.63
|
In the past week, I’ve been exploring a little problem that by
Wednesday I was ready to sit down and code. Now, the details of the
problem aren’t important, but for this problem I was going to need to
have objects that I could read from a file, manipulate a few hundred
times, and then write back to a file.
Now, object serialization is not really what I’d consider “fun” stuff,
so I figured “I’ll just throw YAML at it”. Unfortunately, my objects
contained several NArray (and NMatrix and NVector) objects, and YAML
initially serialized them as:
irb(main):002:0> NArray.float(3,3).to_yaml
=> “— !ruby/object:NArray {}\n\n”
Not helpful. Searching the web pulled up a ruby-talk message from a
few years ago, but apparently the YAML api for defining your own YAML
serialization has changed since then. Although this new API appears
to be undocumented (at least, I couldn’t find any documentation), I
did find a few blog posts in which people showed examples with other
classes.
So anyway, I finally integrated YAML and NArray, and present the
solution here for other people googling in the future on how to get
these two to work together, as well as now for comment and criticism
by current list subscribers. Note that it handles NArray, NMatrix,
and NVector objects:
########## narray-yaml.rb #########
require ‘yaml’
require ‘narray’
First, a yaml utility routine to make the output prettier
module YAML
class YIArray < Array
yaml_as “tag:yaml.org,2002:seq”
def to_yaml_style; :inline; end
end
def YAML.inline_array(arr)
if Array === arr[0] then
arr.map {|s| inline_array(s)}
else
YIArray.new.concat(arr)
end
end
end
class NArray
I used a tag of my own since I wasn’t sure if
someone else had their own serialization of
NArray objects
yaml_as “tag:removed_email_a[email protected],2007:narray”
def to_yaml( opts = {} )
YAML::quick_emit( self.object_id, opts ) do |out|
out.map(taguri) do |map|
map.add(‘typecode’, typecode)
map.add(‘shape’, YAML::inline_array(shape))
map.add(‘data’, YAML::inline_array(to_a))
end
end
end
def self.yaml_new(klass, tag, val)
result = klass.new(val[‘typecode’], *(val[‘shape’]))
result[] = val[‘data’]
result
end
end
END
The result looks like this, for a 2 by 2 by 2 NArray:
typecode: 5
shape: [2, 2, 2]
data: !seq:Array
- !seq:Array
- [0.441292242643088, 0.463176002629107]
- [0.602508503899103, 0.155671031769272]
- !seq:Array
- [0.558707757356912, 0.536823997370893]
- [0.397491496100897, 0.844328968230728]
So I’m pretty happy with the output format, but not happy with how
long it took to get there, both in terms of the amount of code and in
terms of the amount of time spent tracking stuff down, and the amount
of time spent looking at documentation for the wrong API trying to
figure out why my code wasn’t working.
Any suggestions on how to clean up my code, and any pointers to
documentation I missed?
|
https://www.ruby-forum.com/t/yaml-and-narray/112417
|
CC-MAIN-2021-25
|
refinedweb
| 488
| 61.46
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.