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 |
|---|---|---|---|---|---|
Both classes and modules are reference types that encapsulate items defined within, but they differ in how these items are accessed from other procedures.
The primary difference between classes and modules is that classes can be instantiated and standard modules cannot. Because there is never more than one copy of a standard module's data, when one part of your program changes a public variable in a standard module, any other part of the program gets the same value if it subsequently reads that variable. Class data, on the other hand, exists separately for each instantiated object. Another difference is that unlike standard modules, classes can implement interfaces.
Classes and modules also employ different scope for their members. Members defined within a class are scoped within a specific instance of the class, and exist only for the lifetime of the object. The practical result is that, to access class members from outside a class, you must use only fully qualified names; for example, Object.Member. Members declared within a standard module, on the other hand, are shared by default, and are scoped to the declaration space of the standard module's containing namespace. This means that public variables in a standard module are effectively global variables because they are visible from anywhere in your project, and they exist for the life of the program. Unlike class members, members of standard modules are implicitly shared and cannot use the Shared keyword.
Object.Member
Understanding Classes | Structures and Classes | Shared Members | Ways to Implement Component Functionality | Shared | http://msdn.microsoft.com/en-us/library/7825002w%28VS.71%29.aspx | crawl-002 | refinedweb | 255 | 50.26 |
Feedback
Getting Started
Discussions
Site operation discussions
Recent Posts
(new topic)
Departments
Courses
Research Papers
Design Docs
Quotations
Genealogical Diagrams
Archives
Roberto Ierusalimschy discusses the ideas behind the design of Lua specially on the pervasive use of tables and coroutines.
Video, Slides[PDF] and Talk Abstract.
Note: The video is in Windows Media format but it works with Quicktime Player on the Mac if you have Flip4Mac WMV installed. I can open the video using File->Open URL.
Would be great if they post it on, say, blip.tv. Or even their own Youtube site. But I guess they are a bit too concerned with the video escaping into the wild?
They usually do eventually show up on iTunes and YouTube. This is just hot off the press, I guess :)
Another good one from the same colloquium is by David Unger on Self.
Self and Self: Whys and Wherefores [iTunes]
Self and Self: Whys and Wherefores [YouTube].
(September 30, 2009) David Unger, from IBM Research, discusses how his experience in computer science has led him to the conclusion that even if your ideas succeed, the real legacy is the people.
...is really clever!
It may be clever from an implementation standpoint (I don't know), but what always puzzled me about it is how unwieldy it is, given that Lua is designed as an embeddable language. Manually pushing arguments on a stack when calling Lua from C seems very tedious. (Supposedly, most apps use Lua the other way, though: calling C from Lua.)
I don't like to use the stack API. It is very lightweight, though. I spent a bit of time trying to think about a system of contracts that bridged the Lua FFI (i.e., so that it could be expressed both in C and Lua). There is not much to the FFI to make this kind of thing easy, except the fact that paradigmatic use of the FFI does not generate any malloc/free events.
What I find most attractive about Lua's FFI is that the internal decision about how to represent closures makes closures something that are transparent to the FFI, through upvalues.
Beyond this, I think the good press the FFI gets is in large part due to the fact that Lua offered the C/C++ world a useful, thread-safe, fully reentrant interpreter before anyone else did. So that's more to do with good properties of the whole language implementation than of the FFI in particular.
It seems reasonable to treat sets as just a special case of maps, since their operations are so well aligned. But sequences seem sufficiently different that trying to treat them the same way is less "simple" than having a dedicated sequence concept.
For example, sequence concatenation is a very basic operation. But if you're trying to say that your only data type is the table, you need to define concatenation as a table operations. How would you define the operation such that it makes sense for maps and sets as well?
Even though the underlying implementation is the same, I think people's brains still make the distinction between maps and sequences. Trying to merge the two concepts in the language results in a net increase in complexity. Are there benefits that I'm not taking into account (other than ease of implementation)?
Natural number indexes are treated specially by the implementation of Lua's tables, so they take the same space as arrays.
I didn't mean to imply anything about the execution efficiency of their setup. I realize they use techniques to make sure that if you're using something like a sequence, it operates as efficiently as a dedicated sequence implementation.
I was wondering if other people felt that having the sequence concept be just a special case of the table concept did actually reduce complexity. To me it seems that sequences do not fit into the table model cleanly and it would be simpler to model them separately (as opposed to sets, which seem close enough to maps that it seems reasonable to merge the concepts).
personally i don't have an opinion either way, but maps in clojure support sequence ops, if that is of any relevance.
I looked through some of Clojure's docs but couldn't see what you were referring to.
For example, do maps have a concatenate operation that would, if we had two sequences encoded as maps, do the right thing?
"Because collections support the seq function, all of the sequence functions can be used with any collection."
Curse my inability to navigate Clojure's doc website. My guess is that when you view a map as a sequence, map[K,V] becomes either seq[K], seq[V], or seq[tuple[K,V]], all three of which I'm ok with. Java's collection library does something similar.
What I don't like is Lua's setup where seq[V] is map[Nat,V]. 'concat' is now this slightly awkward-looking operation where you have to renumber the keys in the second map and then merge the two. This is not a natural operation for maps. Sure, you can encode sequences with maps, but there seems to be no encoding of sequence concatenation with operations that make sense for maps.
Sometimes, of course, the operations match up. With Lua's encoding of sequences, "seq.length" is simply "map.length". "seq.map" is "map.map_values". I think the more elegant solution is to define certain relationships between sequences and maps (like Clojure and Java do) instead of saying that they're the same thing.
Sometimes, of course, the operations match up. With Lua's encoding of sequences, "seq.length" is simply "map.length".
Not quite. In fact, in Lua the notion of "map.length" becomes another "slightly awkward-looking operation"... From the reference manual:).
There are many things that I find quite elegant and beautiful about Lua, but I'm still not so sure about this one.
What I don't like is Lua's setup where seq[V] is map[Nat,V].
Most every book I've read with a definition of "sequence" in it has been exactly that.
'concat' is now this slightly awkward-looking operation where you have to renumber the keys in the second map and then merge the two.
That has always been the definition of concat.
Most programmers are not used to thinking of sequences in this way. Nonetheless, the sequences they have been using conform to this definition.
I don't think, as you are suggesting, that I'm uncomfortable with the connection between seq[V] and map[Nat,V]. For example, I'm ok with having seq[V] export a view that is essentially map[Nat,V] with read-only keys.
But 'concat' is being defined over maps, even though it only makes sense for the maps that are actually sequences. I don't think this is a simplification over having a distinct sequence concept.
The problem, for me, is that this builds sequences on top of numbers and sequence operations on top of arithmetic — not just in the language implementation, where that's probably unavoidable, but in the user's semantic model. But sequences are, I think, much more basic to algorithms than numbers are. There are lots of programs you can write without numbers, but very few that you can write without some kind of sequence.
The usual non-number-dependent definition of a sequence is that it is either empty, or contains a first item followed by a sequence. Consider how much more natural the definition of concat is when defined that way: concat [] x = x; concat (x : y) z = x : concat y z. And a sequence defined that way allows any number of operations on it to be written lazily.
I think Lua's choice is defensible, but its disadvantages are real.
Note that as soon as you have sequence, you have numbers as well, as they are definable as sequence of elements of the unit type.
You can make formal the troubling similarity between the two following recursive datatypes:
data Nat =
| Z
| S Nat
data List a =
| Z
| S a (List a)
Granted, there is a huge step between this (List a) type, and (Map (Nat, a)).
I first was warned of this correspondence in Okasaki's Purely Functional Data Structures book; it's the idea of "numerical representations" that can be used to example elaborate structures such as Finger Trees (lists are built on *unary* numbers, which is a quite boring way to represent numbers).
The wider idea of building inductive datatypes by "annotating" other ones is explored by Conor McBride's work on "ornaments".
The very simple interface you've written out is actually adequate and superior for many algorithms on sequences, but hopelessly inadequate for efficient arithmetic. The correspondence is beautiful and interesting but not really relevant to the question of whether it makes sense to import all the complexity of arithmetic into a program when all it really needs is "succ" and "zero?".
If those data definitions are as in Haskell (not well-founded inductive data), then Nat isn't really the type of Natural numbers. In fact, I think most of kragen's objections stem from the fact that Lua indexes sequences with ordinary inductive Naturals.
But let's not throw the baby out with the bathwater. I have found the viewpoint of collections as indexed over an index set to be incredibly fruitful.
I think Kannan's point about concat shows that the notion of sequence supported by Lua's tables falls short of that provided by Lisp and even C. Hash tables plus a special sequence length operator doesn't seem to give the kind of full-blooded notion of sequence that programmers expect. I think we can say something similar another way by observing that hash tables are, from the algebra of programming point of view, a deficient notion of collection because I see no clean way of extending CCCs to contain finite maps (say T[A,B] is the object representing the finite maps from A to B) in a way that some reasonable algebraic condition of collections is true; e.g., observe that T[A,-] fails to be a monad over the category for most types A.
But does this really matter in the fundamental way that you and Kannan argue? When you say But sequences are, I think, much more basic to algorithms than numbers are, my question is why? Lua programmers seem to be quite happy with their unalgebraic notion of collection. We've got an odd notion of basic algorithmic construction if it is one we can manage quite well enough without.
Why do I think sequences are much more basic to algorithms than numbers are? Because I've written lots of useful programs with no numbers, but very few with no sequences. Turing machines have a sequence, but no numbers. The λ-calculus doesn't have either one, but when McCarthy (RIP) set about making a practical notation for recursive functions based on it, he added sequences, but not numbers. Cellular automata have sequences, but no numbers. Post machines have sequences, but no numbers. You can, of course, reduce a Turing machine to a counter machine, which has numbers but no sequences, because numbers and sequences are isomorphic; but nobody does, because it's a totally unnatural way to program, even more than the Turing machine itself. "Hello, world" has a sequence in it, but no numbers, unless you give main a return value. Real digital computers don't have numbers in them; like Turing machines, they have sequences of symbols, typically bits, which we then add higher-level logic to interpret as numbers.
main
C programmers manage quite well enough without polymorphism or strong type-checking, but that doesn't make it beneficial.
I really like Python's version of sequences. It supports lazy sequences, which can be generated on demand by a coroutine, which can (Haskell-like) be written inline as an expression. Any object can implement the "iterable" protocol, and thus be used any place in the language that a sequence is expected. This means I can write things like this:
# Print longest line in foo.c, using only memory enough for two lines
# plus a fixed-size file input buffer:
print max(open('foo.c'), key=len)
# Inline coroutine ("generator expression") ensures only two vectors
# are needed; xs, cs, and the return of Numeric.cos are vectors of
# 1280 numbers.
cs = sum(Numeric.cos(xs * ii) for ii in harmonics)
# Iteratively compute the first eigenvector of matrix, without using
# the matrix math abilities of Numeric.
def occupancies(matrix, occupancy):
while True:
yield occupancy
occupancy = [sum(a * b for a, b in zip(occupancy, column))
for column in zip(*matrix)]
In D, a similar concept (Alexandrescu's "range" object) allows a more natural implementation of all of the STL's algorithms. Some of them are defined as custom adaptors, allowing them to run lazily and be composed within a single expression, like Python's iterators; but it can express a larger range of algorithms, including lazy reversal, constant-space aliased slices (including of linked lists), and so on. You can wander around in UTF-8 strings, including files, in constant time, even though you can't efficiently count their characters.
None of this is on the table if the first thing you want to do when you get a sequence is to count its length, and your later accesses to it are by a numerical index.
I'm really after things that are really "core" to the notion of algorithm: I thought that by sequence you were talking about the notion of sequence you get with, say Lisp and Prolog, and which is essentially given to you by constructs such as Simula's simsets. Clearly Lua's tables do offer a usable notion of sequence (a map from integers to numbers) in a wider sense, with less need for handwaving than for cellular automata.
It's not the deficiencies of Lua's notion of table that stops the language being extended to marry its notion of table and collection: this could easily be done by modifying the semantics of for loops to look for, say, an iterator function in a table argument, but that kind of extension would be in tension with Lua's minimalist philosophy. An obvious deficiency of any small language will be that it lacks many things.
This missed the point of what I wrote. Type-checking is an algorithmic property of some programming languages, but the fact that a program passed type checking is not part of the algorithm that it expresses.
So I was looking for a sense in which the choice of tables might make Lua a poor candidate for expressing certain algorithms. But I guess I missed your point, which was maybe about which were better constructs for programming languages to have.
This is well put. Note that Lua does encourage use of iterators.
I was wondering if other people felt that having the sequence concept be just a special case of the table concept did actually reduce complexity.
I feel that way. I have read plenty of math book in which a sequence is defined as a kind of set. It's how I think of them.
Hard not to think more abstractly once you have laziness, generators, ... .
Lua tables are more than just arrays and maps, they are also structs, environments, objects, modules/packages, sets, etc. The issue I think comes down to just being able to treat conceptually different entities with a uniform interface.
The advantage of that ability is that you can write generic code that operates on the one uniform interface, and then use it on all the specific cases you might encounter without further thought.
I think having everything be the same construct at some level simplifies the language and standard library definitions and reduces the number of things you have to know. From this angle we can draw an analogy to encodings of data in the lambda calculus; even though booleans, numbers, cons cells, and so on are different, being able to express them all as the same thing (higher order functions) leads to the simplicity that makes LC so useful.
I'm afraid I can't think of any good concrete examples of how the Lua approach reduces complexity in code, but as a Lua programmer, I know I definitely appreciate it, and take full advantage whenever I can.
The issue I think comes down to just being able to treat conceptually different entities with a uniform interface.
This does seem nice at first blush. It would be nice if your functional language could auto-lift type constructors to functions so you wouldn't need to wrap it in a lambda, and if your record labels were first-class and were also auto-lifted as selector functions, and if object messages were also first-class and message dispatch was just function application, and so on.
If every language abstraction could be auto-converted to a lambda you seemingly gain some power, though perhaps you'd lose something elsewhere. In the above, function abstraction and application are the functional "uniform interface" that would replace Lua's primitive table operations.
Imagine a set as a mapping from undefined to each value in the set.
A sequence needs ordered keys, so to use this as a sequence would require remapping the keys from undefined to particular values.
Since a set is unordered, any ordering of unique keys will be satisfactory.
Concatenation is an operation upon sequences, so you could implement it as a re-key and merge operation upon maps.
Now you can concatenate multiple sets to produce an arbitrary ordering of the union of members.
You could then rekey that sequence to be all undefined to produce a set from that sequence, which would produce the union.
I don't see any theoretical problems here (except that you need to support one-to-many mappings).
How would that help with adding a sequence interface on maps?
You would still need a separate sequence data type, for when you want sequential concatenation ...
Not a separate type, but a separate function, to "massage" your sequence into a form compatible with general map concatenation.
You should have many such "massage" functions, depending on how you want the sequences put together.
All of these functions should be usable on compatible maps and sets, in a way that does not affect the invariants they care for, but do affect the sequence's invariants, for instance, those relating to insertion order. | http://lambda-the-ultimate.org/node/3894 | CC-MAIN-2017-22 | refinedweb | 3,124 | 60.24 |
It looks like you're new here. If you want to get involved, click one of these buttons!
Hi, Guys,
I need to debug a program which is about 2d geometry processing, and i have to examine the coordinates all the time in gdb. While debugging, it is really difficult when there are >10 data records to look at.
I wrote a gdb custom command to convert the information from gdb memory to .gds and call Klayout to visualize my shapes. That usage is ok. Now i want to improve this flow by making klayout as a gui display server, which is alive all the time, and different gdb process can send requests to the server to display shapes. My klayout server can update the view every time it processed a request from client.
The problem I have now is, how to make my python script run in the background.
I tried to use python thread, but it does not work. When I run the script in Macro Development IDE, it would run without error, but klayout does not display any shapes that i added in my thread.run()
The other questions is about the "redraw()" function, once i updated the data model of a cellview (the Layout instance), i called "view.add_missing_layers()". Not sure if that's right function to call.
in "gdb_displayer.py"
[import pya import sys import threading import time class GdbDisplayServer(threading.Thread): def __init__(self): super(GdbDisplayServer, self).__init__() #-- prepare first lyaout view. self.mw = pya.MainWindow.instance() self.lvIdx = self.mw.create_view() self.lview = self.mw.view( self.lvIdx ) #-- prepare the layout db and load it to our layoutview. self.layout = pya.Layout() self.top = self.layout.create_cell('TOP') self.lview.show_layout(self.layout, True) #-- self.layers = {} print('gdb display server initialized.') def run(self): print('GdsDisplayServer thread starts!') for i in range(10): for j in range(10): x1 = i * 1000 y1 = j * 1000 x2 = x1 + 1000 y2 = y1 + 1000 self.add_shape(1, 0, x1, y1, x2, y2) time.sleep(2) print('dump a box {} {} {} {}'.format( x1, y1, x2, y2)) def add_shape(self, layerid, dataid, *coords): if (layerid, dataid) in self.layers: layer = self.layers[(layerid, dataid)] else: layer = self.layout.layer(layerid, dataid) self.layers[(layerid, dataid)] = layer if len(coords) == 4: #-- rectangle box = pya.Box( *coords ) self.top.shapes( layer ).insert( box ) elif len(coords) == 8: box = pya.Box( coords[0], coords[1], coords[4], coords[5] ) def redraw(self): self.lview.add_missing_layers() self.lview.zoom_fit()
in gdb_displayer.lym
import pya from importlib import reload import gdb_displayer gdb_displayer = reload(gdb_displayer) server = gdb_displayer.GdbDisplayServer() server.start()
Reply to myself.
After reusing the klayout qt http server sample code, and use "klayout -rm server.py" to launch the klayout. I can successfully get my server run in background.
Here's a working prototype:
A simple client test driver:
To run:
/> klayout -rm server.py &
/> client.py
Input a box: 1 1 0 0 100 100
input a box: 2 1 100 100 200 200
Very good. Thanks for sharing this code
The key feature is Qt's event loop which polls event sources (including sockets). That is the way, background processing is done in classic UI applications. As KLayout is a Qt application you can hook into this event loop in many ways - one is the TCP connection object like you did it, but you can also user timers and poll some data source.
Kind regards,
Matthias | https://www.klayout.de/forum/discussion/2114/how-to-make-python-script-run-as-background-server-to-receive-request-and-display-things-iteratively | CC-MAIN-2022-33 | refinedweb | 574 | 68.36 |
Stream implementation based on an encrypted SSH tunnel. More...
#include <mitsuba/core/sshstream.h>
Stream implementation based on an encrypted SSH tunnel.
This class remotely starts a program and exposes its stdin/stdout streams through an instance of Stream. To make all of this work, passwordless authentication must be enabled (for example by using public key authentication in addition to a running ssh-agent, which stores the decrypted private key).
On Windows, things are implemented a bit differently: Instead of OpenSSH, plink.exe (from PUTTY) is used and must be available in $PATH. For passwordless authentication, convert your private key to PuTTY's format (with the help of puttygen.exe). Afterwards, pageant.exe is required to load and authenticate the key.
Note: SSH streams are set to use network byte order by default.
Create a new SSH stream.
The timeout parameter specifies specifies the maximum amount of time that can be spent before failing to create the initial connection. This feature is unsupported (and ignored) on Windows.
Virtual destructor.
The destructor frees all resources and closes the socket if it is still open
Can we read from the stream?
Implements mitsuba::Stream.
Can we write to the stream?
Implements mitsuba::Stream.
Flush the stream's buffers.
Implements mitsuba::Stream.
Retrieve this object's class.
Reimplemented from mitsuba::Stream.
Return the destination machine's host name.
Get the current position inside the stream.
Implements mitsuba::Stream.
Return the number of received bytes.
Return the number of sent bytes.
Return the size of the stream.
Implements mitsuba::Stream.
Return the user name used for authentication.
Read a specified amount of data from the stream.
Throws an exception when the stream ended prematurely
Implements mitsuba::Stream.. | http://mitsuba-renderer.org/api/classmitsuba_1_1_s_s_h_stream.html | CC-MAIN-2019-51 | refinedweb | 283 | 52.26 |
An introduction to environment files.
How to manage different environments with Angular CLI? [Updated for v6+]
Most web applications require to run in different environments before they make their way to production. You might need…
blog.angulartraining.com
When you create a new Angular project using the CLI you are provided with an
environments folder with (2) environment files, one for production and one for all other environments.
Your first impulse is to find a way to use
environment.ts to your advantage, shoving all sorts of things inside it — api keys, feature flags, api urls, default configuration settings, your grandmother’s birthday…
Pretty soon that
environment.ts file is going to be packed with all sorts of state (the fact that it typically doesn’t change during runtime doesn’t mean it’s not state) that your services, directives and components will depend on.
And since Angular swaps in the correct version of the file when you do a build with an environment flag on the command line, you can sleep well at night knowing the values you use for dev stay in dev and the values you use in production are only used in production!
Except there is a problem here…
…
[your] environment.tsfile is going to be packed with all sorts of state … that your services, directives and components will depend on
Testability
One of the benefits of using Angular as a framework is the focus on testability.
Angular provides a Dependency Injection system which provides seams in your application where you can swap out one implementation of a dependency for another.
Angular provides abstractions of the runtime and browser apis via services like the Render and ElementRef so we don’t have interact directly with the DOM and can run our code in other environments like the server for server-side rendering or automated testing.
But every time you add the line
import { environment } from '../environments/environment' (your import paths my vary) you are taking a dependency on a non-testable external dependency, which in our case is a file on the file system.
The environment file is not part of Angular’s injector graph and so it can’t be replaced with something different when testing.
While the Angular CLI build toolchain does swap the file bundled into your app code when you run
ng serve or
ng build , this is not something you can change at test-runtime because it’s already set by the time your tests start to run.
The goal of unit testing is to isolate parts of your code from external dependencies and construct scenarios for those parts to act under. You then see if the results of executing your code matches your expectations for those controlled scenarios.
We need to be able to isolate our code from environment configuration…
… every time you add the line
import { environment } from '../environments/environment'… you are taking a dependency on a non-testable external dependency
Creating an abstraction
One of the best ways to separate parts of a system is to create an abstraction between them — adding a layer, if you will.
We can use this strategy to fix our environment dependency problem.
Let’s start by fixing up our
/environments folder.
One pattern I use in all my Angular CLI apps is to create an environment interface
ienvironment.ts . This file helps keep all my different environment files consistent with each other.
Now implement this interface in all your various environment files. This will ensure that when you update properties in your interface all the environment files will need to add these properties to avoid compile-time errors (and therefore runtime errors).
Now that we have a well structured
/environments folder let’s create our next abstraction
We need a way to integrate
environment.ts into Angular’s DI system so that we can substitute it at test time with a mockable/spy-able dependency.
We could use an InjectionToken which would allow us to supply a value as an injectable token to our classes but this pattern works much better in a library and the syntax isn’t very ergonomic — you don’t want to wrap a commonly used constructor parameter in
@Inject(...) if you can help it.
Instead let’s use a service,
environment.service.ts
Since we have that interface we created for our environment files, let’s put that to good use too and implement it on our service.
Now we add our service as a dependency of the
app.component.ts and assign a value from our service to the component class instance.
Finally let’s write a test that uses a mock version of the service to set our environment values. Since our service is just a pass-through of our environment file there’s definitely no behavior or logic to fake, which is a normal reason to replace a dependency, but we are removing a dependency on hardcoded values on the filesystem.
[with our environment.service.ts] we are removing a dependency on hardcoded values on the filesystem.
One bonus here is that our original
environment import was a plain javascript object and Typescript knew it had no write protection so there was nothing stopping you from accidentally coding this somewhere in your app…
import { environment } from '@environments/environment';...someMethod() {
this.myField = environment.apiUrl; // ... make an api request // OOPS !!!!!
environment.apiUrl = this.someOtherField; // ... make an api request that is sure to fail
}
But now our
environment.service.ts exposes readonly values, not a mutable object, so something like this will have the Typescript compiler complaining about an error.
// [ts] Cannot assign to 'apiUrl' because it is a constant
// or a read-only property.
environment.apiUrl = 'test';
Isn’t that nice!
Be conscious of your enviroment(s)
As you can see, adding a layer of abstraction between our external, non-test friendly
environment.ts dependency and our application components/services means we have an opportunity to:
- Insert a mock or use the original values (we choose!)
- Set up different scenarios of our choosing during testing by crafting specific states (simulate a bad config file?)
- Redefine the rules for accessing our
environment.tsdata using Typescript (avoid confusing mistakes :D )
So what’s the best way to use Angular’s environment files??
Sparingly and behind a layer of abstraction! But go ahead and use that abstraction to your heart’s content!
I hope you’ll keep these suggestions in mind the next time you find yourself beginning to type
import { environment } from ...
Below is a link to the source code
Next time I’d like to cover the difference between dynamic and static application configuration and how we can take advantage of both.
Let me know if this was helpful.
Thanks! | https://seangwright.medium.com/the-best-way-to-use-angulars-environment-files-a0c098551abc?source=post_internal_links---------7---------------------------- | CC-MAIN-2021-31 | refinedweb | 1,123 | 51.89 |
Manpage of TTYNAME
TTYNAMESection: Linux Programmer's Manual (3)
Updated: 2015-08-08
Index
NAMEttyname, ttyname_r - return name of a terminal
SYNOPSIS
#include <unistd.h>char *ttyname(int fd);int ttyname_r(int fd, char *buf, size_t buflen);
DESCRIPTION call. The function ttyname_r() stores this pathname in the buffer bufof length buflen.
RETURN VALUEThe function ttyname() returns a pointer to a pathname on success. On error, NULL is returned, and errnois set appropriately. The function ttyname_r() returns 0 on success, and an error number upon error.
ERRORS
- EBADF
- Bad file descriptor.
- ENOTTY
- File descriptor does not refer to a terminal device.
- ERANGE
- (ttyname_r()) buflenwas too small to allow storing the pathname.
ATTRIBUTESFor an explanation of the terms used in this section, see attributes(7).
CONFORMING TOPOSIX.1-2001, POSIX.1-2008, 4.2BSD.
SEE ALSOfstat(2), ctermid(3), isatty(3)
Index
This document was created by man2html, using the manual pages.
Time: 22:27:52 GMT, June 20, 2016 | https://www.linux.com/manpage/man3/ttyname.3.html | CC-MAIN-2016-36 | refinedweb | 158 | 51.24 |
I'm using apex 5.1.3 and universal theme.
I'm using apex item in a classic report to enter some data.
'SELECT c002 segment_no, segment_name, '
APEX_ITEM.text(3,c007,15,null, 'onchange="OnSegChange(this)" id="fPS07''||seq_id) seg_code,
FROM apex_collections
WHERE collection_name = '<name>'
below is what I normally use to update the value of an item back to the collection
function OnSegChange(cb){
var get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=OnChangeCollection',$v('pFlowStepId'));
get.addParam('x01',cb.id);
get.addParam('x02',cb.value);
var gReturn = get.get();
get = null;
In this case I need to pass the data and change it back if needed example I need to pad it to left or right.
My question is how do I change the value?
I know I can use $s or apex.item to set the value but in this case I cannot access it using item name.
Is there something like cb.setValue?
Thanks
If I am understanding your code correctly, you can access it using jquery selector on the id that you are assigning in the select statement. Assuming the id you are assigning is unique: $('#'+cb.id).text('newvalue') or something like that.
Public service announcement: people should stop using htmldb_Get (its deprecated and will move to legacy) and switch to functions in apex.server namespace. | https://community.oracle.com/thread/4098119 | CC-MAIN-2017-51 | refinedweb | 221 | 58.99 |
We added a C# MVC Single Page Application (SPA) template in ASP.NET Fall 2012 Update BUILD Preview. John Papa had written a detailed blog about the preview version. With help of John Papa’s detailed feedback and sample code, we’ve rewritten and reorganized the JavaScript code to make it more structured in RC. We really appreciate the help from John Papa. He just wrote another blog about SPA template in RC version.
The major improvement for the MVC Single Page Template RC release includes the following:
1. Added VB MVC SPA template for .net framework 4.5 and 4.0.
2. Added WebAPI HelpPage support
3. Moved all the application specific JavaScript files to Scripts/app folder
4. Redo the datacontext, model and viewmodel files to make cleaner separation of data access, model and viewmodel layers
5. Created a namespace for the app called "todoApp"
6. Updated the knockout Nuget packages
Let’s discuss the important components for MVC SPA template using C#.
Introduction
The MVC SPA template is actually a sample application to demonstrate how to build a SPA application with MVC Web API. The application is able to create, read, update and delete (CRUD) todo-list with todo-items in each list for authenticated users.
At the server side, we use MVC Web API to create the scaffolding of our todo-list and todo-items models.
At the client side, we use Knockout JS framework and binding syntax to demo the Model-View-View Model pattern for SPA. We use JQuery $.ajax to send and receive JSON requests between client data access layer and server’s Web API layer. If you have not used KnockoutJS, you can use the links from the reference section to learn it.
To use the template, just choose “Single Page Application” template when you creates a new ASP.NET MVC 4 Project.
Layers
Server models
We have 2 basic entity framework models TodoItem and TodoList.
TodoList entity contains a list of TodoItems.
TodoItem entity has a foreign key TodoListId and a virtual TodoList to represent the relationship with TodoList entity.
The default JSON/XML serialization of these two models, however, will run into circular reference problems. Here are a few solutions to solve them. If the project only uses JSON, it can be solved quite simply by adding a “[JsonObject(IsReference = true)]” attribute to TodoList class.
The default XML serialization could also fail when you have the EF proxy and lazy loading enabled. The issue arises when you try to serialize a proxy of TodoList which really isn’t a TodoList but a dynamically generated type. Thus the following exception is thrown:
Type ‘System.Data.Entity.DynamicProxies.TodoList_4ECA216B8773C8B6552AD787C3BA8087E9C365199E3C2F3C1E28B89CD6556441’ with data contract name TodoList_4ECA216B8773C8B6552AD787C3BA8087E9C365199E3C2F3C1E28B89CD6556441:’
In our template, we demonstrated how to use Data Transfer Object (DTO) to solve both problems so that it works for XML and JSON serialization. DTO is a preferred design pattern for solutions with complex data models. You can see the DTO classes from TodoItemDto.cs and TodoListDto.cs files.
Server Web API DBContext
The TodoItemContext.cs file provides the Database Context that Entity framework will use. This file would normally be generated and modified via data model Web API Scaffolding.
Server Web API Controllers
Controllers\TodoController.cs and TodoListController.cs files contain the Web API controller code. When we built the SPA application for template, we generated the files through Web API scaffolding, and then modified them to work with DTOs and authorizations. Controller class attribute “[Authorize]” ensures only authorized user can access these Web API controller calls. Checking against User.Identity.Name inside most functions is to ensure that the database records can only be accessed by their corresponding owners.
The TodoListController.GetTodoLists function has an include statement in its LINQ call. It’s because our default connection string does not have MultipleActiveResultSets=”true” set (MARS). You can modify the SQL connection string locally if you want MARS behavior. For Windows Azure deployment, you need to manually modify its SQL Azure connection string to include MARS if you choose to do so.
Server View and Client View with Knockout JS
In Views\Home\Index.cshtml, we use the knockout data-bind attributes as the view. You can see all the knockout data-bind attributes are colorized and have limited intelliSense available for RC. In order to get the knockout binding handlers and user defined handlers’ intelliSense, we need to reference the knockout and app/todo*.js files in Scripts/_references.js file.
Client JavaScript Data Access Layer
Scripts/app/todo.datacontext.js file defines the todoApp namespace and the data access layer to communicate with the server Web API controllers. One thing to note is the usage of $.ajax with “cache: false” inside its options parameter, because in certain browsers, JSON requests can be cached and we will not be able to get updated Web API results. One thing we might improve in the future for this file is to remove the knockout relationship in this file so that any other SPA framework can work with this file without changing it.
Client JavaScript Models
Scripts/app/todo.model.js file defines the knockout data models. Besides the general knockout observable defines, it also shows how to subscribe a function to an observable so that function will get called whenever the observed property changes.
Client JavaScript ViewModels
Scripts/app/todo.viewmodel.js defines the view model for the page. It defines the page level view model and initiates the knockout bindings for the page.
Knockout Bindings JavaScript File
Scripts/app/todo.bindings.js defines customized knockout binding handlers which demonstrate how to extend knockout JavasSript framework. We also extended the knockout binding handlers to work with JQuery Validation plugin.
AjaxLogin.js file
Scripts/app/ajaxlogin.js shows how we use AJAX to do form based login with JSON. We also have the code to handle the login/register link actions.
Summary
In MVC SPA template, we showed a SPA design pattern with KnockoutJS framework, to work with server end MVC Web API. Our purpose is to provide a simple starting point for people to study knockoutJS SPA framework with MVC Web API, instead of trying to fully cover all SPA aspects, which also includes routing and much more.
Knockout can also be easily replaced with other SPA JavaScript frameworks that you feel comfortable with. Don’t be shy to study the difference of all the SPA frameworks out there.
References
John Papa’s blog about our ASP.NET and Web Tools 2012.2 RC SPA template
John Papa’s blog about our ASP.NET Fall Update 2012 Build Preview SPA template
The excellent Knockout tutorial
Join the conversationAdd Comment
Why does it use "return new createTodoList(list)" instead "return createTodoList(list) in the function at datacontext.js?
function getSucceeded(data) {
var mappedTodoLists = $.map(data, function (list) { return new createTodoList(list); });
todoListsObservable(mappedTodoLists);
}
Any benefits?
@Richard, I think you are right, we should be able to remove the "new" here to gain better performance as the objected reutnred from createTodoList is already a "new" object. Thanks for pointing this out!
Hi Xinyang,
I'd like to know more about the solution to the issue with Lazy Loading. I know you use a DTO but how does this solve the issue in the sample? I'm getting this error in my WebAPI and it's incredibly frustrating.
Jason
Hi, Jason,
I'd like to know more about the solution to the issue with Lazy Loading. I know you use a DTO but how does this solve the issue in the sample? I'm getting this error in my WebAPI and it's incredibly frustrating.
I think some Lazy Loading issues are LINQ problem depending on the database connection setting (e.g. multipleactiveresultsets=true is in the connection string or not). Some problems are from EF during serializing object to JSON/XML . Using DTO may not solve the the LINQ lazy loading problems, but will make sure we don't fall to the EF/serialization lazy loading problem.
In our SPA template, the DTO make it straight forward for our models to support both JSON and XML calls. Otherwise, we need to add 2 different type of attributes to enable non-circular reference for JSON and XML. They were very confusing.
Thanks
Xinyang Qiu
How do you authenticate the web api call like: ?
Thank you
@Victor,
I assume you are asking the web application itself. An authentication token is generated and passed back during login as cookie. You can see the code from AccountController.cs file. Then this cookie is used for all future webapi authentication.
To write other non-browser based client to connect to webapi, it's another story, For example, you can use a httpClient with cookie container to save the authentication token, If AntiForgeryToken is enabled, you might need to change the server code to find a better way to pass back the antiforgery token. And if you are using 3rd party oauth provider, then you need to do more customized coding for non-browser based client to achieve the authentications.
Hope it helps
Xinyang
I'm using MVS Ultimate 2013 Update 4
Whenever I choose the 'Single Page Application' template it creates a project what is NOT a SPA but a normal MVC project.
Is that a known issue? | https://blogs.msdn.microsoft.com/webdev/2012/12/19/mvc-single-page-application-template-update-for-asp-net-and-web-tools-2012-2-rc/ | CC-MAIN-2017-09 | refinedweb | 1,554 | 66.03 |
My view is that modules should not be allowed to place things in the global namespace. Obviously we can't enfore it, but it can be strongly discouraged. I think SDL.LoadBMP() is far more consistant with anything else in LuaCheia. It is a lot more obvoius to a user that a given module has functions within a given table, and has the added bonus that dumping the contents of that table gives you a quick list of functions available in the module. I am not certain that SDL will be a major part of an app that uses it in scripting... For example, we don't use SDL in our app at all, and 99% of scripts will not. If a given script does then thats fine, but that is a per-script thing, and to some degree per-use developing the script for our app. I can see the similarity to C code being appealing; but we're not trying to reproduce C, we're trying to make a more consistant manageable scripting system. So, in summary, I would definitely vote for SDL.LoadBMP() etc :) Love, Light and Peace, - Peter Loveday Director of Development, eyeon Software ----- Original Message ----- From: "Asko Kauppi" <asko.kauppi@sci.fi> To: "Lua list" <lua@bazar2.conectiva.com.br> Sent: Tuesday, August 05, 2003 1:11 PM Subject: SDL package (namespace problem) > > I've thought of the SDL namespace problem, and (personally) of the > opinion that it should be in the global namespace. That is, > SDL_LoadBMP() etc. > > Reasons: > - that's how C (sample) code is written > - if you code for SDL, it's not just a library (among the others) but > a main part of your app > > Opinions are welcome. > > > John Belmonte kirjoittaa tiistaina, 5. elokuuta 2003, kello 18:09: > > > This is looking good and builds without any fuss. I wonder if a few > > points could be improved: > > > > * support... > > > > * rewriting wrapper names (for example, SDL.LoadBMP instead of > > SDL.SDL_LoadBMP) > > > > Regards, > > -John > > > > > > Thatcher Ulrich wrote: > >> luacheia is a full-featured, modular Lua distribution. The project > >> homepage is at > > > > > > -- > > http:// if l .o / > > > > | http://lua-users.org/lists/lua-l/2003-08/msg00068.html | CC-MAIN-2019-43 | refinedweb | 348 | 73.37 |
Quantum Multi-node setup instances cannot ping each other from different nodes
I’ve been trying to get Quantum multi-node with openvswitch working but cannot get the instances to be able to ping each other across nodes. I have tried with the milestone-proposed as well as the master branch of Quantum and in neither case can instances on different nodes ping each other.
I tried the devstack and used the flags indicated in the Quantum wiki for services on the second node so stackrc on the second node has this: ENABLED_SERVICES=n-cpu,rabbit,g-api,quantum,q-agt,q-dhcp
Localrc on the controller node (running all services) has this ENABLE_TENANT_VLAN=True TENANT_VLAN_RANGE=1:1000 PHYSICAL_NETWORK=eth0 OVS_PHYSICAL_BRIDGE=br-eth0
The physical host networking is eth0.160 as the primary and eth1.820 for the floating IP’s.
Ovs-vsctl on the controller node 8d3731cf-1ac2-4df8-86e5-47ed0a5106ac Bridge br-ex Port "qg-fe7b62d0-51" Interface "qg-fe7b62d0-51" type: internal Port br-ex Interface br-ex type: internal Bridge "br-eth0" Port "br-eth0" Interface "br-eth0" type: internal br-int Interface br-int type: internal Port "int-br-eth0" Interface "int-br-eth0" ovs_version: "1.4.0+build0"
Ovs-vsctl on the second node 38dbbac7-f643-4bdb-8aa1-83f06e612ec4 Bridge br-int Port br-int Interface br-int type: internal Port "tap26583155-34" tag: 1 Interface "tap26583155-34" type: internal ovs_version: "1.4.0+build0"
Instances come up and can be pinged in the namespace of the server where they are spun up but cannot ping from instances on the controller node to the second node.
I also tried the steps in this question (...) but that did not resolve the problem either.
I checked the router namespace and I see the SNAT and DNAT rules are set correctly. What else needs to be added/corrected here to make multi-node work?
Thanks Eoghan | https://ask.openstack.org/en/question/20262/quantum-multi-node-setup-instances-cannot-ping-each-other-from-different-nodes/ | CC-MAIN-2021-10 | refinedweb | 319 | 58.21 |
How to Pass a Method as an Argument in Python?
In this article, we will learn how to pass a method as an argument in Python. We will discuss the different methodology of passing methods and functions as arguments using custom codes as well.
In Python, everything such as objects, variables, etc. is treated as an object. Therefore, functions/methods, are too treated as objects. In this article, we will stick to methods. A method can take multiple arguments, like objects, variables(of same or different data types), and even other methods because python methods are first-class objects. Methods are callable objects so you can pass them, store them, and can do whatever you want to.
__call__ method is associated with every method and gets called automatically when you invoke the method with or without arguments. You can think about a method (or function) as a variable whose value is the actual callable code object. A user-defined method or a built-in method both can be passed as an argument to another method in python.
Note:
In this article, we will use methods in the following examples, but note that everything below applies identically to functions (except without the
self parameter). Functions and methods both are utility blocks of code, but when a utility function is defined inside a class, it is known as a method. Don’t get confused between methods and functions. All functions in Python can be passed as an argument to another function.
Example: A Class Method Passed as an Argument
Methods are passed as arguments just like a variable. In this example, we define a class and its objects. We create an object to call the class methods. Now, to call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name.
Note: If you want to pass a method of a class as an argument but don't yet have the object on which you are going to call it, you can simply pass the object once you have it as the first argument (i.e. the "self" argument).
class my_class: def method1(self): return "Hello World" def method2(self, methodToRun): result = methodToRun() return result obj = my_class() #method1 is passed as an argument print(obj.method2(obj.method1))
Hello World
Example: Higher Order Functions Passed as an Argument
Just like class methods are called using class objects and are passed as arguments, a general user-defined function can also be passed as an argument to another function because functions are objects. Functions that can accept another function as arguments are called higher-order functions. In the example below, a function func1 is created which takes a function as an argument.
def func2(text): return text.upper() def func3(text): return text.lower() def func1(func): # storing the function in a variable res = func("Hello World") print(res) #funtion calls func1(func2) func1(func3)
HELLO WORLD
hello world
Example: Wrapper Function Passed as an Argument
In Python, Wrapper functions or decorators wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. In Decorators, functions are passed as the argument to another function and then they are called inside the wrapper function.
The below example defines a simple decorator hello_decorator. inner1 is a Wrapper function in which the argument is called. The inner function can access the outer local functions like in this case func(). func() is called inside the wrapper function.
#decorator def hello_decorator(func): #Wrapper function def inner1(): print("Hello, this is before function execution") func() print("This is after function execution") return inner1 # defining a function, to be called inside wrapper def function_to_be_used(): print("This is inside the function !!") # pass 'function_to_be_used' inside the decorator to control its behavior function_to_be_used = hello_decorator(function_to_be_used) # calling the function function_to_be_used()
Hello, this is before function execution
This is inside the function !!
This is after function execution
Example: Lambda Passed as an argument to map()
The most important example of passing methods as arguments is lambda. You often use
map() and
lambda together to perform various list operations and many more in python. In python, a lambda expression is a special syntax for creating an anonymous function. When you evaluate a lambda expression the object you get back is called a lambda function. Lambda functions are just like regular Python functions, with a few caveats.
Python implements the map() function where the first parameter is a function and the second is iterable. In this example, the function call passes the function sqr(x) as a function argument using the map method. Another way to use the map() method is to pass lambda as an argument with iterable.
def sqr(x): return x ** 2 list1 = [1, 3, 5, 7, 9] list(map(sqr, list1)) #use lambda print(list(map((lambda x: x**2), list1)))
[1, 9, 25, 49, 81]
Conclusion
In this article, we learned to pass a method and function as arguments to another function. Every example has its own methodology. Lambda expression as an argument to map() method is the best example to understand this article because you have used them together multiple times. Try passing different functions as arguments to other functions and observe the behavior. | https://www.studytonight.com/python-howtos/how-to-pass-a-method-as-an-argument-in-python | CC-MAIN-2022-21 | refinedweb | 886 | 53.61 |
What is the semantics of the line "using namespace std;"?
Namespaces are a clarification and encapsulation thing. If you want to associate a section of code with a tag, you can do so with a namespace. For instance
namespace foo {
class Foo { };
}
Now, Foo belongs to the foo namespace. In order to use a Foo object in your code you have to do one of several things:
Foo
foo
// Specify the name explicitly
foo::Foo f;
// Bring the type into local scope (just this type)
using foo::Foo;
Foo f;
// Bring in the entirety of the namespace
using namespace foo;
The first method exposes nothing to the local scope but allows you to use that particular item from the foo namespace. The second approach brings in the foo::Foo name to the local scope allowing you to use the Foo name without qualifying where it came from with the scope resolution operator. The final method is an extension of the second except that it brings in all names defined/declared in the namespace to the local scope.
In the case of your question, every type or variable defined within the std namespace will now be visible in the current scope.
foo::Foo
std
Edited 7 Years Ago
by L7Sqr: n ... | https://www.daniweb.com/programming/software-development/threads/350739/what-is-meaning-of-namespace-std | CC-MAIN-2018-17 | refinedweb | 210 | 65.25 |
Un:
If you are an Uncyclopedia game implementor, then you could have a chance to win this trophy!
- One vote per user per month. You may vote once for one implementor.
Nominations count as "for" votes.Actually, no. You may nominate as many people as you like, however you only get one vote.
- No self-noms. Ever.
- However, you may vote for yourself.
- Nominees must have a reasonable number of edits in the Game namespace.
- One vote per registered user. No sockpuppets or IPs.
- You may vote "against", but by doing so you forfeit your month's vote.
edit Rewards
- A trophy for your user page.
- A personal congratulation from yours truly, possibly involving game whoring.
- 7,500 zorkmids prize money.
- The right to add "Grand Implementor" to the beginning of your name, and the right to put "IotM" in your sig. It's not as good as a real title, but whad'ya gonna do?
edit How to Nominate
- Choose your favorite game implementor.
- Inform that particular implementor on his/her/its talk page (optional, but recommended).
- Place {{User:Pongo Version 2/IoTMnom}} on his/her/its userpage (optional, but recommended).
- Create a new heading for that implementor, with your vote on it. There: you're done. Go get yourself a cool glass of organic fairtrade orange juice. | http://uncyclopedia.wikia.com/wiki/User:Pongo_Version_2/Implementor_of_the_Month?diff=prev&oldid=3979616 | CC-MAIN-2015-40 | refinedweb | 219 | 69.99 |
Up to this point in your journeyings of the wonderful world of C++ you have been using cout to do output. This is soooooo boring. WIBNIF we could make a 7-segment timer display? Lets try.
A 7-segment display looks like the following:
But before we can get an oject of type 7-segment display we need to first define a segment object. And not only do we need to define it, but we must make it general enough so that we could use it in many applications.
#ifndef SEGMENT_H_ #define SEGMENT_H_ decl of class segment #endifmakes it so that even if segment.h is included multiple times, the class is only declared just once.
#include "segment.h"
#include "segment.h"This ensures that the segment class is known to the compiler.
#include "7seg.h" #include "segment.h"The latter isn't necessary since 7seg.h includes it anyway. So why do it? It is good programming style to include everything you explicitly reference.
#include "7seg.h"
#include "7seg.h" #include "counterDisp.h"
See Demo counterDispTest.cpp
The geometry involved in the timer is given below:
See Demo HMSTimerTest.cpp for test run of timer. | http://www.cs.dartmouth.edu/~thc/cs5-F96/lec14.html | crawl-002 | refinedweb | 196 | 70.39 |
Hi all, to start with, excuse me, I'm still learning programming alltogether, probably I'm making some fundamental mistake here... I have the files settings.py, GUIclasses.py and main.py in the same directory. In the file main.py are the statements: import settings from GUIclasses import * class Toepassing(wx.App): def OnInit(self): window = KFrame(None, "Testerdetest", (1000,900)) self.SetTopWindow(window) window.Show(True) return True app = Toepassing(None) app.MainLoop() In the file GUIclasses.py I have the statements: import wx import wx.lib.mixins.listctrl as listmix class KFrame(wx.Frame): def __init__(self, parent, title, Size): ...some code... self.lst = settings.attrLijst ....some more code...... Now if I run the main.py file I get the error: File "G:\Programmeren\Codes contactenlijst\GUIclasses.py", line 40, in __init_ _ self.lst = settings.attrLijst NameError: name 'settings' is not defined Why is this? Since "from GUIclasses import *" this KFrame is now at "the lowest" namespace and should therefore be able to make use of any variables living there, including "settings.*", no? Thanks in advance! - Kees | https://mail.python.org/pipermail/python-list/2005-November/332032.html | CC-MAIN-2014-15 | refinedweb | 181 | 63.56 |
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project.
On Wed, Nov 7, 2012 at 5:50 AM, Rainer Orth <ro@cebitec.uni-bielefeld.de> wrote: > Gerald Pfeifer <gerald@pfeifer.com> writes: > >> Just a small note, in the following >> >> +#ifdef __FreeBSD__ >> +# define DEFAULT_PROCESS_FILENAME "/proc/curproc/file" >> +#elif defined(HAVE_GETEXECNAME) >> +# define DEFAULT_PROCESS_FILENAME getexecname () >> +#else >> +# define DEFAULT_PROCESS_FILENAME "/proc/self/exe" >> +#endif >> >> would it make sense to have the feature test (HAVE_GETEXECNAME) before >> the OS test (__FreeBSD__), so that when/if the OS implements the feature >> in newer versions that takes precedence? > > Good point. I've incorporated this into my patch and regularly include > it in my *-*-solaris2.{9, 10, 11} and x86_64-unknown-linux-gnu > bootstraps. Sorry for the delay on this. I wanted to do it in a different way that I think is more flexible and avoids #ifdef __FreeBSD__. This patch tries different approaches to find the executable. It also ha a chance of working if, e.g., the executable was removed. Bootstrapped and ran libbacktrace and Go testsuite on x86_64-unknown-linux-gnu. Committed to mainline. Please let me know if this doesn't fix the problems on Solaris and FreeBSD. Thanks for the earlier patches. Ian 2012-11-12 Ian Lance Taylor <iant@google.com> Rainer Orth <ro@CeBiTec.Uni-Bielefeld.DE> Gerald Pfeifer <gerald@pfeifer.com> * configure.ac: Check for getexecname. * fileline.c: #include <errno.h>. Define getexecname if not available. (fileline_initialize): Try to find the executable in a few different ways. * print.c (error_callback): Only print the filename if it came from the backtrace state. * configure, config.h.in: Rebuild.
Attachment:
foo.patch
Description: Binary data | https://gcc.gnu.org/legacy-ml/gcc-patches/2012-11/msg00947.html | CC-MAIN-2022-33 | refinedweb | 279 | 53.47 |
Locust Performance Testing Using Java and Kotlin
Locust Performance Testing Using Java and Kotlin
In this post we take a look at using Locust for performance testing. Come check out this versatile framework as we give a quick run-through and example!
Join the DZone community and get the full member experience.Join For Free
If you have already put your hands on performance testing with Locust, then you should know it’s a really great code-based framework that provides outstanding capabilities for writing your tests in the Python scripting language. In one of our previous articles, which has a quick comparison of JMeter and Locust, we presented Locust as a wonderful tool for engineers who have some Python scripting experience.
Running Performance Tests in Locust with Custom Languages
But does that mean that this tool is not for you if you are not a Python fan and for some reason do not prefer this powerful scripting language? Surprisingly, it doesn't! We have great news for you! The Locust framework gives you the option to run its custom slaves on other programming languages! Basically, if you have programming experience, you can implement your own custom client to support the custom language you are using. It's worth it to mention that there are already two ready client implementations that allow you to create Locust slaves using Golang and Java programming languages.
In this article, we will demonstrate how to use one of these clients for implementing your performance tests in the Locust framework. We will use the Java client but you can apply the same steps for Golang language as well, because the principles are the same. Moreover, we will show you how to use the same Java Locust library to create your tests using Kotlin. Kotlin has all the benefits provided by Java, but with an additional huge batch of benefits that you can learn from the Kotlin official site. As for me, I love both languages with a slight preference for Kotlin. But as Kotlin and Java can be easily used in the same project, I thought it would be nice to have them both as examples.
The main idea behind the approach for using a custom programming language in Locust performance tests, is that you have the Locust master service running in Python and any number of slave nodes that can be run using any programming language. Each of the Locust slaves sends the metrics to the master, which aggregates the data and runs the Locust web application, which you can use to view the metrics:
Creating a Load Test in Java for Locust
First, let's start with a project that will contain the load tests written in Java programming language. In this article, our examples will be based on API HTTP requests against web app. In order to make API calls we can use REST Assured, one of the best Java frameworks for API testing..
Adding Dependencies
As we need to run written tests as Locust performance scripts, we also need to have the dependency for the Locust4j Java library, which creates all the magic for the Locust integration. To download and use the mentioned libraries in our project we will use Maven. All you need is to create a Maven project in your favorite IDE and use this pom.xml file:
<> <dependencies> <dependency> <groupId>com.github.myzhan</groupId> <artifactId>locust4j</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.jayway.restassured</groupId> <artifactId>rest-assured</artifactId> <version>2.9.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>com.bushnevyuri.Main</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </build> </project>
The provided pom file contains REST Assured and Locust4j dependencies, plus it contains a configuration that allows creating a Java jar file with all the dependencies packed inside. This jar file is important in order to run the project as a Locust slave, without using the IDE environment later.
Running the Locust Master
As we explained above, we need to run Locust master if we want to use custom programming languages on Locust slaves. To run the Locust master, it is enough to create the simplest Locust script with a dummy task inside. Let’s create a Python file that we can place in the root of our test project and called it “locust-master.py”.
from locust import Locust, TaskSet, task class DummyTask(TaskSet): @task(1) def dummy(self): pass class Dummy(Locust): task_set = DummyTask
You can run the master service by this command:
locust -f locust-master.py --master --master-bind-host=127.0.0.1 --master-bind-port=5557
This command says that we are going to run the script in master mode on the local machine and the 5557 port (you can use any another free port on the machine). As a result, you should get something like this:
Now the Locust master is running and ready to get some slaves on board.
Creating the Main Class for the Locust Slave
Let’s create the main class that will be used to run the Locust Java slave. The code is very simple. You just need to create the Locust object and specify which host and port are being used to run the master service:
package com.bushnevyuri;(...........); // <- You custom performance tasks should be here } }
Inside the
locust.run(...) function you need to provide the list of tests that you are going to run. Let’s run a small test that just opens the application: OpenApplicationTask extends AbstractTask { private int weight; @Override public int getWeight() { return weight; } @Override public String getName() { return "Open application task"; } public OpenApplicationTask(int weight){ this.weight = weight; } @Override public void execute() { try { Response response = given().get(""); Locust.getInstance().recordSuccess("http", getName(), response.getTime(), 1); } catch (Exception ex) { ex.printStackTrace(); } } }
Implementing Tests
As you can see, tests implementation is also relatively simple. All you need to do is to extend the new class from the “AbstractTask” class located inside the Locust4j framework and override some of the functions:
getWeight()- should return the weight of the task. This represents how often a specified task is going to be used. In other words, a task with weight 2 will run twice as often as a task with weight 1
getName()- should return the name of the task that we will see in the Locust monitoring and report, to identify the task
execute()- contains the body of the test that you should use to put your task logic inside
In addition, we made the custom class constructor for the task to accept the task weight as an argument (check this article to learn more about constructors). Using this approach, we can configure the weights of the implemented tasks from the main class, which contains all the tasks that are going to be executed, separated by commas.
Creating Assertions
If you need to create some assertions, you can put them inside the same
execute() function that contains the main logic of the task. Let’s create one additional task that simulates a flights search between Paris and Buenos Aires. In the same task we will verify that the response code is 200, which means that request has been executed successfully: FindFlightsTask extends AbstractTask { private int weight; @Override public int getWeight() { return weight; } @Override public String getName() { return "Find flights task"; } public FindFlightsTask(int weight){ this.weight = weight; } @Override public void execute() { try { Response response = given().parameters("fromPort", "Paris", "toPort", "Buenos Aires"). when().post(""); assert response.getStatusCode() == 200; Locust.getInstance().recordSuccess("http", getName(), response.getTime(), 1); } catch (Exception ex) { ex.printStackTrace(); } } }
As soon as our tasks are implemented, we can specify them inside the
locust.run() function separated by a comma:
package com.bushnevyuri; import com.bushnevyuri.tasks.FindFlightsTask; import com.bushnevyuri.tasks.OpenApplicationTask;( new OpenApplicationTask(50), new FindFlightsTask(50) ); } }
Running the Locust Load Test
After that you can run the Locust Java slave right from the IDE:
After the script has started, the master should show you the message:
[2017-12-16 23:09:35,182] Yuris-MBP-2.home/INFO/locust.runners: …. Currently 1 clients ready to swarm.
What if you want to run the same slave but via the console? First, you need to create the jar file with all the dependencies packed inside. If you are following our steps, you should already have the pom.xml file with the correct configuration to create the jar file. Use this command:
mvn clean compile assembly:single
After that, you can run the Locust Java slave using this command (assuming that your console is opened at the root of our test project):
java -cp target/locust-java-kotlin-performance-tests-1.0-SNAPSHOT-jar-with-dependencies.jar com.bushnevyuri.Main
Now, if you run the locust UI (), you should see that you have 1 slave:
Congratulations! You are running your first Locust script written in pure Java!
But what about Kotlin? As for me, I personally love Kotlin as the main language for all kinds of testing activities. It has all the benefits provided by Java but at the same time, it is much faster to write the tests because of simplicity of syntax and different syntax sugar. We are not going to compare these two wonderful programming languages. We will provide you with some steps explaining how you can use Kotlin instead of Java to implement Locust performance scripts.
Installing the Kotlin Runner
First, you need to install the Kotlin runner to execute the Kotlin scripts. You can easily do this by using the brew package manager:
Adding Dependencies and Plugins
brew install kotlin
<> <properties> <kotlin.version>1.2.10</kotlin.version> </properties> > </dependencies> <build> <plugins> …… <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <version>${kotlin.version}</version> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <sourceDirs> <source>src/main/java</source> <source>src/main/kotlin</source> </sourceDirs> </configuration> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> </execution> </executions> <configuration> <jvmTarget>1.8</jvmTarget> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>testCompile</id> <phase>test-compile</phase> <goals> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
After that, you need to create the list of updates in our pom.xml to add the Kotlin dependencies and plugins that will be used to compile the Kotlin scripts:
Converting Tests from Java
If you use the Idea IDE programming environment, then in order to create the same tests in Kotlin, all you need is to create empty files with the same names. (It’s better to add a prefix like ‘Kotlin’ in order to differentiate the Kotlin tests from the existing Java tests). Then, just copy and paste the Java code inside accordingly. The conversion from Java to Kotlin will be done automatically. This is an example of the task that finds the flights between Paris and Buenos Aires, but written on Kotlin this time:
package com.bushnevyuri.tasks import com.github.myzhan.locust4j.AbstractTask import com.github.myzhan.locust4j.Locust import com.jayway.restassured.RestAssured.given class FindFlightsKotlinTask(private val weight: Int) : AbstractTask() { override fun getWeight(): Int { return weight } override fun getName(): String { return "Find flights task" } override fun execute() { try { val response = given().parameters("fromPort", "Paris", "toPort", "Buenos Aires").`when`().post("") assert(response.getStatusCode() == 200) Locust.getInstance().recordSuccess("http", getName(), response.getTime(), 1) } catch (ex: Exception) { ex.printStackTrace() } } }
As soon as all tasks and the main runner function are converted (if you had trouble with the Java -> Kotlin conversion you can check the final classes by this link) you need to package the jar file one more time by using this command:
mvn clean compile assembly:single
Running the Locust Load Test
After that, the Locust Kotlin slave can be run by this command:
kotlin -cp target/locust-java-kotlin-performance-tests-1.0-SNAPSHOT-jar-with-dependencies.jar com.bushnevyuri.KotlinMainKt
As you can see, there is nothing difficult about using Locust with other programming languages. Powerful extensibility is one of the main distinctive features of the Locust framework. So, if you have some programming experience, you should be able to extend the Locust framework with any custom functionality, to achieve any kind of specific goals for your performance testing suite. Couldn’t find Locust integration with your favorite programming language? You can be the person who can creates your own and shares with a grateful Locust community.
As always, you can find the whole project based on provided snippets in the git repo through this link.
That’s it! You now know how to run your load tests in Locust with your custom language, like Java or Kotlin.
Automate your Locust tests through Taurus. You can also easily scale your Locust framework tests, run them in the cloud and analyze the results on BlazeMeter.
Published at DZone with permission of Yuri Bushnev , DZone MVB. 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/locust-performance-testing-using-java-and-kotlin | CC-MAIN-2019-51 | refinedweb | 2,212 | 53.61 |
Python modules & packages play a very important role while working on a code. A module in python is basically a file containing the Python code. However, a package can be defined as a directory that holds sub-packages and modules. A package must hold the file __init__.py. This does not apply to modules. To import everything from a module, we always use *
Python Modules
A file containing a set of functions you want to include in your application is called python modules.
Creating a Module
To create a module, the user just has to save the code you want in a file with the file extension
.py
def company(name): print("Hello, " + name)
Using a Module
The user can use the modules which he creates by using the
import statement:
import mymodule mymodule.company("Megha")
Naming a Module
The user can name the module file whatever he likes, but it must have the file extension
.py
import mymodule as mx a = mx.person1["age"] print(a)
Built-in Modules
There are several built-in modules in Python which user can import whenever he likes.
import platform x = platform.system() print(x)
Python Packages
A Python package usually consists of several modules. A package folder usually contains one file named __init__.py that basically tells Python: “Hey, this is a package!” The init file may be empty, or it may contain code to be executed upon package initialization.
Importing directory from package
We can import modules from packages using the dot (.) operator.
For example, if we want to import the start module in the above example, it is as follows:
import company.joblevel.start
We can now call the function simply as follows:
start.select_difficulty(2)
Module Search Path
The user has to ensure that when he finds the module, he needs to do one of the following:
- Put mod.py in the directory where the input script is located, or the current directory if interactive
- Modify the PYTHONPATH environment variable to contain the directory where mod.py is located before starting the interpreter. Or put mod.py in one of the directories already contained in the PYTHON PATH variable.
- Put mod.py in one of the installation-dependent directories, which you may or may not have write-access to, depending on the OS. | https://www.developerhelps.com/python-modules-packages/ | CC-MAIN-2022-05 | refinedweb | 384 | 56.86 |
Compiling Qt 5.3.1 under Visual Studio 2010 Professional (windows 7 - 64 bits)
Hello,
I am a newbies with Qt (from France).
I have downloaded the source code "qt-everywhere-opensource-src531.zip".
After unpacking the source files in C:\Qt\5.3.1 directory, I set up environment variables.
- QMAKESPEC = win32-msvc2010
- QTDIR = C:\Qt\5.3.1
- Path = ....;%QTDIR\bin\
Then I open the VS2010 console. I changed the current directory with a "cd %QTDIR%"
I launched the following command : "configure & nmake & nmake clean"
The compilation lasted 1 hour and 15 minutes (old PC centrino 2 but with a SSD disk).
Problem n°1 : the compilation sent me an error : "The Directx SDK bould not be detected ... disabling the ANGE backend. I went further.
Problem n°2 : I lauched VS2010, set up a new makefile Project with different settings :
- Exe directory : $(QTDIR)\bin
- Include directory : $(QTDIR)\include
- Library directory : $(QTDIR)\lib
I wrote the main.cpp with the basic Qt example :
@#include <QtGui/qapplication.h>
#include <QtGui/qpushButton.h>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton bouton("Bonjour les Zéros !");
bouton.show();
QObject::connect(&bouton, SIGNAL(clicked()), &app, SLOT(quit()));
return app.exec();
}@
I lauched the build, and received different errors : "Could not find the qapplication.h" !!! ????
I tried to change the %QTDIR% variable to "C:\Qt\5.3.1\qtbase" and change the main.cpp as this :
@#include <QtWidgets/qapplication.h>
#include <QtWidgets/qpushbutton.h>@
I builded it again, and this time, here is the error from VS2010 : the Qt5Guid.lib is not found (it does not exist on my PC !!!)
bq. 1>Build:
1>
1> Microsoft (R) Program Maintenance Utility Version 10.00.30319.01
1> Copyright (C) Microsoft Corporation. Tous droits rÚservÚs.
1>
1> "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\nmake.exe" -f Makefile.Debug
1>
1> Microsoft (R) Program Maintenance Utility Version 10.00.30319.01
1> Copyright (C) Microsoft Corporation. Tous droits rÚservÚs.
1>
1> echo 1 /* CREATEPROCESS_MANIFEST_RESOURCE_ID / 24 / RT_MANIFEST / "debug\TutoQt.exe.embed.manifest">debug\TutoQt.exe_manifest.rc
1> if not exist debug\TutoQt.exe if exist debug\TutoQt.exe.embed.manifest del debug\TutoQt.exe.embed.manifest
1> if exist debug\TutoQt.exe.embed.manifest copy /Y debug\TutoQt.exe.embed.manifest debug\TutoQt.exe_manifest.bak\TutoQt.exe.embed.manifest /OUT:debug\TutoQt.exe @C:\Users\EMMANU~1.GUI\AppData\Local\Temp\nm6325.tmp
1>LINK : fatal error LNK1104: impossible d'ouvrir le fichier 'C:\Qt\5.3.1\qtbase\lib\Qt5Guid.lib'
1>NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\link.EXE"'á: code retour '0x450'
1> Stop.
1>NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\nmake.exe"'á: code retour '0x2'
1> Stop.
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.MakeFile.Targets(38,5): error MSB3073: La commande "qmake & nmake" s'est arrêtée avec le code 2.
1>
1>ÉCHEC de la build.
1>
1>Temps écoulé 00:00:01.02
========== Génération : 0 a réussi, 1 a échoué, 0 mis à jour, 0 a été ignoré ==========
Here it is !
Could you help me ?
Thanks a lot for all.
- SGaist Lifetime Qt Champion
Hi,
If you want an ANGLE build you need to install the DirectX SDK, otherwise configure your build with -opengl desktop
It's normal, Qt has been modularized for the 5 series. If you want to use Qt from Visual Studio, you should consider using the VS-addin otherwise, Qt Creator is a very good alternative.
On a side note, with nmake clean you have removed everything you just built.
- JKSH Moderators
Hi, and welcome to the Qt Dev Net!
Where did you get your instructions for building Qt 5? Here is a good guide: Just ignore the part about git -- You can use qt-everywhere-opensource-src531.zip
But I'm curious:
Why do you want to compile Qt yourself, instead of downloading a precompiled package?
Why do you use MSVC 2010 instead of MSVC 2013?
[quote]I set up environment variables.
QMAKESPEC = win32-msvc2010
QTDIR = C:\Qt\5.3.1
Path = ….;%QTDIR\bin[/quote]You don't need to set any environment variables.
- The build system will automatically detect your compiler, so you don't need QMAKESPEC.
- The build system ignores QTDIR.
- I often encourage people not to put Qt in PATH. You don't need it, and it can cause problems sometimes.
[quote]I launched the following command : “configure & nmake & nmake clean”[/quote]Like SGaist said, nmake clean is supposed to delete the files you built! The correct command is nmake install.
However, in order to use nmake install, you need to set the "-prefix" configuration option. "-prefix" is the folder where you want to install Qt.
You should run configure like this:
@
configure.bat -prefix "C:/Qt/Built/5.3.1/msvc2010" -opensource -confirm-license -nomake examples -nomake tests -opengl desktop
@
Notes:
- "-confirm-license" will automatically apply the "-opensource" license. If you don't include it, you need to answer a prompt.
- Your "-prefix" should be different from your source code folder. If you want to install to C:\Qt\5.3.1, then you should extract qt-everywhere-opensource-src531.zip to a different folder.
- "-nomake examples" and "-nomake tests" will reduce compilation time.
- "-opengl desktop" will get rid of the warning about the DirectX SDK. However, this option only works if your graphics card supports OpenGL 2.0 or higher. If you don't have OpenGL 2.0 or higher, you need to remove this option and install the DirectX SDK.
[quote ????[/quote]Because you didn't run nmake install
Hy,
I am very glad for all your answers. Thank you : I am not alone :)
To SGaist : I am not sure to understand your answer. As I told you, I am new to Qt. For the time being, I need not to use DirectX. What is ANGLE : I have to learn about it. You advise me to install VS-addin ? By the past, I installed Qt Creator but to work with Code::Blocks and MinGW. But I do not understand the link between Qt Creator and VS2010.
To JKSH : I found instructions for using Qt with VS2010 on a french website "here":
This concerns Qt 4.7. The toturial explains that I need to build Qt !
Is it necessary to build QT5 or not ?? You said that I can use only a precompiled package. Like "Qt Online Installer for Windows (14 MB) ", and this could work simply with VS2010 ?
I have a license for VS2010 but not for VS2013. This is why I use VS2010.
Can you direct me more clearly on what to implement and how to build Qt projects in VS2010? After that, I would like to use Qwt too.
Thanks to you.
- JKSH Moderators
Hi,
[quote]For the time being, I need not to use DirectX. What is ANGLE : I have to learn about it.[/quote]See -- basically, Qt uses OpenGL for Qt Quick (QML GUIs). However, some Windows PCs don't have enough OpenGL support, so Qt gives the option of using ANGLE to convert OpenGL functions to DirectX functions.
If you don't plan to use QML, you don't need to worry about OpenGL/ANGLE.
[quote]You advise me to install VS-addin ? By the past, I installed Qt Creator but to work with Code::Blocks and MinGW. But I do not understand the link between Qt Creator and VS2010.[/quote]
- Qt Creator is an IDE (Integrated Development Environment).
- Visual Studio is an IDE.
- When you install Visual Studio, you get the IDE and a compiler.
- The Qt Creator IDE can use the Visual Studio compiler or the MinGW compiler (or a few others)
[quote]I found instructions for using Qt with VS2010 on a french website "here":
This concerns Qt 4.7. The toturial explains that I need to build Qt ![/quote]That tutorial is extremely old. Qt has changed a lot since then. Don't follow that tutorial.
[quote]Is it necessary to build QT5 or not ??[/quote]Not necessary :)
[quote]You said that I can use only a precompiled package. Like “Qt Online Installer for Windows (14 MB) “, and this could work simply with VS2010 ?[/quote]Yes.
The Online Installer is a package manager. Through it, you can select and download precompiled packages like "Qt 5.3.1 for Windows 32-bit (VS 2010, OpenGL, 537 MB)".
[quote]I have a license for VS2010 but not for VS2013. This is why I use VS2010.[/quote]Do you want to use Pro features of the Visual Studio IDE? If not, you can download VS2013 Express for free, and use Qt Creator as your IDE.
Hy,
Thanks for your quick answer !
OK for QML (see later).
I have to download the Qt 5.3.1 for Windows 32-bit (VS 2010, OpenGL, 537 MB)
Do I need to configure VS2010 or VS2013 in order to use Qt ?
Do you advise me to prefer Qt Creator with the VS20XX compiler ?
By the past, I downloaded the VS2013 Express, but I wanted to build a XLL, and for that, I needed to use add-ins (not with the VS2010 PRO). But you advise me to use VS2013 Express with Qt ?
Waiting for your return, I'll start downloads
Best regards.
- SGaist Lifetime Qt Champion
If you install Qt 5.3.1 VS 2010, then you need to also have Visual Studio 2010 installed. You can't mix different versions has Microsoft compilers are not compatible one with the other.
Qt Creator is just an IDE, it doesn't come with a compiler so you still need to install e.g. Visual Studio. Since you're new to Qt, then go with Qt Creator, it's optimized for Qt development (you can still use it for development of software not using Qt though).
Hy,
Finally, I followed the recommandation of JKSH :
Clear of all environment variables
Installation of VS2013 Express
Installation of Qt 5.3.1 for Windows 32-bit (VS 2013, 559 MB)
Installation of Qwt 6.1.0 (need to launch nmake and nmake install)
Use of Qt Creator for build Qt project and Qwt Project
All is right.
Thanks for all to JKSH and SGaist for your help.
Best regards. | https://forum.qt.io/topic/44415/compiling-qt-5-3-1-under-visual-studio-2010-professional-windows-7-64-bits | CC-MAIN-2018-13 | refinedweb | 1,726 | 69.38 |
31 July 2012 16:09 [Source: ICIS news]
LONDON (ICIS)--Some initial European August toluene contracts were settled up by $8-17/tonne from the previous month at $1,127/tonne (€924/tonne) and $1,133/tonne on firmer ?xml:namespace>
For some players, the US Gulf market was crucial. Prices there have managed to hover around the $4.00/gal level over the past few weeks, seesawing alongside crude futures but generally supported by balanced fundamentals.
The European market remains thin, with rising energy costs pushing offers in the spot market as high as $1,160/tonne into August. However, the traditional slowdown in activity over the summer months is keeping any upward momentum limited.
The contracts were settled on a free on board (FOB) northwest Europe (NWE) basis. Further confirmation from other players is pending.
( | http://www.icis.com/Articles/2012/07/31/9582612/initial-europe-august-toluene-up-8-17tonne-on-firmer-us-prices.html | CC-MAIN-2014-49 | refinedweb | 137 | 55.84 |
React automatically Re-Renders the components whenever any of its props or its state is updated. But quite often beginners (especially me in my early days) find it quite difficult getting a component re-rendered.
First, let's look at the methods we can use to re-render a component, and discuss whether we should really force a re-render or let React take care of it.
Re-Render a Class Component
Class Components provide you a built-in method to trigger a Re-Render. Simply use
forceUpdate method to force React to Re-Render the component.
class App extends React.Component{ constructor(){ super(); this.forceUpdateHandler = this.forceUpdateHandler.bind(this); }; forceUpdateHandler(){ this.forceUpdate(); }; render(){ return( <div> <button onClick={this.forceUpdateHandler}> Change Number </button> <h4>Random Number : { Math.random() }</h4> </div> ); } }
Re-Render a Functional Component
Unfortunately, Functional Component doesn't have a
forceUpdate method for ease of use. You can use
useState hook to simulate an update or create a custom hook too.
// forceUpdate hook function useForceUpdate() { const [value, setValue] = useState(0); return () => setValue((value) => value + 1); } // component function App() { const forceUpdate = useForceUpdate(); return ( <div> <button onClick={forceUpdate}> Change Number </button> <h4>Random Number : { Math.random() }</h4> </div> ); }
Should you Force Re-Render a React Component?
Now for answering the most important question...
NO! NO! and NO!!!!!!!!!!
In most cases, you DEFINITELY SHOULD NOT force a re-render!
There are a few niche cases, like modifying a blockchain (which only returns a transaction hash and no data), where the forced re-render makes sense to fetch the updated data from the blockchain.
Debugging Why the Component isn't Updating
Let's look at some of the common issues why React fails to update your components and find solutions for them as well.
1. Incorrectly Updated State
Let's consider the following example:
const App = () => { const [user, setUser] = useState({ name: "", age: 0, }); const updateUser = () => { user.name = "Tom"; setUser(user) } return ( <> <h2>Name: {user.name}</h2> <button onClick={updateUser}> Update User </button> </> ); }
The
App component would not be re-rendering the user's name even when the
Update User button is clicked.
React evaluates state changes by checking its shallow equality (also called reference equality), which checks to see if both the current and the new value for state reference the same object. In our example, we updated one of the properties of the user object, but we technically made
setUser the same object reference, and thus, React didn’t perceive any change in its state.
As React documentation mentions, State should be treated as immutable.
So, how do we fix it? We could create a new object with the updated values:
const updateUser = () => { setUser({ ...user, name: "Tom", }) }
2. Incorrectly Updated Props (without state change)
Incorrectly updating props without a state change can also leads to bugs. Let’s look at an example:
let time = new Date(); // setInterval(() => { // console.log(time) // }, 1000); const App = () => { useEffect(() => { const intervalId = setInterval(() => { time = new Date() }, 1000); return () => clearInterval(intervalId); }, []); return ( <Clock time={time} /> ); }
The
Clock in the example doesn't update the
time after the first load. To confirm that the
time is being properly updated, you can just un-comment the
console.log. Every second, the runtime will update the variable
time, which is then passed to our
Clock component for rendering.
When the state changes,
App (parent component) is re-rendered, thus triggering a re-rendered in
Clock (child component) with the updated
time. Thus updating state is what actually triggers the re-render, which is then propagated through the props. So updating the state is ABSOLUTELY CRUCIAL!
So to fix the issue, we could use the following:
const App = () => { const [time, setTime] = useState(new Date()); useEffect(() => { const intervalId = setInterval(() => { setTime(new Date()); }, 1000); return () => clearInterval(intervalId) }, []) return ( <Clock time={time} /> ); }
Wrapping up
Just like everything in this world, this article too has to end 😛
In the article, we went through some of the ways you can force re-render your React Components as well as the common causes of why React fails to re-render the components. Hope this helps you.
Best of Luck with your React Development Journey! (7)
React automatically Re-Renders the components whenever any of its props ... we should really force a re-render or let React take care of it. Signs Of Black Magic Done On You
That's exactly what I pointed out: React re-renders a component when the state data changes. If the props contains a state data from the parent component, a re-rendered is triggered for it too, else it fails to re-render. The fix for it is provided above too & there is no need to force a re-render
Try out the code provided in the example to see for yourself
Hello!
You should replace
clearInterval(intervalId) with
() => clearInterval(intervalId),
in your case the interval will clear immediately.
Yeah, thanks a lot for pointing it out! A rather silly mistake on my part
I think the best way to force rendering is using key property on an component.
Change it and the component will update.
Could you share an example snippet?
Check this good article from Kent C. Dodds, the last part with a Counter example show how to use a key to reset a component telling React to unmount and mount the component.
kentcdodds.com/blog/understanding-...
To use with great responsibility in mind :) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/ruppysuppy/how-to-force-re-render-a-react-component-should-you-do-it-5h1p | CC-MAIN-2021-49 | refinedweb | 894 | 55.03 |
Join the community to find out what other Atlassian users are discussing, debating and creating.
I have two projects: Software and service desk, and wont to copy customer coment from SD to Software. how i can do it with event listeners? all issues have links.
Here's what I have so far for the before-mentioned comment event listener idea. It worked in my dev environment last week, but since changing the link type it broke (the comment is copied back to the service desk issue causing a feedback loop). Still fine-tuning. Let me know if you find what I'm missing.
import com.atlassian.jira.event.issue.IssueEvent
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.ComponentAccessor
import com.atlassian.jira.issue.comments.Comment
import com.atlassian.jira.issue.comments.CommentManager
import com.atlassian.jira.issue.link.IssueLinkManager
import com.atlassian.jira.issue.link.IssueLink
import com.atlassian.jira.user.ApplicationUser
import org.ofbiz.core.entity.GenericValue
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.Issue;
def issueLinkManager = ComponentAccessor.getIssueLinkManager()
def commentManager = ComponentAccessor.getCommentManager()
def issue = event.issue as MutableIssue
// gather the original author and comment body from the original issues comment
def lastcomment = event.getComment()
String lclc = lastcomment.getBody().toLowerCase()
def commentBody = lastcomment.getBody()
def commentAuthor = lastcomment.getAuthorApplicationUser()
// get original issue linked issues
issueLinkManager.getInwardLinks(issue.getId()).each {issueLink ->;
if (issueLink.issueLinkType.name == "Service Desk") {
//if the last comment author is not your automation account (if you have an account that responds to the customer on other listeners) then
if(lastcomment && !(commentAuthor.getDisplayName().equals("AutomationAccount"))) {
// create comment on the linked issue and fire the comment event on that issue
def modCommentBody = "*{color:#3b7fc4}FROM SERVICE DESK (DO NOT REPLY HERE):{color}*\n" + commentBody
commentManager.create(issueLink.getSourceObject(), commentAuthor.getName(), modCommentBody , true)
}
}
}
Found my problem - change getDestinationObject() to getSourceObject(). So you'll need to check the link type direction for your setup. If you use Outward, use Destination; if you use Inward, use Source. Previous comment corrected.
I have 2 projects (one SD e the outher Software)
SD = Project A
Soft = Project B
I have managed through your script to copy the comments made in project A to project B.
I'm having a hard time doing the reverse, copying from Project B to Project A
In my theory, it would just change the project the listener is checking, but nothing happens ..
Would you help me?
When you make the reverse listener, you need to flip 'getSourceObject()' to 'getDestinationObject()' - this is in reference to the issue link direction.
Another thing to keep in mind is that the comment author must have comment permission in the project you are copying to, in this case your SD project. And if the user commenting in the software project doesn't have an Agent license, their comment will be made on the SD project as an internal comment (not visible to the portal).
Good luck!
Thank you!
I was able to create the reverse.
In the Project SD listener for Project Soft I had to use if to check if the last comment was from my jirabot user.
In the Project Soft listener for Project SD, I removed this check.
Now it's working perfectly!
again, thank you!
It is my understanding that the issue you want your comment to copy to is linked to the source issue, yes? Also, every single comment should be copied? If that is the case, then the algorithm is pretty easy:
1) Create a custom listener that would trigger on 'Issue commented' event.
2) Write a logic so that only specific issues are processed (i.e. issues from your SD project)
3) Get the body of the last added comment and use it to create a new comment in a linked issue.
Can script runner copy comments from linked issues, across different projects?
Yes, as long as those projects are within a single Jira instance. If not you'll have to use REST API to access issues from another Jira.
That's grand, thank you.
We are using the Jira cloud hosted solution, is that going to cause us an issue achieving. | https://community.atlassian.com/t5/Adaptavist-questions/Copy-comment-to-linked-issue-with-event-listeners/qaq-p/698841 | CC-MAIN-2019-26 | refinedweb | 691 | 51.44 |
simple Python config in your home directory
Project description
cnfg
Simple configuration should be simple. Here’s example.py:
import cnfg settings = cnfg.load('.examplerc') print(settings['message'])
Relative paths are awful. Not all systems have /etc. The only reasonable place to put configuration is in your home directory.
JSON and YAML are not Python. eval is not so bad. Here’s .examplerc:
# It's Python, so you can use comments (and more) {"message": "My custom message."}
Now all of these work, with relative directories as implied:
./example.py python ../example.py cat example/example.py | python
What about default settings?
It’s up to you, but it’s easy, especially if you’re keeping all your configuration in a dict:
settings = {"message": "Default message!"} settings.update(cnfg.load('.examplerc'))
What about environment variables?
It’s up to you, but it’s easy:
import os some_var = os.getenv("SOME_VAR", "some default value")
What about “from config import settings,” like confire?
It’s up to you, but it’s easy. Just make a file called config.py and define settings in it.
Where’s my home directory?
On a Mac or Linux machine, echo ~. On Windows, echo %userprofile%.
This is so trivial!
Yes, it’s as simple as possible, and it’s useful all over the place and the right level of complexity for a lot of projects.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/cnfg/ | CC-MAIN-2018-39 | refinedweb | 254 | 62.34 |
ESB Roundup Part Two: Use Cases
In part one of this series, we began with the basic definition of an Enterprise Service Bus (ESB) on the Wikipedia.
One of the points of general agreement seemed to be that an ESB was distinct from orchestration and Business Process Management belonged in a separate class of product. In addition, there was a healthy debate on whether an ESB was a product or pattern.
In part two of this series, InfoQ examines the purpose of an ESB--what are the use cases and requirements for an ESB?
Stuart Charleton (Enterprise Architect for BEA Systems' Strategic Consulting Services, in Toronto, Canada) in the discussion of the previous article offered the following examples of uses:
-
And augmenting these themes, Paul Fremantle (Co-founder and vice president of technology at WSO2) added:
Anne Thomas Manes of The Burton Group has said:Anne Thomas Manes of The Burton Group has said:.":
- ESBs must provide adapters to enterprise data sources (SAP, Peoplesoft, Oracle, SQL Server)
- ESBs must support at least rudimentary business process management
- Open standards (JMS, Web services) support is/was a requirement for our ESB implementation
- An ESB must integrate smoothly with existing enterprise application integration (EAI) and message-oriented products..
Steve's distinctions
by
Stuart Charlton.
What about INVALID use cases?
by
Paul Fremantle
I've seen some customers using an ESB layer to implement stuff like:
- Complex transformations
- Data enhancement
- Stateful workflow management
- Business logic
These things seem really dangerous to me, and in one instance where did all this was done, they ended up junking the whole approach because they couldn't manage it. Fundamentally they had moved their business logic from the applications down into the bus. And in my opinion, the bus is the wrong place for business logic.
So what are "good" use cases:
- Logging, tracing, monitoring, managing message interactions
- Routing, supporting different versions of standards, URL virtualization
- Switching protocols: RM->JMS, SOAP->REST, WSS->HTTPS, Eventing->RSS
- "Standard transformations" - for example JSON->XML
- dumb transformations - e.g. supporting a switch from v1 to v2, changing namespaces, simple XSLTs, are also very valuable
- QoS processing - e.g. terminating WSRM, WSSec connections, or initiating then so as to deal with those outside the application server
Re: What about INVALID use cases?
by
Demed L'Her).
Re: What about INVALID use cases?
by
Stuart Charlton.
Re: What about INVALID use cases?
by
Demed L.)
Re: What about INVALID use cases?
by
Demed L'Her
-.
Re: What about INVALID use cases?
by
Paul Fremantle.
Re: What about INVALID use cases?
by
Paul Fremantle
Improving existing software
by
Eric Newcomer.
Other Use Cases
by
Kris Huggins
2. A layer of abstraction that can insulate consumers from some changes to producers.
3. A central point to enforce governance rules.
Service creation and orchestration
by
James Pasley.
Re: What about INVALID use cases?
by
Steve Jones
I'd like to add one "good" use case
The ability to delegate decision making (policy
Re: Service creation and orchestration
by
Steve Jones
For me I'd put orchestration into one of Paul's "Bad" Use Cases.
Re: What about INVALID use cases?
by
Dave Chappell
Re: What about INVALID use cases?
by
Dave Chappell
Re: Other Use Cases
by
Dave Chappell
Re: Service creation and orchestration
by
Dave Chappell
Delegating orchestration or processing logic to the ESB is a smart thing to do. There's a huge difference between general business logic and process control logic that's used to coordinate the interaction between services.
Dave
Migrating from Batch to Realtime SOA
by
Dave Chappell
An article on ESB use cases
by
Stuart Charlton
Re: Service creation and orchestration
by
James Pasley.
Re: Service creation and orchestration
by
Steve Jones.
An Article on an ESB Use Case from a Customer
by
Dave Chappell
The current issue of Government Computer News features a profile on Washington, D.C.?s adoption of Sonic ESB
This article talks about having ubiquitous access to property information for housing inspectors and tax purposes, but the broader DCStat program also encompasses an emergency response system for the city of DC and the surrounding areas.
A common characteristic of organizations adopting ESB is that they have disparate datacenters that need to operate autonomously, yet work together in a larger federated environment. Sonic ESB was designed to do this, and to even allow the creation of process flows that can seamlessly span the physical locations across IT boundairs. The city of DC fits very well into this use case. There are 66 unique "lines of business" within the city of DC which all have their own way of doing things in their own IT datacenters.
What they needed was a common Services Bus to span those 66.
You can't do that with just a "proxy".
Dave
Re: Service creation and orchestration
by
Dave Chappell
Re: Improving existing software
by
Tiberiu Fustos.
Re: Service creation and orchestration
by
Steve Jones.
Re: What about INVALID use cases?
by
Ozawa Hitoshi.
Re: Service creation and orchestration
by
Naren Chawla
is.tm.tue.nl/research/patterns/patterns.htm. | http://www.infoq.com/news/ESB-Roundup-Part-Two--Use-Cases/ | CC-MAIN-2014-52 | refinedweb | 849 | 54.93 |
Control of modalPanel not renderingCliff Wiggs May 23, 2007 9:31 AM
I want to follow 'best practices' so please let me know if there is a better way to implement what i'm trying to do.
Imagine a shopping cart type application with a modalPanel backed by a bean to show detailed info on a product. You can click on any product and it updates the bean and then displays the same modal. Thats the closest analogy to what I'm doing.
In my app, when I 'update' the modal and display it, the control facet doesn't render. This is where I've placed my 'close' link. Thus I am stuck in the modal.
I stripped this down to just this demo code and the 'Change Message' link works correctly the first two times, but the 3rd time I click it, the control facet doesn't render.
Based on another forum thread, should I create an ajax region inside the modalPanel and rerender it instead of rerendering the entire modalPanel?
Here is my code:
demo.jsp
<%@ taglib <f:view> <h:form> <f:verbatim> <a href="javascript:Richfaces.showModalPanel('popupMsg')">Showpopup</a> </f:verbatim> <a4j:commandLink <a4j:actionparam </a4j:commandLink> <rich:modalPanel <f:facet<h:outputText</f:facet> <f:facet <f:verbatim> <a href="javascript:Richfaces.hideModalPanel('popupMsg')">X</a> </f:verbatim> </f:facet> <h:outputText </rich:modalPanel> </h:form> </f:view> </body> </HTML>
DemoBean.java
package demo.web; public class DemoBean { private String modalMessage="Default Message"; public String getModalMessage() { return modalMessage; } public void setModalMessage(String modalMessage) { this.modalMessage = modalMessage; } }
1. Re: Control of modalPanel not renderingCliff Wiggs May 23, 2007 11:16 AM (in response to Cliff Wiggs)
Update. I've discovered this is not due to the Control facet, but to the verbatim tag.
I moved the verbatim tag to my modalPanel body and it would sometimes render and sometimes not.
I changed to a commandButton and it works even within the control facet.
I would still like comments on any 'bad style' in my approach and some thoughts on why the verbatim tag sometimes doesn't generate.
Thank you for your time.
2. Re: Control of modalPanel not renderingIlya Shaikovsky May 24, 2007 7:50 AM (in response to Cliff Wiggs)
Unfortunatelly I have no problem with your code on the latest snapshot
Al you need to remember - f:verbatim is required around plain html in JSF 1.1
3. Re: Control of modalPanel not renderingCliff Wiggs May 24, 2007 2:11 PM (in response to Cliff Wiggs)
Thank you for the reply anyway.
Even on my system it wasn't a consistent error. I try to test things completely before posting to make sure it isn't something wrong with my environment or something covered in the documentation. I'm having a problem with the dropSupport right now, but I'm not done testing it locally yet.
Cliff | https://developer.jboss.org/thread/6529 | CC-MAIN-2018-47 | refinedweb | 483 | 63.9 |
A list is a data structure in python which is used to store items of multiple data types. Because of that, it is considered to be one of the most versatile data structures. We can store items such as string, integer, float, set, list, etc., inside a given list. A list in python is a mutable data type, which means that even after creating a list its elements can be changed. A list is represented by storing its items inside square brackets ‘[ ]’. We can access list elements using indexing. In this article, we shall be looking into how in a python list, we can find the max index.
1. Finding max index using for loop
Finding the maximum index using a for loop is the most basic approach.
my_list = [10,72,54,25,90,40] max = my_list[0] index = 0 for i in range(1,len(my_list)): if my_list[i] > max: max = my_list[i] index = i print(f'Max index is : {index}')
Here, we have taken a list named ‘my_list’, which contains a list of integers. We initially take the first element of the list as the maximum element and store the element into ‘max’. Then we take a variable as ‘index’ and store it with the value 0.
After that, we shall iterate a loop from index 1 to the last element of the list. Inside the loop using an if statement, we shall compare the ith element, i.e., the current element of ‘my_list’ with the ‘max’ variable. If the value of the current element happens to be greater than the value of ‘max’, then we shall assign the value of the current element to ‘max’ and the current index to ‘i’. After completion of the for loop, we shall print the value of ‘index’, which will denote the index of the maximum value from the list.
The output is:
Max index is : 4
An above method is a naive approach. It is for understanding how the maximum element will be found. There are more compact methods, and now we shall be looking into some of them.
2. Using built in methods – max() and index()
We can use python’s inbuilt methods to find the maximum index out of a python list.
The max() method is used to find the maximum value when a sequence of elements is given. It returns that maximum element as the function output. It accepts the sequence as the function argument.
The index() method is used to find the index of a given element from a python list. It accepts the element as an argument and returns the index of that element. In the case of multiple occurrences, it will return the smallest index of that element.
First, we shall use the max() function to find the maximum element from the given list ‘my_list’ and store it in ‘max_item’. Then using the index() function, we shall pass the ‘max_item’ inside the function. Using my_list.index(), we shall return the index of the maximum element and print that.
my_list = [10,72,54,25,90,40] max_item = max(my_list) print(f'Max index is : {my_list.index(max_item)}')
The output is:
Max index is : 4
3. Using enumerate() function to find Python list max index
The enumerate() function in python is used to add a counter to an iterable. With the help of enumerate() function, we can find the index of the maximum elements from a list. We shall use list comprehension for storing the index. List comprehension is a way of creating sequences out of already existing sequences.
my_list = [10,72,54,25,90,40] max_item = max(my_list) print([index for index, item in enumerate(my_list) if item == max_item])
Using the max() function, we shall store the value of the maximum element into ‘max_item’. Then, we shall enumerate over my_list and check for which list item the value equals max_item. The index for that element shall be printed as a list item.
The output is:
[4]
4. Finding max index for multiple occurrences of elements
If there are multiple occurrences of the maximum element for a list, then we will have to apply a different logic for the same. We will make use of list comprehension to store multiple indexes inside a list.
my_list = [10,72,90,90,54,25,90,40] max_item = max(my_list) index_list = [index for index in range(len(my_list)) if my_list[index] == max_item] print(index_list)
First, using the max() function, we shall find the maximum element from the list. Then, using list comprehension, we shall iterate over the list ‘my_list’, and whenever the item value equals the ‘max_item’, we shall save that index into ‘my_list’. Then, we shall print the ‘index_list’.
The output is:
[2, 3, 6]
5. Maximum index from a numpy array
To find the maximum item index using the numpy library. First, we shall import the numpy library. Then, using the array() function, we shall pass the list my_list as an argument inside the numpy array. This shall convert the given list into a numpy array and store it into ‘n’. Then, using the argmax() function, we shall print the index of the maximum item from the numpy array.
import numpy as np my_list = [10,72,54,25,90,40] n = np.array(my_list) print(f'Max index is : {np.argmax(n)}')
The output is:
Max index is : 4
That wraps up Python List Max Index. If you have any doubts or any thoughts to share, leave them in the comments below.
Until next time, Keep Learning!
How the a list with 5 indexes gives you 4?
The list is [10,72,54,25,90,40], so max() will return 90 for this list. And list.index(90) will get you 4.
This will be the index of the maximum value in the list.
Regards,
Pratik | https://www.pythonpool.com/python-list-max-index/ | CC-MAIN-2021-43 | refinedweb | 968 | 73.07 |
(For those unfamiliar with this mechanism, the 'background' section of this codeproject article provides a quick summary).
When I link my threads library (static library) to an executable, my TLS callback is called as expected. However if I link the threads library in to a DLL (by which I mean, create a DLL which is linked against my static library), the callbacks aren't called.
Furthermore if I go poking around in my MSVC build of the dll (with this, for example) the AddressOfCallBacks field (0x1010DD88) in the PE TLS directory points in to the string table once I've subtracted the preferred image load address (0x10000000). Without the subtraction the address is beyond the end of the image, so it appears to be bogus either way, though realignment at load time might end up shuffling things about suitably(?).
Does anybody know if the PE TLS callback mechanism is supposed to work for DLLs in this manner?
I couldn't find anything on the web that indicated it shouldn't work, but on the other hand all the examples I found were creating executables.
I'm targeting recent versions of MS Visual C++ and MinGW GCC. Here's the code snippet compiled in to my static library that places a pointer to the callback in the appropriate PE section.
extern "C" { #if defined(_MSC_VER) # if defined (_M_IX86) # pragma comment(linker, "/INCLUDE:__tls_used") # else # pragma comment(linker, "/INCLUDE:_tls_used") # endif # pragma data_seg(".CRT$XLB") PIMAGE_TLS_CALLBACK mtl_tls_callback_ = mtl::tls_callback; # pragma data_seg() #elif defined(__GNUC__) PIMAGE_TLS_CALLBACK mtl_tls_callback_ __attribute__ ((section(".CRT$XLB"))) = mtl::tls_callback; #else # error "Toolchain not supported <img src='<#EMO_DIR#>/sad.png' class='bbc_emoticon' alt=':(' />" #endif } // extern "C"
The workaround is to provide an auxhiliary DLL and have its DllMain do the cleanup, but I'd like to know if I can avoid having to do that. | http://www.gamedev.net/topic/628373-windows-pe-tls-callbacks-in-dlls/ | CC-MAIN-2014-52 | refinedweb | 305 | 57.91 |
.
Remove duplicates based on the UUID, typically after a verification. Return the number of entries removed.
Creates a subset of the files that have the kStaged & !kCorrupted bit set.
Merge all TFileCollection objects in li into this TFileCollection object. Updates counters at the end. Returns the number of merged collections or -1 in case of error.' print global meta information 'F' print all the files in the collection in compact form (current url, default tree name|class|entries, md5) 'L' together with 'F', print all the files in the collection in long form (uuid, md5, all URLs, all meta objects; on many lines)
Reset the bit for all TFileInfos
Returns the tree set with SetDefaultTreeName if set the subset of files served by 'server'. The sysntax for 'server' is the standard URI one, i.e. [<scheme>://]<host>[:port].
{ return fTotalSize; }
{ return fNStagedFiles; }
{ return fNCorruptFiles; }
{ return (fNFiles > 0) ? 100. * fNStagedFiles / fNFiles : 0; }
{ return (fNFiles > 0) ? 100. * fNCorruptFiles / fNFiles : 0; }
{ fDefaultTree = treeName; } | http://root.cern.ch/root/htmldoc//TFileCollection.html | crawl-003 | refinedweb | 160 | 58.38 |
This.
FLTK comes with complete free source code. FLTK is ©1998-2011 by Bill Spitzak and others. Use and distribution of FLTK is governed by the FLTK Library License, which is the GNU Library General Public License with an exception added that allows you to distribute statically-linked programs using the library without providing source code to the program or the library). You can thus use FLTK in any software, whether or not you include the source code. came up with "FLTK", with the bogus excuse that it stands for the "Fast Light Tool Kit".
FLTK was designed to be statically linked. This was done by splitting it into many small objects and designing it so that functions that are not used do not have pointers to them in the parts that are used, and thus do not get linked in. It is also designed so that all data used by the GUI, such as images and widget layout, can be inlined into source code.
This allows you to make an easy-to-install program, or to modify FLTK to the exact requirements of your application, without worrying about bloat.
However, FLTK works fine as a shared library. It is often included in this form on Linux distributions.
Here are some of the core features unique to FLTK:
It has always been Bill's belief that the "operating system" does not have to provide any of what people call "GUI". Toolkits (even FLTK) are not what should be provided, the system only has to provide arbitrary shaped but featureless windows, a powerful set of graphics drawing calls, and a simple, unalterable method of delivering events to the owners of the windows. Much of the design of FLTK is to prove that complex UI ideas could be entirely implemented in a user space toolkit, with no knowledge or support by the system.
Many of the ideas in FLTK were developed on a NeXT (but not using NextStep) in 1987 in a C toolkit Bill called "viewkit". Here he came up with passing events downward in the tree and having the handle routine return a value indicating they used the event, which got rid of the need for "interests" that so complicated Motif and NeWS.
After going to film school for a few years, Bill worked at Sun Microsystems on the (doomed) NeWS project. Here he found an even better and cleaner windowing system, and he reimplemented "viewkit" atop that. NeWS did have an unnecessarily complex method of delivering events which hurt it.
With the death of NeWS Bill realized that he would have to live with X. The biggest problem with X is the "window manager", which means that the toolkit can no longer control the window borders or drag the window around. Indeed far more code is spent trying to talk to window managers than would be needed to draw the borders themselves. (fortunately the problems with X are also replicated on Windows, and thus solving them helped with the porting to Windows).
At Digital Domain Bill discovered another toolkit, "Forms". Forms was similar to his work, but provided many more widgets, since it was used in many real applications, rather then as theoretical work. Several large pieces of software were written using a version of Forms with the menus and file browser replaced with code from viewkit.
The need to switch to OpenGL, a desire to use C++, and the closed-source nature of XForms, all led to a requirement to rewrite Forms. This produced the first version of FLTK. The conversion to C++ required so many changes it made it impossible to recompile any Forms objects. Since it was incompatible anyway, Bill decided to incorporate his older ideas as much as possible..
FLTK 2.0 is a rewrite to make the interfaces to each widget more consistent, to use C++ more correctly, including the ability (but not the requirement) to support functor style callbacks, exceptions, and a namespace, and to support themeing of the GUI without having to set the color of every widget.
FLTK is hosted on a web site, operated by Michael Sweet of the Easy Software Corporation (the developer of CUPS). An SVN repository of the source code, downloads of the fltk package, mailing list and newsserver, bug tracking, and programs using FLTK are all here.
FLTK also has a SourceForge page at, though currently all source code is actually on the fltk.org site.
(Other stuff was here but I believe it was inaccurate. Need info on how to read the mailing lists using usenet, get svn access, post bugs, etc. This information is currently available at) | http://www.fltk.org/doc-2.0/html/intro.html | CC-MAIN-2016-07 | refinedweb | 773 | 67.38 |
Here we go again - the mighty piece of code that never dies…
#include <stdio.h> void main(void) { printf("Hello, world!\n"); }
You save the above programming masterpiece using your favourite text editor as hello.c and the fun begins… You probably should read the excellent cc65 documentation or at least the introduction section before continuing. This will make things more clear and structured in your mind
For now, we assume that you know what are the translation phases (or you just don't want to know that) and we go the easy way, using cc65's Compile & Link utility. The beauty of this utility is that single command:
$ cl65 hello.c
should create for you one object file named “hello.o” and one (C64) executable named “hello”:
$ ls -l total 24 -rw-r--r-- 1 user staff 2758 17 cze 20:05 hello -rw-r--r-- 1 user staff 68 17 cze 19:38 hello.c -rw-r--r-- 1 user staff 568 17 cze 20:05 hello.o $
C64 is the default target for many cc65 tools. If you need to have your pride compiled for a different target platform you need to add a switch to the command line:
$ cl65 -t apple2 hello.c
creates executable file for Apple ][ machines. For a complete list of supported target platforms, please refer to the cc65 documentation and ld65 linker options for setting the target. | http://wiki.cc65.org/doku.php?id=cc65:hello_world | CC-MAIN-2017-51 | refinedweb | 235 | 71.65 |
Mar 04, 2014 02:19 PM|laurin1|LINK
Well, things went well for about 2 weeks and now we have a serious problem. After being up and running for around 3 days, IIS begins to lock up. Our Current Non-Anonymous user count (we are using Windows Authentication) goes from 10 to about 60. Eventually, we get timeout errors, all pointing to wincache_ucache_get() or wincache_ucache_set() lines in the code, and the 500 Internal Server errors. The only solution we have is iisreset!
This is a huge problem and we're not even sure how to troubleshoot it.
Mar 04, 2014 04:30 PM|DropPhone|LINK
Step one: Attach windbg.exe to the php-cgi.exe process and get a dump. Then send me mail and we can work out how I can get that dump.
I'll need to know which version of wincache & php you're using (like, where you picked up the bits), so I can find the matching symbols.
Thx!
--E.
Mar 04, 2014 04:52 PM|laurin1|LINK
At any time or when it's locked up?
I've tried to do this before, but never succesfully. If it has to be done during a lockup, that will be very hard to do - we can't suffer an outage like this for more than a few minutes.
Mar 05, 2014 11:41 AM|laurin1|LINK
More info.
The wincache.php file worked fine after the reset, but now the Summary and User Cache pages are blank! I assume that the problem is in it's early stage of failure:
Mar 05, 2014 11:47 AM|laurin1|LINK
So, if I do
print_r(wincache_ucache_info(true));
I get this:
Array ( [total_cache_uptime] => 78052 [is_local_cache] => [total_item_count] => 126669 [total_hit_count] => 3993455 [total_miss_count] => 427399 [ucache_entries] => Array ( ) )
But if I do this:
print_r(wincache_ucache_info(false));
I get nothing!
Mar 05, 2014 01:39 PM|DropPhone|LINK
So, I have the following script:
<?php $bar = 'BAR'; wincache_ucache_set( 'foo', $bar ); $colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8'); wincache_ucache_set($colors_array); echo( "----wincache_ucache_info(true))----\n" ); print_r(wincache_ucache_info(true)); echo( "----wincache_ucache_info(false)----\n" ); print_r(wincache_ucache_info(false)); ?>
Which I ran against php 5.5.7 + Wincache 1.3.5.2 (the dev build I put on sourceforge in Feb). The output I get is as follows:
----wincache_ucache_info(true))---- Array ( [total_cache_uptime] => 0 [is_local_cache] => [total_item_count] => 5 [total_hit_count] => 0 [total_miss_count] => 0 [ucache_entries] => Array ( ) ) ----wincache_ucache_info(false)---- Array ( [total_cache_uptime] => 0 [is_local_cache] => [total_item_count] => 5 [total_hit_count] => 0 [total_miss_count] => 0 [ucache_entries] => Array ( [1] => Array ( [key_name] => green [value_type] => string [value_size] => 18 [ttl_seconds] => 0 [age_seconds] => 0 [hitcount] => 0 ) [2] => Array ( [key_name] => foo [value_type] => string [value_size] => 20 [ttl_seconds] => 0 [age_seconds] => 0 [hitcount] => 0 ) [3] => Array ( [key_name] => yellow [value_type] => string [value_size] => 18 [ttl_seconds] => 0 [age_seconds] => 0 [hitcount] => 0 ) [4] => Array ( [key_name] => cyan [value_type] => string [value_size] => 18 [ttl_seconds] => 0 [age_seconds] => 0 [hitcount] => 0 ) [5] => Array ( [key_name] => Blue [value_type] => string [value_size] => 18 [ttl_seconds] => 0 [age_seconds] => 0 [hitcount] => 0 ) ) )
...so, it looks like "It Works On My Box(tm)". That said, I *am* using a way-old PHP 5.5.x build, so I'll see what happens after I sync & rebuild the world...
Thx!
--E.
Mar 05, 2014 03:00 PM|laurin1|LINK
Maybe I wasn't clear. Yes, that works fine for us too, until whatever is wrong with this begins to happen and then this appears to be the first symptom of a problem, but eventually it starts to lock up the php-cgi.exe processes and finally crashes.
Mar 06, 2014 03:50 AM|DropPhone|LINK
Hm. If you can catch it when it returns 500 and then get a crash dump before you have to do a wincache_ucache_clear(), that would be the best way to make progress on the investigation.
How long (and how many wincache_ucache_set() operations) before this thing starts to go bad? Maybe we just need to run a simulation that hammers on this for several hours (or days).
Thx!
--E.
Mar 06, 2014 02:33 PM|DropPhone|LINK
In your php.ini, what's the size of your wincache.ucachesize? IIRC, you set it pretty large, like 930 MB, right?
I ran into an issue when repro'ing where the call to wincache_ucache_info(false) failed because of an out-of-memory error...
Thx!
--E.
Mar 06, 2014 07:51 PM|laurin1|LINK
sorry, yes 930.
Ok, I was able to the memory info:
Array (
[memory_total] => 975175680
[memory_free] => 908547916
[num_used_blks] => 446581
[num_free_blks] => 3768
[memory_overhead] => 7205616 )
So, it looks like I am using 74MB.
Ah! I just realized, that I am using the 1.3.5.0 version (to test this issue) and it's still happening. Great.
Mar 07, 2014 02:28 AM|DropPhone|LINK
Okay, I've written a torture test for wincache_ucache_set/wincache_ucache_get. I won't post the php code here (it's trivial really), but let's just say populated the cache with 100,000 entries, and I have ~400 php.exe processes hammering on those entries. They are definitely going cross-process, shared memory. I've been able to drive the CPU on the box above 97%. So far, no failures, no AVs.
Remembering your need to have things expire, I am also setting the elements up with a 120 second expiry. Even with things getting purged out of the cache, I still haven't hit a problem.
I'll devise more brutal tests to see if I can trip up the cross-process shared memory locking system.
Thx!
--E.
Mar 07, 2014 07:18 AM|laurin1|LINK
Yesterday, I reset Wincache User Cache at 6:49PM. Right-before I reset Wincache User Cache, I opened the wincache.php page and as i stated, it was already not displaying the User Cache information.
[06-Mar-2014 18:45:35 America/Chicago] PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 263 bytes) in C:\inetpub\wwwroot\wincache.php on line 669
[06-Mar-2014 18:45:36 America/Chicago] PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 263 bytes) in C:\inetpub\wwwroot\wincache.php on line 669
Line 669 is
$ucache_info = wincache_ucache_info();
There are places in my code where I use this function to get the age of the entry or to get the time left of the entry (ttl - age.) I ran some other tests and after it begins to fail, I get the same error:
[05-Mar-2014 23:07:17 America/Chicago] PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 45 bytes) in C:\inetpub\wwwroot\test2.php on line 11
For this code:
echo "Age: ".wincache_ucache_info(false, "xxxx")["ucache_entries"][1]["age_seconds"]."<br />";
So, my theory is that we are not storing too much data for use in any function, except for this one - and that's because wincache_ucache_info(false) returns the entire cache - which is causes a memory overrun!
Sound right?
Mar 07, 2014 07:20 AM|laurin1|LINK
Actually, my age and ttl code looks like this:
44 /** 45 * @param mixed $key 46 * @return int 47 */ 48 public static function getTimeLeftInSeconds($key){ 49 50 return (int) wincache_ucache_info(false, $key)["ucache_entries"][1]["ttl_seconds"]; 51 52 53 } 54 55 /** 56 * @param mixed $key 57 * @return mixed 58 */ 59 public static function getAgeOfEntryInSeconds($key){ 60 61 return (int) wincache_ucache_info(false, $key)["ucache_entries"][1]["age_seconds"]; 62 63 }
Mar 07, 2014 11:39 AM|DropPhone|LINK
From: laurin1
Yes, I was able to reproduce this error on my tests when I had >50K items in the ucache. I had to stop using wincache_ucache_info(true) in my scripts, since it was complaining I was exceeding my memory consumption for the process.
This makes sense, since the call is trying to return *all* of the items in the cache as an array. So it has to alloc & make a copy of the entire ucache to do this.
Glad we ran down this part of the problem!
I'll still see if I can replicate the lock up problem. Just out of curiosity, how many concurrent php-cgi.exe's are running on your system? I'm assuming you have at least two, and possibly 10. If it's more than 10, let me know.
Thx!
--E.
Mar 07, 2014 11:50 AM|laurin1|LINK
So, even though we can raise the limit to 930, that's really unusable if we need to do anything with wincache_ucache_info(false), correct? That sucks.
Right now, we have 5 php-cgi.exe processes running and that's about normal. During these lock-up periods, I saw a few more, but not sure the total count (maybe 10.)
Mar 07, 2014 12:34 PM|DropPhone|LINK
The 930MB limit is in Wincache....however, Wincache is still just a guest in PHP's process, which is just a guest of the OS. I'm not sure whether this limit is imposed by PHP or by the OS, but either way, Wincache is making a call to alloc something big, and PHP is saying, "No."
I just looked through the implementation of wincache_ucache_info, and if you supply a $key, then Wincache will only fetch that one element. So you shouldn't be trying to alloc the whole array in that case.
Looking at your code, if $key is null, it looks like the wincache_ucache_info() function will try to get the whole cache. Is the code that's calling getTimeLeftInSeconds() and getAgeOfEntryInSeconds() guaranteeing that $key is non-null in all cases? You might consider adding an assert that $key is non-null. Otherwise you run the risk of unknowingly hitting this alloc failure.
Thx!
--E.
Mar 07, 2014 12:45 PM|laurin1|LINK
Actually, that 128MB error is in the php.ini setting memory_limit, which is set to 128MB. I could raise that, and my system can definitely handle more, but definitely not 930MB for multiple scripts!
DropPhoneI just looked through the implementation of wincache_ucache_info, and if you supply a $key, then Wincache will only fetch that one element. So you shouldn't be trying to alloc the whole array in that case.
Hmm, well, that's easy enough to work around. I must be grabbing the whole array at times.
Mar 10, 2014 12:02 PM|laurin1|LINK
I think I just found my problem. I misunderstood what the first parameter actually is for and so all my calls, even to get individual entries were like this:
wincache_ucache_info(false, $key)["ucache_entries"][1]["age_seconds"];
And should be this:
wincache_ucache_info(true, $key)["ucache_entries"][1]["age_seconds"];
Because if this is set to true, then even only a summary is returned, not the whole array:.
Mar 10, 2014 12:24 PM|laurin1|LINK
I also modifed this in wincache.php:
668 if($user_cache_available && ($cache_data == SUMMARY_DATA || $cache_data == UCACHE_DATA)){ 669 670 $memory_limit = "256"; 671 672 ini_set("memory_limit", $memory_limit."M"); 673 674 $ucache_mem_info = wincache_ucache_meminfo(); 675 676 if(is_ucache_under_php_memory_limit($ucache_mem_info, $memory_limit)) 677 $ucache_info = wincache_ucache_info(); 678 679 }
691 function is_ucache_under_php_memory_limit($ucache_mem_info, $memory_limit){ 692 693 return 694 (($ucache_mem_info['memory_total'] - $ucache_mem_info['memory_free']) / 1024) < 695 ($memory_limit - 12) * 1000; 696 }
Mar 24, 2014 05:18 PM|DropPhone|LINK
In task manager (taskmgr), go to the tab that has all the process listed.
rght-click on the php-cgi.exe process, select "create dump file". There will be a dialog that comes up after the dump is written with a path to the dump. It's usually in wherever the %TMP% or %TEMP% direcory is for the current user. The file usually ends in .DMP.
That's it!
Thx!
--E.
Mar 25, 2014 06:09 PM|laurin1|LINK
Happened again today.
There is no way to do that using the manual means as there are way too many (too much downtime) and they keep spawning and hard to track which ones I've dumped.
I did dump a few that were "active." Most of the processes showed 0 CPU usage during this period, but 1 was always spiking at around 25% CPU usage. I dumped several of those. However, we have another problem. I opened those dumps and all have this error message in Visual Studio:
You cannot debug a 64-bit dump of a 32-bit process , you must collect a 32 bit dump of a 32 process
I did, however, watch the Work Set numbers for some of these processes spike to over 700MB!
Mar 25, 2014 06:15 PM|laurin1|LINK
FYI, one of my staff turned me on to these, which I am going to try. The first one will get 32 bit dumps by default.
ProcDump v6.0.
PZenDump: Create Memory Dumps For Multiple Processes In Batch
Mar 26, 2014 10:03 AM|laurin1|LINK
The situation is degrading rapidly. It crashed 5 days ago, then 2 days ago, then yesterday, then this morning and it's starting to fail again right now. We are in serious trouble.
Now, for the really bad news. As it was crashing last time, I was able to pull up wincache.php and Wincache User Cache was only using about 38MB of RAM!!
However, we got several timeouts that referrered to Wincache User Cache get and set lines of code. So we still believe the issue is Wincache, but we no longer believe it's due to high memory usage.
Mar 26, 2014 10:13 AM|laurin1|LINK
I've lowered our User Cache limit to 80 - I have to try something, as it's becoming unusable and our system relies heavily on this.
Strange, once I lowered the value, phpinfo() displays the new value, but wincache.php still displays the old value.
Mar 26, 2014 01:25 PM|laurin1|LINK
All day today we are getting PHP script timeouts (referringt to Wincache User Cache gets and sets) and Working Set Maximums for php-cgi.exe processes are still spiking at ridiculous levels (some over 400MB!!). I've reset IIS several times, and the problem begins to occur again within minutes.
I have at least confirmed that the issue is with Wincache. I have effectively disabled Wincache User Cache and performance is slow but stable.
Mar 27, 2014 12:16 AM|laurin1|LINK
I found an article (old) that states that Wincache User Cache does not behave the way the manual states:
"If the total size of variables stored in the user cache exceeds the specified value, then the most stale variables will be removed from the cache."
That instead of this limit is hit, the next set will fail!
Mar 27, 2014 02:04 PM|DropPhone|LINK
laurin1
I opened those dumps and all have this error message in Visual Studio:
You cannot debug a 64-bit dump of a 32-bit process , you must collect a 32 bit dump of a 32 process
Yeah, you'll need windbg.exe to view these dumps. I think there's a stand-alone part of the Win32 SDK that has just the debugger package (windbg/ntsd/cdb).
In any case, message me privately as to where I can get these dumps, and I'll see what we can see.
I'm assuming you're on the 1.3.5.2 php_wincache.dll, yes?
--E.
Mar 27, 2014 03:58 PM|laurin1|LINK
No, I verified that - you cannot use the Task Manager to save a dump from a 32 bit process, because Task Manager is 64 bit. I was able to get some good dumps using ProcMon.
I'm using the version you sent me via PM yesterday (or 2 days ago, can't remember.)
Mar 28, 2014 02:57 PM|laurin1|LINK
I figured this information might be useful to everyone, Eric, so I'm posting here instead of our private:
So, I was attempting to get dumps from the php-cgi.exe processes when the issue occurred again, which it did today. Because there are so many processes, I wrote a script that grabs all of the PID's and runs procdump on all of these. My attempt today failed, which partially my fault. My first script ran for all instances concurrently - BAD IDEA. Completely locked up my server and was barely able to even restart Windows without having to do a hard restart (power off.) However, after it restarted, and while the server was performing normally, I fixed my script and ran it again, just to test it (ran procdump against one PID at a time.) This worked great....until it was complete. First using dumping these processes causes the memory Working Set Peak number to spike to what appears to be the user cache limit for wincache (ours is set at 1000MB) plus some overhead (the number is about 1.2GB.) This by itself should not be a problem for this machine (24GB of RAM, probably 20GB available.) This in turn creates dump files of about 1.2GB each, but this happens pretty quickly. But what happened next was a the thing that really suprised me.
AFTER this was almost complete, as the last file was being written, the server almost came to a halt. Couldn't open any new windows and explorer.exe was locked up. The web application slowed down, but did not lock up completely.
I was watching Resource Monitor and saw the disk was backing up big time - and it looked like the culprit was Windows Defender! I stopped and disabled Windows Defender service and whala! The server resumed normal behavior (processes dropped Worker Set numbers, everything.)
For some reason, this made me thing about Data Execution Prevention and so I checked the setting for APP01 and for some reason, the DEP was set to "Turn on DEP for all programs and services except those I select: ", with nothing in the box below. This is not the default setting, right (not 100% about that, but I think so)? I checked our failover server (also used to run process scripts), APP02, and APP02 was configured for "Turn on DEP for essential Windows programs and services only."
I configured APP01 for what I consider to the "correct" setting and disabled Windows Defender on both machine.
I'm not saying that either of these settings are the problem, but it sure sounds like one or both of them are (or at least contributing factors.)
45 replies
Last post Mar 28, 2014 02:58 PM by laurin1 | https://forums.iis.net/t/1208026.aspx?Locking+Up+Not+Responding+500+Error | CC-MAIN-2021-43 | refinedweb | 3,032 | 71.04 |
Red Hat Bugzilla – Bug 12101
rpm 3.0.4 portability: statfs test fails on OpenBSD
Last modified: 2008-05-01 11:37:56 EDT
(this bug report will look strange again, as bugzilla is obviously
slanted against portability bugs)
The statfs check fails abysmally on OpenBSD. Thus transaction.c
does not compile.
On OpenBSD, to get struct statfs, one must
#include <sys/param.h>
#include <sys/mount.h>
-> hence STATSFS_IN_SYS_MOUNT_H is never verified.
sys/mount.h alone is not enough. The configure.in comment is right,
rpm should borrow fileutils test or something better.
There's a FreeBSD patch that has been applied since rpm-3.0.4. Will that
also fix this OpenBSD issue?
You're right about fileutils tests.
AFAIK, rpm-4.0 will build on *BSD systems.
Stealing the tests from fileutils is still a good idea, that's were many of the
existing tests
were cribbed in the first place. I suspect that the tests should be made
identical.
Please reopen with a patch. | https://bugzilla.redhat.com/show_bug.cgi?id=12101 | CC-MAIN-2017-04 | refinedweb | 168 | 78.55 |
Test Driven Scaffolding: a new agile method (12 messages)
The next evolution of Test Driven Development. Test Driven Scaffolding (TDS) is an idea I propose to improve development productivity by declaratively generating source code from unit tests by holistically merging the benefits of Test Driven Development with Code Generation. Let me capture your imagination: wouldn't it be really cool if we could write a unit test and then when we run the test, it writes the source (production) code for you so you don't have to write the code? You write the test and it declaratively creates the source code under the hood. Well this is the principle of TDS; making your test cases go the extra mile. Let's get more specific. I am interested using TDS for generating web-based user interfaces with component-based web frameworks like Wicket and Google Web Toolkit. I am not not alone as other people have been looking at ways to devise a way on how to create declarative user interfaces where one does not need to write the UI code. The Google Web Toolkit (GWT) engineers have been experimenting with a way to declaratively create GWT web applications but its declarative model is XML - given it is isomorphic to an Abstract Syntax Tree (AST). However wouldn't it be more agile if it was declarative created from a test case rather than XML? Let's look on how we can achieve this. I will now show you a simple demonstration of Test Driven Scaffolding to scaffold a GWT web application (user interface) from a test case. Oh, if you are unfamiliar with Google Web Toolkit then going to will provide a good primer. I will show you the test case, see its output and then look under the hood. Ok, lets start with the test case: import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Button; public class HelloWorldGWTApplicationTestCase { public static void main(String[] args) { final File input = new File("/path/to/template/folder/"); output = new File("/path/to/src/folder/"+applicationName+".java"); final GWTScaffoldTestCase gwtScaffoldTestCase = new GWTScaffoldTestCase(input, output); gwtScaffoldTestCase.assertApplicationName(applicationName); gwtScaffoldTestCase.assertGWTWidget(DecoratorPanel.class); gwtScaffoldTestCase.assertGWTWidget(Label.class); gwtScaffoldTestCase.assertGWTWidget(TextBox.class); gwtScaffoldTestCase.assertGWTWidget(Button.class); gwtScaffoldTestCase.run(); } } If we run this test case then it outputs the following file: import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Button; public class HelloWorld implements EntryPoint { private Label label = new Label(); private TextBox textbox = new TextBox(); private Button button = new Button(); public void onModuleLoad() { RootPanel.get().add(label); RootPanel.get().add(textbox); RootPanel.get().add(button); } } Lets go over what has been written in the test case and its output. After we have talked about what's been written in the test, I will show what's underneath the hood. The HelloWorldGWTApplicationTestCase class instantiates a GWTScaffoldTestCase object and makes several calls to its assertGWTWidget() method passing several Widget (Component) classes, followed by run(). Specifically after the object is instantiated it calls its assertApplicationName passing a String argument - the GWT module name. The next three lines call the assertGWTWidget() method which passes in three GWT widgets. We now are asserting a GWT widget hierarchy which looks like the following. 1.0 RootPanel 1.1 Label 1.2 TextBox 1.3 Button From writing the test case we have killed two birds with one stone as we have written our test case first and when we run it, it writes the foundational structure of our Hello World GWT application. This really promotes developers, more than ever before, to write tests before writing production code as they get a treat for doing it ;-) Your development team will be classically conditioned that if they write tests then they know they get the treat - the foundation structure of their code. Underneath the hood it uses an ontological model to create the output - a template engine. The template engine I used is FreeMarker. The code for GWTScaffoldTestCase is show below: import java.util.*; import java.io.*; import com.google.gwt.user.client.ui.Widget; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; public final class GWTScaffoldTestCase { private final Map root = new HashMap(); private final List widgets = new ArrayList(); private final List imports = new ArrayList(); private final Configuration cfg = new Configuration(); private final File input, output; private Template template; public GWTScaffoldTestCase(File input, File output) { this.input = input; this.output = output; root.put("widgets", widgets); root.put("imports", imports); try { cfg.setDirectoryForTemplateLoading(this.input); template = cfg.getTemplate("test.ftl"); } catch (IOException e) { //Do something with the exception } cfg.setObjectWrapper(new DefaultObjectWrapper()); } public final void assertApplicationName(String name) { root.put("name", name); } public final void assertGWTWidget(Class<!--? extends Widget--> clazz) { widgets.add(new GWTComponent(clazz.getSimpleName())); imports.add(clazz.getName()); return this; } public final void run() { try { Writer out = new OutputStreamWriter(new FileOutputStream(output)); template.process(root, out); out.flush(); } catch (Exception e) { //Do something with the exception } } } The FreeMarker template looks like: import com.google.gwt.core.client.EntryPoint; import com.google.gwt.user.client.ui.RootPanel; <#list imports as import> import ${import}; <!--#list--> public class ${name} implements EntryPoint { <#list widgets as widget> private ${widget.className} ${widget.variableName} = new ${widget.className}(); <!--#list--> public void onModuleLoad() { <#list widgets as widget> RootPanel.get().add(${widget.variableName}); <!--#list--> } } I argue that Test Driven Scaffolding is superior to the scaffolding features of, for example, the Ruby on Rails (RoR) web application framework. RoR's scaffold features are not driven from tests but from a script which generates the necessary files where TDS is driven purely from a test case and provides a richer declarative model in a more agile manner. However, this example is just a basic, primitive example as is not able to cope with component composition (where components are nested), asserting event handling, multiple instances of the same component class nor provides post scaffold preservation (ensuring the asserted component hierarchy is preserved if the hierarchy has been modified). I will leave how one could get around this primitive example's limitation as a thought experiment. James Perry is a software developer special specializing in Nature Inspired Computational Intelligence using Google Web Toolkit, Wicket and deploying applications to Google App Engine. To find out more about myself visit my newly created site:
- Posted by: James Perry
- Posted on: September 02 2009 10:09 EDT
Threaded Messages (12)
- Re: Test Driven Scaffolding: a new agile method by Istvan Soos on September 02 2009 17:52 EDT
- Re: Test Driven Scaffolding: a new agile method by James Perry on September 02 2009 22:25 EDT
- Re: Test Driven Scaffolding: a new agile method by Andy Key on September 07 2009 16:34 EDT
- Good idea : what does is it do more than what Eclipse does by Boni Gopalan on September 04 2009 01:49 EDT
- Good question by James Perry on September 04 2009 11:10 EDT
- writing only tests == writing only code by Amin Mansuri on September 04 2009 17:14 EDT
- Re: writing only tests == writing only code by Senthil Balakrishnan on September 06 2009 06:45 EDT
- Deduction vs Induction by Charles Abreu on September 06 2009 20:49 EDT
- Re: Deduction vs Induction by Charles Abreu on September 06 2009 20:59 EDT
- Not enough information by Bruce Atherton on September 07 2009 01:27 EDT
- Re: Test Driven Scaffolding: a new agile method by Albert Mendonca on September 16 2009 19:53 EDT
- Re: Test Driven Scaffolding: a new agile method by Sergiu Rata on September 19 2009 17:14 EDT
Re: Test Driven Scaffolding: a new agile method[ Go to top ]
Interesting. Not sure however if this can be done with reasonable effort.
- Posted by: Istvan Soos
- Posted on: September 02 2009 17:52 EDT
- in response to James Perry
Re: Test Driven Scaffolding: a new agile method[ Go to top ]
Please feel free to elaborate. IMO it's achievable as the ontological model (template engine) is deterministic as you program the relevant logic to produce the test driven scaffold. However I am not sure if it is achievable in a non deterministic approach using only a heuristic; which would provide great agility as it wouldn't need maintenance when your favourite web framework's API changes.
- Posted by: James Perry
- Posted on: September 02 2009 22:25 EDT
- in response to Istvan Soos
Re: Test Driven Scaffolding: a new agile method[ Go to top ]
I don't really see how this would reduce the amount of code you're actually writing. Either you write test cases that are sufficient to handle literally all possible inputs and scenarios, plus sufficiently intelligent templates to process all of the test cases, or it won't work. And so you basically end up with two complete implementations of your code - the tests that were used to generate, plus the code itself. And heaven forbid you need to change your test cases and regenerate the code 6 months into a project. All in all the effort is going to far outweigh any benefits.
- Posted by: Andy Key
- Posted on: September 07 2009 16:34 EDT
- in response to Istvan Soos
Good idea : what does is it do more than what Eclipse does[ Go to top ]
Let us take the classic TDD use case where developer writes test case first. At the end of the exercise the test case will be a non compiling class. For example : class FooTest{ public void testCreateFoo(){ Foo myFoo = new Foo("simpleFoo"); assertNotNull(myFoo); } public void testMakeFooSayHello(){ Foo myFoo = new Foo("simpleFoo"); assertNotNull(myFoo); String greeting = null; assertNotNull(greeting = myFoo.getGreeting()); assertTrue("Hello".equals(greeting)); } } Once this code is written to the eclipse ide, eclipse helps me create the perfect scaffold for Foo by giving intuitive options for creating Foo in the appropriate package, adding a constructor that accepts a string, and adding a getGreeting() method. This is a simpler example but the code helper feature has lot more powerful helpers to complete an outline. Now, I am perfectly sure that I am not the only one who knows this and there are thousands of developers write code this way. And I am sure James Perry knows this feature and much more. So can you please help me understand what am I missing here?, Why would we reinvent a wheel?
- Posted by: Boni Gopalan
- Posted on: September 04 2009 01:49 EDT
- in response to James Perry
Good question[ Go to top ]
B_G, A great question and I hope my answer provides clarification. You are totally correct that the Eclipse IDE provides code generation features which are similar (as they use the ontological model) but there are subtle differences. Let me explain in more detail. In your code, you're correct that Eclipse will assist in generating the code with the needed constructor and with the getGreeting method but without an implementation of the method. It's fundamentally like an eclipse helper but with more sophistication. AFAIK, specifically most of the Eclipse helper will only generate enough code so it can compile your test case where Test Driven Scaffolding-based helper does more. The Eclipse IDE helpers use the same ontological model so I could create a Eclipse helper to provide the features of TDS; so your argument that I am re-invented the wheel is fundamentally sound but I would say I am evolving the code generation wheel. For example, can Eclipse create me a GWT or Wicket application from my test case? No it wouldn't as it wouldn't know how to create the widget (component) hierarchy, what level a widget is should be in nor assert if my widget hierarchy has been accidentally changed (post verification) after it generated the source code. Another example: if i wanted to write a test case for a servlet to ensure in my doGet() method that I retrieve a request parameter as a long, say using something like assertGetRequestParamAsLong("id"), Eclipse doesn't have a helper to create such code to retrieve the request parameter and to treat it as a long. So to summarize, yes it is exactly like the Eclipse IDE helpers, but with more sophistication. If I get the time I might write my TDS code as an eclipse helper. Cheers, James.
- Posted by: James Perry
- Posted on: September 04 2009 11:10 EDT
- in response to Boni Gopalan
writing only tests == writing only code[ Go to top ]
If you only write the tests, then there's no cross-control on your code and the generated code will only be as good as your "tests are". The key in TDD is that you write a test, then you write the code, and the two need to agree. In your idea, the tests ARE the code, and would then require separate testing. What you've done is no more than change the programming paradigm, but you haven't gotten a more reliable solution. You've only changed the representation. This has already been attempted in languages such as Prolog. Where you write the rules for the program, and the language "writes the program for you". However, though the code in Prolog is often more succint than the Java equivalent it isn't necessarily easier, and it isn't necessarily better. Representing UI code in a declarative manner like HTML or as in old style Windows programming.. and yes even like the newer (uglier) XML representations has its advantages as long as you get to write less code. The main benefit is that the declared UI is simpler to reason about that lines and lines of imperative code. Your testing idea doesn't really reduce the code size, and it doesn't seem to increase reliability. So I don't see the point. (But maybe I just don't get it)
- Posted by: Amin Mansuri
- Posted on: September 04 2009 17:14 EDT
- in response to James Perry
Re: writing only tests == writing only code[ Go to top ]
Hi James, 1. I do believe, it should be possible to create a source code from a set of test cases, provided the test case is complete and has all the necessary scenarios captured. 2. But in a complicated application development,one would have so much of scripting to do which could highly complicate the generation process and need to have developer interventions to correct it. 3. Also, TDS would work better for GWT based application, may not work for other frameworks(which uses no java class for UI representation). Your views. Thanks, Senthil Balakrishnan
- Posted by: Senthil Balakrishnan
- Posted on: September 06 2009 06:45 EDT
- in response to Amin Mansuri
Deduction vs Induction[ Go to top ]
My view is that, when programming, one goes from specific examples to general concepts. It is an inductive, synthesis task. In testing, on the other hand, one goes from generic concept to specific examples. It is a deductive, analysis task. There is no sense in fully defining a concept by testing it, as much as there is no sense in testing a concept by defining it. These are complementary tasks.
- Posted by: Charles Abreu
- Posted on: September 06 2009 20:49 EDT
- in response to James Perry
Re: Deduction vs Induction[ Go to top ]
And that said, I don't see how could your tests generated program be capable of handling other (more general) situations than that given by the written tests.
- Posted by: Charles Abreu
- Posted on: September 06 2009 20:59 EDT
- in response to Charles Abreu
Not enough information[ Go to top ]
I would love to make it easier to keep tests and code in sync, but I think your idea misses an important point: there is not enough information in a test case to be able to provide an implementation. The test class given by Boni Gopalan is a perfect example. getGreeting() returns "Hello", but where does it get it from? Does it load it from a database? Compute it from an encrypted string? Get it as input from the user? Concatenate it from some other strings? Who knows? In order to provide enough detail in the test case to have that information, you will basically be writing an implementation anyway. Even your example with the GWT is flawed. You are providing some boilerplate implementation, but is that the whole implementation of the method? Probably not. Is the boilerplate even correct? Perhaps there are customized subclasses of the Google widgets that are being used. There won't be an assertMyCustomLabelWidget() method in the test framework, so I'd have to stick to the test for a plain Label even though that is not what I will use in the implementation. I could see an argument being made about going the other way but I think that would be a bad idea as well, except perhaps for bootstrapping unit tests on legacy code. Tests and implementations have fundamentally different focuses, and I think trying to mix the two just makes a mess.
- Posted by: Bruce Atherton
- Posted on: September 07 2009 01:27 EDT
- in response to James Perry
Re: Test Driven Scaffolding: a new agile method[ Go to top ]
The idea is definitely creative, but seems amateur.
- Posted by: Albert Mendonca
- Posted on: September 16 2009 19:53 EDT
- in response to James Perry
Re: Test Driven Scaffolding: a new agile method[ Go to top ]
It won't work for the general case. The way I see tests in TDD is that they serve as some sort of requirements for the program. That's why you write them first: I want the program to do this and that. Then you write the implementation that would fulfill your requirements. And then the cycle repeats. What you are advocating is basically to let the developer write only the requirements and the computer somehow will come up with the implementation. Well, I don't think there's such technology today (this is definitely going in the realm of Artificial Intelligence), that's why I fundamentally think that it will not work. Now supposedly that we do find a domain where this might be useful, or where this approach will work. In this case I don't think you care about the implementation, or that you should be changing it. Because the moment the requirements change, or new ones go in effect you will have to write new test cases that will (re)generate the implementation. How will it know how to reconcile the new implementation with your changes? So in essence then your testcases become the new source code. And boy, they surely will need to be tested. What, test the testcases? Yes, because the way I see there are multiple logical what/how levels. The first level is probably at the business level: the business person will state "what" he wants to do, some architect will come up with the high-level solution (the "how"). Then the architect's output will be the "what" input to a development team that will come up with the more detailed design - the "how". In the end an individual developer will write the specific "what" using TDD and then the resulting implementation will be the "how". So you see that TDD is helping only at the lowest level, and to help with the other levels - that's where all these proliferated ALM solutions come in place.
- Posted by: Sergiu Rata
- Posted on: September 19 2009 17:14 EDT
- in response to James Perry | http://www.theserverside.com/discussions/thread.tss?thread_id=57443 | CC-MAIN-2015-35 | refinedweb | 3,282 | 51.68 |
*current inside the function */
boolean Test::processLine(char *line, obj *list, obj **current) {
bool result = false;
if (*current != 0) {
if (strstr(line, *current->end) != NULL) {
*current = 0;
result = false;
}
else
result = true;
}
/* and so on */
...
}//end processLine
/* call it by using & */
void Test::main(char * filename) {
char _line[80];
obj *head = 0;
obj *curr_obj = 0;
bool inSection = false;
...
inSection = processLine(_line, head, &curr_obj);
if (curr_obj != 0) {
...
}
}
This is the better solution.
// Add & on current
// don't change anything else
boolean Test::processLine(char *line, obj *list, obj* & current) {
...
}
Experts Exchange Solution brought to you by
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial
The variable curr_obj defined in the main function remains 0 after calling the processLine function because the function receives a copy of a value of the curr_obj as the argument current. Therefore you can not change the value of curr_obj in the main through the current in the processLine. In general, this calling method is called as "call by value".
You can change the curr_obj in the processLine by using "call by reference". For that purpose, use a pointer or reference to the variable.
Using reference, processLine can be defined as follows:
boolean Test::processLine(...., obj*& current){
...
}
Now the current is an alias of the curr_obj, you can change the curr_obj's value through it and no other modifications are required for the codes. A notation "type& ref" declares ref as a reference to a variable of the type.
Using pointer, processLine can be defined as follows:
boolean Test::processLine(...., obj** current) {
...
}
In this case, the current points to curr_obj and you can change the curr_obj's value through the pointer. But you need to change the notation of the current to *current in the processLine and the processLine(...., curr_obj) to processLine(...., &curr_obj) in the main.
You can use whichever of reference and pointer as your preference. Using pointer is my preference because it makes clear that the function modifies the pointed object.
Here's a sample code:
#include <iostream>
#include <string>
//call by value
void f(std::string s){
s = "f";
}
//call by reference using a reference
void g(std::string& s){
s = "g";
}
//call by reference using a pointer
void h(std::string* s){
*s = "h";
}
int main(){
std::string s = "original value";
f(s);
std::cout << "s = " << s << " after f(s) was called.\n";
g(s);
std::cout << "s = " << s << " after g(s) was called.\n";
h(&s);
std::cout << "s = " << s << " after h(&s) was called.\n";
return 0;
}
Sample code output:
s = original value after f(s) was called.
s = g after g(s) was called.
s = h after h(&s) was called.
Hope this helps.
This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.
I was too lazy :)
Yukapapa - thank you for the thorough explanation.
I will accept Kocil's comment as the answer AND I will post a request to have Yukapapa awarded 250 since the comment was so informative.
Thanks again everyone!
apatia,
Here's what you do now:
1. In this topic area, ask a new question worth 250 points entitled "For yukapapa re: 20547103" and put the URL to this question in the body.
2. Come back to this question and accept the comment of Kocil as an answer. Leave a comment that directs yukapapa to the "points for" question.
3. When yukapapa comments in the new question, accept that as an answer.
That should take care of you.
Netminder
EE Admin
one '&' worth 250 point !
Thanks man, and give me and A please.
for points please see the following question: | https://www.experts-exchange.com/questions/20547103/Problem-maintaining-pointer-assignment.html | CC-MAIN-2018-30 | refinedweb | 630 | 75.1 |
Facebook SDK 4.x versions have a different method now:
boolean loggedIn = AccessToken.getCurrentAccessToken() != null;
or
by using functions
boolean loggedIn; //... loggedIn = isFacebookLoggedIn(); //... public boolean isFacebookLoggedIn(){ return AccessToken.getCurrentAccessToken() != null; }
Check this link for better reference
check this heading too “Access Tokens and Profiles” it says “You can see if a person is already logged in by checking AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile()
I struggled to find a simple answer to this in the FB docs. Using the Facebook SDK version 3.0 I think there are two ways to check if a user is logged in.
1) Use
Session.isOpened()
To use this method you need to retrieve the active session with
getActiveSession() and then (here’s the confusing part) decipher if the session is in a state where the user is logged in or not. I think the only thing that matters for a logged in user is if the session
isOpened(). So if the session is not
null and it is open then the user is logged in. In all other cases the user is logged out (keep in mind
Session can have states other than opened and closed).
public boolean isLoggedIn() { Session session = Session.getActiveSession(); return (session != null && session.isOpened()); }
There’s another way to write this function, detailed in this answer, but I’m not sure which approach is more clear or “best practice”.
2) Constantly monitor status changes with
Session.StatusCallback and
UiLifecycleHelper
If you follow this tutorial you’ll setup the
UiLifecycleHelper and register a
Session.StatusCallback object with it upon instantiation. There’s a callback method,
call(), which you override in
Session.StatusCallback which will supposedly be called anytime the user logs in/out. Within that method maybe you can keep track of whether the user is logged in or not. Maybe something like this:
private boolean isLoggedIn = false; // by default assume not logged in private Session.StatusCallback callback = new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { if (state.isOpened()) { //note: I think session.isOpened() is the same isLoggedIn = true; } else if (state.isClosed()) { isLoggedIn = false; } } }; public boolean isLoggedIn() { return isLoggedIn; }
I think method 1 is simpler and probably the better choice.
As a side note can anyone shed light on why the tutorial likes to call
state.isOpened() instead of
session.isOpened() since both seem to be interchangeable (
session.isOpened() seems to just call through to the
state version anyway).
Note to readers: This is now deprecated in the new FB 3.0 SDK.
facebook.isSessionValid() returns true if user is logged in, false if not. | https://codeutility.org/android-facebook-sdk-check-if-the-user-is-logged-in-or-not/ | CC-MAIN-2021-43 | refinedweb | 430 | 68.26 |
Using Synchronization, you can synchronize access to resources in multithreaded applications.
A mutex can be used to synchronize threads across processes Use it to prevent the simultaneous execution of a block of code by more than one thread at a time.
C# lock statement is used to ensure that a block of code runs without interruption by other threads. A Mutual-exclusion lock is obtained for a given object for the duration of the code block.
Thread pool in C# is a collection of threads. It is used to perform tasks in the background. When a thread completes a task, it is sent to the queue wherein all the waiting threads are present. This is done so that it can be reused.
Let us see how to create a thread pool.
Firstly, use the following namespace −
using System.Threading;
Now, call the threadpool class, using the threadpool object. Call the method QueueUserWorkItem.
ThreadPool.QueueUserWorkItem(new WaitCallback(Run));
The Mutex class in C# is a synchronization primitive that can also be used for interprocess synchronization.
Let us see how to create a new Mutex −
private static Mutex m = new Mutex(); | https://www.tutorialspoint.com/Threads-and-Thread-Synchronization-in-Chash | CC-MAIN-2021-49 | refinedweb | 189 | 66.64 |
-- ) import qualified Control.Exception run :: FilePath -> String -> (String -> String) -> IO String run binary src scrub = do (out,err,_) <- popen binary [] (Just src) let o = scrub out e = scrub err return $ case () of {_ | null o && null e -> "Done." | null o -> e | otherwise -> o } -- -- Ignoring exit status for now. -- -- You have to ignore SIGPIPE, otherwise popening a non-existing executable -- will result in an attempt to write to a closed pipe and crash the wholw -- program. -- -- XXX there are still issues. Large amounts of output can cause what -- seems to be a dead lock on the pipe write from runplugs, for example. -- Posix.popen doesn't have this problem, so maybe we can reproduce its -- pipe handling somehow. -- | popen lets you run a binary with specified arguments. This bypasses the shell. popen :: FilePath -- ^ The binary to execute -> [String] -- ^ A list of arguments to pass to the binary. No need to -- space separate them -> Maybe String -- ^ stdin -> forkIO (Control.Exception.evaluate (length output) >> putMVar outMVar ()) forkIO (Control.Exception.evaluate (length errput) >> putMVar errMVar ()) takeMVar outMVar takeMVar errMVar -- And now we wait. We must wait after we read, unsurprisingly. -- blocks without -threaded, you're warned. -- and maybe the process has already completed.. e <- Control.Exception.catch (waitForProcess pid) (\_ -> return ExitSuccess) return (output,errput,e) | http://hackage.haskell.org/package/lambdabot-utils-4.2/docs/src/Lambdabot-Process.html | CC-MAIN-2016-44 | refinedweb | 213 | 59.7 |
#include <assert.h>
#include <errno.h>
#include <stdbool.h>
#include <string.h>
#include <inttypes.h>
#include <fcntl.h>
#include "nvim/vim.h"
#include "nvim/ascii.h"
#include "nvim/fileio.h"
#include "nvim/buffer.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/diff.h"
#include "nvim/edit.h"
#include "nvim/eval.h"
#include "nvim/ex_cmds.h"
#include "nvim/ex_docmd.h"
#include "nvim/ex_eval.h"
#include "nvim/fold.h"
#include "nvim/func_attr.h"
#include "nvim/getchar.h"
#include "nvim/hashtab.h"
#include "nvim/iconv.h"
#include "nvim/mbyte.h"
#include "nvim/memfile.h"
#include "nvim/memline.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/misc1.h"
#include "nvim/garray.h"
#include "nvim/move.h"
#include "nvim/normal.h"
#include "nvim/option.h"
#include "nvim/os_unix.h"
#include "nvim/path.h"
#include "nvim/quickfix.h"
#include "nvim/regexp.h"
#include "nvim/screen.h"
#include "nvim/search.h"
#include "nvim/sha256.h"
#include "nvim/state.h"
#include "nvim/strings.h"
#include "nvim/ui.h"
#include "nvim/types.h"
#include "nvim/undo.h"
#include "nvim/window.h"
#include "nvim/shada.h"
#include "nvim/os/os.h"
#include "nvim/os/os_defs.h"
#include "nvim/os/time.h"
#include "nvim/os/input.h"
Struct used to keep status while executing autocommands for an event.
Execute autocommands for "event" and file name "fname".
Like apply_autocmds(), but handles the caller's retval. If the script processing is being aborted or if retval is FAIL when inside a try conditional, no autocommands are executed. If otherwise the autocommands cause the script to be aborted, retval is set to FAIL.
Return true if an autocommand is defined for a group, event and pattern: The group can be omitted to accept any group.
event and
pattern can be omitted to accept any event and pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted. Used for: exists("#Group") or exists("#Group#Event") or exists("#Group#Event#pat") or exists("#Event") or exists("#Event#pat")
Return true if augroup "name" exists.
Cleanup after executing autocommands for a (hidden) buffer. Restore the window as it was (if possible).
Check whether given autocommand is supported
Check *argp for <nomodeline>. When it is present return false, otherwise return true and advance *argp to after it. Thus do_modelines() should be called when true is returned.
Delete "name" and everything in it, recursively.
":augroup {name}".
Convert the given pattern "pat" which has shell style wildcards in it, into a regular expression, and return the result in allocated memory. If there is a directory path separator to be matched, then TRUE is put in allow_dirs, otherwise FALSE is put there – webb. Handle backslashes before special characters, like "\*" and "\ ".
Returns NULL on failure.
Read 2 bytes from "fd" and turn them into an int, MSB first. Returns -1 when encountering EOF.
Read 3 bytes from "fd" and turn them into an int, MSB first. Returns -1 when encountering EOF.
Read 4 bytes from "fd" and turn them into an int, MSB first. Returns -1 when encountering EOF.
Read 8 bytes from
fd and turn them into a time_t, MSB first. Returns -1 when encountering EOF.
Return true if there is a matching autocommand for "fname". To account for buffer-local autocommands, function needs to know in which buffer the file will be opened.
Return true when there is a CursorHold/CursorHoldI autocommand defined for the current mode.
Return true if "event" autocommand is defined.
Check if a file matches with a pattern in "list". "list" is a comma-separated list of patterns, like 'wildignore'. "sfname" is the short file name or NULL, "ffname" the long file name.
Get new filename ended by given extension.
Writes a number to file "fd", most significant bit first, in "len" bytes.
Writes time_t to file "fd" in 8 bytes.
Reads a string of length "cnt" from "fd" into allocated memory.
Shorten filename of a buffer. When "force" is TRUE: Use full path from now on for files currently being edited, both for file name and swap file name. Try to shorten the file names a bit, if safe to do so. When "force" is FALSE: Only try to shorten absolute file names. For buffers that have buftype "nofile" or "scratch": never change the file name.
Return true if the CursorHold/CursorHoldI event can be triggered.
Delete the temp directory and all files it contains.
Like fgets(), but if the file line is too long, it is truncated and the rest of the line is thrown away.
Get the name of temp directory. This directory would be created on the first call to this function.
os_rename() only works if both files are on the same file system, this function will (attempts to?) copy the file across if rename fails – webb
Return a unique name that can be used for a temp file. | https://neovim.io/doc/dev/fileio_8c.html | CC-MAIN-2019-13 | refinedweb | 803 | 72.93 |
In the game development cycle, Quality Assurance and testing can be tedious and time consuming. Because of this, these tasks are all too often delayed for small studios. Things like
critical bug fixes or new features typically take a higher priority and time is not consistently spent on automated testing solutions.
That said, every so often a bug gets leaked into a release or a mysterious compile error crops up in the main code repository, making the need for testing clear again. To mitigate these risks, teams will typically perform unit testing with tools like nUnit or Google Test. However, additional steps are required to execute Unity specific code and tests through an automated process.
Having a programmatic way of integrating testing tools with Unity can benefit teams greatly by offloading repetitive tasks like build releases or running unit tests on an automated system. Luckily Unity has an often overlooked feature: its command line toolset. This is available on all supported Unity editor platforms, including the Unity Linux beta. By using the command line toolset, teams can automate events like builds and unit testing.
For our team at KinematicSoup, we chose to use Unity’s command line as it provided us with the flexibility we needed. In our case, when we learned that Unity for Linux supported the command line toolset, we wanted to be able to migrate our deployment and build systems to Linux. To do this, we needed the Windows deployment and asset bundle builder tools we built for our current system to work on Linux in the future. The command line toolset in Unity allowed us to do this, and here’s how:
Using Command Line methods
The basic format of invoking Unity command line methods is to call the Unity editor application followed by the command line options: “/Unity.exe ”. In order to do this you will need to know the paths of the installation locations for Unity. The default Unity install locations for Windows, Mac and Linux are as follows:
Windows: C:Program FilesUnityEditorUnity.exe
OSX: /Applications/Unity/Unity.app/Contents/MacOS/Unity
Linux: /opt/Unity/Editor/Unity
Before we discuss how to run custom classes and methods through the command line, let’s briefly review the built in Unity command line options. The built in functions allow you to do things like build an asset package or build a targeted release. The following list is an excerpt from the full documentation
.
-batchmode –
this should always be present when calling Unity from the command line, it lets Unity know not to open pop ups.
-nographics –
tells Unity to not load any GUI or windows. Unfortunately Unity will still load the Direct X frameworks which will throw errors on systems without graphics capabilities. For example, a headless Linux build machine. We will discuss a work around for this later in the blog.
-projectPath –
opens the Unity project at the specified path. This will likely also be used every time.
-logFile –
Unity will redirect the log output to this file. This is really useful for builds and debugging.
-buildWindows64Player –
builds a win64 version of your project.
-importPackage –
imports the package at the given location.
-exportPackage –
exports the assets at into an asset bundle at the location and name of .
Invoking Custom Methods
The Unity command line functions are often not enough to complete required tasks, which is where the ability to invoke custom methods becomes very helpful. The syntax to call a custom Unity method is as follows:
/unity.exe ... -projectPath -exit -batchmode -executeMethod
Where parameter1 through parameterN are strings to pass into your Unity method.
This can be used to call a public static method where the script is saved in an “Editor” folder (resides in a folder in the assets directory with the name “Editor”). Below is an example of a generic C# class that could be called from the command line.
using UnityEngine; using UnityEditor; using System; Namespace myNameSpace { class myClass { Public static void myMethod() { string[] params; params = Environment.GetCommandLineArgs(); //DO SOMETHING EditorApplication.Exit(0); } } }
In order to parse the command line parameters that are passed in, the Unity class will need to use the query Environment.GetCommandLineArgs(), which will return a string array of arguments. From here you can do whatever is needed, whether making a web request or incrementing a build.
Special Notes on building with Headless Systems
When running Unity on a headless system you will need some sort of virtual frame buffer. As previously mentioned, the -nographics option will prevent any windows from loading but still loads the DX11 environment. On Linux the fix is quite simple, just use the xvfb package (on Ubuntu open a console and run “sudo apt-get install xvfb”) then append xvfb-run in front of your Unity command. For example:
xvfb-run ../unity/Editor/unity…
This should give you a basic idea of how to use the Unity command line interface and how it can be used integrate automated tests with Unity. As your team grows, more rigorous testing will be a vital part of ensuring smooth production. Utilizing automated testing can greatly decrease the time it takes to test your software, and provides a tool that can be used consistently throughout development. Interfacing these tests with the Unity platform takes this one step further and gives your tests the flexibility and adaptability required for modern game development.
To learn more about what we are working on to help developers build better games and ship them sooner, check out our Unity multi-user scene collaboration tool, Scene Fusion
.
References :
Written by Bob Cao, developer at KinematicSoup. | http://colabug.com/890104.html | CC-MAIN-2017-34 | refinedweb | 932 | 53.81 |
#include <fixed_pool_eastl.h>
Note: This class was previously named fixed_node_pool, but was changed because this name was inconsistent with the other allocators here which ended with _allocator.
Implements a fixed_pool with a given node count, alignment, and alignment offset. fixed_node_allocator is like fixed_pool except it is templated on the node type instead of being a generic allocator. All it does is pass allocations through to the fixed_pool base. This functionality is separate from fixed_pool because there are other uses for fixed_pool.
We template on kNodeSize instead of node_type because the former allows for the two different node_types of the same size to use the same template implementation.
Template parameters: nodeSize The size of the object to allocate. 533 of file fixed_pool_eastl.h.
Note that we are copying x.mpHead to our own fixed_pool. This at first may seem broken, as fixed pools cannot take over ownership of other fixed pools' memory. However, we declare that this copy ctor can only ever be safely called when the user has intentionally pre-seeded the source with the destination pointer. This is somewhat playing with fire, but it allows us to get around chicken-and-egg problems with containers being their own allocators, without incurring any memory costs or extra code costs. There's another reason for this: we very strongly want to avoid full copying of instances of fixed_pool around, especially via the stack. Larger pools won't even be able to fit on many machine's stacks. So this solution is also a mechanism to prevent that situation from existing and being used. Perhaps some day we'll find a more elegant yet costless way around this.
Definition at line 580 of file fixed_pool_eastl.h.
can_allocate
Returns true if there are any free links.
Definition at line 623 of file fixed_pool_eastl.h.
reset
This function unilaterally resets the fixed pool back to a newly initialized state. This is useful for using in tandem with container reset functionality.
Definition at line 634 of file fixed_pool_eastl.h. | http://trilinos.sandia.gov/packages/docs/r10.10/packages/stk/doc/html/classeastl_1_1fixed__node__allocator.html | CC-MAIN-2014-35 | refinedweb | 334 | 57.27 |
Modules
Table of contents
Introduction
A module is a namespace, isolated from other modules. Modules can define
methods, types, or run code directly. Modules can be defined as children of
other modules, in which case you refer to them using the syntax
parent_module::child_module.
Every Inko source file is automatically a module, meaning you don't need to do
anything special to create a module. For source files, the name of the module is
based on the path to the module, relative to the project directory. Every file
path separator (a
/ on Unix systems) is replaced with
::. For example, a
module located in
src/myproject/foo.inko is called
myproject::foo. Currently
there is no official way of defining modules that are not tied to a source file,
but this may be supported in the future.
The methods and types in a module are always public, and there is no way to
declare these as private. If your module relies on certain types or methods that
you don't want to expose as part of the public API, moving these types and/or
methods to a separate module is usually the best solution. For example, the
module
std::fs::file relies on various internals provided by the module
std::fs::raw.
Inside a module scope,
self refers to the module itself:
self # => this will return a module object.
We can use the
ThisModule constant to refer to the module object anywhere
inside the module, even in methods and other types:
self # => the current module def example { ThisModule # => the current module } object Person { def example { ThisModule # => the current module } }
This can be useful if we want to send a message to the module, but the lack of a receiver would conflict:
def example -> Integer { 10 } object Example { def example -> Integer { # If we just send "example" here we would recurse into this method, # overflowing the stack. We can use "ThisModule.example" in this case to # work around this. ThisModule.example } }
Imports
A module on its own is not very useful. Fortunately, one module can import resources from another module, optionally binding them to a different name. Imports can only occur at the top-level of a module, and inside something else such as a method or type.
To import a constant or method, we use the
import keyword like so:
import std::fs::file
Here we imported the module
std::fs::file, and don't specify any symbols to
import. This will result in the module itself being imported, and the module
will be bound to the name
file in the importing module:
import std::fs::file file # => std::fs::file
We can import a specific symbol like so:
import std::fs::file::(ReadOnlyFile)
Here we only import the
ReadOnlyFile constant, exposing it as a constant with
the same name. We can also import multiple constants:
import std::fs::file::(ReadOnlyFile, WriteOnlyFile)
We can also give them a different name:
import std::fs::file::(ReadOnlyFile as File) File # => ReadOnlyFile
We can use
self to refer to the module that we are importing symbols from:
import std::fs::file::(self, ReadOnlyFile) file # => std::fs::file ReadOnlyFile # => ReadOnlyFile
Importing methods work a little bit differently. We can't directly import a method, instead we have to import the module then use it as the receiver when sending messages:
import std::fs::file file.read_only('README.md')
Imports are always processed before executing any code in a module, even when code is placed before an import. This means that this:
import std::stdio::stdout stdout.print('hello') import std::fs::file
Is executed as follows:
import std::stdio::stdout import std::fs::file stdout.print('hello')
When importing a symbol that already exists, an error will be produced by the compiler.
Module variables
Module variables are variables that look like local variables, but are available in any scope inside the module. Symbols imported from another module are all defined as module variables in the importing module, allowing you to use them anywhere.
Any constant defined at the top-level of a module is automatically also a module variable:
let NUMBER = 10 object Person { def number -> Integer { NUMBER } } Person.new.number # => 10
When assigning a value to a module variable, the variable will be assigned a copy of the value. This is because module variables are stored on a separate heap, instead of a process' local heap. | https://inko-lang.org/manual/getting-started/modules/ | CC-MAIN-2018-51 | refinedweb | 731 | 50.16 |
Now I realize that having global state (particularly of the mutable variety) is a bad idea, but I've had difficulties in the past getting around it for some applications.
Some time ago I had this problem with logging, but I've gotten around to the idea of just using a free function, because logging doesn't really require any kind of persistent state. Now I have a new problem, and it's logging's ornery younger brother: debug printing.
Here's what I'm using now:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Foo { public static class DebugPrinter { private static StringBuilder debugString = new StringBuilder(); private static List<string> idList = new List<string>(); [Conditional("DEBUG")] public static void RegisterString(String str, String id) { if (!idList.Contains(id)) { debugString.Append(str).AppendLine(); idList.Add(id); } } [Conditional("DEBUG")] public static void Flush() { debugString.Clear(); idList.Clear(); } [Conditional("DEBUG")] public static string getString() { return debugString.ToString(); } } }
Usage is pretty clear: whatever class wants to write to it calls registerString(passing an id, because I'm using the sharpDX toolkit and update and draw aren't synchronized with each other) and the reader calls getString, followed by flush, then renders the string to the screen.
Now, if you feel the urge to stab me in the eye for this, I fully accept that. It's probably the nastiest thing in my whole code base. I just can't think of a way around it. I can't use a free function because I need to mantain state between draw calls. I could make some heavyweight scaffolding around deep dependency-passing down my state hierarchy.
I'm aware that it's kind of one of those leading sorts of questions(how do I keep all this shared global state without any shared global state), but it's also a design problem I don't know any other solution for.
Edited by SeraphLance, 24 September 2013 - 04:56 PM. | https://www.gamedev.net/topic/648211-how-to-avoid-global-state-here/?setlanguage=1&langurlbits=topic/648211-how-to-avoid-global-state-here/&langid=1 | CC-MAIN-2017-17 | refinedweb | 329 | 54.22 |
Subject: Re: [boost] [afio] Formal review of Boost.AFIO
From: Thomas Heller (thom.heller_at_[hidden])
Date: 2015-08-29 16:30:16
On 08/29/2015 02:05 AM, Niall Douglas wrote:
> On 28 Aug 2015 at 10:16, Thomas Heller wrote:
>
>> I took the effort to also reimplement your hello world example:
>>
>
> Firstly thank you very much for your gist. This makes it much easier
> to understand what you are talking about.
>
> My very first thought was that you are using reference capturing
> lambdas in a concurrent use case which may be fine in internal
> implementation, but is a serious no-no to ever place upon a library's
> end users. People regularly get waits and wakeups wrong, and I have
> seen code bases wrecked by memory corruption and race conditions
> induced by reference capturing lambdas used in concurrent situations.
All true. This contrived example is not really concurrent though, but
whatever. Please, stop treating your users as they wouldn't know what
they do.
>
> For me this is an absolute red line which cannot be crossed. I will
> never, *ever* agree to a library API design which makes end users
> even feel tempted to use reference capturing semantics in a
> concurrency context. Period. They are banned as they are nuclear
> bombs in the hands of the typical C++ programmer.
Sure, whatever, this is just derailing ... You do realize though that
you demote your users library to idiots not knowing what they do?
Despite promoting your library as something very niche only used by experts?
This is by giving up your own promoted "Don't pay for what you don't
use" principle. But let's move on...
>
> So let's replace all your reference captures with shared_ptr or value
> captures and thereby making them safe. I have forked your gist with
> these changes to:
>
>
>
> As I mentioned earlier, any of the AFIO async_* free functions just
> expand into a future.then(detail::async_*) continuation which is
> exactly what you've written. So let me collapse those for you:
>
>
Where does error handling happen here? How would the user react to
errors? What does depends do (not really clear from the documentation)?
How do I handle more than one "precondition"? How do I handle
"preconditions" which have nothing to do with file I/O?
Which ultimately leads me to the question: Why not just let the user
standard wait composure mechanisms and let the functions have arguments
that they really operate on?
All questions would have a simple answer then.
NB: I am still not sure what afio::future<>::then really implies, does
it invalidate the future now? When will the continuation be executed,
when the handler future is ready or when the "value" future is ready?
What does that mean for my precondition?
>
> This is almost identical to my second preference API for AFIO, and
> the one Gavin Lambert suggested in another thread.
>
> As I mentioned in that thread with Gavin, I have no problem at all
> with this API design apart from the fact you need to type a lot of
> depends() and I suspect it will be a source of unenforced programmer
> error. I feel the AFIO API as submitted has a nice default behaviour
> which makes it easy to follow the logic being implemented. Any
> depends() which is a formal announcement that we are departing from
> the default stand out like a sore thumb which draws the eye to giving
> it special attention as there is a fork in the default logic.
That's exactly the problem: You have a default logic for something that
isn't really necessary, IMHO. The async operation isn't an operation on
the future, but on the handle. And to repeat myself: That's my problem
with that design decision.
>
> Under your API instead, sure you get unique futures and shared
> futures and that's all very nice and everything. But what does the
> end user gain from it?
1. Clear expression of intent
2. Usage of standard utilities for wait composures
3. Transparent error handling
4. "Don't pay for something you don't use"
> They see a lot more verbiage on the screen. They find it harder to
> follow the flow of the logic of the operations and therefore spot
> bugs or maintain the logic.
Verbosity isn't always a bad thing. Instead of trying to guess what is
the best default for your users stop treating them as they would not
know what they do.
> I am seeing lots of losses and few gains here apart from meeting some supposed design
> principle about single responsibility which in my opinion is a useful
> rule of thumb for inexperienced programmers, but past that isn't
> particularly important.
You do realize that this is highly contradicting to anything else you
just said in your mail? You claim to have your library designed for the
inexperienced user not knowing what they do, yet your design choice
violates principles that are a nice "rule of thumb for inexperienced
programmers"?
Beside that, single responsibility should *always* be pursued. It makes
your code testable, composable and easier to reason about.
>
> I however am probably being a little unfair here. I reduced your
> original to something AFIO like and something I previously gave deep
> consideration to adopting before rejecting it, and you were probably
> actually advocating that people manually write out all the .then()
> logic instead of using free functions which expand into exactly the
> same thing.
Right, dependency handling is something inherhent to the users code.
Anything you'll come up with inside of your library will be the wrong
thing in some cases and then you'll have a problem.
>
> If you really strongly feel that writing out the logic using .then()
> is very important, I can add that no problem. Right now the
> continuation thunk types live inside a detail namespace, but those
> can be moved to public with very little work.
>
> Niall
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2015/08/225109.php | CC-MAIN-2020-50 | refinedweb | 1,014 | 64 |
Python Namespace and Variable Scope – Local and Global Variables
Free Python course with 25 real-time projects Start Now!!
In this Python Tutorial, we discuss Python Namespace, Types of Namespace in python and Python Variable Scope, with their examples and Python Syntax.
Try this: type ‘import this’ in the interpreter.
>>>!
What is Python Name?
Before we move on to namespaces in python, let’s talk about names in python.
A Python name is an identifier- something we use to access a Python object and in Python, everything’s an object.
We’ll take an example.
>>> rank=1
Here, ‘rank’ is the name associated with the Python object 1. To get this object’s address in RAM, we use the id() function.
>>> id(rank)
Output
>>> id(1)
Output
To take a slightly more complex example, we store 2 in a name ‘a’. Then, we increment it by 1 and associate the name ‘b’ to the object 2. We keep checking the id as we go.
>>> a=2 >>> id(a)
Output
>>> a+=1 >>> id(a)
Output
>>> b=2 >>> id(b)
Output
>>> >>> id(2)
Output
>>> id(3)
Output
So what’s actually happening? We’ll illustrate.
As you can see, when we set ‘a’ to 3 and set ‘b’ to 2, ‘b’ starts pointing to the object ‘a’ once pointed to.
Isn’t that quite efficient? It does not have to create another object to hold 2 for b. This dynamic name binding is powerful.
Also, a name can hold any kind of value.
>>> a=1 >>> a='one'
Finally, since everything is an object, so are Python functions. Consequently, you can associate them with names.
>>> identity=id >>> identity(2)
Output
Here, we associate the name ‘identity’ with the built-in function id().
Bonus Question- Check the following code and figure out what’s happening.
>>> def sayhello(): print('Hello') >>> hi=sayhello()
Output
>>> hi >>> type(hi)
Output
Well, since the function does not return anything, we get an object of class ‘NoneType’.
Of course, None is an object that indicates no value. Did function sayhello() return a value, things would be different.
Let’s take another example.
>>> def func1(): print("Hi") return 1 >>> func2=func1()
Output
>>> func2
Output
>>> type(func2)
Output
What is Python Namespaces?
A namespace in python is a collection of names. So, a namespace is essentially a mapping of names to corresponding objects.
At any instant, different python namespaces can coexist completely isolated- the isolation ensures that there are no name collisions.
Simply speaking, two namespaces in python can have the same name without facing any problem. A namespace is implemented as a Python dictionary.
When we start the interpreter, a python namespace is created for as long as we don’t exist. This holds all built-in names.
It is due to this that python functions like print() and id() are always available. Also, each module creates its own global namespace in python.
When you call a function, a local python namespace is created for all the names in it.
A module has a global namespace. The built-in namespace encloses this.
Take a look at the following figure to get a clearer understanding.
What is Python Variable Scope?
Through various python namespaces, not each can be accessed from every part of the program.
A namespace is in variable scope in a part of a program, if it lets you access the python namespace without having to use a prefix.
At any instant, we have at least three nested python scopes:
- Current function’s variable scope- has local names
- Module’s variable scope- has global names
- The outermost variable scope- has built-in names
This in accordance with the three kinds of namespaces in python, we just discussed. This also decides the order of searching for when a reference is made.
The order is- the local Python namespace, the global namespace, the built-in namespace. Also, a nested function creates a nested variable scope inside the outer function’s scope.
Few Python Namespace Example
To further what we said, let’s take an example.
>>> a=1 >>> def func1(): b=2 def func2(): c=3
In this code, ‘a’ is in the global namespace in python. ‘b’ is in the local namespace of func1, and ‘c’ is in the nested local python namespace of func2.
To func2, ‘c’ is local, ‘b’ is nonlocal, and ‘a’ is global. By nonlocal, we mean it isn’t global, but isn’t local either.
Of course, here, you can write ‘c’, and read both ‘b’ and ‘c’. But you can’t access ‘a’, that would create a new local variable ‘a’. See this example,
>>> a=1 >>> def func1(): b=2 def func3(): a=2 b=3 c=3 print(f"a={a}, b={b}, c={c}") func3() print(f"b={b}") >>> func1() a=2, b=3, c=3 b=2 >>> a
Output
To deal with this situation, we can use the ‘global’ and ‘nonlocal’ keywords.
>>> a=1 >>> def func1(): b=2 def func3(): global a a=2 nonlocal b b=3 c=3 print(f"a={a}, b={b}, c={c}") func3() print(f"b={b}") >>> func1() a=2, b=3, c=3 b=3 >>> a
Output
Python Interview Questions on Namespaces and Scopes
- What is namespace and scope in Python?
- Why are namespace and scope used in Python?
- Give an example of Python namespace and scope?
- What is class namespace in Python?
- What is global namespace in Python?
Conclusion
There are three types of Python namespaces- global, local, and built-in. It’s the same with a variable scope in python.
Also, the ‘global’ keyword lets us refer to a name in a global scope. Likewise, the ‘nonlocal’ keyword lets us refer to a name in a nonlocal scope.
If you don’t get something, ask us in the comments.
I do have a two different functions which are not nested and I want to use the variables which were declared in the two above function in an third function Soo how can I?
Hello Sai Kiran,
You can try it this way
def func1(): a=7; return a
def func2(): b=8; return b
def func3(a=func1(), b=func2()): return a+b
func3()
Thanks for the solution. It worked
Hi DataFlair Team,
I have written the code using nested functions. Kindly review and provide suggestions(if any).
def func1():
a = 17
def func2():
b = 8
def func3():
print(a+b)
func3()
func2()
Hello dataflair!
a=2;a=3;b=2
id(a)=!id(a)
when the a’s value is for 2 and 3 respectively.
I guess I making sense!
My confusion is the variable ‘a’ has different memory location if the variable value is change.
And I am wondering do different data value already assigned to memory.
Thank you dataflair. | https://data-flair.training/blogs/python-namespace-and-variable-scope/ | CC-MAIN-2021-10 | refinedweb | 1,128 | 74.49 |
Hello,
I am form commercial embroidery company. We are right now using Adobe products as well as wilcom
We want to shift to opensource, i have few questions
1. Can this software help us to convert files to vector and separate colors same as we do in AI
2. Is any plugins which can combine with this and can be used to digitize the files, you can see file format examples in my website like DST etc
Your help will be appreciated!
Inkscape (open source
Inkscape (open source software for vector graphics) would be better suited IMHO.
It would be cool if some
It would be cool if some Inkscape guru ports a thread extension to help in creating these. There is a GIMP Script-fu that has limited ability to create cross stitching charts by the way; may be limited, but it is cool. :)
Ofnuts and lylejkNew, Thanks
Ofnuts and lylejkNew, Thanks for replying. I have tried it for vector and results lookd great. Can it separate colors also or i need extra plugin, i mean color separations.
I tried GIMP Script-fu, its not what i am looking for, may be i should ask question in GIMP Script-fu thread.
Use trace bitmap in Inkscape
Open the image in Gimp and create an indexed image (Image>Mode>Indexed), with as few colors as possible.
Save the png image
Open the png in Inkscape
Go to Path>Trace Bitmap and select colors and click preview (update).
Select stack scans
In the drop down for scans type however many colors you have.
Click preview again.
When you are happy with the results select ok and Inkscape creates a SVG on top of the png.
Just move it over to the side and delete the png image.
Now you should have a layered svg with few colors.All colors in separate layers.
You will end up with something like this image indexed to 8 colors and traced to 4
-Rod
-- "It would be cool if some
-- "It would be cool if some Inkscape guru ports a thread extension to help in creating these."
?
Cools stuff; thanks for the
Cools stuff; thanks for the link Saul. My motivation's more on the simulation of tapestries, but to actually create output for use with stitching devices is cool. :)
I added the 3 files to the extension folder in Inkscape
I found the extension under Extensions>Render>Embroider
I tried to run the extension with the defaults and got a trace back error to shapely module.
So i added that module from here
Shapely-1.2.14.win32-py2.5.exe
Shapely-1.2.14.win32-py2.6.exe
Shapely-1.2.14.win32-py2.7.exe
to
Python2.5
Python-2.6
Python2.7 and restarted Inkscape
I still get the error
Traceback (most recent call last):
File "embroider.py", line 25, in
import shapely.geometry as shgeo
ImportError: No module named shapely.geometry
This is line #25 in the python script
import shapely.geometry as shgeo
Anyone know how to fix this?
EDIT Update -
All files seem to be present in \Lib\site-packages\shapely\geometry
Still get the trace back error..
-Rod looks great, i will try with some complex designs.
Yet another cool opensource
Yet another cool opensource program that I ran across the other day and did play with it some. You might find some use for it. :)?...
Outback Embroidery so beautiful
I have visited your site. I have read your post. I have received many information about Embroidery plugin to use for commercial purpose. This is very good and informative post. I offer you huge collection of Outback Embroidery so beautiful design.
You can buy my designs and enjoy using their shirts. which is very responsible price. so visit it our site and get more. | http://registry.gimp.org/comment/14621 | CC-MAIN-2014-10 | refinedweb | 637 | 74.08 |
Ticket #1848 (closed Bugs: wontfix)
Boost.Thread is incompatible with UPX
Description
Programs using Boost.Thread can't be compressed with UPX (). This is a regression from 1.34.1 (which UPX could compress) to 1.35.0 (which UPX can't compress). Example, with MinGW GCC 4.2.1 and statically-linked Boost.Thread 1.35.0:
C:\Temp>type foo.cpp #include <iostream> #include <ostream> #include <boost/thread/thread.hpp> using namespace std; using namespace boost; void foo() { cout << "foo()" << endl; } int main() { thread t(foo); t.join(); } C:\Temp>g++ -Wall -Wextra foo.cpp -o foo.exe -lboost_thread C:\Temp>foo foo() C:\Temp>upx --best foo.exe Ultimate Packer for eXecutables Copyright (C) 1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007 UPX 3.02w Markus Oberhumer, Laszlo Molnar & John Reiser Dec 16th 2007 File size Ratio Format Name -------------------- ------ ----------- ----------- upx: foo.exe: CantPackException: TLS callbacks are not supported Packed 1 file: 0 ok, 1 error.
Presumably, "TLS callbacks" are providing some feature.
- It would be nice if this was documented: what the feature is, why it requires TLS callbacks, and that they prevent UPX from working. (Some users might not figure out the connection here.)
- If some users could live without this feature (i.e. if the feature is not universally required for correctness), it would be nice to have a way to disable it, either by defining some macro before including the Boost.Thread headers or by building a special configuration of Boost.Thread.
It appears that TLS callbacks are being used to support thread exit handlers, but I don't know what they provide over Boost 1.34.1, or whether my program can live without them.
Attachments
Change History
Note: See TracTickets for help on using tickets.
TLS callbacks are indeed being used to support thread exit handlers. This allows thread-specific data to be cleaned up on threads launched outside of boost::thread. This has always been supported for those compilers that we knew how to (Mostly MSVC), and is now supported in gcc/mingw as well.
Thread-specific data that needs this cleanup is used by thread_specific_ptr, this_thread::get_id(), and at_thread_exit(). If you use any of these from a thread not managed by boost::thread, you need the cleanup, or you need to call on_thread_exit() from each of those threads before they finish.
Defining tss_cleanup_implemented in your main cpp file will prevent the automatic cleanup machinery being linked in, as your code is assumed to provide it. This should therefore allow your use of UPX. | https://svn.boost.org/trac/boost/ticket/1848 | CC-MAIN-2017-09 | refinedweb | 427 | 68.57 |
Orthogonalise a basis using modified Gram-Schmidt (and normalise) More...
#include "mbl_mod_gram_schmidt.h"
#include <vcl_vector.h>
#include <vnl/vnl_vector.h>
Go to the source code of this file.
Orthogonalise a basis using modified Gram-Schmidt (and normalise)
Definition in file mbl_mod_gram_schmidt.cxx.
Orthogonalise a basis using modified Gram-Schmidt.
Transform basis {vk} to orthonormal basis {ek} with k in range 1..N for j = 1 to N ej = vj for k = 1 to j-1 ej = ej - <ej,ek>ek //NB Classical GS has vj in inner product end ej = ej/|ej| end Convert input basis {v} to orthonormal basis {e}. Each basis vector is a column of v, and likewise the orthonormal bases are returned as columns of e
Definition at line 24 of file mbl_mod_gram_schmidt.cxx. | http://public.kitware.com/vxl/doc/release/contrib/mul/mbl/html/mbl__mod__gram__schmidt_8cxx.html | crawl-003 | refinedweb | 128 | 58.58 |
On Thu, 1 Apr 2004, Zoltan Menyhart wrote:> I can see a couple of functions, like> > static inline struct mm_struct * ptep_to_mm(pte_t * ptep)> {> struct page * page = kmap_atomic_to_page(ptep);> return (struct mm_struct *) page->mapping;> }> > in "rmap.?" without invoking "kunmap_atomic()".> Is it intentional?> What if for an architecture "kunmap_atomic()" is not a no-op ?Amusing misunderstanding. Take a look at kmap_atomic_to_pagein arch/i386/mm/highmem.c: it doesn't _do_ a kmap_atomic, ittranslates the virtual address already supplied by kmap_atomicto the address of the struct page of the physical page backingthat virtual address. So, in the case of try_to_unmap_one, itoperates on the virtual address supplied by rmap_ptep_map(which does do a kmap_atomic), and at the end there's anrmap_ptep_unmap (which does the rmap_ptep_unmap).Hugh-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2004/4/1/140 | CC-MAIN-2016-30 | refinedweb | 150 | 56.45 |
An overview of Web standards
In this step, we introduce the standard protocols behind the World Wide Web. It is important to understand these before we discuss protocols that are more specific to the Semantic Web, which are covered in the next step.
Background standards
The technologies behind the Web are implemented through a number of standard protocols and languages, with acronyms like HTTP, URI, XML, RDF, RDFS, OWL, SPARQL. You may be familiar with some of these already.
You can look up further details of these standards as needed (the W3C website - contains a lot of detailed information), but as background it is useful to know a little about each one, and in particular what they are for.
The standards in the next step build on the earlier ones, so they are often described as a stack of languages, as shown in Figure 1.3 below.
Figure 1.3 The Semantic Web Language Stack
HTTP message.
URI
A Uniform Resource Identifier (URI) is defined in the standard1 as
a compact sequence of characters that identifies an abstract or physical resource.
The word ‘compact’ here means that the string must contain no space characters (or other white-space padding).
‘Abstract or physical’ means that the URI may refer to an abstract resource such as the concepts ‘Beethoven’ and ‘sym, ‘http’ is the scheme, ‘musicbrainz.org’ is the authority, and ‘/doc/Frequently_Asked_Questions’ is the path; the other characters such as the colon are punctuation separating these constituents.
Note that the constituents following the scheme will be different for different schemes: thus the ‘tel’ ‘compact URIs’ or ‘CURIEs’. ‘/’ and ‘#’).
Thus in the example just given, one could introduce a namespace ‘dbp’ for, so reducing the URI to ‘dbp:Karlsruhe’, where the local name preserves the substring that is significant to human readers. We will use this convenient method of abbreviation often in the rest of this course.
XML
The labeled tags are placed around spans of text, thus indicating perhaps that the span should be formatted in italics:
<i>text in italics</i>
The italic tag ‘i’ is part of HTML, not SGML, but the convention of placing tags within angle brackets, and distinguishing the closing tag by a forward slash character, comes from SGML, as does the syntax for adding attributes to the opening tag, as in the following example which yields.
We have now introduced the fundamental protocols and standards upon which the Web runs. In the next step, we move on to look at protocols specific to the Semantic Web.
This work is a derivative of ‘Using Linked Data Effectively’ by The Open University (2014) and licensed under CC by 4.0 International Licence adapted and used by the University of Southampton.
Reference
T. Berners-Lee, R. Fielding and L. Masinter (2005) “Uniform Resource Identifier (URI): Generic Syntax”. Published on-line at. ↩ | https://www.futurelearn.com/courses/linked-data/2/steps/116162 | CC-MAIN-2019-04 | refinedweb | 473 | 58.62 |
9. Frequently Asked Questions¶
9.1. How do I keep my script running?¶()
9.2. My event handler isn’t being called¶
When assigning event handlers, don’t call the function you’re assigning. For example:
from gpiozero import Button def pushed(): print("Don't push the button!") b = Button(17) b.when_pressed = pushed()
In the case above, when assigning to
when_pressed, the thing
that is assigned is the result of calling the
pushed function. Because
pushed doesn’t explicitly return anything, the result is
None.
Hence this is equivalent to doing:
b.when_pressed = None
This doesn’t raise an error because it’s perfectly valid: it’s what you assign when you don’t want the event handler to do anything. Instead, you want to do the following:
b.when_pressed = pushed
This will assign the function to the event handler without calling it. This
is the crucial difference between
my_function (a reference to a function)
and
my_function() (the result of calling a function).
Note
Note that as of v1.5, setting a callback to
None when it was previously
None will raise a
CallbackSetToNone warning, with the intention
of alerting users when callbacks are set to
None accidentally. However,
if this is intentional, the warning can be suppressed. See the
warnings module for reference.
9.3. Why do I get PinFactoryFallback warnings when I import gpiozero?¶
You are most likely working in a virtual Python environment and have forgotten
to install a pin driver library like
RPi.GPIO. GPIO Zero relies upon lower
level pin drivers to handle interfacing to the GPIO pins on the Raspberry Pi,
so you can eliminate the warning simply by installing GPIO Zero’s first
preference:
$ pip install rpi.gpio
When GPIO Zero is imported it attempts to find a pin driver by importing them
in a preferred order (detailed in API - Pins). If it fails to load its
first preference (
RPi.GPIO) it notifies you with a warning, then falls back
to trying its second preference and so on. Eventually it will fall back all the
way to the
native implementation. This is a pure Python implementation
built into GPIO Zero itself. While this will work for most things it’s almost
certainly not what you want (it doesn’t support PWM, and it’s quite slow at
certain things).
If you want to use a pin driver other than the default, and you want to suppress the warnings you’ve got a couple of options:
Explicitly specify what pin driver you want via the
GPIOZERO_PIN_FACTORYenvironment variable. For example:
$ GPIOZERO_PIN_FACTORY=pigpio python3
In this case no warning is issued because there’s no fallback; either the specified factory loads or it fails in which case an
ImportErrorwill be raised.
Suppress the warnings and let the fallback mechanism work:
>>> import warnings >>> warnings.simplefilter('ignore') >>> import gpiozero
Refer to the
warningsmodule documentation for more refined ways to filter out specific warning classes.
9.4. How can I tell what version of gpiozero I have installed?¶
The gpiozero library relies on the setuptools package for installation
services. You can use the setuptools
pkg_resources API to query which
version of gpiozero is available in your Python environment like so:
>>> from pkg_resources import require >>> require('gpiozero') [gpiozero 1.4.1 (/usr/lib/python3/dist-packages)] >>> require('gpiozero')[0].version '1.4.1'
If you have multiple versions installed (e.g. from pip and
apt) they will not show up in the list returned by the
pkg_resources.require() method. However, the first entry in the list will
be the version that
import gpiozero will import.
If you receive the error “No module named pkg_resources”, you need to install pip. This can be done with the following command in Raspbian:
$ sudo apt install python3-pip
Alternatively, install pip with get-pip.
9.5. Why do I get “command not found” when running pinout?¶
The gpiozero library is available as a Debian package for Python 2 and Python 3, but the pinout tool cannot be made available by both packages, so it’s only included with the Python 3 version of the package. To make sure the pinout tool is available, the “python3-gpiozero” package must be installed:
$ sudo apt install python3-gpiozero
Alternatively, installing gpiozero using pip will install the command line tool, regardless of Python version:
$ sudo pip3 install gpiozero
or:
$ sudo pip install gpiozero
9.6. The pinout command line tool incorrectly identifies my Raspberry Pi model¶
If your Raspberry Pi model is new, it’s possible it wasn’t known about at the time of the gpiozero release you are using. Ensure you have the latest version installed (remember, the pinout tool usually comes from the Python 3 version of the package as noted in the previous FAQ).
If the Pi model you are using isn’t known to gpiozero, it may have been added
since the last release. You can check the GitHub issues to see if it’s been
reported before, or check the commits on GitHub since the last release to
see if it’s been added. The model determination can be found in
gpiozero/pins/data.py.
9.7. What’s the gpiozero equivalent of GPIO.cleanup()?¶
Many people ask how to do the equivalent of the
cleanup function from
RPi.GPIO. In gpiozero, at the end of your script, cleanup is run
automatically, restoring your GPIO pins to the state they were found.
To explicitly close a connection to a pin, you can manually call the
close() method on a device object:
>>> led = LED(2) >>> led.on() >>> led <gpiozero.LED object on pin GPIO2, active_high=True, is_active=True> >>> led.close() >>> led <gpiozero.LED object closed>
This means that you can reuse the pin for another device, and that despite
turning the LED on (and hence, the pin high), after calling
close() it is restored to its previous state (LED off, pin low).
9.9. Why do I get “ImportError: cannot import name” when trying to import from gpiozero?¶
It’s common to see people name their first gpiozero script
gpiozero.py.
Unfortunately, this will cause your script to try to import itself, rather than
the gpiozero library from the libraries path. You’ll see an error like this:
Traceback (most recent call last): File "gpiozero.py", line 1, in <module> from gpiozero import LED File "/home/pi/gpiozero.py", line 1, in <module> from gpiozero import LED ImportError: cannot import name 'LED'
Simply rename your script to something else, and run it again. Be sure not to
name any of your scripts the same name as a Python module you may be importing,
such as
picamera.py.
9.10. Why do I get an AttributeError trying to set attributes on a device object?¶
If you try to add an attribute to a gpiozero device object after its initialization, you’ll find you can’t:
>>> from gpiozero import Button >>> btn = Button(2) >>> btn.label = 'alarm' Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3/dist-packages/gpiozero/devices.py", line 118, in __setattr__ self.__class__.__name__, name)) AttributeError: 'Button' object has no attribute 'label'
This is in order to prevent users accidentally setting new attributes by mistake. Because gpiozero provides functionality through setting attributes via properties, such as callbacks on buttons (and often there is no immediate feedback when setting a property), this could lead to bugs very difficult to find. Consider the following example:
from gpiozero import Button def hello(): print("hello") btn = Button(2) btn.pressed = hello
This is perfectly valid Python code, and no errors would occur, but the program
would not behave as expected: pressing the button would do nothing, because the
property for setting a callback is
when_pressed not
pressed. But
without gpiozero preventing this non-existent attribute from being set, the
user would likely struggle to see the mistake.
If you really want to set a new attribute on a device object, you need to create it in the class before initializing your object:
>>> from gpiozero import Button >>> Button.>> btn = Button(2) >>> btn.>> def press(btn): ...: print(btn.label, "was pressed") >>> btn.when_pressed = press
9.11. Why is it called GPIO Zero? Does it only work on Pi Zero?¶
gpiozero works on all Raspberry Pi models, not just the Pi Zero.
The “zero” is part of a naming convention for “zero-boilerplate” education friendly libraries, which started with Pygame Zero, and has been followed by NetworkZero, guizero and more.
These libraries aim to remove barrier to entry and provide a smooth learning curve for beginners by making it easy to get started and easy to build up to more advanced projects. | https://gpiozero.readthedocs.io/en/stable/faq.html | CC-MAIN-2019-26 | refinedweb | 1,440 | 62.78 |
#include <wave-mac-helper.h>
Definition at line 86 of file wave-mac-helper.h.
Create a QosWaveMacHelper that is used to make life easier when working with Wifi 802.11p devices using a QOS MAC layer.
Definition at line 80 of file wave-mac-helper.cc.
Definition at line 83 of file wave-mac-helper.cc.
Create a mac helper in a default working state.
Definition at line 87 of file wave-mac-helper.cc.
All the attributes specified in this method should exist in the requested mac.
note: Here we require users set type with OcbWifiMac or its subclass, otherwise it will become error
Reimplemented from ns3::QosWifiMacHelper.
Definition at line 100 of file wave-mac-helper.cc.
References NS_FATAL_ERROR, and ns3::QosWifiMacHelper::SetType(). | https://www.nsnam.org/docs/release/3.20/doxygen/classns3_1_1_qos_wave_mac_helper.html | CC-MAIN-2022-40 | refinedweb | 126 | 70.29 |
Next: Defined, Previous: Ifdef, Up: Conditional Syntax
The `#if' directive allows you to test the value of an arithmetic expression, rather than the mere existence of one macro. Its syntax is
#if expression controlled text #endif /* expression */
expression is a C expression of integer type, subject to stringent restrictions. It may contain
&&and
||). The latter two obey the usual short-circuiting rules of standard C.
definedoperator, which lets you check whether macros are defined in the middle of an `#if'.
#if MACROinstead'.
The preprocessor does not know anything about types in the language.
Therefore,
sizeof operators are not recognized in `#if', and
neither are
enum constants. They will be taken as identifiers
which are not macros, and replaced by zero. In the case of
sizeof, this is likely to cause the expression to be invalid.
The preprocessor calculates the value of `#if' succeeds and the controlled text is included; otherwise it is skipped. | http://gcc.gnu.org/onlinedocs/gcc-3.4.6/cpp/If.html | CC-MAIN-2014-41 | refinedweb | 153 | 64.51 |
OwletOwlet
Owlet is a Typed Spreadsheet UI library for ScalaJS. It is built on top of Monix and Typelevel Cats to combine predefined input fields to a reactive user interface, just like what you would done in spreadsheet. Owlet is inspired by the PureScript library Flare.
Do one thing and do it well micro birds library series
1. add dependency in your
build.sbt
StableStable
libraryDependencies += "us.oyanglul" %%% "owlet" % "<maven version>"
RCRC
resolvers += "jitpack" at "" libraryDependencies += "com.github.jcouyang" % "owlet" % "<jitpact version>"
2. Now programming UI is just like using spreadsheet2. Now programming UI is just like using spreadsheet
import us.oyanglul.owlet._ import DOM._ val a1 = number("a1", 1) val a2 = number("a2", 2) val a3 = number("a3", 3) val sum = fx[List, Double, Double](_.sum, List(a1, a2, a3)) render(a1 &> a2 &> a3 &> sum, "#app")
val a1 = number("a1", 1) val a2 = number("a2", 2) val a3 = number("a3", 3) val sum = a1 |+| a2 |+| a3 renderOutput(sum, "#app")
eh... Ready for 3D spreadsheet programming?eh... Ready for 3D spreadsheet programming?
You know spreadsheet is 2D, when we have monad, it became 3D
!!!Monad Warning!!!
val numOfItem = int("noi", 3) val items = numOfItem .flatMap( no => (0 to no).toList.parTraverse(i => string("inner", i.toString)) )
- imagine that
numOfItemlives in dimension (x=1, y=1, z=0)
- then
itemslive in dimension (x=1,y=1,z=1)
you can render either
numOfItem or
items seperatly, for they live in diffenrent z axis (which means render
items you won't able to see
numOfItem even it's flatMap from there
but you can some how connect the dots with magic
&>
renderOutput(numOfItem &> items, "#output")
Anyway, just keep in mind that monad ops
map
ap
flatMap... will lift your z axis
parMap
parAp
parXXX instead, will keep them in the same z axis | https://index.scala-lang.org/jcouyang/owlet/owlet/0.3.1?target=_sjs0.6_2.12 | CC-MAIN-2021-43 | refinedweb | 304 | 67.04 |
In recent years, Deep Learning (DL) techniques have evolved greatly. The number of companies using this technology is growing annually because DL can be applied to various tasks throughout multiple spheres. However, despite the rapid development of the artificial intelligence (AI) sphere and some technological advances being made for the last few years, Deep Learning is still considered a very expensive AI function both in time and computation-wise.
Nevertheless, there are many ways and approaches to accelerating the Deep Learning training process and making it more efficient. Still, all of them require training on a graphics processing unit (GPU).
In this article we will talk about:
- What is a GPU?
- The principles of GPU computing
- Models of parallelism, general purpose GPU programming
- How deep learning frameworks utilize GPUs?
- CPU vs. GPU
- What is a CPU?
- How do GPUs work?
- FPGA and ASIC accelerators
- What is an ASIC?
- What is an FPGA?
- Pros and cons of using ASICs and FPGAs for deep learning
- How to choose the best hardware device for deep learning?
- Benefits of using GPUs for deep learning
- How to choose the best GPU for deep learning?
- GPU market overview
- Selecting the right resources for your task
- Consumer-grade GPUs
- Best deep learning GPUs for data centers
- DGX for deep learning at scale
- What is the best GPU for deep learning?
- Metrics to monitor GPU performance
- Actions you can take to improve GPU utilization
- How to use GPU for deep learning?
- What is CUDA?
- What is cuDNN?
- How to train on GPU with PyTorch?
- How to train on GPU with TensorFlow?
- How to train on GPU with Keras?
- How to train on GPU with MxNet?
- Using distributed training to accelerate your workload
- Data parallelism
- Model parallelism
- Multi-GPU
- Synchronization methods
- Deep Learning on GPU clusters
- What is Mixed Precision?
- What is NVIDIA SDK?
- Cloud services vs. On-premise approach
- Best practices, tips, and strategies
Let’s jump in.
What is a GPU?
Graphics Processing Unit (GPU) is a specialized processor that was originally designed to accelerate 3D graphics rendering. However, over time it became more flexible and programmable which allowed developers to broaden the horizons and use GPUs for other tasks. The greatest strength of a GPU is the ability to process many pieces of data at the same time. This makes GPUs quite useful devices for machine learning (ML), gaming, and video editing.
Nowadays, a GPU is one of the most important types of computing technology that is widely used for both personal and industrial purposes. Despite GPUs being the best known for their gaming capabilities, they are in high demand in AI as well.
From the hardware point of view, a GPU can be integrated into the computer’s central processing unit (CPU) or be a completely discrete hardware unit. When talking about a discrete hardware unit the term graphics card or video card might be used to replace the GPU term. However, it is worth mentioning that though these terms often interchange with one another, a GPU is not a video card.
Let’s make this clear. The GPU is just a part of the video card. The concept is the same as with a motherboard and a CPU. The graphics card is an add-in board that includes a GPU and various components that allow a GPU to work correctly and connect to the rest of the system.
The principles of GPU computing
Knowing what GPUs are in general, let’s talk about why they are in high demand in deep learning. The reason behind that is simple. GPUs can effectively parallelize massive computational processes.
Models of parallelism
As mentioned above, the greatest advantage that comes with a GPU is the ability for parallel computing. Nowadays, there are four basic approaches to parallel processing:
- Single instruction, single data (SISD) – only one operation is performed over one piece of data at a time
- Single instruction, multiple data (SIMD) – single operation is performed over multiple pieces of data at a time
- Multiple instructions, single data (MISD) – several operations are performed over one piece of data at a time
- Multiple instructions, multiple data (MIMD) – several operations are performed over multiple pieces of data at a time
A GPU is a hardware device with SIMD architecture. Thus, a GPU fits deep learning tasks very well as they require the same process to be performed over multiple pieces of the data.
General purpose GPU programming
Since the launch of NVIDIA’s CUDA framework, there is no barrier between the developers and the GPU resources. Nowadays, developers do not need to understand specialized GPU programming languages. Thus, GPU’s processing power was quickly applied to deep learning tasks.
How deep learning frameworks utilize GPUs?
As of today, there are multiple deep learning frameworks such as TensorFlow, PyTorch, and MxNet that utilize CUDA to make GPUs accessible. They offer a high-level structure that minimizes the complexity of working directly with CUDA while making GPU processing a part of modern deep learning solutions.
CPU vs. GPU
As you might know, there are two basic neural network training approaches. You might train either on a CPU or a GPU. As mentioned above, training on GPUs accelerates the training process. It is time to find out why this is happening.
What is a CPU?
The Central Processing Unit or CPU is considered to be the brain of the computer. It executes almost every process your computer or operation system needs. From the hardware point of view, the CPU consists of millions of transistors and can have multiple processing cores.
Nowadays, most CPUs have multiple cores which operate with the MIMD architecture. This fits the CPU’s philosophy perfectly as the computer’s brain must be able to execute different instructions on different data at the same time.
Overall, the CPU is the major component of your computer that handles the computer’s operation logic.
How do GPUs work?
At this point, you understand the basics of a GPU and a CPU, their roles, and key capabilities. Now, let’s move on and discuss how they work so we will be able to identify the advantages of the GPU over the CPU in deep learning tasks.
It is worth mentioning that CPUs are latency optimized while GPUs are bandwidth optimized. So, for example, you can imagine that a CPU is a reactive plane while a GPU is a cargo plane. If you have the task of transporting a number of packages from point A to point B, your CPU being an extremely fast reactive plane will be able to deliver some of them very quickly. Still, the CPU will go back and forth numerous times as it cannot take many packages aboard. Now imagine that the packages are actually some memory and you need to transport it to your RAM. As shown above, the CPU is good at fetching small amounts of memory quickly. On the other hand, the GPU being a cargo plane is slower in doing that but can fetch much more memory at once.
A CPU tends to have less memory bandwidth than a GPU. That is why the more memory your computational operations require the more significant the advantage of GPUs over CPUs. When speaking about neural networks the most computationally demanding piece in the training process is multiple matrix multiplications which take up a lot of memory.
Still, there is a latency problem. The GPU cargo plane might be able to deliver a large amount of memory at once but it will take some time for it to return to the initial point and deliver the remaining part. Fortunately, the GPU solves this problem by using multiple cargo planes at once which helps to effectively hide latency. It is called thread parallelism. In theory, we could hire many reactive planes to deliver the packages but in practice, there is no real benefit of this scenario.
This is actually the reason why GPUs are used to train deep learning models. For a large amount of memory, GPUs provide the best memory bandwidth while having almost no drawback due to latency via thread parallelism. It is that simple, GPUs are simply faster.
Overall, it is worth mentioning that despite CPUs and GPUs having a lot in common, they have unique strengths. The CPU is a powerful execution engine that is suited to a wide variety of workloads, especially those for which latency or per-core performance is important. Still, for Deep Learning tasks GPU tends to save you a fair amount of time compared to the CPU.
FPGA and ASIC accelerators
However, other hardware devices can be used to train a neural network as well. For example, sometimes you might face strange abbreviations like an FRGA or an ASIC. Let’s talk in-depth about these devices and once and for all decide which hardware device should be used when working on a Deep Learning project.
What is an ASIC?
An application-specific integrated circuit (ASIC) is an integrated circuit chip customized for a particular use rather than intended for general purpose use. For example, a chip designed to run in a digital voice recorder is an ASIC. In general, ASICs require a lot of development time and are very expensive to design and fabricate. There are many names for these chips but the most commonly used is TPU (Google TPU). If you are familiar with Kaggle you know that it provides an ability to turn on the TPU accelerator in your notebook.
So, ASICs are very interesting devices that can outperform GPUs due to their more specialized nature. However, for private usage, you do not need an ASIC even for complicated DL tasks. You will be more than fine with a GPU. Still, if you want to access TPUs you can use Kaggle accelerator or Google Cloud.
What is an FPGA?
Field programmable gate arrays (FPGAs) are integrated circuits with a programmable hardware fabric. FPGAs are a great and cheaper alternative to ASICs as the circuitry inside a chip is not hard etched and you can reprogram it for a specific task. FPGAs deliver the needed performance without the cost and complexity of developing ASICs. Still, you must be able to reprogram them in order to unveil their true potential.
Pros and cons of using ASICs and FPGAs for deep learning
Now when you understand the basics of ASICs and FPGAs let’s talk about the pros and cons of using them for deep learning.
Pros for ASICs:
- Designed for a specific deep learning workload
- Show great performance
Cons for ASICs:
- Have a long production cycle time (12 – 18 months)
- Very expensive
- Not flexible
Pros for FPGAs:
- Reprogrammable devices
- Flexible
- Cheaper than ASICs
- Show performance comparable to ASICs
Cons for FPGAs:
- Very difficult to program
- Reprogramming can take from several hours to several weeks
- Still pretty expensive comparing to GPUs
How to choose the best hardware for a deep learning project?
As mentioned before, there are four hardware devices to choose from for your deep learning project:
- CPU
- GPU
- ASIC (TPU)
- FPGA
It is more or less easy with the CPU. In general, a CPU is not used to train deep learning models as it will not deliver the necessary performance. Still, on the preprocessing, inference, and deployment stages of a DL project, a CPU is a commonly used hardware device. Moreover, if you think of the cost/performance ratio, you can often afford multiple CPU infrastructure for the same price or less than the cost of a single GPU. That is why you should explore your opportunities before you make a final choice.
As for the rest of the list, that is when things get really tricky. If you want raw performance power then ASICs are the devices you might want to look into. ASICs are built for a specific deep learning workload. That is why they will excel at it. However, it can be difficult to access them. You might even need to spend some money to get access to the Google Cloud, for example.
As for FPGAs, they are not as popular as GPUs or even ASICs. Despite FPGAs having the potential to deliver performance similar to ASICs, they need to be programmed first to do so. That is an additional obstacle because you need to learn how to do that. Thus, it might be hard to unveil FPGAs true potential.
On the other hand, GPUs are almost everywhere simply because each personal computer must have a video card. I am sure you have one on your computer. An enterprise-grade solution can be a GPU cluster or a cloud service with access to the GPUs. GPUs are great in parallel processing and can deliver incredible acceleration in cases where the same operation must be performed many times in rapid succession.
That is why the only true competitors to GPUs right now is ASICs. Still, GPUs are more commonly used due to easier access.
Benefits of using GPUs for deep learning
If you have chosen a GPU as your hardware device for your next deep learning project, you can be sure that:
- Your machine learning operations will run faster than on CPU
- Your training process will be distributed
- You will work with a large memory bandwidth
- You will be able to process large datasets faster. The larger the dataset the greater benefit you can gain from using GPUs
- You will be able to use some advanced techniques to enhance the performance even more
How to choose the best GPU for deep learning?
At this point, you understand the basics of GPUs and know the benefits of using them as your hardware device for a deep learning project. Now it is time to figure out what to look out for when choosing a GPU for a deep learning project.
Let’s start with the obvious one. As mentioned above, GPUs benefit from a large memory bandwidth. That is why you should pick a GPU with the highest bandwidth within your budget. Also, you should pay attention to the number of cores as it determines the speed at which a GPU can process the data. The higher the number, the better. This is especially crucial if you plan to work with large datasets.
Moreover, please pay attention to the video RAM size as it is the measurement of how much data the GPU can handle at once. Last but not least, you must check the processing power because it shows the speed at which the GPU can compute the data which determines how fast the system will perform tasks.
Overall, you need to pay attention to memory bandwidth, the number of cores, video RAM size, and processing power. The higher each of these indicators, the better. Still, please stay within your budget as GPUs can be quite expensive.
GPU market overview
As you might know, there is a variety of GPUs on the market, still, the NVIDIA solutions tend to be the most popular and powerful. However, in 2020, AMD has made a massive step towards being a strong competitor in the GPU market. Some analysts believe that over the next few years the GPU market might change a lot. Nevertheless, as of today, AMD GPUs are decent for gaming but as soon as deep learning comes into the picture NVIDIA is the best option that provides all grades of GPUs. Moreover, NVIDIA’s CUDA tool is used by the majority of modern deep learning frameworks to work with GPUs.
Among the NVIDIA offers you can find:
- Consumer-grade GPUs (basically they are GPUs for personal usage)
- GPUs for data centers
- DGX systems
Selecting the right resources for your task
It is always better to identify the complexity of the deep learning tasks you want to perform on a GPU to choose a proper one. Let’s make this clear. You should not buy the most expensive and powerful GPU on the market as you might simply never use its true power. On the other hand, you should not buy the cheapest one as it might not fit well on your tasks. Also, there might be budget issues as GPUs can be pricy. Thus, some tips can help you.
- You must figure out what your current video card model is. You might not need a new GPU at all
- If you want to use a GPU for studies or to train simple and small deep learning models you don’t need the latest video card. You will be good with some low-end GPU, for example, NVIDIA’s GEFORCE GT 930M. In general, any GPU older than 2015 will fit well on light tasks
- If you want to train large and complex models and solve difficult deep learning problems you need to think of the latest GEFORCE lineup, for example, NVIDIA GEFORCE RTX 3090 or even a more powerful TITAN lineup. On the other hand, you can use cloud services that provide access to powerful GPUs.
- If your task is complex enough that it requires GPU parallelism, you must think of a deep learning infrastructure that supports multi-GPU processing and has multiple high-end GPUs aboard. On the other hand, cloud services that provide access to TPU clusters might be a solution as well.
Consumer-grade GPUs
To tell the truth, it is a bit complicated when talking about the consumer-grade GPUs simply because they are not designed for large-scale deep learning projects. In general, these GPUs are more focused on gaming and entertainment, however, they might be an entry point for deep learning enthusiasts who want to try themselves in the industry.
Still, it is worth mentioning that consumer-grade GPUs are widely used by data scientists. For example, there are AI companies that use computers with consumer-grade NVIDIA GPUs to train massive neural networks. Generally, it happens because of budget issues but this approach can be quite successful.
As of today, the best consumer-grade GPUs on the market are:
- NVIDIA GEFORCE RTX 3090 – as of today NVIDIA GEFORCE RTX 3090 is the most powerful GPU from the RTX 30 series. The GEFORCE RTX 3090 is a GPU with TITAN class performance. It’s powered by Ampere (NVIDIA’s second gen RTX architecture) doubling down on ray tracing and AI performance with enhanced Ray Tracing Cores, Tensor Cores, and new streaming multiprocessors.
- RTX 30 series in general – despite NVIDIA GEFORCE RTX 3090 being the most powerful model from this series the rest of the models are still great for delivering a great deep learning performance
- NVIDIA GEFORCE RTX 2080 TI is the most powerful GPU from the RTX 20 series. Sure it is not as powerful as latest models but its powerful NVIDIA Turing architecture and 11 GB of next-gen, ultra-fast GDDR6 memory (vRAM) as well as a 352-bit memory bus, a 6MB cache, and roughly 120 teraflops of performance make it an ultimate gaming and deep learning GPU
- NVIDIA TITAN V is a GPU designed specifically for data scientists and researchers that provides performance similar to datacenter-grade GPUs for some deep learning workloads. NVIDIA TITAN V is the most powerful Volta-based graphics card ever created for the PC. It has two editions and provides from 12 to 32GB vRAM memory, 4.5 to 6MB cache, and 3072 to 4096-bit memory bus.
- NVIDIA TITAN RTX is comparable to TITAN V. It was designed for researchers, developers and creators and built on Turing architecture, bringing 130 Tensor teraflops of performance, 576 tensor cores, and 24 GB of ultra-fast GDDR6 memory (vRAM).
Best deep learning GPUs for data centers
GPUs for data centers are the standard for deep learning implementations in production. They are designed for large-scale projects and show company-grade performance. That is why most enterprises either build their own computing clusters using such GPUs or rent one.
The best available models are:
- NVIDIA Tesla A100 Tensor Core GPU powered by the NVIDIA Ampere architecture was designed for machine learning, data analytics, and high performance computing (HPC). A100 is the engine of the NVIDIA data center platform. Each Tesla A100 provides up to 624 teraflops performance, 40GB memory, 1555 GB memory bandwidth, and 600GB/s interconnects.
- NVIDIA Tesla v100 Tensor Core is an advanced data center GPU designed for machine learning, deep learning and HPC. It’s powered by NVIDIA Volta architecture, comes in 16 and 32GB configurations with 149 teraflops of performance and 4096-bit memory bus, and offers the performance of up to 100 CPUs in a single GPU
- NVIDIA Tesla P100 powered by NVIDIA Pascal architecture is designed for accelerating both HPC and AI. It is a low-end data center GPU as it provides only up to 21 teraflops of performance, 16GB of memory, and a 4096-bit memory bus.
- NVIDIA Tesla K80 is designed to accelerate data analytics. It is powered by NVIDIA Kepler architecture and provides 4992 NVIDIA CUDA and GPU Boost technology, 24 GB of GDDR5 memory, and 480 GB/s aggregate memory bandwidth.
- Standard version of Google tensor processing unit (TPU) provides up to 420 teraflops of performance and 128 GB high bandwidth (HBM) memory each. Still, there is a version that provides over 100 petaflops of performance, 32TB HBM.
DGX for deep learning at scale
NVIDIA DGX systems are full-stack AI solutions. In general, they are AI data centers-in-a-box. They are designed specifically for machine and deep learning tasks and show enterprise-grade performance. Moreover, they are really convenient to use due to the plug-n-play philosophy.
For enterprises, many cnvrg.io customers benefit from the DGX workstations, as cnvrg.io provides the easiest way to manage your DGX workstation for deep learning projects. DGX provides teams with a variety of servers for teams that need to run diverse workloads in parallel. You can learn more about our DGX integration here.
As of today, you might need to take a closer look at:
- DGX-1 was the first system in the DGX concept. It has 8 NVIDIA Tesla v100 Tensor Core GPUs with 16GB of memory aboard and provides 1 petaflops of performance. However, since the DGX-2 system was presented DGX-1 is not relevant anymore.
- DGX-2 is an upgrade over DGX-1. Just as its ancestor DGX-2 is an AI server for the most complex deep learning challenges. Powered by NVIDIA DGX software and the scalable architecture of NVIDIA NVSwitch each DGX-2 has 16 NVIDIA Tesla v100 Tensor Core GPUs with 32 GB of memory integrated and provides 2 petaflops of performance.
- DGX A100 is designed to be a universal system for any AI workload, for example, training, testing, inference and analytics. DGX A100 is the first AI system built on NVIDIA Tesla A100 Tensor Core GPU. Each DGX A100 system has 8 A100 GPUs with 40 GB memory and provides 5 petaflops of performance.
What is the best GPU for deep learning?
Generally, the best GPU for deep learning is the one that fits your budget and the deep learning problems you want to solve. At the moment, the best NVIDIA solutions you can find are:
- RTX 30 series – all video card from this series will be a great fit for your deep learning infrastructure
- NVIDIA TITAN V – if you want a consumer-grade GPU that provides datacenter-grade performance on some tasks
- NVIDIA Tesla A100 – as it seems like the best datacenter-grade GPU right now
- Google tensor processing unit (TPU) – for raw power and Google Cloud service convenience
- DGX A100 and DGX-2 – as full-stack AI solution with limitless potential to power your business
My personal choice is the latest consumer-grade GPU from the NVIDIA GEFORCE series. First, it effectively covers all the deep learning tasks you can even think of without any issues. Second, it is quite cheap compared to the datacenter-grade GPUs.
Metrics to monitor GPU performance
Now it is time to think of assessing the GPU performance as we want it to run at full power. To tell the truth, many deep learning projects utilize only a small part of their GPU potential because of different mistakes. Also, a GPU is simply a hardware device that can break or underperform for various reasons. That is why you need to know what to look out for in order to identify the possible problem.
To start with, if you are using an NVIDIA GPU device, you must try NVIDIA’s system management interface. The interface comes with the GPU, so you can easily use a Terminal command to access it.
nvidia-smi -l
The interface constantly monitors your system and displays the percent rate of your GPU utilization. Thus, you will be able to assess it and identify bottlenecks in your deep learning pipelines. For example, if your batch forming takes a lot of time, your GPU utilization will fluctuate from 100% to 20% or less. This approach will help you to optimize your pipelines. You might even decide to add another GPU to your system if your initial one is always utilized at maximum.
The interface is also really effective when talking about memory usage. It has a comprehensive list of memory metrics, so you will have no problem assessing your GPU memory access and usage. It is crucial as this metric will help you to identify the percentage of time your GPU’s controller is actually in use. Thus, you will be able to evaluate the efficiency of your deep learning pipeline and make some adjustments, for example, change the batch size.
Also, it is a good practice to monitor the power consumption and the temperature of your GPU. The power metric will help you to predict and control the power consumption whereas the temperature metric will indicate if your cooling system works fine or you need to make some adjustments in order to prevent the potential hardware damage. Please pay attention to these metrics as they can save your hardware.
To sum up, in order to assess your GPU’s performance you must look out for GPU utilization, GPU memory access and usage, power consumption, and temperature. Keep track of these metrics and your GPU will be used at its maximum. Please use NVIDIA’s system management interface as it is a great tool to monitor your GPU’s performance
Actions you can take to improve GPU utilization
As mentioned above, you can make adjustments to deep learning pipelines to improve your GPU utilization. Here is what you can do:
- Increase the batch size
- Use asynchronous mini-batch allocation
- If you are preprocessing images on the fly, try to preprocess all the files, save them in a more efficient structure, for example, pickle, and construct batches from the raw numpy arrays
- Use multiprocessing to improve batch generation speed
How to use GPU for deep learning?
As mentioned above, you can massively accelerate a neural network training process simply by running it on a GPU. In previous sections, you have learned the reasons behind that. Now let’s move on and discuss how to actually work with GPUs.
To tell the truth, the answer is really simple but it depends on the deep learning framework you are using. As you might know, there are many DL frameworks out there, for example, TensorFlow (TF), Keras, PyTorch, MxNet, and others. Each one of them supports training on a GPU. However, for some of them, it will be easier.
What is CUDA?
To start with, let’s talk a bit about Compute Unified Device Architecture or CUDA. CUDA is a parallel computing platform and programming model developed by NVIDIA that focuses on general computing on GPUs. CUDA speeds up various computations helping developers unlock the GPUs’ full potential.
CUDA has its drivers that can be used to communicate with a GPU. Thus, all deep learning frameworks in one way or another use CUDA to properly run on a GPU. This makes CUDA a really useful tool for data scientists. In order to have the latest version of CUDA installed please update your NVIDIA driver.
Overall, CUDA is a very popular tool due to its high-level structure, so if you have a GPU from NVIDIA you must definitely try it out. Still, CUDA does not work with non-NVIDIA GPUs which makes sense given CUDA’s developer.
What is cuDNN?
The NVIDIA CUDA Deep Neural Network library or cuDNN is a GPU accelerated library that helps to achieve NVIDIA GPUs’ full potential. It has a set of basic functions implemented, for example, various convolutions, activation and pooling layers, and many more.
You should not worry about installing cuDNN as it is already included in all popular deep learning frameworks. You should simply update your NVIDIA driver in order to use the latest version of cuDNN.
Let’s make this clear. cuDNN is the library that is optimized for working on GPUs and has highly tuned implementations for standard deep learning routines. On the other hand, CUDA is the tool that connects deep learning frameworks with cuDNN, communicates with a GPU, and ensures the code will be properly executed on it.
How to train on GPU with PyTorch?
PyTorch seems like the easiest DL framework to train on a GPU as it natively supports CUDA. CUDA can be accessed in the torch.cuda library. The concept of training your deep learning model on a GPU is quite simple. You should just allocate it to the GPU you want to train on.
net = MobileNetV3() #net is a variable containing our model
net = net.cuda() #we allocate our model to GPU
From this point, your model will store on the GPU and the training process will be executed there as well. It is worth mentioning that all the data you want to train on must be allocated to the same GPU as well or you will face errors. Anyway, you can easily do that by using a .cuda() method.
Fortunately, PyTorch does not require anything complicated to carry out this task, unlike some other frameworks. From my perspective, PyTorch is the best deep learning framework option that makes your coding process intuitive and smooth. However, you might feel the other way. For extra support, you can access the in-depth article from cnvrg.io on this topic for further code and documentation.
How to train on GPU with TensorFlow?
You should not expect any obstacles if you want to train your deep learning model on a GPU using TensorFlow. There were times when Tensorflow actually had two packages, the GPU and the CPU one. You can still install them via pip using TF release 1.15 or older:
pip install tensorflow==1.15 # CPU
pip install tensorflow-gpu==1.15 # GPU
Nowadays, since TensorFlow 2.0 these are not separated and you simply need to install TF. It will already include GPU support if you have an NVIDIA card or CUDA already installed:
pip install tensorflow
TensorFlow code, and tf.keras models will automatically run on a single GPU with no code changes required. You just need to make sure TensorFlow detects your GPU. You can do this using a simple command.
import tensorflow as tf
print(“Num GPUs Available: “, len(tf.config.experimental.list_physical_devices(‘GPU’)))
If the number printed is more than zero, it means TensorFlow has successfully detected your GPU. That is all it takes for your future TensorFlow code to run on the GPU by default. Still, you will be able to perform computation on a CPU without any difficulties. To tell the truth, there is a great notebook from the developers’ team that covers TensorFlow GPU support in-depth. Please access it for extra support.
How to train on GPU with Keras?
Nowadays, Keras is completely integrated with TensorFlow. The original Keras library is not maintained or updated anymore. That is why when talking about Keras data scientists usually refer to the Keras API integrated into TensorFlow.
Let’s make this clear. Keras is a high-level API that deeply integrates with low-level TF functionality. It means you can use Keras methods without having to figure out how it interacts with TensorFlow.
Thus, everything mentioned above about TensorFlow GPU support is true with Keras.
How to train on GPU with MxNet?
To tell the truth, there is not much to say about MxNet. The concept it uses to run deep learning models on GPUs is similar to the PyTorch concept. You simply need to specify a hardware device you want to train on, allocate your model and data to the same GPU and start training. For more information please refer to the official MxNet tutorial.
Using distributed training to accelerate your workload
Training a neural network is a complicated and time-consuming process. Even if you do this on a GPU, it might take ages for your model to fully train. Sure the time needed for that depends on the task and the network complexity, however, you might want to use some advanced techniques to speed up the training process even more.
For example, you can use the distributed training technique. In this case, the name speaks for itself. Distributed training suggests dividing your training process on different workloads across so-called worker nodes. Nodes are actually GPU’s mini-processors that are used to parallelize tasks. If you remember the GPUs thread parallelism feature we discussed earlier, you must have already guessed it is achieved by worker nodes. So, when talking about distributed training we refer to the training process parallelization concept.
In general, there are two completely different types of distributed training:
- Data parallelism
- Model parallelism
Data parallelism
The first type is known as data parallelism. The concept is quite simple:
- You make a copy of your initial model for each worker node
- You train each copy on a different batch of training data. Thus, your data will be split up and processed in parallel
- You combine the results after computations and update your initial model
- You repeat steps 1 – 3 until your network is trained
In general, data parallelism is a very efficient concept. However, it has a major disadvantage. Sometimes the neural network is so large that it can not fit on a single worker node. In this case, the data parallelism concept will not work at all.
Model parallelism
However, that is where the second type of distributed training called model parallelism comes in. The concept suggests dividing a model into several different parts and training them simultaneously across worker nodes. Moreover, all worker nodes use the same dataset and from time to time share global model parameters with other workers. Thus, model parallelism helps to solve the problem of large neural networks.
Unfortunately, the model parallelism concept has major disadvantages. First, it will work well only if the initial neural network model has a parallel architecture. Second, this type of distributed training is really hard to implement code-wise. That is why the data parallelism concept is more commonly used.
Multi-GPU
Still, if you have a large neural network, there is a technique besides model parallelism that can be used to improve deep learning performance. It is called multi-GPU processing and can be used only if you have several GPUs aboard.
If it is true to your system, you must definitely try multi-GPU processing as it will be both fast and effective. There are two ways of working with multiple GPUs. The first approach suggests using each GPU for a separate task. Thus, you will be able to experiment and run multiple algorithms at once. However, you will not achieve better speed.
The second type requires combining several GPUs in one computer (making a GPU cluster) to achieve better performance. It is called GPU parallelism and can be used to work with the data parallelism concept with no fear of the large neural network obstacle. Let’s make this clear. You can simply use each separate GPU as a worker node. Thus, your model’s performance will improve drastically.
As far as I am aware all modern deep learning frameworks (PyTorch, TensorFlow, Keras, and MxNet) are up to the task. Moreover, there are deep learning frameworks, for example, Horovod that specialize in distributed learning. Feel free to explore the opportunities as the industry is constantly evolving. From the coding perspective, you should not face any obstacles. Please refer to the tutorials linked above for extra-support.
Synchronization methods
Unfortunately, distributed training has its own challenges, for example, determining how different worker nodes will share and synchronize their results. There are two approaches to this problem: a parameter server technique and an all-reduce technique.
A parameter server-based architecture suggests dividing all GPU nodes into two groups. The first group consists of nodes called workers which train a neural network model. The second one consists of nodes called parameter servers which preserve the global parameters of a model. Thus, the workers will receive the global parameters from a parameter server, calculate gradients with their data batches and return the results to a parameter server.
Still, a parameter server-based architecture has major disadvantages. To start with, if the global model parameters are synchronously shared across workers, you will wait until each worker completes its iteration and returns the results which might be time-consuming. Also, if you have only one parameter server, you will not benefit from adding more workers as your server will have to work with more data from the workers which creates a bottleneck.
The all-reduce approach limits the disadvantages of a parameter server-based technique as it suggests each node to store a neural network global parameters. To tell the truth, there are various all-reduce algorithms, but overall it is a powerful technique as it allows to add more workers without any limitations. Thus, it is used more often than a parameter server-based architecture.
Deep Learning on GPU clusters
A GPU cluster concept is based on having multiple GPUs aboard. In general, a GPU cluster is a computing cluster in which each node is equipped with a Graphics Processing Unit. Moreover, there are TPU clusters that are more powerful than GPU clusters.
Still, there is nothing special in using a GPU cluster for a deep learning task. Imagine you have a multi-GPU deep learning infrastructure. You could either use each GPU for a specific task or try a distributed training data parallelism technique to utilize your GPUs effectively. Moreover, you could follow your own logic and play with your system as you wish. Despite a GPU cluster being way more powerful the same is true to using it.
What is Mixed Precision?
Let’s continue with advanced techniques and talk about Mixed precision. It is an interesting technique that requires using both 16-bit and 32-bit floating-point types in a neural network model during training to make it run faster and use less memory. The concept suggests keeping certain parts of the model in the 32-bit types for numeric stability. Thus, the model will have a lower step time while training equally as well in terms of the evaluation metrics. For extra support and code please refer to the official notebook concerning this technique.
Overall, mixed precision is an advanced technique that can be used effectively if you study it. So, feel free to experiment and play with it.
What is NVIDIA SDK?
Last but not least, let’s cover the NVIDIA Software development kit (SDK). NVIDIA CUDA-X AI is an SDK designed for effective deep learning model building which can be easily used with an NVIDIA GPU. It includes multiple GPU-accelerated libraries for AI and high-performance computing (HPC). There are libraries for:
- Deep learning routines
- Linear algebra
- Matrix operations
- Multi-GPU communication
- And many more
Overall, NVIDIA CUDA-X AI is designed for computer vision (CV) tasks and recommendation systems. The SDK can be used to accelerate your deep learning framework and build new model architectures directly for a GPU. CUDA-X AI libraries offer a unified programming model that enables you to develop deep learning models on your desktop. However, you should not overcomplicate things. NVIDIA SDK is an advanced tool, so you might probably want to return to it when you have mastered the basics of training on a GPU.
Cloud services vs. On-premise approach
Let’s talk a bit about cloud technologies. In general, when choosing your deep learning infrastructure you must choose whether you will use an on-premise or a cloud approach.
An on-premise approach requires having a computer with at least one hardware device that can be used to train a neural network model effectively. From my experience, it might be enough for personal usage especially if you have a high-end consumer-grade GPU aboard. You will be able to work on any deep learning task but the time needed for your models to train can be significant (although it depends on your system configuration). Moreover, building an on-premise infrastructure might be very expensive. Still, such an approach is really flexible as all the hardware you have will be yours. You will be able to perform as many experiments as you want and train your models as long as you want. Also, using an on-premise approach you can control hardware configurations and security. Thus, an on-premise infrastructure allows you to explore the task from all the angles you want with stable costs and enormous flexibility.
On the other hand, there is a cloud approach that requires less money to start using. Also, the majority of cloud services provide scalability and provider support. Moreover, you will be able to get access to more powerful hardware, for example, TPU clusters. Unfortunately, cloud services are not as flexible and if you use them consistently it might cost you a lot.
Moreover, when companies move workloads and data to the cloud, their on-premise infrastructure often continues to play an important role. A combination of on-premise infrastructure and cloud service is known as hybrid cloud. Some organizations use hybrid cloud as a path to migrate their entire datacenter to the cloud over time. Other organizations use cloud services to extend their existing on-premises infrastructure.
A hybrid solution might be useful in multiple situations. For example, it might serve as a transition step during a longer-term migration to a fully cloud-native solution or for disaster recovery and fault tolerance by replicating data and services between on-premises and cloud environments. Moreover, it might help to reduce latency between your on-premise infrastructure and remote locations by hosting part of your architecture in a cloud.
Enterprises are transitioning to hybrid cloud, and for a good reason. Cloud services can be great for short-term projects and for organizations that are just getting started. However, for long-term and large projects or personal everyday usage, an on-premise approach is the one to choose as it will spare you loads of money. Still, a hybrid solution might be really useful in some scenarios as well.
Best practices, tips and strategies
Throughout this article I mentioned plenty of valuable tips you might want to remember after reading this article, so let’s summarize them into a list:
- A GPU is a part of a video card. However, these terms often interchange with one another
- When solving a deep learning problem GPU is more powerful than CPU
- A CPU is good in the tasks where latency or per-core performance is important
- GPUs often perform better than CPUs for deep learning projects
- Still, both ASICs and FPGAs are a more powerful hardware tool than GPUs as they are specialized and tuned to solve a particular task
- It is easier to use a GPU for your deep learning project
- A GPU will make your training process fast
- You can make it even faster using parallelization
- You will be able to process large datasets using a GPU
- When choosing a GPU you must look out for the memory bandwidth, the number of cores, video RAM size, and processing power
- As of today, NVIDIA GPUs are the best ones for deep learning tasks
- When assessing your GPU’s performance you must pay attention to the GPU utilization, GPU memory access and usage, power consumption, and temperature
- CUDA is a tool that is used to communicate with a GPU
- cuDNN is the library that is optimized for working on GPUs and has highly tuned implementations for standard deep learning routines
- It is easy to train your model on a GPU using any modern deep learning framework
- You can use distributed training to enhance your deep learning performance even more
- Model parallelism is not a commonly used technique
- Multi-GPU processing works perfectly with the data parallelization concept as it limits the drawbacks of the large neural networks
- Mixed precision is an interesting technique that is not commonly used
- NVIDIA SDK is an advanced tool that can be properly used only if you mastered the basics
- You might want to try cloud services for short-term projects
- On-premise infrastructure offers flexibility, security and stable costs
- If you are building a deep learning infrastructure, you must select the right resources. Please consider the complexity of the deep learning tasks you need to solve and make your choice among GPUs or cloud services based on that knowledge. If you have chosen an on-premise approach, you should study the GPU market using the criteria mentioned above to find the best GPU for your task within your budget
- NVIDIA provides a great set of the model’s architecture examples for various deep learning tasks (Computer Vision, NLP, Recommender Systems, and more)
- You should explore your opportunities as you might find something interesting. For example, cnvrg.io and NVIDIA DGX Data Science Solution. The cnvrg.io platform, running on NVIDIA DGX Systems, provides data scientists with accelerated data science project execution from research to production. All tools for building, managing, experimenting, tracking, versioning, and deploying models are available with one-click
Final Thoughts
Hopefully, this article will help you succeed and use your GPU in your next Deep Learning project effectively.
To summarize, we started with an in-depth comparison of different hardware devices such as GPU, CPU, ASIC, and FPGA, and went through a step-by-step guide on how to choose and assess a GPU. Also, we talked about training neural networks on a GPU from the code perspective. Lastly, we considered some advanced techniques and tools that can be used to accelerate the training process.
If you enjoyed this post, a great next step would be to start building your own Deep Learning project with all the relevant tools. Check out tools like:
Thanks for reading, and happy training!
Resources
-
-
-
-
-
-
-
-
- | https://cnvrg.io/deep-learning-gpu/ | CC-MAIN-2021-43 | refinedweb | 7,808 | 61.46 |
Last Update:
May,
2008
RibbonSoft is the organization behind the development, distribution
and marketing of QCad, CAM Expert, vec2web, the QCad Libraries and dxflib.
QCad is a multi-platform 2D CAD system and the flagship product of
RibbonSoft. All other products are either extending QCad or
side products which were developed for QCad. More..
CAM Expert is a CAM extension for QCad. Due to the very flexible
configuration of CAM Expert, it is possible to create virtually any text
based output format (such as various G-Code formats, HP/GL and other
individual formats). More...
vec2web is a tool for converting CAD drawings (DXF) into bitmaps (BMP, GIF,
PNG, ..) or Postscript. More...
xParrot is a Zope / XML based content management framework that is used
by RibbonSoft to write and translate manuals and other documents.
More...
QCad uses the DXFTM file format to store CAD files. DXF is an industry
standard for exchanging drawings among CAD programs. To make the ability
of dealing with DXF files available to other products, dxflib is released
as an independent product. More...
The QCad libraries are released for developers who need to create CAD related
applications with similar capabilities like QCad. It features drawing views,
import / export filters, creation and modification of entities.
More... | http://www.qcad.org/ | crawl-001 | refinedweb | 209 | 54.02 |
MooseX::Role::Restricted - (DEPRECATED) Restrict which sub are exported by a role
package MyApp::MyRole; use MooseX::Role::Restricted; sub method1 { ... } sub _private1 { ... } sub _method2 :Public { ... } sub private2 :Private { ... }
This module is no longer supported. I suggest looking at namespace::autoclean as an alternative. In its default form MooseX::Role::Restricted simple excludes ann sub with names starting with
_ to be excluded. This can be accomplished using
use namespace::autoclean -also => qr/^_/;
If you are using
lazy_build or other Moose features that require the use of
_ prefixed methods make sure to change the pattern to not match those. Or use some other prefix, for example a double
_, for your private subs that you do not want included in the role.
By default Moose::Role will export any sub you define in a role package. However it does not export any sub which was imported from another package
MooseX::Role::Restricted give a little more control over which subs are exported and which are not.
By default an sub with a name starting with
_ is considered private and will not be exported. However MooseX::Role::Restricted provides two subroutine attributes
:Public and
:Private which can control is any sub is exported or kept private
Graham Barr <gbarr@cpan.org>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | http://search.cpan.org/~gbarr/MooseX-Role-Restricted-1.03/lib/MooseX/Role/Restricted.pm | CC-MAIN-2017-13 | refinedweb | 233 | 54.73 |
What is Hashtable? Hashtable is another useful data structure in C# that allow us to store data using key value pairs. let's learn how to use Hashtable in C# with examples.
Hashtable htObj = new Hashtable();
C# Hashtable is a collection object that comes under System.Collections namespace, Hashtable is similar to generic Dictionary collection object, with some difference like Hashtable allow us to store data of different data type, which is not supported in dictionary object.
Adds an item with a key and value into the hashtable,
below is an example of adding key value in hashtable in C#.
Hashtable htObj = new Hashtable(); htObj.Add(1, "This is string");
Checks whether the hashtable contains a specific key
Removes the item with the specified key from the hashtable
Removes all the items from the hashtable.
Checks if hashtable contains a specific key
Checks if the hashtable contains a specific value.
Gets boolean value indicating whether the Hashtable is read-only.
Gets or sets the value associated with the specified key.
Gets an ICollection of keys in the Hashtable.
Gets an ICollection of values in the Hashtable.
Below is an example of how to get value from hashtable object in C#
Hashtable htObj = new Hashtable(); htObj.Add(1, "This is string"); string strValue1 = (string)htObj[1];
Gets the total count of keys in the Hashtable.
Remember that hashtable works on key/value combination, key or value can be of any data type, look at the example below, this is how we can add key/value to Hashtable
Hashtable htObj = new Hashtable(); htObj.Add(1, "This is string"); htObj.Add(2, 2.2); htObj.Add(3, true); htObj.Add(4, DateTime.Now); htObj.Add(5, null); htObj.Add("Six", "see the key difference");
Now you see how to retrieve value from hashtable, As you have seen that hashtable store values with key, so you can retrieve value using same key, or you can hashtable get value by index.
string strValue1 = (string)htObj[1]; Console.WriteLine(strValue1); DateTime? strValue4 = (DateTime?)htObj[4]; Console.WriteLine(strValue4);
As you have seen that a Hashtable can contains a key and a value of any data type. So while casting, values must be cast to an appropriate data type otherwise it will give compile-time error.
Notice in above example while retrieving data from hashtable, one converted to string and four converted to datetime
Now we have seen that in hashtable we can have different data type for key and values both field, but ideally we should have only same data type for key fields.
Now let’s try to loop through a hashtable c#, all the key values of above hashtable dynamically, htObj.Keys will get all the keys
foreach (int key in htObj.Keys) { Console.WriteLine("Key: " + key + " Value: " + htObj[key]); }
See the error for last key, which is a different data type, when all keys are integer and the last (six) key is a string
So, remember to keep all the keys of same data type while creating a hashtable in C#
You should also look at others C# Data Structures Fundamental. | https://www.webtrainingroom.com/csharp/hashtable | CC-MAIN-2021-49 | refinedweb | 518 | 61.97 |
Created on 2017-08-31 16:25 by Oren Milman, last changed 2017-09-19 12:54 by serhiy.storchaka. This issue is now closed.
The following code causes an assertion failure in get_encoded_name(), which is
called by _PyImport_LoadDynamicModuleWithSpec() (in Python/importdl.c):
import imp
class BadSpec:
name = 42
origin = 'foo'
imp.create_dynamic(BadSpec())
this is because _PyImport_LoadDynamicModuleWithSpec() assumes that spec.name is
a string.
should we fix this (even though imp is deprecated)?
I'm about to go on vacation so I might not be right of mind to comment, but I think throwing a TypeError is valid if it's triggering an assertion error that is already there.
P.S. Thanks for all the fuzz testing you're doing, Oren!
do you mean that we should fix it to raise a TypeError?
the assertion is there, but not explicitly.
get_encoded_name() calls PyUnicode_FindChar(), which calls
PyUnicode_READY(), which does assert(_PyUnicode_CHECK).
so i get:
>>> import imp
>>>
>>> class BadSpec:
... name = 42
... origin = 'foo'
...
>>> imp.create_dynamic(BadSpec())
Assertion failed: PyUnicode_Check(op), file ..\Objects\unicodeobject.c, line 380
Yes, I'm saying that instead of hitting the C-level assertion error an explicit TypeError should be raised (or some other change like calling str() on the object). Either way, a C-level assertion from valid Python code is bad. :)
On Thu, Aug 31, 2017 at 1:32 PM, Brett Cannon <report@bugs.python.org> wrote:
> I think throwing a TypeError is valid if it's triggering an assertion error that is already there.
+1
> P.S. Thanks for all the fuzz testing you're doing, Oren!
Also a big +1. :)
New changeset 9974e1bcf3d0cec9b38b39b39b7ec8a1ebd9ef54 by Serhiy Storchaka (Oren Milman) in branch 'master':
bpo-31315: Fix an assertion failure in imp.create_dynamic(), when spec.name is not a string. (#3257)
New changeset 99a51d4e5b154a7b8d971090fecc1e34769a3ca1 by Serhiy Storchaka (Miss Islington (bot)) in branch '3.6':
[3.6] bpo-31315: Fix an assertion failure in imp.create_dynamic(), when spec.name is not a string. (GH-3257) (#3653)
Thank you Oren! | https://bugs.python.org/issue31315 | CC-MAIN-2020-40 | refinedweb | 332 | 60.92 |
Working faster with tests
Carlos Gándara
Updated on
・5 min read
faster and better testing (3 Part Series)
As we saw in the previous post of this series, we want our tests to provide us with fast feedback about the correct behavior of our application.
In this post, we will touch an aspect of the testing process not usually written about: how to work faster with tests. We will talk about three things you can do to make your testing flow more efficient.
Write them faster!
The book The Pragmatic Programmer, despite being 20 years old, is full of good advice, much of which still applies to modern software development.
One of its tips is this:
Use a Single Editor Well
Modern IDEs have ways to automatize almost everything, and investing some time in knowing the nuts and bolts of the tools you use for most of your coding time absolutely pays off. When it comes to tests, the sooner you get them written the sooner you can start to get feedback from them. What can you do to write them faster?
As an IntelliJ user and PHP programmer, I use PHPStorm as my IDE. Below I describe some functionalities that improve the speed of writing tests substantially. There is likely something similar in whatever tool you use (unless you go full Windows' Notepad, in which case you can skip this whole section).
IntelliJ's IDEs have a templating system for almost all the code they autogenerate for you. When it comes to tests we can, for instance, create them with a setup method setting a new SUT (System Under Test) instance as a property and maybe extending a base test class for the concrete project. Just analyze what you always do manually when creating a test and incorporate it into the test templates.
Then we have the keyboard shortcuts that allow us to navigate between a class and its test(s). If the class has no tests, it will show an option for creating one (which will make use of the aforementioned templates).
Here is a working example of the templating system and keyboard shortcuts in action (well, static action). First the template:
<?php #if (${NAMESPACE}) namespace ${NAMESPACE}; #end #if (${TESTED_NAME} && ${NAMESPACE} && !${TESTED_NAMESPACE}) use ${TESTED_NAME}; #elseif (${TESTED_NAME} && ${TESTED_NAMESPACE} && ${NAMESPACE} != ${TESTED_NAMESPACE}) use ${TESTED_NAMESPACE}\\${TESTED_NAME}; #end use PHPUnit\Framework\TestCase; class ${NAME} extends TestCase { /** @var ${TESTED_NAME} **/ private $sut; protected function setUp() { parent::setUp(); $this->sut = new ${TESTED_NAME}; } public function testSomething(): void { //TODO } }
When, in the body of a class, we press the shortcut for jumping to test, the IDE shows an option to go to one of the available ones or create a new one:
Choosing "Create New Test" will use the template and bring up the following automatically:
<?php namespace Example; use PHPUnit\Framework\TestCase; final class MyClassTest extends TestCase { /** @var MyClass * */ private $sut; protected function setUp() { parent::setUp(); $this->sut = new MyClass; } public function testSomething(): void { //TODO } }
Now, in the test class, using the jump to test shortcut again brings us we will be back in the tested class.
Get in the habit of using these shortcuts and tweak the templates to your needs and you will gain considerable speed when writing tests.
Run them faster!
The less time you invest from the moment your mind thinks I want to run the tests now and the tests start to run, the better. If we somehow automate the process of running tests in some mechanical actions we will do it seamlessly in our coding workflow without losing focus.
If you use IntelliJ IDEs, it is worth knowing about keyboard shortcuts to:
run the tests under the current scope—A single test if cursor is inside a test method or the whole test case if you are in the class but outside a method.
rerun your last run, which is especially relevant when doing TDD.
Also, if you are not familiar with them, run configurations are also an important time saver. You can define them for only unit tests, for only integration tests, or for a concrete suite or folder and then use a keyboard shortcut to run them automatically.
If you are not an IntelliJ user, consider spending some reasonable time in writing scripts that will reduce the time to run your tests suites.
In the PHP world, you have the option to configure Composer (the standard package management tool) scripts to run arbitrary stuff. For instance, this is part of the script section of one of my project's composer.json file:
"scripts": { "test-unit": "phpunit --configuration phpunit.xml.dist --testsuite unit", "test-integration": "phpunit --configuration phpunit.xml.dist --testsuite integration", "test-functional": "phpunit --configuration phpunit.xml.dist --testsuite functional", "test-all": "phpunit --configuration phpunit.xml.dist", "all-checks": [ "parallel-lint . --exclude vendor --exclude var", "phpcs -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests", "phpunit --configuration phpunit.xml.dist", "vendor/bin/phpstan analyse" ] },
So, running a terminal
composer test-unit will run all my unit tests. It is the same for other suites. And there is this handy
composer all-checks that will run linters, tests, and PHPStan, all in one.
Run them often!
So, now you can implement your tests in a breeze and run them with a subsecond, lightning-fast hand movement. It would be a waste not to use this superpower, so try introducing the act of running tests in your coding flow as something natural. This is a must to get these so desirable fast feedback loops.
If you do TDD (and you should), it is a core part of the process. If not, train yourself. Even more, given we trend to forget stuff, might it be a good idea to somehow enforce running our tests with every commit we do.
In the IntelliJ world you can configure scripts to run before doing a commit. This implies using git through the IDE's GUI.
Another option is to configure your project git hooks to run the tests before a commit, canceling it if they are not green.
Or even aliasing shell commands, so you just do not commit even more but test-and-commit always.
Tools like GrumpPHP, obviously in the PHP ecosystem, help for those automations.
Do not stop with tests!
All the previous advice focuses on tests, but for sure your spider powers have already been activated and you noticed these tips apply to the whole coding process.
One thing we programmers do is automatize solutions to problems. Investing time in doing so for tasks we do over and over every day seems like a good move.
Summarizing
We have seen three ways to speed up writing and using tests:
- Writing them faster.
- Running them faster.
- Running them often.
These three ways can be automatized with the technology we use on a daily basis. So, give it a try!
Further reading
- This article talks about optimizing what you do most of time, not what you do not do.
- As usual, is not a good idea to overengineer. Listen to XKCD and think about the effort vs the value.
faster and better testing (3 Part Series)
Why is Linux Not More Popular on the Desktop?
Picture taken from wikipedia. There are issues when it comes to Linux being mo...
Nice article 👍 👍 thanks!
Glad you liked it! | https://practicaldev-herokuapp-com.global.ssl.fastly.net/docplannertech/working-faster-with-tests-31mn | CC-MAIN-2019-39 | refinedweb | 1,217 | 63.09 |
When debugging applications, it is often useful to have a debugging framework that will allow you to control the amount of output generated.
This class does not have the extensibility of the java.util.logging package that is part of the Java(TM) 1.4 release. If you require a more feature rich logging facility, I suggest you use the one provided by the java.util.logging package.
java.util.logging
When I started actually using Java, it was for the purposes of learning Java. I generally don't use Java in my daily job duties, but wanted to be proficient in it. Since I was trying to learn how things worked inside of Java applications and applets, I needed a way to print debugging information. I came up with the com.rl.debug package. Soon after writing this package, I found the java.util.logging package that is part of the Java 1.4.x release.
com.rl.debug
The Debug class, which is part of the com.rl.debug package, follows a simple "hierarchical" logging method. Each debug message is assigned a level. Based upon the level of the message and the current logging level set in the debugging class, the message may or may not be output. All messages which meet the current logging level or higher are logged.
Debug
Since the current 1.4.x release of Java contains a very powerful and extensible logging framework in the java.util.logging package, why use anything else? Good question. Here are some points that I think will help a developer to make that choice.
ConsoleHandler
INFO
NONE
I am sure there are many other arguments that can be given for both of these packages. I think those presented here are enough to show the value of each, and to give a good basis for deciding which one is right for your own project.
To use the Debug class, you need a reference to a singleton instance. You can obtain this by using the getLogger() method.
getLogger()
Obtaining an instance of the Debug class.
// Obtain an instance of the default logger
private static Debug log = Debug.getLogger();
// Obtain a named logger
private static Debug namedLog = Debug.getLogger("LogFile");
You can set the level of detail output by the Debug class, by using the setLevel() method. The following code will log messages that are WARNING or higher.
setLevel()
WARNING
// Set the debug level to WARNINGS or higher.
log.setLevel(log.WARNING);
By default, all messages are logged to the System.err print stream. This can be changed using the setPrintStream method.
System.err
setPrintStream
import com.rl.debug.*;
import java.io.*;
public class TestDebug {
public static void main(String argv[]) {
FileOutputStream logFile = null;
PrintStream p = System.out;
try {
logFile = new FileOutputStream("TestDebug.log", true);
p = new PrintStream((OutputStream)logFile, true);
} catch (Exception e)
{
}
Debug log = Debug.getLogger();
Debug logger = Debug.getLogger("LogFile");
logger.setPrintStream(p);
log.setLevel(DebugLevel.ALL);
logger.setLevel(DebugLevel.WARNING);
log.DebugOut("We be a log!");
logger.DebugOut("We be a logger!");
log.DebugOut("I be saying I a logger!");
logger.warning("TestDebug", "main", "This is a warning");
log.setLevel(DebugLevel.WARNING);
log.DebugOut("We should not show up.");
logger.DebugOut("We should not be loggered");
log.DebugOut("I said, no output!");
logger.warning("TestDebug", "main",
"This is a warning with a WARNGING level.");
}
}
The above examples should be enough to get you going. I suggest you read the comments in the code. The comments should be enough to explain how to use a particular feature. Of course, I have heard that argument before. :)
I must warn you that I have not tested this class for thread safety, so treat it as not safe.
Happy coding.
Ideally it would be nice to provide your own custom format for outputting the messages. I have considered implementing this and may in the future. However, if you really need that flexibility, you should probably just use the java.util.logging package. Perhaps, if I get some feedback and a sense that formatting is really wanted, I will implement it. For now, I think the code is about as functional as it needs to be.
After sleeping it over, I realized that I had an awful log of static items that just don't need to be. I modified it so that the private members are no longer static and the only static methods are the getLogger methods.
getLogger
After doing this, I realized it would be nice to have some information in my application logged to the console, while other information went to a file. Once I made the private members not static, this was possible, but only if I had more than one instance of the Debug. This would allow me to set PrintStream on one and not affect the other. To facilitate this, I removed the class member m_logger and added the class member m_loggers. m_loggers is a hashtable of the loggers. This keeps the loggers accessible at a class level and keeps existing applications from breaking. It also now allows you to maintain multiple loggers. I updated the sample code to reflect the new version.
PrintStream
m_logger
m_loggers
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here | http://www.codeproject.com/Articles/3770/A-Debugging-Package-for-Java | crawl-003 | refinedweb | 908 | 58.99 |
This is a discussion on Re: Remarks on draft-stjohns-dnssec-sigonly - DNS ; Hi Andrew - Thanks for the thoughtful analysis. With respect to off-tree signatures - a zone admin could add an off-tree pointer at any point in a hierarchy and then you could rely upon the pointer if the validator actually ...
Hi Andrew -
Thanks for the thoughtful analysis.
With respect to off-tree signatures - a zone admin could add an
off-tree pointer at any point in a hierarchy and then you could rely
upon the pointer if the validator actually got it. The problem is
that without some external flag (in PNE - that's the set of trust
anchors) - the resolver doesn't even know the hierarchy should be
signed; a simple deletion of the off-tree pointer would put the zone
back into unsecure status. If you added this, you'd be basically
creating something about half way between PNE and SO - maybe a
reasonable idea, but my guess is that it makes the PNE validator even
more complex. :-) It would definitely change the security model at
least as much as SO does.
With respect to the item below and
draft-ietf-dnsext-dnssec-opt-in-09.txt: If I'm reading this document
correctly, I think my statement still stands (for 4033-4045 for sure
and for this document maybe). What the document does is replace a
chain of NSEC (delegation here, but no DS) records with a single NSEC
(no DS records in the span). The entire namespace of the zone does
continue to be signed, but in a summary way. (Of course, you can put
other things in the span besides delegations, but as I read the
document - that's not the intent. The document is silent on the
treatment of other records in the "opt in span". It would be
interesting to try and figure out what the proper behavior for a
normal, non-delegation (e.g. not NS, not DS, not glue A) record in
that space would be - my guess is that anything in the span is
subject to a deletion attack.
What I meant by partial signing was the ability to sign only one or a
few RRSets (e.g. the MX records plus the referred to A records plus
the DNSKEY records) - the ones I really might want people to care
about - and still have a validly signed zone. I *think* if you did
opt in, and did an opt nsec record "zonename nsec zonename" - you
*might* get the same behavior? Again, hard to tell as the document
really doesn't talk about non-delegation records.
Mike
At 04:09 PM 12/20/2006, Andrew Sullivan wrote:
.
--
to unsubscribe send a message to namedroppers-request@ops.ietf.org with
the word 'unsubscribe' in a single line as the message text body.
archive: | http://fixunix.com/dns/59528-re-remarks-draft-stjohns-dnssec-sigonly.html | CC-MAIN-2014-52 | refinedweb | 474 | 68.1 |
UFDC Home | Help | RSS TABLE OF CONTENTS HIDE Front Cover Title Page Acknowledgement Dedication Table of Contents Preface Chapter 1: Introduction Chapter 2: The small-scale family... Chapter 3: Economic characteristics... Chapter 4: Initial characterization... Chapter 5: Designing alternative... Chapter 6: Technology development... Chapter 7: Organization for... Copyright Title: Perspectives on farming systems research and extension CITATION PAGE IMAGE ZOOMABLE PAGE TEXT Full Citation STANDARD VIEW MARC VIEW Permanent Link: Material Information Title: Perspectives on farming systems research and extension Alternate Title: Farming systems research and extension Physical Description: xiv, 167 p. : ill. ; 24 cm. Language: English Creator: Hildebrand, Peter E Publisher: L. Rienner Place of Publication: Boulder Colo Publication Date: 1986 Subjects Subject: Family farms ( lcsh )Farms, Small ( lcsh )Agricultural innovations ( lcsh )Agricultural systems ( lcsh )Agricultural extension work ( lcsh )Agricultural systems -- Research ( lcsh ) Genre: bibliography ( marcgt )non-fiction ( marcgt ) Notes Bibliography: Includes bibliographies. Statement of Responsibility: edited by Peter E. Hildebrand. Funding: Electronic resources created as part of a prototype UF Institutional Repository and Faculty Papers project by the University of Florida. Record Information Bibliographic ID: UF00072280 Volume ID: VID00001 Source Institution: University of Florida Holding Location: University of Florida Rights Management: All rights reserved, Board of Trustees of the University of Florida Resource Identifier: aleph - 000894800oclc - 13457045notis - AEK3365lccn - 86010029 isbn - 093147793X : Table of Contents Front Cover Front Cover Title Page Page i Page ii Page iii Acknowledgement Page iv Page v Page vi Dedication Page vii Page viii Table of Contents Page ix Page x Page xi Page xii Preface Page xiii Page xiv Page xv Chapter 1: Introduction Page 1 The need for new strategy Page 1 Page 2 Page 3 Page 4 Page 5 Page 6 Page 7 Page 8 Page 9 Page 10 Page 11 Farming systems research and development Page 12 Page 13 Page 14 Page 15 Page 16 Chapter 2: The small-scale family farm as a system Page 17 Human society Page 17 Page 18 Page 19 Page 20 Page 21 Page 22 Page 23 Page 24 Page 25 Page 26 Page 27 Page 28 Hierarchical agricultural systems Page 29 Page 30 Page 31 Defining a farming system Page 32 Page 33 Prevailing farming systems by regions Page 34 Page 35 Page 36 Page 37 Page 38 Characteristics of selected systems Page 39 Page 40 Page 41 Page 42 Page 43 Page 44 Page 45 Page 46 Page 47 Page 48 Page 49 Page 50 Page 51 The concept of "homogeneous systems" and its usefulness Page 52 Hierarchy of constraints to system productivity Page 53 Page 54 Page 55 Page 56 Chapter 3: Economic characteristics of small family-farm systems Page 57 Economic characteristics of small-scale, limited-resource family farms Page 57 Page 58 On the non-neutrality of scale of agricultural research Page 59 Page 60 Page 61 Page 62 Page 63 Page 64 Page 65 The puzzle: Panajachel, Guatemala Page 66 Page 67 Page 68 Unforeseen consequences of introducing new technologies in traditional agriculture Page 69 Page 70 Page 71 Page 72 Page 73 Response to technological change Page 74 Page 75 Page 76 Page 77 Page 78 Page 79 Page 80 Chapter 4: Initial characterization of farming systems: Comprehending and utilizing what we see and hear Page 81 Anthropological perspectives on contemporary human problems Page 81 Page 82 The art of the informal agricultural survey Page 83 Page 84 Page 85 Page 86 Page 87 Page 88 Page 89 Page 90 Page 91 Page 92 The sondeo: A team rapid survey approach Page 93 Page 94 Page 95 Page 96 Page 97 Comparing informal and formal surveys Page 98 Page 99 Page 100 Page 101 Page 102 Chapter 5: Designing alternative solutions and improved practices Page 103 Necessary and sufficient conditions for adoption of improved practices Page 103 Human problems in technological change Page 104 Page 105 Page 106 Prescreening potential technological components Page 107 Page 108 Page 109 Page 110 Page 111 Page 112 Page 113 Page 114 Page 115 Page 116 Infrastructural support for technological change Page 117 Page 118 Page 119 Page 120 Design of technology Page 121 Page 122 Page 123 Examples of planning on-farm experiments Page 124 Page 125 Page 126 Page 127 Empirical results of farming systems research Page 128 Page 129 Page 130 Page 131 Page 132 Chapter 6: Technology development and continuing characterization Page 133 Enterprise records (A form of multiple visit survey) Page 133 Page 134 Page 135 Page 136 Types of on-farm trials Page 137 Research to test the value of recommended practices Page 138 Page 139 Page 140 Page 141 Page 142 Page 143 Page 144 Page 145 Page 146 Page 147 Farmer-managed trials Page 148 Page 149 Page 150 Page 151 Page 152 Page 153 Page 154 Chapter 7: Organization for development Page 155 Page 156 Page 157 Page 158 Page 159 Page 160 Page 161 FSR/E regions and field teams Page 162 Page 163 Page 164 Page 165 Page 166 Page 167 Copyright Page 168 Page 169 Full Text Perspe c t i v e s on FARMING SYSTEMS RESEARCH and EXTENSION Edited by Peter E. Hildebrand RI Pers p e c t i ves on FARMING SYSTEMS RESEARCH and EXTENSION Edited by Peter E. Hildebrand Perspectives on FARMING SYSTEMS RESEARCH and EXTENSION Published in the United States of America in 1986 by Lynne Rienner Publishers, Inc. 948 North Street, Boulder, Colorado 80302 a 1986 by Lynne Rienner Publishers, Inc. All rights reserved Library of Cq ress atalogg-i'PbhliatHm Data Perspectives on farming systems research and extension. 1. Agricultural systems. 2. Agricultural systea-- Research. 3. Agricultural extension work. 4. Agricul- tural innovations. 5. Family farms. 6. Fanrs, snall. I. Hildebrand, Peter E. S494.5.S95P47 1986 631,5 86-10029 Distributed outside of North and South America and Japan by Frances Pinter (Publishers) Ltd, 25 Floral Street, London WC2E 916 aEgland UK ISN 0-86187-669-5 Printed and bound in the United States of America The paper used in this publication meets the requirements of the American National Standard far oPenmence of Paper for Printed Library Materials 239.48-1984. ACKNOWLEDGMENTS Chapter 1 Introduction Fro mhyte, Willian F. "Participatory Approaches to Agricultural Research and Development: A State-of-the-Art Paper," vol. 3, no. 1. Ithaca, New York: Rural Development Caurittee, Center for International Studies, Carnell University (1981): 1-6. Reprinted with permission of the publisher. rom Hildebrand, Peter E., and R.K. Waugh. "Farning Systems Research and Development." SSP Newsletter vol. 1, no. 1 (1983): 4-5. By permission. Chapter 2 The Smal-Scale Family Farm as a System Excerpted from Shapiro, Harry L., ed. Man, Culture, and Society. Copyright o 1956, 1971 by Odford University Press, Inc.; renewed 1984 by Hary L. Shapiro. Reprinted by permission of the publisher. Excerpted fram Shaner, W.W. Readings in Farming System Research. Copyright o1982 by Colorado State University. Boulder, Colorado: Westview Press. Reprinted with permission of the publisher. Frcm Norman, D.W. "Dhe Farming Systems Approach: Relevancy for the Smll Farmer," MSU Rural Develo nt Paper No. 5. Fast lansing, Michigan: Michigan State University (19M0): 2-4. By permission. romn mcuoau, R. E., and P. E. Hildebrand. "Integrated Crop and Animal Production: Making the Mbst of Resources Available to Small Farns in Developing Countries." The Rockefeller Foudation Working Papers. New York: The Rockefeller Foundation (1980): 9-15. By penmisssion. Fran McDowell, R. E., and P. E. Hildebrand. 'Integrated Crop and Animal Production: Making the Most of Resources Available to Snall Farms in Developing Countries." The Rockefeller Foundation Working Papers. New York: The Rockefeller Foundation (1980): 17-25, 36-39, 51-56. By permission. Excerpted from Hildebrand, P. E. Working Paper, Institute of Food and Agricultural Sciences (IFAS), International Programs, Farming Systems Support Project. Gainesville, Florida: University of Florida (1983). By permission. Excerpted front Hildebrand, P. E. The Farmin Systems Approach to Technology Development and Transfer. Water Managemet Synthesis II Project, International Irrigation Center. Logan, Utah: Utah State University (1983): 31-35. By permission. Chapter 3 Econaomc Qaracteristics of Snall Family Farm Systems First two readings front Hildebrand, P. E. IWrking Paper, Institute of Food and Agricultural Sciences (IFAS), International Prograns, Farming Systems Support Project. Gainesville, Florida: University of Florida (1983). By permission. Excerpted from Schultz, Theodore W. Transforming Traditional Agriculture. New Haven, Connecticut: Yale University Press (1964): 33-35, 41-44. Reprinted with permission of the publisher. Fran Hildebrand, P. E., and Edgar G. Luna. Paper presented at Session No. 5, Public Investment in Research, Fducation, and Technology, Fifteenth Conference of Agricultural Economics. Sao Paulo, Brazil (1973). By peradession. Excerpted front Wharton, C. R., Jr., ed. Subsistence Agriculture and economic Develobent. Ocago: Aldine Publishing Copany (1969): Chapter 7. Reprinted with permission of the publisher. Chapter 4 Initial characterization of Farming System Excerpted fran Bodley, J. H. Anthropoloy and Contenporary Humn Problems. Menlo Park, California: The Benjami/mOmJugs Publishing Company (1976): 10-12. Reprinted with permission of the publisher. From Rhoades, R. E. Training Document. Social Science Department, International Potato Center, Lima, Peru (1982). Fram Hildebrand, P. E. Cacbining Disciplines in Rapid Appraisal: The Sondeo Approach." Agricultural Administration 8. (1981): 423-432. From Franzal, Steven. paringig the Results of an Infornal Survey with Those of a Formal Survey: A Case Study of Farming Systems Research/Extension (PR/E) in Middle Kirinyaga, Kenya." Paper presented at the Farming Systes Research and Etension Symposium, Manhattan, Kansas (1984). Chapter 5 Designing Alternative Solutions and Improved Practices From Norman, D. W. "The Farming Systems Approach to Research." Paper presented at the Farming Systems Research Symposiun "Farmrng Systems in the Field," Kansas State University, Manhattan,. Kansas (1982): 5. Fran "Foreword and Introduction," by Alexander H. Leighton and Ediard H. Spicer, respectively, in HuIan Problems in Technological Change: A Casebook edited by Edward H. Spicer. 1952 by Russell Sage Foundation. Reprinted by permission of Basic Books, Inc., Publishers. From Planning Technologies Appropriate to Farmers: Concepts and Procedures. Mexico: CIfIY (1980): Chapter 11. By permission. Fran Zandstra, H., and K. Swanberg, C. Zulberti, and B. Nestel. Caque Living Rural Development. Ottawa: International Development Research Center (IRC) (1979): 255-258. Reprinted with pernlsssion of the publisher. From Gilbert, E. H., D. W. Norman, and F. E. Winch. IJ Rural DevelopIent Paper No. 6. East Lansing, Michigan: Michigan State University (1980): 51-54. By permission. Fran Planning Technologies Appropriate for Farners: Concepts and Procedures. Mexico: CIMAYT (1980): Qhapter 12. By permission. Fran Norman, D. W. 'The Farming Systems Approach: Relevancy for the Small Farner," MSU Rural Development Paper No. 5. East Lansing, Michigan: Michigan State University (1980): 10-20. By permission. Chapter 6 Technology Development and Continuing Characterization Excerpted froa Shaner, W. W., P. F. Phillip, and W. R. Schmehl. Farming Systems Research and Development: Guidelines for Developing Countries. Copyright 1982 by Consortium for International Development. Boulder, Colorado: Westview Press: Appendix 5-x, 309-314. Reprinted with permission of the publisher. Fran Hildebrand, P. E., and F. Poey. 'On-Farm Agroncmic Trials," Faming System Research and Extension. Boulder, Colorado: Lynne Rienner Publishers, Inc. (1985): 6-8. Reprinted with permission of the publisher. Excerpted from Zandstra, H., K. Swanberg, C. Zulberti, and B. Nestel. Caqueza: Living Rural Development. Ottawa: International Development Research Center (IIIC) (1979): Chapter 10, 160-189. Reprinted with permission of the publisher. From Hildebrand, P. E., and F. Poey. '"n-Farm Agronanic Trials," Faring Systems Research and Extension. Boulder, Colorado: Lynne Rienner Publishers, Inc. (1985): 115-147. Reprinted with permnrssion of the publisher. Fran Hildebrand, P. E. 'b-Farm Research: Organized Camunity Adaptation, Learning and Diffusion for Efficient Agricultural Technology Innovation," FSSP Newsletter, vol.3, no.4 (1985): 6-9. By permission. Fran Hildebrand, P. E., E. Martinez, and R. Ortiz. generalizedd Organization of FSR/E Regions and Field Teams," FSSP Newsletter, vol.3, no.2 (1985): 1-3. By permisssion. To Maria and Annie with love Contents PREFACE xi 1. INTRODUCTION 1 The Need for a New Strategy William F. Whyte 1 Farming Systems Research and Development Peter E. Hildebrand and Robert K. Waugh 12 2. THE SMALL-SCALE FAMILY FARM AS A SYSTEM 17 Human Society Robert Redfield 17 Hierarchical Agricultural Systems Robert D. Hart 29 Defining a Farming System David W. Norman 32 Prevailing Farming Systems by Regions Robert E. McDowell and Peter E. Hildebrand 34 Characteristics of Selected Systems Robert E. McDowell and Peter E. Hildebrand 39 The Concept of "Homogeneous Systems" and Its Usefulness Peter E. Hildebrand 52 Hierarchy of Constraints to System Productivity Peter E. Hildebrand 53 3. ECONOMIC CHARACTERISTICS OF SMALL FAMILY-FARM SYSTEMS 57 Economic Characteristics of Small-Scale. Limited-Resource Family Farms Peter E. Hildebrand 57 ix On the Non-Neutrality of Scale of Agricultural Research Peter E. Hildebrand 59 The Puzzle: Panajachel, Guatemala Theodore W. Schultz 66 Unforeseen Consequences of Introducing New Technologies in Traditional Agriculture Peter E. Hildebrand and Edgar G. Luna 69 Response to Technological Change John W. Mellor 74 4. INITIAL CHARACTERIZATION OF FARMING SYSTEMS: COMPREHENDING AND UTILIZING WHAT WE SEE AND HEAR 81 AnthropologicalPerspectives on Contemporary Human Problems J. H. Bodley 81 The Art of the Informal Agricultural Survey Robert E. Rhoades 83 The Sondeo: A Team Rapid Survey Approach Peter E. Hildebrand 93 Comparing Informal and Formal Surveys Steven C. Franzel 98 5. DESIGNING ALTERNATIVE SOLUTIONS AND IMPROVED PRACTICES 103 Necessary and Sufficient Conditions for Adoption of Improved Practices David W. Norman 103 Human Problems in Technological Change Edward H. Spicer 104 Prescreening Potential Technological Components CIMMYT 107 Infrastructural Support for Technological Change Hubert Zandstra, Kenneth Swanberg, Carlos Zulberti, and Barry Nestel 117 Design of Technology Elon H. Gilbert, David W. Norman, and Fred E. Winch 121 Examples of Planning On-Farm Experiments CIMMYT 124 Empirical Results of Farming Systems Research David W. Norman 128 6. TECHNOLOGY DEVELOPMENT AND CONTINUING CHARACTERIZATION 133 Enterprise Records (A Form of Multiple Visit Survey) William W. Shaner, Perry F. Phillip, and Willard R. Schmehl 133 Types of On-Farm Trials Peter E. Hildebrand and Federico Poey 137 Research to Test the Value of Recommended Practices Hubert Zandstra, Kenneth Swanberg, Carlos Zulberti, and Barry Nestel 138 Farmer-Managed Trials Peter E. Hildebrand and Federico Poey 148 7. ORGANIZATION FOR DEVELOPMENT 155 FSR/E in a Community Context Peter E. Hildebrand 155 FSR/E Regions and Field Teams Peter E. Hildebrand, Eugenio Martinez, and Ramiro Ortiz 162 Preface As this book goes to press, several important events related to farming systems research and extension have occurred. In February 1986, the International Agricultural Research Centers held a conference in Hyderabad, India, where they confirmed the importance of the farming systems concept as a method for reaching the majority of the world's farmers with new technology. In April 1986, the Office of Technology Assessment commissioned a paper to help the Congress of the United States evaluate farming systems as a means of solving rural poverty and hunger, particularly in Africa. The World Bank, after assessing the disappointing impact of the Training and Visitation extension system, has decided that farming systems must become a part of the technology innovation process in order to provide the technology necessary for the T and V system to be effective. In all, the Farming Systems Support Project has accumulated a current list of 253 farming systems projects in Asian, African, and Latin American countries. These are funded by many internation- al donors in combination with the national budgets of those countries. In addition, several of the land grant universities in the United States have initiated farming systems projects in their own states. This collection of readings is designed to provide back- ground and historical perspective cn farming systems research and extension. As the collection originated, it was much longer and contained both background and required readings for the farming systems. research and extension methods course offered at the University of Florida. It was also used for short courses, approximately one week in length, taught under the auspices of the USAID-funded Farming Systems Support Project at the University of Florida and several other U.S. campuses and foreign locations. In order to reduce the volume of reading required of the participants in these courses, the readings were reduced to a minimum set. It is difficult to put together a book of readings in a field that is developing as fast as is farming systems. Each year new basic readings appear that should be included. However, xiii it was thought that a book of background readings would be useful to provide a perspective on the development of the ap- proach. The majority of the articles appeared in the 1980s, although much of the information contained in them was developed during the 1970s, when farming systems began to gain momentum. Selections are taken from the biological, the social, and the economic sciences, as should be expected from an activity that requires multidisciplinary participation. Articles have been abbreviated or excerpted--in some cases only one or two key paragraphs are included. Some of the papers have been written specifically for this book. Grateful appreciation is expressed for the kind permission granted to use all the articles. I want to especially thank Jeanette Romero, who worked with me for several years and typed many drafts of the book, and Dorita Osorio, able replacement, upon whom fell the responsi- bility for typing the final version. Thanks also are due to all the students and fellow farming systems professionals who contributed many thoughts and suggestions on what to include or exclude. Their continuing interest has provided the incentive to complete this volume. Peter E. Hildebrand Perspectives on FARMING SYSTEMS RESEARCH EXTENSION EXTENSION of countries. Yet as many critics have noted, the new technology has tended to favor those rural producers already in relatively advantageous positions, doing much less to improve the lot of the rural majority, even in some cases having negative effects by spurring labor displacement or land concentration. This uneven impact of the new technology has not been a con- sequence simply of different sizes of landholdings. While on the average, larger farmers have benefited from it more than smaller farmers, studies sponsored by the International Rice Research Institute in Asia have found that where small farmers were cultivating irrigated land, they tended to adopt the new technology about as rapidly as the larger farmers and to reap substantial benefits. Indeed, their more intensive use of labor produced higher yields per acre than on larger, less intensively cultivated farms. The new technology, however, by concentrating on achieving the largest possible increases in yield, required good water control, application of chemical fertilizer, herbicides, pesti- cides, etc., even in some instances, mechanical power. Such conditions could not be generally met by smaller, poorer farmers. Indeed, worldwide we find that only about 15 percent of land under cultivation is served by irrigation systems, so this means that farmers on about 85 percent of the total area will benefit much less from innovations developed for irrigated land. Some of the agricultural research programs are broadening the objectives in their plant breeding programs. We find IRRI, CIMMYT, and other international research centers, as well as their national agricultural research counterparts, increasingly working on upland crops and on improvements like inbred pest and disease resistance, nitrogen fixation, etc. Yet even as these laudable new efforts are launched, there is reason to be concerned that the very style and organization of most current agricultural R and D will not adequately take account of the cir- cumstances of small farmers and improve their productivity, for reasons discussed later. We do not wish to discount the great achievements in agri- cultural science and technology to date or to underestimate the potential for economic and social gains through agricultural research in the future. We begin our review with a recognition that the agricultural sciences have been enormously successful in some important respects. Without the advance of the so-called "Green Revolution," worldwide production of cereal grains would be far less than it is today, and the brunt of shortfalls would surely fall on the poorest sectors of society. Existing agricultural R and D strategies have not given much direct support to those farmers who struggle to survive under conditions of climate, soil, and water which are much less favorable than assumed by the "Green Revolution" technology. Moreover, they labor and produce within systems of agricultural production far more complex than the "primitive" stereotype we usually have of "peasant" farming (Harwood 1979; also Wharton 1969; Loomis 1976; Scrimshaw and Taylor 1980, pp. 86-88). We need to come to terms with these circumstances if agricultural R and D is to assist the poor rural majority as LDC governments and donor agencies intend. We do not assume that a new agricultural R and D model will be able to transform all rural people into productive farmers able to feed their families and have some surplus to sell for cash income. In the first place, there are many millions of landless rural families. Among those who own no land at all, a substantial part of the rural population has access to land only under highly oppressive conditions of tenancy (Esman 1978; Rosenberg and Rosenberg 1978; Lassen 1979; Harik 1979). Research in the plant and animal sciences can hardly be expected to benefit them substantially unless land tenure conditions are changed. In the second place, there are millions of near- landless households -- minifundistas as they are called in Latin America -- who own so little land that they have no possibility of growing enough food to feed their families, let alone having any. surplus to market. Improvements in their well-being will also depend in large measure on the generation of new employment opportunities. While most of our attention here is focused on small farm- ers who are the next level up, owning enough land to have a possibility of becoming self-sufficient in food production and even producing a small surplus, we are also concerned with these minifundistas. While it may be impossible for this category to make their small farms produce enough to feed their families and also bring in a small cash income, we should not conclude that plant and animal sciences can do nothing for them. Around the world, there are millions of minifundistas who are at least able to meet some of their families' food consumption needs through their own farm work and at the same time have members of their families work off their farms, either for larger farmers elsewhere or in nonagricultural occupations, thus bringing in some income to buy food and some of the other necessities of life. Such families might profit significantly from increases in the efficiency of their farms; but changes in their practices which would require substantially more farm work (when they are already working a great deal off the farm), or a substantially greater expenditure on inputs (when cash is very scarce), might involve sacrifices of opportunities for off-farm employment or of consumption that would make the changes seem impractical to such farmers. This fact means that researchers and extensionists must go beyond dealing with one crop at a time, rather considering the pattern of the farming system as a whole and relating that farming system to the total economic and social environment of the rural family. Having opened up far larger problems than we can deal with in an introduction, we begin with discussion of deficiencies in conventional agricultural research and development strategies. Our purpose is not to make negative arguments but rather to determine what lessons can be learned from past experience for deriving more fruitful R and D models for the future. RECOGNIZING SHORTCOMINGS IN CONVENTIONAL STRATEGIES Agricultural research and development models have mostly been created in industrialized nations and then have been introduced into developing nations. Although some implications are involved, it is instructive to consider two general types of models that have been transferred. The first type, the European colonial model, was already introduced before World War II in the African and Asian colonies. The second type was developed after 1945 through U.S. technical and financial assistance in Latin America and some Middle Eastern and Asian nations. The European colonial model was based primarily upon large- scale plantations devoted to production of crops for export - and particularly for export to the mother country. In some cases, these plantations developed a high degree of productivity and efficiency, based on thorough farm management backed up by high quality research in the plant sciences. Until shortly before the end of the colonial period however, such research was concentrated largely upon export crops, thus providing for no technical assistance to the small farmers who were raising crops for home consumption and for local marketing. When researchers finally began experimentation on domestically consumed crops, the plantation system did not lend itself to effective work with small farmers. Thus, the Europeans and their African and Asian research counterparts were in need of a new agricultural research and development model. The structure of the European model, in its initial concep- tion and supporting philosophy, was distinctly "vertical." Research was carried out in the laboratories and sent "down" to the plantation, where production could be closely supervised and controlled, as in a traditional industrial organization. Any feedback was definitely "upwards" to the scientist who guided the operation. Naturally, adapting this model for work with small farmers proved difficult. With the passing of the colonial era, the U.S. model of agricultural research and extension gained in popularity and influence. Indeed, in the late 1940s, many U.S. experts assumed that transplantation of their model to developing nations could result in the same increase in productivity and farmer income as had occurred in the United States. The Point IV program, designed to bring technological and financial assistance to agriculture in developing nations, carried with it the model of American "land grant" universities linked to an extension service taking the results of university-based research "out" to farmers. If the system worked as intended, it brought farmers' experience and problems "back" to the researchers at the university or experiment station. This model was intended to be "horizontal," although in practice this second model can resemble the first by having essentially a one-way flow of initiatives and information. As is well known in studies of industry and government, in a vertical organization it is much easier to transmit information accurately downward than upward, and initiation of changes from below is likely to be especially difficult. The horizontal model was intended to overcome this imbalance in flow of communication and exercise of influence. In the 1950s and 1960s, the United States spent millions of dollars to expand and strenghten agricultural extension in Latin America and also in some Middle Eastern and Asian nations. Toward the end of this period, AID commissioned an evaluation (Rice 1971) to determine the effects of these expenditures in the Andean nations. The study sought evidence in concrete terms of increased yields or other quantitative indices of improvement. The author was not seeking to discredit agricultural extension. On the contrary, he made an exhaustive search for any solid indications that this enormous expenditure by the U.S. and by the host nations had produced measurable benefits, but with no success. As we examine the factors underlying the failure of the at- tempted U.S. transplant to become broadly effective, we should recognize that program planners focused mostly on one part of the model agricultural extension. Until the failure of this partial transplant became evident, they did not undertake to build in developing countries (or were not able to build) the other components, particularly the university- and experiment-station- based research programs, which were vital features of the U.S. model. The failure of the agricultural extension system to produce expected benefits cannot be attributed to any single cause. It will be instructive to describe some of the main fac- tors that were involved, however. LIMITATIONS IN EXTENSION STRATEGY The strategy employed in agricultural extension also in- volved the now discredited assumption still implicit in the commonly used phrase, "transfer of technology." The term is seriously misleading because it implies that small farmers have such inadequate knowledge about agriculture that they must depend upon the professionals to provide them with the information and ideas to improve production. We find many common deficiencies in knowledge and ability on the part of extension agents. In most developing countries, college education and even high school education had been confined largely to persons coming from urban families. Men of such background employed as extension agents often had little or no actual farming experience, and, furthermore, their education had been largely a matter of book learning. Therefore, one usually had a young and inexperienced extension agent dealing with a middle-aged farmer. That farmer was likely to discover rather quickly that the agent was without practical experience and might not know what he was talking about. The agent, lacking confidence in his own farming ability, would be inclined to compensate for his insecurity by emphasizing the superior importance of his book learning. Relationships built upon such a foundation could hardly lead to constructive outcomes. Even when the extension agent has been able to combine some practical knowledge with his formal learning, and has learned to relate well to peasant farmers, his effectiveness can be undermined by the scope of work he is expected to cover in tasks, territory, and population. In a study of the extension of high-yielding rice varieties in Tamil Nadu State of India, agents were responsible for supervising 30 or more other schemes, many of which had multiple operational components (one included promotion of five varieties, a loan program, and fertilizer distribution). In addition, the extension agent was to submit a 21-page monthly report which could take up to a week to complete (Heginbotham 1975 pp. 107-108). Superiors freely demanded still other reports and soil samples from hundreds of randomly selected locations, setting "targets" beyond any human capability to achieve (pp. 112-119). That the HYV program did not make more progress was at least partly due to the irrationality of extension administration, though the top administrators could blithely insist that all targets were "rationally decided." In neighboring Andhra Pradesh State, a study found extension officers spending 19 to 44 percent of their time in preparing and maintaining reports and returns, ana that District Agricultural Officers had about 125 reports (weekly, monthly, quarterly, half-yearly, and annual) to submit (Reddy 1981 p.103). In Kenya, where monthly work loads of extension staff were analyzed in terms of the targets already set, meeting all of them would require as much as 474 percent of the available staff time (Chambers 1974 p.66). In such situations, it becomes "rational" for the agents themselves to adopt strategies vis-a-vis farmers that protect their careers, giving precedence to reports over fieldwork, or in their fieldwork focusing on richer farmers who are more inclined to cooperate and who have larger holdings so they can take more of the proffered seeds and fertilizer and thereby make the agent's performance record look better. In a study of the Kenyan extension service's performance, it turned out to be "rational" for agents -- unable to serve all the hundreds of farmers in their assigned area -- to serve the richer, more "progressive" farmers disproportionately. Indeed such farmers were 42 times more likely to receive a visit from an extension agent during the year than a farmer who was not already using hybrid corn seed and raising a cash crop. This "bias" in extension services would minimize the likelihood of complaints against the agent by influential people which would make his personnel record look bad (Leonard 1977). The scope of the agent's responsibilities -- the number of activities and the number of farmers assigned to him -- thus often prevented him from undertaking the kind of follow-up on the results of his recommendations that would enable him to be a more effective change agent -- or they would keep him from engaging himself with the problems which face small farmers not yet part of a commercial system of production and marketing. If farmers did not accept the agent's recommendations or did not get the promised results, this should raise a number of questions, seldom answered. Did the farmer adopt the recommendations exactly as proposed by the agent? If not, why not? Because he did not understand the agent's explanations? Because he understood but did not believe that the recommendations would yield good results? Because he could not afford the cost of the necessary inputs? Or because the inputs were not available? If the farmer did attempt to apply the recommendations but achieved poor results, the following questions suggest them- selves. Did he apply the recommendations in accordance with the directions of the agent? If not, why not? This leads back to the questions raised above. If he did apply the recommendations faithfully, but still results were poor, were the recommendations simply wrong? None of these questions can be answered by the agent who works in the traditional top-down style of field operations. If an extension agent works closely with farmers throughout the agricultural cycle, he will have a good chance of learning the answers to most or all of these questions, and those answers will greatly enrich his learning and increase his effectiveness. However, such an intensive relationship cannot be developed and maintained if the agent is responsible for a large territory and a large number of farmers, as usually is the case. This might lead us to the conclusion that agricultural min- istries should multiply the number of agents so as to achieve more intensive relations between agents and farmers. Even if there were no other reasons to argue against this conclusion -- and indeed there are -- it is obvious that developing countries simply lack the money and the professional talent to provide for this more intense technical assistance relationship. Such a conclusion must lead us to recognize that the basic design of the relationship is faulty: if we think only in terms of a one-on-one relationship between the extension agent and the farmer, then it is impossible to develop a cost-effective system of agricultural research and extension. We therefore need to think of organizational strategies which will not only provide more useful information but will channel it more effectively and economically to those who need to use it. We also find almost universally a lack of integration among the various government agencies which have official respon- sibilities of serving the small farmers. It is rare indeed to find a country where there is an effective collaborative relationship between research and extension. We commonly find that research people look down upon extension agents, considering them incompetent and poorly trained. On the other hand, extension agents are often inclined to think that research people are out of touch with the practical realities of farming and simply pursuing esoteric projects designed to lend them profes- sional prestige. The problems are compounded by difficulties with agricul- tural credit and marketing. As various studies have shown, credit tends to go predominantly to the more affluent farmers. This bias cannot be explained in terms of credit risk, for research suggests that the failure of repayment is higher among large farmers, whose social position and political connections help them to avoid penalties for defaulting on their obligations. This social-class bias in the channeling of credit has been documented in various parts of the world. (For India, see Ames 1975; for Bangladesh, see Blair 1978.) The cost of credit for small farmers is also likely to be a major problem. In order to protect poor people from the exorbi- tant rates of money lenders, many governments have established special credit programs for small farmers. However, even if such programs do provide money at lower nominal interest rates than private lenders, the de facto rates may still be so high as to discourage borrowers. Or the cost, in terms of time, to obtain necessary certificates and signatures may be substantial and detract from the value of the loan. It is not just a question of the availability or unavailability of credit or even of rates of interest so high that loans are not attractive to farmers. There are problems in getting authorized credit to farmers in time for them to make the optimum use of that credit. ...now, more than ten years after the beginning of Pro- ject Puebla (in 1967) it is still impossible to get credit in the hands of the small farmers of Puebla earlier than one month after they need it to achieve best results. (Antonio Turrent, personal communica- tion ) Further, in industrialized nations, many farm families own trucks or pickups that they use to get their produce to the market. Few small farmers in developing countries can afford such vehicles. Unless they band together to form a cooperative -- a possibility we will discuss later they are at the mercy of their more affluent neighbors or of intermediaries from elsewhere for getting their produce to the market. The poor farmer often finds that he has to sell his produce on the spot at a fraction of what he could get for it if he himself were able to put it in the market. To deal with this marketing problem, some governments have established buying organizations, guaranteeing to buy what the farmer produces at prices designed to provide him a reasonable income. However, such government organizations often are so inefficient that they fail to provide help to small farmers. Nor is it just a matter of the difference in efficiency between the independent entrepreneur and the government agency. Even if he offers the farmer a price substantially below the government guarantee, the entrepreneur makes his decisions and pays cash on the spot. The driver of the government truck has no such freedom. Since he is dealing with money of the state, he can only weigh the produce and give the farmer a receipt for the amount he has delivered. The farmer then may have to wait several months before collecting in cash from the government agency and, even at that time, he may be disappointed in finding that the amount he had expected to receive has been reduced because of reported deficiencies in quality or presence of impurities. Such discounts, based upon judgments and calcula- tions made behind the scenes (and possibly incorrect) are beyond his control. Furthermore, sometimes a bribe must be paid to an official to redeem the receipt issued for the produce, a complaint among cocoa farmers in Ghana (Beckman 1976) and small farmers selling export crops in Jamaica (Goldsmith and Blustain 1980). Then, too, there may be serious storage problems for the small farmer. If he must sell his produce at the time of harvest, he finds himself going into the market when supplies are most bountiful and prices lowest. He knows he could get a substantially higher price if he could hold his produce off the market for several weeks or months, but, even if he could afford to delay the sale, his ability to do that depends upon having his own storage facilities or having access at reasonable cost to other facilities in his neighborhood. Without such support, the farmer is constantly entering the market under disadvantageous conditions. Finally there is the sex bias that has been built into agricultural R and D organizations from the beginning but which only recently has come to be recognized as a problem (Staudt 1975, 1978). In the past all over the world, agricultural extension has been a job for men. The extension activities provided for women have traditionally centered around the homemaker functions of cooking, sewing, and so on. This division of labor is based upon the implicit and incorrect assumption that farm women only take care of home and family. In many parts of the developing world, women are actively engaged in agricultural production. In fact, in some countries in Africa it is estimated that women do 70 percent of the farm work (E. Boulding 1977). Even in countries where most of the farm work is carried on by males, women participate at critical points. Then there is always a large number of farm households (20 to 30 percent in many countries) headed by widows or by women whose husbands are away seasonally or for extended periods in urban employment. In such cases, women can be severely disadvantaged if they receive no assistance from the agricultural professionals. Furthermore, even when the extension agent recognizes the woman's involvement in agricultural production, he is likely to find it difficult to work effectively with her because of communication problems or suspicions that would be aroused in some cultures by the outside professional spending time alone with the farm woman. While all of these factors add up to a general explanation of the ineffectiveness of the traditional agricultural extension system, we gain a more systematic picture of the problem if we place it in the context of the socioeconomic structure of a developing nation, compared to the United States. The U. S. model of land grant university and extension systems fits into a socioeconomic structure of relatively ample landholdings, in an affluent farm population with a high level of education so that farmers are able to read and study published material, and all of this set in a democratic culture which emphasizes status differences and promotes free exchange of opinion and ideas. Furthermore, the U. S. farmer is supported by a modern infrastructure for communication and transportation. There are many farmers who earn more money than do extension agents and many have had as much education as the agents themselves. The more successful farmers do not hesitate to bypass the extension agent to go to talk to a researcher in the university or seek out a specialist in a private company to get advice on their problems. The farmers also have a social position and organizational base which enables them to put pressure on the R and D system to respond to their interests. To be sure, all of this has led to what is coming to be recognized as a bias in the system in favor of serving the larger farmers and agribusiness, but still the system has served a much broader base in the United States than in developing countries. In the latter countries, there may be such a gap in social .status, education, and income between peasant farmers and extension agents that the farmers are hesitant to express their opinions and make demands upon the agent, while at the same time the difference in social positions tends to lead the agent to underestimate the intelligence and competence of peasant farmers. The gap between the two may be further accentuated by major differences in language and culture. In many countries, there are large populations of peasant peoples who speak an indigenous language and speak and understand the national language poorly if at all. "Language difficulties reinforce the negative view agents hold toward small farmers. That is, the small farmer may be fluent and eloquent in his indigenous language and yet be able to speak only at a primitive or crude level in the national lan- guage. Being addressed at this 'childish level', the agent often unconsciously assumes that the farmer has a childish mentality and limited intelligence. Such a demeaning view presents a major barrier against the building of mutual respect upon which satisfactory cooperation depends. "When the extension agent does speak the indigenous lan- guage, as is sometimes the case, this helps him to cross the communication barrier. But rarely is much competence in an indigenous language considered in making appointments of exten- sion agents, so often we find communication problems between 'two cultures' compounded by the language barrier. The basic differences in social status, education, affluence, language and culture do not make it impossible to establish effective communication between the professionals and farmers, but they do present formidable barriers which will not be overcome simply by applying a U.S. model of agricultural research and development." (Norman Uphoff, personal communication ) CONCLUSIONS We can sum up the main points in terms of the following general propositions: 1. Both the European colonial model and the U.S. agricul- tural extension model were based upon the implicit assumption characterized elsewhere as "the myth of the passive peasant" (Whyte 1975). 2. More effective organizational models must be based upon the assumption that the poor farmer is an intelligent individual, interested in changes that may improve the standard of living of his family, within the limits of his resources and the information available to him and taking into account the risks that may accompany change. 3. A one-on-one relationship between the small farmer and extension agent will not be cost-effective. More effective orga- nizational models will link agricultural professionals with organized groups of farmers, with farmers participating actively in change programs. 4. Small farmers face major problems in the number of uncoordinated agencies with which they must deal if they are to get help from the state. Therefore, more effective organiza- tional models will have to provide better coordination among these agriculture-related agencies. 5. Communication and cooperation between small farmers and agricultural professionals are influenced by the culture and social structure of the country in which they live and work. REFERENCES Ames, Glenn. 1975. Who benefits from credit programs and who repays? Large farmers in village level cooperatives in My- sore, India. Land Tenure Center Newsletter, January- March, pp. 16-22. Madison: University of Wisconsin. Beckman, Bjorn. 1976. Organizing the farmers: Cocoa politics and national development in Ghana. Uppsala: Scandinavian Institute of African Studies. Blair, Harry W. 1978. Rural development, class structure, and bureaucracy in Bangladesh." World Development, 6:1, pp. 65-83. Boulding, Elise. 1977. Women in the twentieth century world. New York: Wiley. Chambers, Robert. 1974. Managing rural development: experience in East Africa. Uppsala: Scandinavian Institute of African Studies. Esman, Milton, et al. 1978. Paraprofessionals in rural development. Ithaca: Cornell University, Rural Development Committee. Goldsmith, Arthur and Harvey Blustain. 1980. Local organization and participation in integrated rural development in Jamaica. Ithaca: Cornell university, Rural Development Committee. Harik, Iliya, with Susan Randolph. 1979. Distribution of land, employment and income in rural Egypt. Ithaca: Cornell University, Rural Development Committee. Harwood, R.R. 1979. Small farm development: understanding and improving farming systems in the humid tropics. Boulder: Westview Press. Heginbotham, Stanley. 1975. Cultures in conflict: four faces of Indian bureaucracy. New York: Columbia University Press. Lassen, Cheryl. 1979. Landlessness and rural poverty in Latin America: conditions, trends and policies affecting income and employment. Ithaca: Cornell University, Rural Develop- ment Comnittee. Loomis, R.S. 1976. Agricultural systems in food and agriculture. Scientific American, 235:3. Reddy, G. Ram. 1981. Panchayati Raj and rural development in Andhira Pradesh India. In N. Uphoff (ed.), Rural devel- opment and local organization in Asia. Vol I: South Asia. New Delhi: MacMillan. Rice, E.B. 1971. Extension in the Andes: an evaluation of official U.S. assistance to agricultural extension service in Central and South America. Washington: U.S. Agency for International Development. Rosenberg, David, and Jean Rosenberg. 1978. Landless peasants and rural poverty in selected Asian countries. Ithaca: Cornell University, Rural Development Committee. Scrimshaw, Nevin, and Lance Taylor. 1980. Food. Scientific American, 243:3. Staudt, Kathleen. 1975. Women farmers and inequities in agri- cultural services. Rural Africana, Winter. Staudt, Kathleen. 1978. Male preference in government agri- cultural policy implementation. Development and Change, July. Wharton, Clifton (ed.). 1969. Subsistence agriculture and eco- nomic development. Chicago: Aldine. Whyte, William F. 1975. Organizing for agricultural develop- ment: human aspects in the utilization of science and tech- nology. New Brunswick: Transaction Books. FARMING SYSTEMS RESEARCH AND DEVELOPMENT Peter E. Hildebrand and Robert K. Waugh The term "farming systems" was applied in the 1970s to several different activities being developed around the world. These activities had a common thread and general purpose, but the methods used to pursue the goals differed greatly. The threads that bound them all together and that are basic to the farming systems approach are these: A concern with small-scale family farmers who generally reap a disproportionately small share of the benefits of organized re- search, extension, another developmental activities. Recognition that thorough understanding of the farmers' situation gained firsthand is critical to increasing their productivity and to forming a basis for improving their welfare. The use of scientists and technicians from more than one discipline as a means of understanding the farm as an entire system rather than isolating pol- icy, the variables it treats are mainly outside the farm gate and involve social scientists and economists more than agro- biological scientists. Methodologies frequently include surveys to provide the perspective on farming systems as a means of more accurately predicting farmer responses to different policy stimuli. FSIP is applied, farmer-oriented, socioeconomic research, supported by the agro-biological sciences in a team effort. The principal product is information. The primary clients are policymakers and managers of services and infrastructure. FSR/E is more "micro" in scope and deals mostly with conditions inside the farm gate. Because it is concerned with technology generation, evaluation, and delivery, more agro- biological scientists than socioeconomic scientists are involved and methodology is heavy in on-farm biological research with relatively little time devoted to surveys. policymakers because it can provide more detailed information on farms and farmers than FSIP can obtain. Similarly, FSIP can have significant impact sequence for mass transfer into specified recommendation domains of acceptable technology. c. Provide cultivation, that make best use of those at their disposal given the objectives of each individual farm family. While the choices available to each farmer are different, those with similar sets of resources and constraints tend to make similar choices as to crops, livestock, and management practices. Those who have responded in similar ways can be grouped together into homogeneous farming systems (recommendation farmimg systems approach to research. Farming Systems Research Paper No.3. Kansas State Univer- sity, Manhattan, Kansas. Shaner, W.W., P.F. Philipp, and W.R. Schmehl. 1982. Farming systems research and development: guidelines for developing countries. westview Press, Boulder, Colorado. together, generation after generation, according to traditional ways of life. Such societies are whole societies, in that they exist for all human needs and interests. They are enduring societies in that children are born and raised to become adults with ways of life much like those of their parents and grandparents. A nation is such a society, and so is an Indian tribe. So, too, is a town or village, and even a single family insofar as its members have traditions that are transmitted to each succeeding generation and make that family, through time, distinguishable from other families. On the other hand groups of nations taken together are great societies; one speaks of Western society in contrast to Oriental society. In some sense all the people of the world taken together constitute a single society. But it is of the separate tribes and nations that we are chiefly thinking here. Because there have been and still are so many and so various primitive societies, one learns a good deal about society in general by referring to one or another of these simple societies. A society is easily seen as people doing work. It has other aspects too. A society is also people sharing common convictions as to the good life. This is to say that it is not merely a system of production and of services an anthill is that but that a human society exists in the fact that its members feel that certain conduct is right and other conduct wrong, and act more or less accordingly. And a third aspect of human society is to be recognized in the sentiment its members have of belonging together as against other people who do not belong. A society is people feeling solidarity with one another. A SOCIETY AS PEOPLE DOING WORK In every society the work is divided. Everyone takes ad- vantage from work done by others of a kind which he does not do and in exchange serves those others by doing useful things that are not done by them. The division of labor between men and women is universal, in that everywhere what women do is on the whole different from what men do; on the other hand what each sex does varies with the society; in Polynesia the men did the cooking, among the Hisra Indians the women did the farming. Equally obvious is the division of labor that goes with differences in age. Beyond these bases for the organization of work, there are those which depend on differences in temperament, or on training, or on the accidents of opportunity, or on the variations in demand. In some small, isolated primitive societies there is almost no division of labor except between the sexes and the age-groups, and except some individuals who act as magicians or as leaders of ceremonies. Every adult man does about what every other does, and so it is with women. With the development of tools and techniques, with increase in population, and with the advancement of communication and transportation, the division of labor has become far more complete and complex. In the Guatemalan village of San Pedro de la Laguna, fifty-nine different kinds of specialists are to be recognized in a population of less than two thousand. A classified telephone directory suggests but by no means completely lists the thousands and thousands of kinds of specialists that make up a modern city. An obvious result of this increasing division of labor is the increasing ease in the number and kinds of commodities and services which people can enjoy. But another effect is to limit the view which any one individual has of the operations and goals of his society to a very small segment of the whole, with corresponding difficulties for industrial management, for dem- ocratic government, and for personal happiness. Another result is greatly to extend the number and distribution of people who divide labor with one another. Millions of people, from China to Congo to Akron, come to depend upon one another for services and products exchanged, and yet these people have no common purposes and understandings; they hardly know that one another exist. The organization of work tends to become world-wide while national and other local groups distrust, dislike, or fear one another. So men come to depend upon one another while yet without common sentiments and values. A SOCIETY AS PEOPLE SHARING CONVICTIONS ABOUT THE GOOD LIFE The organization of work takes place in ways other than the mere division of labor. Slavery is a way of organizing work. The market, to be discussed below, is another way. And a third, perhaps the basic form of the organization of work, arises from the fact that in a society people share common sentiments and beliefs as to what it is good to do. People work, not only because in most cases they are uncomfortable or even will starve if they do not, but because work is a part of the meaning of life. To the primitive agricultural Indian, farming is a nec- essary part of decent and appropriate human existence, an es- sential way of maintaining relationship with the supernaturals, a test and duty of honorable manhood. In such a society one prays as one works, and work is, in part, religion. In aristocratic societies of recent times on the other hand, work was appropriate only to the underprivileged masses; while in modern Western society work is again a general positive value, and men work for wealth and power and to excel their neighbors. The more general statement to make about society is that it consists of a plan of life. Society operates because its members have around them a universe which to them makes sense. Moreover, this plan is not merely a pattern without moral meaning: it is a plan for right conduct, an organization of conceptions as to the good, the true, and indeed the beautiful. The body of con- ventional meanings that are made known to us through acts and artifacts is by anthropologists called "the culture" of a community. In the primitive societies the "wholeness" of these meanings is more easily seen than in the case of large, complex, and rapidly changing societies. The customs and institutions fit together to make a single moral representation of the universe. The Papago Indians, for example, carry on warfare not as an opportunity for exploit separate from their other interests. The Apache scalp taken in a foray is the symbol of the supernatural power brought to the Papago camp by the warrior who killed, a source of spiritual strength, a form of divine power, solemnly to be welcomed into the camp, into the home of the killer. When the men are away on the expedition, the women and children, by abstaining from noisy or indecorous conduct, in effect share in the making of war, just as, in some primitive societies, men share in the importance and responsibilities of childbirth by "lying-in" by restricting their behavior for the welfare of the newborn child. Labor is divided, but all members of the society act in terms of common conceptions and ideals. Commonly the myths of such a society are narrative representations of its moral values, as its ceremonies are dramatic expressions that correspond. So every culture is a provider of a course of action for the individual, a source of his motives, and validator of his convictions. This is the way a simple and isolated society operates. But as societies have become larger and rapidly changing, with many different kinds of people in them, the customs and institutions no longer preserve this nation or town, but rather a great many incomplete cultures, so that what a man does at his office or in his factory is not always closely related to what he does when he plays or goes to church or visits the neighbors--if he does visit them. And what his children do and believe may be notably dif- ferent from what he himself was brought up to do and believe. Then the sense of the meaning of life tends to be lost; men experience uncertainty, insecurity, and confusion. On the other hand as this happens men more and more come to think rationally and critically about the life around them and to act inten- tionally to change and to guide it. Science develops, along with rational administrations and planning. The basis for the operation of society thus tends to shift, over the course of human history, from tradition to deliberate social invention and thoughtful choice.... (pp. 345-348) THE ORGANIZATION OF PRODUCTION, DISTRIBUTION, AND CONSUMPTION In the first part of this chapter the division of labor was emphasized as a universal method for organizing work. This as- pect of the operation of society may now be examined more fully. The division of labor does bring it about that the whole society realizes the advantages of having some people do some things well through their freedom from necessity to do other things. But this is not all there is to social organization of economic activity. In every society it is also necessary to determine, somehow, what resources shall be used in producing what products. How shall products and consumable commodities be distributed and to whom? Who shall consume what commodities? The organized ways of accomplishing these ends may be called the economy of that society. The technology is the tools and techniques for producing and making useful things; the economy is the institutions and customs that get raw materials into products and that get both distributed and consumed. It is easy for us, who read these words, to think of factories, markets, and money as principal social machinery for getting these things done. But looking at primitive and ancient societies shows that these three are recent and special devices for bringing about production and distribution. In most societies raw materials and manufactured goods get around to producers and consumers without markets and money. The ancient and the basic form of economy is one in which goods are made and goods are distributed not by buying and selling at all, but by virtue of the traditional rights and obligations that custom recognizes to exist between one individual and another in that society, or be- tween one group in that society and another. This kind of economy is easily seen in most families. The product of the father's labor, whether it be meat from the hunt or a paycheck brought home from office or factory, is shared with his wife and children not because he sells something to them which they buy, but because it is recognized to be part of his role as father to share his product with his wife and children. The allocation of the father's labor to daily work, of the mother's labor to cooking and sewing, and perhaps of the small one's labor to fetching firewood or going to the store for lemons and soap, is a matter which requires no competitive bidding to determine and in most cases no payment of money to compensate. It is fixed by the very relationships of the members of the family to one another. The word "status" is conveniently used for all the rights and obligations which attach to an individual or a group, according to the customs of the society. The father's status in our society includes his right to choose the place to live, ac- cording to his need and ability to get work, and his duty to provide for his family, as well as to share in the practical and moral guidance of his children. The work he does and the sharing of what he earns are parts of his status, too. So we may speak of this kind of economy as a status economy. The basic form of economy in human societies is a status economy. In primitive societies most of the production - whether by hunting or by farming or by raising cattle or by handicraft manufacture is brought about not because somebody sees a chance to make a profit in some market, but because it is part of the traditional status of that man or woman to hunt or farm or make baskets. And what is made is shared with others according to status. In many South Pacific societies a man works, not to feed his own children, but to feed his sister's children; his own children will be fed by his wife's brother. In certain hunting tribes it is usual for the hunter to give certain parts of the slain animal to just certain relatives perhaps eight or nine different parts go, respectively, to eight or nine different relatives. So goods are distributed and consumed. These are reciprocal exchanges according to status: what a woman's brother gives to his sister's son is balanced by what that same man, as sister's son, gets from his own mother's brother, in the long run, and on the average. It is also common for goods to be distributed in status economies by the gathering of these goods in one place and by their distribution to all from this center. In a certain Melanesian community every gardener brings some of his best yams and puts them into the chief's yam house. They are "given" to the chief. As the large and beau- tiful yams pile up, the villagers take satisfaction in the richness and industry of their own community; the abundance of the chief's yams rebounds to the credit and glory of all. At a certain festival, the chief distributes these yams, some to visitors, and some to the villagers themselves. So everyone participates, in both the pride and the feasting. In many simple societies there is neither money nor market. The whole society is, in respect to this matter of the economy, like a family; the status relationships determine production and distribution. The medieval manor had an economy which was largely a matter of status. In contrast with this is that economy which depends upon the market. For the beginnings of the market economy in primitive societies we look outside of the local society to its relations with other societies. The beginnings of human social living must be thought of as taking the form of small groups scattered over a territory and pretty much isolated from one another. The re- lation between such groups is not ordinarily only of warfare. Organized aggressive violence against a neighboring society is not characteristic of the very simple societies. Many such so- cieties get along.with one another in a more or less friendly way: both societies recognize customary visits, without hostile intention, from one to another. An occasional invader from the outside may be killed, but the formal visit is expected and is received without violence. Many such visits are the occasion of the exchange of goods. More commonly, in primitive societies, people from one community pay a visit to another community, taking with them goods produced by the visitors and wanted by those visited. Then goods are exchanged, partly by barter and partly by exchange of gifts. Something is given in the expectation that something will be given to the giver by the one to whom he gives. It is an equivalence of good will, rather than of precise market value, that determines the transaction. So in such a market personal relations, and the status of guest and host, affect the exchange. In larger communities, where people do not know each other personally, and more goods and more kinds of goods appear, the market may be more fully a matter of an effort to sell at the highest price and to buy at the lowest; then buyer and seller alike "shop around," and who the man is who buys or sells does not matter as compared with the opportunity to get the best price. Such a market can to some degree operate by the exchange of one sort of good for another, but money, as a universal measure of value, is an enormous help in facilitation of market exchanges. In some societies incomplete money appears: in some Melanesian communities certain strings of shell beads are used only in payment for pigs or wives. But in other places metal hoes or copper axes or coined metal or engraved certificates of promises to pay both serve as tokens of value that measure the value of one article against all others in the market, and also provide a way of temporarily holding buying power from one market or opportunity to buy to another. In most societies of the world, and through most of human history, the production and distribution of goods has taken place chiefly as an aspect of the status relationships of the society: the market has been not the central mechanism for making society work, but a special or peripheral part of it. In modern times, and especially in the Western World, the market became much more important. In our society the effort of the laborer is to a considerable extent bid for and offered to the highest bidder, and the use of land, paid for as rent, also enters into market competition. Now markets are very wide; for some goods, like wheat and rubber and tin, the market is world-wide; and, with rapid and universal communication, and with the machinery of banking and credit, what goes into production where and what goes where to what consumer are matters that the market "decides," rather than status and moral custom. So, in our society, the operations of the market have a principal and even determining influence on all sorts of affairs. Many a worker must live where the opportunity to get a job determines, and if suddenly the produce he makes ceases to be wanted, he may have no livelihood at all, and perhaps cannot keep his family together; in parts of the world men starve because the market no longer needs their labor. Where a family goes to live, perhaps its own solidarity, perhaps even whether its members live at all, follow from what happens in an immense impersonal market, and the action of a na- tion, from its form of government to its remaining at peace or its going to war, may be shaped by what happens in markets. The operation of the economy may also be regarded from the point of view of the organization and regulation of productive effort. Even in the simple societies there is more to this than the mere separate work of single individuals. The household economy is in many cases under the leadership or direction of someone: the husband of several wives, as among the Hidatsa In- dians, an older woman in a large matrilineal family of the Iroquois. When the Chukehee of Siberia go to hunt seal or wal- rus, the builder of the boat is master: he gives the orders and he receives the largest share of the meat. In modern societies with highly developed markets, the enterpriser may be one or a group that brings together a very great amount of money and credit, labor and raw materials, in order that automobiles or steel plate may be made. Furthermore, with the development of the state as formal government, its own efforts enter largely into production and distribution. The state may itself be the principal producer, as in Russia, or it may supplement private enterprise, either to limit the operations of a free market, as in granting a monopolytoa single telegraph company, or in helping a freer market to operate, as in legislation against trusts. PROPERTY Among the common understandings which constitute the ul- timate basis of society are those which attach to things that may be used, enjoyed, or disposed of. Where the understandings limit or otherwise define such rights and obligations of one in- dividual or one group as to others, we speak of "property." Property operates to keep use and enjoyment and disposal in expected channels; it contributes to the working of society in wide and far-reaching ways; to confer and to limit power and the basis for getting more power; to serve as a criterion for status; to provide motives for effort. Wanting to own things, men may work, steal, or go to war. Owning things, men may enter social groups otherwise barred to them, exercise influence over polit- ical decisions, or assume correspondingly great responsibility for serving the common good. Property is thought of most immediately in connection with such tangible goods as tools, automobiles, houses, and land. It exists also with respect to such intangibles as magical spells, power-inducing songs addressed to supernaturals, hunting and fishing rights, patents and copyrights. In some societies personal names are owned in that they may be disposed of by sale or gift; in our society, a trade name may be registered and so owned. On the whole, the conceptions of ownership have become more complex with the developing complexity of society. Land, in particular, has become subject to private and exclusive own- ership, with rights of sale and disposition by will; in most primitive societies such precise and exclusive rights to land are not recognized; nevertheless, individual or familiar rights over hunting and fishing territories may be sanctioned in custom in some very simple societies. In primitive societies, and to an extent in modern society that is not always recognized, property does not consist of a single all-embracing bundle of rights held by one man as against all the world. On the other hand, thoroughly communal ownership of important goods, in the sense that every individual has the same right in most goods as has every other, is not to be found. What is usual, rather, is that every species of ownership turns out to be the exercise of certain rights as to the thing owned subject to other rights in that thing held by others, at least in possibility. The Melanesian canoe-maker does not completely "own" his canoe: he is expected to share it with certain others, and to share the catch it helps to bring about. The owner of land on Main Street may own it subject to zoning regulations, and to the right of the state to take it from him for certain public uses. Beyond this, furthermore, are the claims on property which are make outside of the law, but through expectations resting on custom. The primitive fisherman may share his catch with the whole settlement, as a matter of course. The rich American is expected to do something useful and generous with his riches; and everywhere the claims of the nearest of kin constitute a real limitation on ownership of many kinds of goods. And still further it is to be recognized that property rights are deeply associated with attachments that are sentimental and outside of the rights of control and disposal. It is not so much that the aborigine, long established on the desert or in the forest, owns the desert or the forest; he is attached to it, is a part of it, almost "is owned" by it. And the reader of these pages may feel similar about his home, if he happens to live in a home and not simply in a house, or about an heirloom of tender memories, or about a familiar old garment. (pp. 352-357) CUSTOM AND LAW The simplest answer that can be made to the question, how does society operate, is that it operates because on the whole people do what is expected of them. But why do people do what is expected of them? To this question there are a number of true answers. It is easier to do what one has done before than to do something else; a habit that everyone in a society has we call a custom. Further, the things that one has done, and that one's father's father has done, as well as some things that have been thought over and struggled for, have come to be so rooted in sentiments and in explanations and justifications that they have the force of what we speak of as conscience: they are felt to be right, ultimately and necessarily right. And still further, one does what is expected of one because it is often extremely in- convenient, even dangerous, if one does not. That is why I do not start out tomorrow to drive on the left-hand side of an American road. There is an efficiency, an ease, about doing what is expected of one. In a more special form, the expediency of doing what other people expect appears in the exchanges of services and benefits which help us all to get along. I do a thing helpful to another knowing that he is then more apt to do something helpful to me. If I pay my bills, lend my lawnmower, keep out of those of my neighbor's affairs which correspond to those of mine that I want him to keep out of, and yet listen to enough of his troubles so that I may tell him mine, we all get along pretty well. It is, however, to be emphasized that it is the nature of human society to regard these considerations of expediency, important as they are, as less worthy than those which are rooted in conscience and the sense of duty. Society is not, basically, so much a body of traffic rules and favors exchanged as it is a system of moral convictions. At a more obvious level society operates because conduct is sanctioned. A sanction is a consequence, pleasant or unpleasant, that follows the doing of something and is known to follow it. Some such consequences are internal the pangs of conscience - but others fall upon the transgressor from without. Of those that so fall, many are imposed by almost anybody in a diffuse and generalized way, as is illustrated by the looks I receive from the people who know me if I do something of which they disapprove. Perhaps what I do is not otherwise punishable. If a specific consequence follows through the exercise of same centralized authority, we begin to think of the transgression and its consequence as an affair of the law. Legal sanctions have a quality of preciseness about them: the misconduct is defined in advance in clear terms, and the consequence is also precisely known. Commonly the procedure for matching the transgression to its appropriate consequence complaint for arrest, charge, hearing, trial, judgement is specific and formal. Also, for the matter to be one of law and not just custom, the consequence, that is, the sanctions carried out not entirely, if at all by the particular person who suffered the transgression, but by someone who stands for the society as a whole and acts for it. Law is the whole society settling a local dispute or punishing or redressing a wrong in the interest of the whole society and according to its common conscience. When in a Plains Indian tribe a society of warriors finds a wrongfully wounded man and sees to it that the wrongdoer heals the wound and pays horses as a fine, law has begun. One may recognize law-making and law-administering in groups smaller than the whole society: there is something like law in some families; and there is certainly law in many gangs. But there is a tendency for that group which is the principal in-group, the tribe or the nation, to insist on its chief or exclusive power and right to make and enforce law. So law appears more clearly in the centralized and monopolizing force of the state. POLITICAL INSTITUTIONS In the simplest societies there is nothing that is "polit- ical" if we use that word for institutions to express or enforce the common will or the ruler's will formally and publicly. In the Andaman Islands the natives lived in small bands without chief, council, law or administrative regulation. If a man lost his temper and smashed things, the rest of the people just let him alone until he got over it. No one exercised any general authority to rule or to decide or to negotiate on behalf of the community. In such a society there is no state, no political government. Political institutions do clearly appear, however, in many tribal societies; there is a chief who has power to decide issues or to lead in the making of decisions; there may be a council; there may be groups to police the people. The dependence of modern complex societies upon political institutions for their operations is obvious. The making, enforcing, and interpreting of law are the manifold business of thousands of individuals and hundreds of bodies: from leg- islatures, courts, and executives to the citizens who vote or discuss public issues with their neighbors or write letters to some newspaper. These political institutions keep people's be- havior more or less within the rules. They also are means to the reconsideration of the rules and the changing of the rules. They operate in that frontier of rule-making and rule-observing where conflicts occur, or at least differences of opinion, and the enforcement and interpretation of the rules helps to keep at least some of the people conscious of them, and so pushing to change them. Formal political institutions not only keep societies going in the good old ways; they also provoke a challenge of those ways. What is, then, not so obvious is that political and administrative acts have an effect upon moral custom. It is commonly said that the laws express the customs and grow out of them. This is true, but it is also true that the passage of a law or the making of an administrative decision has an impact upon the sentiments and convictions of the society. To punish a criminal is to make a solemn gesture renewing the collective moral judgement with regard to the conduct for which the criminal is punished. Sometimes the law stands for a sort of theoretical or ideal norm which the society does not really mean to have realized, at least without exception, as when a southern jury of white men finds confessed lynchers of a Negro not guilty. Then the decision expresses a moral judgement that is inconsistent with the letter of the law. At the same time such a decision sharpens the conflict between the general principles and the exception and helps either to remove the exception or to weaken the principle. The decision and act whereby American citizens of Japanese descent were locked up during the war had no effect in strengthening the prejudices of those who were prejudiced against Orientals, for by conspicuous and effective public action a discriminatory act was performed. On the other hand, it aroused or strengthened sentiments of condemnation of the act. It is true that the customs make the law. It is also true that legal and administrative acts help to change the moral judgements of the society. (pp. 359-362) THE EXPRESSIVE LIFE: PLAY, ART, CEREMONY, MYTH In many of the preceding pages the operation of society has been described as a matter of work and discipline. It has been suggested how people become and continue as a society by virtue of the fact that they labor together for common ends, and how they are kept at it by the convenience of cooperation and by the rewards and penalties which are provided by law, the general opinion, or the conscience of the individual. In this account the sober, the practical, and the constraining have perhaps been too strongly emphasized. Perhaps the impression that society gets along wholly or chiefly because people do what they are compelled to do, or that work is the sole or the basic form of activity. As a matter of fact, a very great part of human social behavior is quite the opposite of work. In work one does what a particular end demands in just the way it demands it and when the end requires it. To hoe corn effectively is usually work because one must move the hoe just so, one must do the hoeing just when the weather and the weeds make it necessary, and one may not stop when one would care to. But a very great deal of human activity is simply expressed. It is activity which responds to the impulse of the individual to be active; it is thinking and feeling; it is a fruit of the human impulse to create. Some expressive activity takes place at times fixed by the expectations and rhythms of society, but even then without having to meet the demands of practically useful effort. Laughing, joking, improvising with language, storytelling, praying, arranging flowers, painting pictures, enjoying or playing a ball game or Beethoven, and dancing are all forms of expressive activity. The expressive forms of behavior in large part give each society its own special character as they give special flavor to each personality. Different societies may have the same tools and the same work habits, but if their art and storytelling are different, the societies are then different. "What do you dance?" is the first inquiry a man of a certain Bantu tribe puts to a stranger. What a man dances in that part of Africa is the key to a man's whole life, the way to ask about a foreign society. The relations between expressive activity and work appear in considering magic. If a man has something immediate and practical to accomplish, he may do a little work to get the thing done. If the pipe leaks, I may unscrew the faucet and put in a new washer. If the pigs are eating the Melanesian's yams, he may fence the yam patch to keep out the pigs. What is done is done in just the way that the end requires. The putting in the new washer and the building of the fence are technically "correct" - in both cases what is done is responsive to the demands of the situation outside of thestateof mind of the worker. I may not express my anxieties or my annoyance too vividly and originally in putting in the washer or building the fence; if I attempt to express my sentiments I may not do a good job with the washer or the fence. These are practical actions appropriate to the mechanical solutions of the problems. But in some cases there is room for expressing the way one feels besides doing the appropriate practical acts, and in other cases no appropriate practical acts are known and one expresses the way one feels, believing that what is done is effective, instead of doing something really effective in getting the result desired. The Melanesian who wants his yams to grow may fence them in and cultivate them; he may also recite little spells expressive of his desire for a good crop. Tom Sawyer knew how to get rid of warts by putting water from a decaying stump on them while reciting a charm imploring the warts to go away. We call these actions "magical." Magic is that activity directed toward accomplishing some special limited end and done in a form which is determined not by the real effectiveness of the act to bring about the result but by the desires and fears and general thinking and feeling of the man who performs them. Magic is practical action in that it is done for a certain limited end, like work; but it is expressive action, and work is not. Magic is characteristically colorful, even dramatic. Magical rites are little pictures of what one wants. One sticks pins into a figure of one's enemy. One sacrifices not just any hen; it must be a black hen. If a problem bothers a deliberating assembly, it may appoint a committee; the result may be practically effective, or it may in part just express the concern and desire to do something about the problem; it is then not so different from many acts recognized as magical. (pp. 363-365) In ceremony and in mythology the expressive side of life appears in forms plainly related to the persistence of society. A ceremony is a meaningful formal act that signalizes an occasion of special importance. It is a little drama to underline the significance of a person or a moment that is out of the ordinary and that the society wishes to recognize. Some ceremonies are in ancient forms of deep religious meaning, like the Mass; others are unconnected with the church but yet are public and solemn, like the pledge of allegiance before the national flag; still others are domestic matters and not solemn at all, like the merry little ceremonies of a birthday party. All of them are representations of beliefs that the people hold; they are ways in which people together show that they care about something. Although not every society has well-developed myths and also well-developed ceremonies, myths are the stories that correspond to the ceremonies. Myths are ways in which the institutions and expectations of the society are emphasized and made dramatic and persuasive in narrative form. Myths show that what a people has to enjoy or endure is right and true-true to the sentiments the people hold. It does not so much matter whether or not little George Washington really cut down the cherry tree and told his father about it; what matters is that the story expresses some ideas the tellers had about telling the truth when it goes against you. The religious myths are true to the moral and sa- cred ideas that inspire them; they need not be true as legal evidence must be true. Myths and ceremonies, like much of art and some of play, are collective and traditional forms in which the people of a society remind themselves of what matters to them and why it matters. They are gestures made by a people to itself. Work and sanctions alone do not suffice to keep a so- ciety in operation. It is also needful that the tendencies of people to leap, move, shape and tell fall into representations that satisfy and intensify the conceptions which, held in common, make that people a society. This section suggests some of the answers to the question expressed in its title: How does a human society operate? In its first pages the answer given was that a society is kept in operation by arrangements whereby a number of people can do the work that needs to be done to keep them going and whereby they can feel that they belong together and share a kind of life which they believe to be good. There is a world of necessity into which people are born; to survive they must live together; to live together they must have tacit agreements as to who does what, and what is what. They must, in short, regulate their common life. The regulation is a matter of conventional understandings partly as to what each one should do and partly as to what is, generally and for everybody, the good life. The plan of the good life finds expression, it was then added, in religion, myth, and art. We can think of the operation of society as machinery for social control and also as a sort of charter or drama of a scheme of all things. But there is another way to think of the operation of soc- iety that is, probably, implicit in what has been written here. We may also think of society as operating so as to realize impulses and meet needs of human beings. Instead of asking, as we have, What operations keep this society going? we can ask, What is there about society that keeps human beings going? Any human being must have protection and food, and we can see society as providing for these necessities. Human beings have also sexual demands or needs, and every society provides some ar- rangement for meeting these. Moreover, beyond this, human be- ings have characteristics that are not shared with the animals but are peculiarly human. The foregoing discussion of the "Expressive Life" rests on the assumption that there is an "impulse of the individual to be active," that it is the nature of human nature to use the imagination and to shape things that please themselves. While it is perhaps not possible very definitely to describe the human impulses and needs beyond those that are shared with animals, it is hardly possible to deny that there are some; and society may thus be seen as a way of providing for the development and expression in everyone of human nature. In this sense, society operates by doing for us what our natures, given society, demand. (pp. 367-368) HIERARCHICAL AGRICULTURAL SYSTEMS Robert D. Hart If the hierarchical ecological systems conceptual framework is applied to an agricultural production process, a set of hierarchically related agricultural systems emerge. As in the case of the ecological systems framework, agricultural systems exhibit not only vertical hierarchical system interaction, but also horizontal system interaction. Each hierarchical level is a functioning set of subsystems with the outputs of some subsystems acting as inputs to others. While it is possible to describe a. global level agricultural system, from the point of view of agricultural research and development the geographical region is probably the largest unit of interest. A regional agricultural system includes all the farms in the geographic region; the marketing, credit, and information cen- ters; and the infrastructure that ties these regional sub- systems together, Figure 2.1. A region can be analyzed as a system with materials, energy, money, and information flowing into and out of the region and between subsystems within the region. From an agricultural research point of view the farms within the region are the most important subsystems and form the next lower hierarchical level under the region. A farm is also a system made up of subsystems. A farm sy- stem can be viewed conceptually as a set of spatially definable areas in which either crops or animals, or both, are produced, and a homestead area where the farmhouse is located. The crop or animal production areas form units, analogous to the ecosystem unit in ecology, and can be defined as agroecosystems. The farmhouse area in which the farm family is fed and clothed and the economic transactions and management decisions that occur on a farm can be combined to form a socioeconomic subsystem of the farm system. The socioeconomic subsystem and the agroecosystems interact to form a farm system. If agricultural research is of primary concern, the agroecosystem of a farm system is the most logical next-lower hierarchical level to be analyzed in more detail. An agroecosystem is also a system made up of subsystems. As in the case of natural ecosystems, it is composed of a biotic community of plants, animals, and microorganisms and the physical environment in which the community functions. Energy flows be- tween trophic levels and materials are cycled. An agroeco- system differs from a natural ecosystem in that at least one plant or animal population is of agricultural value and that man plays an important management role. Soil, crops, weeds, insects and microorganisms can be defined as subsystems of crop-dominated agroecosystems. In a domesticated animal-dominated agroeco- system, soils, pasture, weeds, insects, microorganisms, and domesticated animals make up the subsystems that function as a unit in the agroecosystem. Agronomic research has been done on all of these subsystems, but crop systems and animal systems have received the most attention. A crop system is an arrangement of crop populations that process energy (solar radiation) and material inputs (soil nutrients, water) to produce outputs (crop yield). The crop population can be arranged both spatially (planting distances) and chronologically (date of planting). when more than one crop species is combined in space and time, the resulting assemblage can be exceedingly complex. The individual crop species are subsystems of the crop system and make up the next hierarchical level under the crop system. The individual crops can also be subdivided into hierarchically lower subsystems as physiological processes. In agronomy considerable attention has been given to this hierarchical level with the recent emphasis on the study of crop architecture and crop genetic systems as part of crop A Region Figure 2.1. Hierarchical relationship between agricultural systems breeding programs. A domesticated animal system is an arrangement of animal populations that processes energy and material inputs (pasture, feed supplements, etc.) to produce outputs (meat or animal products). An animal system is on the same hierarchical level as a crop system. Animal populations made up of individual animals composed of interrelated physiological systems form the next- lower hierarchical level. In applying the agricultural systems conceptual framework to a specific case, it is not always necessary or practical to use the entire hierarchy. Emphasis can be placed at one level, as for example in the case of a cropping systems project. In principle, however, it will always be necessary to study at least three levels: the unit of interest, and the next higher and next lower levels. The next higher system must be studied in order to measure the inputs into the system, and the next lower level must be studied in order to understand how the system functions. In the case of a cropping systems project, activities will need to be applied to the agroecosystem, crop system, and crop levels. A farming system project must study regions, farm systems, and agroecosystems. The first step in either a region, farm, agroecosystem, crop or animal system study is the construction of a qualitative model of the unit under consideration. In the context of this framework, model building involves identifying the inputs and outputs of the system of interest, the subsystems of the system, and the circuitry connecting these subsystems. The next step is to begin to quantify the relationships hypothesized in the qualitative model, and to construct a quantitative model of the system. The precision required depends upon how the model will be used. The qualitative models that would be developed by a multi- disciplinary team if the heirarchical agricultural systems model were used would vary with the ecological and socioeconomic conditions of a specific region, farm, agroecosystem, or crop or animal system. However, these systems have general inherent characteristics that make it possible to outline general qualitative models for each level of the heirarchy. I have as- sumed that these models would be used for research and development purposes. DEFINING A FARMING SYSTEM David W. Norman A system can be defined conceptually as any set of elements or components. Figure 2.2 illustrates some of the underlying determinants of the farming system. The total en- vironment can be divided into two elements: technical and human (Institut d'Economie Rurale 1976). The technical element de- termines the types and physical potential of livestock and crop enterprises and includes physical and biological factors that have been modified to some extent by man often through technology development. Man has developed, for example, me- chanical techniques to improve the availability of water through Bonia Hanan Technical I --I C 1 -i 1 St C he. ca.,Chem ,cal. Factor Exogen dPhysical B oiolca Camuisy I Mschanical Norms, and uthP .A Belies Sid 1 i------- Income InsSutons B a s t Inputs Land Capital L Ag, PrFosses Ol-farm Livestock ir Farming System Broken hasrepresena reaJs of ns systems I---- ----- _ Figure 2.2. Schematic representation of some determinants of the farming system irrigation and chemical techniques to improve soil quality, etc. The farming, ex- tension credit and input distribution systems are often financed and managed by government agencies. On the out- put side, the government may directly (e.g., marketing boards) or indirectly (e.g, improved evacuation routes, transportation systems, etc.) influence the prices farm- ers recieve. technology development and making technology a variable instead of a parameter. REFERENCES Institute d'Economie Rurale. 1976. Rapport de Synthese sur les Systems de Culture et d'elevage dans le context de Mali. Bamako: Institut d'Economie Rurale. PREVAILING FARMING SYSTEMS BY REGIONS Robert E. McDowell and Peter E. Hildebrand There has been a number of attempts to identify or systemize the prevailing farming systems of regions (Ruthenberg 1971) and of the world (Griss 1974; Kolars and Bell 1975; Whittlesey 1936). These classifications have been done on several bases, including geography (political and physical), climate, type of crop or animal, and the production method for that species. The panel took the position that farming systems could be more readily understood if the focus were directed toward crop/animal interactions. Tables 2.1, 2.2, and 2.3 show that the panel has attempted to identify and characterize the prevailing systems employed on small farms in Asia, Africa and Latin America with the dominant crops, the predominant animal species on the farms, and the main feed resources utilized by the animals. A farming-system type consists of a small number of major or dominant crops and numerous minor crops that fit around them. The systems given attention by the panel were those having an animal complement, with the dominant crops largely determining the feed source and, hence, being a major factor in selection of animals for the systems. Nutrient flow through the system is critical in limited-resource agriculture, and crop/animal rela- tionships are critical to its efficiency. Crop/animal rela- tionships have particular implications for labor use as well as requirements for social organization. For instance, security and social structure in the village largely determine the way in which animals are tended or looked after. The market structure must also be aligned to the needs of the farming system. These and many additional factors describe the complex of interrelated physical, environmental, and social elements which must interact in any particular system. The panel members felt that in order to understand mixed farming systems in small-farm agriculture, one should first look at a type of crop/animal interaction and be familiar with its essential elements. Then one can look at the range of conditions under which it is found. A final step is the understanding of change in the system across environments. The classification proposed here is not so much intended to present new information as it is to alter the traditional viewpoint of those studying the system. The panel is not attempting to give detailed descriptions and information on the specific systems, but rather suggesting a conceptual frame- work to guide further study. As an example, attention is drawn to the coastal fishing and farming complexes in Asia (Table 2.1). These systems are found across most countries of Asia and also represent the predominant systems in the smaller islands across the Pacific. They are adapted to areas of relatively high population density and are found on the extremely poor soils of the coastal areas. These systems are designed for intensive use of the scarce resources in the coastal environment. The major crops, determined to a large extent by soil type and fertility, are coconuts, cassava, and cacao, together with a range of minor crops. The coconut by- Sproducts are utilized for swine feed, while the marine by- products, such as fish trimmings, shrimp, or nonmarketable marine products taken along with the commercial catch, are fed to ducks. Cattle and goats are pastured under the coconut palms or in the more marginal land extending back onto the slopes of the hills, which are usually not far from the coast. The coastal fishing and farming complexes are highly specific to the physical and geographical environments in which they are found, but since these environments spread across the full length of Asia and Oceania, the system transects an extremely broad socioeconomic range. To know and understand the interaction of the system in the coastal area of southern Luzon in the Philippines is to feel familiar with it wherever it is found. The selection of animals to match food availability, the matching of crops to their spec- ific low-fertility environment, the use of animals to con- centrate nutrients for cycling into the limited but all- important food-crop areas, the suitability of animals and food crops for marketing over long distances, the high diversity of enterprises within the system, giving it both biological and economic stability, are all crucial points in understanding its function. The system is, in cases of extreme isolation, ideally suited to subsistence conditions. Where resources are somewhat more plentiful and markets available, the system becomes im- mediately commercialized. It is relatively self-sufficient and self-sustaining, requiring few new inputs and a minimum of rural infrastructure. One could go through each of the nine other farming systems listed for Asia (Table 2.1), the ten for Africa (Table 2.2), and the four for Latin America (Table 2.3) in a similar manner, studying social adaptability, biological stability, economic stability, nutrient recycling or energy flow characteristics, infrastructure required, the adaptability to commercialization, or a host of relevant features. It is suggested that this ap- proach be used not only to study and appreciate the complexity of farming systems in Asia, but also to structure research and de- velopment strategies for those systems. The major advantage of the approach is that it should increase the probability that the technology derived can become immediately adapted to the situations into which it is to fit. Such an approach would minimize the risk of developing a new and productive technology TABLE 2.1. PREVAMIIN SYSIT1 OF AGRICTUIMR CN SMALL FARMS, M~A RECCNS OF USE, MAJOR CIRPS D ANDBLM SPECIES, AND FE) SOURCES FOR ANIMALS OF ASIA Famning system Major crops Major animals Main regions* Fed sources 1. coastal fishing and Coonuts, cassava, Swine P, T Conut by-products, rice farming complexes, cacao, rice livestock relatively Important Vegetables 2. Low elevation intensive vegetable and swine, live- stock important Ducks Cattle, goats Swine TW, T, M, P, I SL, P, M, I C, IW, HK Swine, fish T, m1 3. Highland vegetables Vegetables, rice, sur- Buffalo, cattle P, T and mixed cropping cane, sweet potatoes, (intensive), live- Irish potatoes Sheep, goats I stock inmortant Vegetables Swin P Rice Cattle, buffalo Asia 4. Upland crops of Maize, cassava, Cattle, buffalo, IN, T semiarid tropics, sorghan, kenaf, wheat, goats, sheep, livestock important millet, plses, oilseeds, poultry, swine peanuts, etc. bran Marine products, rice bran Pastured with coOmuts HK Sweet potato residues, rice bran, fermented residues fan vegetable crops Crop residues, imported feeds Crop residues, rice bran Crop residues, rice bran, cut forage, sugarcane tops Same crop residues, waste vege- tables Crop residues Bran, oilseed cake, straw, ster, vines, hulls, hay 5. Humid uplands, livestock uiportant 6. Laoland rice, inten- sive livestock Rice, maize, cassava, wheat, kenaf, sorghum, beans Sugarcane Rice, vegetables, pulses, hick-peas, mug-bean, sugarcane 7. Multistory Coonuts, cassava, (perennial mixtures), bananas, mangoes livestck sane coffee iportane Pineapple Swine, poultry, Asia cattle, buffalo 01000 mn rain) Cattle, buffalo T, P, I Cattle, buffalo, Asia swine, ducks, fish Cattle, goats, P, IN sheen Cattle Stover, weeds, by- products, ugarcane tops Sugarcane tope, crop residues Crop esidues, ueds, by- products, sugarcane tope Cut and carry feeds from croplands P, I Crop residue, by-products 8. Tree crops (mixed orchard and rubber), livestock same importance orchard, trees, rubber, oil palm 9. Swidden, livestock Maize, rice, beans, important peanuts. vegetables 10. Animal based Fdder crops Cattle, goats, P, M, swine South T Swine, poultry, Asia goats, sheep Cattle, buffalo, I, M, IN goats, sheep Grazing or cut ad carry Animals scavenge Cut and carry foder, crop residue *C, Chinat ;I, Hong Kong; IN, India; I, Indonesia; M, Malaysia; P, Philippines; SL, Sri Lanka; T, Taiwan; T, Thailand. that would be unacceptable because it did not fit into the farming system for which it was intended. Where a lack of fit is predominant, the reason for nonacceptance is usually a net reduction in productivity of the system, due to the fact that interactions among components are not adequately understood by the technology developers. WABLE 2.2. PREVAILING SYSIS OF AGICULJTUE ON SULL FARI~ AIMN IEGICNS OF USE, MMJOR CIOS AND ANIMAL SPECIES, MAD E S=CURS FOR ANIMx S OF AFRICA Major crops Major animals Main regions eed sources 1. Pastoral herding 2 t Vegetables (Phase I, L = >10 ), P animals very important symbioticc relation- ships) 2. Bush fallow (shifting cultivation, Phase II, L = 5-10), animals not important 3. Rudinentary sedentary agriculture (shifting cultivation, Phase III, L = 2-4), animals important 4. Compound farming and intensive subsistence agriculture (shifting cultivation, Phase IV, L = <2), animals important 5. Highland agriculture, animals important 6. Flood land and valley bottom agriculture, animals of sane important Millet, vegetables Rie/Ya-s/ Plantains maize, cassava. vegetables, tree crops, cocoyMa, yanMs Sorhm/Millet maize, sesame, soybeans, cassava, sugarcane, tree crops, cowpeas, vegetables, yards Rie/Yamse/Plantains maize, cassava, vegetables, tree crops, mocyars SorgbumMillet maize, sesame, cotton, sugarcae, tree crops, cowpeas, yams, tobacot, ground- nuts, vegetables Rioe/Yams/Plantains maize, cassava, vegetables, tree crops, coooyam, yams Vegetables sugarcne, tcacx, sesame. maize, tree crops, groundnuts Vegetables/Millet cassava, oowpeas, taboo cttsn. groundnuts, tree crops Rice/Yaf /Plantains raie, cassava, vegetables, plantain, oo0yanse cowpeas, cassava, maize, millet, groundnuts Millet/Sorghum ianze, groundnuts, cowpeas, sesame, tobacco, ctton, vegetables, cassava, yans Rice/Yams/Plantains Mnaize, vegetables, sugarcane, rioe, yams, cooyarM, millet, groundnuts Rice vegetables, maize, millet, groudnuts, plantain, sugarcane, cocoyans Yane/Sugarcane maize, mopeas, cocyans, groundnuts, vegetables, plantains, rice, yams Cattle, goats, Savanna sheep (Southern Guinea) Cattle, goats. Savanna sheep (Northern Guinea and Sahel) Goats, sheep Humid tropics Cattle, goats. Transition sheep, poultry, forest/savana horses Southern Guinea Northern Guinea and Sahel Natural rangelands, tree forage Natural rangelands, tree forage, crop residues Fallow, crop residues Fallow, straws, stover, vines, cull roots, sesame cake Goats, sheep. Humid tropics ice bran, cull roots, poultry, swine straws, crop residues, vines, stover Cattle, goats, Transition sheep, poultry forest/savanna Savanna (Guinea and Sahel) Goats, sheep, Humid tropics swine, cpultry Goats, sheep, Transition poultry, swine forest/savanna Cattle Savanna (Guinea and Sahel) Goats, sheep, Hurmd tropics poultry, swine Cattle, goats, Transition sheep, poultry forest/savanna Cattle, goats, Savanna sheep, poultry, (Guinea and horses, donkeys Sahel) Stover, vines, sugarcane tops, cull roots or tubers, tree forage, groundnut cake, brans Rice straw, rice bran, vegetable waste, fallow, vines, cull roots or tubers, stover, tree- crop by-products, palm oil cake Vines, stover, tree-crop by-products, groundnut cake Vines, tree-crop by- products, cassava leaves, fallow Fallow, leaves, stover, rice by-produts, cull tubers, cassava leaves, vegetables, residues Stover, vines, groundnut cake Crop residues, sare oil cake, brans, stover, vines, cull tubers Goats, poultry Hunid trpics Crop residues, vines, grazing Cattle, goats, sheep, poultry, swine, horses, donkeys Transition Straw, stover, molasses, forest/savanna brans, groundnut cake Cattle, goats, Savanna sheep, poultry, (Guinea and swine, hrses, Sahel) donkeys Vines, brans, cull tubers, molasses, sgarcane tops Farming system TABLE 2.2. continued ) Farming system 7. Mixed fanning (farm size variable; animals important) 8. Plantation crops, East Africa smalll holdings), animals of sone importance 9. Plantation crops, (onpound fares, etc.), animals of soan inportanc 10. Market gardening (animals say or may not be present) Major crops Rice/aYm/Plantains Rime/Veetables yams, omysn= jil lU-s~ctton, tObcOn. Maite, nempeas. vegetables Coconuts rgeejes' maize, plantains, cscoy-n, cassava Cacao egetables, inmize, plantainns Tre crops sugarcane, plant-w Vegetables Transition forest/savanna Humid tropics Transition forest/savana tL C + F/C; L, land-se factor; C, area of cultivation; P, area in fallow. enclosed areas around household or village. Preset or absent, depends on area. TABLE 2.3. PREVAILING SYSMIS (OF AGRICWILUE FO SMALL FARS, MMN FIGICS OP USE, taCOR C3iPS AND AKMD SPECIES, AND Fr SOURS FOR ANIMD CP IATI PNERC Famnning system Major crops najor animals Main regions* Feed sources 1. Perennial fixtures Cocnuts, coffee, Cattle, aine All Natural pastures, by- (large fans; livesto cacaoo, plantains, products, cul lateral relatively uniportant) bananas, oil palm, sugarcane, rubber 2. Ccrcial annals l croe Rice, maize, sorgun Swine, cattle, All eept C Pasture, crop residues, mediann to large fans, soybeans, snall grains poultry grain livestock moderately important) 3. Conercial livestock a. Extensive Large- o very Nne are inortant Cattle (beef) C, V, Br, Bo, Natural grasslands large, livestock G, CA dominant b. Intensive iunm large, Inproved pasture, Cattle (dairy), All Natural and inprove livestock dominant sae grains swine, poultry pasture, feed grains, by-peducts 4. Mied cropping a. Smal size in Rice, maise, Cattle, poultry, All natural pastures, crop settled areas sorgFum, beans, goats, sheep, residues, cut feed b. Medium size in wheat, caao, donkeys, horses, frontier areas plantains, coffee, mules, wine c. Subsistence or tnbah mcnetized eamxny d. Livestodk relatively important *All, all countries; Bo, Bolivia; Br, Brazil; C, Colontia; CA, Central America; CI, Caribbean Islands; E, Ecador; G, Guyanas; P, Peru; V, Venezuela. Major animals Main regions T1W or pore Humid tropics species (widely variable) Sane cattle Transition forest/savarma Cattle, goats, Savanna sheep, poultry, (Guinea and horses, donkeys, Sahel) camels Cattle, horses, Humid tropics donkeys Transition forest/savanna Goats, sheep, Hunid tropics Feed sources Fallow, straw, brans, vines Fallow, vines, straw Stover, vines, fallow Grazing or cut and carry Grazing or cut and cazry, stower Grazing or cut and carry, sugarcane tops Natural rangelands, crop residues, brrose plants, range forbs poultry, swine Goats, sheep, poultry, swine Variable direct relation to market, absent in cases where little is sold serious liabilities, such as poor use. off mn,. WHEAT MAIZE GRASS POTA- MAIZE TOES WHEAT FARMSTEAD AND FRUIT LL MAIZE BUSH GAR - MAIZE WHEAT BEANDEN MAIZE WHEAT I MAIZE I WHEAT MRAW LAT4NE c\ VM SSTOVER LA1ME - [IAG E W EA CO SWE CATTLE. 49 in which are purchased include tomatoes, garlic, onions, peppers, beans (Phaseolus vulgaris), coffee, sugar, chocolate, riceflour, oatmeal, cooking oil, lard, noodles, etc. Even though someio CONCEPT OF "HOMOGENEOUS SYSTEMS" AND ITS USEFULNESS Peter E. Hildebrand It is obvious from the preceding discussion that no two farms will be alike in all respects. Adding social, economic, cultural, and political influences to physical and climatic factors as constraints to adoption of new technology creates a situation which could seem to be impossible short of individual attention to each individual farmer. This, of course, is im- possible. Fortunately, it has been found that in any area, certain farming systems or portions of the system are similar in important characteristics. These systems or subsystems can be grouped into "homogeneous systems" (Hildebrand 1981, pp.425-426; Norman 1980, p.8) or "recommendation domains" (Byerlee et al. 1982, p. 899) which provide a convenient means for developing "location-specific" technologies. The premise on which the selection of a homogeneous cropping or farming system is based is that all the farmers who presently use it have made similar adjustments to a set of restrictions which they all face and that, since they made the same adjustments, they must all be facing the same set of agro-socioeconomic conditions (Hilde- brand). Once a homogeneous system is identified, it is necessary to discover what agro-socioeconomic characteristics or conditions all the farmers who use the system have in common and then to identify which are the most important to consider in any modifications to be made through changed technology. The homogeneous system or recommendation domain is a group of farmers with roughly similar practices and circumstances for whom a given recommendation will be broadly appropriate. It is a strat- ification of farmers, not area. Socioeconomic criteria may be just as important as agroclimatic variables in delineating domains. Thus, resulting domains are often not amenable to geographical mapping because farmers of different domains may be interspersed in a given area (Byerlee et al.). Although all farms in a geographic area may not (usually will not) fall into the same recommendation domain, it is still important to be able to geographically locate the boundaries for which a particular technology is appropriate. To be able to do this requires an understanding of the farming system itself, the characteristics or factors endogenouss or exogenous) that con- strain the system, and what factors change the system and its geographical boundaries. REFERENCES Byerlee, D., L. Harrington, and D.L. Winkelman. 1982. Farming systems research strategy and technology design. American Agricultural Economics Association, Vol. 64, No. 5, pp 899-904. Hildebrand, P.E. 1981. Combining disciplines in rapid ap- praisal: the sondeo approach. Agricultural Administration 8, PR 423-432. Norman, D.W. 1980. The farming systems approach: relevancy for the small farmer. MSU Rural Development Papers, No. 5. East Lansing. HIERARCHY OF CONSTRAINTS TO SYSTEM PRODUCTIVITY Peter E. Hildebrand Hart highlights the different levels of systems and subsystems which form the environment within which farms operate. Each of these levels within the hierarchy is composed of its own set of resources and conditions, and therefore, of potential constraints to the productivity or efficiency of that particular system or subsystem. A constraint upon the productivity of any level of the systems hierarchy efficiently constrains the productivity of the entire hierarchy. If farmers in a country are capable, for whatever reason, of producing only so much of a product, then that will be the limit to availability of that product withinthe country's economic system. In the absence of imports, production constrains the amount of that product that can be processed in other levels of the in-country systems hierarchy or otherwise be made available as inputs or for consumption. Likewise, if processing is limiting because the only plant is antiquated and no others can be built because of other intervening governmental policies, then no matter how much of the product is produced by the farm level system, processing becomes the constraint to the productivity of the entire hierarchy. A common point of entry for agricultural development tech- nicians into the systems hierarchy of a country is at the crop level,Fig.2.10. Low productivity of one or more crops, that is, lack of self-sufficiency, is seen as a problem by policy makers. One or more projects are initiated in attempts to increase the productivity, or overall production, of the particular crop or crops. The problem is, that policy makers, just like professional scientists and technicians, are all influenced by disciplinary and experiential bias. This means that the individual policy maker or the individual technical consultant will influence the selection of the level within the hierarchy which will become the focus of the project for increasing the productivity or production of the crop or crops in question. The more narrow the training or experience of the individual, the more restrictive will be the focus of attention. A soil scientist will look for soil constraints. He may be concerned with general fertility problems, or more narrowly with micro or macro elements or pH. And, if he is looking for constraints in any of these particular areas, he is sure to find them. Any factor is constraining at some point, and when viewed in isolation, can easily be considered to be the constraining factor to the system. For a person with narrow training or experience, this is an honest assessment and should not be discounted out-of-hand. But the probability that an individual assessment of a person with narrow training and experience will discover the one or the few most limiting constraints, is small. A plant breeder will most assuredly be convinced that germplasm is the most limiting constraint and a farm management economist will be Figure 2.10. Hierarchy of constraints in an agricultural system sure that the problem is allocation of resources on individual farms. An irrigation engineer will view the inefficient use of water, if there is an irrigation system, or the lack of an irrigation system if there is not one, as the major constraint. A marketing economist will see product marketing and perhaps input marketing as the problem. An industrial engineer will see 54 product processing as the bottleneck, and a banker will see credit as the need. At the same time, each of these individuals, when his own solution is not effective, will readily see that the subsystem which falls in someone else's area of responsibility is not functioning as it should to "allow" his "solution" to be effective. A multidisciplinary team with varied experiences will inevitably have a higher probability of discovering which subsystems in the hierarchy and which constraints within the subsystems are the most limiting to the productivity of the entire hierarchical system. This does not guarantee, of course, that any particular team is assured that it will find the most critical constraints to an entire hierarchical system. But the use of such a team definitely will increase the probability that these constraints will be found. It is, of course, exceedingly difficult, if not impossible, to plan or implement the kind of project that would be required to search for constraints at all levels within the systan hierarchy of a country and then to create solutions that would remove them as constraints. But also, this is not required. What is important is that before undertaking a project at any level in the hierarchy, an understanding of the other levels of the hierarchy is gained so that the constraints to the system from the other levels is appreciated. Then, if the lack of a market (either marketing mechanism or effective demand) for a perishable product exists, and this is known, there will be much less temptation on the part of the project design effort, to blindly search for ways to increase the production of that product. Or if credit is simply not available to target farmers, there will be less temptation to develop a technology that requires a source of credit in order to be acceptable to or usable by the clients. Developing the means for removing a constraint which is not one of the constraints limiting the system provides employment for the technicians involved in the process, but does not alleviate the problem nor increase the productivity of the system. If the productivity of the system is not increased as a result of the technicians' activities, in the long run, there will not be a means of paying for the services of those technicians nor the policy makers who authorize the projects. In the long run, it would, therefore, be beneficial to all concerned, to do a better job in searching for and alleviating the key or most limiting constraints to the system, at whatever level in the hierarchy they are found., 2,000 hectares can be considered a small farm. But in any of these areas, smaller farms can be identified. The type of farm being considered here is usually the smaller (as opposed to the larger) farms in an area. Diversification into several ac- tivities creates even smaller enterprises within the small farm. LIMITED RESOURCES Limited-resource is another relative term. All farmers will insist they have limited resources, and they are all correct. But, again, in any area, there will be obvious differences in the resource base of different farmers. This is particularly true if one considers resource quality and not just resource quantity. Land It is tautologous to argue that small farmers have less land. But the quality of land held by small-scale farmers is frequently, if not usually, inferior to that of large-scale commercial or plantation farms. Capital All farmers face some sort of limitations on capital, but many small-scale, family farmers have virtually no cash with which to operate and frequently do not have title to fixed capital (such as land) which could serve as collateral were it possible otherwise to borrow. Many farmers in this situation do borrow, but at very high interest rates, which in itself has the same effect of severely limiting operating capital. Labor Conventional wisdom conveys that small-scale family farms usually have an abundance of labor (large families, small holdings). Off-farm work and a large number of enterprises on the farm, however, can create situations for which labor can become scarce. Because of limited opportunity to hire additional labor, this resource can also be limited at critical times. Management Part-time farmers, who have many different types of enterprises on the farm, have much less time to devote to the management of each enterprise than managers of large-scale commercial or specialized farms. Lower levels of education and more limited access to information also reduce the quality of management on many small-scale family farms. Services Services, which many managers of large farms take for grant- ed, are also frequently limited for small-scale farmers. This is true of information services, product or input marketing services, transportation, storage and processing services and even communication services. All of these factors can be considered as resources to the farmer and have an impact on the productivity of the farm. Fixed Resources Not only is the small-scale farm faced with limited resources compared to a large commercial farm, but also the proportion of fixed to variable resources is different. In a large commercial farm with a relatively abundant capital base, additional resources of most kinds can be purchased when needed. In a small farm with very limited capital, this is not the case, and a relatively high proportion of the resources are fixed. Manure from existing animals may be the only source of fertilizer. The family may be the only source of labor and management. The only source of seed may be that left over after consumption, limited sales and losses in rustic storage. ON THE NON-NEUTRALITY OF SCALE OF AGRICULTURAL RESEARCH Peter E. Hildebrand Carter et al. reported in a recent study that most of the research carried out in the United States was considered by the research directors involved to be scale neutral, meaning it should demonstrate the same potential on small as on large farms. Hence, they argue that the research product was equally adoptable on large and small farms. Yet it has been amply demonstrated, even in the United States, that small farms have not adopted much of the newer technology and have not been able to compete with larger farms in the current economic environment. In this paper, it is argued that the majority of the research that is conceived as scale neutral by the research directors responding to the Carter study is, in fact, not scale neutral and is strongly biased toward large-scale commercial agriculture and against small limited-resource or low-volume family farms. This is true in the United States but even more true in developing countries. Three reasons are primarily responsible for this bias. These reasons are not recognized by most agricultural researchers and have not entered into the evaluation criteria regarding scale effect of the research directors who classified the research reported by Carter et al. The reasons, all interrelated, are: 1. The quality of resources is frequently lower on small farms than on largefarms. This has the effect of shifting a small farm production function downward in comparison with large farms so that response from a technology on a small farm is less than on a large farm. 2. Limited quantities of resources, fixed in a higher proportion for the firm, result in a concave opportunities curve for the low-volume farm. This results in a reduction in Income when enterprises are combined. Yet many small farmers are forced in- to diversification for subsistence or because they have little 59 confidence in support from normal market infrastructure. 3. Forced farm enterprise diversification and/or off-farm work reduce the quantity if not the quality of management in each enterprise on the low volume farm. This influences the time required to learn to use a new technology, shifts the learning curve to the right, and makes learning more expensive. Low-volume output prevents spreading the higher learning costs (loss of income from not achieving anticipated results) over a sufficient number of units to make complex learning situations profitable for the small farm. The combined effect of these three factors is to make it unprofitable for the low-volume farm to adopt more complex modern technology. The need under the conditions of low volume is for technology that is simple, as opposed to complex, and uses mostly resources already fixed on the farm, as opposed to purchased inputs. This is not the kind of technology being produced by the research directors polled by Carter et al., nor by most research establishments in developing countries. RESOURCE AND INPUT QUALITY Not universally, but frequently enough to make it a general rule, small farmers operate with inputs and resources of inferior quality compared to large or commercial farmers. It is common to see small farms pushed off onto steep or rocky hillsides with obviously poorer soils. Animals or power equipment, if they exist at all, are weaker or smaller and do a less effective job in soil preparation and cultivation. Purchased inputs are more apt to have been poorly stored or otherwise arrive at the farm with inferior quality. These and other reasons account for a lower quality input and resource base on a small farm. Combining these inputs with a new technology leads to lower responses than those achieved on farms with a higher quality resource base and reduces profit potential from adoption. It is not the size of the field in which an improved seed is plant-edthat-iiimTpo-ran-. It is the quality of the soil, the amount of moisture, the presence or absence of pest and disease control, and the losses between maturity and harvest, when combined with the improved seed, that influence response. Technical innovations that appear promising with high level production functions are much less so with lower level response surfaces. FIXED RESOURCES Undoubtedly the least understood effect of producing on a farm with a high proportion of fixed inputs or resources is the influence of fixed resources on the production possibilities or opportunities curve. Many economics texts cover the case of limited-resource firms combining products in Stage I of the production function. This produces an opportunities curve that is concave from the origin (Figure 3.1), for which spec- ialization and not diversification, maximizes income. But even Opportunities Curve X IX2 ...X, X1 I X2...Xn Figure 3.1. Combining enterprises with inputs limited to Stage I in this case, the effect of the resources fixed for the firm but variable between enterprises is usually ignored. Rather, it is assumed implicitly that the amount of the X2 to n fixed factors in each of the production functions in Figure 3.1 is equal. This implies that X2 to X are not interchangeable between Y1 and Y2. This clearly is not the case with a limited-resource firm. Consider the case of a firm choosing between two products, Y, and Y2' and with four units of a resource X2, fixed for the firm but variable between the two enterprises. If one input X1 is variable, there will be a family of production functions related to the levels of the fixed resource with which it is combined (Figure 3.2). Implicitly assumed in standard texts is that there are four units of the fixed resource available for each of the two enterprise possibilities. However, if rather than produce only one product, using all four units of the fixed resource, the farmer produces some of both, then some of the same four units of the fixed resource must be used in the production of the second product. The effect is to shift both production functions downward from X1 | X2 = 4, a consequence not considered in the standard explanation of enterprise combination. As a result, production possibilities are represented by a family of opportunity curves for which the envelope opportunity curve is again concave, not convex (Figure 3.2c). This effect exacerbates even more the consequences of forced diversification. COST OF LEARNING One of the most critical functions of management is learning to use new technology. Depending on the nature of the technology, it may take several attempts before its anticipated potential can be reached. The responses achieved at each different attempt form what can be called a learning curve. Most work dealing with learning curves has associated successful learning with reduction in unit cost. In Figure 3.3, learning is related to increase in yield, which is frequently the aim of a new agricultural technology. In this figure, yield potential MaxX1 X 1X2 Envelope Opportunities Curve MaxX1 XI)X2 2a 2b Figure 3.2 Combining enterprises with a limited fixed resource, x2 = 4 units. from the new technology is very high. However, it takes nearly five attempts before the full potential is achieved. Economically, present yield has an associated gross income, cost, and net income (Figure 3.4). A farmer with a relatively low level of yield and income is presented with a new technology that has high gross-income potential. However, associated with this potential high income is usually an increased cost, Figure 3.5. If a farmer decides to use the new technology, he invests at the higher cost level. If he does not achieve the potential response on the first or second attempt, as shown in Figure 3.5 net income can be negative for a period of time. In this figure it takes three years to break even. In a large-volume commercial operation, the future positive income stream can easily pay for the losses during the early stages of learning. However, on a small farm with low volume, this is more difficult, especially if a portion of that low volume is used for subsistence on the farm and does not enter the market. A person who has less time to devote to the learning process cannot achieve the potential from the new technology as rapidly as a person who has more time available for learning. Hence, for a manager of the small-scale family farm who has many enterprises to manage, the learning curve shifts to the right and more attempts will be required before potential is achieved (Figure 3.6). On the other hand, technology that is simpler to learn can shift the curve to the left. Fewer attempts are required before the full potential is reached. The conclusion is that simple rather than complex technology is more appropriate for the small-scale family farmer with little time available for learning how to use the new technology for each individual enterprise. However, simpler technology that would shift the learning curve to the left usually is associated with a lower potential benefit and net income (Figure 3.7). This leads to rejection of the simpler technology by scientists when evaluating alternative technologies in favor of more complex technologies with higher yield and income potential. For the scientist who assumes instantaneous learning, this is a logical decision. But for the small diversified farmer who does not learn instantaneously, the Yield Results with New Technology (Learning Curve) Yield with Present 0 1 2 3 4 5 6 ATTEMPTS Figure 3.3. Responses achieved with a new technology related to number of times used $ PoFenial Fiomn Nev. Tcchnrolog Gross Income, present rechnolog ~----------------------- Net Income, present technology I- --------------------------------- Cost, present technoloMv 0 1 2 3 4 5 6 ATTEMPTS Figure 3.4. Gross income from new technology related to the learning curve YIELD RESULT Figure 3.5. Gross Income Cost New Technology Cost New Technology Net Income SNew Technology 0 1 2 /3 4 5 6 Net Loss ATTEMPTS New Technology Negative and positive net income from using a new technology related to the learning curve simpler technology may be more acceptable and more adoptable than a higher-payoff technology tat takes several attempts to learn and may therefore be rejected. A rapid rate of learning, a large volume over which to amortize the learning cost, and a low discount rate would all enhance the adoptability of a proposed new technology. None of these are characteristic of a small farm. In their absence, a particularly high potential profit would be required to entice a small farmer to try the new technology. But high payoff technology is usually associated with a high proportion of purchased inputs requiring cash or credit, which the small farmer does not have, and/or increased risk to levels unacceptable to a person who would be risking his home and not just his business. SUMMARY AND CONCLUSIONS Low quality resources on small farms compared with large farms shift downward the response surfaces associated with a technological change, making the potential profit from the POTENTIAL RESULT PRESENT RESULT 0 1 2 3 4 5 6 ATTEMPTS Figure 3.6. YIELD Shifts in the learning curve related to complexity of new technology and facility or time for learning Potential Complex Technology Potential Simple Technology ------------Present Technology Present Technology --------- E -----_---- 0 1 Figure 3.7. 2 3 4 5 ATTEMPTS Frequent relationship of simpler (easier to learn to use) technology and potential productivity adoption of the technology less than for a large farm. Forced diversification on small farms, combined with a high proportion of fixed resources, reduces income rather than increasing it as it does on a larger capital base with a higher proportion of variable resources. Less management time available for each enterprise on small diversified farms makes learning more difficult and costly and further reduces the discounted present value of the response of a new technology that does not produce anticipated returns the first year. Any of the effects in- dividually reduces the acceptability of a high-cost or complex technology to the small farmer. When all effects are taken together, as is the case on most small farms, the result can be overwhelming rejection of much modern technology. And if small farmers are unable to adopt new research results (technology) because of these straightforward economic reasons, it is. not correct to argue that most of our agricultural research is scale neutral. The conclusion is that agricultural research designed for small farms must result in technology that is simple and not complex, to reduce learning costs; use mostly resources available on small farms with a minimum of purchased inputs, to reduce capital requirements; and be evaluated and tested under the resource conditions found on the farms of the clientele for whom they are designed, to reduce inflated estimates of potential response. It is critical that agricultural researchers com- prehend the economics of small farms if they intend to produce technology for them. Otherwise, agricultural research will continue almost inevitably with a bias, albeit unintentional, toward large commercial farms, and worldwide efforts to aid small farmers will continue to have only limited effects. REFERENCES Carter, H.O., W.W. Cochrane, L.M. Day, R.C. Powers, and L. Tweeten. 1981. Research and the family farm. Paper prepared for the Committee on Organization Policy. Cornell University, Ithaca, N.Y. THE PUZZLE: PANAJACHEL, GUATEMALA Theodore W. Schultz THE PUZZLE Suppose it were true that not much additional income could be had from a better allocation of the existing stock of traditional factors of production. This assumption does not rule out some small gains from this source, but it does imply that growth opportunities in this direction are unimportant (Harberger 1959). Suppose, further, that it were also true that investment to increase somewhat the stock of traditional factors of production would produce a very low rate of return (Subcommittee 1962). Here, too, there could be some imperfections in the way the capital "market" functions, which could be corrected, and if this were achieved some additional investment would be forthcoming. Yet the increase in income from such measures would not open the door wide for economic growth. Lastly, then, suppose there were some reproducible factors of production in other communities that differ from the traditional factors on which a particular community is dependent and that these differences make them both more productive and profitable. Why is it that farm people now dependent upon traditional agriculture do not take advantage of these more productive and more profitable factors? The puzzle underlying this question is ever so perplexing in the case of Panajachel, Guatemala, a community to be examined in some detail. The people are obviously hard working, thrifty, and acute in selling their crops, renting land, and buying things for consumption and production. The community is not an isolated subsistence economy, but is closely integrated into a larger market economy. Yet, hoes, axes, and machetes are not replaced by better tools and equipment. There is not even a wheel. Coffee leaves used as fertilizer are not replaced or supplemented by chemical fertilizers. Traditional breeds of chickens are not replaced by better hens for producing eggs and broilers for producing meat. The traders and firms in the towns that serve this community are not offering for sale any of the superior factors. If one wanted to plan a community like Panajachel that would go on for decades without any change in the state of arts on which it was dependent, it would strike one as impossible within the market economy of Guatemala. Yet Panajachel has been doing the "impossible" in this respect for generations. That is the puzzle. PANAJACHEL, GUATEMALA: VERY POOR BUT EFFICIENT A classic study by Sol Tax, Penny Capitalism (1953), opens with these words: it is a "society which is 'capitalist' on a microscopic scale. There are no machines, no factories, no co-ops or corporations. Every man is his own firm and works ruggedly for himself. Money there is, in small denominations; trade there is, with what men carry on their backs; free entrepreneurs, the impersonal market place, competition these are in the rural economy." Tax leaves no doubt that this community is very poor, that it is under strong competitive behavior, and that its 800 people are making the most of the factors and techniques of production at their command. No one ought to be surprised that the people are very poor. Tax puts their poverty this way: they "live without medical aid or drugs, in dirt-floored huts with hardly any furniture, the light only of the fire that smokes up the room, or of a pitch-pine torch' or a little tin kerosene lamp; the mortality rate is high; the diet is meager and most people cannot afford more than a half-pound of meat a week. Schools are almost nonexistent; the children cannot be spared from work in the field. Life is mostly hard work." (Tax 1953 p.28) Tax presents many data measuring the consumer goods and the level and cost of living to support this poignant testimony on the poverty of the community. Competition is present everywhere in the way products and factors are priced. "All household utensils pottery, grinding stones, baskets, gourds, china, and so on and practically all household furnishings, such as tables and chairs and mats, must be brought in from other towns. So must many articles of wearing apparel, such as material for skirts and cloaks, hats, sandals, blankets, and carrying bags, as well as cotton and thread for weaving the other things. So must most of the essential foodstuffs: the greater part of the corn, all lime, salt and spices, most of the chile, and most of the meat. To get the money they depend upon the sale of agricultural produce. . Onions and garlic, a number of fruits, and coffee are the chief commodities produced for sale." (Tax 1953 pp. 11-12) Prices are in every respect highly flexible. Tax goes on to document the fact that the Indian is "above all else an entrepreneur, a business man," always looking for new means of turning a penny. He buys the goods he can afford with a close regard for price in various markets, he calculates with care the value of this labor in producing crops for sale or for home consumption against his working for hire, and he acts accordingly. He rents and pawns parcels of land with a shrewd eye to the return, and he does likewise in acquiring the few producer goods that he buys from others. All of this business, "may be characterized as a money economy organized in single households as both consumption and production units, with a strongly developed market which tends to be perfectly competitive." (Tax 1953 p.13) The economy has been geared to a stable, virtually sta- tionary, routine pattern. Not that the Indian is not always looking for new ways to improve his lot. Tax notes that "he is on the lookout for new and better seeds, fertilizer, ways of planting". But such improvements come along infrequently, and their effects upon production are exceedingly small. There was a growing demand by "foreigners" for some shore land along Lake Atitlan but this development was having very little effect upon the land Indians used for producing crops and on which they built their huts. Some buses and trucks had become available for transport to more distant towns and they were being used to go to and from markets in these towns because it was "cheaper" than walking and carrying the goods. There were more tourists in and about the lake but these too were having little or no discernible influence on the community. All the evidence revealed in the careful documentation of the behavior of the people in Penny Capitalism and in the many tables showing prices, costs, and returns strongly supports the inference that the people are remarkably efficient in allocating the factors at their disposal in current production. There are no significant indivisibilities in methods of production, none in factors, and none in products. There is no disguised unemploy- ment, no underemployment of either men, women, or children old enough to work, and for the least of them there is no such thing as a zero marginal product. Because even very young children can contribute something of value by working in the field, they cannot be spared the time to go to school. Product and factor prices are flexible. People respond to profit. For them every penny counts. REFERENCES Harberger, A.C. 1959. Using the resources at hand more effec- tively. American Economic Review (Papers and Proceedings), 49:134-46. Subcommittee on Inter-American Economic Relationships of the Joint Economic Committee of the Congress of the United States. 1962. The rate of return on capital in Latin-American economies: with special reference to Chile. Hearings on Economic Development in South America, May 10-11. Tax, Sol. 1953. Penny capitalism. Smithsonian Institution, Institute of Social Anthropology, Publication No. 16 (Washington,: U.S. Government Printing Office). Reprinted by the University of Chicago Press. 1983. UNFORSEEN CONSEQUENCES OF INTRODUCING NEW TECHNOLOGIES IN TRADITIONAL AGRICULTURE Peter E. Hildebrand and Edgar G. Luna coordinated programs, and lack of information regarding economic constraints and requirements and optimum input and product combinations for feasible solutions to problems of the minifundistas. Schultz's "Economic Efficiency Hypothesis"(Shultz 1964 p. 16) proposes that farmers in traditional, but stable, agriculture have adjusted to their conditions in such a manner as to be eco- nomically efficient. We agree with this hypothesis, which implies that no changes in input or product mix from among the alternatives historically available will result in any sig- nificant improvement in the income of the farm. But more and more, traditional farms are being affected by new technologies. (pp. 162 ff.), that the introduction of a modern technique is not always profitable in any particular area, because it may not be adapted, the price conditions may not be similar, risk may be increased, etc. Again, we do not disagree with these considerations. But we would argue that a more important effect is that the introduction of one or more new factors in an otherwise stable 69 and traditional farm economy adversely influences the economic balance of the traditional factors that are not being changed. The introduction of a new variety, a high analysis fertilizer, or a potent insecticide singly, or in a package, can have unforeseen effects, suchino, which sheds some light on the nature of the problem and should be of wide interest to economists and other agriculturalists working in small-farm development. In the study area traditional agri- culture remains the predominant characteristic, but through the efforts of rigorous research, extension, and credit programs, many new technologies are finding their way into common use. Nevertheless, farm incomes remain low. The study that of 10 to 15 and 15 to 20 hectares.. FARM clas- sification could be used and this only for wheat, the most widely produced crop in the region. Contrary to what one would expect, the smaller farms were not using sufficient labor in the production of wheat. Addi- tional, fertilizers, and pesticides. But these modern technologies have all been developed in association with adequate mechanized land preparation. Hence, the formerly adequate land preparation techniques become inadequate when combined with a partial "package" of modern technology. Apparently the productivity of the modern technology is also difficult to predict when transferred to a traditional agri- cultural was excessive. An informed explanation of the underuse of seed on the small farms (even though the average use corresponds to current recommendations) was that the seed used by these farmers was not of the quality used for experiments or demonstrations or even by the larger farmers. Hence, the same quantity yielded fewer tt proportions of the modern and traditional factors in use on thee farms could increase income substantially. An increase i fertilizer and seed use accompanied by more labor in lan preparation could increase production of wheat per hectare by 5 percent and the additional costs would have a 100 percent ne return. But an overriding problem with this solution is that it i doubtful that land preparation can be markedly improved b intensifying current traditional practices. As a minimum improved yokes for the bullocks and better implements for anima traction will have to be introduced to the area in order t achieve a more efficient balance with the other modern technique now being used. Possibly only mechanized land preparation wil suffice. In the Department of Narino potatoes are an important commercial crop, but in the study area (Municipio of Yacuanquer they rate much more as a subsistence crop (wheat is the mail commercial crop). Nevertheless, potato production is high ris) and requires more technology than wheat. Labor used in land preparation was found to be adequate foi potatoes but an increase in labor would be desirable during th( growth of the crop. Relatively large quantities of fertilizer were used (from about U.S. $20.00 to $125.00 per hectare with at average of $65.00) but an increase would be profitable. Pes- ticide use, while very common, was found to be quite inadequate as average insecticide use did not reach Stage II. Corn, another subsistence crop in the area, is considered inferior to potatoes and grown usually in small plots. Ir accordance with its stature in importance, it receives relatively poor care and few modern inputs. Indeed, our study indicated that labor, seed, fertilizer,.and pesticides were all used ir sub- jected to incomplete "packages" of modern or new techniques. But it is also very likely that it is not feasible to supply complete packages because too many factors would have to be included. One extremely important factor which is virtually impossible tc include in a package (except on a very small scale) is the management capability of the small farmer. The conclusion that must be reached is that maladjustments will always exist so long as traditional (or even nontraditional but poorly developed) agriculture is subjected to the development process. The same conclusion holds, of course, for any economy that pro- duction are inefficiently allocated. In fact, there has never been any real need for such studies. It can be concluded that there is a tendency toward lesser incomes on small farms that are diversified than on those that that would mean to feel the effect of the concave opportunities curve. Another conclusion of the study is that specialization of small farms can tend to reduce the pressure for expanding farm size in areas where population is high and land scarce. It is easier on a small farm to reach the optimum area planted for one crop farm than for each of two or more crops. Thus, specialization can be an important component of an agrarian reform program. RECOMMENDATIONS One of the high id that he can purchase his,. REFERENCES Luna T., Edgar G. 1972. Estudio de la productividad de los recursos agricolas en zonas de minifundio. Unpublished MS thesis. Program de Estudios para Graduados, Universidad Nacional, Instituto Colombiano Agropecuario (ICA). Bogota, Colombia. Schultz, Theodore W. 1964. Transforming traditional agricul- ture. Yale University Press. New Haven, Conn. RESPONSE TO TECHNOLOGICAL CHANGE John W. Mellor The record in regard to acceptance of technological change by subsistence farmers in traditional economies is mixed. On the one hand we have the generally poor record in this regard of major programs of community development and extension. Such programs have normally included an effort to gain farmer acceptance of a wide range of innovations said to increase production and incomes, and yet the acceptance of change and particularly the impact on production has generally been rather small. On the other hand we have-numbers of examples of individual innovations, including a number of mechanical in- novations, improved seed varieties, inorganic fertilizers, and so on, which have in certain specific situations spread very rapidly even without formal programs of farmer education and exhortation. In regard to the failures of community development and ex- tension, it is easy to demonstrate that a high proportion of what has been recommended has not been economically or even technically suitable, and hence failure of farmers to accept such innovation appears more as a recommendation of their economic acumen than of their non-economic drives. But on the other hand, a high proportion of the success stories tend to involve innovations which were very similar to practices already fol- lowed, which were simple and easy to apply, and which provided unusually high returns. The record for complex innovations providing some modest returns is not so clear. The record in regard to acceptance of innovation is further clouded by the wide range of factors which may inhibit acceptance of innovation. Innovation may be accepted by farmers, not because of direct economic benefits from the innovation itself, but because acceptance of innovation brings ancillary benefits of favor from personnel and agencies fostering the innovation. The tying of extension programs with programs of government subsidized inputs, including credit, is an important case in point. Innovation may also be accepted or rejected on basically non-economic grounds of traditionalism on the one hand or prestige of being an innovator on the other. Insofar as acceptance of innovation by subsistence farmers in traditional agriculture is based on the individual direct economic gains from the innovation, then three conditions must be met if innovation is to be accepted. There must be a desire for increased material welfare, there must be expectation that specific innovation will increase wealth, and there must be expectation that the farmer as innovator will participate in an increase in wealth from innovation. The desire for increased material welfare may be weak in a traditional agriculture. An apparent attitude of uninterest in improved material welfare may grow in a situation in which there has been a history of no possibility of improved welfare through increased production a condition carmon in traditional agriculture. Under such circumstances improvement in the position of one individual must come largely from taking income away from others that is, by redistribution of wealth . The alternative of increasing individual wealth through expanding production is not thought to exist. In such circumstances a stable society requires conventions which inhibit desire for increased material welfare. Lacking such restraints, society will be constantly torn by strife as each attempts to benefit himself by taking advantage of others. Thus it is likely that, the longer the stable cultural history of an economically traditional society, the more inhibitions to incentives for change will have become institutionalized. In such societies the first requisite to increasing incentives is development of an awareness of the possibility of change and an awareness that this possibility can be positively rewarding both to the individual and to society as a whole and not just at the expense of the welfare of others. In most parts of the world enough has already been done in effectuating political and social change, and to a certain extent in introducing economic change, to achieve the requisite awareness. A problem which was probably critical a few decades ago is probably now restricted in importance to scattered pockets of traditionalism. Judging from past history, it is likely that political fer- ment plays an important role in developing a favorable personal and institutional attitude toward change. The very act of change in political leadership, the emphasis upon man's control of his own destiny which accompanies political ferment, and the rapid development and dissemination of ideas, must all play a role in the process of loosening men's minds and encouraging an attitude favoring change and improvement. In most parts of the world recent decades have seen substantial political ferment and it is likely that this has broad impact upon the motivation of men and their attitude toward change. Given a general environment of ferment and change, the for- mal educational system may play an additional important role in shaping the development of broadened horizons. Education introduces a logic and rationale to many aspects of life, it opens up knowledge of different things, it demonstrates change, and, equally important, education itself provides one of the most important means of change by increasing mobility to other jobs and by providing a basis for understanding changes within agriculture which may improve welfare. In addition to the political framework and education, phys- ical health may play an important part in the development of positive motivation toward change. Where a population is heavily ridden with parasitic infections and debilitative disease, its physical energy is certainly sapped and it seems likely that an attitude of lethargy and inertia is created. It is difficult for persons ill and weak from such health conditions to develop an interest and enthusiasm for change. Indeed, in nations with substantial stock of unutilized manpower the favorable effect of control of disease on mental attitude may be much more important to the progress of development than its purely physical effect. Unfortunately little empirical study of this aspect of public health has been made, so we can do little more than speculate upon its significance. It is also likely that the variety and quantity of consumer goods available has an important influence on the extent of desire for improved material welfare. Even where the possibility of change is accepted and education and health have broadened horizons and ambitions, the desire for increased material welfare may be small because of the lack of availability of consumer items of the type and units which are suitable to existing incomes. It is probably correct that the longer the history of cultural development of a society, the more standardized and traditional will be consumption patterns and the greater the inhibitions to the introduction of new consumption patterns. Again, however, most societies have now had sufficient history of new forms of consumption patterns to have at least seriously weakened the hold of traditionalism on consumption patterns. The problem nowadays in most areas is more likely one of providing the consumer-goods incentives in the appropriate price, quality, and quantity ranges rather than in breaking the hold of traditionalism on consumption patterns. Thus, it is likely that subsistence farmers in a traditional economy are slow to innovate, even if innovation is highly profitable, because of various inhibitions to material im- provement. Contemporary political ferment, expansion of education, widespread marketing of consumer goods, improved health and other factors, have all contributed to a much more encouraging current attitude toward innovation in most of the world's peasant economies. Currently it is likely that a greater barrier to acceptance of technological change is that of the farmers' low expectations that specific technological changes will, in fact, increase wealth. Again there is a tendency in traditional agriculture with a long history of cultural development to have insti- tutionalized resistance to innovation. In a traditional agriculture the past evidence concerning innovation and change has generally been that it does not provide improvement. Until development of innovations (research) is institutionalized and based on a solid body of theory and tested thoroughly, the group which is most likely to survive is the one which puts decision-making power into the hands of senior persons who have had ample opportunity to see innovation fail and who will profit from that experience by extreme conservatism. Even initial efforts to institutionalize research are likely to include a relatively high proportion of failures. Hence, even as conscious development commences, the premium may still lie with the conservative rather than the innovative. It thus is important to the development of a desire for change, and motivation to change, that successful innovation be produced and demonstrated. And then a slow process of change in leadership patterns may be required. Particularly in early stages of agricultural development, innovation may require additional labor input if it is to be profitable (Mellor 1962). In such a case innovation may not be accepted for the simple reason that it requires a substantial labor input and yet does not generate sufficient income to return the labor enough to attract it into production. In such a case farmers' actions seem uneconomic only if it is assumed that the labor has no opportunity cost or reservation price a not uncommon error on the part of economists. On the other hand, technological advance may provide the basis for shifting the labor-input, crop-output schedule up to the right sufficiently to raise the level of returns to the requisite additional labor input enough to attract it into use (Mellor 1963). Indeed, the expectation of very high returns to technological advance in low-income countries is based in part on the premise that such an effect will be had. Farmers may, of course, also be inhibited from accepting innovation because of their reluctance to increase debt. In a subsistence economy special problems arise if innovation requires added cash expenditure and cash indebtedness and yet generates more output which is likely to be consumed in the farm household. The tendency for technological innovation to require increased monetary input also increases the problem of risk associated with price instability. Finally, the profitability of innovation is affected by the skill and knowledge with which it is executed. In traditional subsistence agriculture the background of education or experience with change is such that innovation is often poorly executed and hence provides poor returns. In the case of very simple innovation, involving simple substitution of one seed for another, this may prove of small restrictive importance. How- ever, with complex innovation, such as the complex package including hybrid maize, a major problem may exist which the standard institutions of a subsistence agriculture are not well adapted to meet. Even if farmers are motivated to change and innovation is profitable, there remains a requirement for expectation on the part of the innovator that he will himself participate in the net increase in wealth which accompanies successful innovation. The innovator may fail to participate in the benefits of innovation for three sets of reasons: he may not have sufficient control of the factors of production to channel benefits to himself; he may not have sufficient control of the marketing process to channel benefits to himself; and he may not have sufficient control of his own consumption patterns to allow increased income to be used to his own benefit. All three of these influences are likely to be closely related to the system .of land tenure, and all three are likely to represent a special problem in subsistence agriculture in traditional economies. Land represents the key case of a factor of production which may be controlled by someone other than the innovator in such a way as to draw a disproportionate portion of benefits away from the farmer-innovator. Where population pressure is heavy, the bargaining power of the landowner may be such that he can control the division of benefits from innovation. Of course it appears to be against the landlord's own economic interest to take so much of the benefit of innovations as to remove all incentive from the farmer to innovate. Such practice may arise, however, because in fact the landlord is, on the one hand, not himself strongly motivated to increase his income from agriculture and, on the other hand, more concerned with maintaining subjugation of the tenant class. Such subjugation is likely to be reduced by improved economic position of the tenant class, and hence the landlord class may even have a positive incentive to prevent such improvement. Such restrictive practice may also arise simply from the institutionalization of the landlord-tenant relationship so as to load the costs of innovation on the tenant and the benefits on the landlord. In a traditional agriculture land- lord-tenant relations may develop in a manner which is optimal for the given production conditions. Where purchased inputs are not important, there is unlikely to be an institutionalized means of dividing the cost of such inputs. With the introduction of change which requires substantial quantities of purchased inputs, the landlord may not understand the potential for return and may refuse to participate, even though he may still demand a full share of the total output, including that due to the purchased inputs. In commercial agriculture technological innovation has been accepted for so long that land tenure institutions, including landlord-tenant relationships, have generally adjusted in a manner to encourage innovation to the benefit of both landlord and tenant. Capital is another input over which the farmer may have little control but which is crucial to production. If capital is scarce and highly complementary with other inputs, the farmer may have to relinquish much of the benefit of innovation to the provider of capital. This problem is often tied to the problem of land tenure, since the capital input may be provided by the landowner. Where it is not tied in with land tenure, it is likely to be a limiting factor to incentives for only those farmers with relatively small holdings and lower-than-average incomes. These farmers are important from a welfare point of view but control too little land in the aggregate production. A problem very similar to the credit problem is that of marketing. If the marketing channels are limited and entry is difficult or impossible, then the marketing agencies may draw off most of the benefit from innovation and thereby discourage application of innovation. Again, of course, it is never to the advantage of the monopolist to squeeze so tight that he prevents income-increasing innovation, but institutionalization of pres- sures, ignorance, and even a desire to maintain control through restriction of incomes and maintenance of dependency may all work to provide pressure restrictive of innovation. However, entry into agricultural marketing in low-income countries is generally relatively easy; and therefore it is unlikely that monopoly power will be wielded for any considerable period of time. Again, the hold of credit and marketing agencies on the very small, very low-income farmer may be strong and exploitative. It is important here, however, to distinguish between the welfare problem and the production problem. Such restrictions are not restrictive of the total volume of production, even though they may inhibit improvement of conditions for a substantial number of people. Again it is likely that the worst abuses of market power occur in cases in which credit and marketing are tied to control of the land resource. Restriction of consumption patterns is a less obvious but nevertheless potentially important factor which may remove expectation on the part of the innovator that he will benefit from increased wealth. Again, important restriction in this regard is likely to be tied in with control by the landlord, or other power agents may restrict consumption from important outlets. A key example is schooling. In most low-income countries the drive to provide schooling is very high in rural areas. This continues from and grows out of the drive for providing alternative employment opportunities. If the political power structure, particularly including the landlord class, is opposed to the provision of rural schooling for fear that it will eventually upset the political power structure, then an important reason for generating additional income is lost. In a more general way, tight control of the availability of consumption goods and the general control of their own lives and destiny may lead to a sense of resignation which is discouraging to in- novation even when a significant portion of the monetary benefits of innovation may come to the farmer decision-maker. REFERENCES Bauer, P.T., and B.S. Yamey. 1959. A case study of response to price in an underdeveloped country. Economic Journal, Vol. LXIX, No. 276 (December 1959), pp. 300-305. Desai, D.K. 1963. Increasing income and production in Indian farming. Bombay: Indian Society of Agricultural Economics. Falcon, Walter P. 1964. Farmers' response to price in sub- sistence economy: the case of West Pakistan. American Economic Review, Vol. LIV, No. 3 (May 1964), pp. 580-591. Heady, E.O., and Narindar S. Randhawa. 1964. Inter-regional programming model for agricultural planning in India. Journal of Farm Economics, Vol. 46, No. 1 (February 1964), pp. 137-149. Krishna, Raj. 1963. Farm supply response in India-Pakistan: a case study of the Punjab Region. Economic Journal Vol. LXXIII, No. 291 (September 1963), pp. 477-487. Mellor, John W. 1962. Increasing agricultural production in early stages of economic development, relations, problems and prospects. Indian Journal of Agricultural Economics. Vol. 27, No. 2 (April/June 1962), pp. 29-46. Mellor, John W. 1963. The use and productivity of farm family labor in early stages of agricultural development. Journal of Farm Economics, Vol. XLV, No. 3 (August 1963), pp. 517-534. Mellor, John W. 1966. The economics of agricultural dev- elopment. Cornell University Press. Ithaca, New York. Schickele, Rainer. 1966. Farm management research for planning agricultural development. ADC reprint (December). Agri- cultural Development Council. New York. Schultz, Theodore W. 1964. Transforming traditional agri- culture. Yale University Press. New Haven, Conn. Stevens, Robert D. 1959. Capital formulation and agriculture in some Lebanese villages. Unpublished Ph.D. dissertation, Cornell University. Ithaca, New York. Tax, Sol. 1953. Penny Capitalism: a Guatemalan Indian eco- nomony. Smithsonian Institution, Institute of Social Anthropology, Pub. No. 16. Washington D.C.: U.S. Gov- ernment Printing Office. Republished, University of Chi- cago Press, 1963. CHAPTER 4 Initial Characterization of Farming Systems: Comprehending and Utilizing What We See and Hear The last two chapters have discussed the nature and characteristics of small-scale, limited-resource family farms and farmers. This chapter is the first in a series devoted to the methods used in FSR/E to develop and disseminate technology to farmers with these characteristics. The first step is to characterize the farming system or systems in an area and de- termine the constraints to enhanced productivity and to improved welfare of the farm families. Rapid reconnaissance has become one of the trademarks of FSR/E. It is used as the means of obtaining an initial characterization of an area. It is also one of the phases of FSR/E most heavily influenced by the concepts and practices of the social sciences. ANTHROPOLOGICAL PERSPECTIVES ON CONTEMPORARY HUMAN PROBLEMS J. H. Bodley ANTHROPOLOGY'S CONTRIBUTION I hope to demonstrate that a clear understanding of the principles of anthropology illuminates the social processes of our times and may show us, if we are ready to listen to its teachings, what to do and what to avoid. (Boas 1928,11) We have defined the general nature of the world crisis and suggested some of the possible dangers and difficulties inherent in the slow response that is occurring -- now it must be argued that anthropology has something important to say to these issues. The problems facing us are unmistakable but complex, and ac- ceptable solutions are still neither obvious nor easily implemented. In recent years, there has been an enormous outpouring of crisis-related literature. Specialists in many disciplines have attacked isolated problems; unfortunately, however, overall results have been limited. For example, far Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2010 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Last updated October 10, 2010 - - mvs | http://ufdc.ufl.edu/UF00072280/00001 | CC-MAIN-2015-14 | refinedweb | 28,537 | 50.16 |
I know to make a singleton class but if suppose I require to clone it how can that be done.
If anybody can reply with sample code it would be better.
Thanx in advance!
Printable View
I know to make a singleton class but if suppose I require to clone it how can that be done.
If anybody can reply with sample code it would be better.
Thanx in advance!
How do you clone a non-singleton instance? What have you tried? Where exactly are you stuck?
Not tried cloning an instance ever but I know that the class needs to implement the Cloneable interface and override the clone method of the object's class(Please correct if I am wrong anywhere). But I know of how making a class as singleton. But then suddenly this thing striked in my mind that what if I require to clone a singleton instance and if so how can I do that?
I suggest you put together a small SSCCE that demonstrates a concrete example of what you're talking about. Whether or not an instance is a singleton or not really doesn't have anything to do with how you clone it. Why you'd want to clone a singleton really depends on your context though, so I'm not sure what you're asking. An SSCCE will help with that.
I got your context of getting confused that if suppose I am making a class singleton whats the exact reason I would like to clone it. Its just for my understanding I need to know when I make a singleton class and then I require to clone that particular class then how can I do that. Actually is it possible to clone a singleton class and if so how? Below is the demonstration.
public class A {
private static A a;
private A(){}
public static synchronized A getAObject(){
if (a == null)
a = new A();
return a;
}
}
Now i need to clone the instance of this class. How can I do that?
That's the whole objective of creating a decent singleton -- to make it so that it is difficult if not impossible to have more than one instance of the class. In this context I agree that your question doesn't make much sense.
Thanks for the answer. I tried cloning a singleton. It was exactly the same as you have told. Like the non singleton instance. | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/22951-how-clone-singleton-class-printingthethread.html | CC-MAIN-2017-47 | refinedweb | 405 | 82.54 |
Opened 13 years ago
Closed 13 years ago
Last modified 13 years ago
#428 closed bug (fixed)
Firefox crashing on load
Description
starting firefox from the script heralds
[Switching to team ./firefox-bin (132) thread firefox-bin (132)] 0x017e1f9f in nsFtpState::ConvertFilespecToVMS ()
from /boot/apps/firefox/./components/libnecko.so
(gdb) sc #0 0x017e1f9f in nsFtpState::ConvertFilespecToVMS ()
from /boot/apps/firefox/./components/libnecko.so
(gdb)
Change History (34)
comment:1 Changed 13 years ago by
comment:2 Changed 13 years ago by
comment:3 Changed 13 years ago by
comment:4 Changed 13 years ago by
All other libs are loaded with full path through 'load_add_on(const char *pathname)'
comment:5 Changed 13 years ago by
Now trying with the binary;
It enters the debugger again, [Switching to team /boot/apps/firefox/./firefox-bi (196) thread firefox-bin (196)] 0x00217eb3 in nsToolkitProfileService::CreateProfile ()
from /boot/apps/firefox/./lib/libxul.so
(gdb)
comment:6 Changed 13 years ago by
Ok, and specifically is great for browsing the code..
comment:7 Changed 13 years ago by
So, we have something in this function:
comment:8 Changed 13 years ago by
Oh, and the initial report is here:
comment:9 Changed 13 years ago by
For the first one we can activate logging, if it's a debug-build or logging was built in by running this in terminal we start firefox in: export NSPR_LOG_MODULES=nsFTP:5 (As defined here: )
comment:10 Changed 13 years ago by
What is the message: seg-fault?
comment:11 Changed 13 years ago by
For the most recent report: a seg-violation. No more output from
bt, sadly.
I can no longer get firefox to reproduce the nsFtpState::ConvertFilespecToVMS debug call. Thanks a lot for the pointers; if anything else crops up, i'll know where to look.
Could it be that Haiku is missing some dirs that Mozilla presumes exist?
comment:12 Changed 13 years ago by
I can't really see a reason why it crashes in those functions instead of objects those functions use, so not sure. Unless those objects themselves are invalid.
comment:13 Changed 13 years ago by
Hmm. It sounds like it would be good for someone else to try Firefox under Haiku
- I've encountered errors before due to low memory; I just hope this isn't related.
comment:14 Changed 13 years ago by
I've done a few tests with an old ff tree I have lying around.
Copying a working profile from your R5 disk should get around the CreateProfile crash.
Mine now crashes out in static_initialization_and_destruction_0 in libnecko. This is a function gcc creates to initialise the static members of the shared library when it is linked. My guess is it crashes due to some binary incompatibility between the R5 libs and the ones on Haiku (different size of a datatype perhaps?)
This is the simple HelloWorld Be sample app, I also linked it against libnecko: - it works fine on R5, crashes while loading on Haiku. (libnecko needs the other libs but Haiku can load it fine just linked to the others, so the problem is definately in libnecko itself)
My hunch is that it's to do with the net libs, although copying libnet.so from R5 to the hwdbg/lib/ directory gave errors about missing symbols and didn't even attempt to launch the program.
I'm a bit stuck now; some help from anyone who knows more about shared libraries and stuff would be great.
comment:15 Changed 13 years ago by
comment:16 Changed 13 years ago by
That's above my head unfortunatly.
comment:17 Changed 13 years ago by
It's above mine too. I've tried some more investigation:
The tools I was looking for were the binutils things - nm and readelf. I got readelf to list all the "local objects" in libnecko (they seem to be the static things) - there are lots (1000s I guess). I went through a few of them that sounded interesting (the vast majority were just the IIDs used to refer to objects or factories) using LXR but they were nothing particularly special - static char[]s mainly or some other static structs containing basic types - nothing that I thought should cause a problem.
There was one that initialised a log variable by calling a function deep in nspr and perhaps caused pr initialisation, but I added a printf to the PR_NewLogModule function and it seems that actually works OK, and the crash is somewhere else.
Axel, could this be a memory thing caused by having so many static objects (I don't know where in memory static objects are created) - or would that give a KDL or something different to a normal segfault?
Is there any way of finding out exactly which part of static_initialization_and_destruction_0 causes the segfault from gdb?
The reason using the R5 libs didn't work is that R5 libnet.so needs libbe.so from R5, which is missing the memset_internal symbol that I think the R5 kernel magically patches at run-time or something. Whatever, it didn't work...ooh maybe I could try using the Haiku libs in R5 and seeing if that crashes...I'll report back on that later.
comment:18 Changed 13 years ago by
Latest "progress":
The app does seem to get through the static initialiser phase running on R5 with Haiku libraries - it crashes in the BApplication constructor but that's not suprising with Haiku having a different protocol for app_server communication.
That points to some problem with the runtime_loader initialising static objects perhaps. There are some repeated objects in the same context in libnecko - perhaps they are declared static in a header file or something. I'm going to investigate that a bit now. Mac OS X seemed to have a problem with that from this thread I found:
comment:19 Changed 13 years ago by
I found one static variable initialised in a header:
I copied that into a header, made a .so with 2 different files that included it, and a simple app that linked to the so. That worked fine.
Now I really am pretty stumped, and need to work out how to get more info from gdb about where it crashes exactly. I'm not about to check all 4019 static objects in libnecko! Saying that, I may try checking the pointers as they are the most likely to be causing the crash in their constructors I reckon, assuming it's not just a memory/some other limit thing from there being so many symbols. Hopefully there won't be that many, I'll grep the list and see...
comment:20 Changed 13 years ago by
Yay, I've tracked down this crash. I expect they'll be more so I've opened a new one for that specific issue and made this one depend on it. It's #490.
For some reason, calling gettimeofday (a libroot function) from a shared library causes a segfault. It was happening during static initialisation as there is a static member variable to hold the current number of seconds here (PR_NOW is a macro that expands to a function calling gettimeofday on BeOS):
My mozilla source is a little old so current ff would probably crash in a different place. The bug still occurs whenever the gettimeofday function is called from a shared library though - there's a simple test app that demonstrates that attached to #490.
That same bug is probably responsible for the crash in CreateProfile too - that uses the PR_NOW function to generate the random name for the new profile directory.
comment:21 Changed 13 years ago by
comment:22 Changed 13 years ago by
I think I had a modified NSPR that uses inline PR_IMPLEMENT(PRTime) PR_Now(void) {
return (PRTime) real_time_clock_usecs();
} before.
comment:23 Changed 13 years ago by
Good one Fredrik, that's a good workaround until #490 is fixed. Gets a bit further now, crashing out in Date() in libmozjs.so - that actually calls another macro PRMJ_NOW which also calls our good old friend gettimeofday - I'll change that to use get_real_time_clock_usecs too later, but I'm off out now for a bit. - line 203 is the gettimeofday call.
comment:24 Changed 13 years ago by
comment:25 Changed 13 years ago by
comment:26 Changed 13 years ago by
comment:27 Changed 13 years ago by
You guys rock! What a capable QA team Haiku has!
comment:28 Changed 13 years ago by
Nice work Simon. Anyway gettimeofday is slower so it should be changed in NSPR anyway.
comment:29 Changed 13 years ago by
Yeh real_time_clock_usecs is definately the way to go.
I quite like the whole QA side of things - as Haiku gets closer to completion it's an area where I intend to spend a bit of time.
My other intended contribution is a port of WebCore (prefered to KHTML simply for real-world web compatibility, as web developers are more likely to test in Safari than Konq), but I'll see how that goes when I get exams out of the way.
First guess about the focus issues in ff is it's something in firefox code - the message passing in moz is pretty horrible I seem to remember to try and make the BeOS model fit the moz one, it may well use some "undocumented assumptions" about BMessages.
Most of the moz window is one BView (iframes are seperate ones too) apart from the little favicon. I've found clicking on or around there often corrects focus issues and means you can click links and stuff. Keyboard navigation seems to work fine all the time though.
Seems to me all the problems could be caused by messages not being forwarded to the correct places - it seems to happen with both mouse messages and invalidate ones, and probably others.
I'll look into it when I get back to uni with a decent net connection to update my ff source.
comment:30 Changed 13 years ago by
We don't do very much with BMessage's. The internal eventhandling is currently bad, but should be equally bad under BeOS as Haiku (port-based). Focus and mouse-handling as well as trying to minimize eventflow in the widget-code are much more probable to behave 'different' under Haiku I think. Also the widget-code tries to do a lot of optimization for just about everything to get a BeOS-feel.
I plan to change the internal event-code. My plan is actually to use the App and windows loopers instead of doing things on barebone ports. Although this is not 'easy' to do. First step seperating nsWindow into nsChildView, nsPopupWindow, nsWindow and nsWidget (baseclass) is well on it's way. After that we can set views and popups to process events on the nsWindow's looper.
comment:31 Changed 13 years ago by
When you're reading mouse messages and the like directly from the window's port, this is likely to fail under Haiku, as the app_server knows less about the window as it does under R5 - the window is going part of the work to get the message right.
comment:32 Changed 13 years ago by
Hmm, are you looking at the nsWindow-code, or did you misunderstood my cryptic comment :)
We receive the messages from BeOS the ordinary way. Most code are from historic first attempt at port, before first Mozilla, so it's not very modern though.
The two classes based on BWindow and BView, translates between BeOS and Mozilla's handling here: Notice the ugly recieving and sending it thru a port to the eventhandler's thread, which is what I'm trying to get rid of. It all boils down to that only the app and toplevel windows (windows, dialogs) are allowed to have it's own processing thread. Although we have only one for everything. Views and popups are not allowed to have their own threads.
On the BeOS-side: If I understand BeOS correctly views are using the window thread so only popups would need special handling in a BLooper based internal handling.
comment:33 Changed 13 years ago by
I like your idea about reworking the internal event handling Fredrik, that will probably help things under Haiku. It's true that the difference in behaviour is obviously caused by something in Haiku, I meant it might be that moz does something in a very non-BeOS way and so may well be the only app affected. Sorry I haven't kept up on events on bezilla, I lost interest in all things BeOS for a while.
For anyone who is looking at the moz source for the first time, it took me a while to realise that nsWindow in moz is sort of equivalent to a BView (I guess taken from MS Windows where a hwnd can is a "window handle" to pretty much any widget) - it's not necessarily a top-level BWindow. looks like messages are just dropped silently if the port is full...that'll be the first place I'll look. I guess the BeOS "workaround" is also not necessary for Haiku and might not help the situation. I should be able to do some investigation using my old source tree for a bit (tho I really should be revising!)
comment:34 Changed 13 years ago by
Well nsWindow are in current CVS a combined baseclass and class of toplevel windows. There is a patch to split that too in the works. nsPopupWindow are for popups and childviews (the real BView equivalents) are in nsChildView.
This is a work in progress, so a lot of code is still loitering in nsWindow.
Here is the latest code:
To run without the scripts:
(The stubs should probably be moved, but I think it might be unneccary for Haiku.
I suspect that the packaging script for Firefox does stripping, but havn't confirmed that, so there might be a problem. | https://dev.haiku-os.org/ticket/428 | CC-MAIN-2019-18 | refinedweb | 2,336 | 67.18 |
Bugtraq
mailing list archives
---------------[ MasterSecuritY <> ]---------------
-----------[ Local root exploit in LBNL traceroute - Part 2 ]-----------
----------[ By Michel "MaXX" Kaempf <maxx () mastersecurity fr> ]----------
--[ 0x00 - Table of contents ]------------------------------------------
0x01 - Brief summary
0x02 - Updating the exploit
0x03 - The exploit versus Non-executable user stack area
0x04 - The exploit versus PaX
0x05 - Credits
--[ 0x01 - Brief summary ]----------------------------------------------
The first part of this advisory, available at:
described a known vulnerability in traceroute and a portable way of
exploiting the problem. However, the first version of the exploit
contained minor imperfections, and could not work against systems
protected by the Linux kernel patches from the Openwall Project or the
PaX Team. These three issues are discussed in this second part of the
advisory.
--[ 0x02 - Updating the exploit ]---------------------------------------
The new version of the traceroute exploit is available at:
Two minor imperfections were fixed:
- The memory address of the function pointer overwritten by the exploit,
__free_hook, was part of the arch structure in the first version.
However, this address will not necessarily be the same on two different
computers running the very same operating system. This memory address
was removed from the arch structure, and is now provided by the user
thanks to the new victim command line argument.
- The first version of the exploit was unable to detect null bytes in
the structures it built. The new version of the exploit will return an
error if null bytes are found. A workaround exists: the structures can
be split into many pieces, allowing null bytes thanks to the string
terminators of the command line arguments passed to traceroute. However,
the case where null bytes were present, and where no other valid victim
could be chosen was never encountered, and that is why the workaround
was not implemented.
Moreover, "Red Hat Linux release 6.2 (traceroute 1.4a5) i386" support
was added. Thanks to fish stiqz, teleh0r and Ady Wicaksono.
--[ 0x03 - The exploit versus Non-executable user stack area ]----------
The first version of the exploit could not work against systems
protected by the Linux kernel patch from the Openwall Project (a.k.a.
Solar Designer non-executable stack patch), available at:
Thanks to Alex Khanin for notifying the problem. An exploit against i386
patched systems, which stores the shellcode in the heap instead of the
stack, was written and is available at:
Following the example of the regular version of the traceroute exploit,
the exploit against patched systems requires a few adjustments:
- filename: the full path where the suid traceroute binary can be found.
- p: the pointer returned to the savestr() function by the malloc(1024)
call. Check out the first part of the advisory for more information.
- victim: the memory address where the function pointer overwritten
by the exploit is stored. __free_hook is not a good choice on patched
systems, as its most significant byte is null. The dynamic relocation
record of the free() function is a better choice:
% objdump -R /usr/sbin/traceroute | grep free
0804c88c R_386_JUMP_SLOT free
- program: the program executed after successful exploitation of
traceroute. "/bin/sh" is a possibility, but "/tmp/sh" is another one:
% cat /tmp/sh.c
#include <unistd.h>
int main()
{
char * argv[] = { "/bin/sh", NULL };
setuid( 0 );
setgid( 0 );
execve( argv[0], argv, NULL );
return( -1 );
}
--[ 0x04 - The exploit versus PaX ]-------------------------------------
The exploit will lose the fight. The return-into-libc technique, or any
other technique virtually possible against PaX, will not work against
traceroute. The PaX patch is available at:
When the exploit overwrites the pointer stored at the memory address
foo with the pointer bar, it also overwrites the pointer stored at the
memory address bar with the pointer foo (not exactly, two offsets are
involved in this process, check out the first part of the advisory, or
the unlink() macro used by free(), for more information). This is why a
rwx memory page is needed, and (un)fortunately, PaX removes these pages.
--[ 0x05 - Credits ]----------------------------------------------------
Again, thanks to Pekka Savola, Chris Evans, Dvorak and Solar Designer.
Thanks to Alex Khanin, Eugene Tsyrklevich, fish stiqz, teleh0r, Ady
Wicaksono, Matthias Eckermann, Pierre Mondie, Samuel Hocevar and Olivier
Thereaux.
And thanks to the Securite.Org Team, for providing the best (french)
security web site in the world. Check out:
--
Michel "MaXX" Kaempf
By Date
By Thread | http://seclists.org/bugtraq/2000/Nov/181 | CC-MAIN-2014-41 | refinedweb | 702 | 59.03 |
7/21/16
- Mom sent me this article here.
- I applied to Rmotr. What’s the harm really. I don’t know anything about Object Oriented Programming so I just had to guess when that question came up.
7/22/16
- Wasn’t able to get anything in today - busy working at SDCC. 😢
7/23/16
- CS50 is having a coding contest next weekend I will try to take part in. You can have teams and setup meetups too.
CS50 and HackerRank present the first-ever...
CS50x CODING CONTEST 2016
an epic weekend of code
Friday, 29 July 2016 – Sunday, 31 July 2016
Open to CS50x students around the world (and friends). Solve as many problems (in C!) as you can!
- Practice problems here:
7/24/16
- Worked on the Temperature Conversion practice challenge for CS50. It’s a simpler version of the Daily Challenge I did a bit ago, but I can’t seem to get my code to pass two of their test cases and I don’t know why.
Write a program that, given a temperature in Celsius, C, as a floating-point value via standard input, prints via standard output that temperature in Fahrenheit, F, as a floating-point value, rounded to one decimal place.
Recall that:
F = C * 9/5 + 32
For example, if a user inputs:
0.0, your program should print 32.0
100.0, your program should print 212.0
42.0, your program should print 107.6
- Doesn’t help that I don’t know what those inputs are either.
- My solution so far that gets 1.33 out of 2 😖
7/25/16
- Was out working and then visiting sites in San Diego. Nothing done today.
7/26/16
- Flying all day back from working SDCC. Didn’t do anything on the plane except watch a movie and nap.
7/27/16
- Found a guy in Atlanta that was looking for a teammate for the CS50 challenge. Hopefully he responds favorably to my email.
- Asked for help on the CS50 practice problem, and the only reason my code failed two test cases was because I used float instead of double...weird.
- Solution here
#include <math.h> #include <stdio.h> #include "cs50.h" int main(void) { double num; while (scanf("%lf", &num) == 1) { if (num < DBL_MAX || num >= -DBL_MAX) { double answer = num * 1.8 + 32; printf("%.1f\n", answer); } else { printf("Enter a number between %f and %f degrees Celsius.", -DBL_MAX, DBL_MAX); return 1; } } return 0; }
7/28/16
- Finished the factorization practice problem.
- Write a program that takes an integer as input and outputs its factorial.
- Solution here
- It took me a long time (a bit over an hour), but I finished the practice problem to find a substring in a string! There is only a 60% success rate on that one.
- Write a program that takes two strings as input. If the second string is a substring of the first, output the index where the second string begins within the first string. Otherwise, output -1. Be sure to support wildcard characters, represented by an asterisk (*).
- Solution here
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "cs50.h" int main(void) { int num = GetInt(); int factorial = 1; for (int i = num; i > 0; i--) { factorial *= i; } printf("%i", factorial); return 0; }
- Solved decimal to binary converter practice problem (took maybe 10 minutes)
- Take in a decimal number via input and output the corresponding binary number, displaying only significant bits (i.e., don't show 01111 for 15, only 1111).
- Solution here
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "cs50.h" int main(void) { int i = 0; int remainder; int binary[50]; //this is an array placeholder for the binary digits. Once we put each one in there we will print it out again but backwards. int decimal = GetInt(); while (decimal != 0) { binary[i] = decimal % 2; decimal = decimal / 2; i++; } for (int j = i - 1; j >= 0; j--) printf("%d", binary[j]); } | https://www.craigrodrigues.com/blog/2016/07/28/learning-to-code-week-11 | CC-MAIN-2019-47 | refinedweb | 671 | 77.64 |
Domain Architect
InterSystems IRIS® data platform provides the Domain Architect as an interactive interface for creating and populating NLP domains and performing analysis on the indexed data. Domain Architect is accessed using the InterSystems IRIS Management Portal.
It consists of three tools:
Domain Architect: for creating an NLP domain and populating it with source text data.
Domain Explorer: for analyzing the data in an NLP domain by looking at specific entities.
Indexing Results: for displaying how NLP analyzed the text data in a source, using highlighting to show different types of entities.
All functionality provided through the Domain Architect is also available by using ObjectScript to invoke NLP class methods and properties.
Accessing namespaces, from which you can make your selection.
A namespace must be enabled for NLP before it can be used. Selecting an enabled namespace displays the NLP Domain Architect option.
If selecting an enabled namespace does not display the Domain Architect option, you do not have a valid license for NLP. Look at Licensed to in the Management Portal header. Review or activate your license key.
Enabling a Namespace
A namespace must be enabled for NLP before it can be used with Domain Architect.
If no namespaces are enabled, the Text Analytics option does not display any options.
If the current namespace is not enabled, the Analytics option displays a list of analytics-enabled namespaces. Select one of these displayed namespaces.
To enable a namespace for NLP from the Management Portal, select System Administration, Security, Applications, Web Applications. This displays a list of web applications; the third column indicates if a listed item is a namespace (“Yes”) or not. Select the desired namespace name from the list. This display the Edit Web Application page. In the Enable section of the page select the Analytics check box. Click the Save button.
You cannot enable the %SYS namespace. This is because you cannot create NLP domains in the %SYS namespace.
You can set your Management Portal default namespace. From the Management Portal select System Administration, Security, Users. Select the name of the desired user. This allows you to edit the user definition. From the General tab, select a Startup Namespace from the drop-down list. Click Save.
Creating a Domain
From the Domain Architect press the New button to define a domain. You specify the following domain values (in the specified order):
Domain name: The name you assign to a domain must be unique for the current namespace (not just unique within its package class). A domain name may be of any length and contain any typeable characters, including spaces (the % character is valid, but should be avoided). Domain names are not case-sensitive. However, because Domain Architect uses the domain name to generate a default domain definition class name, it is recommended that you follow class naming conventions when naming a domain, unless there are compelling reasons to do otherwise.
Definition class name: the domain definition package name and class name, separated by a period. If you first specified the domain name, clicking on the Definition class name generates default names for the domain definition package and class. The package name defaults to User. The class name defaults to the domain name, stripped of non-alphanumeric characters. You can accept or modify this default.
The package name and the class name can contain only alphanumeric characters, and are case-sensitive. Specifying a package name that differs from an existing package name only in lettercase results in an error. Within a package, specifying a class name that differs from an existing class name only in lettercase results in an error.
Allow Custom Updates: optionally select this box if you wish to enable adding data or dictionaries to this domain manually; the default is to not allow custom updates.
Click the Finish button to create the domain. This displays the Model Elements selection screen.
You must Save and Compile a newly created domain before exiting that domain.
If you attempt to create a duplicate domain name, the Domain Architect issues a “Domain name already in use” error.
For other ways to create a domain, refer to NLP Domains. Note that Domain Architect is the only domain creation interface that allows you to define a domain definition package name and class name.
Opening a Domain
Creating a domain using the Management Portal interface immediately opens the domain, allowing you to begin immediately to manage this new domain.
To manage an existing domain, click the Open button to list all existing domains in the namespace. This display lists the packages that contain domains. Select a package to display its domains. Select an existing domain. This displays the Model Elements selection screen.
Changing the Domain Name and Check Boxes
Creating or opening a domain displays the Model Elements window. If you click on the domain name in this window, the Details tab displays the Domain Name field, the Domain Tables Package field, and the Allow Custom Updates and Disabled check boxes. You can modify these characteristics of the domain. Changing the Domain Name does not change the Definition class name.
Checking the Allow Custom Updates check box allows the manual loading of data sources and dictionaries into this domain using interfaces other than Domain Architect.
Checking the Disabled check box prevents the loading of all data (source data, metadata, dictionary matching data) during the Build operation. Each of these types of data also has its own Disabled check box that allows you to disable loading of each types of data separately.
You must Save and Compile a renamed domain before exiting that domain.
Deleting a Domain
To delete the current domain, click the Delete button. This displays the Drop domain data window. you can either delete just the domain contents or delete the domain definition. Click Drop domain & definition class to delete the domain and its associated class definition, including the specifications of data sources, blacklists, and other model elements.
Model Elements
After creating a domain, or opening an existing domain, you can define model elements for the domain. To add or modify model elements, click on the expansion triangle next to one of the headings. Initially, no expansion occurs. Once you have defined some model elements, clicking the expansion triangle shows the model elements you have defined.
To add a model element, click the heading. Then click the Add button shown in the Details tab on the right side. Specify the name and values. The model element is automatically generated when you leave the Details area. Model elements are listed in the order of their creation, with the most-recently-created element at the top of the list; modifying a model element does not change its position in the list.
To modify a model element, expand the heading, then click a defined model element. The current values are shown in the Details tab on the right side. Modify the name and/or values as desired. The model element is automatically re-generated when you leave the Details area.
Once you have created model elements, clicking on the Expand All button (or one of the expansion triangles) displays these defined values. The Element Type column shows the type of each model element. Clicking on the red “X” deletes that model element.
The Save button saves all changes. The Domain Architect page heading is followed by an asterisk (*) if there are unsaved changes. Click Save to save your changes.
The Undo button reverses the most recent unsaved change. You can click Undo repeatedly to reverse unsaved changes in the reverse order that they were made. Once changes are saved, this button disappears.
The following Model Elements are provided:
Domain Settings
This model element allows you to modify the characteristics of the domain. All Domain Settings are optional and take default values. Domain Settings provides the following options:
Languages: select one or more languages that you wish NLP to identify in the text data. If you check more than one language, automatic language identification is activated. This increases the processing required for texts. Therefore, you should not select multiple languages unless there is a real likelihood that texts in the selected language will be part of the data set. The default language is English.
Add Parameter: this button allows you to specify a domain parameter value. You can only add a domain parameter to an empty domain; this means that you must add all desired domain parameters before you Build the domain with Data Locations specified. Otherwise, the Compile to add, modify, or delete domain parameters fails with an error message; you can use the Delete button to drop domain contents to allow you to add, modify, or delete domain parameters.
To add a parameter, specify the domain parameter name and the new value. Domain parameter names are case-sensitive. You can use either name form. For example, Name=SortField, Value=1 or Name=$$$IKPSORTFIELD, Value=1. No validation is performed. All unspecified domain parameters take their default values. To view the parameters that you have added, expand the Domain Settings heading.
Maximum Concept Length: the largest number of words that should be indexed as a concept. This option is provided to prevent a long sequence of words from being indexed as a concept. The default (0) uses the language-specific default for the maximum number of words. This default should be used unless there are compelling reasons to modify it.
Manage User Dictionary: this button displays a “Manage User Dictionary” box that allows you to specify one or more strings to the user dictionary. Each specified string either specifies a string that will rewrite to a new string, or specifies a string to which you assign an attribute label from a drop-down list.
Metadata Fields
Add Metadata: this button allows you to specify a source metadata field. For each metadata field you specify the field name, the data type (String, Number, or Date), the supported operators, and the storage type. After creating a domain, you can optionally specify one or more metadata fields that you can use as criteria for filtering sources. A metadata field is data associated with an NLP data source that is not itself NLP indexed data. For example, the date and time that a text source was loaded is a metadata field for that source. Metadata fields must be defined before loading text data sources into a domain.
Case Sensitive check box: By default, a metadata field is not case-sensitive; you can select this check box to make it case-sensitive.
Disabled check box: You can select the Disabled check box to disable all metadata fields, or you can select the Disabled check box displayed with an individual metadata field to disable just that metadata field. A disabled field is not loaded during the Build operation.
The metadata fields that you specify here appear in the Data Locations Add data from table and Add data from query details under the title “Metadata mappings”.
Data Locations
Specifies the source for adding data. Option are Add data from table, Add data from query, Add data from files, Add RSS data, and Add data from global.
The Drop existing data before build check box allows you to specify whether source text data already indexed in this NLP domain should be deleted before adding the source text data specified here. To use this check box to drop data, data loading must not be disabled. To drop existing data without loading new data, use the Delete button Drop domain contents only option.
The Disabled check box allows you to disable source indexing; disabled source data is not loaded during the Build operation. If data loading is disabled, the Drop existing data before build check box is ignored.
A Build operation for a large number of texts may take some time. If you have already loaded the data locations and wish to add or modify metadata or a matching dictionary you can click the Data Locations Disabled check box to index these model elements without reloading the data locations.
After specifying data locations, you must Save and Compile the domain, then select the Build button to build the data indices.
Add Data from Table
This option allows you to specify data stored in an existing SQL table in the current namespace. It provides the following fields:
Name: you can either specify a name or take the default name for the extracted result set table. Follows SQL table naming conventions. The default name is Table_1 (with the integer incrementing for each additional extracted result set table you define).
Batch Mode: a check box indicating whether or not to load source text data in batch mode.
Schema: from this drop-down list select an existing schema in the current namespace.
Table Name: from this drop-down list select an existing table in the selected schema.
ID Field: from this drop-down list select a field from the selected table to serve as the ID field (primary record identifier). An ID field must contain unique, non-null values..
Group Field: an SQL select-item expression that retrieves a secondary record identifier from the selected table. This field defaults to the initial ID Field selection..
Data Field: from this drop-down list select a field from the selected table to serve as the data field. The data field contains the text data loaded for NLP indexing. You can specify a field of data type %String or %Stream.GlobalCharacter (character stream data)..
Where Clause: you can optionally specify an SQL WHERE clause to limit which records are included in the result set table. Do not include the WHERE keyword.
If you have defined one or more Metadata Fields for this domain, the Metadata mapping option allows you to specify a metadata field for this table. From the drop-down list you can select a field from the selected table, select – not mapped –, or select – custom –. If you select – custom – the Architect displays an empty field in which you can specify the custom mapping.
If you have not defined any Metadata Fields for this domain, the Metadata mapping option provides a Declare Metadata button that directs you to the Add Metadata domain option.
Add Data from Query
Add data from query is similar to Add data from table, but allows you to specify a fully-formed SQL query for an existing table (or tables), from which you provides the following fields:
Name: you can either specify a name or take the default name for the extracted result set table. Follows SQL table naming conventions. The default name is Query_1 (with the integer incrementing for each additional extracted result set table you define).
Batch Mode: a check box indicating whether or not to load source text data in batch mode.
SQL: the query text, an InterSystems SQL SELECT statement. Defining a query allows you to select fields from more than one table by using JOIN syntax. When specifying more than one table, assign column aliases to selected fields. Defining a query also allows you to specify an expression field that you can use as the Group field.
The following field selection drop-down lists display the selected fields. They do not display table alias prefixes. If the field has a column alias, this alias is listed rather than the field name.
ID Field: from this drop-down list select a field from the selected table to serve as the ID field. An ID field must contain unique, non-null values.
Group Field: from this drop-down list select a select-item expression (such as an SQL function expression) from the query to serve as a secondary record identifier (group field). For example, YEAR(EventDate).
Data Field: from this drop-down list select a field from the selected table to serve as the data field. The data field contains the text data loaded for NLP indexing.
If you have defined one or more Metadata Fields for this domain, the Metadata mapping option allows you to select either – not mapped – or – custom – for each defined metadata field. The default is – not mapped –. If you select – custom – the Architect displays an empty field in which you can specify the custom mapping.
If you have not defined any Metadata Fields for this domain, the Metadata mapping option provides a Declare Metadata button that directs you to the Add Metadata domain option.
The Model Elements window Element Type column displays a truncated form of the query you defined; the query is truncated after the first table name in the FROM clause. The full query is shown in the Details window.
Add Data from File
This option allows you to specify data stored in files. It provides the following fields:
Name: you can either specify a name or take the default name for the extracted data file. The default name is File_1 (with the integer incrementing for each additional extracted data files you define).
Path: the complete directory path to the directory containing the desired files. The Path syntax is filesystem dependent; on a Windows system it might look like the following: C:\\temp\NLPSources\
Extensions: the file extension, such as txt or xml. Do not include the dot prefix when specifying the file extension. Specify multiple extensions as a comma-separated list with no dots and no spaces; for example, txt,xml. If specified, only files with the specified extensions are included in the resulting extracted data. If the Extensions field is left blank (the default) all files are included, regardless of their extensions.
Filter Condition: a condition used to restrict which files are to included in the resulting extracted data.
Recursive: a check box indicating whether to select files recursively. When checked, data can be extracted from the files in the specified directory and files in all of its subdirectories, and their sub-subdirectories, etc. When not checked, data can be extracted only from files in the specified directory. The default is non-recursive (check box not checked).
Batch Mode: a check box indicating whether or not to load source text data in batch mode.
Encoding: a drop-down list of the types of character set encoding to use to process the files.
Add RSS Data
This option allows you to specify data from an RSS stream feed. It provides the following fields:
Name: you can either specify a name or take the default name for the extracted data. The default name is RSS_1 (with the integer incrementing for each additional RSS source you define).
Batch Mode: a check box indicating whether or not to load source text data in batch mode.
Server Name: the name of the host server on which the URL is found.
URL: the navigation path within the server address to the actual RSS feed.
Text Elements: a comma-separated list of text elements to load from the RSS feed. For example title,description. Leave blank for defaults.
Add Data from Global
This option allows you to specify data from an InterSystems IRIS global. It provides the following fields:
Name: you can either specify a name or take the default name for the extracted data. The default name is Global_1 (with the integer incrementing for each additional global source you define).
Batch Mode: a check box indicating whether or not to load source text data in batch mode.
Global Reference: The global from which you wish to extract the source data.
Begin Subscript: the first global subscript in a range of subscripts to include.
End Subscript: the last global subscript in a range of subscripts to include.
Filter Condition: a condition used to restrict which files are to included in the resulting extracted data.
Blacklists
Define blacklists: After creating a domain, you can optionally create one or more blacklists for that domain. A blacklist is a list of terms (words or phrases) that you do not want a query to return. Thus a blacklist allows you to perform NLP operations that ignore specific terms in data sources loaded in the domain.
Name: specify the name of a new blacklist, or take the default name. Blacklist names are not case-sensitive. Specifying a duplicate blacklist name results in a compile error. The default name is Blacklist_1 (with the integer incrementing for each additional blacklist you define).
Entries: specify terms to include in the blacklist, one term per line. Terms should be in lower case. Duplicate terms are permitted. You can copy/paste terms from one blacklist to another. You can include blank lines to separate groups of terms. A line return at the end of your list of terms is optional; blank lines are not counted as entries.
If you add, modify, or delete a blacklist, you must Save and Compile the domain for this change to take effect.
Because defining blacklists has no effect on how data is loaded into a domain, changes to blacklists do not require re-building the domain.
Blacklists are compiled, then supplied to the Domain Explorer, which allows you to specify none, one, or multiple blacklists when performing analysis of source text data loaded into the domain. A blacklist is applied to some (but not all) Domain Explorer analytics.
Matching
The Matching option provides the Add Dictionary option to define a dictionary and specify its items and terms.
The Matching option provides four check box options, as follows:
Disabled: You can select the Disabled check box to disable building of all dictionaries, or you can select the Disabled check box displayed with an individual dictionary to disable the building of that dictionary. Selecting Disabled check boxes allows you to build only those dictionaries that you have changed. The default is off.
DropBeforeBuild: default on
AutoExecute: default on
IgnoreDictionaryErrors: default on
Add Dictionary
The Add Dictionary button displays the dictionary definition options: dictionary name (with a supplied default), an optional description, the dictionary language selected from a drop-down list of NLP supported languages, and the disabled check box. The default name is Dictionary_1 (with the integer incrementing for each additional dictionary you define).
The Add Item button displays the item definition options: item name (with a supplied default), a uri name (with a supplied default), the item language selected from a drop-down list of NLP supported languages, and the disabled check box. To define more items, select the dictionary name. Items are listed in order of creation, with the most recent at the top of the list. Within each item you can define one or more terms. The default name is Item_1, the default uri name is uri:1 (with the integer incrementing for each additional item you define for this dictionary).
The Add Term button displays the term definition options: a string specifying the term, the term language selected from a drop-down list of NLP supported languages, and the disabled check box. To define more terms, select the item name. Terms are listed in order of creation, with the most recent at the top of the list.
Save, Compile, and Build
You must save, compile, and build a domain (in that order) using the buttons provided. You must save and compile a domain after adding, modifying, or deleting any Model Elements.
The Save button saves the current domain definition. Architect greys out (disables) the Save button if no domain definition is open. Architect does not issue an error if you save a domain definition without changing it.
The Compile button compiles the current domain definition. It compiles all of the classes and routines that comprise the domain definition. If you have not saved changes that you made to the domain definition, the compile operation prompts you to save the domain definition before compiling.
The Build button loads the specified sources into the current domain. If you have made changes to the Data Locations, Metadata Fields, or Matching dictionaries, you must build the domain. The Build Domain window displays progress messages such as the following:
13:50:48: Loading data... 13:51:49: Finished loading 3 sources 13:51:49: Creating dictionaries and profiles... 13:51:49: Finished creating 1 dictionaries, 1 items, 3 terms and 0 formats 13:51:49: Matching sources... 13:51:50: Finished matching sources 13:51:50: Successfully built domain 'mydomain'
The build operation can be time-consuming. If a Disabled check box is checked for a model element, the Build operation does not load the corresponding sources. Selecting Disabled check boxes allows you to build only those model elements that you have changed.
Domain Explorer
There are two ways to access the Domain Explorer:
From the Management Portal Analytics option select the Text Analytics option. This displays the Domain Explorer option. When you select this option it prompts you to select an existing domain from a drop-down list.
From the Management Portal Analytics option select the Text Analytics option. Access the Domain Architect and create or access a domain. Once you have specified Data Locations and populated the domain with this data using the Build button, you can select Domain Explorer from the Tools tab. This displays the Domain Explorer as a separate browser tab with the current domain selected.
The Domain Explorer is a display interface with broad application. It shows a wealth of information about the source text data indexed in a domain. It initially displays a list of either the top (most-frequently-occurring) concepts, or the dominant (highest dominance) concepts. You can toggle between these two lists.
If you select an entity, the Domain Explorer provides analysis of similar entities and related concepts, and analysis of the appearance of the specified entity in larger text units (sources, paths, and CRCs). This provides a contextual at-a-glance view of what's in your data.
The Domain Explorer provides generic filters that support selecting subsets of the sources in a domain based on metadata criteria. This interface provides a sample of how NLP Smart Indexing can be used to quickly overview and navigate a large set of documents.
Domain Explorer Settings
By default, the Domain Explorer displays analysis of the domain that was current in Domain Architect or the domain you selected when you invoked the Domain Explorer.
To select another domain:
Select the Gear icon at the upper right of the Domain Explorer. This displays the Settings box.
The Settings box contains the Switch domain drop-down list. Select a domain from this list. By default, this list include the domains defined in the current namespace. If you select the Include other namespaces check box, the drop-down list includes domains defined in all namespaces.
To apply blacklists:
Select the Sunglasses icon at the upper right of the Domain Explorer. If the domain has no defined blacklists, this icon does not appear.
The Blacklists box contains check boxes for each defined blacklist. Select one or more, then click the Apply button.
Select the Gear icon at the upper right of the Domain Explorer. This displays the Settings box.
If the domain is configured for stemming, the Settings box also contains the Use stems instead of entities and Show representation form for stems check boxes. If Use stems instead of entities is checked, the Domain Explorer performs stemming analysis and changes the Domain Explorer headings as follows: Top Concepts/Dominant Concepts becomes Top Stems/Dominant Stems, Similar Entities becomes Similar Stems, Related Concepts disappears, leaving Proximity Profile, and the CRCs tab disappears. If Show representation form for stems is checked, each stem is displayed as a representative word; if not checked, the stem itself is displayed. Both boxes are checked by default.
The number at the top right of the Domain Explorer is the number of sources loaded in the selected domain that are available for data analysis. This number can be limited by applying filters.
Listing All Concepts
The Domain Explorer initially provides concept analysis of the data sources loaded in the domain. There are two ways to list concepts, by frequency or by dominance. You can toggle between these two by selecting the frequency or dominance button:
Top Concepts: selecting the frequency button lists all concepts in the sources in descending order of frequency. If multiple concepts have the same frequency, the concepts are listed in descending collation order. Each concept is listed with its frequency (total number of occurrences in all sources) and spread (number of sources containing that concept). To view frequency counts for a single source, use the Indexing Results tool.
Dominant Concepts: selecting the dominance button lists all concepts in the sources in descending order of dominance score. If multiple concepts have the same dominance score, the concepts are listed in descending collation order. The dominance score is calculated by taking the dominance values for each source and using an averaging algorithm to determine the dominance of a concept across all loaded sources. Dominance values in a single source are integer values, with the most dominant concept given a dominance of 1000. To view dominance values for a single source, use the Indexing Results tool.
Analyzing a Specified Entity
There are two ways to display analysis of a specific entity:
Select a concept from either the Top Concepts or Dominant Concepts listings.
In the entry field in the top left corner you can type the first few characters (minimum of 2, not case-sensitive) of a word found in an entity, and the Domain Explorer displays a drop-down list of all of the existing entities that contain a word beginning with those characters. Select an entity from this drop-down list, then press the Explore! button. You can use this option to display Relations or Concepts; both types of Entities are shown in the drop-down list.
Selecting an entity displays two kinds of analysis of that entity: associated entities and specified entity in context.
Associated Entities
Selecting an entity displays the following listings:
Similar Entities: a list of concepts and relations that are similar to the specified entity, with the frequency (total number of occurrences in all sources) and spread (number of sources containing that concept) of each concept or relation. The first similar entity listed is always the specified entity itself. For a concept, this first listed entity is the same as the Top Concepts listing for that concept.
Related Concepts: selecting the related button displays a list of concepts that are related to the specified concept, with the frequency (total number of occurrences in all sources) and spread (number of sources containing that concept) each concept. A related concept is a concept that appears in a CRC with the specified concept.
Proximity Profile: selecting the proximity button displays the Proximity Profile table. This lists concepts associated by proximity to the specified concept, with a proximity score for each concept.
Selecting an entity from the Similar Entities, Related Concepts, or Proximity Profile listings changes all listings to analysis of that entity. It does not change the Top Concepts and Dominant Concepts listings.
Entity in Context
Selecting an entity also displays the following listings of that entity in context:
Sources: a list of source texts containing the specified entity (shown highlighted in green), along with the internal source ID (an integer) and external source ID. Sources are listed in descending order by internal source ID. The source text displays all sentences in the source that contain the entity; intervening sentences that do not contain the entity are not displayed, but are indicated by ellipsis (...); note that leading ellipsis is not shown when the first displayed sentence is not the first sentence in the source, and trailing ellipsis is always shown after the final sentence, even when the last displayed sentence is actually the last sentence in the source.
Red text indicates negation, with the entities within the scope of the negation attribute in red letters. Negation scope is not necessarily the same as the corresponding path, sentence, or CRC.
Selecting the Eye icon or clicking anywhere in the listing for a source displays the full text of the source. Each occurrence of the specified entity is highlighted and each negation scope text is shown in red letters in the full text. (The % option must be set to 100% to display all occurrence of the specified entity in this full text box.)
Selecting the Arrow icon displays the Indexing Results tool.
Paths: a list of paths containing the specified entity. Paths are listed in descending order by ID. Note that because path IDs are assigned on a per-source basis, the same path text may be listed multiple times with different path IDs.
The entities and attributes of the path are color coded and highlighted as described in the Indexing Results tool description of Indexed Sentences, with the addition of the Explore! entity appearing in yellow-orange.
Selecting a path element changes all listings to analysis of that entity. It does not change the Top Concepts and Dominant Concepts listings.
Selecting the Eye icon displays the full text of the source with the specified entity highlighted in green.
Selecting the Arrow icon displays the Indexing Results tool.
CRCs: a list of Concept-Relation-Concept (CRC) sequences that contain the specified entity, with the frequency (total number of occurrences of that CRC in all sources) and spread (number of sources containing that CRC). Note that many CRCs contain only one concept: CR or RC. The entity type highlighting is the same as for Paths, except that Path-relevant Words are not part of CRCs and are therefore not displayed. Attributes are not highlighted in the CRCs listing.
Selecting a CRC element changes all listings to analysis of that entity. It does not change the Top Concepts and Dominant Concepts listings.
Selecting the Eye icon displays the Sources with selected CRCs box, listing each source that contains an instance of the CRC. The CRC is highlighted in green in the context of its sentence, and flagged with the Source ID of the source. A source ID listing can contain multiple sentences containing the specified CRC; intervening sentences that do not contain the CRC are indicated by ellipsis. From the Sources with selected CRCs box you can select the Eye icon for a source containing the CRC to display the full text of the source with the specified entity (not the CRC) highlighted in green.
If Japanese is the only language supported for the domain, the Domain Explorer display differs as follows: the Related Concepts and CRCs listings are not shown. An Entity Vectors listing is substituted for the Paths listing.
Full Text Box
The Eye icon displays the full text of a selected source. This text box is identified by the external ID of the source. For example, :SQL:1171:1171.
The source text is tagged as follows:
The specified entity is highlighted in green.
Red text indicates negation, with the entities within the scope of the negation attribute in red letters.
This full text box provides the following option buttons:
metadata: displays the metadata for the source. All sources are provided with a DateIndexed metadata field. This date stamp is represented as a UTC date and time in the Display format for your locale. It is truncated to whole seconds. To return to the source text, press the metadata button again.
highlight: performs no action.
indexing: displays the source text highlighted to indicate the types of entities, as follows:
Green: the specified entity (either a Concept or a Relation).
Blue: a Concept.
White: a Relation.
Light Blue: a Path-relevant Word.
Unmarked: a Non-relevant word.
Negation scope text is displayed in red letters.
dictionaries: performs no action.
%: summarizes the source text. The default percentage is 100% (full text). Specifying a integer less than 100 and then pressing the % button summarizes the source text by reducing the text to (roughly) the specified size by eliminating sentences that are have a low relevancy score, when compared to the other sentences in the source. Summerization does not necessarily retain sentences that contain the specified entity.
Limiting the Sources to Analyze
You can limit the scope of your data analysis by using filters. A filter includes or excludes data sources that are loaded in the domain from analysis. By default, the Domain Explorer analyzes all data sources loaded in the domain.
The Filter icon (funnel) button at the top right of the Domain Explorer applies a filter, which includes or excludes sources from analysis based on the criteria you specify. You can specify several types of filters, and can apply more than one filter. Multiple filters can be associated with AND, OR, NOT AND, or NOT OR logic.
To add a filter, select the filter type from the drop-down list, specify the filter criteria, then select the add button, then the Apply button. When adding multiple filters, you select the AND/OR logic option associating the filters after the add button and before the Apply button.
When one or more filters are in effect, the Filter icon displays in green.
The number to the left of the Filter icon indicates the number of sources included after applying the filters. If no filters are applied, this number is the total number of sources in the domain.
To remove a single filter, select the Filter icon, then select the black X next to the filter description, then select the Apply button. To remove all filters, select the Filter icon, then the Clear button, then the Apply button.
The following filter types are supported:
Metadata: used to exclude sources by their metadata values. By default, all sources have DateIndexed metadata. To apply DateIndexed metadata, select this field, select an operator, and select a date value by clicking on the calendar icon, then selecting the desired day.
Source IDs: used to select sources for inclusion by source ID. You can specify a single source ID or a comma-separated list of source IDs.
Source ID Range: used to select sources for inclusion by source ID. You can range of source IDs by specifying the from and to range values. The range is inclusive of these values.
External IDs: used to select sources for inclusion by their external IDs. For example, :SQL:1171:1171. You can specify a single ID or a comma-separated list of IDs. External source IDs are listed in the Sources listing.
SQL: used to select sources for inclusion by specifying an SQL query.
Indexing Results
The Indexing Results tool enables you to view the NLP indexing of the contents of a individual data source. This displays three listings: Indexed sentences, Concepts, and CRCs. The Indexed sentences display includes both color-coded text that shows entity types (Concept, Relations, Non-relevants, Path-relevants) and color-coded highlighting that shows attributes and their scope.
You can access the Indexing Results tool from the InterSystems IRIS Management Portal by selecting Analytics, then Text Analytics. The Analytics options are not displayed unless you are in a namespace that has been enabled for Analytics. Select the desired namespace. This displays the Analytics tools. You can access the Indexing Results tool in either of two ways:
By selecting the Text Analytics and then the Indexing Results option.
By selecting the Text Analytics and then the Domain Architect option. In the Domain Architect you open an existing domain or define a new domain. Once you are in a compiled domain, you can use the Tools tab Indexing Results button to display how NLP has indexed the data. This displays the Indexing Results tool as a separate browser tab.
The Indexing Results tool enables you to display indexed results of either data in a specified domain or manual input data.
To display Indexing Results options displayed at the top right you may have to scroll horizontally.
Domain Data
At the top right of the Indexing Results window is a drop-down list of defined domains. It defaults to the first defined domain. Select the desired domain.
Click the wide blank box across the top of the window to display a drop-down single-line listing of the contents of each indexed data source. Select one of these sources to display the indexing results for that source.
You can use the >> button to collapse (make disappear) the wide single-line source box. This enables you to view the indexing results without horizontal scrolling. You can use the << button to expand (make reappear) the wide single-line source box as a blank box that you can click to select another data source.
Manual input Data
At the top right of the Indexing Results window select the manual input button to input text directly for NLP indexing results analysis. This opens the Real-time input box. Type or paste your input text in the blank box. Use the Configuration drop-down box to select an existing (or default) configuration, or select language —> and then use the second drop-down list to select a national language or Auto-detect.
Indexed Sentences
The sentences in the source are listed in order, one sentence per line. Entity types (Concept, Relations, Non-relevants, Path-relevants) and attributes are indicated by color-coding and highlighting.
At the top right of the Indexing Results window you can select the highlighting type: either light or full: light uses color-coding and underlining to indicate entity types and attributes; it is intended to be unobtrusive to allow for convenient reading of sentences; full displays boxes around each entity and uses thick lines for attributes to provide a clearer representation of the NLP indexed structures. The information content of both type of highlighting is the same. The default is full.
The sentence text is highlighted for entities as follows:
concept: blue, boxed
relation: light green, boxed
non-relevant: grey, not boxed
path-relevant: black, grey box
The sentence text is highlighted for attributes as follows:
A Negation attribute phrase has red text (with concepts in bold letters and relations in regular letters); the concepts and relations are further clarified in full highlighting, where the enclosing boxes are the entity type color: blue for concepts, light green for relations. The negation keywords are underlined in red; multi-word negation terms (such as “was not”) are shown with each word underlined in red.
A Time, Duration, or Frequency attribute phrase is underlined with an orange dotted line. Time attribute keywords are underlined in orange. Duration attribute keywords are underlined in bright green. Frequency attribute keywords are underlined in yellow.
A Measurement attribute is underlined with a magenta dotted line. The measurement keywords are underlined in magenta.
A Negative Sentiment attribute is underlined with a purple dotted line. The sentiment keywords are underlined in purple.
A Positive Sentiment attribute is underlined with a green dotted line. The sentiment keywords are underlined in green.
These combinations make it possible to highlight combinations of entities and attributes. For example, a Measurement attribute that is part of a Negation attribute phrase.
Concepts and CRCs
The Indexing Results displays two listings, one of all concepts in the source, one of all of the CRCs in the source
Concepts in the source in descending order.
CRCs in the source highlighted (as above) to indicate concepts and relations, in descending order. Note that the CRCs listings do not include non-relevant or path-relevant words and do not indicate attributes.
At the top right of the Indexing Results window the sort by buttons allow you to toggle the Concepts and CRCs listings to display either frequency counts or dominance values in descending order.
In the Concepts listing, the most dominant concept(s) are given a dominance of 1000. Less dominant concepts are given smaller integer values, with larger sources tending to have lower least-dominant values. For example, a source containing 25 concepts might have a dominance range between 1000 and 83; a source containing 300 concepts might have a dominance range between 1000 and 2.
In the CRCs listing, the dominance score is arrived at my adding the dominance values of the concepts and relations.
If Japanese is the only language supported for the domain, the Indexing Results display substitutes a single Entities listing for the Concepts and CRCs listings. | https://docs.intersystems.com/irisforhealthlatest/csp/docbook/DocBook.UI.Page.cls?KEY=GIKNOW_ARCHITECT | CC-MAIN-2021-10 | refinedweb | 7,342 | 55.13 |
BIND 9 Administrator Reference Manual 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 Internet Systems Consortium, Inc. ("ISC") Introduction. Organization of This Document contains more advanced concepts that the system administrator may need for implementing certain options. Chapter 5 describes the BIND 9 lightweight resolver. The contents of Chapter 6 are organized as in a reference manual to aid in the ongoing maintenance of the software. Chapter 7 addresses security considerations, and Chapter new term or concept Fixed width literal user input Fixed Width (Berkeley Internet Name Domain) . For more detailed information about the design of the DNS and the DNS protocol, please refer to the standards documents listed in .. Periodically, the slave server must send a refresh query to determine whether the zone contents have been updated. This is done by sending a query for the zone's SOA record and checking whether the SERIAL field has been updated; if so, a new transfer request is initiated. The timing of these refresh queries is controlled by the SOA REFRESH and RETRY fields, but can be overrridden with the max-refresh-time, min-refresh-time, max-retry-time, and min-retry-time options. If the zone data cannot be updated within the time specified by the SOA EXPIRE option (up to a hard-coded maximum of 24 weeks) then the slave zone expires and will no longer respond to queries.. BIND Resource Requirements Hardware requirements DNS hardware requirements have traditionally been quite modest. For many installations, servers that have been pensioned off from active duty have performed admirably as DNS servers. The DNSSEC features of BIND 9 may prove to be quite CPU intensive however, so organizations that make heavy use of these features may wish to consider larger systems for these applications. BIND 9 is fully multithreaded, allowing full utilization of multiprocessor systems for installations that need it. CPU Requirements CPU requirements for BIND 9 range from i486-class machines for serving of static zones without caching, to enterprise-class machines if you intend to process many dynamic updates and DNSSEC signed zones, serving many thousands of queries per second. Memory Requirements The memory of the server has to be large enough to fit the cache and zones loaded off disk. The max-cache-size option can be used to limit the amount of memory used by the cache, at the expense of reducing cache hit rates and causing more DNS traffic. Additionally, if additional section caching () is enabled, the max-acache-size option can be used to limit the amount of memory used by the mechanism.. Name Server Intensive Environment Issues For name server intensive environments, there are two alternative configurations that may be used. The first is. Supported Operating Systems ISC BIND 9 compiles and runs on a large number of Unix-like operating systems and on Microsoft Windows Server 2003 and 2008, and Windows XP and Vista. For an up-to-date list of supported systems, see the README file in the top level directory of the BIND 9 source distribution. Name Server Configuration In this chapter we provide some suggested configurations along with guidelines for their use. We suggest reasonable values for certain option settings. Sample Configurations A Caching-only Name Server; }; An Authoritative-only Name Server This sample configuration is for an authoritative-only server that is the master server for "example.com" and a slave for the subdomain "eng.example.com". options { // Working directory directory "/etc/namedb"; // Do not allow access to cache allow-query-cache { none; }; // This is the default allow-query { any; }; // Do not provide recursive service recursion no; }; //; }; }; Load Balancing: Name TTL CLASS TYPE Resource Record (RR) Data www 600 IN A 10.0.0.1 600 IN A 10.0.0.2 600 IN A 10.0.0. For more detail on ordering responses, check the rrset-order sub-statement in the options statement, see .. Since BIND 9.2, rndc supports all the commands of the BIND 8 ndc utility except ndc start and ndc restart, which were also not supported in ndc's channel mode. If you run rndc without any options it will display a usage message as follows: rndc -c config -s server -p port -y key command command See for details of the available rndc commands. rndc requires a configuration file, strings "hmac-md5", "hmac-sha1", "hmac-sha224", "hmac-sha256", "hmac-sha384" and "hmac-sha512" have any meaning. The secret is a Base64. Advanced DNS Features Notify DNS NOTIFY is a mechanism that allows master servers to notify their slave servers of changes to a zone's data. In response to a NOTIFY from a master server, the slave will check to see that its version of the zone is the current version and, if not, initiate a zone transfer. For more information about DNS NOTIFY, see the description of the notify option in and the description of the zone option also-notify in . The NOTIFY protocol is specified in RFC 1996. As a slave zone can also be a master to other slaves, named, by default, sends NOTIFY messages for every zone it loads. Specifying notify master-only; will cause named to only send NOTIFY for master zones that it loads. Dynamic Update Dynamic Update is a method for adding, replacing or deleting records in a master will be permitted for the key local-ddns, which will be generated by named at startup. See for more details. Dynamic updates using Kerberos signed requests can be made using the TKEY/GSS protocol by setting either the tkey-gssapi-keytab option, or alternatively by setting both the tkey-gssapi-credential and tkey-domain options. Once enabled, Kerberos signed requests will. The journal file will also occasionally write ("dump") will be created with the extensions .jnw and .jbk; under ordinary circumstances, these will be removed when the dump is complete, and can be safely ignored. When a server is restarted after a shutdown or crash, it will replay the journal file to incorporate into the zone any updates that took place after the last zone dump. Changes that result from incoming incremental zone transfers are also journalled. If you have to make changes to a dynamic zone manually, the following procedure will work: Disable dynamic updates to the zone using rndc freeze zone. This will update the zone's master file with the changes stored in its .jnl file. Edit the zone file. Run rndc thaw zone to reload the changed zone and re-enable dynamic updates. rndc sync zone will update the zone file with changes from the journal file without stopping dynamic updates; this may be useful for viewing the current zone state. To remove the .jnl file after updating the zone file, use rndc sync -clean. Incremental Zone Transfers (IXFR) The incremental zone transfer (IXFR) protocol is a way for slave servers to transfer only changed data, instead of having to transfer the entire zone. The IXFR protocol is specified in RFC 1995. See . When acting as a master, BIND 9 supports IXFR for those zones where the necessary change history information is available. These include master zones maintained by dynamic update and slave zones whose data was obtained by IXFR. For manually maintained master zones, and for slave zones obtained by performing a full zone transfer (AXFR), IXFR is supported only if the option ixfr-from-differences is set to yes. When acting as a slave, BIND 9 will attempt to use IXFR unless it is explicitly disabled. For more information about disabling IXFR, see the description of the request-ixfr clause of the server statement. Split DNS Setting up different views, or visibility, of a in to the internal network. Example split DNS setup. In order to accomplish this, the company will set up two sets of name servers. will need to know how to deliver mail to internal hosts. In order for this to work properly, the resolvers on the bastion hosts will need to be configured to point to the internal name servers name servers both . master zone zone "site1.example.com" { type master; file "m/site1.example.com"; // do normal iterative resolution (do not forward) forwarders { }; allow-query { internals; externals; }; allow-transfer { internals; }; }; // sample slave config: slave TSIG master to a slave server. This is a guide to setting up TSIG in BIND. It describes the configuration syntax and the process of creating TSIG keys. named supports TSIG for server-to-server communication, and some of the tools included with BIND support it for sending messages to named: supports TSIG via the -k, -l and -y command line options, or via the key command when running interactively. supports TSIG via the -k and -y command line options. Generating a Shared Key TSIG keys can be generated using the tsig-keygen command; the output of the command is a key directive suitable for inclusion in named.conf. The key name, algorithm and size can be specified by command line parameters; the defaults are "tsig-key", HMAC-SHA256, and 256 bits, respectively. Any string which is a valid DNS name can be used as a key name. For example, a key to be shared between servers called host1 and host2 could be called "host1-host2.", and this key could be generated using: $ tsig-keygen host1-host2. > host1-host2.key This key may then be copied to both hosts. The key name and secret must be identical on both hosts. (Note: copying a shared secret from one server to another is beyond the scope of the DNS. A secure transport mechanism should be used: secure FTP, SSL, ssh, telephone, encrypted email, etc.) tsig-keygen can also be run as ddns-confgen, in which case its output includes additional configuration text for setting up dynamic DNS in named. See for details. Loading A New Key will be able to verify the signature. If the signature is valid, the response will be signed using the same key. TSIG keys that are known to a server can be listed using the command rndc tsig-list. Instructing the Server to Use a Key A server sending a request to another server must be told whether to use a key, and if so, which key to use. For example, a key may be specified for each server in the masters statement in the definition of a slave zone; in this case, all SOA QUERY messages, NOTIFY messages, and zone transfer requests (AXFR or IXFR) will be signed using the specified key. Keys may also be specified in the also-notify statement of a master or slave. Whenever any server sends a TSIG-signed DNS request, it will expect the response to be signed with the same key. If a response is not signed, or if the signature is not valid, the response will be rejected. TSIG-Based Access Control TSIG keys may be specified in ACL definitions and ACL directives such as allow-query, allow-transfer and allow-update. The above key would be denoted in an ACL element as key host1-host2. for a discussion of the more flexible update-policy statement. Errors, with the TSIG extended error code set to BADTIME, and the time values will be adjusted so that the response can be successfully verified. In all of the above cases, the server will return a response code of NOTAUTH (not authenticated). TKEY, will contain a TKEY record in its answer section. After this transaction, both participants will have enough information to calculate a shared secret using Diffie-Hellman key exchange. The shared secret can then be used by. SIG(0) will only be verified if the key is known and trusted by the server. The server will not attempt to recursively fetch or validate the key. SIG(0) signing of multiple-message TCP streams is not supported. The only tool shipped with BIND 9 that generates SIG(0) signed messages is nsupdate. DNSSEC ones.. Generating Keys the only one is RSASHA1. The following command will generate a 768-bit RSASHA1 key for the child.example zone: dnssec-keygen -a RSASHA1 -b 768 -n ZONE child.example. Two output files will be produced: Kchild.example.+005+12345.key and Kchild.example.+005+12345.private (where 12345 is an example of a key tag). The key filenames contain the key name (child.example.), algorithm (3 is DSA, 1 is RSAMD5, 5 is RSASHA1,. Signing the Zone The dnssec-signzone program is used to sign a zone. Any keyset files corresponding to secure subzones should be present. The zone signer will generate NSEC, NSEC3 and RRSIG records for the zone, as well as DS for the child zones if '-g' is specified. If '-g' is not specified, then DS RRsets for the secure child zones need to be added manually.. dnssec-signzone will also produce a keyset and dsset files and optionally a dlvset file. These are used to provide the parent zone administrators with the DNSKEYs (or their corresponding DS records) that are the secure entry point to the zone. Configuring Servers To enable named to respond appropriately to DNS requests from DNSSEC aware clients, dnssec-enable must be set to yes. (This is the default setting.) To enable named to validate answers from other servers, the dnssec-enable option must be set to yes, and the dnssec-validation options must be set to yes or auto. If dnssec-validation is set to auto, then a default trust anchor for the DNS root zone will be used. If it is set to yes, however, then at least one trust anchor must be configured with a trusted-keys or managed-keys statement in named.conf, or DNSSEC validation will not occur. The default setting is yes. trusted-keys are copies of DNSKEY RRs for zones that are used to form the first link in the cryptographic chain of trust. All keys listed in trusted-keys (and corresponding zones) are deemed to exist and only the listed keys will be used to validated the DNSKEY RRset that they are from. managed-keys are trusted keys which are automatically kept up to date via RFC 5011 trust anchor maintenance. trusted-keys and managed-keys are described in more detail later in this document. Unlike BIND 8, BIND 9 does not verify signatures on load, so zone keys for authoritative zones do not need to be specified in the configuration file. After DNSSEC gets established, a typical DNSSEC configuration will look something like the following. It has one or more public keys for the root. This allows answers from outside the organization to be validated. It will also have several keys for parts of the namespace the organization controls. These are here to ensure that named is immune to compromises in the DNSSEC components of the security of parent zones. managed-keys { /*"; }; trusted-keys { /* Key for our organization's forward zone */ example.com. 257 3 5 "AwEAAaxPMcR2x0HbQV4WeZB6oEDX+r0QM6 5KbhTjrW1ZaARmPhEZZe3Y9ifgEuq7vZ/z GZUdEGNWy+JZzus0lUptwgjGwhUS1558Hb 4JKUbbOTcM8pwXlj0EiX3oDFVmjHO444gL kBOUKUf/mC7HvfwYH/Be22GnClrinKJp1O g4ywzO9WglMk7jbfW33gUKvirTHr25GL7S TQUzBb5Usxt8lgnyTUHs1t3JwCY5hKZ6Cq FxmAVZP20igTixin/1LcrgX/KMEGd/biuv F4qJCyduieHukuY3H4XMAcR+xia2nIUPvm /oyWR8BW/hWdzOvnSCThlHf3xiYleDbt/o 1OTQ09A0="; /* Key for our reverse zone. */ 2.0.192.IN-ADDRPA-enable yes; dnssec-validation yes; }; None of the keys listed in this example are valid. In particular, the root key is not valid. When DNSSEC validation is enabled and properly configured, the resolver will reject any answers from signed, secure zones which fail to validate, and will return, then it must assume an insecure response to be a forgery; it rejects the response and logs an error. The logged error reads "insecurity proof failed" and "got insecure response; parent indicates it should be secure". IPv6 Support in BIND 9 BIND 9 fully supports all currently defined forms of IPv6 name to address and address to name lookups. It will also use any more, and will return an error if given. In particular, an authoritative BIND 9 name server will not load a zone file containing binary labels. For an overview of the format and structure of IPv6 addresses, see . Address Lookups Using AAAA Records. Address to Name Lookups Using Nibble Format. ) The BIND 9 Lightweight Resolver The Lightweight Resolver Library Traditionally applications have been linked with a stub resolver library that sends recursive DNS queries to a local caching name server. IPv6 once introduced new complexity into the resolution process, such as following A6 chains and DNAME records, and simultaneous lookup of IPv4 and IPv6 addresses. Though most of the complexity was then removed, these are hard or impossible to implement in a traditional stub resolver. BIND 9 therefore can also provide. Running a Resolver Daemon To use the lightweight resolver interface, the system must run the resolver daemon lwresd or a local name server configured with a lwres statement. By default, applications using the lightweight resolver library will make UDP requests to the IPv4 loopback address (127.0.0.1) on port 921. The address can be overridden by lwserver lines in /etc/resolv.conf. The daemon currently only looks in the DNS, but in the future it may use other sources such as /etc/hosts, NIS, etc. The lwresd daemon is essentially a caching-only name server that responds to. The number of client queries that the lwresd daemon is able to serve can be set using the lwres-tasks and lwres-clients statements in the configuration. BIND 9 Configuration Reference BIND 9 configuration is broadly similar to BIND 8; however, there are a few new areas of configuration, such as views. BIND 8 configuration files should work with few alterations in BIND 9, although more complex configurations should be reviewed to check if they can be more efficiently implemented using the new features found in BIND 9. BIND 4 configuration files can be converted to the new format using the shell script contrib/named-bootconf/named-bootconf.sh. Configuration File Elements Following is a list of elements used throughout the BIND configuration file documentation: acl_name The name of an address_match_list as defined by the acl statement. address_match_list A list of one or more ip_addr, ip_prefix, key_id, or acl_name elements, see . masters_list A named list of one or more ip_addr with optional key_id and/or ip_port. A masters_list may include other masters_lists. domain_name A quoted string which will be used as a DNS name, for example "my.test.domain". namelist A list of one or more domain_name elements. dotted_decimal One to four integers valued 0 through 255 separated by dots (`.'), such as 123, 45.67 or 89.123.45.67. ip4_addr An IPv4 address with exactly four elements in dotted_decimal notation. ip6_addr An IPv6 address, such as 2001:db8::1234. IPv6 scoped addresses that have ambiguity on their scope zones must be disambiguated by an appropriate zone ID with the percent character (`%') as delimiter. It is strongly recommended to use string zone names rather than numeric identifiers, in order to be robust against system configuration changes. However, since there is no standard mapping for such names and identifier values, currently only interface names as link identifiers are supported, assuming one-to-one mapping between interfaces and links. For example, a link-local address fe80::1 on the link attached to the interface ne0 can be specified as fe80::1%ne0. Note that on most systems link-local addresses always have the ambiguity, and need to be disambiguated. ip_addr An ip4_addr or ip6_addr. ip_dscp A number between 0 and 63, used to select a differentiated services code point (DSCP) value for use with outgoing traffic on operating systems that support DSCP. ip_port An IP port number. The number (`/') and then the number of bits in the netmask. Trailing zeros in a ip_addr may omitted. For example, 127/8 is the network 127.0.0.0 with netmask 255.0.0.0 and 1.2.3.0/28 is network 1.2.3.0 with netmask 255.255.255.240. When specifying a prefix involving a IPv6 scoped address the scope may be omitted. In that case the prefix will match packets from any scope. key_id A domain_name representing context in which it is used. path_name A quoted string which will be used as a pathname, such as zones/master/my.test.domain. port_list A list of an ip_port or a port range. A port range is specified in the form of range followed by two ip_ports, port_low and port_high, which represents port numbers from port_low through port_high, inclusive. port_low must not be larger than port_high. For example, range 1024 65535 represents ports from 1024 through 65535. In either case an asterisk (`*') character is not allowed as a valid ip_port. size_spec A 64-bit unsigned integer, or the keywords unlimited for details on how they interpret its use. Numeric values can optionally be followed by a scaling factor: K or k for kilobytes, M or m for megabytes, and G or g for gigabytes, which scale by 1024, 1024*1024, and 1024*1024*1024 respectively. unlimited generally means "as big as possible", and is usually the best way to safely set a very large number. default uses the limit that was in force when the server was started. size_or_percent size_spec or integer value followed by '%' to represent percents. The behavior is exactly the same as size_spec, but size_or_percent allows also to specify a positive integer value followed by '%' sign to represent percents. yes_or_no Either yes or no. The words true and false are also accepted, as are the numbers 1 and 0. dialup_option One of yes, no, notify, notify-passive, refresh or passive. When used in a zone, notify-passive, refresh, and passive are restricted to slave and stub zones. Address Match Lists Syntax address_match_list = address_match_list_element ; ... address_match_list_element = [ ! ] ( ip_address | ip_prefix | key key_id | acl_name | { address_match_list } ) Definition and Usage `/' notation) a key ID, as defined by the key statement the name of an address match list defined with the acl statement will cause the server to refuse queries on any of the machine's addresses which do not match the list. Order of insertion is significant. If more than one element in an ACL is found to match a given IP address or prefix, preference will. Comment Syntax The BIND 9 comment syntax allows for comments to appear anywhere that whitespace may appear in a BIND configuration file. To appeal to programmers of all kinds, they can be written in the C, C++, or shell/perl style. Syntax /* This is a BIND comment as in C */ // This is a BIND comment as in C++ # This is a BIND comment as in common UNIX shells # and perl Definition and Usage character # (number sign) and continue to the end of the physical line, as in C++ comments. For example: # This is the start of a comment. The next line # is a new comment, even though it is logically # part of the previous comment. You cannot use the semicolon (`;') character to start a comment such as you would in a zone file. The semicolon indicates the end of a configuration statement. Configuration File Grammarc utility. include includes a file. key specifies key information for use in authentication and authorization using TSIG. logging specifies what the server logs, and where the log messages are sent. lwres configures named to also act as a light-weight resolver daemon (lwresd). masters defines a named masters list for inclusion in stub and slave zones' masters or also-notify lists. options controls global server configuration options and sets defaults for other statements. server sets certain configuration options on a per-server basis. statistics-channels declares communication channels to get access to named statistics. trusted-keys defines trusted DNSSEC keys. managed-keys lists DNSSEC keys to be kept up to date using RFC 5011 trust anchor maintenance. view defines a view. zone defines a zone. The logging and options statements may only occur once per configuration. acl Statement Grammar acl Statement Definition and Usage ACL element is updated to reflect the changes. localnets Matches any host on an IPv4 or IPv6 network for which the system has an interface. When addresses are added or removed, the localnets ACL element is updated to reflect the changes. Some systems do not provide a way to determine the prefix lengths of local IPv6 addresses. In such a case, localnets only matches the local IPv6 addresses, just like localhost. controls Statement Grammar controls Statement Definition and Usage you will only use rndc in ) will set up a default control channel listening on the loopback address 127.0.0.1 and its IPv6 counterpart ::1. In this case, and also when the controls statement is present but does not have a keys clause, named will attempt to load the command channel key from the file rndc.key in /etc (or whatever sysconfdir was specified as when BIND was built). To create a rndc.key file, run rndc-confgen -a. The rndc.key feature was created to ease the transition of systems from BIND 8, which did not have digital signatures on its command channel messages and thus did not have a keys clause. It makes it possible to use an existing BIND 8 configuration file in BIND 9 unchanged, and still have rndc work the same way ndc worked in BIND 8, simply by executing the command rndc-confgen -a after BIND 9 is installed. Since the rndc.key feature is only intended to allow the backward-compatible usage of BIND 8 configuration files, this feature does not have a high degree of configurability. You cannot easily change the key name or the size of the secret, so you should make a rndc.conf with your own key if you wish to change those things. The rndc.key file also has its permissions set such that only the owner of the file (the user that named is running as) can access it. If you desire greater flexibility in allowing other users to access rndc commands, then you need to create a rndc.conf file and make it group readable by a group that contains the users who should have access. To disable the command channel, use an empty controls statement: controls { };. include Statement Grammar include filename; include Statement Definition and Usage The include statement inserts the specified file at the point where the include statement is encountered. The include statement facilitates the administration of configuration files by permitting the reading or writing of some things but not others. For example, the statement could include private keys that are readable only by the name server. key Statement Grammar key Statement Definition and Usage The key statement defines a shared secret key for use with TSIG (see ) or the command channel (see ). The key statement can occur at the top level of the configuration file or inside a view statement. Keys defined in top-level key statements can be used in all views. Keys intended for use in a controls statement (see ). logging Statement Grammar logging Statement Definition and Usage is no logging statement, the logging configuration will be: logging { category default { default_syslog; default_debug; }; category unmatched { null; }; }; If named is started with the -L option, it logs to the specified file at startup, instead of using syslog. In this case the logging configuration will be: logging { category default { default_logfile; default_debug; }; category unmatched { null; }; }; In BIND 9, the logging configuration is only established when the entire configuration file has been parsed. In BIND 8, it was established as soon as the logging statement was parsed. When the server is starting up, all logging messages regarding syntax errors in the configuration file go to the default channels, or to standard error if the -g option was specified. The channel Phrase All log output goes to one or more channels; you can make as many of them as you want. Every channel definition must include a destination clause that says whether messages selected for the channel go to a file, to a particular syslog facility, to the standard error stream, or are discarded. It can optionally also limit the message severity level that will limitations both on how large the file is allowed to become, and how many versions of the file will be saved each time the file is opened. If you use the versions log file option, then named will retain that many backup versions of the file by renaming them when opening. For example, if you choose to keep three old versions of the file lamers.log, then just before it is opened lamers.log.1 is renamed to lamers.log.2, lamers.log.0 is renamed to lamers.log.1, and lamers.log is renamed to lamers.log.0. You can say versions unlimited to not limit the number of versions. If a size option is associated with the log file, then renaming is only done when the file being opened exceeds the indicated size. No backup versions are kept by default; any existing log file is simply appended. The size option for files is used to limit log growth. If the file ever exceeds the size, then named will stop writing to the file unless it has a versions option associated with it. If backup versions are kept, the files are rolled as described above and a new one begun. If there is no versions option, no more data will be written to the log until some out-of-band mechanism removes or truncates the log to less than the maximum size. The default behavior is not to limit the size of the file. Example usage of the size and versions options: channel an_example_channel { file "example.log" versions 3 size 20m; print-time yes; print-category yes; }; The syslog destination clause directs the channel to the system log. Its argument is a syslog facility as described in the syslog man page. Known facilities are kern, user, mail, daemon, auth, syslog, lpr, news, uucp, cron, authpriv, ftp, local0, local1, local2, local3, local4, local5, local6 and local7, however not all facilities are supported on all operating systems. How syslog will handle messages sent to this facility is described in the syslog.conf man page. If you have a system which uses a very old version of syslog that only uses two arguments to the openlog() function, then this clause is silently ignored. On Windows machines syslog messages are directed to the EventViewer., then debugging mode will, and higher debug levels give debug level to determine what messages to print. If print-time has been turned on, then the date and time will be logged. print-time may be specified for a syslog channel, but is usually pointless since syslog also logs-Feb-2000 15:05:32.863 general: notice: running If buffered has been turned on the output to files will not be flushed after each log entry. By default all log messages are flushed. There are four predefined channels that are used for named's default logging as follows. If named is started with the -L then a fifth channel default_logfile is added. How they are used is described in .. If you need to capture this output, you must run the server with the -L option to specify a default logfile, or the -g option to log to standard error which you can redirect to a file. wherever; }; If you start named with the -L option then the default category is: category default { default_logfile; default_debug; }; As an example, let's say you want to log security events to a file, but you also want keep the default logging behavior. You'd. The query-errors Category The query-errors category is specifically intended for debugging purposes: To identify why and how specific queries result in responses which indicate an error. Messages of this category are therefore only logged with debug levels. At the debug levels of 1 or higher, will particularly help identify the cause of SERVFAIL for an authoritative server. At the debug levels of 2 or higher, detailed context information of recursive resolutions that resulted in SERVFAIL is logged. The log message will look like as follows: fetch completed at resolver.c:2970 for in 30.000183: timed out/success [domain:example.com, referral:2,restart:7,qrysent:8,timeout:5,lame:0,neterr:0, badresp:1,adberr:0,findfail:0,valfail:0] The first part before the colon shows that a recursive resolution for AAAA records of completed in 30.000183 seconds and the final result that led to the SERVFAIL was determined at line 2970 of source file resolver.c. The following part shows the detected final result and the latest result of DNSSEC validation. The latter is always success when no validation attempt is made. In this example, this query resulted in SERVFAIL probably because all name servers are down or unreachable, leading to a timeout in 30 seconds. DNSSEC validation was probably not attempted. The last part enclosed in square brackets shows statistics information collected for this particular resolution attempt. The domain field shows the deepest zone that the resolver reached; it is the zone where the error was finally detected. The meaning of the other fields is summarized in the following table. referral The number of referrals the resolver received throughout the resolution process. In the above example this is 2, which are most likely com and example.com. restart The number of cycles that the resolver tried remote servers at the domain zone. In each cycle the resolver sends one query (possibly resending it, depending on the response) to each known name server of the domain zone. qrysent The number of queries the resolver sent at the domain zone. timeout The number of timeouts since the resolver received the last response. lame The number of lame servers the resolver detected at the domain zone. A server is detected to be lame either by an invalid response or as a result of lookup in BIND9's address database (ADB), where lame servers are cached. neterr The number of erroneous results that the resolver encountered in sending queries at the domain zone. One common case is the remote server is unreachable and the resolver receives an ICMP unreachable error message. badresp The number of unexpected responses (other than lame) to queries sent by the resolver at the domain zone. resolution process. valfail Failures of DNSSEC validation. Validation failures are counted throughout the resolution process (not limited to the domain zone), but should only happen in domain. At the debug levels of 3 or higher, the same messages as those at the debug 1 level are logged for other errors than SERVFAIL. Note that negative responses such as NXDOMAIN are not regarded as errors here. At the debug levels of 4 or higher, the same messages as those at the debug 2 level are logged for other errors than SERVFAIL. Unlike the above case of level 3, messages are logged for negative responses. This is because any unexpected results can be difficult to debug in the recursion case. lwres Statement Grammar This is the grammar of the lwres statement in the named.conf file: lwres { [ listen-on { ( ip_addr [ port ip_port ] [ dscp ip_dscp ] ; ) ... }; ] [ view view_name; ] [ search { domain_name ; ... }; ] [ ndots number; ] [ lwres-tasks number; ] [ lwres-clients number; ] }; lwres Statement Definition and Usage The lwres statement configures the name server to also act as a lightweight resolver server. (See .) There may be multiple lwres statements configuring lightweight resolver servers with different properties. The listen-on statement specifies a list of IPv4 addresses (and ports) that this instance of a lightweight resolver daemon should accept requests on. If no port is specified, port 921 is used. If this statement is omitted, requests will be accepted on 127.0.0.1, port 921. The view statement binds this instance of a lightweight resolver daemon to a view in the DNS namespace, so that the response will be constructed in the same manner as a normal DNS query matching this view. If this statement is omitted, the default view is used, and if there is no default view, an error is triggered. The search statement is equivalent to the search statement in /etc/resolv.conf. It provides a list of domains which are appended to relative names in queries. The ndots statement is equivalent to the ndots statement in /etc/resolv.conf. It indicates the minimum number of dots in a relative domain name that should result in an exact match lookup before search path elements are appended. The lwres-tasks statement specifies the number of worker threads the lightweight resolver will dedicate to serving clients. By default the number is the same as the number of CPUs on the system; this can be overridden using the -n command line option when starting the server. The lwres-clients specifies the number of client objects per thread the lightweight resolver should create to serve client queries. By default, if the lightweight resolver runs as a part of named, 256 client objects are created for each task; if it runs as lwresd, 1024 client objects are created for each thread. The maximum value is 32768; higher values will be silently ignored and the maximum will be used instead. Note that setting too high a value may overconsume system resources. The maximum number of client queries that the lightweight resolver can handle at any one time equals lwres-tasks times lwres-clients. masters Statement Grammar masters Statement Definition and Usage masters lists allow for a common set of masters to be easily used by multiple stub and slave zones in their masters or also-notify lists. options Statement Grammar This is the grammar of the options statement in the named.conf file: options Statement Definition and Usage The options statement sets up global options to be used by BIND. This statement may appear only once in a configuration file. If there is no options statement, an options block with each option set to its default will be used. attach-cache option may also be specified in view statements, in which case it overrides the global attach-cache option. The cache_name specifies the cache to be shared. When the named server configures views which are supposed to share a cache, it creates a cache with the specified name for the first view of these sharing views. The rest of the views will simply refer to the already created cache. One common configuration to share a cache would be to allow all views to share a single cache. This can be done by specifying the attach-cache option as a view, cleaning-interval, dnssec-accept-expired, dnssec-validation, max-cache-ttl, max-ncache-ttl, max-cache-size, administrator's responsibility to ensure configuration differences in different views do not cause disruption with a shared cache. directory The working directory of the server. Any non-absolute pathnames in the configuration file will be taken as relative to this directory. The default location for most server output files (e.g. named.run) is this directory. If a directory is not specified, the working directory defaults to `.', the directory from which the server was started. The directory specified should be an absolute path. It is strongly recommended that the directory be writable by the effective user ID of the named process. dnstap dnstap is a fast, flexible method for capturing and logging DNS traffic. Developed by Robert Edmonds at Farsight Security, Inc., and supported by multiple DNS implementations, dnstap uses libfstrm (a lightweight high-speed framing library, see) to send event payloads which are encoded using Protocol Buffers (libprotobuf-c, a mechanism for serializing structured data developed by Google, Inc.; see). To enable dnstap at compile time, the fstrm and protobuf-c libraries must be available, and BIND must be configured with --enable-dnstap. The dnstap option is a bracketed list of message types to be logged. These may be set differently for each view. Supported types are client, auth, resolver, and forwarder. Specifying type all will cause all dnstap messages to be logged, regardless of type. Each type may take an additional argument to indicate whether to log query messages or response messages; if not specified, both queries and responses are logged. Example: To log all authoritative queries and responses, recursive client responses, and upstream queries sent by the resolver, use: dnstap { auth; client response; resolver query; }; Logged dnstap messages can be parsed using the dnstap-read utility (see: Controls. Note that all of the above minimum, maximum, and default values are set by the libfstrm library, and may be subject to change in future versions of the library. See the libfstrm documentation for more information. dnstap-output Configures the path to which the dnstap frame stream will be sent if dnstap is enabled at compile time and active. The first argument is either file or unix, indicating whether the destination is a file or a UNIX domain socket. The second argument is the path of the file or socket. (Note: when using a socket, dnstap messages will only be sent if another process such as fstrm_capture (provided with libfstrm) is listening on the socket.) dnstap-output can only be set globally in options. Currently, it can only be set once while named is running; once set, it cannot be changed by rndc reload or rndc reconfig. dnstap-identity Specifies an identity string to send in dnstap messages. If set to hostname, which is the default, the server's hostname will be sent. If set to none, no identity string will be sent. dnstap-version Specifies a version string to send in dnstap messages. The default is the version number of the BIND release. If set to none, no version string will be sent. geoip-directory Specifies the directory containing GeoIP .dat database files for GeoIP initialization. By default, this option is unset and the GeoIP support will use libGeoIP's built-in directory. (For details, see about the geoip ACL.) key-directory When performing dynamic update of secure zones, the directory where the public and private DNSSEC key files should be found, if different than the current working directory. (Note that this option has no effect on the paths for files containing non-DNSSEC keys such as bind.keys, rndc.key or session.key.) lmdb-mapsize When named process. The default of 32 megabytes was chosen to be usable with 32-bit named builds. The largest permitted value is 1 terabyte. Given typical zone configurations without elaborate ACLs, a 32 MB NZD file ought to be able to hold configurations of about 100,000 zones. managed-keys-directory Specifies the directory in which to store the files that track managed DNSSEC keys. By default, this is the working directory. The directory must be writable by the effective user ID of the named process. If named is not configured to use views, then managed keys for the server will be tracked in a single file called managed-keys.bind. Otherwise, managed keys will be tracked in separate files, one file per view; each file name will be the view name (or, if it contains characters that are incompatible with use as a file name, the SHA256 hash of the view name), followed by the extension .mkeys. (Note: in previous releases, file names for views always used the SHA256 hash of the view name. To ensure compatibility after upgrade, if a file using the old name format is found to exist, it will be used instead of the new format.) named-xfer This option is obsolete. It was used in BIND 8 to specify the pathname to the named-xfer program. In BIND 9, no separate named-xfer program is needed; its functionality is built into the name server. tkey-gssapi-keytab The KRB5 keytab file to use for GSS-TSIG updates. If this option is set and tkey-gssapi-credential is not set, then updates will be allowed with any key matching a principal in the specified keytab. tkey-gssapi-credential The security credential with which the server should authenticate keys requested by the GSS-TSIG protocol. Currently only Kerberos 5 authentication is available and must also be set if a specific keytab is not set with tkey-gssapi-keytab. tkey-domain The domain appended to the names of all shared keys generated with TKEY. When a client requests a TKEY exchange, it may or may not specify the desired name for the key. If present, the name of the shared key will be client specified part + tkey-domain. Otherwise, the name of the shared key will be random hex digits + tkey-domain. In most cases, the domainname should be the server's domain name, or an otherwise non-existent subdomain like "_tkey.domainname". If you are using GSS-TSIG, this variable must be defined, unless you specify a specific keytab using tkey-gssapi-keytab. tkey-dhkey The Diffie-Hellman key used by the server to generate shared keys with clients using the Diffie-Hellman mode of TKEY. The server must be able to load the public and private keys from files in the working directory. In most cases, the key_name should be the server's host name. cache-file This is for testing only. Do not use.. lock-file The pathname of a file on which named will attempt to acquire a file lock when starting up for the first time; if unsuccessful, the server will will terminate, under the assumption that another server is already running. If not specified, the default is /var/run/named/named.lock. Specifying lock-file none disables the use of a lock file. lock-file is ignored if named was run using the -X option, which overrides it. Changes to lock-file are ignored if named is being reloaded or reconfigured; it is only effective when the server is first started up. pid-file The pathname of the file the server writes its process ID in. If not specified, the default is /var/run/named/named.pid. The PID file is used by programs that want to send signals to the running name server. Specifying pid-file none disables the use of a PID file — no file will be written and any existing one will be removed. Note that none is a keyword, not a filename, and therefore is not enclosed in double quotes. recursing-file The pathname of the file the server dumps the queries that are currently recursing when instructed to do so with rndc recursing. If not specified, the default is named.recursing. statistics-file The pathname of the file the server appends statistics to when instructed to do so using rndc stats. If not specified, the default is named.stats in the server's current directory. The format of the file is described in . bindkeys-file The pathname of a file to override the built-in trusted keys provided by named. See the discussion of dnssec-validation for details. If not specified, the default is /etc/bind.keys. secroots-file The pathname of the file the server dumps security roots to when instructed to do so with rndc secroots. If not specified, the default is named.secroots. session-keyfile The pathname of the file into which to write a TSIG session key generated by named for use by nsupdate -l. If not specified, the default is /var/run/named/session.key. (See , and in particular the discussion of the update-policy statement's local option for more information about this feature.) session-keyname The key name to use for the TSIG session key. If not specified, the default is "local-ddns". session-keyalg The UDP/TCP port number the server uses for receiving and sending DNS protocol traffic. The default is 53. This option is mainly intended for server testing; a server using a port other than 53 will not be able to communicate with the global DNS. dscp The global Differentiated Services Code Point (DSCP) value to classify outgoing DNS traffic on operating systems that support DSCP. Valid values are 0 through 63. It is not configured by default. random-device The source of entropy to be used by the server. Entropy is primarily needed for DNSSEC operations, such as TKEY transactions and dynamic update of signed zones. This options specifies the device (or file) from which to read entropy. If this is a file, operations requiring entropy will fail when the file has been exhausted. If not specified, the default value is /dev/random (or equivalent) when present, and none otherwise. The random-device option takes effect during the initial configuration load at server startup time and is ignored on subsequent reloads. preferred-glue If specified, the listed type (A or AAAA) will be emitted before other glue in the additional section of a query response. The default is to prefer A records when responding to queries that arrived via IPv4 and AAAA when responding to queries that arrived via IPv6. root-delegation-only Turn if they are signed by a child zone or not. The authority section is also some TLDs are not delegation only (e.g. "DE", "LV", "US" and "MUSEUM"). This list is not exhaustive. options { root-delegation-only exclude { "de"; "lv"; "us"; "museum"; }; }; disable-algorithms Disable the specified DNSSEC algorithms at and below the specified name. Multiple disable-algorithms statements are allowed. Only the best match disable-algorithms clause will be used to determine which algorithms are used. If all supported algorithms are disabled, the zones covered by the disable-algorithms will be treated as insecure. disable-ds-digests Disable the specified DS/DLV digest types at and below the specified name. Multiple disable-ds-digests statements are allowed. Only the best match disable-ds-digests clause will be used to determine which digest types are used. If all supported digest types are disabled, the zones covered by the disable-ds-digests will be treated as insecure. will be appended to the key name and a DLV record will be looked up to see if it can validate the key. If the DLV record validates a DNSKEY (similarly to the way a DS record does) the DNSKEY RRset is deemed to be trusted. If dnssec-lookaside is set to no, then dnssec-lookaside is not used. NOTE: The ISC-provided DLV service at dlv.isc.org, has been shut down. The dnssec-lookaside auto; configuration option, which set named up to use ISC DLV with minimal configuration, has accordingly been removed.-keys or managed-keys statement, or dnssec-validation auto must be active. dns64 This directive instructs named to return mapped IPv4 addresses to AAAA queries when there are no AAAA records. It is intended to be used in conjunction with a NAT64. Each dns64 defines one DNS64 prefix. Multiple DNS64 prefixes can be defined. Compatible IPv6 prefixes have lengths of 32, 40, 48, 56, 64 and 96 as per RFC 6052. Additionally a reverse IP6.ARPA zone will be created for the prefix to provide a mapping from the IP6.ARPA names to the corresponding IN-ADDR.ARPA names using synthesized CNAMEs. dns64-server and dns64-contact can be used to specify the name of the server and contact for the zones. These are settable at the view / options level. These are not settable on a per-prefix basis. Each dns64 supports an optional clients ACL that determines which clients are affected by this directive. If not defined, it defaults to any;. Each dns64 supports an optional mapped ACL that selects which IPv4 addresses are to be mapped in the corresponding A RRset. If not defined it defaults to any;. Normally, DNS64 won't apply to a domain name that owns one or more AAAA records; these records will simply be returned. The optional exclude ACL allows specification of a list of IPv6 addresses that will be ignored if they appear in a domain name's AAAA records, and DNS64 will be applied to any A records the domain name owns. If not defined, exclude defaults to ::ffff:0.0.0.0/96. A optional suffix can also be defined to set the bits trailing the mapped IPv4 address bits. By default these bits are set to ::. The bits matching the prefix and mapped IPv4 address must be zero. If recursive-only is set to yes the DNS64 synthesis will only happen for recursive queries. The default is no. If break-dnssec is set to yes the DNS64 synthesis will happen even if the result, if validated, would cause a DNSSEC validation failure. If this option is set to no (the default), the DO is set on the incoming query, and there are RRSIGs on the applicable records, then synthesis will and ). The dnssec-loadkeys-interval option sets the frequency of automatic repository checks, in minutes. The default is 60 (1 hour), the minimum is 1 (1 minute), and the maximum is 1440 (24 hours); any higher value is silently reduced. dnssec-update-mode If this option is set to its default value of maintain in a zone of type master which is DNSSEC-signed and configured to allow dynamic updates (see ), and if named has access to the private signing key(s) for the zone, then named will automatically sign all new or changed records and maintain signatures for the zone by regenerating RRSIG records whenever they approach their expiration date. If the option is changed to no-resign, then named will sign all new or changed records, but scheduled maintenance of signatures is disabled. With either of these settings, named will reject Species the default lifetime, in seconds, that will be used will abort the DNSSEC validation process and treat the data as insecure rather than bogus. This continues until the NTA's lifetime is elapsed. NTAs persist across named restarts. For convenience, TTL-style time unit suffixes can be used to specify the NTA lifetime in seconds, minutes or hours. nta-lifetime defaults to one hour. It cannot exceed one week. nta-recheck Species how often to check whether negative trust anchors added via rndc nta are will periodically send to zero. For convenience, TTL-style time unit suffixes can be used to specify the NTA recheck interval in seconds, minutes or hours. The default is five minutes. It cannot be longer than nta-lifetime (which cannot be longer than a week). max-zone-ttl Specifies a maximum permissible TTL value in seconds. For convenience, TTL-style time unit suffixes may be used to specify the maximum value. When loading a zone file using a masterfile-format of text or raw, any record encountered with a TTL higher than max-zone-ttl will cause the zone to be rejected. This is useful in DNSSEC-signed zones because when rolling to a new DNSKEY, the old key needs to remain available until RRSIG records have expired from caches. The max-zone-ttl option guarantees that the largest TTL in the zone will be no higher than the set value. (NOTE: Because map-format files load directly into memory, this option cannot be used with them.) The default value is unlimited. A max-zone-ttl of zero is treated as unlimited. serial-update-method Zones configured for dynamic DNS may use this option to set the update method that will be used for the zone serial number in the SOA record. With the default setting of serial-update-method increment;, the SOA serial number will be incremented by one each time the zone is updated. When set to serial-update-method unixtime;, the SOA serial number will be set to the number of seconds since the UNIX epoch, unless the serial number is already greater than or equal to that value, in which case it is simply incremented by one. When set to serial-update-method date;, the new SOA serial number will be the current date in the form "YYYYMMDD", followed by two zeroes, unless the existing serial number is already greater than or equal to that value, in which case it is incremented by one. zone-statistics If full, the server will collect statistical data on all zones (unless specifically turned off on a per-zone basis by specifying zone-statistics terse or zone-statistics none in the zone statement). The default is terse, providing minimal statistics on zones (including name and current serial number, but not query type counters). These statistics may be accessed via the statistics-channel or using rndc stats, which will dump them to the file listed in the statistics-file. See also . For backward compatibility with earlier versions of BIND 9, the zone-statistics option can also accept yes or no; yes has the same meaning as full. As of BIND 9.10, no has the same meaning as none; previously, it was the same as terse. Boolean Options automatic-interface-scan If yes and supported by the OS, automatically rescan network interfaces when the interface addresses are added or removed. The default is yes. Currently the OS needs to support routing sockets for automatic-interface-scan to be supported.. Zones added at runtime will have their configuration stored either in a new-zone file (NZF) or a new-zone database (NZD) depending on whether named was linked with liblmdb at compile time. See for further details about rndc addzone. auth-nxdomain If yes, then. memstatistics Write memory statistics to the file specified by memstatistics-file at exit. The default is no unless ' also be specified in the view and zone statements, in which case it overrides the global dialup option. If the zone is a master zone, then the server will send, then the server will suppress the regular "zone up to date" (refresh) queries and only perform them when the heartbeat-interval expires in addition to sending NOTIFY requests. Finer control can be achieved by using notify which only sends NOTIFY messages, notify-passive which sends NOTIFY messages and suppresses the normal refresh queries, refresh which suppresses normal refresh processing and sends refresh queries when the heartbeat-interval expires, and passive which just disables normal refresh processing. dialup mode normal refresh heart-beat refresh heart-beat notify no (default) yes no no yes no yes yes notify yes no yes refresh no yes no passive no no no notify-passive no no yes Note that normal NOTIFY processing is not affected by dialup. fake-iquery In BIND 8, this option enabled simulating or do not flush any pending zone writes. The default is flush-zones-on-shutdown no. geoip-use-ecs When BIND is compiled with GeoIP support and configured with "geoip" ACL elements, this option indicates whether the EDNS Client Subnet option, if present in a request, should be used for matching against the GeoIP database. The default is geoip-use-ecs yes. enabled keeping of statistics for every host that the name server interacts with. Not implemented in BIND 9. root-key-sentinel Respond to root key sentinel probes as described in draft-ietf-dnsop-kskroll-sentinel-08. The default is yes.. message-compression If yes, DNS name compression is used in responses to regular queries (not including AXFR or IXFR, which always uses compression). Setting this option to no reduces CPU usage on servers and may improve throughput. However, it increases response size, which may cause more queries to be processed using TCP; a server with compression disabled is out of compliance with RFC 1123 Section 6.1.3.2. The default is yes. minimal-responses If set to yes, then when generating responses the server will only add records to the authority and additional data sections when they are required (e.g. delegations, negative responses). This may improve the performance of the server. When set to no-auth, the server will omit records from the authority section unless they are required, but it may still add records to the additional section. When set to no-auth-recursive, this is only done if the query is recursive. These settings are useful when answering stub clients, which usually ignore the authority section. no-auth-recursive is designed for mixed-mode servers which handle both authoritative and recursive queries. The default is no. minimal-any If set to yes, then when generating a positive response to a query of type ANY over UDP, the server will reply with only one of the RRsets for the query name, and its covering RRSIGs if any, instead of replying with all known RRsets for the name. Similarly, a query for type RRSIG will is turned on for these queries, so no unnecessary records will be added to the authority or additional sections. The default is no. multiple-cnames This option was used in BIND 8 to allow a domain name to have multiple CNAME records in violation of the DNS standards. BIND 9.2 onwards always strictly enforces the CNAME rules both in master files and dynamic updates. notify If yes (the default), DNS NOTIFY messages are sent when a zone the server is authoritative for changes, see . The messages are sent to the servers listed in the zone's NS records (except the master server identified in the SOA MNAME field), and to any servers listed in the also-notify option. If master-only, notifies are only sent for master zones. If explicit, notifies are sent only to servers explicitly listed using also-notify. If no, no notifies are sent. The notify option may also be specified in the zone statement, in which case it overrides the options notify statement. It would only be necessary to turn off this option if it caused slaves to crash.. recursion If yes, and a DNS query requests recursion, then the server will attempt to do all the work required to answer the query. If recursion is off and the server does not already know the answer, it will return a referral response. The default is yes. Note that setting recursion no does not prevent clients from getting data from the server's cache; it only prevents new data from being cached as an effect of client queries. Caching may still occur as an effect resolver category at level info. The default is no. request-sit This experimental option is obsolete. require-server-cookie Require a valid server cookie before sending a full response to a UDP request from a cookie aware client. BADCOOKIE is sent if there is a bad or no existent server cookie. answer-cookie When set to the default value of yes, COOKIE EDNS options will be sent when applicable in replies to client queries. If set to no, COOKIE EDNS options will not be sent in replies. This can only be set at the global options level, not per-view. talked option. nocookie-udp-size Sets the maximum size of UDP responses that will be sent to queries without a valid server COOKIE. A value below 128 will be silently raised to 128. The default value is 4096, but the max-udp-size option may further limit the response size. sit-secret This experimental option is obsolete. cookie-algorithm Set the algorithm to be used when generating the server cookie. One of "aes", "sha1" or "sha256". The default is "aes" if supported by the cryptographic library or otherwise "sha256". cookie-secret If set, this is a shared secret used for generating and verifying EDNS COOKIE options within an anycast cluster. If not set, the system will generate is used to generate new server cookies. The others will only be used to verify returned cookies. rfc2308-type1 Setting this to yes will cause the server to send NS records along with the SOA record for negative answers. The default is no. Not yet implemented in BIND 9. trust-anchor-telemetry Causes named to send specially-formed queries once per day to domains for which trust anchors have been configured via trusted-keys, managed-keys, will be able to see which resolvers have been updated to trust a new key; this may help them decide when it is safe to remove an old one. The default is yes. use-id-pool This option is obsolete. BIND 9 always allocates query IDs from a pool. use-ixfr This option is obsolete. If you need to disable IXFR to a particular server or servers, see the information on the provide-ixfr option in . See also . provide-ixfr See the description of provide-ixfr in . request-ixfr See the description of request-ixfr in . request-expire See the description of request-expire in . treat-cr-as-space This option was used in BIND 8 to make the server treat carriage return ("\r") characters the same way as a space or tab character, which have additional data, or when following CNAME and DNAME chains. When both of these options are set to yes (the default) and a query is being answered from authoritative data (a zone configured into the server), the additional data section of the reply will be filled in using data from other authoritative zones and from the cache. In some situations this is undesirable, such as when there is concern over the correctness of the cache, or in servers where slave zones may be added and modified by untrusted third parties. Also, avoiding the search for this additional data will speed up server operations at the possible expense of additional queries to resolve what would otherwise be provided in the additional section. For example, if a query asks for an MX record for host foo.example.com, and the record found is "MX 10 mail.example.net", normally the address records (A and AAAA) for mail.example.net will be provided as well, if known, even though they are not in the example.com zone. Setting these options to no disables this behavior and makes the server only search for additional data in the zone it answers from. These options are intended for use in authoritative-only servers, or in authoritative-only views. Attempts to set them to no without also specifying recursion no will cause the server to ignore the options and log a warning message. Specifying additional-from-cache no actually disables the use of the cache not only for additional data lookups but also when looking up the answer. This is usually the desired behavior in an authoritative-only server where the correctness of the cached data is an issue. When a name server is non-recursively queried for a name that is not below the apex of any served zone, it normally answers with an "upwards referral" to the root servers or the servers of some other known parent of the query name. Since the data in an upwards referral comes from the cache, the server will not be able to provide upwards referrals when additional-from-cache no has been specified. Instead, it will respond to such queries with REFUSED. This should not cause any problems since upwards referrals are not required for the resolution process. match-mapped-addresses If yes, then an IPv4-mapped IPv6 address will match now solves this problem internally. The use of this option is discouraged.. The default is no. The filter-aaaa-on-v4 option may also be specified in view statements to override the global filter-aaaa-on-v4 option. If yes, the DNS client is at an IPv4 address, in filter-aaaa, and if the response does not include DNSSEC signatures, then all AAAA records are deleted from the response. This filtering applies to all responses and not only authoritative responses. If break-dnssec, then AAAA records are deleted even when DNSSEC is enabled. As suggested by the name, this makes the response not verify, because the DNSSEC protocol is designed detect deletions. This mechanism can erroneously cause other servers to not give AAAA records to their clients. A recursing server with both IPv6 and IPv4 network connections that queries an authoritative server using this mechanism via IPv4 will be denied AAAA records even if its client is using IPv6. This mechanism is applied to authoritative as well as non-authoritative records. A client using IPv4 that is not allowed recursion can erroneously be given AAAA records because the server is not allowed to check for A records. Some AAAA records are given to IPv4 clients in glue records. IPv4 clients that are servers can then erroneously answer requests for AAAA records received via IPv4. filter-aaaa-on-v6 Identical to filter-aaaa-on-v4, except it filters AAAA responses to queries from IPv6 clients instead of IPv4 clients. To filter all responses, set both options to yes. ixfr-from-differences When yes and the server loads a new version of a master zone from its zone file or receives a new version of a slave file via zone transfer, it will compare the new version to the previous one and calculate a set of differences. The differences are then logged in the zone's journal file such that the changes can be transmitted to downstream slaves as an incremental zone transfer. By allowing incremental zone transfers to be used for non-dynamic zones, this option saves bandwidth at the expense of increased CPU and memory consumption at the master. In particular, if the new version of a zone is completely different from the previous one, the set of differences will be of a size comparable to the combined size of the old and new zone version, and the server will need to temporarily allocate memory to hold this complete difference set. ixfr-from-differences also accepts master and slave at the view and options levels which causes ixfr-from-differences to be enabled for all master or slave zones respectively. It is off by default. Note: if inline signing is enabled for a zone, the user-provided ixfr-from-differences setting is ignored for that zone. multi-master This should be set when you have multiple masters for a zone and the addresses refer to different machines. If yes, named will not log when the serial number on the master is less than what named currently schedule, according to the keys' timing metadata (see and ). The command rndc sign zonename causes named to load keys from the key repository and sign the zone with all keys that are active. rndc loadkeys zonename causes named to load keys from the key repository and schedule key maintenance events to occur in the future, but it does not sign the full zone immediately. Note: once keys have been loaded for a zone the first time, the repository will be searched for changes periodically, regardless of whether rndc loadkeys is used. The recheck interval is defined by dnssec-loadkeys-interval.) The default setting is auto-dnssec off. dnssec-enable This indicates whether DNSSEC-related resource records are to be returned by named. If set to no, named will not return DNSSEC-related resource records unless specifically queried for. The default is yes. dnssec-validation Enable DNSSEC validation in named. Note dnssec-enable also needs to be set to yes to be effective. If set to no, DNSSEC validation is disabled. If set to auto, DNSSEC validation is enabled, and a default trust anchor for the DNS root zone is used. If set to yes, DNSSEC validation is enabled, but a trust anchor must be manually configured using a trusted-keys or managed-keys statement. The default is yes. The default root trust anchor is stored in the file bind.keys. named will load that key at startup if dnssec-validation is set to auto. A copy of the file is installed along with BIND 9, and is current as of the release date. If the root key expires, a new copy of bind.keys can be downloaded from. To prevent problems if bind.keys is not found, the current trust anchor is also compiled in to named. Relying on this is not recommended, however, as it requires named to be recompiled with a new key when the root key expires.) named only loads the root key from bind.keys. The file cannot be used to store keys for other zones. The root key in bind.keys is ignored if dnssec-validation auto is not in use. Whenever the resolver sends out queries to an EDNS-compliant server, it always sets the DO bit indicating it can support DNSSEC responses even if dnssec-validation is off. dnssec-accept-expired Accept expired signatures when verifying DNSSEC signatures. The default is no. Setting this option to yes leaves named vulnerable to replay attacks. querylog Specify whether query logging should be started when named starts. If querylog is not specified, then the query logging is determined by the presence of the logging category queries. check-names This option is used to restrict the character set and syntax of certain domain names in master files and/or DNS responses received from the network. The default varies according to usage area. For master zones the default is fail. For slave zones the default is warn. For answers received from the network (response) the default is ignore. The rules for legal hostnames and mail domains are derived from RFC 952 and RFC 821 as modified by RFC 1123. check-names applies to the owner names of A, AAAA and MX records. It also applies to the domain names in the RDATA of NS, SOA, MX, and SRV records. It also applies to the RDATA of PTR records where the owner name indicated that it is a reverse lookup of a hostname (the owner name ends in IN-ADDR.ARPA, IP6.ARPA, or IP6.INT). check-dup-records Check master zones for records that are treated as different by DNSSEC but are semantically equal in plain DNS. The default is to warn. Other possible values are fail and ignore. check-mx Check whether the MX record appears to refer to a IP address. The default is to warn. Other possible values are fail and ignore. check-wildcard This option is used to check for non-terminal wildcards. The use of non-terminal wildcards is almost always as a result of a failure to understand the wildcard matching algorithm (RFC 1034). This option affects master zones. The default (yes) is to check for non-terminal wildcards and issue a warning. check-integrity Perform post load zone integrity checks on master zones. for publishing and can be suppressed with check-spf. check-mx-cname If check-integrity is set then fail, warn or ignore MX records that refer to CNAMES. The default is to warn. check-srv-cname If check-integrity is set then fail, warn or ignore SRV records that refer to CNAMES. The default is to warn. check-sibling When performing integrity checks, also check that sibling glue exists. The default is yes. check-spf If check-integrity is set then check that there is a TXT Sender Policy Framework record present (starts with "v=spf1") if there is an SPF record present. The default is warn. zero-no-soa-ttl When returning authoritative negative responses to SOA queries set the TTL of the SOA record returned in the authority section to zero. The default is yes. zero-no-soa-ttl-cache command will be ignored for that algorithm. dnssec-dnskey-kskonly When this option and update-check-ksk are both set to yes, only key-signing keys (that is, keys with the KSK bit set) will be used to sign the DNSKEY RRset at the zone apex. Zone-signing keys (keys without the KSK bit set) will be used to sign the remainder of the zone, but not the DNSKEY RRset. This is similar to the dnssec-signzone -x command line option. The default is no. If update-check-ksk is set to no, this option is ignored. try-tcp-refresh Try to refresh the zone using TCP if UDP queries fail. For BIND 8 compatibility, the default is yes. dnssec-secure-to-insecure Allow will be removed from the zone as well. If the zone uses NSEC3, then it is also necessary to delete the NSEC3PARAM RRset from the zone apex; this will cause the removal of all corresponding NSEC3 records. (It is expected that this requirement will be eliminated in a future release.) Note that if a zone has been configured with auto-dnssec maintain and the private keys remain accessible in the key repository, then the zone will be automatically signed again the next time named is started. Forwarding-domain basis, allowing for the global forwarding options to be overridden in a variety of ways. You can set particular domains to use different forwarders, or have a different forward only/first behavior, or not forward at all, see . Dual-stack Servers Dual-stack servers are used as servers of last resort to work around problems in reachability due the lack of support for either IPv4 or IPv6 on the host machine. dual-stack-servers Specifies host names or addresses of machines with access to both IPv4 and IPv6 transports. If a hostname is used, the server must be able to resolve the name using only the transport it has. If the machine is dual stacked, then the dual-stack-servers have no effect unless access to a transport has been disabled on the command line (e.g. named -4). Access Control Access to the server can be restricted based on the IP address of the requesting system. See for details on how to specify IP address lists. allow-notify Specifies which hosts are allowed to notify this server, a slave, of zone changes in addition to the zone masters. allow-notify may also be specified in the zone statement, in which case it overrides the options allow-notify statement. It is only meaningful for a slave zone. If not specified, the default is to process notify messages only from a zone's master. allow-query Specifies which hosts are allowed to ask ordinary DNS questions. allow-query may also be specified in the zone statement, in which case it overrides the options allow-query statement. If not specified, the default is to allow queries from all hosts. allow-query-cache is now used to specify access to the cache. allow-query-on Specifies which local addresses can accept ordinary DNS questions. This makes it possible, for instance, to allow queries on internal-facing interfaces but disallow them on external-facing ones, without necessarily knowing the internal network's addresses. Note that allow-query-on is only checked for queries that are permitted by allow-query. A query must be allowed by both ACLs, or it will be refused. allow-query-on may also be specified in the zone statement, in which case it overrides the options allow-query-on statement. If not specified, the default is to allow queries on all addresses. allow-query-cache is used to specify access to the cache. allow-query-cache Specifies which hosts are allowed to get answers from the cache. If allow-query-cache is not set then allow-recursion is used if set, otherwise allow-query is used if set unless recursion no; is set in which case none; is used, otherwise the default (localnets; localhost;) is used. allow-query-cache-on Specifies which local addresses can give answers from the cache. If not specified, the default is to allow cache queries on any address, localnets and localhost. allow-recursion Specifies which hosts are allowed to make recursive queries through this server. If allow-recursion is not set then allow-query-cache is used if set, otherwise allow-query is used if set, otherwise the default (localnets; localhost;) is used. allow-recursion-on Specifies which local addresses can accept recursive queries. If not specified, the default is to allow recursive queries on all addresses. allow-update Specifies which hosts are allowed to submit Dynamic DNS updates for master zones. The default is to deny updates from all hosts. Note that allowing updates based on the requestor's IP address is insecure; see for details. allow-update-forwarding Specifies which hosts are allowed to submit Dynamic DNS updates to slave zones to be forwarded to the master. The default is { none; }, which means that no update forwarding will be performed. To enable update forwarding, specify allow-update-forwarding { any; };. Specifying values other than { none; } or { any; } is usually counterproductive, since the responsibility for update access control should rest with the master server, not the slaves. Note that enabling the update forwarding feature on a slave server may expose master servers relying on insecure IP address based access control to attacks; see for more details. Specifies which hosts are allowed to receive zone transfers from the server. allow-transfer may also be specified in the zone statement, in which case it overrides the options allow-transfer statement. If not specified, the default is to allow transfers to all hosts. blackhole Specifies a list of addresses that the server will not accept queries from or use to resolve a query. Queries from these addresses will not be responded to. The default is none. filter-aaaa Specifies a list of addresses to which filter-aaaa-on-v4 and filter-aaaa-on-v6 apply. The default is any. keep-response-order Specifies a list of addresses to which the server will send responses to TCP queries in the same order in which they were received. This disables the processing of TCP queries in parallel. The default is none. no-case-compress Specifies a list of addresses which require responses to use case-insensitive compression. This ACL can be used when named needs to work with clients that do not comply with the requirement in RFC 1034 to use case-insensitive name comparisons when checking for matching domain names. If left undefined, the ACL defaults to none: case-insensitive compression will be used for all clients. If the ACL is defined and matches a client, then case will be ignored when compressing domain names in DNS responses sent to that client. This can result in slightly smaller responses: if a response contains the names "example.com" and "example.COM", case-insensitive compression would treat will not preserve the case of owner names of records: if a zone file defines records of different types with the same name, but the capitalization of the name is different (e.g., "" and ""), then all responses for that name will use the first version of the name that was used in the zone file. This limitation may be addressed in a future release. However, domain names specified in the rdata of resource records (i.e., records of type NS, MX, CNAME, etc) will always have their case preserved unless the client matches this ACL. resolver-query-timeout The amount of time in seconds that the resolver will spend attempting to resolve a recursive query before failing. The default and minimum is 10 and the maximum is 30. Setting it to 0 will result in the default being used. Interfaces The interfaces and ports that the server will answer queries from may be specified using the listen-on option. listen-on takes an optional port and an address_match_list of IPv4 addresses. (IPv6 addresses are ignored, with a logged warning.) IPv4 interfaces. The listen-on-v6 option is used to specify the interfaces and the ports on which the server will listen for incoming queries sent using IPv6. If not specified, the server will listen on port 53 on all IPv6 interfaces. only. IPv4 addresses specified in listen-on-v6 will be ignored, with a logged warning. Multiple listen-on-v6 options can be used. For example, listen-on-v6 { any; }; listen-on-v6 port 1234 { !2001:db8::/32; any; }; will enable the name server; }; Query Address If the server doesn't know the answer to a question, it will query other name servers. query-source specifies the address and port used for such queries. For queries sent over IPv6, there is a separate query-source-v6 option. If address is * (asterisk) or is omitted, a wildcard IP address (INADDR_ANY) will be used. If port is * or is omitted, a random port number from a pre-configured range is picked up and will be used for each query. The port range(s) is will check if the operating system provides a programming interface to retrieve the system's default range for ephemeral ports. If such an interface is available, named will use the corresponding system default range; otherwise, it will use its own defaults: use-v4-udp-ports { range 1024 65535; }; use-v6-udp-ports { range 1024 65535; }; Note: make sure the ranges will automatically be applied when named is reloaded. It is encouraged to configure use-v4-udp-ports and use-v6-udp-ports explicitly so that the ranges are sufficiently large and are reasonably independent from the ranges used by other applications. Note: the operational configuration where named runs may prohibit the use of some ports. For example, UNIX systems will not allow named running. The address specified in the query-source option is used for both UDP and TCP queries, but the port applies only to UDP queries. TCP queries always use a random unprivileged port. Solaris 2.5.1 and earlier does not support setting the source address for TCP sockets. See also transfer-source and notify-source. Zone Transfers BIND has mechanisms in place to facilitate zone transfers and set limits on the amount of load that transfers place on the system. The following options apply to zone transfers. also-notify Defines a global list of IP addresses of name servers that are also sent NOTIFY messages whenever a fresh copy of the zone is loaded, in addition to the servers listed in the zone's NS records. This helps to ensure that copies of the zones will quickly converge on stealth servers. Optionally, a port may be specified with each also-notify address lists can be used. If an also-notify list is given in a zone statement, it will override the options also-notify statement. When a zone notify statement is set to no, the IP addresses in the global also-notify list will not be sent NOTIFY messages for that zone. The default is the empty list (no global notification list). max-transfer-time-in Inbound zone transfers running longer than this many minutes will be terminated. The default is 120 minutes (2 hours). The maximum value is 28 days (40320 minutes). max-transfer-idle-in Inbound zone transfers making no progress in this many minutes will be terminated. The default is 60 minutes (1 hour). The maximum value is 28 days (40320 minutes). max-transfer-time-out Outbound zone transfers running longer than this many minutes will be terminated. The default is 120 minutes (2 hours). The maximum value is 28 days (40320 minutes). max-transfer-idle-out Outbound zone transfers making no progress in this many minutes will be terminated. The default is 60 minutes (1 hour). The maximum value is 28 days (40320 minutes). notify-rate The rate at which NOTIFY requests will be sent during normal zone maintenance operations. (NOTIFY requests due to initial zone loading are subject to a separate rate limit; see below.) The default is 20 per second. The lowest possible rate is one per second; when set to zero, it will be silently raised to one. startup-notify-rate The rate at which NOTIFY requests will be sent when the name server is first starting up, or when zones have been newly added to the nameserver. The default is 20 per second. The lowest possible rate is one per second; when set to zero, it will be silently raised to one. serial-query-rate Slave servers will periodically query master servers to find out if zone serial numbers have changed. Each such query uses a minute amount of the slave server's network bandwidth. To limit the amount of bandwidth used, BIND 9 limits the rate at which queries are sent. The value of the serial-query-rate option, an integer, is the maximum number of queries sent per second. The default is 20 per second. The lowest possible rate is one per second; when set to zero, it will be silently raised to one. serial-queries In BIND 8, the serial-queries option set the maximum number of concurrent serial number queries allowed to be outstanding at any given time. BIND 9 does not limit the number of outstanding serial queries and ignores the serial-queries option. Instead, it limits the rate at which the queries are sent as defined using the serial-query-rate option. transfer-format Zone transfers can be sent using two different formats, one-answer and many-answers. The transfer-format option is used on the master server to determine which format it sends. one-answer uses one DNS message per resource record transferred. many-answers packs as many resource records as possible into a message. many-answers is more efficient, but is only supported by relatively new slave servers, such as BIND 9, BIND 8.x and BIND 4.9.5 onwards. The many-answers format is also supported by recent Microsoft Windows nameservers. The default is many-answers. transfer-format may be overridden on a per-server basis by using the server statement. transfer-message-size This is an upper bound on the uncompressed size of DNS messages used in zone transfers over TCP. If a message grows larger than this size, additional messages will, and any values outside that range will be refused. The default value is 10. transfers-per-ns The maximum number of inbound zone transfers that can be concurrently transferring statement. transfer-source transfer-source determines which local address will-view or per-zone basis by including a transfer-source statement within the view or zone block in the configuration file. Solaris 2.5.1 and earlier does not support setting the source address for TCP sockets. transfer-source-v6 The same as transfer-source, except zone transfers are performed using IPv6. alt-transfer-source An alternate transfer source if the one listed in transfer-source fails and use-alt-transfer-source is set. If you do not wish the alternate transfer source to be used, you should set use-alt-transfer-source appropriately and you should not depend upon getting an answer back to the first refresh query., and optionally UDP port, will be used to send NOTIFY messages. This address must appear in the slave server's masters zone clause or in an allow-notify clause. This statement sets the notify-source for all zones, but can be overridden on a per-zone or per-view basis by including a notify-source statement within the zone or view block in the configuration file. Solaris 2.5.1 and earlier does not support setting the source address for TCP sockets. notify-source-v6 Like notify-source, but applies to notify messages sent to IPv6 addresses. UDP Port Lists use-v4-udp-ports, avoid-v4-udp-ports, use-v6-udp-ports, and avoid-v6-udp-ports specify a list of IPv4 and IPv6 UDP ports that will be used or not used as source ports for UDP messages. See about how the available ports are determined. For example, with the following configuration use-v6-udp-ports { range 32768 65535; }; avoid-v6-udp-ports { 40000; range 50000 60000; }; UDP ports of IPv6 messages sent from named will your. Operating System Resource Limits . The following options set operating system resource limits for the name server process. Some operating systems don't support some or any of the limits. On such systems, a warning will be issued if the unsupported limit is used. coresize The maximum size of a core dump. The default is default. datasize of limiting the amount of memory used by the server, but it can be used to raise an operating system data size limit that is too small by default. If you wish to limit the amount of memory used by the server, use the max-cache-size and recursive-clients options instead. files The maximum number of files the server may have open concurrently. The default is unlimited. stacksize The maximum amount of stack memory the server may use. The default is default. Server Resource Limits 9. max-journal-size Sets a maximum size for each journal file (see ). When the journal file approaches the specified size, some of the oldest transactions in the journal will be automatically removed. The largest permitted value is 2 gigabytes. The default is unlimited, which also means 2 gigabytes. This may also be set on a per-zone basis. max-records The maximum number of records permitted in a zone. The default is zero which means unlimited. host-statistics-max In BIND 8, specifies the maximum number of host statistics entries to be kept. Not implemented in BIND 9. recursive-clients The maximum number ("hard quota") of simultaneous recursive lookups the server will perform on behalf of clients. The default is 1000. Because each recursing client uses a fair bit of memory (on the order of 20 kilobytes), the value of the recursive-clients option may have to be decreased on hosts with limited memory. recursive-clients defines a "hard quota" limit for pending recursive clients: when more clients than this are pending, new incoming requests will not be accepted, and for each incoming request a previous pending request will also be dropped. A "soft quota" is also set. When this lower quota is exceeded, incoming requests are accepted, but for each one, a pending request will be dropped. If recursive-clients is greater than 1000, the soft quota is set to recursive-clients minus 100; otherwise it is set to 90% of recursive-clients. tcp-clients The maximum number of simultaneous client TCP connections that the server will accept. The default is 150. clients-per-query max-clients-per-query These set the initial value (minimum) and maximum number of recursive simultaneous clients for any given query (<qname,qtype,qclass>) that the server will accept before dropping additional clients. named will attempt to self tune this value and changes will be logged. The default values are 10 and 100. This value should reflect how many queries come in for a given name in the time it takes to resolve that name. If the number of queries exceed this value, named will assume that it is dealing with a non-responsive zone and will drop additional queries. If it gets a response after dropping queries, it will raise the estimate. The estimate will then be lowered in 20 minutes if it has remained unchanged. If clients-per-query is set to zero, then there is no limit on the number of clients per query and no queries will be dropped. If max-clients-per-query is set to zero, then there is no upper bound other than imposed by recursive-clients.. Optionally, this value may be followed by the keyword drop or fail, indicating whether queries which exceed the fetch quota for a zone will be dropped with no response, or answered with SERVFAIL. The default is drop. If fetches-per-zone is set to zero, then there is no limit on the number of fetches per query and no queries will-zone limit. The maximum number of simultaneous iterative queries that the server will allow or fail, indicating whether queries will be dropped with no response, or answered with SERVFAIL, when all of the servers authoritative for a zone are found to have exceeded the per-server quota. The default is fail. If fetches-per-server is set to zero, then there is no limit on the number of fetches per query and no queries will be dropped. The default is zero. The fetches-per-server quota is dynamically adjusted in response to detected congestion. As queries are sent to a server and are either answered or time out, an exponentially weighted moving average is calculated of the ratio of timeouts to responses. If the current average timeout ratio rises above a "high" threshold, then fetches-per-server is reduced for that server. If the timeout ratio drops below a "low" threshold, then fetches-per-server is increased. The fetch-quota-params options can be used to adjust the parameters for this calculation. fetch-quota-params Sets the parameters to use for dynamic resizing of the fetches-per-server quota in response to detected congestion. The first argument is an integer value indicating how frequently to recalculate the moving average of the ratio of timeouts to responses for each server. The default is 100, meaning we recalculate The number of file descriptors reserved for TCP, stdio, etc. This needs to be big enough to cover the number of interfaces named listens on plus tcp-clients, as well as to provide room for outgoing TCP queries and incoming zone transfers. The default is 512. The minimum value is 128 and the maximum value is 128 less than maxsockets (-S). This option may be removed in the future. This option has little effect on Windows. max-cache-size The maximum amount of memory to use for the server's cache, in bytes or % of total physical memory. When the amount of data in the cache reaches this limit, the server will cause records to expire prematurely based on an LRU based strategy so that the limit is not exceeded. The keyword unlimited, or the value 0, will place no limit on cache size; records will be purged from the cache only when their TTLs expire. Any positive values less than 2MB will be ignored and reset to 2MB. In a server with multiple views, the limit applies separately to the cache of each view. The default is 90%. On systems where detection of amount of physical memory is not supported values represented as % fall back to unlimited. Note that the detection of physical memory is done only once at startup, so named will not adjust the cache size if the amount of physical memory is changed during runtime. tcp-listen-queue The listen queue depth. The default and minimum is 10. If the kernel supports the accept filter "dataready" this also controls how many TCP connections that will be queued in kernel space waiting for some data before being passed to accept. Nonzero values less than 10 will be silently raised. A value of 0 may also be used; on most platforms this sets the listen queue length to a system-defined default value. Periodic Task Intervals cleaning-interval This interval is effectively obsolete. Previously, the server would remove expired resource records from the cache every cleaning-interval minutes. BIND 9 now manages cache memory in a more sophisticated manner and does not rely on the periodic cleaning any more. Specifying this option therefore has no effect on the server's behavior. heartbeat-interval The server will perform zone maintenance tasks for all zones marked as dialup whenever this interval expires. The default is 60 minutes. Reasonable values are up to 1 day (1440 minutes). The maximum value is 28 days (40320 minutes). If set to 0, no zone maintenance for these zones will occur. interface-interval. statistics-interval Name server statistics will be logged every statistics-interval minutes. The default is 60. The maximum value is 28 days (40320 minutes). If set to 0, no statistics will be logged. Not yet implemented in BIND 9. topology In BIND 8, this option indicated network topology so that preferential treatment could be given to the topologicaly closest name servers when sending queries. It is not implemented in BIND 9. The sortlist Statement The response to a DNS query may consist of multiple resource records (RRs) forming a resource record set (RRset). The name server will normally return the RRs within the RRset in an indeterminate order (but see the rrset-order statement in ). of the records placed into the response. The rrset-order statement permits configuration of the ordering of the records in a multiple record response. See also. random Records are returned in some random order. cyclic Records are returned in a cyclic round-robin order. If BIND is configured with the "--enable-fixed-rrset" option at compile time, then the initial ordering of the RRset will match the one specified in the zone file. For example: rrset-order { class IN type A name "host.example.com" order random; order cyclic; }; will cause, all records are returned in random order. In this release of BIND 9, the rrset-order statement does not support "fixed" ordering by default. Fixed ordering can be enabled at compile time by specifying "--enable-fixed-rrset" on the "configure" command line. Tuning lame-ttl Sets the number of seconds to cache a lame server indication. 0 disables caching. (This is NOT recommended.) The default is 600 (10 minutes) and the maximum value is 1800 (30 minutes). servfail-ttl seconds; any higher value will be silently reduced. The default is 1 second. max-ncache-ttl To reduce network traffic and increase performance, the server stores negative answers. max-ncache-ttl is used to set a maximum retention time for these answers in the server in seconds. The default max-ncache-ttl is 10800 seconds (3 hours). max-ncache-ttl cannot exceed 7 days and will be silently truncated to 7 days if set to a greater value. max-cache-ttl Sets the maximum time for which the server will cache ordinary (positive) answers in seconds. The default is 604800 (one week). A value of zero may cause all queries to return SERVFAIL, because of lost caches of intermediate RRsets (such as NS and glue AAAA/A records) in the resolution process. min-roots The minimum number of root servers that is required for a request for the root servers to be accepted. The default is 2. Not implemented in BIND 9. sig-validity-interval Specifies the number of days into the future when DNSSEC signatures automatically generated as a result of dynamic updates () will expire. There is an optional second field which specifies how long before expiry that the signatures will be regenerated. If not specified, the signatures will be regenerated at 1/4 of base interval. The second field is specified in days if the base interval is greater than 7 days otherwise it is specified in hours. The default base interval is 30 days giving a re-signing interval of 7 1/2 days. The maximum values are 10 years (3660 days). The signature inception time is unconditionally set to one hour before the current time to allow for a limited amount of clock skew. The sig-validity-interval should be, at least, several multiples of the SOA expire interval to allow for reasonable interaction between the various timer and expiry dates. sig-signing-nodes Specify the maximum number of nodes to be examined in each quantum when signing a zone with a new DNSKEY. The default is 100. sig-signing-signatures Specify a threshold number of signatures that will terminate processing a quantum when signing a zone with a new DNSKEY. The default is 10. sig-signing-type Specify a private RDATA type to be used when generating signing state records. The default is 65534. It is expected that this parameter may be removed in a future version once there is a standard type. Signing state records are used to internally by named to track the current state of a zone-signing process, i.e., whether it is still active or has been completed. The records can be inspected using the command rndc signing -list zone. Once named has master, giving slave server administrators little control over their contents. These options allow the administrator to set a minimum and maximum refresh and retry time in seconds per-zone, per-view, or globally. These options are valid for slave and stub zones, and clamp the SOA refresh and retry times to the specified values. The following defaults apply. min-refresh-time 300 seconds, max-refresh-time 2419200 seconds (4 weeks), min-retry-time 500 seconds, and max-retry-time 1209600 seconds (2 weeks). edns-udp-size Sets the maximum advertised EDNS UDP buffer size in bytes, to control the size of packets received from authoritative servers in response to recursive queries. Valid values are 512 to 4096 (values outside this range will be silently adjusted to the nearest value within it). The default value is 4096. The usual reason for setting edns-udp-size to a non-default value is to get UDP answers to pass through broken firewalls that block fragmented packets and/or block UDP DNS packets that are greater than 512 bytes. When named first queries a remote server, it will advertise a UDP buffer size of 512, as this has the greatest chance of success on the first try. If the initial response times out, named will try again with plain DNS, and if that is successful, it will be taken as evidence that the server does not support EDNS. After enough failures using EDNS and successes using plain DNS, named will default to plain DNS for future communications with that server. (Periodically, named will send an EDNS query to see if the situation has improved.) However, if the initial query is successful with EDNS advertising a buffer size of 512, then named will advertise progressively larger buffer sizes on successive queries, until responses begin timing out or edns-udp-size is reached. The default buffer sizes used by named are Sets the maximum EDNS UDP message size named will send in bytes. Valid values are 512 to 4096 (values outside this range will be silently adjusted to the nearest value within it). The default value is 4096. This value applies to responses sent by a server; to set the advertised buffer size in queries, see edns-udp-size. The usual reason for setting max-udp-size to will encourage additional TCP traffic to the nameserver. masterfile-format Specifies the file format of zone files (see ). The default value is text, which is the standard textual representation, except for slave zones, in which the default value is raw. Files in other formats than text are typically expected to be generated by the named-compilezone tool, or dumped by named. Note that when a zone file in a different format than text is loaded, named may omit some of the checks which would be performed for a file in the text format. In particular, check-names checks do not apply for the raw format. This means a zone file in the raw format must be generated with the same check level as that specified in the named configuration file. Also, map format files are loaded directly into memory via memory mapping, with only minimal checking. This statement sets the masterfile-format for all zones, but can be overridden on a per-zone or per-view basis by including a masterfile-format statement within the zone or view block in the configuration file. masterfile-style Specifies the formatting of zone files during dump when the masterfile-format format is most suitable when a zone file needs to be processed automatically by a script. The relative format is more human-readable, and is thus suitable when a zone is to be edited by hand. The default is relative. max-recursion-depth Sets the maximum number of levels of recursion that are permitted at any one time while servicing a recursive query. Resolving a name may require looking up a name server address, which in turn requires resolving another name, etc; if the number of indirections exceeds this value, the recursive query is terminated and returns SERVFAIL. The default is 7. max-recursion-queries Sets the maximum number of iterative queries that may be sent while servicing a recursive query. If more queries are sent, the recursive query is terminated and returns SERVFAIL. Queries to look up top level domains such as "com" and "net" and the DNS root zone are exempt from this limitation. The default is 75. notify-delay The delay, in seconds, between sending sets of notify messages for a zone. The default is five (5) seconds. The overall rate that NOTIFY messages are sent for all zones is controlled by serial-query-rate. max-rsa-exponent-size The maximum RSA exponent size, in bits, that will be accepted when validating. Valid values are 35 to 4096 bits. The default zero (0) is also accepted and is equivalent to 4096. prefetch When a query is received for cached data which is to expire shortly, named can refresh the data from the authoritative server immediately, ensuring that the cache always has an answer available. The prefetch specifies the "trigger" TTL value at which prefetch of the current query will take place: when a cache record with a lower TTL value is encountered during query processing, it will be refreshed. Valid trigger TTL values are 1 to 10 seconds. Values larger than 10 seconds will be silently reduced to 10. Setting a trigger TTL to zero (0) causes prefetch to be disabled. The default trigger TTL is 2. An optional second argument specifies the "eligibility" TTL: the smallest original TTL value that will be accepted for a record to be eligible for prefetching. The eligibility TTL must be at least six seconds longer than the trigger TTL; if it isn't, named will silently adjust it upward. The default eligibility TTL is 9. v6-bias When determining the next nameserver to try preference IPv6 nameservers by this many milliseconds. The default is 50 milliseconds. Built-in server information zones The server provides some helpful diagnostic information through a number of built-in zones under the pseudo-top-level-domain bind in the CHAOS class. These zones are part of a built-in view (see ) of class CHAOS which is separate from the default view of class IN. Most global configuration options (allow-query, etc) will apply to this view, but some are locally overridden: notify, recursion and allow-new-zones are always set to no, and rate-limit is set to allow three responses per second. If you need to disable these zones, use the options below, name server as found by the gethostname() function. The primary purpose of such queries is to identify which of a group of anycast servers is actually answering your queries. Specifying hostname none; disables processing of the queries. server-id The ID the server should report when receiving a Name Server Identifier (NSID) query, or; will cause named to use the hostname as found by the gethostname() function. The default server-id is none. Built-in Empty Zones The named server has some built-in empty zones (SOA and NS records only). These are for zones that should normally be answered locally and which queries should not be sent to the Internet's root servers. The official servers which cover these namespaces return NXDOMAIN responses to these queries. In particular, these cover the reverse namespaces for addresses from RFC 1918, RFC 4193, RFC 5737 and RFC 6598. They also include the reverse namespace for IPv6 local address (locally assigned), IPv6 link local addresses, the IPv6 loopback address and the IPv6 unknown address. The server will attempt to determine if a built-in zone already exists or is active (covered by a forward-only forwarding declaration) and will are settable at the view level and only apply to views of class IN. Disabled empty zones are only inherited from options if there are no disabled empty zones specified at the view level. To override the options list of disabled zones, you can disable the root zone at the view level, for example: disable-empty-zone "."; If you are using the address ranges covered here, you should already have reverse zones covering the addresses you use. In practice this appears to not be the case with many queries being made to the infrastructure servers for names in these spaces. So many in fact that sacrificial servers were needed to be deployed to channel the query load away from the infrastructure servers. The real parent servers for these zones should disable all empty zone under the parent zone they serve. For the real root servers, this is all built-in empty zones. This will enable them to return referrals to deeper in the tree. empty-server Specify what server name will appear in the returned SOA record for empty zones. If none is specified, then the zone's name will be used. empty-contact Specify what contact name will appear in the returned SOA record for empty zones. If none is specified, then "." will be used. empty-zones-enable Enable or disable all empty zones. By default, they are enabled. disable-empty-zone Disable individual empty zones. By default, none are disabled. This option can be specified multiple times. Additional Section Caching The additional section cache, also called acache, is an internal cache to improve the response performance of BIND 9. When additional section caching is enabled, BIND 9 will cache an internal short-cut to the additional section content for each answer RR. Note that acache is an internal caching mechanism of BIND 9, and is not related to the DNS caching server function. Additional section caching does not change the response content (except the RRsets ordering of the additional section, see below), but can improve the response performance significantly. It is particularly effective when BIND 9 acts as an authoritative server for a zone that has many delegations with many glue RRs. In order to obtain the maximum performance improvement from additional section caching, setting additional-from-cache to no is recommended, since the current implementation of acache does not short-cut of additional section information from the DNS cache data. One obvious disadvantage of acache is that it requires much more memory for the internal cached data. Thus, if the response performance does not matter and memory consumption is much more critical, the acache mechanism can be disabled by setting acache-enable to no. It is also possible to specify the upper limit of memory consumption for acache by using max-acache-size. Additional section caching also has a minor effect on the RRset ordering in the additional section. Without acache, cyclic order is effective for the additional section as well as the answer and authority sections. However, additional section caching fixes the ordering when it first caches an RRset for the additional section, and the same ordering will be kept in succeeding responses, regardless of the setting of rrset-order. The effect of this should be minor, however, since an RRset in the additional section typically only contains a small number of RRs (and in many cases it only contains a single RR), in which case the ordering does not matter much. The following is a summary of options related to acache. acache-enable If yes, additional section caching is enabled. The default value is no. acache-cleaning-interval The server will remove stale cache entries, based on an LRU based algorithm, every acache-cleaning-interval minutes. The default is 60 minutes. If set to 0, no periodic cleaning will occur. max-acache-size The maximum amount of memory in bytes to use for the server's acache. When the amount of data in the acache reaches this limit, the server will clean more aggressively so that the limit is not exceeded. In a server with multiple views, the limit applies separately to the acache of each view. The default is 16M. Content Filtering will be accepted regardless of the filter setting. Likewise, if the alias name is a subdomain of the corresponding zone, the deny-answer-aliases filter will will be silently ignored. If a response message is rejected due to the filtering, the entire message is discarded without being cached, and a SERVFAIL error will be returned to the client. This filtering is intended to prevent "DNS rebinding attacks," in which an attacker, in response to a query for a domain name the attacker controls, returns an IP address within your own network or an alias name within your own domain. A naive web browser or script could then serve as an unintended proxy, allowing the attacker to get access to an internal node of your local network that couldn't be externally accessed otherwise. See the paper available at for more details about the attacks. For example, if you own a domain named "example.net" and your internal network uses an IPv4 prefix 192.0.2.0/24, you might specify the following rules: deny-answer-addresses { 192.0.2.0/24; } except-from { "example.net"; }; deny-answer-aliases { "example.net"; }; If an external attacker lets a web browser in your will be ignored. On the other hand, if the browser looks up a legitimate internal web server "" and the following response is returned to the BIND 9 server. A 192.0.2.2 it will be accepted since the owner name "" matches the except-from element, "example.net". Note that this is not really an attack on the DNS per se. In fact, there is nothing wrong for an "external" name to be mapped to your "internal" IP address or domain name from the DNS point of view. It might actually be provided for a legitimate purpose, such as for debugging. As long as the mapping is provided by the correct owner, it is not possible or does not make sense to detect whether the intent of the mapping is legitimate or not you are very sure you have no other choice and the attack is a real threat for your applications. Care should be particularly taken if you want to use this option for addresses within 127.0.0.0/8. These addresses are obviously "internal", but many applications conventionally rely on a DNS mapping from some name to such an address. Filtering out DNS records containing this address spuriously can break such applications. Response Policy Zone (RPZ) Rewriting 32 on the number of policy zones in a single response-policy option; more than that is a configuration error. relativized to the policy zone origin name address relativized to the RPZ origin name. NSIP triggers match IP addresses in A and AAAA RRsets for domains that can be checked against NSDNAME policy records. RPZ-NSIP NSIP triggers match the IP addresses of authoritative servers. They are enncoded like IP triggers, except as subdomains of rpz-nsip. NSDNAME and NSIP triggers are checked only for names with at least min-ns-dots dots. The default value of min-ns-dots is 1, to exclude top level domains. If a name server's IP address is not yet known, named will recursively look up the IP address before applying an RPZ-NSIP rule. This can cause a processing delay. To speed up processing at the cost of precision, the nsip-wait-recurse option can be used: when set to no, RPZ-NSIP rules will only be applied when a name servers's IP address has already been looked up and cached. If a server's IP address is not in the cache, then the RPZ-NSIP rule will be ignored, but the address will be looked up in the background, and the rule will be applied to subsequent queries. The default is yes, meaning RPZ-NSIP rules should always be CNAME whose target is the wildcard top-level domain (*.). It rewrites the response to NODATA or ANCOUNT=1. Local Data A set of ordinary DNS records can be used to answer queries. Queries for record types not the set are answered with NODATA. A special form of local data is a CNAME whose target is a wildcard such as *.example.com. It is used as if were an ordinary CNAME after the asterisk (*) has been replaced with the query name. The purpose for this special form is query logging in the walled garden's authority will be written (or not) according to any triggered policy records that are not disabled. Disabled policy zones should appear first, because they will often not be logged if a higher precedence trigger is found first. PASSTHRU, DROP, TCP-Only, NXDOMAIN, and NODATA override with the corresponding per-record policy. CNAME domain request default behavior can cost significant time. The qname-wait-recurse no option overrides that default or not RRSIG records were found during resolution. Using this option can cause error responses such as SERVFAIL to appear to be rewritten, since no recursion is being done to discover problems at the authoritative server. The TTL of a record modified by RPZ policies is set from the TTL of the relevant record in policy zone. It is then limited to a maximum value. The max-policy-ttl clause changes the maximum seconds from its default of 5. For example, you9. Response Rate Limiting, all responses are dropped. A value of 1 causes every response to slip; values between 2 and 10 cause every n, then. Rate limiters for different name spaces maintain separate counters: If, for example, there is a rate-limit statement for "com" and another for "example.com", queries matching "example.com" will not be debited against the rate limiter for "com". If a rate-limit statement does not specify a domain, then it applies to the root domain (".") and thus affects the entire DNS namespace, except those portions covered by other rate-limit statements. Communities of DNS clients can be given their own parameters or no rate limiting by putting rate-limit statements in view statements instead of the global option statement. A rate-limit statement in a view replaces, rather than supplementing, STMP make truncated by rate limits are included in RateSlipped and RespTruncated. Named supports NXDOMAIN redirection via two methods: Redirect zone Redirect namespace With both methods you have the original NXDOMAIN response and the replacement data or a NXDOMAIN indicating that there is no replacement. If both a redirect zone and a redirect namespace are configured, the redirect zone is tried first. server Statement Grammar server Statement Definition and Usage you discover that a remote server is giving out bad data, marking it as bogus will prevent further queries to it. The default value of bogus is no. The provide-ixfr clause determines whether the local server, acting as master, will respond with an incremental zone transfer when the given remote server, a slave, requests it. If set to yes, incremental transfer will be provided whenever possible. If set to no, all transfers to the remote server will be non-incremental. If not set, the value of the provide-ixfr option in the view or global options block is used as a default. The request-ixfr clause determines whether the local server, acting as a slave, will request incremental zone transfers from the given remote server, a master. If not set, the value of the request-ixfr option in the view or global options block is used as a default. It may also be set in the zone block and, if set there, it will override the global or view setting for that zone. IXFR requests to servers that do not support IXFR will master and slave claim to support it, for example if one of the servers is buggy and crashes or corrupts data when IXFR is used. The request-expire clause determines whether the local server, when acting as a slave, will request the EDNS EXPIRE value. The EDNS EXPIRE value indicates the remaining time before the zone data will expire and need to be be refreshed. This is used when a secondary server transfers a zone from another secondary server; when transferring from the primary, the expiration timer is set from the EXPIRE field of the SOA record instead. The default is yes. The edns clause determines whether the local server will attempt will be silently adjusted to the nearest value within it). This option is useful when you wish to advertise a different value to this server than the value you advertise globally, for example, when there is a firewall at the remote site that is blocking large replies. (Note: Currently, this sets a single UDP size for all packets sent to the server; named will will will be silently adjusted. This option will not be needed until higher EDNS versions than 0 are in use.. The tcp-only option sets the transport protocol to TCP. The default is to use the UDP transport and to fallback on TCP only when a truncated response is received. The server supports two zone transfer methods. The first, one-answer, uses one DNS message per resource record transferred. many-answers packs as many resource records as possible into a message. many-answers is more efficient, but is only known to be understood by BIND 9, BIND 8.x, and patched versions of BIND 4.9.5. You can specify which method to use for a server with the transfer-format option. If transfer-format is not specified, the transfer-format specified by the options statement will (TSIG, ) when talking to the remote server. When a request is sent to the remote server, a request signature will will add a NSID EDNS option to requests sent to the server. This overrides request-nsid set at the view or option level. The send-cookie clause determines whether the local server will add a COOKIE EDNS option to requests sent to the server. This overrides send-cookie set at the view or option level. The named server may determine that COOKIE is not supported by the remote server and not add a COOKIE EDNS option to requests. statistics-channels Statement Grammar statistics-channels Statement Definition and Usage The statistics-channels statement declares communication channels to be used by system administrators to get access to statistics information of the name server. This statement intends will fail no port is specified, port 80 is used for HTTP channels. The asterisk "*" cannot be used for ip_port. The attempt of opening a statistics channel will). trusted-keys Statement Grammar trusted-keys Statement Definition and Usage The trusted-keys statement defines DNSSEC security roots. DNSSEC is described in . A security root is defined when the public key for a non-authoritative zone is known, but cannot be securely obtained through DNS, either because it is the DNS root zone or because its parent zone is unsigned. Once a key has been configured as a trusted key, it is treated as if it had been validated and proven secure. The resolver attempts DNSSEC validation on all DNS data in subdomains of a security root. All keys (and corresponding zones) listed in trusted-keys are deemed to exist regardless of what parent zones say. Similarly for all keys listed in trusted-keys only those keys are used to validate the DNSKEY RRset. The parent's DS RRset will not be used. The trusted-keys statement can contain multiple key entries, each consisting of the key's domain name, flags, protocol, algorithm, and the Base64 representation of the key data. Spaces, tabs, newlines and carriage returns are ignored in the key data, so the configuration may be split up into multiple lines. trusted-keys may be set at the top level of named.conf or within a view. If it is set in both places, they are additive: keys defined at the top level are inherited by all views, but keys defined in a view are only used within that view. Validation below specified names can be temporarily disabled by using rndc nta. managed-keys Statement Grammar managed-keys Statement Definition and Usage The managed-keys statement, like trusted-keys, defines DNSSEC security roots. The difference is that managed-keys can be kept up to date automatically, without intervention from the resolver operator. Suppose, for example, that a zone's key-signing key was compromised, and the zone owner had to revoke and replace the key. A resolver which had the old key in a trusted-keys statement would be unable to validate this zone any longer; it would reply with a SERVFAIL response code. This would continue until the resolver operator had updated the trusted-keys statement with the new key. If, however, the zone were listed in a managed-keys statement instead, then the zone owner could add a "stand-by" key to. A managed-keys statement contains a list of the keys to be managed, along with information about how the keys are to be initialized for the first time. The only initialization method currently supported is initial-key. This means the managed-keys statement must contain a copy of the initializing key. (Future releases may allow keys to be initialized by other methods, eliminating this requirement.) Consequently, a managed-keys statement appears similar to a trusted-keys, differing in the presence of the second field, containing the keyword initial-key. The difference is, whereas the keys listed in a trusted-keys continue to be trusted until they are removed from named.conf, an initializing key listed in a managed-keys statement is only trusted once: for as long as it takes to load the managed key database and start the RFC 5011 key maintenance process. The first time named runs with a managed key configured in named.conf, it fetches the DNSKEY RRset directly from the zone apex, and validates it using the key specified in the managed-keys statement. If the DNSKEY RRset is validly signed, then it is used as the basis for a new managed keys database. From that point on, whenever named runs, it sees the managed-keys statement, checks to make sure RFC 5011 key maintenance has already been initialized for the specified domain, and if so, it simply moves on. The key specified in the managed-keys statement is not used to validate answers; it has been superseded by the key or keys stored in the managed keys database. The next time named runs after a name has been removed from the managed-keys statement, the corresponding zone will be removed from the managed keys database, and RFC 5011 key maintenance will no longer be used for that domain. In the current implementation, the managed keys database is stored as a master-format zone file. On servers which do not use views, this file is named managed-keys.bind. When views are in use, there will be a separate managed keys database for each view; the filename will be the view name (or, if a view name contains characters which would make it illegal as a filename, a hash of the view name), followed by the suffix .mkeys. When the key database is changed, the zone is updated. As with any other dynamic zone, changes will be written into a journal file, e.g., managed-keys.bind.jnl or internal.mkeys.jnl. Changes are committed to the master file as soon as possible afterward; this will usually occur within 30 seconds. So, will automatically initialize a managed. view Statement Grammar view view_name [ class ] { match-clients { address_match_list } ; match-destinations { address_match_list } ; match-recursive-only yes_or_no ; [ view_option ; ... ] [ zone_statement ; ... ] } ; view Statement Definition and Usage will will be resolved in the context of the first view that it matches. Zones defined within a view statement will only be will apply"; }; }; zone Statement Grammar zone Statement Definition and Usage Zone Types The type keyword is required for the zone configuration unless it is an in-view configuration. Its acceptable values include: delegation-only, forward, hint, master, redirect, slave, static-stub, and stub. master The server has a master copy of the data for the zone and will be able to provide authoritative answers for it. slave A slave zone is a replica of a master zone. The masters list specifies one or more IP addresses of master servers that the slave master can also be done with per-server TSIG keys. If a file is specified, then the replica will slave server for the zone example.com might place the zone contents into a file called ex/example.com where ex/ is just the first two letters of the zone name. (Most operating systems behave very slowly if you put 100000 files into a single directory.) stub1918 addressing may be configured with stub zones for 10.in-addr.arpa to use a set of internal name servers as the authoritative servers for that domain. static-stub A static-stub zone is similar to a stub zone with the following exceptions: the zone data is statically configured, rather than transferred from a master server; when recursion is necessary for a query that matches a static-stub zone, the locally configured data (nameserver names and glue addresses) is always used even if different authoritative information is cached. Zone data is configured via the server-addresses and server-names zone options. The zone data is maintained in the form of NS and (if necessary) glue A or AAAA RRs internally, which can be seen by dumping zone databases by rndc dumpdb -all. The configured RRs are considered local configuration parameters rather than public data. Non recursive queries (i.e., those with the RD bit off) to a static-stub zone are therefore prohibited and will be responded with REFUSED. Since the data is statically configured, no zone maintenance action takes place for a static-stub zone. For example, there is no periodic refresh attempt, and an incoming notify message will be rejected with an rcode of NOTAUTH. Each static-stub zone is configured with internally generated NS and (if necessary) glue A or AAAA RRs forward re-specify the global forwarders. hint The initial set of root name servers is specified using a "hint zone". When the server starts up, defaults hints. redirect Redirect zones are used to provide answers to queries when normal resolution would result in NXDOMAIN being returned. Only one redirect zone is supported per view. allow-query can be used to restrict which clients see these answers. If the client has requested DNSSEC records (DO=1) and the NXDOMAIN response is signed then no substitution will occur. To redirect all NXDOMAIN responses to 100.100.100.2 and 2001:ffff:ffff::100.100.100.2, one would configure a type redirect zone named ".", with the zone file containing wildcard records that point to the desired addresses: "*. IN A 100.100.100.2" and "*. IN AAAA 2001:ffff:ffff::100.100.100.2". To redirect all Spanish names (under .ES) one would use similar entries but with the names "*.ES." instead of "*.". To redirect all commercial Spanish names (under COM.ES) one would use wildcard entries called "*.COM.ES.". Note that the redirect zone supports all possible types; it is not limited to A and AAAA records. Because redirect zones are not referenced directly by name, they are not kept in the zone lookup table with normal master and slave zones. Consequently, it is not currently possible to use rndc reload zonename to reload a redirect zone. However, when using rndc reload without specifying a zone name, redirect zones will be reloaded along with other zones. delegation-only This is used to enforce the delegation-only status of infrastructure zones (e.g. COM, NET, ORG). Any answer that is received without an explicit or implicit delegation in the authority section will be treated as NXDOMAIN. This does not apply to the zone apex. This should not be applied to leaf zones. delegation-only has no effect on answers received from forwarders. See caveats in . Class. Zone Options allow-notify See the description of allow-notify in . allow-query See the description of allow-query in . allow-query-on See the description of allow-query-on in . allow-transfer See the description of allow-transfer in . allow-update See the description of allow-update in . update-policy Specifies a "Simple Secure Update" policy. See . allow-update-forwarding See the description of allow-update-forwarding in . also-notify Only meaningful if notify is active for this zone. The set of machines that will receive a DNS NOTIFY message for this zone is made up of all the listed name servers (other than the primary master) for the zone plus any IP addresses specified with also-notify. A port may be specified with each also-notify address to send the notify messages to a port other than the default of 53. A TSIG key may also be specified to cause the NOTIFY to be signed by the given key. also-notify is not meaningful for stub zones. The default is the empty list.. check-mx See the description of check-mx in . check-spf See the description of check-spf in . check-wildcard See the description of check-wildcard in . check-integrity See the description of check-integrity in . check-sibling See the description of check-sibling in . zero-no-soa-ttl See the description of zero-no-soa-ttl in . update-check-ksk See the description of update-check-ksk in . dnssec-loadkeys-interval See the description of dnssec-loadkeys-interval in . dnssec-update-mode See the description of dnssec-update-mode in . dnssec-dnskey-kskonly See the description of dnssec-dnskey-kskonly in . try-tcp-refresh See the description of try-tcp-refresh in . database Specify the type of database to be used for storing the zone data. The string following the database keyword in . delegation-only The flag only applies to forward, hint and stub zones. If set to yes, then the zone will also be treated as if it is also a delegation-only type zone. See caveats in . file Set the zone's filename. In master, hint, and redirect zones which do not have masters defined, zone data is loaded from this file. In slave, stub, and redirect zones which do have masters defined, zone data is retrieved from another server and saved in this file. This option is not applicable to other zone types. forward Only meaningful if the zone has a forwarders list. The only value causes the lookup to fail after trying the forwarders and getting no answer, while first would allow a normal lookup to be tried. forwarders Used to override the list of global forwarders. If it is not specified in a zone of type forward, no forwarding is done for the zone and the global options are not used. ixfr-base Was used in BIND 8 to specify the name of the transaction log (journal) file for dynamic update and IXFR. BIND 9 ignores the option and constructs the name of the journal file by appending ".jnl" to the name of the zone file. ixfr-tmp-file Was an undocumented option in BIND 8. Ignored in BIND 9. journal Allow the default journal's filename to be overridden. The default is the zone's filename with ".jnl" appended. This is applicable to master and slave zones. max-journal-size See the description of max-journal-size in . max-records See the description of max-records in . max-transfer-time-in See the description of max-transfer-time-in in . max-transfer-idle-in See the description of max-transfer-idle-in in . max-transfer-time-out See the description of max-transfer-time-out in . max-transfer-idle-out See the description of max-transfer-idle-out in . notify See the description of notify in . notify-delay See the description of notify-delay in . notify-to-soa See the description of notify-to-soa in . pubkey In BIND 8, this option was intended for specifying a public zone key for verification of signatures in DNSSEC signed zones when they are loaded from disk. BIND 9 does not verify signatures on load and ignores the option. zone-statistics See the description of zone-statistics in . server-addresses Only meaningful for static-stub zones. This is a list of IP addresses to which queries should be sent in recursive resolution for the zone. A non empty list for this option will internally configure the apex NS RR with associated glue A or AAAA RRs. For example, if "example.com" is configured as a static-stub zone with 192.0.2.1 and 2001:db8::1234 in a server-addresses option, the following RRs will be internally configured. example.com. NS example.com. example.com. A 192.0.2.1 example.com. AAAA 2001:db8::1234 These records are internally used to resolve names under the static-stub zone. For instance, if the server receives a query for "" with the RD bit on, the server will initiate recursive resolution and send queries to 192.0.2.1 and/or 2001:db8::1234. server-names Only meaningful for static-stub zones. This is a list of domain names of nameservers that act as authoritative servers of the static-stub zone. These names will be resolved to IP addresses when named needs to send queries to these servers. To make this supplemental resolution successful, these names must not be a subdomain of the origin name of static-stub zone. That is, when "example.net" is the origin of a static-stub zone, "ns.example" and "master.example.com" can be specified in the server-names option, but "ns.example.net" cannot, and will be rejected by the configuration parser. A non empty list for this option will internally configure the apex NS RR with the specified names. For example, if "example.com" is configured as a static-stub zone with "ns1.example.net" and "ns2.example.net" in a server-names option, the following RRs will be internally configured. example.com. NS ns1.example.net. example.com. NS ns2.example.net. These records are internally used to resolve names under the static-stub zone. For instance, if the server receives a query for "" with the RD bit on, the server initiate recursive resolution, resolve "ns1.example.net" and/or "ns2.example.net" to IP addresses, and then send queries to (one or more of) these addresses. sig-validity-interval See the description of sig-validity-interval in . sig-signing-nodes See the description of sig-signing-nodes in . sig-signing-signatures See the description of sig-signing-signatures in . sig-signing-type See the description of sig-signing-type in . transfer-source See the description of transfer-source in . transfer-source-v6 See the description of transfer-source-v6 in . alt-transfer-source See the description of alt-transfer-source in . alt-transfer-source-v6 See the description of alt-transfer-source-v6 in . use-alt-transfer-source See the description of use-alt-transfer-source in . notify-source See the description of notify-source in . notify-source-v6 See the description of notify-source-v6 in . min-refresh-time max-refresh-time min-retry-time max-retry-time See the description in . ixfr-from-differences See the description of ixfr-from-differences in . (Note that the ixfr-from-differences master and slave choices are not available at the zone level.) key-directory See the description of key-directory in . auto-dnssec See the description of auto-dnssec in . serial-update-method See the description of serial-update-method in . in . masterfile-format See the description of masterfile-format in . max-zone-ttl See the description of max-zone-ttl in . dnssec-secure-to-insecure See the description of dnssec-secure-to-insecure in . Dynamic Update Policies BIND 9 supports two alternative methods of granting clients the right to perform dynamic updates to a zone, configured by the allow-update and update-policy option, respectively. The allow-update clause is a simple access control list. Any client that matches the ACL is granted permission to update any record in the zone. The update-policy clause allows more fine-grained control over client source address. update-policy rules are only meaningful for zones of type master, and are not allowed in any other zone type. It is a configuration error to specify both allow-update and update-policy at the same time. A pre-defined update-policy rule can be switched on with the command update-policy local;. Using this in a zone causes named to generate a TSIG session key when starting up and store will be set to allow that key to change any record within the zone. Assuming the key name is "local-ddns", this policy is equivalent to: update-policy { grant local-ddns zonesub any; }; ...with the additional restriction that only clients connecting from the local system will be permitted to send updates. Note that only one session key is generated by named; all zones configured to use update-policy local will will statement appears. This obviates the need to type the zone name twice, and enables the use of a standard update-policy statement rule type is most useful when allowing one key per name to update, where the key has the same name as the record to be updated. In this case, the identity field can be specified as * (an asterisk). selfsub This rule is similar to self except that subdomains of self can also be updated. selfwild This rule is similar to self except that only subdomains of self can be updated. ms-self When a client sends an UPDATE using a Windows machine principal (for example, 'machine$@REALM'), this rule allows records with the absolute name of 'machine.REALM' to be updated. The realm to be matched is specified in the identity field. The name field has no effect on this rule; it should be set to "." as a placeholder. For example, grant EXAMPLE.COM ms-self . A AAAA allows any machine with a valid principal in the realm EXAMPLE.COM to for the zone "example.com" includes grant EXAMPLE.COM ms-subdomain hosts.example.com. A AAAA, any machine with a valid principal in the realm EXAMPLE.COM will be able to update address records at or below "hosts.example.com". krb5-self When a client sends an UPDATE using a Kerberos machine principal (for example, 'host/machine@REALM'), this rule allows records with the absolute name of 'machine' to be updated provided it has been authenticated by REALM. This is similar but not identical to ms-self due to the 'machine' part allows any machine with a valid principal in the realm EXAMPLE.COM to update its own address records. krb5-selfsub This is similar to krb5-self except it also allows updates to any subdomain of the name specified in the 'machine' part and ip6.arpa namespaces match the name to be updated. The identity field must match that name. The name field should be set to ".". Note that, since identity is based on the client's IP address, it is not necessary for update request messages to be signed.pa reverse tree. The identity field must match the 6to4 prefix in ip6.arpa. The name field should be set to ".". Note that, since identity is based on the client's IP address, it is not necessary for update request messages to be signed. In addition, if specified for an ip6.arpa name outside of the 2.0.0.2.ip6.arpa namespace, the corresponding /48 reverse name can be updated. For example, TCP/IPv6 connections from 2001:DB8:ED0C::/48 can update records at C.0.D.E.8.B.D.0.1.0.0.2.ip6.arpa. It is theoretically possible to spoof these TCP sessions.. Multiple views When multiple views are in use, a zone may be referenced by more than one of them. Often, the views will changing the zone object itself.) Zone level acls (e.g. allow-query, allow-transfer) and other configuration details of the zone are all set in the view the referenced zone is defined in. Care need to be taken to ensure that acls are wide enough for all views referencing the zone. An in-view zone cannot be used as a response policy zone. An in-view zone is not intended to reference a forward zone. Zone File Types of Resource Records and When to Use Them This section, largely borrowed from RFC 1034, describes the concept of a Resource Record (RR) and explains when each is used. Since the publication of RFC 1034, several new RRs have been identified and implemented in the DNS. These are also included. Resource Records and .. The following are types of valid RRs: A A host address. In the IN class, this is a 32-bit IP address. Described in RFC 1035. AAAA IPv6 address. Described in RFC 1886. A6 IPv6 address. This can be a partial address (a suffix) and an indirection to the name where the rest of the address (the prefix) can be found. Experimental. Described in RFC 2874. AFSDB Location of AFS database servers. Experimental. Described in RFC 1183. AMTRELAY Automatic Multicast Tunneling Relay discovery record. Work in progress draft-ietf-mboned-driad-amt-discovery. APL Address prefix list. Experimental. Described in RFC 3123. ATMA ATM Address. AVC Application Visibility and Control record. CAA Identifies which Certificate Authorities can issue certificates for this domain and what rules they need to follow when doing so. Defined in RFC 6844. CDNSKEY Identifies which DNSKEY records should be published as DS records in the parent zone. CDS Contains the set of DS records that should be published by the parent zone. CERT Holds a digital certificate. Described in RFC 2538. CNAME Identifies the canonical name of an alias. Described in RFC 1035. CSYNC Child-to-Parent Synchronization in DNS as described in RFC 7477. DHCID Is used for identifying which DHCP client is associated with this name. Described in RFC 4701. DLV A DNS Look-aside Validation record which contains the records that are used as trust anchors for zones in a DLV namespace. Described in RFC 4431. DNAME Replaces the domain name specified with another name to be looked up, effectively aliasing an entire subtree of the domain name space rather than a single record as in the case of the CNAME RR. Described in RFC 2672. DNSKEY Stores a public key associated with a signed DNS zone. Described in RFC 4034. DOA Implements the Digital Object Architecture over DNS. Experimental. DS Stores the hash of a public key associated with a signed DNS zone. Described in RFC 4034. EID End Point Identifier. EUI48 A 48-bit EUI address. Described in RFC 7043. EUI64 A 64-bit EUI address. Described in RFC 7043. GID Reserved. GPOS Specifies the global position. Superseded by LOC. HINFO Identifies the CPU and OS used by a host. Described in RFC 1035. HIP Host Identity Protocol Address. Described in RFC 5205. IPSECKEY Provides a method for storing IPsec keying material in DNS. Described in RFC 4025. ISDN Representation of ISDN addresses. Experimental. Described in RFC 1183. KEY Stores a public key associated with a DNS name. Used in original DNSSEC; replaced by DNSKEY in DNSSECbis, but still used with SIG(0). Described in RFCs 2535 and 2931. KX Identifies a key exchanger for this DNS name. Described in RFC 2230. L32 Holds 32-bit Locator values for Identifier-Locator Network Protocol. Described in RFC 6742. L64 Holds 64-bit Locator values for Identifier-Locator Network Protocol. Described in RFC 6742. LOC For storing GPS info. Described in RFC 1876. Experimental. LP Identifier-Locator Network Protocol. Described in RFC 6742. MB Mail Box. Historical. MD Mail Destination. Historical. MF Mail Forwarder. Historical. MG Mail Group. Historical. MINFO Mail Information. MR Mail Rename. Historical. MX Identifies a mail exchange for the domain with a 16-bit preference value (lower is better) followed by the host name of the mail exchange. Described in RFC 974, RFC 1035. NAPTR Name authority pointer. Described in RFC 2915. NID Holds values for Node Identifiers in Identifier-Locator Network Protocol. Described in RFC 6742. NINFO Contains zone status information. NIMLOC Nimrod Locator. NSAP A network service access point. Described in RFC 1706. NSAP-PTR Historical. NS The authoritative name server for the domain. Described in RFC 1035. NSEC Used in DNSSECbis to securely indicate that RRs with an owner name in a certain name interval do not exist in a zone and indicate what RR types are present for an existing name. Described in RFC 4034. NSEC3 Used in DNSSECbis to securely indicate that RRs with an owner name in a certain name interval do not exist in a zone and indicate what RR types are present for an existing name. NSEC3 differs from NSEC in that it prevents zone enumeration but is more computationally expensive on both the server and the client than NSEC. Described in RFC 5155. NSEC3PARAM Used in DNSSECbis to tell the authoritative server which NSEC3 chains are available to use. Described in RFC 5155. NULL This is an opaque container. NXT Used in DNSSEC to securely indicate that RRs with an owner name in a certain name interval do not exist in a zone and indicate what RR types are present for an existing name. Used in original DNSSEC; replaced by NSEC in DNSSECbis. Described in RFC 2535. OPENPGPKEY Used to hold an OPENPGPKEY. PTR A pointer to another part of the domain name space. Described in RFC 1035. PX Provides mappings between RFC 822 and X.400 addresses. Described in RFC 2163. RKEY Resource key. RP Information on persons responsible for the domain. Experimental. Described in RFC 1183. RRSIG Contains DNSSECbis signature data. Described in RFC 4034. RT Route-through binding for hosts that do not have their own direct wide area network addresses. Experimental. Described in RFC 1183. SIG Contains DNSSEC signature data. Used in original DNSSEC; replaced by RRSIG in DNSSECbis, but still used for SIG(0). Described in RFCs 2535 and 2931. SINK The kitchen sink record. SMIMEA The S/MIME Security Certificate Association. SOA Identifies the start of a zone of authority. Described in RFC 1035. SPF Contains the Sender Policy Framework information for a given email domain. Described in RFC 4408. SRV Information about well known network services (replaces WKS). Described in RFC 2782. SSHFP Provides a way to securely publish a secure shell key's fingerprint. Described in RFC 4255. TA Trust Anchor. Experimental. TALINK Trust Anchor Link. Experimental. TLSA Transport Layer Security Certificate Association. Described in RFC 6698. TXT Text records. Described in RFC 1035. UID Reserved. UINFO Reserved. UNSPEC Reserved. Historical. URI Holds a URI. Described in RFC 7553. WKS Information about which well known network services, such as SMTP, that a domain supports. Historical. X25 Representation of X.25 network addresses. Experimental. Described in RFC 1183. ZONEMD Zone Message Digest. Work in progress draft-wessels-dns-zone-digest. The following classes of resource records are currently valid in the DNS: IN The Internet. CH Chaosnet, a LAN protocol created at MIT in the mid-1970s. Rarely used for its historical purpose, but reused for BIND's built-in server information zones, e.g., version.bind. HS Hesiod, an information service developed by MIT's Project Athena. It is used to share information about various systems databases, such as users, groups, printers and so on.. Textual expression of RRs RRs are represented in binary form in the packets of the DNS protocol, and are usually represented in highly encoded form when stored in a name server or resolver. In the examples provided in RFC 1034, a style similar to that used in master. Discussion of MX Records As described above, domain servers store information as a series of resource records, each of which contains a particular piece of information about a given domain name (which is usually, but not always, a host). The simplest way to think of will fall back to the next largest priority. Priority numbers do not have any absolute meaning — they are relevant only respective to other MX records for that domain name. The domain name given is the machine to which the mail will be delivered. It must have an associated address record (A or AAAA) — CNAME is not sufficient. For a given domain, if there is both a CNAME record and an MX record, the MX record is in error, and will be ignored. Instead, the mail will be delivered to the server specified in the MX record pointed to by the CNAME. For example: example.com. IN MX 10 mail.example.com. IN MX 10 mail2.example.com. IN MX 20 mail.backup.org. mail.example.com. IN A 10.0.0.1 mail2.example.com. IN A 10.0.0.2 Mail delivery will be attempted to mail.example.com and mail2.example.com (in any order), and if neither of those succeed, delivery to mail.backup.org will be attempted. Setting TTLs will cache no-such-domain (NXDOMAIN) responses from you. will control how long other servers can cache it. All of these TTLs default to units of seconds, though units can be explicitly specified, for example, 1h30m. Inverse Mapping in IPv4: $ORIGIN 2.1.10.in-addr.arpa 3 IN PTR foo.example.com. The $ORIGIN lines in the examples are for providing context to the examples only — they do not necessarily appear in the actual usage. They are only used here to indicate that the example is relative to the listed origin. Other Zone File Directives The Master File Format was initially defined in RFC 1035 and has subsequently been extended. While the Master File Format itself is class independent all records in a Master File must be of the same class. Master File Directives include $ORIGIN, $INCLUDE, and $TTL. The @ (at-sign) When used in the label (or name) field, the asperand or at-sign (@) symbol represents the current origin. At the start of the zone file, it is the <zone_name> (followed by trailing dot). The $ORIGIN Directive Syntax: $ORIGIN domain-name comment $ORIGIN sets the domain name that will be appended to any unqualified records. When a zone is first read in there is an implicit $ORIGIN <zone_name>. (followed by trailing dot). The current $ORIGIN is appended to the domain specified in the $ORIGIN argument if it is not absolute. $ORIGIN example.com. WWW CNAME MAIN-SERVER is equivalent to. CNAME MAIN-SERVER.EXAMPLE.COM. The $INCLUDE Directive Syntax: $INCLUDE filename origin comment Read and process the file filename as if it were included into the file at this point. If origin is specified the file is processed with $ORIGIN set to that value, otherwise the current $ORIGIN is used. The origin and the current domain name revert to the values they had prior to the $INCLUDE once the file has been read. RFC 1035 specifies that the current origin should be restored after an $INCLUDE, but it is silent on whether the current domain name should also be restored. BIND 9 restores both of them. This could be construed as a deviation from RFC 1035, a feature, or both. The $TTL Directive Syntax: $TTL default-ttl comment Set the default Time To Live (TTL) for subsequent records with undefined TTLs. Valid TTLs are of the range 0-2147483647 seconds. $TTL is defined in RFC 2308. BIND Master File Extension: the $GENERATE Directive: Classless IN-ADDR.ARPA delegation. . Generate a set of A and MX records. Note the MX's right hand side is a quoted string. The quotes will. lhs This describes the owner name of the resource records to be created. Any single $ (dollar sign) symbols within the lhs string are replaced by the iterator value. To get a $ in the output, you need to escape the $ using a backslash \, e.g. \$. The $ may optionally be followed by modifiers which change the offset from the iterator, field width and base. Modifiers are introduced by a { (left brace) immediately following the $ as ${offset[,width[,base]]}. For example, ${-20,3,d} subtracts 20 from the current value, prints the result as a decimal in a zero-padded field of width 3. Available output forms are decimal (d), octal (o), hexadecimal (x or X for uppercase) and nibble (n or N\ for uppercase). The default modifier is ${0,0,d}. If the lhs is not absolute, the current $ORIGIN is appended to the name. In nibble mode the value will be treated as if it was a reversed hexadecimal string with each hexadecimal digit as a separate label. The width field includes the label separator. For compatibility with earlier versions, $$ is still recognized as indicating a literal $ in the output. ttl Specifies the time-to-live of the generated records. If not specified this will be inherited using the normal TTL inheritance rules. class and ttl can be entered in either order. class Specifies the class of the generated records. This must match the zone class if it is specified. class and ttl can be entered in either order. type Any valid type. rhs rhs, optionally, quoted string. The $GENERATE directive is a BIND extension and not part of the standard zone file format. BIND 8 did not support the optional TTL and CLASS fields. Additional File Formats In addition to the standard textual is capable of being loaded directly into memory via the mmap() function; the zone can begin serving queries almost immediately. For a primary server, a zone file in raw or map format is expected to be generated from a textual zone file by the named-compilezone command. For a secondary server or for a dynamic zone, it is automatically generated (if this format is specified by the masterfile-format option) when named dumps the zone contents after zone transfer or when applying prior updates. If a zone file in a binary format needs manual modification, it first must be converted to a textual form by the named-compilezone command. All necessary modification should go to the text file, which should then be converted to the binary form by. BIND9 Statistics BIND 9 maintains lots of statistics information and provides several interfaces for users to get access to the statistics. The available statistics include all statistics counters that were available in BIND 8 about incoming request processing. Zone Maintenance Statistics Statistics counters regarding zone maintenance operations such as zone transfers. Resolver Statistics Statistics counters about name resolution performed in the internal resolver. Maintained per view. Cache DB RRsets The number of RRsets per RR type and nonexistent names stored in the cache database. If the exclamation mark (!) is printed for a RR type, it means that particular type of RRset is known to be nonexistent (this is also known as "NXRRSET"). If a hash mark (#) is present then the RRset is marked for garbage collection. Maintained per view. Socket I/O Statistics Statistics counters about network related events. A subset of Name Server Statistics is collected and shown per zone for which the server has the authority when zone-statistics is set to full (or yes for backward compatibility. See the description of zone-statistics in .) The Statistics File The text format statistics dump begins with a line, like: +++ Statistics Dump +++ (973798949) The number in parentheses is a standard Unix-style timestamp, measured) Statistics Counters The following tables summarize statistics counters that BIND 9 provides. For each row of the tables, the leftmost column is the abbreviated symbol name of that counter. These symbols are shown in the statistics information accessed via an HTTP statistics channel. The rightmost column gives the description of the counter, which is also shown in the statistics file (but, in this document, possibly with slight modification for better readability). Additional notes may also be provided in this column. When a middle column exists between these two columns, it gives the corresponding counter name of the BIND 8 statistics, if applicable. Name Server Statistics Counters Symbol BIND8 Symbol Description Requestv4 RQ IPv4 requests received. Note: this also counts non query requests. Requestv6 RQ IPv6 requests received. Note: this also counts non query requests. ReqEdns0 Requests with EDNS(0) received. ReqBadEDNSVer Requests with unsupported EDNS version received. ReqTSIG Requests with TSIG received. ReqSIG0 Requests with SIG(0) received. ReqBadSIG Requests with invalid (TSIG or SIG(0)) signature. ReqTCP RTCP TCP requests received. AuthQryRej RUQ Authoritative (non recursive) queries rejected. RecQryRej RURQ Recursive queries rejected. XfrRej RUXFR Zone transfer requests rejected. UpdateRej RUUpd Dynamic update requests rejected. Response SAns Responses sent. RespTruncated Truncated responses sent. RespEDNS0 Responses with EDNS(0) sent. RespTSIG Responses with TSIG sent. RespSIG0 Responses with SIG(0) sent. QrySuccess Queries resulted in a successful answer. This means the query which returns a NOERROR response with at least one answer RR. This corresponds to the success counter of previous versions of BIND 9. QryAuthAns Queries resulted in authoritative answer. QryNoauthAns SNaAns Queries resulted in non authoritative answer. QryReferral Queries resulted in referral answer. This corresponds to the referral counter of previous versions of BIND 9. QryNxrrset Queries resulted in NOERROR responses with no data. This corresponds to the nxrrset counter of previous versions of BIND 9. QrySERVFAIL SFail Queries resulted in SERVFAIL. QryFORMERR SFErr Queries resulted in FORMERR. QryNXDOMAIN SNXD Queries resulted in NXDOMAIN. This corresponds to the nxdomain counter of previous versions of BIND 9. QryRecursion RFwdQ Queries which caused the server to perform recursion in order to find the final answer. This corresponds to the recursion counter of previous versions of BIND 9. QryDuplicate RDupQ Queries which the server attempted to recurse but discovered an existing query with the same IP address, port, query ID, name, type and class already being processed. This corresponds to the duplicate counter of previous versions of BIND 9. QryDropped Recursive queries for which the server discovered an excessive number of existing recursive queries for the same name, type and class and were subsequently dropped. This is the number of dropped queries due to the reason explained with the clients-per-query and max-clients-per-query options (see the description about .) This corresponds to the dropped counter of previous versions of BIND 9. QryFailure Other query failures. This corresponds to the failure counter of previous versions of BIND 9. Note: this counter is provided mainly for backward compatibility with the previous versions. Normally a more fine-grained counters such as AuthQryRej and RecQryRej that would also fall into this counter are provided, and so this counter would not be of much interest in practice. QryNXRedir Queries resulted in NXDOMAIN that were redirected. QryNXRedirRLookup Queries resulted in NXDOMAIN that were redirected and resulted in a successful remote lookup. XfrReqDone Requested zone transfers completed. UpdateReqFwd Update requests forwarded. UpdateRespFwd Update responses forwarded. UpdateFwdFail Dynamic update forward failed. UpdateDone Dynamic updates completed. UpdateFail Dynamic updates failed. UpdateBadPrereq Dynamic updates rejected due to prerequisite failure. RateDropped Responses dropped by rate limits. RateSlipped Responses truncated by rate limits. RPZRewrites Response policy zone rewrites. Zone Maintenance Statistics Counters Symbol Description NotifyOutv4 IPv4 notifies sent. NotifyOutv6 IPv6 notifies sent. NotifyInv4 IPv4 notifies received. NotifyInv6 IPv6 notifies received. NotifyRej Incoming notifies rejected. SOAOutv4 IPv4 SOA queries sent. SOAOutv6 IPv6 SOA queries sent. AXFRReqv4 IPv4 AXFR requested. AXFRReqv6 IPv6 AXFR requested. IXFRReqv4 IPv4 IXFR requested. IXFRReqv6 IPv6 IXFR requested. XfrSuccess Zone transfer requests succeeded. XfrFail Zone transfer requests failed. Resolver Statistics Counters Symbol BIND8 Symbol Description Queryv4 SFwdQ IPv4 queries sent. Queryv6 SFwdQ IPv6 queries sent. Responsev4 RR IPv4 responses received. Responsev6 RR IPv6 responses received. NXDOMAIN RNXD NXDOMAIN received. SERVFAIL RFail SERVFAIL received. FORMERR RFErr FORMERR received. OtherError RErr Other errors received. EDNS0Fail EDNS(0) query failures. Mismatch RDupR Mismatch responses received. The DNS ID, response's source address, and/or the response's source port does not match what was expected. (The port must be 53 or as defined by the port option.) This may be an indication of a cache poisoning attempt. Truncated Truncated responses received. Lame RLame Lame delegations received. Retry SDupQ Query retries performed. QueryAbort Queries aborted due to quota control. QuerySockFail Failures in opening query sockets. One common reason for such failures is a failure of opening a new socket due to a limitation on file descriptors. QueryTimeout Query timeouts. GlueFetchv4 SSysQ IPv4 NS address fetches invoked. GlueFetchv6 SSysQ IPv6 NS address fetches invoked. GlueFetchv4Fail IPv4 NS address fetch failed. GlueFetchv6Fail IPv6 NS address fetch failed. ValAttempt DNSSEC validation attempted. ValOk DNSSEC validation succeeded. ValNegOk DNSSEC validation on negative information succeeded. ValFail DNSSEC validation failed. QryRTTnn Frequency table on round trip times (RTTs) of queries. Each nn specifies the corresponding frequency. In the sequence of nn_1, nn_2, ..., nn_m, the value of nn_i is the number of queries whose RTTs are between nn_(i-1) (inclusive) and nn_i (exclusive) milliseconds. For the sake of convenience we define nn_0 to be 0. The last entry should be represented as nn_m+, which means the number of queries whose RTTs are equal to or over nn_m milliseconds. Socket I/O Statistics Counters Socket I/O statistics counters are defined per socket types, which are UDP4 (UDP/IPv4), UDP6 (UDP/IPv6), TCP4 (TCP/IPv4), TCP6 (TCP/IPv6), Unix (Unix Domain), and FDwatch (sockets opened outside the socket module). In the following table <TYPE> represents a socket type. Not all counters are available for all socket types; exceptions are noted in the description field. Symbol Description <TYPE>Open Sockets opened successfully. This counter is not applicable to the FDwatch type. <TYPE>OpenFail Failures of opening sockets. This counter is not applicable to the FDwatch type. <TYPE>Close Sockets closed. <TYPE>BindFail Failures of binding sockets. <TYPE>ConnFail Failures of connecting sockets. <TYPE>Conn Connections established successfully. <TYPE>AcceptFail Failures of accepting incoming connection requests. This counter is not applicable to the UDP and FDwatch types. <TYPE>Accept Incoming connections successfully accepted. This counter is not applicable to the UDP and FDwatch types. <TYPE>SendErr Errors in socket send operations. This counter corresponds to SErr counter of BIND 8. <TYPE>RecvErr Errors in socket receive operations. This includes errors of send operations on a connected UDP socket notified by an ICMP error message. Compatibility with BIND 8 Counters Most statistics counters that were available in BIND 8 are also supported in BIND 9 as shown in the above tables. Here are notes about other counters that do not appear in these tables. RFwdR,SFwdR These counters are not supported because BIND 9 does not adopt the notion of forwarding as BIND 8 did. RAXFR This counter is accessible in the Incoming Queries section. RIQ This counter is accessible in the Incoming Requests section. ROpts This counter is not supported because BIND 9 does not care about IP options in the first place. BIND 9 Security Considerations Access Control Lists Access Control Lists (ACLs) are address match lists that you can set up and nickname for future use in allow-notify, allow-query, allow-query-on, allow-recursion, blackhole, allow-transfer, match-clients, etc. Using ACLs allows you to have finer control over who can access your name server, without cluttering up your config files with huge lists of IP addresses. It is a good idea, or ecs elements, which specify a network prefix but are only matched if that prefix matches an EDNS client subnet option included in the request. ecs prefix. (Note: The authoritative ECS implementation in named is based on an early version of the specification, and is known to have incompatibilities with other implementations. It is also inefficient, requiring a separate view for each client subnet to be sent different answers, and it is unable to correct for overlapping subnets in the configuration. It can be used for testing purposes, but is not recommended for production use.) When BIND 9 is built with GeoIP support, ACLs can also be used for geographic access restrictions. This is done by specifying an ACL element of the form: geoip db database field value The field indicates which field to search for a match. Available fields are "country", "region", "city", "continent", "postal" (postal code), "metro" (metro code), "area" (area code), "tz" (timezone), "isp", "org", "asnum", "domain" and "netspeed". value. The database database will force the query to be answered from that database and no other. If database is not specified, then these queries will be answered from the "city", database if it is installed, or the "region" database if it is installed, or the "country" database, in that order. geoip-use-ecs to no. Some example GeoIP ACLs: indicated that the query should be accepted, and the second element is ignored. will be rejected, and this will terminate processing of the ACL. Any address that is both conditions are true. Chroot and Setuid On UNIX servers, it is possible to run BIND in a chrooted environment (using the chroot() function) by specifying the -t option for named. This can help improve system security by placing BIND in a "sandbox", which will limit The chroot Environment directory and pid-file to account for this. Unlike with earlier versions of BIND, you typically will not need to compile named statically nor install shared libraries under the new root. However, depending on your operating system, you may need to set up things like /dev/zero, /dev/random, /dev/log, and /etc/localtime. Using the setuid Function Prior to running the named daemon, use the touch utility (to change file access and modification times) or the chown utility (to set the user id and/or group id) on files to which you want BIND to write. If the named daemon is running as an unprivileged user, it will not be able to bind to new restricted ports if the server is reloaded. Dynamic Update Security. Troubleshooting Common Problems It's not working; how can I figure out what's wrong? The best solution to solving installation and configuration issues is to take preventative measures by setting up logging files beforehand. The log files provide a source of hints and information that can be used to figure out what went wrong and how to fix the problem. Incrementing and Changing the Serial Number Zone serial numbers are just numbers — they aren't date related. A lot of people set them to a number that represents a date, usually of the form YYYYMMDDRR. Occasionally they will make a mistake and set them to a "date in the future" then try to correct them by setting them to the "current date". This causes problems because serial numbers are used to indicate that a zone has been updated. If the serial number on the slave server is lower than the serial number on the master, the slave server will attempt to update its copy of the zone. Setting the serial number to a lower number on the master server than the slave server means that the slave will not perform updates to its copy of the zone. The solution to this is to add 2147483647 (2^31-1) to the number, reload the zone and make sure all slaves have updated to the new zone serial number, then reset the number to what you want it to be, and reload the zone again. Where Can I Get Help? The Internet Systems Consortium (ISC) offers a wide range of support and service agreements for BIND and DHCP servers. Four levels of premium support are available and each level includes support for all ISC programs, significant discounts on products and training, and a recognized priority on bug fixes and non-funded feature requests. In addition, ISC offers a standard support agreement package which includes services ranging from bug fix announcements to remote support. It also includes training in BIND and DHCP. To discuss arrangements for support, contact info@isc.org or visit the ISC web page at to read more. Release Notes A Brief History of the DNS and BIND Although the "official" beginning of the Domain Name System occurred in 1984 with the publication of RFC 920, the core of the new system was described in 1983 in RFCs 882 and being several corporations, and by the tireless work efforts of numerous individuals. General DNS Reference Information IPv6 addresses (AAAA) the same as) Request for Comments (RFCs) obtained online via FTP at: (where xxxx is the number of the RFC). RFCs are also available via the Web at:. Standards RFC974 PartridgeC. Mail Routing and the Domain System January 1986 RFC1034 MockapetrisP.V. Domain Names — Concepts and Facilities November 1987 RFC1035 MockapetrisP. V. Domain Names — Implementation and Specification November 1987 Proposed Standards RFC2181 ElzR., R. Bush Clarifications to the DNS Specification July 1997 RFC2308 AndrewsM. Negative Caching of DNS Queries March 1998 RFC1995 OhtaM. Incremental Zone Transfer in DNS August 1996 RFC1996 VixieP. A Mechanism for Prompt Notification of Zone Changes August 1996 RFC2136 VixieP. S.Thomson Y.Rekhter J.Bound Dynamic Updates in the Domain Name System April 1997 RFC2671 P.Vixie Extension Mechanisms for DNS (EDNS0) August 1997 RFC2672 M.Crawford Non-Terminal DNS Name Redirection August 1999 RFC2845 VixieP. O.Gudmundsson D.Eastlake3rd B.Wellington Secret Key Transaction Authentication for DNS (TSIG) May 2000 RFC2930 D.Eastlake3rd Secret Key Establishment for DNS (TKEY RR) September 2000 RFC2931 D.Eastlake3rd DNS Request and Transaction Signatures (SIG(0)s) September 2000 RFC3007 B.Wellington Secure Domain Name System (DNS) Dynamic Update November 2000 RFC3645 S.Kwan P.Garg J.Gilroy L.Esibov J.Westhead R.Hall Generic Security Service Algorithm for Secret Key Transaction Authentication for DNS (GSS-TSIG) October 2003 DNS Security Proposed Standards RFC3225 D.Conrad Indicating Resolver Support of DNSSEC December 2001 RFC3833 D.Atkins R.Austein Threat Analysis of the Domain Name System (DNS) August 2004 RFC4033 R.Arends R.Austein M.Larson D.Massey S.Rose DNS Security Introduction and Requirements March 2005 RFC4034 R.Arends R.Austein M.Larson D.Massey S.Rose Resource Records for the DNS Security Extensions March 2005 RFC4035 R.Arends R.Austein M.Larson D.Massey S.Rose Protocol Modifications for the DNS Security Extensions March 2005 Other Important RFCs About DNS Implementation RFC1535 GavronE. A Security Problem and Proposed Correction With Widely Deployed DNS Software October 1993 RFC1536 KumarA. J.Postel C.Neuman P.Danzig S.Miller Common DNS Implementation Errors and Suggested Fixes October 1993 RFC1982 ElzR. R.Bush Serial Number Arithmetic August 1996 RFC4074 MorishitaY. T.Jinmei Common Misbehaviour Against DNS Queries for IPv6 Addresses May 2005 Resource Record Types RFC1183 EverhartC.F. L. A.Mamakos R.Ullmann P.Mockapetris New DNS RR Definitions October 1990 RFC1706 ManningB. R.Colella DNS NSAP Resource Records October 1994 RFC2168 DanielR. M.Mealling Resolution of Uniform Resource Identifiers using the Domain Name System June 1997 RFC1876 DavisC. P.Vixie T.Goodwin I.Dickinson A Means for Expressing Location Information in the Domain Name System January 1996 RFC2052 GulbrandsenA. P.Vixie A DNS RR for Specifying the Location of Services October 1996 RFC2163 AllocchioA. Using the Internet DNS to Distribute MIXER Conformant Global Address Mapping January 1998 RFC2230 AtkinsonR. Key Exchange Delegation Record for the DNS October 1997 RFC2536 EastlakeD.3rd DSA KEYs and SIGs in the Domain Name System (DNS) March 1999 RFC2537 EastlakeD.3rd RSA/MD5 KEYs and SIGs in the Domain Name System (DNS) March 1999 RFC2538 EastlakeD.3rd GudmundssonO. Storing Certificates in the Domain Name System (DNS) March 1999 RFC2539 EastlakeD.3rd Storage of Diffie-Hellman Keys in the Domain Name System (DNS) March 1999 RFC2540 EastlakeD.3rd Detached Domain Name System (DNS) Information March 1999 RFC2782 GulbrandsenA. VixieP. EsibovL. A DNS RR for specifying the location of services (DNS SRV) February 2000 RFC2915 MeallingM. DanielR. The Naming Authority Pointer (NAPTR) DNS Resource Record September 2000 RFC3110 EastlakeD.3rd RSA/SHA-1 SIGs and RSA KEYs in the Domain Name System (DNS) May 2001 RFC3123 KochP. A DNS RR Type for Lists of Address Prefixes (APL RR) June 2001 RFC3596 ThomsonS. C.Huitema V.Ksinant M.Souissi DNS Extensions to support IP version 6 October 2003 RFC3597 GustafssonA. Handling of Unknown DNS Resource Record (RR) Types September 2003 DNS and the Internet RFC1101 MockapetrisP. V. DNS Encoding of Network Names and Other Types April 1989 RFC1123 BradenR. Requirements for Internet Hosts - Application and Support October 1989 RFC1591 PostelJ. Domain Name System Structure and Delegation March 1994 RFC2317 EidnesH. G.de Groot P.Vixie Classless IN-ADDR.ARPA Delegation March 1998 RFC2826 Internet Architecture Board IAB Technical Comment on the Unique DNS Root May 2000 RFC2929 EastlakeD.3rd Brunner-WilliamsE. ManningB. Domain Name System (DNS) IANA Considerations September 2000 DNS Operations RFC1033 LottorM. Domain administrators operations guide November 1987 RFC1537 BeertemaP. Common DNS Data File Configuration Errors October 1993 RFC1912 BarrD. Common DNS Operational and Configuration Errors February 1996 RFC2010 ManningB. P.Vixie Operational Criteria for Root Name Servers October 1996 RFC2219 HamiltonM. R.Wright Use of DNS Aliases for Network Services October 1997 Internationalized Domain Names RFC2825 IAB DaigleR. A Tangled Web: Issues of I18N, Domain Names, and the Other Internet protocols May 2000 RFC3490 FaltstromP. HoffmanP. CostelloA. Internationalizing Domain Names in Applications (IDNA) March 2003 RFC3491 HoffmanP. BlanchetM. Nameprep: A Stringprep Profile for Internationalized Domain Names March 2003 RFC3492 CostelloA. Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA) March 2003 Other DNS-related RFCs Note: the following list of RFCs, although DNS-related, are not concerned with implementing software. RFC1464 RosenbaumR. Using the Domain Name System To Store Arbitrary String Attributes May 1993 RFC1713 RomaoA. Tools for DNS Debugging November 1994 RFC1794 BriscoT. DNS Support for Load Balancing April 1995 RFC2240 VaughanO. A Legal Basis for Domain Name Allocation November 1997 RFC2345 KlensinJ. T.Wolf G.Oglesby Domain Names and Company Name Retrieval May 1998 RFC2352 VaughanO. A Convention For Using Legal Names as Domain Names May 1998 RFC3071 KlensinJ. Reflections on the DNS, RFC 1591, and Categories of Domains February 2001 RFC3258 HardieT. Distributing Authoritative Name Servers via Shared Unicast Addresses April 2002 RFC3901 DurandA. J.Ihren DNS IPv6 Transport Operational Guidelines September 2004 Obsolete and Unimplemented Experimental RFC RFC1712 FarrellC. M.Schulze S.Pleitner D.Baldoni DNS Encoding of Geographical Location November 1994 RFC2673 CrawfordM. Binary Labels in the Domain Name System August 1999 RFC2874 CrawfordM. HuitemaC. DNS Extensions to Support IPv6 Address Aggregation and Renumbering July 2000 Obsoleted DNS Security RFCs Most of these have been consolidated into RFC4033, RFC4034 and RFC4035 which collectively describe DNSSECbis. RFC2065 Eastlake3rdD. C.Kaufman Domain Name System Security Extensions January 1997 RFC2137 Eastlake3rdD. Secure Domain Name System Dynamic Update April 1997 RFC2535 Eastlake3rdD. Domain Name System Security Extensions March 1999 RFC3008 WellingtonB. Domain Name System Security (DNSSEC) Signing Authority November 2000 RFC3090 LewisE. DNS Security Extension Clarification on Zone Status March 2001 RFC3445 MasseyD. RoseS. Limiting the Scope of the KEY Resource Record (RR) December 2002 RFC3655 WellingtonB. GudmundssonO. Redefinition of DNS Authenticated Data (AD) bit November 2003 RFC3658 GudmundssonO. Delegation Signer (DS) Resource Record (RR) December 2003 RFC3755 WeilerS. Legacy Resolver Compatibility for Delegation Signer (DS) May 2004 RFC3757 KolkmanO. SchlyterJ. LewisE. Domain Name System KEY (DNSKEY) Resource Record (RR) Secure Entry Point (SEP) Flag April 2004 RFC3845 SchlyterJ. DNS Security (DNSSEC) NextSECure (NSEC) RDATA Format August 2004 Internet Drafts Internet Drafts (IDs) are rough-draft working documents of the Internet Engineering Task Force.. Other Documents About BIND AlbitzPaul CricketLiu DNS and BIND 1998 Sebastopol, CA: O'Reilly and Associates BIND 9 DNS Library Support Manual pages | https://gitlab.isc.org/isc-projects/bind9/-/raw/0b4e2cd4c3192ba88569dd344f542a8cc43742b5/doc/arm/Bv9ARM-book.xml?inline=false | CC-MAIN-2021-25 | refinedweb | 30,483 | 56.66 |
#include <db.h>
int memp_fclose(DB_MPOOLFILE *mpf);
The memp_fclose function closes the source file indicated by the DB_MPOOLFILE structure. Calling memp_fclose does not imply a call to memp_fsync; that is, no pages are written to the source file as as a result of calling memp_fclose.
In addition, if the DB_MPOOLFILE was temporary, any underlying files created for this DB_MPOOLFILE will be removed.
After memp_fclose has been called, regardless of its return, the DB_MPOOLFILE handle may not be accessed again.
The memp_fclose function returns a non-zero error value on failure and 0 on success.
The memp_fclose function may fail and return a non-zero error for errors specified for other Berkeley DB and C library or system functions. If a catastrophic error has occurred, the memp_fclose function may fail and return DB_RUNRECOVERY, in which case all subsequent Berkeley DB calls will fail in the same way. | http://pybsddb.sourceforge.net/api_c/memp_fclose.html | CC-MAIN-2017-47 | refinedweb | 146 | 50.87 |
[Date Index]
[Thread Index]
[Author Index]
Problem importing java class
Hello,
I am trying to use an external jar that I've implemented. This .jar file
import other class libraries such as ejml class.
I am able to load my java class and see the methods inside but when I go to
call one of these methods it returns me an exeption:
java.lang.NoClassDefFoundError:org/ejml/ops/RandomMatrices..
I tried to import into my notebook alse the java class RandomMatrices to which
refers the exeption but nothing happen!
Have you any clue how to solve it?
Thanks in advance
Paolo | http://forums.wolfram.com/mathgroup/archive/2012/Oct/msg00058.html | CC-MAIN-2017-09 | refinedweb | 101 | 55.54 |
Getting Started with SQL¶
SQL (vapor/sql) is a library for building and serializing SQL queries in Swift. It has an extensible, protocol-based design and supports DQL, DML, and DDL.
Tip
If you use Fluent, you will usually not need to build SQL queries manually.
Package¶
The SQL package is lightweight, pure Swift, and has no dependencies. This means it can be used as a SQL serialization framework any Swift project—even one not using Vapor.
To include it in your package, add the following to your
Package.swift file.
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "Project", dependencies: [ ... .package(url: "", from: "1.0.0"), ], targets: [ .target(name: "Project", dependencies: ["SQL", ... ]) ] )
Use
import SQL to access the APIs.
The rest of this guide will give you an overview of what is available in the SQL package. As always, feel free to visit the API docs for more in-depth information. | https://docs.vapor.codes/3.0/sql/getting-started/ | CC-MAIN-2018-22 | refinedweb | 155 | 67.96 |
ISSUE-197: charset/encoding unconstrained
charset/encoding unconstrained
- State:
- CLOSED
- Product:
- TTML 1.0
- Raised by:
- Mike Dolan
- Opened on:
- 2012-11-29
- Description:
- TTML is silent on the document charset (xml encoding) permitted. Since the core XML specification permits virtually anything, then TTML is also unconstrained. Certain encodings, such as "binary" are generally non-interoperable. Further, since we permit other namespaces, constraints on those should also be required. For example, even if TTML is constrained to utf-8 and utf-16, then allowing other namespaces to use binary would make the document using such namespaces unparseable.
XML decoders are only required to support utf-8 and utf-16. Propose we so constrain TTML.
Related to Issue-196:
Related to Action-131:
Related to Action-129:
- Related Actions Items:
ACTION-136 on Glenn Adams to Integrate changes from Action-133 into the TTML 1.0 Second Edition - due 2013-01-14, closed ACTION-166 on Mike Dolan to Open issue for 1.1 regarding encodings - due 2013-06-27, closed
- Related emails:
- [Minutes] TTWG telecon 08/08/2013 (from tmichel@w3.org on 2013-08-08)
- Minutes - 2013-06-20 TML Agenda for 31/01/13 (from Sean.Hayes@microsoft.com on 2013-01-31)
- RE: TTML Agenda for 25/01/13 (from momartin@microsoft.com on 2013-01-24)
- TTML Agenda for 25/01/13 (from Sean.Hayes@microsoft.com on 2013-01-24)
- RE: TTML Agenda for 17/01/13 (from mdolan@newtbt.com on 2013-01-17)
- TTML Agenda for 17/01/13 (from Sean.Hayes@microsoft.com on 2013-01-17)
- TTWG Meeting Minutes Jan 10, 2013 (from momartin@microsoft.com on 2013-01-10)
- RE: TTML Agenda for 10/01/13 (from Sean.Hayes@microsoft.com on 2013-01-10)
- ISSUE-197: charset/encoding unconstrained [DFXP 1.0] (from sysbot+tracker@w3.org on 2012-11-29)
Related notes:
Opened to resolve for TTML 1.0 Second Edition.Monica Martin, 7 Jan 2013, 16:09:09
Related to: Actions 88, 133, 136 and Issue 175.Monica Martin, 7 Jan 2013, 16:14:43
see new Appendix M (informative)Glenn Adams, 2 May 2013, 05:28:15
[plh]: Jun 2013, 14:50:10
Display change log | http://www.w3.org/AudioVideo/TT/tracker/issues/197 | CC-MAIN-2015-22 | refinedweb | 370 | 59.8 |
Oracle Nashorn: A next-generation JavaScript engine for the JVM
Julien Ponge outlines scenarios for using Oracle Nashorn as a command-line tool and as an embedded interpreter in Java applications.
Scenarios for using Oracle Nashorn as a command-line tool and as an embedded interpreter in Java applications runtime performance through invokedynamic-bound call sites..
The examples can be run using a recent JDK 8 early-access release. You can also use a custom build of OpenJDK 8. This is very simple to do thanks to the new OpenJDK build infrastructure (for example, sh configure && make images on a Mac OS X operating system with the XCode command-line tools installed).
It’s just JavaScript
A simple way to get started with Oracle Nashorn is to run JavaScript programs from the command line. To do so, builds of Oracle’s JDK or OpenJDK include a command-line tool called jjs. It can be found in the bin/ folder of a JDK installation along with the well-known java, javac, or jar tools.
The jjs tool accepts a list of JavaScript source code files as arguments. Consider the following hello.js file:
var hello = function() { print("Hello Nashorn!"); }; hello();
Evaluating it is as simple as this:
$ jjs hello.js Hello Nashorn! $
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var filtered = data.filter(function(i) { return i % 2 == 0; }); print(filtered); var sumOfFiltered = filtered.reduce(function(acc, next) { return acc + next; }, 0); print(sumOfFiltered);
Listing 1
Oracle Nashorn is an ECMA-compliant implementation of the language; hence, we can run more-elaborate snippets, such as the one shown in Listing 1, which prints a filtered list in which only the even numbers remain from the original list. It also prints the sum of those even numbers:
2,4,6,8,10 30
While Oracle Nashorn runs ECMA-compliant JavaScript, it is important to note that objects normally accessible in a web browser are not available, for example, console, window, and so on.
Scripting extensions
If you run jjs -help to get a comprehensive list of the jjs command-line tool commands, you will notice a few interesting features:
It can run scripts as JavaFX applications.
JavaScript strict mode can be activated.
Additional classpath elements can be specified for the Java Virtual Machine (JVM).
An intriguing scripting mode can be enabled.
The scripting mode is interesting if you plan to take advantage of jjs to run system scripts written in JavaScript, just as you would do in Python, Ruby, or Bash. The scripting mode mainly consists of two language extensions: heredocs and shell invocations.
A simple way to get started with Oracle Nashorn is to run JavaScript programs from the command line.
Heredocs. Heredocs are simply multiline strings, and they use a syntax that is familiar to Bash, Perl, and Ruby programmers (see Listing 2). Text begins with << followed by a special termination marker, which is EOF in our case. The formatting is left intact until the termination marker. Also, JavaScript expressions can be embedded in ${...} expressions. Running this program yields the output shown in Listing 3.
var data = { foo: “bar”, time: new Date() }; print(<So... foo = ${data.foo} and the current time is ${data.time} EOF);
Listing 2
$ jjs -scripting heredocs.js So... foo = bar and the current time is Thu Aug 01 2013 16:21:16 GMT+0200 (CEST) $
Listing 3
Note that in scripting mode, double-quoted strings can embed expressions that will be evaluated: "Hello ${name}" will evaluate against the value of name, while 'Hello ${name}' will not.
Shell invocations. Shell invocations allow the invocation of external programs in which the command is put between back-tick characters. Consider the following example:
var lines = 'ls -lsa'.split("n"); for each (var line in lines) { print("|> " + line); }
It runs the ls -lsa command. A shell invocation returns the standard console output as a string, which enables us to split lines and print them prepended with "|> ", as shown in Listing 4. If you need more-elaborate control over invoked processes, you should know that a $EXEC function exists, which provides access to the standard input, output, and error streams.
jjs -scripting dir.js |> total 72 |> 0 drwxr-xr-x 2 jponge staff 238 Aug 1 16:12 . |> 0 drwxr-xr-x 5 jponge staff 170 Aug 1 12:15 .. |> 8 -rw-r--r-- 1 jponge staff 90 Jul 31 23:36 dir.js |> 8 -rw-r--r-- 1 jponge staff 304 Aug 1 15:56 hello.js |> 8 -rw-r--r-- 1 jponge staff 143 Aug 1 16:12 heredocs.js |> $
Listing 4
Other goodies. The scripting mode provides further goodies:
The $ENV variable provides the shell environment variables.
The $ARG variable is an array of the program command-line arguments.
Comments can start with #, which is useful for making scripts executable on UNIX-like systems. exit(code) and quit() functions can terminate the current JVM process.
Consider the following executable.js file:
#!/usr/bin/env jjs -scripting print( "Arguments (${$ARG.length})"); for each (arg in $ARG) { print("- ${arg}") }
We can make it executable and invoke it (arguments are passed after –), as shown in Listing 5.
$ chmod +x executable.js $ ./executable.js Arguments (0) $ ./executable.js -- hello world ! Arguments (3) - hello - world - ! $
Listing 5
Embedding Oracle Nashorn
The public API to embed Oracle Nashorn is simply javax.script. When Oracle Nashorn is available, its scripting engine is accessible through the nashorn identifier.
Listing 6 shows how you can access Oracle Nashorn from a Java application to define a sum function, call it, and then display the result.
package sample1; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class Hello { public static void main(String... args) throws Throwable { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName("nashorn"); engine.eval("function sum(a, b) { return a + b; }"); System.out.println(engine.eval("sum(1, 2);")); } }
Listing 6
The scripting engine object is the sole entry point to the Oracle Nashorn interpreter. It can be cast to the javax.script.Invocable interface, too:
Invocable invocable = ( Invocable) engine; System.out.println( invocable.invokeFunction( "sum", 10, 2));
The Invocable interface also provides a method to convert evaluated code to a reference on a Java interface. Suppose that there exists some interface Adder as follows:
public interface Adder { int sum(int a, int b); }
The evaluated code defines a sum function with two arguments; hence, we can use it as an implementation as follows:
Adder adder = invocable.getInterface( Adder.class); System.out.println( adder.sum(2, 3));
This is a convenient way to extend Java types from JavaScript, but fortunately it’s not the only one, as we will see in the next sections.
Not every JavaScript code is to be evaluated from a String: java.io.Reader; instances can be used, too, as shown in Listing 7.
engine.eval(new FileReader("src/sample1/greeter.js")); System.out.println(invocable.invokeFunction("greet", "Julien"));
Listing 7
You should consult the complete javax.script APIs for more details, including the information about the ability to define scopes and bindings of script engines.
mustache.js
Let’s now call a real-world JavaScript library from a Java application. To do so, let’s use the popular mustache.js template library, which is commonly used to render view fragments in HTML applications. Briefly, given a JSON data object {"name":"Bean"} and a template "Hello {{name}}", Mustache renders "Hello Bean". The template engine can do more than that, though, because it also supports conditions, collection iteration, and more.
Suppose that we downloaded mustache.js. Listings 8a and 8b show our Java integration example.
package sample2; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.FileReader; public class Mustache { public static void main(String... args) throws Throwable { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName("nashorn"); engine.eval(new FileReader("src/sample2/mustache.js")); Invocable invocable = (Invocable) engine; String template = "Email addresses of {{contact.name}}:n" + "{{#contact.emails}}n" + "- {{.}}n" + "{{/contact.emails}}"; String contactJson = "{" + ""contact": {" + ""name": "Mr A", "emails": [" + ""contact@some.tld", "sales@some.tld"" + "]}}";
Listing 8a
Object json = engine.eval("JSON"); Object data = invocable.invokeMethod(json, "parse", contactJson); Object mustache = engine.eval("Mustache"); System.out.println(invocable.invokeMethod( mustache, "render", template, data)); } }
Listing 8b
After getting a scripting engine reference for Oracle Nashorn, we evaluate the mustache.js code. We then define the Mustache template as a String. The data model needs to be a JSON object. In our case, we first have to define it as a String and call JSON.parse to have it as a JSON object. We can then call Mustache.render. Running this program yields the following output, calling mustache.js for template rendering:
$ java sample2.Mustache Email addresses of Mr A: - contact@some.tld - sales@some.tld $
Java seen from Oracle Nashorn
In most cases, calling Java APIs from Oracle Nashorn is straightforward, with the resulting code being Java written in JavaScript.
print(java.lang.System.currentTimeMillis()); Java objects can be instantiated using the new operator: var file = new java.io.File("sample.js"); print(file.getAbsolutePath()); print(file.absolutePath);
Listing 9
Basic example. We can call the System.currentTimeMillis() static method, as shown in Listing 9. And Java objects can be instantiated using the new operator:
var file = new java.io.File("sample.js"); print(file.getAbsolutePath()); print(file.absolutePath);
Note that although java.io.File does not define an absolutePath method or public field, Oracle Nashorn inferred a property for it, so the expression file.absolutePath is equivalent to file.get AbsolutePath(). In fact, Oracle Nashorn treats the getXY() and setXY(value) methods as properties.
Dealing with arrays. The following snippet populates a queue as an instance of java.util.LinkedList:
var stack = new java.util.LinkedList(); [1, 2, 3, 4].forEach(function(item) { stack.push(item); }); print(stack); print(stack.getClass());
This produces the following output, confirming that we are directly manipulating Java objects from JavaScript:
[4, 3, 2, 1] class java.util.LinkedList
We can also take a tour through the new Java 8 stream APIs to sort the collection, although in this case, this is not the most efficient way to do so:
var sorted = stack .stream() .sorted() .toArray(); print(sorted);
This time, it prints something like [Ljava.lang.Object;@473b46c3, which indicates a Java native array. However, a Java array is not a JavaScript array. Internally, Oracle Nashorn provides JavaScript arrays using a custom class that also implements java.util.Map. Conversions can be performed using the to and from methods of the Oracle Nashorn–provided Java object:
var jsArray = Java.from(sorted); print(jsArray); var javaArray = Java.to(jsArray); print(javaArray);
which prints:
1,2,3,4 [Ljava.lang.Object;@23a5fd2
Imports. By default, all references to Java types need to be fully qualified (for example, java.lang.String, java.util.LinkedHashSet, and so on). Oracle Nashorn does not import the java package by default, because references to String or Object conflict with the corresponding types in JavaScript. Hence, a Java string is java.lang.String, not String.
Mozilla Rhino was the predecessor of Oracle Nashorn as the JavaScript engine implementation provided with Oracle’s JDK releases. It featured a load(path) function to load a third-party JavaScript file. This is still present in Oracle Nashorn. You can use it to load a special compatibility module that provides importClass to import a class (like an explicit import in Java) and importPackage to import a package (like a wildcard import in Java):
load( "nashorn:mozilla_compat.js"); importClass(java.util.HashSet); var set = new HashSet(); importPackage(java.util); var list = new ArrayList();
It is important to note that these functions import the symbolic references into the global scope of the JavaScript code being interpreted. While they are still supported for compatibility reasons, the use of mozilla_compat.js and importClass is discouraged. Instead, it is recommended that you use another function coming from the Mozilla Rhino heritage—JavaImporter—as shown in Listing 10.
var CollectionsAndFiles = new JavaImporter( java.util, java.io, java.nio); with (CollectionsAndFiles) { var files = new LinkedHashSet(); files.add(new File("Plop")); files.add(new File("Foo")); files.add(new File("w00t.js")); }
Listing 10
JavaImporter takes a variable number of arguments as Java packages, and the returned object can be used in a with statement whose scope includes the specified package imports. The global JavaScript scope is not affected, making JavaImporter a much better alternative to importClass and importPackage.
Overloaded methods. Java allows method overloading, that is, the definition within a single class of several methods that have the same names but different signatures. The java.io.PrintStream class is a good example, providing many print and println methods for objects, strings, arrays, and primitive types.
Oracle Nashorn properly selects the most suitable target at runtime on a per-invocation basis. This means that you should never have to worry about overloaded methods when dealing with Java APIs. Still, there is a way to precisely select the required target if you need to. This need mainly occurs with ambiguous parameters when you are passing a function object in which different interface types are permitted by overloaded methods, such as with the submit methods of java.util.concurrent executors.
In the following code, the first call to println will select the println(String) overloaded method. The second call uses a JavaScript object property to access the println(Object) variant. The string to be passed provides a signature that Oracle Nashorn uses at resolution time. Note that as an exception, classes from the java package need not be qualified; hence, we can write println(Object) instead of the valid, but longer, println(java.lang.Object).
var stdout = java.lang.System.out; stdout.println("Hello"); stdout["println(Object)"]( "Hello");
Type objects. The Java.type function can be used to obtain references to precise Java types. These include not just objects but also primitive types and arrays:
var LinkedList = Java.type( "java.util.LinkedList"); var primitiveInt = Java.type( "int"); var arrayOfInts = Java.type( "int[]");
The returned objects are an Oracle Nashorn–specific representation of mappings to Java types. It is important to note that they differ from instances of java.lang.Class. Type objects are useful as constructors and for instanceof-based comparisons. Let’s look at Listing 11.
var list = new LinkedList; list.add(1); list.add(2); print(list); print(list instanceof LinkedList); var a = new arrayOfInts(3); print(a.length); print(a instanceof arrayOfInts);
Listing 11
It is possible to go back and forth between a type object and a Java class reference. The class property of type objects returns their java.lang.Class counterpart. Similarly, the static property is made available to java.lang.Class instances to get their corresponding type objects.
print(LinkedList.class); print(list.getClass().static); print(LinkedList.class === list.getClass()); print(list.getClass().static === LinkedList);
The code in Listing 12 would print the following:
class java.util.LinkedList [JavaClass java.util.LinkedList] true true
Extending Java types
Oracle Nashorn provides simple mechanisms for extending Java types from JavaScript code. It is important to be able to provide interface implementations and concrete subclasses.
Implementing interfaces. Given a Java interface, a simple way to provide an implementation is to instantiate it, and pass its constructor function a JavaScript object in which the methods to be implemented are given as properties.
Listing 13 provides a concrete implementation of java.util.Iterator, giving implementations of the next and hasNext methods (the remove method is provided by a default method in Java 8). We can run it, and check that it works as expected (see Listing 14).
var iterator = new java.util.Iterator({ i: 0, hasNext: function() { return this.i < 10; }, next: function() { return this.i++; } }); print(iterator instanceof Java.type("java.util.Iterator")); while (iterator.hasNext()) { print("-> " + iterator.next()); }
Listing 13
true -> 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
Listing 14
When interfaces consist of a single method, a function object can be directly given with no need to perform an explicit new operator call. The example in Listing 15 illustrates this on collection streams.
var list = java.util.Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); var odd = list.stream().filter(function(i) { return i % 2 == 0; }); odd.forEach(function(i) { print(">>> " + i); });
Listing 15
Running the code in Listing 15 prints the following:
>>> 2 >>> 4 >>> 6 >>> 8
Note that Oracle Nashorn also provides a language extension in the form of Oracle Nashorn functions, which provides an abridged syntax for small lambda functions. This works everywhere a single abstract-method type is expected from Java APIs, too. Therefore, we can rewrite the following code from Listing 15:
var odd = list.stream().filter( function(i) { return i % 2 == 0; });
Like this:
var odd = list.stream().filter( function(i) i % 2 == 0);
This language extension is useful when dealing with the new Java SE 8 APIs that provide support for lambda expressions, because JavaScript functions can be used wherever a Java lambda is expected. Also, note that this shorter form is to be supported by JavaScript 1.8 engines.
The case of abstract classes is the same as interfaces: you provide a JavaScript object with the required method implementations to its constructor function. Or, directly pass a function when an instance of a single abstract-method class is required.
Using instance-bound implementations. To extend concrete classes, you have to use the Java.extend function. It takes a type object as a first argument to denote the base class to be extended. If the parameter is an interface type, it assumes that the base class is java.lang.Object. Further types can be given as extra parameters to specify a set of implemented interfaces.
Consider the example shown in Listing 16. The Java.extend function returns a type object, also called an extender. It can be invoked to create concrete subclasses; in our case, instance is a subclass of java.lang.Object that implements the two interfaces java.lang .Comparable and java.io.Serializable. Implementations are passed to instances being created through a JavaScript object passed to the constructors.
var ObjectType = Java.type("java.lang.Object"); var Comparable = Java.type("java.lang.Comparable"); var Serializable = Java.type("java.io.Serializable"); var MyExtender = Java.extend( ObjectType, Comparable, Serializable); var instance = new MyExtender({ someInt: 0, compareTo: function(other) { var value = other["someInt"]; if (value === undefined) { return 1; } if (this.someInt < value) { return -1; } else if (this.someInt == value) { return 0; } else { return 1; } } }); print(instance instanceof Comparable); print(instance instanceof Serializable); print(instance.compareTo({ someInt: 10 })); print(instance.compareTo({ someInt: 0 })); print(instance.compareTo({ someInt: -10 }));
Listing 16
Running the code in Listing 16 yields the following console output:
true true -1 0 1
Using class-bound implementations. Instances created from the same extender type share the same class although their implementations differ on a per-instance basis (see Listing 17).
var anotherInstance = new MyExtender({ compareTo: function(other) { return -1; } }); // Prints 'true'! print(instance.getClass() === anotherInstance.getClass());
Listing 17
While this is fine in many cases, passing the implementation to each instance might not always be convenient. Indeed, there are cases where objects must be instantiated through some form of inversion-of-control mechanism, such as those found in dependency injection APIs. In such cases, the third-party APIs typically require a reference to the implementation class, which makes the previous extender mechanism unsuitable.
Fortunately, Java.extend allows implementations to be bound to a class definition rather than being specified for each instance. To do so, you simply need to pass an implementation JavaScript object as the last parameter.
Consider Listing 18, which defines two extender types: FooCallable and BarCallable. When creating instances foo and bar, there is no need to pass implementations. We can also check that instances do not have the same class definition. In fact, FooCallable.class or BarCallable.class can be passed to third-party Java APIs that need instances of java.lang.Class definitions.
var Callable = Java.type("java.util.concurrent.Callable"); var FooCallable = Java.extend(Callable, { call: function() { return "Foo"; } }); var BarCallable = Java.extend(Callable, { call: function() { return "Bar"; } }); var foo = new FooCallable(); var bar = new BarCallable(); // 'false' print(foo.getClass() === bar.getClass()); print(foo.call()); print(bar.call());
Listing 18
Although not illustrated by this example, classes defined with class-bound implementations provide constructors inherited from their superclass. In this example, our objects implicitly extend java.lang.Object and implement java.util.concurrent.Callable; hence, the corresponding class definition simply has a public no-arguments constructor.
Using instance-bound and class-bound implementations. Last but not least, it is possible to combine both instance-bound and class-bound implementations. You can refine the class-bound implementation of all or some of the methods by passing an implementation object to its constructor, as shown in Listing 19.
var foobar = new FooCallable({ call: function() { return “FooBar”; } }); // ‘FooBar’ print(foobar.call()); // ‘true’ print(foo.getClass() === foobar.getClass());
Listing 19
Conclusion
This article covered various scenarios for using Oracle Nashorn as a command-line tool and as an embedded interpreter in Java applications. It also covered the interoperability between Java and JavaScript, including the ability to implement and extend Java types from JavaScript.
Oracle Nashorn is an excellent way to take advantage of a scripting language for polyglot applications on the JVM. JavaScript is a popular language, and the interaction between Java and JavaScript is both seamless and straightforward for a wide range of use cases.
Originally published in the Jan/Feb 2014 issue of Java Magazine. Subscribe today.
About the author
Julien Ponge (@jponge) is a longtime open source craftsman who is currently an associate professor in computer science and engineering at INSA de Lyon. He focuses his research on programming languages, virtual machines, and middleware as part of the CITI Laboratory activities.
(1) Originally published in the Jan/Feb 2014 Edition of
Java Magazine
(2) Copyright © [2014] Oracle. | http://jaxenter.com/oracle-nashorn-a-next-generation-javascript-engine-for-the-jvm-107625.html | CC-MAIN-2014-52 | refinedweb | 3,650 | 50.12 |
Image credit easysolutionweb.com
In this post Laurence Bird covers how to use the power of property based testing and automatic type class derivation, with the end goal of making your tests more concise and less prone to bugs. This article was orignally found on OVO Enegy Tech Blog and is written by Laurence Bird.
"A wise man once told me “never try and explain more than one concept in a blog post”, this christmas I’m throwing caution to the wind and doing just that. Stay with me and this blog post I'm going cover how to use the power of property based testing and automatic type class derivation, with the end goal of making your tests more concise and less prone to bugs.
Type classes
Scalacheck
import org.scalacheck.Prop.forAll val propReverseList = forAll { l: List[String] => l.reverse.reverse == l }
What the above code is doing within the forAll block, is generating a random list of strings, reversing it twice and ensuring that the original ordering of the list is preserved. The code within the forAll block is executed a configurable number of times, with an assertion which is evaluated to determine the test result.
One of the things I really like about this is it removes the need for ever growing utility objects for testing, which consistently need to be updated as case classes evolve over time. Under the hood scalacheck uses an implicit instance of a type class called Arbitrary to configure the generated Arbitrary values for any generic type T which looks like this:
sealed abstract class Arbitrary[T] extends Serializable { val arbitrary: Gen[T] }
That is to say for an instance of a type class, we need a Gen (generator) to generate an instance of this type. Scalacheck provides Arbitrary type class instances for most standard scala types out the box (which can be found here), along with helper methods to create generators (as seen here).
One important feature to be noted here is that an arbitrary needs to be defined for all types and not just primatives. This means as your code base grows and your tests get more complex, as do the Arbitrary values which you need for your tests to function. Arbitrary type classes can be composed, however for large codebases there can be some of boilerplate involved. Those dreaded test utility packages which were once filled with endless varieties of case class instances are now filled with Arbitrary type class instances, which if you're not careful can continually grow.
However if we consider the following case class:
case class Gift(name: String, cost: Long, currency: Currency)
If we have arbitrary values defined for types String, Long and Currency, logically speaking there should be away we can combine these into a single arbitrary instance of Gift without having to hand write a new Arbitrary instance? Luckily we can do just that, using automatic type class derivation: enter Magnolia.
Magnolia
Magnolia abstracts over scala Macros to allow users to generate type classes for case classes, and sealed trait hierarchies. On a high level, it will generate type class instances for you by automagically combining defined primitive type class instances at compile time to a composite type class. This same thing can be achieved using shapeless, however Magnolia distinguishes itself by claiming to offer between 4x and 15x performance improvement. Very exciting I know, let's jump into an example of what a basic derivation object for an Arbitrary in magnolia would look like:
import magnolia._ import scala.language.experimental.macros import org.scalacheck.Arbitrary trait ArbDerivation { type Type class[T] = Arbitrary[T] def combine[T](caseClass: CaseClass[Type class, T]): Type class[T] = ??? def dispatch[T](sealedTrait: SealedTrait[Type class, T]): Type class[T] = ??? implicit def gen[T]: Type class[T] = macro Magnolia.gen[T] }
The combine method will provide the code we need to combine the primitive type class instances which make up all the constructor parameters of a case class, to a single type class instance for that given case class. And the dispatch method will allow us to determine the appropriate type class to use for a sealed trait hierarchy.
Lets move our focus to the combine method, from this we need to derive an Arbitrary[T] from all the parameters on a given CaseClass[Type class, T]. Luckily CaseClass exposes a method which allows us to do just that:
def construct[Return](makeParam: Param[Type class, Type] => Return): Type
To use this method we pass an anonymous function, which defines how to construct an instance of any parameter on a case class from its as associated type class (which in the context of this given example Arbitrary). We can use this to summon an instance of a given case class, from all the Arbitrary type class instances we have in scope of its primatives. At compile time then Magnolia expand this using macros to generate an instance of the Arbitrary type class which represents the whole case class being handled (the source code can be found [here]).
Now I know thats a lot of information, so lets see what makeParam function we would pass to the construct method defined above, in order to construct a value Type, from it's respective type class instance Arbitrary[Type] would look like:
def makeParam[Type](param: Param[Type class, Type]) = { param .type class .arbitrary .pureApply( Parameters.default, Seed.random() ) }
Parameters and seeds in the context of above are simply configuration settings for scalacheck to determine the size of the generated item and the random number generation settings. So this is the makeParam function we need to pass to Magnolia to construct an instance of of a given case class. Lets go back to the original derivation object we saw previously and see where we have got to now:
package com.ovovenergy.christmas import magnolia._ import org.scalacheck.Gen.Parameters import org.scalacheck.rng.Seed import org.scalacheck.{Arbitrary, Gen} import scala.language.experimental.macros trait ArbDerivation { implicit def parameters: Parameters implicit def gen[T]: Arbitrary[T] = macro Magnolia.gen[T] type Type class[T] = Arbitrary[T] def combine[T](ctx: CaseClass[Arbitrary, T]): Arbitrary[T] = { val t: T = ctx.construct { param: Param[Type class, T] => param .type class .arbitrary .pureApply(parameters, Seed.random()) } Arbitrary(Gen.delay(t)) } }
You can see in the final step, we wrap our value of T in an Arbitrary, and voilà! We can now automatically derive composite Arbitrary type classes for any case class, given we have Arbitrary instances for its primitive types in scope. It's worth noting in this case the Gen.delay, ensures that the arbitrary instance is evaluated lazily and each time it is summoned rather than once. Otherwise this would result in the same value being generated continually for each test case.
For fear of information overload I haven't included an explanation of the derivation of sealed traits, but if you're interested the code for this and the rest of the example covered in this post can be found in this example project.
Conclusion
Although a lot has been covered in this post, when you actually go and look at the code required for this derivation it's very concise, surpisingly readable and the compile time is negligible. There isn't a tonne of documentation out there but thats partly because there aren't that many concepts which need to be covered, by reading through their examples on git, and the tutorial it's very achievable to be deriving your own type classes in no time.
It's worth noting that Magnolia is still an experimental library, run time performance hasn't been evaluated and as stated in their documentation it hasn't had the same exposure to real-world datatypes that Shapeless has had. Overall however I've had fun working with it, and the compile time to magic ratio (CMR) makes it a compelling tool to utilise in future projects."
Article found on OVO Energy Tech Blog. Written by Laurence Bird. | https://www.signifytechnology.com/blog/2018/04/boilerplate-free-testing-with-scalacheck-and-magnolia-by-laurence-bird | CC-MAIN-2019-13 | refinedweb | 1,338 | 57.71 |
Typesafe Interview: Scala + Akka is an IaaS for Your Process Architecture
This is an email interview with Viktor Klang, Director of Engineering at Typesafe, on the Scala Futures model & Akka, both topics on which is he is immensely passionate and knowledgeable.
How do you structure your application? That’s the question I explored in the article Beyond Threads And Callbacks. An option I did not talk about, mostly because of my own ignorance, is a powerful stack you may not be all that familiar with: Scala and Akka.
To remedy my oversight is our acting tour guide, Typesafe’s Viktor Klang, long time Scala hacker and Java enterprise systems architect. Viktor was very patient in answering my questions and was enthusiastic about sharing his knowledge. He’s a guy who definitely knows what he is talking about.
I’ve implemented several Actor systems along with the messaging infrastructure, threading, async IO, service orchestration, failover, etc, so I’m innately skeptical about frameworks that remove control from the programmer at the cost of latency.
So at the end of the interview am I ready to drink the koolaid? Not quite, but I’ll have a cup of coffee with the idea.
I came to think of Scala + Akka as a kind of a IaaS for your process architecture. Toss in Play for the web framework and you have a slick stack, with far more out of the box power than Go, Node, or plaino jaino Java.
The build or buy decision is surprisingly similar to every other infrastructure decision you make. Should you use a cloud or build your own? It’s the same sort of calculation you need to go through when deciding on your process architecture. While at the extremes you lose functionality and flexibility, but since they’ve already thought of most everything you would need to think about, with examples, and support, you gain a tremendous amount too. Traditionally, however, processes architecture has been entirely ad-hoc. That may be changing.
Now, let’s start the interview with Viktor...
HS: What is an Actor?
So let’s start from the very beginning! An Actor in the Actor Model is comprised by 3 distinct pieces:
- A behavior
- An address
- A mailbox
The Address is the thing you send messages to, they are then put into the Mailbox and the Behavior is applied to the messages in the mailbox—one at a time. Since only one message is processed at a time, you can view an Actor as an island of consistency, connected to other actors via their Addresses and by sending and receiving messages from them.
There are 3 core operations that an Actor needs to support in order for it to qualify as an Actor.
- CREATE—an Actor has to be able to create new Actors
- SEND—an Actor needs to be able to send messages to Actors
- BECOME—an Actor needs to be able to change its behavior for the next message
Since what you send messages to is an Address, there is an indirection which allows the Mailbox and Behavior to live essentially anywhere, as long as the message can get routed there. This is also referred to as Location Transparency.
HS: How does Akka implement the Actor model?
Like the Actor model but requests are served by a designated pool configured on a per-actor basis. This allows for fine-grained control over execution provisioning and a means of bulkheading parts of your application from other parts of the application. Akka also allows to configure the mailbox implementation on a per-actor basis, which means that some actors might need a bounded one, some might want a priority-based one, some might want a deduplicating one, or fine-tuning things like overflow protection with head-dropping vs. tail-dropping etc.
Comparing with Threads, Akka Actors are extremely light-weight, clocking in at around 500b per instance, allowing for running many millions of actors on a commodity machine. Like Erlang Processes, Akka Actors are location transparent which means that it is possible to scale out to multiple machines without changing the way the code is written.
Akka Actors do not block on a thread when not having anything to process, which allows for high throughput at low latency as wake-up lag for threads can be avoided. It is also possible to configure the number of messages to process before handing back the thread to the pool, it is also possible to specify a time slice which will allow for the actor to keep processing new messages as long as it hasn’t run out of its time slice before handing back the thread to the pool.
This allows to tune for fairness or for throughput. Akka Actors will not be preempted when a higher-priority message arrives, but it is possible to have multiple actors sharing the same mailbox, which can mitigate this if required.
Inspired by Process Linking from Erlang, Akka Actors form a strict hierarchy, where actors created by an actor from a child-parent relationship where the parent is responsible for handling the failure of the children by issuing directives on how to deal with the different types of failure that can occur, or choose to escalate the problem to its parent. This has the benefit of creating the same kind of self-healing capabilities exhibited by Erlang. It is also possible for an Akka Actor to observe when another Actor will not be available anymore, and handle that accordingly.
HS: Can you give an example of how Process Linking works in practice?
Actor A receives message B, which entails a potentially risky operation C (could be contacting an external server or do a computation that might blow up) instead of doing that work itself, it may spawn a new actor and let that actor do this risky operation. If that operation fails, then the exception is propagated to A (being the "parent") who can decide to restart the failed actor to retry, or perhaps log that it failed. No matter if it fails or not, A has not been at risk, as the dangerous operation was delegated and managed. In the case of a more serious error that A cannot manage, A would escalate that error to its parent who might then act upon it instead.
HS: Can you go into some more detail about bulkheading, why is it important and how it's accomplished in Akka?
The Bulkhead Stability Pattern is from EIP by Nygard. It's about gaining stability by compartmentalization, just like bulkheads for a boat.
Bulkheading of Threads in Akka is accomplished by assigning different thread pools to different segments of your actor hierarchy, which means that if one thread pool is overloaded by either high load, DoS attempt or a logic error creating an infinite loop for instance, other parts of the application can proceed since their Threads cannot be "infected" by the failing thread pool.
HS: Tail-dropping?
When it comes to dealing with asynchronous message passing systems one needs to decide what contention management policies one should use. Back-pressure is one policy, dropping messages is another, and if you decide to drop messages, which ones do you drop. Usually this is something that needs to be decided on a "per service" basis, either you drop the oldest (the one at the front of the queue, i.e. front-dropping) or the newest (tail-dropping). Sometimes one wants to have a priority queue so that the important messages end up at the front of the queue.
HS: What about these abilities helps programmers develop better/faster/robuster systems?
In any system, when load grows to surpass the processing capability, one must decide how to deal with the situation. With configurable mailbox implementations you as the developer can decide how to deal with this problem on a case-by-case basis, exploiting business knowledge and constraints to make sure that performance and scalability is not compromised to get the robustness (which is more than likely the case for a one-size-fits-all solution like backpressure).
HS: How does the location transparency work?
Each Akka Actor is identified by an ActorRef which is similar to Erlang PIDs, a level of indirection between the instance of the Actor and the senders. So senders only ever interact with ActorRefs which allows the underlying Actor instance to live anywhere (in the world potentially).
HS: Is there latency involved in schedule an Akka thread to execute?
When an Actor doesn't have any messages it is not scheduled for execution, and when it gets a message it will attempt to schedule itself with the thread pool if it hasn't already done so. The latency is completely up to the implementation of the Thread Pool used, and this is also configurable and extensible/user replaceable. By default Akka uses a state-of-the-art implementation of a thread pool without any single point of contention.
HS: Given you can configure the number of messages to process before handing back the thread to the pool, that makes it a sort of run to completion model and the CPU time isn't bounded?
Exactly.
HS: Can it be interrupted?
No, but as soon as one message is done, it will check if it still has time left, and if so it will pick the next message.
HS: Can you ensure some sort of fair scheduling so some work items can make some progress?
That is up to the ThreadPool implementation and the OS Scheduler, fortunately the user can affect both.
HS: When multiple Actors share the same mailbox, if some actor has the CPU, it won't give up the CPU for the higher priority message to be executed? How does this work on multiple CPUs?
If you have 10 Actors sharing a single priority mailbox and a thread pool of 10 Threads,
there is more opportunity for an actor to be done to pick up the high-priority work than if it's a single actor that is currently processing a slow and low priority message. So it's not a watertight solution, but it improves the processing of high-prio messages under that circumstance.
By placing requirements on priority of messages increases lock contention and sacrifices throughput for latency.
HS: How do Actors know where to start in a distributed fabric?
That is done by configuration so that one can change the production infrastructure without having to rebuild the application, or run the same application on multiple, different infrastructures without building customized distributions.
HS: How do Actors know how to replicate and handle failover?
Also in configuration.
HS: How do you name Actors?
When you create an Akka Actor you specify its name, and the address of the actor is a URI of its place in the hierarchy.
Example: "akka.tcp://applicationName@host:port/user/yourActorsParentsName/yourActorsName"
HS: How do you find Actors?
There are a couple of different ways depending on the use-case/situation, either you get the ActorRef (every Akka Actor is referred to by its ActorRef, this is equivalent to Address in the Actor Model) injected via the constructor of the Actor, or you get it in a message or as the sender of a message. If you need to do look ups of Actors there are 2 different ways, 1 is to create an ActorSelection, which can be described as query of the hierarchy, to which you can send messages and all actors matching the query will get it. Or you can use "actorFor" which lets you look up a specific actor using its full URI.
HS: How do you know what an Actor can do?
You don't. Well, unless you define such a protocol, which is trivial.
HS: Why is indirection an important capability?
The indirection is important because it clearly separates the location of the behavior from the location of the sender. An indirection that can even be rebound at runtime, migrating actors from one physical node to another without impacting the Address itself.
HS: How does you not have contention on you thread pools?
Every Thread in that pool has its own task-queue, and there is no shared queue. Tasks are randomly distributed to the work-queues and when a Thread doesn't have any tasks it will randomly work steal from other Threads. Having no single point of contention allows for much greater scalability.
HS: Could you please give a brief intro into Scala and why it's so wonderful?
Sure!
I come from a C them C++ then Java background and discovered Scala back in 2007.
For me Scala is about focusing on the business-end of the programming and removing repetition & "ritual" code.
Scala is a unifier of object orientation and functional programming, as well as it is trying to minimize specialized constructs in the language and instead giving powerful & flexible constructs for library authors to ad functionality with.
I personally enjoy that Scala is expression oriented rather than statement oriented, which simplifies code by avoiding a lot of mutable state which tend to easy turn into an Italian pasta dish.
A statement doesn't "return"/"produce" a result (you could say that it returns void), but instead it "side-effects" by writing to memory locations that it knows about, whereas an expression is a piece of code that "returns"/"produces" a value.
So all in all Scala lets me write less code, with less moving parts making it cheaper to maintain and a joy to write. A great combination in my book!
And not to forget that it allows me to use all good Java libraries out there, and even be consumed by Java (Akka can be used by both Scala and Java as an example).
HS: How do Scala futures fit into the scheme of things?
Alright. So I was a co-author of the SIP-14 proposal that was included in Scala 2.10. So the following explanations and discussions will center around that.
A Future is a read-handle for a single value that may be available at some point in time. Once the value is available it cannot and will not be changed.
A Promise is a write-handle for a single value that should be set at some point in time. Once the value is available it cannot and will not be changed.
The value of a Future/Promise may either be a result or an exception.
(You can get the corresponding Future from a Promise (by calling the future()-method on Promise) but not vice versa)
The strength of this model is that it allows you to program as if you already have the result, and the logic is applied when the result is available, effectively creating a data-flow style of programming, a model which easily can take advantage of concurrent evaluation.
When you program with Futures you need to have an ExecutionContext which will be responsible for executing the logic asychronously, for all intents and purposes this is equivalent to a thread pool.
As an example in Scala:
import scala.concurrent.{ Future, ExecutionContext }
import ExecutionContext.Implicits.global // imports into scope the global default execution context
// lets first define a method that adds two Future[Int]s
// This method uses a Scala for-expression, but it is only sugar for:
// f1.flatMap(left => f2.map(right => left + right))
// it asynchronously and non-blockingly adds the result of future1 to the result of future2
def add(f1: Future[Int], f2: Future[Int]): Future[Int] = for(result1 <- f1; result2 <- f2) yield result1 + result2
// Then lets define a method that produces random integers
def randomInteger() = 4 // Determined by fair dice roll
val future1 = Future(randomInteger()) //Internally creates a Promise[Int] and returns its Future[Int] immediately and calls "randomInteger()" asynchronously and completes the promise with the result which is then accessible from its Future.
val future2 = Future(randomInteger()) // same as above
val future3 = add(future1, future2)
None of the code above is blocking any thread, and the code is declarative and doesn't prescribe _how_ the code will be executed. The ExecutionContext can be switched without changing any of the logic.
So what happens if the value is exceptional?
val future3 = add(Future(throw new BadThingsHappenedException), Future(randomInteger()))
Then the exceptional completion of future1 will be propagated to future3.
So lets say we know a way to recover from BadThingsHappenedExceptions, let's use the recover method:
val future1a = Future(throw new BadThingsHappenedException)
val future1b = future1a recover { case e: BadThingsHappenedException => randomInteger() }
val future2 = Future(randomInteger())
val future3 = add(future1b, future2)
So here we first create future1a, which will be completed exceptionally with a BadThingsHappenedException,
then we call the "recover" method on future1a, and provide a (partial) function literal that can convert BadThingsHappenedExceptions to an Int by calling our amazing randomInteger() method, the result of "recover" is a new future, which we call future1b.
So here we can observe that futures are only completed once, and the way to transform the results or exceptions of a future is to create a new Future which will hold the result of the transformation.
So from a less contrived example standpoint, we can do things like:
val future1 = Future(callSomeWebService) recover { case _: ConnectException => callSomeBackupWebService() }
val future2 = Future(callSomeOtherWebService) recover { case _: ConnectException => callSomeOtherBackupWebService() }
val future3 = for(firstResult <- future1; secondResult <- future2) yield combineResults(firstResult, secondResult)
future3 map { result => convertToHttpResponse(result) }
recover { case _ => HttpResponse(400) } // underscore means "anything"
foreach { response => sendResponseToClient(response) }
So what we do here is that we asynchronously call a couple of web services, and if any of them fail with a ConnectException we try to call some backup webservice, then we combine the results of those web-service responses into some intermediate result, then we convert that result into some HttpResponse, if there has been any exceptional things happened this far, we'll recover to a HttpResponse which will have a 400-status and as the very last step we send our HttpResponse to some client that requested it.
So in our code we never wait for anything, what we do is to declare what we want to happen when/if we have a result, and there is a clear flow of data.
HS: Is a Future a scalar or can it have structure (arrays, maps, stucts, etc)?
It is a single memory slot that can only be written once. So what you write to it should be a value (i.e. immutable) but can be a struct, a Map or what have you.
HS: How do you implement more interesting state machines where results from one state are used in another? I think that's what I have a problem with a lot of times. I would prefer to go to clear error state where errors handled, for example. In the linkedin example they parallelize three separate calls and have a bit of error handling code somewhere that doesn't seem to know where the error came from or why, which makes crafting specific error response difficult.
I understand what you mean, but I view it differently. With Futures you deal with the failure where you can, just as you deal with exceptions in Java where you can. This may or may not be in the method that produces the exception, or in the caller, or in the callers caller or otherwise.
You could view Futures (with exceptional results) as an on-heap version of exception handling (in contrast to plain ex
Exception handling which is on stack, meaning that any thread can choose to deal with the exception and not only the thread that causes it).
HS: A lot of the never wait for anything seems normal to me in C++. Send a message. All IO is async. Replies comes back. Gets dropped into the right actor queue.
I hear you! A lot of the good things we learned from C/C++ still applies, i.e. async IO is more resource efficient than blocking IO etc.
HS: The actor state machine makes sense of what to do. Thread contexts are correct. In your example there's no shared state, which is the simplest situation, but when shared state is involved it's not so clean, especially when many of these are bits of code are execution simultaneously.
Of course, but it depends on what one means by shared state. Something that I find useful is "what would I do if the actors were people and they'd be in different locations?"
Sharing state (immutable values) via message-passing is perfectly natural and in reality mimics how we as humans share knowledge (we don't flip each others neurons directly :) )
Reader Comments (4)
Thanks for the interview, the Akka implementation of actors has been interesting for quite a while.
Is there a good (public) example of clustering with Akka? In this interview you talk about configurable mailboxes but I'm not sure where a good example for that is either. Clustering would obviously support reliability and also horizontal scalability.
Thanks for any references,
John
Nice article, thanks!
But I think the code examples need syntax highlighting urgently! (e.g. put them in a gist?)
Hi John,
Sorry for the late response.
For the most up-to-date documentation on the clustering, see this link:
The Akka reference documentation is around 500 pages(!)
Here's the documentation on mailboxes:
Does that answer your questions?
Cheers,
√
Great interview. Keep up the good work! | http://highscalability.com/blog/2013/5/8/typesafe-interview-scala-akka-is-an-iaas-for-your-process-ar.html | CC-MAIN-2017-09 | refinedweb | 3,581 | 58.11 |
Using Unsafe Code and Pointers in C#
Introduction
One of the biggest features of the .NET platform is the support for type safety. This means that the Common Language Runtime – the engine of .NET - guarantees that there will not be any type errors (issues which generally arise because of discrepancy between different data types for an application’s constants, variables and methods).
The benefits of type safety include:
- Illegal operations are avoided.
- No wild pointers – a pointer of one type is considered as pointer of other type
- Avoiding buffer overflow
Any method, type or code block can be defined as unsafe using the unsafe C# keyword.
To compile the code, we need to use the “/unsafe” compiler flag.
Caveat: Tagging your code as unsafe can result in security risks in your code.
The Pointer Basics
In unsafe code, you can declare a type to be a pointer type.
The declaration is shown below:
type* typename;
For example, to declare a pointer to an int, we would declare it as:
int* ptr_MyVal;
If you want to declare multiple pointer types, we declare them as:
int* ptr_MyVal1, ptr_MyVal2;
Pointers can be declared for:
- all scalar types: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal and bool.
- Enum types
- Pointer types (pointers to pointers) (type**) - e.g. int**
- User-defined structs
Let us take a look at a simple C# application to do some pointer arithmetic.
We will create a pointer and use the pointer to add a number to the pointee.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PointersDemo { class Program { static void Main(string[] args) { int valueToBeOperated = 10; unsafe { int* ptr_value = &valueToBeOperated; Console.WriteLine("valueToBeOperate = " + valueToBeOperated); Console.WriteLine("valueToBeOperate via pointer = " + *ptr_value); *ptr_value += 10; Console.WriteLine("valueToBeOperate = " + valueToBeOperated); Console.WriteLine("valueToBeOperate via pointer = " + *ptr_value); } } } }
In the above listing, we are declaring a pointer to an int and then using the pointer reference to add 10 and then print the output.
To do this, you will have to do two things.
First, the code, which uses pointers will need to be declared in an unsafe context (see the highlighted section).
Next, we need to declare to the compiler that we want to compile unsafe code. In Visual Studio, we can do it by changing the Project Properties.
Allow Unsafe Code
This signals to the compiler to pass the “/unsafe” flag to the csc.exe compiler.
The output of the above code is:
valueToBeOperate = 10 valueToBeOperate via pointer = 10 valueToBeOperate = 20 valueToBeOperate via pointer = 20
Next, we can take an advanced look to pointers.
In our second case, we will look at pointers to an array.
When we need pointers to objects in the heap, we need to use the fixed keyword to annotate the pointer, to indicate to the compiler that the objects must be fixed to avoid changing the location the pointer is referencing. This results in the object not moving when memory management operations are done.
// Listing 2- Array pointers int[] myArray = new int[5] { 1, 2, 3, 4, 5 }; fixed (int* ptr_array = &myArray[0]) { int* ptr_ptr = ptr_array; // pointer to a pointer Console.WriteLine("*ptr_array = " + *ptr_array); Console.WriteLine("**ptr_ptr = " + *ptr_ptr); *ptr_array += 10; Console.WriteLine("*ptr_array = " + *ptr_array); Console.WriteLine("**ptr_ptr = " + *ptr_ptr); ptr_ptr++; Console.WriteLine("*ptr_array (does not change) = " + *ptr_array); Console.WriteLine("**ptr_ptr (changes to the next array element) = " + *ptr_ptr); }
In the above snippet, we declare a pointer to an array, ptr_array. Notice that we need to decorate it with the fixed keyword (highlighted).
When we add 10 to *ptr_array, we are actually dereferencing to the first element and adding 10.
When we increment ptr_ptr (pointer to the pointer to the array), we are telling the pointer to move to the next array element.
The output of the above snippet is:
*ptr_array = 1 **ptr_ptr = 1 *ptr_array = 11 **ptr_ptr = 11 *ptr_array (does not change) = 11 **ptr_ptr (changes to the next array element) = 2
The complete listing of the above code including a working Visual Studio 2013 project is available at PointersDemo
.
Summary
In this article, we learned about using unsafe code and pointers in! | http://www.codeguru.com/csharp/using-unsafe-code-and-pointers-in-c.htm | CC-MAIN-2017-26 | refinedweb | 685 | 56.05 |
This is one of those long overdue posts (and yes there are certainly many more where it came from in my drafts folder) regarding some of the incorrect instructions about setting up Autodiscover which can be found on the Internet.
What am I wibbling about? Well repeatedly over the last 5 years or so since Exchange 2007 shipped, multiple sources have claimed that one *MUST* configure the InternalURL and ExternalURL on all of your Autodiscover Virtual Directories. It does not help that TechNet also says the same thing for Exchange 2007 & 2010.
Setting the InternalURL and ExternalURL on the Autodiscover Virtual Directory is not required, and has no effect on your configuration. You can knock yourself out and change it if it makes you feel good, but it's pretty pointless!
Let’s look to see what Autodiscover is doing and why we do not have to set InternalURL or ExternalURL values on the Autodiscover Virtual Directory.
Autodiscover – Bring The Action!
The below screenshot shows a default Exchange 2010 installation. Note that the InternalURL and ExternalURL parameters are not filled in by default for any of the Autodiscover virtual directories.
So let us check that Autodiscover is actually working, and we will use the Test-OutlookWebServices cmdlet. This example retrieves the information for the Administrator account (yes kids, don’t do this at home
) and as you can see the relevant information is found and rendered onto the screen.
So that is good, and the InternalURLs are not entered onto the Autodiscover Virtual Directories. These values are obtained by directly querying Active Directory. What about machines that cannot query AD directly to locate the Autodiscover endpoint?
Machines that are not domain joined or are outside of the corporate network cannot get to AD to issue any queries. For such scenarios DNS name resolution to well known names is the only way to locate the Autodiscover endpoint. As covered on more detail here the flow looks like this:>
Sooooooooooooooooooooooooo
If Autodiscover is working, clients are getting the right data and we do not have the URLs filled in on the Autodiscover Virtual Directories then what gives? How is this possible?
As mentioned in this post on Autodiscover, domain joined machines that are on the internal network locate the Autodiscover endpoint by directly querying AD. They look for Service Connection Point (SCP) objects that have a well known GUID and AD returns a list to the Outlook client. Outlook will get either an in-site list or out of site list of SCP endpoints. It will not get both. The SCP contains the URL that the internal domain joined Outlook client will connect to using HTTPS. This and the AD Site coverage can be seen below.
EDIT 3-4-2013: Please note that I am *NOT* advocating that the AutoDiscoverServiceInternalUri is left at the default. It is here for explanation purposes, and to get into why it should be pointed to a load balancer and what issues that causes with certificates means I have to finish another one of those draft posts……
Please see the comments at the bottom of the post for full details. Thanks for the feedback!!
We can tell how Outlook located the Autodiscover endpoint by running a Test E-Mail AutoConfiguration, and looking at the Log tab. Note that the URL was located by SCP.
The SCP object can be found in AD at the following path:
CN=exchangeserver,CN=Autodiscover,CN=Protocols,CN=exchangeserver,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=org name,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domain,DC=com
On the SCP object there are a couple of values that interest us. Firstly the attribute called serviceBindingInformation is where the AutoDiscoverServiceInternalUri data is stored. Secondly the attribute called keywords holds the AutodiscoverSitescope value.
For external domain joined machines, or those in a workgroup they both have no method to directly query AD for the SCP so they will only use DNS to locate the Autodiscover endpoint. Again this is mentioned in the previous Autodiscover post.
The Big Reveal
(well almost)
So as you can see everything is working fine without setting the InternalURL or ExternalURL on the Autodiscover Virtual Directory. Now that we have established, and proved by testing, that it is not needed let’s answer the burning question about why it’s actually there.
The reason for this is pretty simple. In the schema that defines Exchange virtual directory objects the InternalURL and ExternalURL are mandatory. So every object of class Exchange Virtual directory must have these attributes. Thus they are present on the Autodiscover virtual directory as they are inherited. Exchange does not use them on the Autodiscover Virtual Directory, but they are heavily used to configure proxy and redirection for the other Virtual Directories – OWA for example.
If you look at the Exchange 2013 Set-AutodiscoverVirtualDirectory cmdlet documentation on TechNet, you will note that the InternalURL and ExternalURL attributes are not present.
Cheers,
Rhoderick
To add: if you use certificates without server names, you do have to change the autodiscover URL listed in the SCP. Otherwise Outlook clients will get a certificate name mismatch. You can change this specific autodiscover URL per server via Set-ClientAccessServer
technet.microsoft.com/…/bb125157.aspx
I agree with Dave. The current recommendation is not to include server FQDN on the certificates so setting the AutoDiscoverServiceInternalUri to the load balancer VIP name is recommended for all deployments.
Amen brother.
Hi folks,
I totally agree that planning CAS namespaces is a critical and often overlooked aspect of an Exchange deployment.
The SCP should indeed be pointed to a load balanced value when applicable. The point of this post was not to dive into that, but to focus on the Autodiscover VDir aspect. Hence I wanted to show that a vanilla configuration works, and did not want to muddy the water by changing it.
Which reminds me, I should go back and finish that certificate post I started a year ago…….
Cheers,
Rhoderick
Oh – Nice T-Shirt BTW Andrew 🙂
I had forgotten how bad the colour was!
@Rhoderick: I understand completely that you wanted to focus on this aspect, certainly something that could be confusing for less experienced IT Pros. However, my concern was that this post would come across as if you should do nothing with the Autodiscover URL itself. But I certainly understand why you wanted to keep the certificate requirements apart, it's something that you could write books about 🙂
Are you planning to write it also with Lync IM/UM, SharePoint and OWAS/WAC integration in mind?
Hi Dave,
I'll edit the above to highlight the best practice around changing the URL. Its was something I was wrestling with — do I write this for the people who have load balancers, or try to include those with no LB devices? The customers that you and I deal with will be the former, but I didn't want to exclude the latter.
I'm engaged on the Exchange side primarily right now, but I should do some more Lync.
I did one of the first (if not the first) OCS 2003 deployments in Canada and that taught me so many aspects of Certificates, and what NOT to do with them, that Exchange 2007 was easy 🙂
Cheers,
Rhoderick
One more thing to note: You said:
If you look at the Exchange 2013 Set-AutodiscoverVirtualDirectory cmdlet you will note that the InternalURL and ExternalURL attributes are not present.
But it actually does exist. I'm running a pure Exchange 2013 environment and was able to put those parameters in. Even though its not listed on the TechNet site. Seems to be hidden.
Hi Gus,
That's correct – they are not listed on TechNet but you can still find them in the schema.
Cheers,
Rhoderick
Hey,
I've read in a few places that the AutodiscoverVirtualDirectory Urls are required for Lync client to integrate with EWS properly.
Do you know if this is true?
Thanks
Well you prompted me to finish yet another draft post 🙂
blogs.technet.com/…/exchange-autodiscover-amp-lync.aspx
In short, no. UC devices leverage DNS to locate Exchange AutoD. Check out the whitepaper that is linked in the above post.
Cheers,
Rhoderick
Thank you,
useful and clear.
Rocco Daniele Ciaravolo
Cle IT staff
For an O365 migration all autodiscover records are set correctly. Non-domain joined machines work find inside and outside the corporate network. Domain joined PCs work correctly outside but not inside the corporate network. The AD settings are clearly
over-riding the DNS entries.
@ IDTTHISC
Where are your AutoD records pointing to internally and externally?
Why do you not think this is correct?
Cheers.
Rhoderick
Rhoderick,
I found this post when trying to solve the issue of using an external URL for my internal URL for the purpose of satisfying the certificate rules of no longer issuing .local domains on SSL. I followed the instructions at this link…
I made the changes to my internal DNS as well. I have triple checked the settings. I’m still having an issue of my internal domain clients automatically using the server.domain.local url even if I do a manual set up and put in server.domain.com url it will
switch back to the local on its own which in turn gives a certificate error. For the moment I have had to set the ssl to ignore so that my users can continue to use their mail without the annoyance. I ran the test command as you have shown and it’s successful
up until it tests the .local and then it gives an error.
Do you have any insight on how I can fix this. I am a super noob on exchange and this is 2010 btw.
Thanks
Hi Rob,
Do an test outlook configuration from Outlook itself.
Do you get the expected URLs for all services?
Cheers,
Rhoderick
I seemingly do get the correct servers. When using the account on the domain it will show the local server and naturally give a certificate error. I can’t seem to get rid of the error without choosing ignore in IIS for autodiscover. Here are my results
of the outllook test. It does list the local server should that part list the external url like the rest?
Protocal: Exchange RPC
Server: Server.domain.local
Login Name: xxxxxx
Availability Service URL:
OOF URL:
OAB URL:-…….
Unified Message Service URL:
Auth Package: Unspecified
Protocol:Exchange HTTP
Server: server.domain.com
Login Name: xxxxxxx
SSL: yes
Mutual Authentication: yes
Availability Service URL:
OOF URL:
OAB URL:-…….
Unified Message Service URL:
Auth Package: NTLM
Certified Principal Name: msstd:server.domain.com
In that – you expect to see server.domain.com — correct?
one thing worth eliminating is Outlook using stale data. Open up the Account settings, highlight the Exchange profile and click repair.
Does that change anything?
Cheers,
Rhoderick
Yes that is what I expect to see. But since it still sees the server as .local then the certificate warning comes up. I did a repair and that gave the same results. Does everything look correct to you given that I am trying to use the external url as the
internal and it is seeing the server at the .local address. Is this correct or should it be seeing it as the external? Im a bit confused. If there is a better way to do this then I am game for that. The server works for send receive except for the certificate
error. When I ran the test – outlookwebservices I got errors when it got to all the internal url’s.
hi Rob,
to complete you setup with single name certificate you need also to create SRV record for AutoDiscover instead of A or C Name. this SRV record is must if you are using Single Name Certificate. do it for Internal And public DNS.
good luck
Hello there, I would like an advice about the issue I currently encounter. Outlook client have an accessibility problem, they cannot have free/busy information, OOO problem, etc… I’ve turned myself to the autodiscover and I’m currently trying to know
what is going on.
Outlook clients connects to an autodiscover URI who redirect them to the load-balancer, but they seems to receive wrong informations about one of our CAS. The wrong URL point to our CAS, and I think this is where the problem is.
Except I cannot find where to remove this URI :
– i’ve first had a look on the Set-ClientAccessArray and Set-ClientAccessServer, set the internalURI to the good parameters but that doesn’t change anything (like you explained). So I tried a Set-AutodiscoverVirtualDirectory and set the good URI too. but nothing
has changed.
– After seeking into the web, i’ve found some informations about AD Parameters, and SCP connectors. After looked at the SCP parameters for this server, they were correct too (good URI, good AD sites).
I don’t know where to look now, and i’m a little confuse. If you can explain to me what do I’ve missed ?
Thank you so much !
What exactly have you checked ? List the PowerShell commands please.
Cheers,
Rhoderick
Hello, first thank you to take the time to answer me,
I’ve type those commands :
– Set-ClientAccessServer -Identity SERVERNAME -AutoDiscoverInternalURI
– Set-AutodiscoverVirtualDirectory -Identity SERVERNAME -InternalURL
i verified the Site Scope too (The Autodiscover of those CAS is configured for 5 different sites).
The Test-OutlookWebServices works fine for me, it says that the autodiscover works correctly (but we’ve a little latency, like 150ms)
I’ve checked the serviceBindingInformation and it match the correct URL for the suspicious CAS
I’ve check the Keywords value too and it’s correctly set for the used sites.
In fact I’ve tried to check the configuration of another CAS of my DAG but I couldn’t see where I’ve failed the configuration for the incriminated server.
I’ve check the DNS entries and it’s fine (it is working well for my Other CAS)
I also tried to run an autoconfiguration test from a Vm who it pointing directly on my CAS and I’ve got this URL :.
Autodiscover is most likely not the cause of the cert prompts.
I don’t see you checking EWS, OAB, ECP, POP, IMAP, UM EAS…..
Check all CAS servers for those URLs
Cheers,
Rhoderick
Hello Rhoderick,
Thank you for your help, there is some web services that aren’t well configurated, like EWS or ECP.
I’ve just changed the bad values and I hope it’ll return to normal state soon.
Thank you very much !
Good stuff!
Then send some flowers and an apology note to Autodiscover since it was innocent of all crimes 🙂
Remove the URLS from the autodiscover virtualdirectory – set them to $NULL
And if you don’t see the valid ones being returned do an IISRESET in a defined change window.
Cheers,
Rhoderick
This is a post for reference purposes. The intent is to look at how Outlook will locate the correct Autodiscover
This is link throw down for items that we discussed in a Exchange 2013 workshop which I delivered in
What is deploy hybrid migration with enabled MRS.
Can i deploy hybrid migration only enabled auto discover. | https://blogs.technet.microsoft.com/rmilne/2013/04/02/busting-the-set-autodiscovervirtualdirectory-myth/ | CC-MAIN-2019-39 | refinedweb | 2,555 | 63.19 |
The assignment is :
Write a C++ program that calculates the volume of 3 different geometric shapes. Your
program should give the user a menu like the following and repeat until the user wants to stop.
Volume Calculation Program
Select the Number of Your Chosen Object
1. Dumbbell
2. Axle
3. Spear
When the user selects one of the 3 objects, the program should then request the appropriate measurements (in inches) and then calculate and display the volume of that object. The result should be printed showing cubic-inch units with 3 decimals of precision.
Axle: 2 cylinders and a rod
Dumbbell: two spheres and a rod
Spears: two cones and a rod
Program requirements and Assumptions
Formulas and Abbr.
II P1 = 3.141 59
r radius
= height (or length)
Vol. of a sphere = 4I3flr3
Area of a circle = flr2
Vol. of a cylinder fl9b
Vol. of a cone = 1/3fJr2h
1. The rod-end fits against the dumbbell ball snugly; there is no “air-gap’. You may assume that there is no loss of volume of the ball when the rod is fitted against it.
2. The radius of the dumbbell and axle center rods cannot be larger than half the radius of the ball or wheel. Do not make calculations if the rod radius is more than half of the ball or wheel radius. Give the user an error message instead. For example, if the user enters a radius of 5 inches for the ball or wheel, the rod radius must be no larger than 2.5 inches.
3. The spear’s cone base has exactly the same radius as the connecting rod.
4. Output is to both the monitor and the printer.
This is so crazy, here is what I've got so far:
#include <cstring> #include <iostream> #include <iomanip> #include <cmath> #include <fstream> #include <string> #include <ctime> using namespace std; int main() { string Dumbell = '1'; string Axel = '2'; string Spear = '3'; double radius, height, length, width, ball, rod, wheel, cone, vol; double pie = 3.14159; cout<<"Which shape are you working with"<<endl; cin>>'1' || '2' || '3'; if (cin == 1) { cout<<"Please enter the radius (of ball), height, length of object & radius of rod"<<endl; cin>>radius>>height>>length>>rod; cout<<"Dumbell: "<<endl; cout<<"Radius of the ball: "<<radius<<endl; cout<<"Radius of the rod: "<<rod<<endl; cout<<"Length of rod: "<<heigth<<endl; vol = (4/3) * 3.142 * radius * radius * radius: cout<<"The volume of the dumbbell is "<<vol<<" "<<"cubic inches"<<endl; } else if (cin == 2) { cout<<"Please enter the radius of the wheel, radius of the rod, length of the rod, width of the wheel"<<endl; cin>>radius>>rod>>length>>width; cout<<"Axle: "<<endl; cout<<"Radius of the wheel: "<<radius<<endl; cout<<"Radius of the rod: "<<rod<<endl; cout<<"Length of the rod: "<<length<<endl; cout<<"Width of the wheel: "<<width<<endl; vol = ((pie * (radius *radius) * length) * 2) cout<<"The volume of the axel is "<<vol<<" "<<"cubic inches"<<endl; } else if (cin==3) { cout<<"Please enter the radius (of rod), the length of the rod & heigth of the cone"<<endl; cin>>radius>>length>>heigth; cout<<"Spear: "<<endl; cout<<"Radius of the rod: "<<radius<<endl; cout<<"Length of the rod: "<<length<<endl; cout<<"Height of the cone: "<<heigth<<endl; vol = (1/3 * pie * (radius * radius) * height) * 2; cout<<"The volume of the spear is "<<vol<<" "<<"cubic inches"<<endl; return 0; }
Thx for assistance in advance. | https://www.daniweb.com/programming/software-development/threads/91041/c-shape-calculations | CC-MAIN-2017-26 | refinedweb | 568 | 65.05 |
1.4 Code Obfuscation
The first protection technique we’re going to look at is code obfuscation. What’s particularly interesting about obfuscation is that it’s a double-edged sword: Bad guys use it to protect their malware from discovery (you will see this in the next section), good guys use it to protect their programs from reverse engineering, and bad guys can also use it to destroy secrets (such as watermarks) stored in the good guys’ programs.
In the most general sense, to obfuscate a program means to transform it into a form that is more difficult for an adversary to understand or change than the original code. We are deliberately vague about defining “difficult,” but we typically take it to mean that the obfuscated program requires more human time, more money, or more computing power to analyze than the original program. Under this definition, to distribute a program in a compiled form rather than as source code is a form of obfuscation, since analyzing binary machine code is more demanding than reading source. Similarly, we would consider a program that has been optimized to be more obfuscated than one that has not, since many code optimizations make analysis (both by humans and tools such as disassemblers and decompilers) more onerous.
However, the tools and techniques we present in this book go further than compilation and optimization in order to make a program hard to understand. In contrast to an optimizer that rearranges code for the purposes of efficiency, a code obfuscator transforms code for the sole purpose of making it difficult to analyze. A negative by-product of obfuscating transformations is that the resulting code often becomes larger, slower, or both. The author of the code has to decide whether the protection that the transformations afford is worth this overhead.
Obfuscation is often confused with security through obscurity, a term (used contemptuously) for the “branch” of cryptography or security where the algorithms used are expected to remain secret. This is in contrast to mainstream research that teaches that you must assume that all algorithms are public, and the only secrets you may keep are the cryptographic keys, and so on, that are the inputs to the algorithms. The idea is that many eyes examining the same algorithm or piece of code will likely be able to find flaws, and the more eyes that have failed to find a flaw, the more confident you can be that the algorithm is, in fact, secure. This principle is frequently violated, and you’ll often see unscrupulous web-sites advertise “military-strength, proprietary” cryptographic algorithms, arguing that “since no one knows what our algorithm does, this will make it that much harder to break.” The same argument is sometimes made in reverse by software vendors like Microsoft: “Open-source software is inherently more vulnerable to attacks than our closed-source code since you can easily read the source and find bugs to exploit.” We know from experience that both claims are false. Hackers have no problem finding holes in closed-source software, and once a proprietary algorithm is leaked (which, inevitably, happens) it is often found to have serious and exploitable flaws.
As we define it in this book, obfuscation isn’t security through obscurity. As with research in cryptography, we generally expect that the obfuscating code transformation algorithms are known to the attacker and that the only thing the defender can assume is kept secret are the seeds that determine how and where these algorithms are applied.
Listing 1.1. Obfuscation example. The original unobfuscated version of the code can be found on the book’s Web site.
public class C { static Object get0(Object[] I) { Integer I7, I6, I4, I3; int t9, t8; I7=new Integer(9); for (;;) { if (((Integer)I[0]).intValue()%((Integer)I[1]).intValue()==0) {t9=1; t8=0;} else {t9=0; t8=0;} I4=new Integer(t8); I6=new Integer(t9); if ((I4.intValue()^I6.intValue())!=0) return new Integer(((Integer)I[1]).intValue()); else { if ((((I7.intValue()+ I7.intValue()*I7.intValue())%2!=0)?0:1)!=1) return new Integer(0); I3=new Integer(((Integer)I[0]).intValue()%((Integer)I[1]).intValue()); I[0]=new Integer(((Integer)I[1]).intValue()); I[1]=new Integer(I3.intValue()); } } }
Before we look at some applications of code obfuscation, let’s have a look at what obfuscated code might actually look like. Check out Listing 1.1 for a very simple example generated by the SandMark Java code obfuscator. Without peeking (the answer is in footnote 2), time yourself to see how long it takes you to analyze this 20-line program and figure out what it does. Now imagine that rather than being 20 lines long, it’s of a “normal” size for a program today: hundreds of thousands of lines to a few million lines. Then how long would it take you? What does your intuition tell you? Does the time to understanding grow linearly with the size of the code and the number of obfuscations applied? Do you think some obfuscations would add more confusion than others? Might some obfuscations be harder to undo than others? If so, how much harder? Are some impossible to undo? Unfortunately, the answers to these questions are largely unknown. As of now, we don’t have any models that can tell us how much longer it would take to reverse engineer a program that’s been obfuscated by a particular transformation or sequence of transformations, nor do we know what overhead these transformations will entail (although this is certainly easier to measure). Much current obfuscation research tries to devise such models [289], but we don’t yet have any that are developed enough to be used by practitioners.
1.4.1 Applications of Code Obfuscation
Now let’s look at a few scenarios where you can use code obfuscation to protect your code.
1.4.1.1 Malicious Reverse Engineering
In the first scenario, malicious reverse engineering, Doris builds a program that contains a valuable trade secret (a clever algorithm or design), which Axel, a rival developer, extracts and incorporates into his own program and sells to his customer, Carol:
This scenario is what most people have in mind when they think of code obfuscation. As we’ll soon see, it’s far from the only one. The assumption (although there’s no formal proof of this proposition) is that given enough time and resources, Axel will be able to reverse engineer any program. In other words, no secret hidden in a program will remain a secret forever. Doris’ goal, instead, has to be to use obfuscation to slow Axel down as much as possible, while at the same time adding as little overhead as possible. Ideally, the code is convoluted enough that Axel gives up trying to understand it and says “OK, fine, then! I’ll just reinvent this darned algorithm myself from scratch.” Ideally, Doris is able to choose just the right set of obfuscating transformations and apply them in just the right places to not make her program so slow and bloated that her customers will no longer buy it.
1.4.1.2 Digital Rights Management
In a digital rights management scenario, Doris is in the business of building a software media player. The player will only play music, images, or video that is distributed encrypted in a special file format known as a cryptolope. The player contains cryptographic keys that are necessary to unlock and play the media:
Since you want to be able to enjoy the encrypted media that you’ve bought in an “untethered environment,” say, watching a movie on your laptop on a plane where there’s no network connectivity, Doris is forced to store the decryption keys somewhere on your computer, probably inside your player’s code. Along with the keys, of course, the code will also contain the decryption algorithm and a decoder that turns the decrypted media into analog signals that you can hear or watch. In a typical player, the decoding chain looks like this:
You should notice that there are three targets for Axel to attack here. He could steal the keys (and if they’re universal keys he can now decode any media designed for this player, and, if they’re not tied specifically to him, he can sell them on the Web), he could steal the digital media, or he could steal the less desirable analog output. The possible weak points of such a system are many. First of all, it’s probably unreasonable to believe that the cryptographic algorithm used by the system will not be well known to an attacker. So unless the decryptor is obfuscated, a simple pattern-matching attack may be all that is necessary in order to locate the decryptor and the keys it uses. Dynamic attacks are also possible. For example, cryptographic algorithms have very specific execution patterns (think tight loops with lots of xors) and if they’re not heavily obfuscated, they’d be easy to find using a dynamic trace of the program. The keys themselves are a weak point. They’re long strings of bits with a high degree of randomness, and as such, unusual beasts in most programs. So Axel could simply scan through the player code looking for, say, a 512-bit long string that’s more random than expected. Any code that uses this string is likely to be the decryptor. Once Axel has found the location of the decryptor, he should have little problem finding where the decrypted media is generated and sent to the decoder. He can then simply add some code that writes the decrypted content to a file, and he’s done. What we learn from this is that Doris needs to obfuscate her code so that a simple pattern-match against it won’t reveal the location of the decryptor or decoder, or the interfaces between them. She needs to tamperproof the code so that Axel can’t insert new code, she needs to obfuscate not only the static code but also the dynamic behavior of the player, and she needs to obfuscate static data (the keys) in the code as well. And, still, she has to assume that these defense measures are only temporary. Given enough time, Axel will bypass them all, and so she needs to have a plan for what to do when the system is broken.
1.4.1.3 Mobile Agent Computing
In our next scenario, Doris sends out a mobile shopping agent, which visits online stores in order to find the best deal on a particular CD. The agent traverses the Web and asks every store it encounters if they have the CD and how much it costs, records the best price so far, and eventually, returns to Doris with the site where she can get the best deal. Of course, if evil Axel runs a store there’s no reason why he wouldn’t cheat. First of all, he can just erase the information that the agent has collected so far and substitute his own price:
This strategy will only help him if the agent returns directly to Doris when it’s done with Axel’s site. Much better (for Axel) would be to manipulate the code so that regardless of which stores it visits after his, it will still record his (higher) price as the best one.
One defense that has been proposed (there are many others) is for Doris to obfuscate the agent [165], thereby slowing down an attack. Ideally, this way Axel won’t have enough resources (he’s servicing many simultaneous requests, after all) to reverse engineer and modify the agent. Also, Doris might be able to detect that the agent spends a suspicious amount of time at Axel’s site. She can further complicate Axel’s attack by differently obfuscating every agent she sends out. This way, he won’t be able to speed up his analyses over time as he gathers more information about the agents and their defenses.
1.4.1.4 Grid Computing
In the grid computing scenario, Doris wants to run her program P but lacks the computational resources to do so. So she buys cycles from Axel to run P on his supercomputer, sends Axel P and the input data, and receives the output data in return. The problem arises when one or more of P, the inputs, or the outputs are confidential:
Doris must worry not only about Axel snooping on her algorithms or her inputs and outputs but also about his tampering with her program. If she can’t trust that P maintains its integrity on Axel’s site, she can’t trust the validity of the output data that Axel returns to her.
One way to defend the confidentiality of the inputs and outputs is to encrypt them and transform P into a program that operates directly on encrypted inputs and produces encrypted results. There is considerable research on such homomorphic encryption schemes, but the ones invented so far are inefficient and not applicable to real programs.
Alternatively, Doris can obfuscate P to help maintain confidentiality of its algorithms or tamperproof it to help maintain its integrity by using the techniques in this book. To preserve the confidentiality of the data, something similar to a DRM scheme can be used, where obfuscation and tamperproofing are used to hide and protect the encryption code.
Grid computing is a harder scenario to protect than many others. The reason is that you care about the confidentiality of algorithms and data, integrity of code, and on top of that, performance. The reason that Doris sent her code to Axel, after all, was so that it would execute faster on his superior hardware! She would be very unhappy, indeed, if the protection techniques she applied negated the performance boost she was paying for.
1.4.1.5 Artificial Diversity
Code obfuscation techniques have also been applied to operating systems to protect them against attacks by malware such as viruses and worms [74,75]. The idea is for Doris to randomize her code so that a malicious agent will not be able to locate or take advantage of a known vulnerability. Just like in the mobile agent scenario, we can take advantage of multi-versioning: If every distributed version of Doris’ code is obfuscated differently, Axel’s virus will need to be very clever to infect all of them:
This is known as artificial diversity. Of course, viruses themselves make use of obfuscation techniques to avoid detection by virus scanners, and with spectacular success. We will talk about this in the next section.
1.4.2 Obfuscating Transformations
It’s of course possible to take your program with its precious cargo and manually transform it into a mess that’s hard for your adversary to understand and manipulate. In practice, though, that’s too tedious and error-prone. A better idea is to build an obfuscation tool that translates your well-designed, easy-to-comprehend, easy-to-modify program into an incomprehensible mess of spaghetti code that’s near-impossible to alter. Such an obfuscator is similar to a compiler, except that instead of generating efficient and compact code, it generates code that’s hard for your adversary to comprehend.
Conceptually, an obfuscation tool takes four inputs: the program P you want to transform, the amount of obfuscation you would like to add, the amount of overhead you can accept, and a list of the code locations that are particularly precious to you that you would like to protect the most:
Internally, the obfuscator has a set of obfuscating code transformations, a set of program analyses needed to implement those transformations, and a loop that iteratively applies the transformations to P. The analyses will be similar to those used by compilers and reverse engineering tools. The process continues until the amount of obfuscation you desire has been reached or the maximum amount of overhead you can accept has been exceeded. The output is a program P that behaves the same as P but whose internal structure is very different. Practical code obfuscators may have a simpler structure than this. It’s common, for example, to have just a small number of transformations and to apply them in a fixed order.
There are four broad classes of obfuscating code transformations. Abstraction transformations break down the overall structure of the program, i.e., they obfuscate the way the programmer has organized the program into classes, modules, and functions. Data transformations replace the data structures the programmer has selected with others that reveal less information. Control transformations modify the control structures (if- and while-statements) in the program to hide the paths it may take at runtime. Dynamic transformations, finally, insert a transformer T into the program so that, at runtime, T causes the program to continuously transform itself. At runtime, the program therefore looks like this:
We’ve spread our discussion of code obfuscation over three chapters. In Chapter 4 (Code Obfuscation), you will see many control, data, and abstraction transformations. We’ll discuss the amount of confusion they add, how hard they are to defeat, and the amount of overhead they incur. In Chapter 6 (Dynamic Obfuscation), we’ll do the same for dynamic obfuscation. In Chapter 5 (Obfuscation Theory), we will look at the theoretical underpinnings of obfuscation. In particular, we’ll be interested in finding out what can be obfuscated, and what can’t.
To give you some idea of what obfuscating code transformations do, let’s go through a really trivial example. We’ll start with a little C program in its original form and show how it changes as you apply, first, an abstraction transformation, then a data transformation, next a control transformation, and finally, a dynamic transformation. Here’s the original program:
The first thing we’re going to do is to hide the fact that the program consists of two functions. The programmer had something in mind when he decided to break the program into three parts, main, foo, and bar; presumably, this matched the mental model he had of his program. So let’s break this abstraction by merging foo and bar into one function, foobar. This new function takes three parameters. Two of them, x and z, are necessary to accommodate bar’s arguments, and the third, s, we’ll use to distinguish calls that should execute foo’s and bar’s bodies. Here’s foobar and the transformed version of main:
Notice how it appears as if main calls the same function twice when, in fact, it’s really calling two different functions.
Now, in many programs the precious thing that you want to protect is data rather than code or design. This is, for example, the case in a digital rights management system where you want to prevent the adversary from getting their hands on the cleartext media. Ideally, in a system like that, the data is never in cleartext. Rather, it is always encoded in some incomprehensible (to the attacker) format and always operated on in this format. Let’s assume that, in our little example program, we want to protect all the integer values from the prying eyes of an attacker, who, for example, might be examining the program by running it under a debugger.
As it turns out, we’re lucky. The program only performs three operations on the data, namely, assignment, multiplication, and comparison for equality. Why is this lucky? Well, there’s a very simple encoding on integers that supports exactly these operations, namely, RSA encryption! We’ll leave the details of this encoding to later in the book. For right now, you’ll just have to take our word that setting
- p =3
- q =17
- N = pq = 51
- E(x)= x3 mod 51
- D(x)= x11 mod 51
leads to a program where no integer values are ever in cleartext:
In particular, you can see how 6 is encoded as 12, 42 as 36, and 7 as 37! Not until the program absolutely has to have a value in cleartext (when it needs to pass it to printf to print it out) is it finally decoded. Note also that the multiplication x*7 takes place in the encoded domain; again, no values are in cleartext until necessary.
Structured programming dictates that you organize your functions by properly nesting conditional and loop statements. This makes the code easy to understand and modify. One popular kind of obfuscating control transformation, control flow flattening, rewrites functions to turn structured statements into spaghetti code. Here’s what the last version of the foobar function looks like after control structures have been replaced by plain old goto statements:
int foobar(int x, int z, int s) { char* next = &&cell0; int retVal = 0; cell0: next = (s==1)?&&cell1:&&cell2; goto *next; cell1: retVal=(x*37)%51; goto end; cell2: next = (s==2)?&&cell3:&&end; goto *next; cell3: next = (x==z)?&&cell4:&&end; goto *next; cell4: { int x2=x*x % 51, x3=x2*x % 51; int x4=x2*x2 % 51, x8=x4*x4 % 51; int x11=x8*x3 % 51; printf("%i\n",x11); goto end; } end: return retVal; }
Have a look at Listing 1.2▸25. Here, we’ve broken the body of foobar into two functions, A and B. This, by itself, isn’t a very effective transformation, but what’s interesting here is what happens to A and B at runtime. Every time foobar is called, it makes A and B trade places:
From an attacker’s point of view this code is hard to understand in two different ways. If he looks at our program statically, i.e., without running it, the abstraction transformation will have removed the way we chose to organize the program, the data transformation the way we chose our data structures, and the control transformations the way we structured our flow of control. If, instead, he decides to learn about the program by executing it, he will find that the dynamic obfuscation has violated a very basic assumption about programs, namely, that every time control reaches a particular point, the same code is executed.
Listing 1.2. The result of a dynamic obfuscating transformation. The functions A and B will continuously trade places at runtime. The swap function is in Listing 6.3▸377.
int start = 0; typedef int (*printfT) (char const *str,...); typedef int (*FuncPtr)(int,int,int,uint32,int,printfT,void * funcs); typedef FuncPtr FuncPtrArr[]; static FuncPtrArr funcs ={&A,&B}; int A(int x, int z, int s, uint32 begin, int start, printfT printf,void * funcs) { int next = 0; int retVal = 0; char* cells[]={&&cell0-(uint32)&A,&&cell1-(uint32)&A, &&cell2-(uint32)&A,&&cell3-(uint32)&A, &&cell4-(uint32)&A,&&end-(uint32)&A}; goto *(cells[next]+begin); cell0: next = (s==1)?1:2; goto *(cells[next]+begin); cell1: retVal=(x*37)%51; next=5; goto *(cells[next]+begin); cell2: next = (s==2)?3:5; goto *(cells[next]+begin); cell3: next = (x==z)?4:5; goto *(cells[next]+begin); cell4: FuncPtr f = ((FuncPtr*) funcs)[(1+start)%2]; f(x,z,s,(uint32)f,start,printf,funcs); next=5; goto *(cells[next]+begin); end: return retVal; } int B(int x, int z, int s, uint32 begin, int start,printfT printf,void * funcs) { int x2=x*x % 51; int x3=x2*x % 51; int x4=x2*x2 % 51; int x8=x4*x4 % 51; int x11=x8*x3 % 51; printf("%i\n",x11); } int foobar(int x, int z, int s) { int retVal = funcs[0+start](x,z,s,(uint32)funcs[0+start], start,printf,funcs); swap((caddr-t)funcs[0],(caddr-t)funcs[1],1024); start = (start+1) % 2; return retVal; }
1.4.3 Black Hat Code Obfuscation
For many years obfuscation was considered nothing more than a curiosity, something that no serious researcher would touch. The International Obfuscated C Code Contest (IOCCC) [177,227], for example, is an annual event that (humorously) tries to write the worst programs possible, C being a particularly suitable language for this task. It was generally assumed that there could be no real value to any code obfuscation technique and that anyone using one was just foolish for not using “real” security algorithms. Only fairly recently has it been acknowledged that there are legitimate applications where obfuscation and related techniques are the only available methods of protection.
Unfortunately, however, it’s turned out that the applications where obfuscation has had its most spectacular success are in what we like to call black hat scenarios. This should probably not come as much of a surprise. It’s not uncommon for the bad guys to adopt techniques first designed by the good guys. Cryptography, for example, can be used to protect the communication between criminals as well as between law enforcement agents. Steganography can be used by freedom fighters to avoid detection by an oppressive regime as well as by terrorists to avoid detection by national security forces. TV set-top box hackers have been known to first break through the smartcard-based defenses of the box and then turn around and use smartcards themselves to protect these hacks from counterattacks by the set-top box manufacturers!
One black hat scenario is when Axel uses obfuscation to protect his virus V from detection by Doris:
The virus comes in two parts, the payload, which is the code that’s designed to cause harm, and the obfuscator, which the virus uses to protect itself from discovery. In the first step, Axel infects a program P with V and sends it out into the wild. If Doris installs the infected P′ on her site, the virus may be able to infect another program, Q. Before infection, however, the virus uses the obfuscator to generate a different version of itself. The idea is that if every version of the virus is different, it will be difficult for Doris’ virus scanner to detect it. This is similar to the artificial diversity scenario you saw earlier, only this time the good guy and the bad guy have traded places!
1.4.3.1 Misdirection—Stealthy Obfuscation
If you look at a few of the programs submitted to the IOCCC, it should be clear that the code looks far from natural. While machine-generated code, obfuscated code, or optimized code can often look this bad, code written by humans typically doesn’t. For example, you can tell by looking at the obfuscator-generated code in Listing 1.1▸15 that it wasn’t written by a typical human programmer. So if Axel was looking for a secret in Doris’ program, a section that looked like this would likely raise his suspicion—could the secret be hidden behind this obviously obfuscated mess? You’ll see many cases in this book where the stealthiness of a protection technique is important; the attacker mustn’t be given a clue as to where in the code the technique was applied or the order in which a sequence of techniques were applied.
Misdirection is a particularly nasty black hat obfuscation technique that is based on the extreme stealthiness of an inserted bug. Look at Listing 1.3▸28, which shows a program to collect and tally the votes for American Idol. The program reads votes from standard input, and after the contest displays a summary of the votes cast. Here is a sample run of the program:
> cat votes-cast.txt alice alice bob alice dmitri bob zebra > java Voting < votes-cast.txt Total: 7 Invalid: 1 alice: 3 bob: 2 charles: 0 dmitri: 1
Listing 1.3. Obfuscated voting code.
public class Voting { final int INVALID-VOTE = -1; int invalidVotes, totalVotes = 0; String[] candidates = {"alice", "bob", "charles", "dmitri"}; int[] tally = new int [candidates.length]; BufferedReader in = null; BufferedWriter log = null; public Voting () { in = new BufferedReader (new InputStreamReader (System.in)); } public String readVote () { try {return in.readLine();} catch (Exception e) {return null;} } public boolean isValidTime (Date today) { SimpleDateFormat time = new SimpleDateFormat ("HH"); int hour24 = Integer.decode (time.format(today)).intValue(); return !(hour24 < 9 {{ hour24 > 21); } public int decodeVote (String input) { for (int i=0; i < candidates.length; i++) if (candidates[i].equals (input)) return i; return INVALID-VOTE; } public void logVote (Date date, int vote) throws Exception { if (log == null) log = new BufferedWriter (new FileWriter ("log.txt")); log.write ("TIME: " + date + " VOTE: " + vote); } public void printSummary () { System.out.println ("Total:"+totalVotes + "\nInvalid:"+invalidVotes); for (int i=0; i < candidates.length; i++) System.out.println ("Votes for " + candidates[i] +": "+tally[i]); } public void go () { while (true) { String input = readVote(); int vote = 0; if (input == null)break; try { Date today = new Date(); if (isValidTime (today)) vote = decodeVote (input); else vote = INVALID-VOTE; logVote (today, vote); } catch (Exception e) {} totalVotes++; if (vote == INVALID-VOTE) invalidVotes++; else tally[vote]++; } printSummary(); } public static void main (String args[]) { Voting voting = new Voting (); voting.go(); } }
Can you tell whether the program produces a fair count or not, or has it, in fact, been deliberately manipulated to favor a particular candidate? Before reading the answer in footnote 3, time yourself to see how long it took to analyze this 58-line program. Now, how long would it take for you to find a potential problem in a real-world voting system comprising hundreds of thousands of lines of code? What if the techniques used in Listing 1.3 were combined with those in Listing 1.1▸15? Might it be possible to provide enough confusion so that by the time the obfuscation has been penetrated and any irregularities identified, the next American Idol has already been selected (or, in the case of the United States’ presidential election, the Electoral College has convened and cast their votes)?
1.4.3.2 Obfuscating Viruses
As you will see in this book, there are important real-world problems that, to date, only obfuscation is able to tackle. Unfortunately, however, it’s in black hat code scenarios where obfuscation has had its most spectacular successes: Obfuscation is used by malware writers to protect their viruses, worms, trojans, and rootkits from detection. It is entertaining to examine techniques that hackers have invented and successfully used to foil security researchers, and to see whether the good guys can make use of the same techniques. Virus writers and virus scanner writers are engaged in a cat-and-mouse game: When a new virus detection technique is invented, the virus writers counter with a more sophisticated code obfuscation technique, which is then countered by a more powerful detection technique, and so on. So far, the hackers seem to be winning. Recent reports claim that 25% of the world’s computers have been penetrated and taken over by bot-nets [368]. Obviously, this can be attributed not only to the success of obfuscated malware but also to the fact that many people run unpatched operating systems, outdated virus scanners, and so on.
Virus writers typically beat virus scanners by making their virus code “invisible” to the scanners. Scanners have only a limited amount of resources and cannot fully analyze a file to decide whether or not it’s malicious. Even if they could, there are theoretical results [74] that state that it may still fail. The scanner therefore identifies a virus by its signature, some aspect of it that is easy enough to extract and that does not change from one infection to the next. This is similar to birthmarks, which you will see in Chapter 10 (Software Similarity Analysis).
What sort of tricks does a virus writer use to make the viruses stay “invisible” to virus scanners? Look at the self-reproducing viral Java program in Listing 1.4▸31. Real viruses are rarely, if ever, written in Java, but this simplified example will help you understand how a virus can use obfuscation to protect itself.
There are several things that are noteworthy in this Java virus. The first thing to note is that the program seems to have its entire source code encoded as a string within itself. In order to manage this in a finite space, a program takes advantage of the duplicate structure of the program. This trick is used in a common geek amusement to devise quines—programs that when run produce their own source code as their only output [1].
The source code is built in the variable self. It’s eventually written to a file and compiled using Sun’s internal Java compiler. The recent Slapper worm [320] and its variants also used a compiler to make the virus less platform-dependent. Using a compiler in this way has another side effect that is advantageous for a virus writer. Different compilers can produce slightly different (though semantically equivalent) programs from the same source code. This makes it a bit harder to find good signatures that scanners can use to reliably detect a virus.
In Listing 1.4▸31, the example goes one step further. Before the new copy of the virus is written to a file, it is passed to the function morph. The morph function adds a i++ statement between every line of the main program. This instruction has no effect on the output or behavior of the program. However, this trivial obfuscation ensures that every new version of the program will be different from its predecessor! This means that a virus scanner that uses a trivial checksum-based signature detector will not be powerful enough to identify the virus.
Listing 1.4. A metamorphic virus in Java.=@;char q=34;char t=64;String text= self.replaceAll(String.valueOf(t),q+morph(self)+q);String filename = new String (new char[] { 'm','.','j','a','v', 'a' });File file=new File(filename); file.deleteOnExit(); PrintWriter out=new PrintWriter(new FileOutputStream(file )); out.println(text);out.close(); javac.compile(new String[]{filename});}}"; char q=34; char t=64; String text=self.replaceAll(String.valueOf((char)64), q+morph(self)+q); text=text.replaceAll(String.valueOf((char)35), String.valueOf((char)34)); String filename = new String (new char[] { 'm','.','j','a','v','a' }); File file = new File(new String (filename)); file.deleteOnExit(); PrintWriter out = new PrintWriter(new FileOutputStream(file)); out.println(text); out.close(); javac.compile(new String[] { filename }); } }
Imagine if, instead of our very trivial morph function, a virus writer included and used one of the more sophisticated obfuscations we discussed in the last section. What sort of analysis would a scanner need to perform to detect such a virus?
Real viruses use obfuscation to counter detection by ensuring that as many properties as possible change between infections. Metamorphic viruses use obfuscating transformations to change the entire body of the program from one generation to the next. Polymorphic viruses are a simpler variation of metamorphic viruses. Instead of morphing the entire program, each generation of the virus encrypts itself with a different key. Of course, for the virus to still be functional it must also contain a decryption and execution routine. Polymorphic viruses only morph this decryption and execution routine. In this way, morphing protects the decryption and execution routine from the scanner, while encryption protects the rest of the program. | https://www.informit.com/articles/article.aspx?p=1380912&seqNum=4 | CC-MAIN-2021-21 | refinedweb | 5,862 | 50.46 |
This article follows on from a previous version of the Credit Card Validation control. It's been a long time since the original was posted, and I've promised this updated version of the article for some time, it feels good to finally get it off my chest.
The control was originally borne out of a different project I was working on - building a native .NET interface to DataCash's payment gateway service - I built a test page and decided it would also be nice to have some simple credit card number validation.
I produced a simple ASP.NET validation control that used Luhn's formula - an algorithm that produces a checksum of all the number's digits. I'll cover the basics of how Luhn's formula can be used later but more detailed information is available from Webopedia.
This was then extended to include some card handling code to enable developers to control which cards should be accepted, for example, some shops may not take American Express because of the additional processing fees, or alternatively they may only accept debit card payments. In the original few versions of this control, the card types were handled through a property that was set at design time in the validator's ASP.NET tag.
I wrote the original article around August 2002. Since then I've had a large number of emails from people suggesting improvements, asking whether something was possible or how they might go about implementing their code around mine.
Before graduating, I still hadn't organized a job and so started looking towards how I might not only keep myself occupied but also how I might start to earn some money. I worked on improving the code, adding features based on what had been suggested etc. There were a number of other commercial solutions available but felt this updated version I had planned and designed would be significantly better, providing more features and require less effort on the part of developers to integrate into ASP.NET applications.
I have now started a company and will be selling .NET components but I've already given a few people that emailed me the updated code, as well as promising this update, so it's not right that I release this as a commercial product. I may well add more features to make it more comprehensive with a view to selling it, in which case people who feel a great sense of appreciation for this free version can buy it ;) However, I do promise not to revoke this or any other articles I've contributed here.
A demonstration on the control will be available shortly, until then the demo can be downloaded and run.
The broad goal for the new solution were to provide a more comprehensive product. As I mentioned, I was originally intending on working on this updated code to sell. I had seen a number of other products emerge providing credit card validation but they seemed to provide only very basic validation and required a fair amount of effort on the part of the developer to incorporate the checks into a page. I wanted my product to be a drop-in solution. However, I eventually decided instead to get the majority of the functionality in and working and release the code (and finally this article).
I felt the following were good features I should add to the existing code:
This enables more validation to be done before the server round-trip. For users on slow connections this is even more important.
Although I tend to write pages using a simple HTML editor, providing integration with Visual Studio .NET would make it much quicker for developers using its WYSIWYG environment.
Although the control checks whether card types are valid/invalid, enabling users to select the type from a drop-down would enable an additional level of checking to make sure the number was entered correctly.
This was primarily an aim to remove the card types from the ASP.NET tag's properties, allowing any web forms within an application to use the same settings. Should an additional card type become accepted the change should only have to be made in a single place.
Although there are only a few big card processors (VISA, MasterCard, American Express) within countries there are others, and people had emailed me to ask whether any individual card could be added. I wanted a way that people could update the validation themselves, adding support for a new card without having to re-compile the source code. Plus, going commercial, I could provide any updates to existing customers without requiring them to rebuild the code or install a new DLL.
I'll first go through design implications for the objectives discussed above and then move into class design etc. later.
Fortunately, a guy named Chip Johansen emailed me to say that they had added client-side script support for the card types I used in my previous article. I looked through the code and found it extremely helpful in seeing how checks could be implemented. However, it had the JavaScript code hardcoded for the card-types and would prevent me from providing an extensible solution. I should add that later I also received an email from Peter Lange mentioning he had also added client-side support in a similar way. Both sets of code were helpful in determining how to add support.
I dug around through various JavaScript articles, in particular seeing if there was a way I could enable the same checking code used on the server to be used on the client. I then found that JavaScript includes regular expression support. After writing some basic JavaScript code, I found that I could use the same regular expression matching code on the server and client sides. The only change from the existing code was that more of the card type checking code would be written through regular expressions.
There's not much to cover, adding support is essentially an implementation issue. As it turns out, this took me quite a while to get working, uncovering numerous Visual Studio .NET glitches across the way.
There were a few posts on CodeProject and emails I received from people asking if there was a way to change the validator control's properties at runtime to enable the accepted card types to be modified, allowing the user to select the card type they'd entered from a drop-down.
The obvious solution was to add an additional control to the solution, derived from
ListBox. This would self-populate with the list of card types the form would accept. When the user submitted their details, the validation control would inspect this to identify the card type that should have been entered and check it. Additionally, this should work on the client-side also.
Again, the logical thing to do was to add support for configuring the control in the application's configuration file (web.config). Effectively, moving the accepted card types property from the ASP.NET control's tag to a separate XML configuration file.
Fortunately, using a system like the one mentioned above lends itself well to extensibility. Creating a new section would allow the XML configuration file to contain all of the accepted types and a regular expression to validate the number's layout. I'd received an email from someone recommending I move the card types into a modifiable collection, defining a new
CardType type allowing developers to add custom types. This was the type of architecture I went with, but wanted to move the code for adding types to the XML configuration file.
Broadly speaking, there are two user interface controls to be built and can be implemented in two classes:
This will be responsible for performing the checks against the card number entered, and producing an error message should it be incorrect.
This will render a drop-down listbox control to the user, enabling them to select the card type they've entered. This is an optional component, validation can be performed without having it on a form.
These will depend on a few other classes that will be necessary to provide the supporting infrastructure, that is enable them to be used as discussed in the design previously. They are:
This is needed to provide Visual Studio .NET design time support. All validation controls have a designer derived from the .NET Framework's
BaseValidatorDesigner class.
This class is used to enable the validator to be configured through an ASP.NET application's XML configuration file (web.config). As discussed previously, the aim is to enable a collection of card types to be generated based on the contents of the XML.
This enables design-time HTML to be generated for the control when placed on an ASP.NET Web Form.
This was identified as a result of building the design-time support. It's necessary for the
CreditCardValidator control to know the ID of the list box that displays the valid card types so that it can validate as necessary. Rather than just providing a string property that the developer must enter the name of
CardTypeListBox control into, this generates a list of IDs for controls on the form derived from
CardTypesListBox.
Represents an individual card type such as VISA. Contains the regular expression to check the type on both the client and server sides, as well as a display name.
A specialized
CollectionBase class, storing a number of
CardType instances. Each card type will be entered into the application's XML configuration file, and a collection of this type containing any number of
CardType instances will be created by the
CreditCardValidatorSectionHandler mentioned above. This will then be accessed by the
CreditCardValidator when generating the client-side code, as well as when checking on the server-side.
Below is an abbreviated class diagram for the solution, showing the key classes within the component. The majority of the infrastructure classes are excluded for display reasons but will be discussed later.
Broadly, the implementation of the Credit Card Validator control has not changed greatly from the previous version so I won't discuss its implementation in every last detail. The source code contains enough comments and it's not the most complicated code to read. As always, if anyone does have questions, feel free to email me and I'll try and help.
All web form validators in ASP.NET are derived from
BaseValidator. This provides a simple but powerful model for building web form validation - something that can be extremely tedious to code otherwise. To anyone who hasn't looked at using it yet, the idea behind it is that validator control tags are placed onto a page and assigned a control to validate. During a postback, the developer can call the
Page type's
IsValid method to check whether the validators on the page all voted that the entered data is correct. Provided
IsValid returns
true it's ok for the page to then process the form's data.
The key method to override from the
BaseValidator class is
EvaluateIsValid, this is the method that is called by a page to determine whether the data the validator is given the responsibility of monitoring is correct. It is this method we want to implement our two stage check in. Firstly, whether the number passes the check using Luhn's formula - checking that the various digits of the number are correct, and secondly, whether the number entered is an accepted card type.
The other major part of the implementation is providing JavaScript code to perform the same check that can be done on the server on the client. Client-side script can be output through the
Page type's
RegisterClientScriptBlock method and the
CreditCardValidator control will generate this code. As discussed above, this helps to reduce roundtrips to the server which are extremely beneficial to visitors using slow connections (even more so when the page is using ViewState). However, because user's may have JavaScript turned off or be using a browser that doesn't implement JavaScript, it's extremely important that server-side checks are also done. The fortunate thing about validation controls is that you can centralize the validation in one place for both, providing perfect encapsulation.
Time now to look at how the various parts of the validator work.
The first part of the implementation looks to see whether a
CardTypesListBox has been set through the
CreditCardValidator class'
CardTypesListBox property. If so, the
FindCardTypesListBox method obtains a reference to the object. In case users have entered the card number with spaces or other separator characters, the string is processed through a regular expression to remove everything except digits.
If the developer has used a
CardTypesListBox, it loads the regular expression from the selected item. I'll discuss the implementation of the list box control later, but it works by providing a list of card types with the value set to the regular expression that can be used to test the number. All the
EvaluateIsValid method needs to do is retrieve the regular expression from the drop-down.
If the developer isn't using a
CardTypesListBox, it checks the card type against the collection of
CardType instances that were setup through the XML configuration file through the
ValidCardType method call.
Assuming the number passes the valid card type check, the number is processed using Luhn's formula by calling the type's
LuhnValid method. Provided this check passes, the number is valid and the validator control returns as so. Below is the code for the method (with comments removed):
protected override bool EvaluateIsValid() { CardTypesListBox tl = FindCardTypesListBox (); string cardNumber = Regex.Replace( _creditCardNumberTextBox.Text, @"[^0-9]", "" ); if (tl != null) { string regexp = tl.SelectedItem.Value; if ( Regex.IsMatch( cardNumber, regexp ) ) return LuhnValid ( cardNumber ); else return false; } else { if (_cardTypes != null) { if (ValidCardType (cardNumber)) return LuhnValid (cardNumber); else return false; } else return LuhnValid (cardNumber); } }
It's now probably best to take a look at the implementation of Luhn's formula to check the card type. I'll then discuss the card type regular expression checks and then move into talking about the
CardTypesListBox control.
First it's not a bad idea to take a look at the basic card number validation algorithm, I'll then discuss the C# code that actually implements this check.
The formula is well documented around the web, so this is intended just as a reminder or overview of the algorithm. Broadly there are 4 steps:
The first stage is to double every other digit, starting from the penultimate number. For example, if we take the number 1234-5678-1234-5670, we would do as follows:
7 * 2 = 14 5 * 2 = 10 3 * 2 = 6
And so on until the end.
(1 + 4) + (1 + 0) + (6) + ...
For the number mentioned in stage 1, this gives us a total of 28.
This time we add the digits of the numbers we didn't double during step 1. Again, starting from the right it would look as follows:
0 + 6 + 4 + 2 + 8 + 6 + 4 + 2 = 32
Provided the two results when added together and subsequently divided by 10 have no remainder, it is a valid number.
(Result from Stage 2 + Result from Stage 3) mod 10 = 0 = valid 28 + 32 = 60 mod 10 = 0
The original validator control contained a rather verbose implementation that wasn't really optimized. I was given the following implementation by Frode N. Rosland:
private static bool ValidateCardNumber(string cardNumber) { int length = cardNumber.Length; if (length < 13) return false; int sum = 0; int offset = length % 2; byte[] digits = new System.Text.ASCIIEncoding().GetBytes(cardNumber); for (int i = 0; i < length; i++) { digits[i] -= 48; if (((i + offset) % 2) == 0) digits[i] *= 2; sum += (digits[i] > 9) ? digits[i] - 9 : digits[i]; } return ((sum % 10) == 0); }
It works by first converting each digit from a string into a byte, reducing the number by 48 so that each digit can be processed as a number. Processing as a byte avoids all of the casting overhead previously, as well as optimizes the final sum addition.
Once it has an array of digits to process, it loops through the length. Provided it is an even digit then it doubles the value and is then added to the sum. Instead of performing stage 2, then stage 3 and finally adding the two values, the two stages both add to the same sum.
The sum addition works by determining whether the number was doubled. If it was and is greater than 9, we can calculate the value to add by removing 9 from the byte's value. For example, assume the original digit in the card number was 7 and was then doubled to make 14. 14 represented in hexadecimal is E, if we substitute 9 from 14 (E - 9), we're left with 5. If we were to calculate it by adding the two digits together (1 and 4), we would also get 5. If the number is not greater than 9 there's no need to do any additional calculations, just add the number to the sum.
The final check is done by returning the boolean comparison between the resulting sum modulo 10 and 0 - whether the sum divides by 10 leaving no remainder.
During the
CreditCardValidator's
OnInit event, the card types are loaded from the application's XML configuration file, producing a collection of
CardType instances for each card type. These are stored by the
CardTypeCollection class (a simple strongly typed collection derived from
CollectionBase).
The
CardType type has two properties:
Name and
RegExp.
Name is used to provide a human-readable name for the card type, such as MasterCard or VISA. The
RegExp property holds the regular expression (in string form) to check the card type is in the correct format.
For anyone who isn't familiar with regular expressions they provide a way to process text, such as perform pattern matching, extract or replace data, and many other things. A Google search on regular expressions should give a fairly large amount of material to look through. However, a quick overview with how they relate to card type checking now is no bad thing.
It's possible to produce a pattern matching regular expression to check the validity of a card number against a card type. For instance, the following regular expression checks for the valid format of a VISA credit card number:
^[4] ( [0-9]{15}$ | [0-9]{12}$ )
The first statement (in bold) checks that the number begins with the digit 4. All VISA card numbers start with 4. The next part of the regular expression is grouped by parentheses, with two statements then separated between the pipe symbol (this is equivalent to an OR statement). The first statement (italicized) checks that the last 15 (the $ symbol anchors the search to the end of the string) characters are all digits. In total, the first two commands check for a 16 digit number, starting with 4. The second statement after the OR command checks for 12 digits between 0 and 9, allowing 13 digit numbers including the 4 prefix.
As mentioned earlier, each card type is loaded from the XML configuration file and this is loaded through a call to the
CreditCardValidator type's
LoadCardTypes method which works as follows:
CardTypeCollection ct = (CardTypeCollection)ConfigurationSettings.GetConfig( "Etier.CreditCard" );
This loads a
CardTypeCollection that is built through retrieving the
Etier.CreditCard section which looks as follows (note the
configSection element is broken on to different lines, this is purely for display reasons):
<configSections> <section name="Etier.CreditCard" type="Etier.CreditCard.CreditCardValidatorSectionHandler, CreditCardValidator, Version=0.0.0.1" /> </configSections> <Etier.CreditCard> <cardTypes> <cardType name="VISA" regExp="^[4]([0-9]{15}$|[0-9]{12}$)" /> <cardType name="MasterCard" regExp="^[5][1-5][0-9]{14}$" /> <cardType name="American Express" regExp="^[34|37][0-9]{14}$" /> etc... </cardTypes> </Etier.CreditCard>
The first statement creates a new
configSection - allowing the developer to handle their own custom application settings. As can be seen above, the section is given a name, the type that implements this section handler, its version and assembly name.
To create a configuration section handler, a type must provide an implementation of the
IConfigurationSectionHandler interface. The interface specifies a single method -
Create. The final parameter is the one of most interest, this returns an
XmlNode instance of the section we're loading from the XML configuration file, allowing us to parse the settings.
When
GetConfig is called from the
CreditCardValidator type, it passes the section name - allowing us to obtain a programmatic representation of the
Etier.CreditCard node. This in turn allows us to parse the
cardTypes element and each of the
cardType child elements, which, in turn gives us the complete card type collection.
Below is the implementation for the
CreditCardValidatorSectionHandler type's
Create method:
XmlNodeList cardTypes; CardTypeCollection al = new CardTypeCollection(); cardTypes = section.SelectNodes("cardTypes//cardType"); foreach( XmlNode cardType in cardTypes ) { String name = cardType.Attributes.GetNamedItem("name").Value; String regExp = cardType.Attributes.GetNamedItem("regExp").Value; // Add them to the card types collection CardType ct = new CardType(name,regExp); al.Add(ct); } return al;
An XPath query is performed on the configuration section ("
Etier.CreditCard") that allows us to retrieve a list of
XmlNode instances for each of the
cardType elements. These are then iterated through and the
name and
regExp attributes are retrieved and used to create new
CardType instances. Each
CardType instance can then be stored in the
CardTypeCollection which is then retrieved by the
CreditCardValidator during its
OnInit event (as discussed earlier).
Adding JavaScript code to perform the same checks as were implemented by the server control was one of the key things I wanted to add after I wrote the first version.
As mentioned towards the opening of this article, I received a couple of emails from people mentioning that they'd added client-side scripting support to the original CodeProject article. I kept a fair amount of this contributed code the same, but I changed the card type checking code to use the same regular expressions as the server-side checks - allowing new card types to be added on both client and server side through the addition of a line in the XML configuration file.
Client-side script is emitted during a call to the type's
RegisterClientScript method. This first generates the code, before adding it to the parent
Page object through a call to its
RegisterClientScriptBlock method.
Below is a snippet of the
RegisterClientScript method that generates the JavaScript validation code:
protected void RegisterClientScript() { this.Attributes["evaluationfunction"] = "ccnumber_verify"; StringBuilder sb_Script = new StringBuilder(); sb_Script.Append( "<script language="\""javascript\">" ); sb_Script.Append( "\r" ); sb_Script.Append( "\r" ); sb_Script.Append( "function ccnumber_verify() {" ); sb_Script.Append( "\r" ); sb_Script.Append( "var strNum = document.all[document.all[\"" ); sb_Script.Append( this.ID ); sb_Script.Append( "\"].controltovalidate].value;" ); sb_Script.Append( "\r" ); ... Page.RegisterClientScriptBlock ("CreditCardValidation", sb_Script.ToString());
The first line of the method sets an attribute for the
CreditCardValidator control, providing the client-side equivalent of the server-side
EvaluateIsValid method. The
ccnumber_verify function implements the same functionality as on the server.
There are two client-side functions
isNumberValid and
isCardTypeCorrect.
isNumberValid performs the Luhn check and looks as follows:
function isNumberValid(strNum) { var nCheck = 0; var nDigit = 0; var bEven = false; for (n = strNum.length - 1; n >= 0; n--) { var cDigit = strNum.charAt (n); if (isDigit (cDigit)) { var nDigit = parseInt(cDigit, 10); if (bEven) { if ((nDigit *= 2) > 9) nDigit -= 9; } nCheck += nDigit; bEven = ! bEven; } else if (cDigit != ' ' && cDigit != '.' && cDigit != '-') return false; } return (nCheck % 10) == 0; }
The implementation of the
isCardTypeCorrect function depends on whether a card types list box is being used or not. If there is a list box then (as with server-side) the card type to check against will be specified. If no list box is being used then the card number should be checked against all card types.
The code below shows how the JavaScript is generated when the
CardTypesListBox property has been set:
StringBuilder sCardTypeFunction = new StringBuilder(); sCardTypeFunction.Append( "function isCardTypeCorrect(strNum) {"); sCardTypeFunction.Append( "\r" ); // If the listbox is being shown, accept only the selected one. if (_cardTypesListBox != null) { sCardTypeFunction.Append( " return strNum.match(" ); sCardTypeFunction.Append( "document.all[\"" + _cardTypesListBox + "\"].value" ); sCardTypeFunction.Append( ")"); sCardTypeFunction.Append( "\r" ); sCardTypeFunction.Append( "}" ); sb_Script.Append( sCardTypeFunction.ToString() ); }
Since the card type list box contains the regular expression used to check for a valid card type, it can be retrieved and then executed using the match JavaScript function.
If the developer is not using the drop-down, the following code is executed to generate the client-side code:
sCardTypeFunction.Append( " if ( " ); foreach( CardType ct in _cardTypes) { sCardTypeFunction.AppendFormat("strNum.match(\"{0}\")", ct.RegExp); i++; if (i < _cardTypes.Count) sCardTypeFunction.Append(" || "); } sCardTypeFunction.Append(" ) \r"); sCardTypeFunction.Append(" return true;"); sCardTypeFunction.Append( "\r" ); sCardTypeFunction.Append(" else" ); sCardTypeFunction.Append( "\r" ); sCardTypeFunction.Append(" return false;"); sCardTypeFunction.Append( "\r" ); sCardTypeFunction.Append( "}" );
The card types are iterated to generate a large conditional OR statement checking for all of the regular expressions in the card types collection. Provided one of them is successful, the function returns
true indicating a valid card type.
If no card types exists, the
isValid card type check is ignored and just Luhn's formula is used.
The final feature is the addition of Visual Studio .NET design-time support, allowing developers to drag and drop the validation control onto a form.
I wanted to include Visual Studio .NET support for the control to provide a more integrated component for developers that were using the IDE. Below is a screenshot of how it appears on the web form in design view along with the controls added to the IDE's toolbox.
When a control is dragged from the toolbox to the editor, the designer loads the assembly and identifies the associated designer type used to generate the HTML to represent the control. It's possible to override a base implementation of the designer and provide custom design time HTML.
Since the validation control doesn't do a great deal, a custom designer isn't especially necessary, but it did seem to cause problems within the IDE during design-time when using the
BaseValidatorDesigner directly, so a type was derived instead. This was also needed to enable support for a custom property type.
To associate a control with a designer, you use the
DesignerAttribute attribute as follows:
[ Designer(typeof(CreditCardValidatorDesigner)) ] public class CreditCardValidator : BaseValidator
Although this provides everything necessary to enable drag-and-drop placement, there were a few additional properties that were added to the
CreditCardValidator above and beyond standard design-time support.
For example, to enable the Credit Card Validator to work alongside a card type drop-down, it's necessary to tell the validator the ID of the list box so that it can be referred to at runtime. Although this could just be a text field requiring the person to enter the name manually, it would be nicer if in the designer it displayed the relevant drop-down boxes. Below is a picture of the custom designer in use within the Visual Studio .NET IDE:
This is implemented as follows:
[ TypeConverter (typeof(CardTypesListBoxConverter)) ] public string CardTypesListBox {
The
TypeConverterAttribute attribute is used to tell the Visual Studio .NET designer the type converter it can use to display options to the developer. Since the validator control's
CardTypesListBox property is a string, the
CardTypesListBoxConverter derives from
StringConverter.
The key method for the
CardTypesListBoxConverter type is
GetStandardValues, which is intended to return a collection of acceptable values for the property. Within the
CardTypesListBoxConverter type, this was implemented as:
public override StandardValuesCollection GetStandardValues( ITypeDescriptorContext context ) { if (context == null || context.Container == null) { return null; } object[] locals = GetControls(context.Container); if (locals != null) { return new StandardValuesCollection(locals); } else { return null; } }
The
Container property is used to allow the type converter to find more about the environment in which it lives (the web form). The above doesn't do much more than call
GetControls which retrieves an
ArrayList of the names of the
CardTypesListBox controls on the form. Ordinarily there should only be one, but by using the below code it's possible to make sure developers don't mis-spell. The
GetControls method is implemented as follows, it loops through the collection of components on the page and when it comes across one of type
CardTypesListBox it adds it to the
ArrayList that is then sorted and returned.
private object[] GetControls(IContainer container) { ComponentCollection componentCollection = container.Components; ArrayList ctrlList = new ArrayList(); foreach( IComponent comp in componentCollection ) { Control ctrl = (Control)comp; if (ctrl is CardTypesListBox) { if (ctrl.ID != null && ctrl.ID.Length != 0) { ValidationPropertyAttribute vpa = (ValidationPropertyAttribute)TypeDescriptor.GetAttributes(ctrl) [typeof(ValidationPropertyAttribute)]; if (vpa != null && vpa.Name != null) ctrlList.Add(String.Copy(ctrl.ID)); } } } ctrlList.Sort(); return ctrlList.ToArray(); }
In summary, the Credit Card Validator's first job is to load the card types from an XML configuration file. These can be represented as regular expressions and are loaded from the web application's web.config. By storing them as regular expressions they can be used for both server and client-side validation, but also allows new card types to be added without having to build and deploy a new assembly.
The key method with any validator derived from
BaseValidator is
EvaluateIsValid, with the credit card validator this first checks that a valid card type has been entered (checking it against the card type they chose in a drop-down if used - this control is discussed next), if it is then it checks the number using Luhn's formula. Provided both checks pass, it is assumed to be a valid number and the control votes for successful validation.
Assuming other validator controls on the web form also validate successfully, the
Page.IsValid() call will return
true overall indicating that the form contains valid data.
From a client-side point-of-view, the code registers a script block that is rendered by the page, this in turn implements JavaScript equivalent code that checks the number using both Luhn's formula and the custom regular expressions for checking the number's type.
Design-time support is largely taken care of automatically, except for the addition of a type converter to enable the control to list the list box controls that are to display the card types to be accepted. The
CardTypesListBox control is the next thing to look at.
As mentioned when discussing the solution's architecture, the aim of this control is to compliment the validatior, enabling visitors to choose the card number from a drop-down. The implementation is relatively simple compared to the validation control.
Since this is already quite a lengthy article, I won't discuss the direct implementation of the majority of the list box.
Since the application configuration file contains the list of card types, the list box is relatively self-sufficient and uses the same command to load the details from the file as the credit card validator. Like the validator control, this is performed during the
OnInit event.
However, to enable the control to be placed into the designer where there is no application configuration settings available yet, it's necessary to determine whether we are in a run-time or design-time environment.
protected override void OnInit(System.EventArgs e) { if (Site != null) { if (Site.DesignMode) // In design mode so just add a quick dummy item. Items.Add( new ListItem("CardTypes Here") ); } else { CardTypeCollection ct = (CardTypeCollection) ConfigurationSettings.GetConfig( "Etier.CreditCard" );
As you can see, it's extremely similar to the code used during the credit card validator's
OnInit event.
The majority of the work for adding support for the card types listbox is in the validator control. Because the validation uses regular expressions, it's possible to load regular expressions into the list box and then retrieve them directly from there. It's the regular expression for the card type the visitor selected that's actually used.
The links at the top include a demo project that contains a sample of how the control can be used. However, here are the required steps.
CreditCardValidatorassembly into the application's /bin directory.
<%@ Register TagPrefix="etier" Namespace="Etier.CreditCard" Assembly="CreditCardValidator" %>
ControlToValidateand other properties where necessary):
<etier:CreditCardValidator
<etier:CardTypesListBox
and set the validator control's
CardTypesListBox property:
CardTypesListBox="CardTypesListBox1"
IsValid()and only process the form data if it returns
true.
To use the control from within Visual Studio .NET, you need to right click on the toolbox, choose "Add/Remove Items ...", and then browse for the compiled assembly. Then double check that the
CreditCardValidator and
CardTypesListBox components are then listed and checked in the list box. Then you can drag and drop them onto the page. If you want to use the card types list box, it's also necessary to add card types into the application's XML configuration file.
This has turned out to be quite a large article, and has grown significantly beyond what I had originally written in 2002. I've been extremely grateful to hear from those who've used the code and found it useful, and do appreciate all suggestions that people email me.
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/validation/CreditCardValidator2.aspx | crawl-002 | refinedweb | 5,519 | 53.1 |
Azure Event Grid
February 9, 2018 Leave a comment
On January 30th, Azure launched a new service that, at least in Azure terms, represents a bit of a paradigm shift. This new service, the Azure Event Grid, is unlike anything else that exists in Azure, for one simple reason… its part of the “fabric” that is Azure. In Azure, you create a database, a virtual machine, a queue, etc… but there’s no creating a “grid”. The Azure Event Grid just exists. For all purposes, its just part of Azure.
This caused me a bit of confusion at first. I’ve never claimed to be the smartest guy in the room, but I think I’m fairly savy. So if I was confused by this at first, I figured there have to be others that might have similar challenges. So I wanted to put my own version of what this service is down in writing.
Overview
Azure Event Grid (we’ll just call it “the grid” for short, and because I’m a Tron fan), conceptually, can be thought of as a model for publishing, and consuming events using a pub/sub model. It has topics to which events are published, and subscribers that allow you to get those events with filtering so you only receive the events you want. Unlike queues and Azure’s Event Hub, grid subscriptions don’t need to be polled, instead they use a message pump approach to push events to a predefined endpoint (usually a web hook). And unlike Event Hub, its not a long term buffer. Instead it does it’s best to retry delivery periodically before the message is finally discarded. For a more detailed breakdown of the differences, be sure to look at the official documentation.
Topics come in two varieties, system topics and custom topics. System topics are created and managed by the various Azure Services. Azure storage, Azure Subscriptions, Events Grid already provides system topics and more are on the way. System topics are “just part of Azure”, so there’s no need to create them and you won’t see them in the portal. They are “just there” and managed by Azure for you to use if you so desire. If you want to publish your own events, you can create a custom topic and you’ll be able to see and manage the custom topics as you would any other Azure resource. To loop back on the early message, the topic is an input endpoint, and the subscription are output endpoints, the grid is in the middle doing the plumbing between the two so you don’t have too.
To get the messages, you create subscriptions on the topics. A subscription provides the filtering criteria describing the events you want to receive and the endpoint you want events that meet those criteria to be sent too. Where you “see” subscriptions as Azure resource objects, depends on the type of topic they are associated with. If its a custom topic, you’ll see them listed as sub-resource objects of the custom topic they belong too. For system topics, you’ll see subscribers as sub-resources of the system resources you’re subscribing too (sort of like queues within a Service Bus namespace).
One last little catch here. System topics, even though they are part of Azure, are not system wide. For example, you currently can’t subscribe to all events from every storage account within a subscription. You instead have to subscribe to each storage account you want messages on. This means individual subscriptions on each storage account. Fortunately, you can have each of those subscriptions sending events to the same endpoint, giving you consolidated processing. But you do have to manage the individual subscriptions.
System topics do have another important difference from custom topics. A system topic will have an established list of events types, and their schema. These published schemas are there to help you better determine the proper filtering when creating subscriptions on system defined topics. This doesn’t exist for custom topics because you, as you’d expect, have full control over the events that get published into it.
Publishing Events
Like I said, system topics publish their own events and you can’t publish to those same topics. So if you want to have your own events, you will need to create a custom topic and send the events to that. This is done using a simple HTTP operation. In c#, it xould look as follows:
HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("aeg-sas-key", sasKey); // add in our security header HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, topicEndpoint) // create our request object { Content = new StringContent(JsonConvert.SerializeObject(eventList), Encoding.UTF8, "application/json") }; HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult(); // post the events
sasKey is the security token for the custom topic. eventList is a generic List object that contains a collection of our event objects for serialization. That custom object should look something like this.
public class GridEvent where T : class { public string Id { get; set; } public string Subject { get; set; } public string EventType { get; set; } public T Data { get; set; } public DateTime EventTime { get; set; } }
Of course you can do follow the approach above using the language of your choice. I just provided an example in C# as its my primary language. If you are using C#, you may opt to use the .NET SDK instead. If so, it looks a bit like this.
<pre>// create a list object for the events that will be send List eventList = new List(); // loop through adding events to the list foreach (var message in eventHubMessages) { EventGridEvent myEvent = new EventGridEvent() { Id = Guid.NewGuid().ToString(), EventTime = DateTime.UtcNow, EventType = $"{eventType}", Subject = $"{eventMessage}", Data = $"{eventData}", DataVersion = "1.0" }; eventList.Add(myEvent); } // create the topic credential TopicCredentials topicCredentials = new TopicCredentials(sasKey); // Create the client object and publish/send to topic EventGridClient client = new EventGridClient(topicCredentials); client.PublishEventsAsync($"{gridname}.{regionprefix}.eventgrid.azure.net", eventList).Wait();</pre>
In this case I’m using the SDK defined EventGridEvent class (naming brought to you by the Department of Redundancy Department). But the general approach is still the same, create a collection, put the event objects into the collection, then send them to the topic endpoint. The collection is used to help batch things together because http handshakes can be resource intensive so this helps reduce the number of handshakes when we’re sending events. You can also find this full SDK example on github.
Consuming Events
As we mentioned, a subscription defines what events you want to receive from a topic and the endpoint they should be sent too. When you create the subscription, you define these settings using a pre-defined schema. The schema represents a JSON object that describes the properties of the subscription. Things like…
includedEventTypes – an array of the event types you want to receive. If not specified, it defaults to all types. If one or more types is specified and you’re creating a subscription on a system topic, the values must match registered event types for that topic.
subjectBeginsWith – the value of the event’s Subject property starts with the specified value. What is contained in the Subject property will depend on the topic you are subscribing too.
subjectEndsWith – the value of the event’s Subject property ends with the specified value
subjectIsCaseSensitive – if the two subject matches should be case sensitive or not
Now the obvious question is why doesn’t Event Grid just support something like REGEX for matching on the Subject property (which is just a string value). I won’t speak for the product team on this but, but my theory is that when you’re building a solution like Azure Event Grid… one that commits to dealing with potentially tens of thousands of events and doing so with single digit millisecond latency… you have to make choices. REGEX, while simple to use, is a bit more complex under the covers and therefore more computationally intensive then a simple string match on the beginning or ending of a string. So I suspect they’ve done this to maximize throughput while minimizing latency.
When you create the subscription, assuming you’re sending to an https/webhook endpoint, you’ll need to make sure the receiver is prepared to respond to the validation event. Validation of endpoints is important, because without it, Event Grid turns into a giant DDOS engine. The validation event is Event Grid’s way of ensuring that events are only being sent to endpoints that are prepared to receive them. When the subscription is created, it sends a special event to the endpoint and expects a specific response back in return. If its not received, the subscriber will be invalidated and events won’t be published. This helps prevent abuse by ensuring that all endpoints agree to receive events. Another important point here, unless you want to write your own validation code, when creating an Azure Function to be used as an endpoint, be sure to use the Event Grid trigger and not the more generic HTTP trigger. If you want an example of using the HTTP trigger, then I’d recommend this post by Brandon Hurlburt.
Now at this point I could show you code for processing the event once its been delivered. But fortunately the product team has already done a really good job of documenting how to do this. And given that we’ve already covered how to wire things up, I don’t know that I can add anything meaningful.
Event – End of Line
So that’s really it. Event Grid, because its part of Azure, is incredibly easy to use. Its really just a matter of saying “I want to subscribe to these events, and here’s where to send them”. This makes it a great example of serverless approach because the wiring is taken care of for you so you can focus on just processing the event itself. That said, this service is still very new, so the number of Azure system topics is somewhat limited. But the team behind the Event Grid is working to change this and is also great about listening to suggestions on how to improve the service. If you have problems using the event grid and need some advice, post on StackOverflow with the tag “azure-eventgrid”. If you have a suggestion about the service, something you think is needed or could be improved, then make use of the official Azure Feedback forum.
Lastly, I’d like to thank Bahram, Dan R, and the rest of the Service Bus team for the great work they did bringing Event Grid to market. Also a shout out to Cicil Phillip for his post on sending to event grid with http and C#.
Until next time!
PS – yes, this post was written while listening the Tron Legacy soundtrack on repeat. Please don’t judge. 🙂 | https://brentdacodemonkey.wordpress.com/2018/02/09/azure-event-grid/ | CC-MAIN-2018-26 | refinedweb | 1,823 | 61.67 |
Creating a Java-based Job Launcher with an OSGi ICE plug-in
This tutorial series is for anyone who needs to extend ICE, for whatever reason, to perform custom tasks such as launching new types of jobs or creating new types of input files. In the second part, Using the Job Profile Editor to create Job Launchers, you learned about the Job Profile Editor, which can be used to automate the plug-in creation process for launching jobs. This part continues the tutorial by showing you how to create the same Job Launcher that you did in part two, but with the Java API.
Contents
Using the Java API and putting up with the build
Job Launchers are a special case in ICE where writing native Java code to perform the tasks related to execution may not be worth the effort, because the infrastructure in ICE is already available, well-tested and quite capable. This is not true for other types of tasks, such as generating input from third-party input generators or analyzing domain data. ICE provides access to some utilities for the latter, but in either of those cases, there are normally very specific tasks to be done. The only way to do this is to write the code directly using the Java API.
We will do this for the Job Launcher that you created in the last tutorial to ease you in to your first plug-in. You will not have to implement reviewEntries() or process() for this exercise and your implementation of setupForm() will use some more convenient routines to simplify the programming aspect. This lesson is more about familiarizing you with the process of making the OSGi plug-in and writing the Java code than dealing with ICE's data structures, which will be covered in the next couple of lessons.
The Job Launcher that you created in the last exercise had the benefit of being serialized and interpreted. Unfortunately, it will not be that easy with this plug-in because the Java code must be compiled. This is a good thing if you plan to distribute your plug-in publicly and have a lot of custom work to do, but it can be a pain if you only want to launch a job. Compilation is required for any other type of plug-in, so consider Job Launchers an exception to the rule.
Generating your OSGi plug-in
The first step to develop your Java-based ICE plug-in is to create the actual OSGi plug-in that will serve it. We will walk through that process briefly, but for details on how OSGi bundles work, we ask that you look into tutorials specifically for OSGi bundles. There are a lot of good OSGi tutorials on the internet, such as OSGi Modularity by Lars Vogel.
OSGi bundles can be created by hand, but the easiest way to create one for use with the reference implementation--Equinox--on which ICE is built, is to have Eclipse generate as much of the "boiler plate" coffee and metadata as possible. Since Eclipse itself is based on Equinox and has a large community of developers, it is already very good at doing this.
Open your Eclipse installation and make sure you are in the Plug-in Development perspective by finding the Perspectives bar. It is not explicitly labelled, but it's at the top right of the workbench. If the plug-in development button does not appear in this bar, click the Open Perspective button (first one in the bar) and search for it. If it is not in the list that appears, then you do not have it installed and need to check your Eclipse installation.
Create a new plug-in project with the wizard. Keep in mind that a plug-in project is not the same as a normal Java project. It has its own wizard, along with some additional files and dependencies.
The next window that appears will ask for a project name and some other information. The only information you need to change here is the name. We have used com.mycompany.nice for the name of the plug-in, and we recommend that you use something similar, but with the name of your organization instead of the placeholder. All of the plug-ins in ICE start with gov.ornl.nice, for example, because they were written at Oak Ridge National Laboratory for ICE. Do not change any of the other information on this screen unless you have experience developing plug-ins and know what will happen. You should make sure that the target platform is an OSGi framework and not an Eclipse version. When you are finished, continue to the next screen.
The Content window asks for some more descriptive information about your plug-in here. Again, for the tutorial we have just used com.mycompany.nice, but you can use whatever you want. Be sure to uncheck the box next to Generate an activator... Activators are used to bootstrap your plug-in in the OSGi framework, but for ICE plug-ins, we use an alternative method called OSGi Declarative Services to load our plug-ins.
Here, we used version number 1.0.0. This is fine, but it's worth noting that most of ICE's plug-ins use version 2.0.0, and that is another possible option. Likewise, as a result of updates, your execution environment might be different. Neither discrepancy would make a difference in this tutorial.
When you continue to the next screen you will be asked to select a template from which your plug-in should be generated. Do not select a template and uncheck the box labeled Create a plug-in using one of the templates.
Click Finish when you have supplied all of the information above. Your plug-in should appear in the Package Explorer or Project Explorer views to the left of the workbench and your MANIFEST.mf file should appear in the editor portion of your workbench.
The MANIFEST.mf file editor lets you edit all of the configuration details of your plug-in and is read by the OSGi framework to load your bundle... so don't delete it! :) You need to modify your bundle dependencies to let the framework know that you depend on different pieces of ICE. Click the Dependencies tab of your MANIFEST.mf file and under the Required Plug-ins section, add gov.ornl.nice.nicedatastructures and gov.ornl.nice.niceitem. In an ideal world we would list these dependencies via the Imported Packages mechanism, because it would allow us to change out those bundles more dynamically (because it only describes imports, not hard-links to bundles), but the plug-ins must be required in ICE because the Java Persistence API is used to persist Items. If you use Imported Packages instead of Required Bundles, you may be able to find the pieces of ICE that you need, but the binary build will not work! After you add those two bundles, also add the org.eclipse.core.resources and org.eclipse.core.runtime bundles. If you can not find those bundles, make sure you followed the instructions in Compiling ICE From Scratch to set your target properly. When you finish this step, save your progress. Otherwise, the change won't be processed, and you won't be able to do the next step.
Creating your custom LauncherBuilder and Launcher
A quick software quality note: While we will not show it as part of this tutorial, it is totally possible to and we strongly suggest unit testing and smoke testing your ModelItem and ModelItemBuilder. Those tasks are beyond the scope of the tutorial, but we do it for everything in ICE and we recommend that you do it for your plug-ins too.
Note that when adding the interface in the table, searching for the class name alone, i.e. ItemBuilder will do the trick.
Throughout this tutorial, always keep in mind that a JobLauncher is a type of Item!
package myplugin; import org.eclipse.core.resources.IProject; import gov.ornl.nice.niceitem.item.Item; import gov.ornl.nice.niceitem.item.ItemBuilder; import gov.ornl.nice.niceitem.item.ItemType; public class LauncherBuilder implements ItemBuilder { // The name of the Item and this builder private final String name = "List Directory Contents"; // The type of the Item private final ItemType type = ItemType.Simulation; /** * The constructor. */ public LauncherBuilder() { // If you require some special initialization stuff, you can do it here. // Otherwise, you don't actually need a constructor for the builder. } public String getItemName() { // Just return the name return name; } public ItemType getItemType() { // Just return the type return type; } public Item build(IProject projectSpace) { // The Item that will be returned Launcher item = null; // Make sure the project space is not null before creating the Item if (projectSpace != null) { item = new Launcher(projectSpace); } return item; } }
On to the Launcher class!
package myplugin; import org.eclipse.core.resources.IProject; import gov.ornl.nice.niceitem.item.Item; import gov.ornl.nice.niceitem.item.jobLauncher.JobLauncher; public class Launcher extends JobLauncher { /** * The constructor. * * @param projectSpace * The Eclipse project space that will be used for file * management. */ public Launcher(IProject projectSpace) { // Call the JobLauncher constructor to let it know what project space to // use and to setup for the job launch. It will in turn call // Item(projectSpace). super(projectSpace); } /** * The alternative nullary constructor. In general this should not be used. */ public Launcher() { // Just defer to the other constructor because work does need to be // performed. this(null); } /** * This operation creates a Form for the FileSimulation with two Entries, * one for the file name and one for the computing platform,. It also creates * one DataComponent. */ protected void setupForm() { // Set the name and description of the Item setName("List Directory Contents"); setDescription("A launcher for the \"ls\" system command on Linux. " + "This command is used to list the contents of a directory" + " on the file system."); //Note that if you're on a Windows machine, you should use dir instead of ls. // Setup the Form super.setupForm(); // Setup the executable information setExecutable(getName(), getDescription(), "ls"); // Add a couple of hosts addHost("127.0.0.1", "linux x86_64", "/usr/bin"); addHost("localhost.localdomain", "linux x86_64", "/usr/bin"); return; } }
Create the OSGi component definition
We will now create the OSGi component, which will register your ItemBuilder service and ensure your plug-in is booted by the framework.
We will first go to File --> New --> Folder. Make your plug-in the parent folder, and name the folder OSGi-INF. While we will only make one component definition, creating a folder is standard and will keep everything tidy. Hit Finish.
Next, right-click on the folder you've created, then click New --> Component Definition
Your window should look something like the picture below. Make sure the parent folder is the name of your plug-in and the File name is something relevant. The Name can be anything, but if it ever matches the name of any other component definition you make, they'll clash and you'll get errors, so it's good practice to name it for its plug-in and class.
Note that the request for the Class is a bit misleading. "Class" must include both your package name, and class name, following the format: package.class
Next, when the component has been created, you should automatically be on the Overview tab. Look to the top right, and under Options, make sure the box next to This component is enabled when started is checked.
Proceed to the Services tab. Under Provided Services, click Add and choose ItemBuilder - gov.ornl.nice.niceitem.item.
Now your component is ready for configuration.
Add your component to the build and launch configurations
Return to your MANIFEST.MF and select the Build tab. This may have happened automatically, but make sure that in the section titled Binary Build, the square next to your OSGi-INF
file is filled or checked. As you can see, this is also the section you would go to for changing runtime information, but we don't need to do that for this tutorial.
Now we're ready for the final step: adding your plug-in to the launch! When compiling ICE, you should have imported gov.ornl.nice.client.eclipse.rcp. Right-click on this plug-in, go to Run As..., then click on Run Configurations at the bottom.
Go to the Plug-ins tab and search for your plug-in name. Check the box, and then make sure auto-start is set to True. This will ensure the inclusion of your plug-in within ICE.
Now select Apply. Now if you select Run, when ICE launches, you should be able to create your customized Item. Remember that ICE must be run as an Eclipse application.
Source code for this exercise
The source code for this section can be checked out from our repo of tutorials here. It will be under ICEYourFirstPluginTutorial > Part 3. The Build tab in the MANIFEST.mf file will look a little bit funky, but hopefully you can make do with the screenshot.
Next Steps
This tutorial allows you to have your plug-in in binary form, so you can customize its behavior, which is necessary for more complex tasks. Users who want to go a step further can check out part 4: Extending your plug-in to generate input files. | https://wiki.eclipse.org/Creating_a_Java-based_Job_Launcher_with_an_OSGi_ICE_plug-in | CC-MAIN-2021-39 | refinedweb | 2,233 | 63.7 |
Linear Regression with Tabpy : Predict Wine QualityTOMOHIRO IWAHASHI
Hi, Can I ask for advice ?
I want to create linear regression line predicting Alcohol by Density of red wine quality .
Data set is from UCI Machine Learning Repository:
UCI Machine Learning Repository: Wine Quality Data Set
I want to draw Linear Regression trend line on scatter plot by Tabpy.
like this:
* I created calculation field like this:
SCRIPT_REAL(
'
# Read pandas and numpy
import pandas as pd
import numpy as np
# Read sklearn.linear_model.LinearRegression
from sklearn import linear_model
clf = linear_model.LinearRegression()
X = pd.DataFrame(_arg1)
Y = pd.DataFrame(_arg2)
Ymat=Y.as_matrix()
Xmat=X.as_matrix()
Xmatr=Xmat.reshape(-1,1)
#Fit Linear Regresion Model
clf.fit(Xmatr, Ymat)
predict = clf.predict(Xmatr)
# Convert to list format
return predict.tolist()
#return 1
',
SUM([Density]), SUM([Alcohol])
)
* And get following Error "Cannot interpret json value of type 'array' as scalar value .
When I change "return predict.tolist()" to "return 1 " it succeeds, so At the point of "return predict.tolist()" , the error is occurring .
The lines above is OK.
Does anybody have idea what is wrong ?
I attached workbook and ipython notebook .
Regards,
Tomohiro.
1. Re: Linear Regression with Tabpy : Predict Wine QualityPrayson Wilfred Daniel Sep 6, 2017 1:12 AM (in response to TOMOHIRO IWAHASHI)1 of 1 people found this helpful
It is now that I see this question
I will show you three ways to go about it. The first two are just like what you are trying to do with a bit of modification. The second tries to split training and testing data in Tableau. The third is what I will recommend
and find simple because TabPy comes with best deployment tools that allow you to work and deploy your model from Jupyter Notebook (/or whatever IDE you are using).
1. I can see you want to train and predict in the same dataset (risky business ). To do so you can do this:
I modified your script to this:
// We are looking for 3 clusters based on the 4 measures SCRIPT_REAL( ' import numpy as np # sklearn.linear_model.LinearRegression クラスを読み込み from sklearn import linear_model clf = linear_model.LinearRegression() X = np.transpose(np.array([_arg1])) y =np.array(_arg2) clf.fit(X,y) return clf.predict(X).tolist() ', SUM([Density]), SUM([Alcohol]) )
2. If you want to train on a training data, and then test it on testing data using Tableau. You can use Random Function
and train the model on training, and test it on the test. During training, you could save your model with joblib (or pickle or dill)
e.g.
SCRIPT_REAL( ' import numpy as np # sklearn.linear_model.LinearRegression クラスを読み込み from sklearn import linear_model from sklearn.externals import joblib clf = linear_model.LinearRegression() X = np.transpose(np.array([_arg1])) #I used transpose here incase you want to add more predictors y =np.array(_arg2) clf.fit(X,y) joblib.dumb(clf, open('C:\\Users\\NameX\\lnWineModel.sav'.'wb')) return clf.predict(X).tolist() ## We could return a better info here ... ', SUM([Density]), SUM([Alcohol]) )
To score the data:
SCRIPT_REAL( " import numpy as np from sklearn.externals import joblib X = np.transpose(np.array([_arg1])) #Used transpose incase you want to add more predictors clf = joblib.load(open('C:\\Users\\NameX\\lnWineModel.sav','rb')) return clf.predict(X).tolist() ", SUM([Density]) )
3. A better way is to train, validate and deploy your model from Jupyter Notebook with TabPy client. From your Jupyter Notebook
you only have to create a function and deploy your model:
def lnWineModel(X): X = np.transpose([X]).astype(np.float64) return clf.predict(X).tolist() import tabpy_client # Connect to local or server TabPy using client #Here I will connect to local server listening at port 9004 connection = tabpy_client.Client(''") #Deploy the model connection.deploy('lnWineModel', lnWineModel, 'Returns the predicted Alcohol given Density')
In Tableau, you now only have to call:
SCRIPT_REAL( " return tabpy.query('lnWineModel', _arg1)['response'] ",SUM([Density])
Let me know if you need more help and I will be glad to guide you.
2. Re: Linear Regression with Tabpy : Predict Wine QualityTOMOHIRO IWAHASHI
Sep 6, 2017 2:25 AM (in response to Prayson Wilfred Daniel)
Hi, Prayson. Thank you for your kind answer.
I could do this by using reshape_(-1,1) in the same way.
You mentioned cross validation too. It is very useful information . Thank you very much !!
SCRIPT_REAL(
'
# Read numpy and pandas
import numpy as np
import pandas as pd
# Read sklearn.linear_model.LinearRegression
import sklearn
from sklearn.linear_model import LinearRegression
# Read data from Tableau
X = np.array(_arg1)
Y = np.array(_arg2)
X = X.reshape(-1,1)
#Fit Linear Regresion Model
lreg = LinearRegression()
lreg.fit(X,Y)
pred = lreg.predict(X)
# Convert to list format and return to Tableau
return pred.tolist()
',
SUM([RM]), SUM([Price])
)
3. Re: Linear Regression with Tabpy : Predict Wine QualityPrayson Wilfred Daniel Sep 10, 2017 6:26 AM (in response to TOMOHIRO IWAHASHI)
Totally true. I would clean unused imports though
SCRIPT_REAL( ' # Import numpy import numpy as np # Read sklearn.linear_model.LinearRegression from sklearn.linear_model import LinearRegression # Read data from Tableau X = np.array(_arg1).reshape(-1,1) y = np.array(_arg2) #Initiate and Fit Linear Regresion Model lreg = LinearRegression() lreg.fit(X,y) #Score using the model pred = lreg.predict(X) # Convert to list format and return to Tableau return pred.tolist() ', SUM([RM]), SUM([Price]) )
We do not need pandas nor sklearn imported | https://community.tableau.com/thread/245053 | CC-MAIN-2018-17 | refinedweb | 898 | 52.66 |
We value your feedback.
Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!
Become a Premium Member and unlock a new, free course in leading technologies each month.
import java.util.*; class testInput{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int code; String fname,lname; System.out.print("code: "); code = in.nextInt(); System.out.print("first name: "); fname = in.nextLine(); System.out.print("last name: "); lname = in.nextLine(); System.out.printf("code: %d fname: %s lname: %s \n",code,fname,lname); } }
Add your voice to the tech community where 5M+ people just like you are talking about what matters.
If you are experiencing a similar issue, please ask a related question
Join the community of 500,000 technology professionals and ask your questions. | https://www.experts-exchange.com/questions/23826954/Keyboard-input-with-Scaner-class.html | CC-MAIN-2017-22 | refinedweb | 141 | 51.14 |
Hey All,
Been reading similar topics but really can't find the answer.
Trying to do a full planet import on a dell R230 32gb ram/ 4core 3Ghz / 2x 7200RPM drives in raid0
(I know don't have SSD's)
Processing: Node(4076728k 1344.6k/s) Way(183316k 0.78k/s) Relation(0 0.00/s)
Looking at htop I see it's still processing, cpu is nowhere near busy, ram is 28.8/31.3GB and using approx 6G of swap.
If it helps my ultimate use case is reverse geocode lat/lon in large batches. I only need Country/State/City or similar (town/suburb/county etc)/Postal Code not sure if -slim or something else might have helped there.
Any insight is appreciated.
Thanks
asked
23 Sep '17, 00:43
felix2001
11●1●1●2
accept rate:
0%
Once you sign in you will be able to subscribe for any updates here
Answers
Answers and Comments
Markdown Basics
learn more about Markdown
This is the support site for OpenStreetMap.
Question tags:
import ×161
ways ×136
planet_osm ×22
question asked: 23 Sep '17, 00:43
question was seen: 678 times
last updated: 23 Sep '17, 00:43
Unable to render tiles after full planet import
Import only lakes
Does order of ways on relation members is random?
Import crashed at "going over pending ways"
osm2pgsql planet import killed
Restarting osm2pqsql full planet import because of too low --cache setting? (import runs for 6 days already)
Uploading a small bit of new TIGER data (and 3 other unrelated questions)
Is there a limit to the number of ways containing a node?
How to see roads underneath areas in JOSM ?
Uploading a GPX from TTGpsLogger doesn't work
First time here? Check out the FAQ! | https://help.openstreetmap.org/questions/59787/planet-import-very-slow-ways | CC-MAIN-2019-26 | refinedweb | 295 | 71.55 |
JSP PDF books
JSP PDF books
Collection is jsp books in the pdf format... to set up than do beans. Fourth, beans are often defined in
one servlet
calling one jsp from another jsp page
calling one jsp from another jsp page need coding for calling one jsp from another jsp including the xml file.Its urgent
JSF Books
JSF Books
Introduction
of JSF Books
When we heard about JavaServer? Faces (JSF) at the 2002 Java One conference,
we?
Struts Books
to turn to once they have read the introductory books.
Identifies what... provides a set of tag libraries that simplify programming JSP pages (the view). James...
This is one of those books that just gets worn out. I'm always reaching
Ajax Books
when one should be used over another. You will also learn different Ajax...
Ajax Books
AJAX - Asynchronous JavaScript and XML - some books and resource links
These books
calling one jap page from another jsp page
calling one jap page from another jsp page i created a button in one jsp page i need to call another jsp page as an action to that button. so how can i call.. plz any one explain. its urgent
VoIP Books
VoIP Books
VoIP Books Voice over IP
With a potential 90 percent... specialty, and in IP Telephony Demystified he offers the best set of tools out....
Practical VoIP Using VOCAL
While many books describe the theory
Java Programming Books
program, objects enter one of their methods when cued to do so by another object...
Java Programming Books
...
As the author of computer books, I spend a lot of time loitering in the computer
onfly conversion of jsp to pdf (urgent) - Development process
onfly conversion of jsp to pdf (urgent) Hi,
i m facing problem to convert jsp to pdf on on fly,
i have an application in which there is some set of questions, user select the page 1 ques and click next .there is another
EJB Books
EJB Books
Professional
EJB Books
Written... of useful sample code, this title is one of the best available guides to working
The session Attribute of page Directive In JSP
for running the JSP page on the server. If
you set the value of session object false... The session Attribute of page Directive In JSP
... illustration of the session
attribute of the page directive in JSP
Free JSP Books
Free JSP Books
Download the following JSP books... of the form.
The JSP page Directive: Structuring Generated Servlets
calling one jsp from another jsp - JSP-Servlet
calling one jsp from another jsp Hi All,
In my web application I have two jsp files(one.jsp and two.jsp). I have written a seperate method...
pageContext.include("./nextjsppage.jsp");
when you use this statement the jsp page
Mantain a Session in one application after opening another third party application - JSP-Servlet
Mantain a Session in one application after opening another third party application Hi
My Requirements is like this..
I have one ear... up a third party application in another widow., and session in the current
Tomcat Books
This is one of the first set of books from Wrox Press after its acquisition... of your site.
Tomcat
Works
This is one of the rare books.... The last one I read was Tannenbaums classic "Operating Systems". The Tomcat book
Free Java Books
with. For one thing, they were all too big! There was no way my students would read...
Free Java Books
Sams Teach Yourself Java 2 in 24 Hours
As the author of computer books, I spend a lot
<jsp:useBean
<
Session Problem in JSP - JSP-Servlet
Session Problem in JSP I have developed a online feedback form in JSP platform. I have created normal session in JSP page. It is running in my machine properly, but when I am trying to access it from another machine
Free JSP download Books
Free JSP download Books
Java Servlets and JSP
free download books... optimization.
The
Professional JSP Books
The JDC
session in jsp - Java Beginners
Hi friend,
session is implicit object in jsp.
using session oject in jsp.
first u set using following methods
String name... let me know how to create a session in jsp.
Session for jsp with two side
Generate pdf file - JSP-Servlet
Generate pdf file
Hi Friends,
How to generate the pdf file for the jsp page or in servets Hi Friend,
You need to download itext api. After that set the classpath and try the following code
Servlets Books
amazon.com and fatbrain.com as one of the ten best computer programming books of the year, and was one of the top ten best-selling computer-related books at Borders...;
Books : Java Servlet & JSP Cookbook
jsp
jsp Suppose we want to pass data to one page to another page with same request on the session how do we do
The Page Directive in JSP Page
and explanation one-by-one. This is the directive
of the JSP page which defines the properties for the entire JSP page by using
it's different attributes and set... session because the
client must be in the HTTP session for running the JSP page
session
session how can transfer data of one page to another page using session in java swingSTL: Set Session Attribute
and jsp. That's why
the jstl is too easy.
In jstl we will set the session...JSTL: Set Session Attribute
... are using the jstl and
there is a need to set a variable in the session. You all know
Preventing the creation of a Session in a Jsp Page
Preventing the creation of a Session in a Jsp
Page... this make one jsp page or html page where we
have given two field, one is of name... have been provided the implicit session
object. In jsp the session time in jsp page
how to set time in jsp page I need code for set the time in jsp code .iam using struts frame work back end oracle 10g ide is eclipse 6
session tracking - JSP-Servlet
username on top of page( that is how do i transfer info from one page to other...session tracking hi,
i m working on a real estate web site....which i have to submit as final year project. im having problem regarding session
JSP Session Parameter rewrite
JSP Session Parameter rewrite
... in jsp.
JSP session provides methods like getCreationtime(), getLastAccessedTime... to set the time
out for each session. removeAttribute() method is used
MySQL Books
;
Larry Ullman's Books
On this page you will find all of the books written... Balling, finally arrived from Amazon. There?s very few tech books I can read from... one
expert on Oracle's PL/SQL, having written a number of books which are seen
query regarding exporting table from jsp page to pdf
query regarding exporting table from jsp page to pdf hello
i am displaying one table on my jsp page and i want to save that table in pdf file can u...;
</form>
</html>
2)pdfTable.jsp:
<%@page import="java.io.*"%>
Set Parameter - JSP-Interview Questions
Set Parameter Hi, could someone please explain the process of setting parameter in the session from JSP with the help of code? Thanks! Hi,In your JSP page use the Set Tag, and set the scope attribute
session syntax for logout - JSP-Servlet
session syntax for logout What is the syntax for writing session for logout page in login services ? Hi friend<%@page import="...;----------------------------read for more information,
Page Directive attribute - session
Page Directive attribute - session
This tutorial contains description of session attribute of page Directive.
session Attribute :
session attribute is one... that the JSP page has permission to access existing session
and false value
Disabling Session in JSP
page.
You can tell the container to disable session in the JSP file by setting the
session attribute to false. Set the session attribute of the page... Disabling Session in JSP
how to generate the pdf report from jsp
how to generate the pdf report from jsp <%@page import... want to generate the pdf file from jsp page.I add the itext.jar to the libraries... not getting the pdf file.Any one please help me asap.Its very important
Session In JSP
data from one page to another page only
when the session is true .
...;
JSP Hidden Form Fields
It is one of the way to maintain the session...;
Preventing the creation of a Session in a Jsp
Page..._equivalentset);// added to session attribute
JSP FILE 2 : // the file where i
searching books
searching books how to write a code for searching books in a library through jsp
JSP Tutorials - Page2
application.
The session Attribute of page Directive In JSP... page level variables
declared by the JSP page.
Use Session...JSP Tutorials page 2
JSP Examples
Hello World JSP Page&
JSP Tutorials
. In any web application user moves from one page
to another and it becomes... the value of the same cookie in another JSP page.
Cookie Example...
the performance of your JSP container.
JSP PDF books
JSP Session Object
JSP Session Object JSP Session Object?
Session Object denotes the data associated with a specific session of user. The class... of Session Objects is to maintain states when there are multiple page requests
Session Timeour - JSP-Servlet
Session Timeour Hi,
How to create a session timeout page in JSP? Session timeout should happen after 15 mins of idle instance.
Thanks ... the following link:
jsp - JSP-Servlet
that session ?????? Hi friend,
Disabling Session in JSP
By default attribute "session" is true. To disable it set session is "false".
Session Disabled
Session is Disabled in this page
For read in more details
parser xml one page to another
parser xml one page to another parser xml one page to another
Open Source Books
.
Open Source and Linux
One of our very first books was about...
Open Source Books
Open Books
O'Reilly has published a number of Open Books--books with various forms of "open" copyright--over the years
JSP Implicit object "session"
about JSP implicit object "session" with an
example. Session Object... of
object as string's value and you can get this value in other JSP page...
to fetch the value of "String" which is set by you, in other JSP
Misc.Online Books
Misc.Online Books
... vision of a software project is dealing with one's coworkers and customers... when I was twenty-one.
This is very subjective and, therefore
Session concept - JSP-Servlet
Session concept Hai friends,
I am doing a jsp project with session concept. If one person is not accessing his logged window for more than 10 minutes it gets automatically log out.Anybody explain me the reason
JSP
organization. OSCache has a set of JSP tags that make it easy to implement page... entry. In a JSP application,a cache entry is typically the output of a JSP page, a portion of a JSP page, or a servlet.
Cache key
A page cache is like a hash
CORBA and RMI Books
CORBA and RMI
Books
... and CORBA
The standard by which all other CORBA books are judged, Client/Server Programming with Java and CORBA is the book to read if you're thinking about file using BufferedReader, then writing the output like this:
String
Session expire and back button in jsp and servlet .
Session expire and back button in jsp and servlet . Hii Sir,
I have to make a login and logout page with sessions .Now i have... button.Means that
after session expiry time and logout action no one can access
session - JSP-Servlet
session How to manage session for a particular user ..using session... then userid is set in your session.RegardsAmar Answer:If you get id as a integer from mlid field then userid is set in your session.RegardsAmar
JSP Programming Books
JSP Programming Books
... is updated to cover JSP 1.2's full feature set, and both the advantages... and services.
Servlets and JSP technology is the foundation
Oracle Books
bought two Oracle books- this and one from another publisher-and this is always...
Oracle Books
... language. His new book looks thoroughly at one especially advanced and powerful
session
session is there any possibility to call one session from another session
session maintainence - JSP-Servlet
session maintainence how to enable a link only if the form in previous page is clucked please show me your
|
JSP PDF books
| Free JSP Books
| Free
JSP Download |
Authentication... in JSP Page
|
import Attribute of
page Directive JSP |
session Attribute... To Lowercase Tags of JSTL |
Display image on JSP page using XML |
Make
a Pdf
Passing Parameters to Another JSP Page
Passing Parameters to Another JSP Page
By using the include action we can pass the parameters
to another jsp page... introduce a new request parameter when calling a jsp page.
This param tag can
jsp - session - JSP-Servlet
JSP - Session How to manage session in JSP
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://roseindia.net/tutorialhelp/comment/2921 | CC-MAIN-2015-27 | refinedweb | 2,173 | 72.36 |
26 July 2011 12:25 [Source: ICIS news]
Correction: In the ICIS story headlined “PETRONAS working with BASF on new $20.2bn project in Malaysia” dated 26 July 2011, please read in the headline… $1.36bn project…instead of…$20.2bn project. Also please read in the first paragraph...(M$) 4bn...instead of...(M$) 60bn. A corrected story follows.
SINGAPORE (ICIS)--PETRONAS is currently working with German chemicals major BASF on a Malaysian ringgit (M$) 4bn ($1.36bn) project to be built at a new integrated complex at Pengerang in southern Johor, a top industry executive said on Tuesday.
The project is expected to be completed by the end of 2012, PETRONAS Chemicals chairman Wan Zulkiflee Wan Ariffin was quoted by national news agency Bernama as saying.
The joint venture project will be part of PETRONAS’new $20bn integrated refinery and petrochemicals complex in southern Johor, Bernama said without further elaborating on details.
Both companies will also undertake a feasibility study to expand some of PETRONAS Chemicals’ facilities in Gebeng, Pahang, which includes an investment of M$4bn, Bernama quoted Wan Zulkiflee as saying without elaborating further.
BASF and PETRONAS had earlier in March this year announced plans to conduct a feasibility study for a superabsorbent polymers plant in ?xml:namespace>
The feasibility study is expected to be completed by the end of 2011, Wan Zulkiflee said.
BASF and PETRONAS Chemicals operate a joint venture integrated petrochemicals complex, producing acrylic monomers, oxo products and butanediol in the Gebeng industrial zone in
Meanwhile, PETRONAS Chemicals is currently searching for “internal and external sources of funding” for a new $1.5bn fertilizer plant in Sipitang,
The fund raising exercise for the development of the fertilizer plant is expected to be concluded by the end of 2011, Wan Zulkiflee was quoted as saying.
PETRONAS Chemicals is willing to offer an up to 30% stake in the fertiliser project, according to Bernama.
PETRONAS was not immediately available for comment.
($1 = M$2.95)
For more on BASF and PETRON | http://www.icis.com/Articles/2011/07/26/9479835/corrected-petronas-working-with-basf-on-new-1.36bn-project.html | CC-MAIN-2014-10 | refinedweb | 335 | 52.49 |
As happens in LINQ, with Cpplinq, you can use the
std::list<game,std::allocator<game>> generated in the previous query (
highest_scores_for_played_games) as an input for another LINQ-style query and apply operators to the list. The following lines show a simple example that uses the
from range source to create a range from the
std::list<game,std::allocator<game>> to serve as a kick-off for a new query. Then, the query uses the
select project operator to retrieve just the game's name and the
first_or_default element operator to get the first game's name or the default value. The result is the same as in the first example (which used
first_or_default) because the sum of all the operators included in that first and in this second query is equivalent to the query in the first example.
auto first_highest_score_for_played_games = from(highest_scores_for_played_games) >> select([](game const & g){return g.name; }) >> first_or_default();
Working with Range Sources Supported in Cpplinq
One of the main differences between the LINQ-style queries generated with Cpplinq and the original LINQ queries in .NET is the way you have to specify range sources. The following list shows the different range sources that Cpplinq supports:
from: Creates a range from a STL-like container such as
std::listand
std::vector.
from_array: Creates a range from an
Array.
from_iterators: Creates a range from the pair of iterators specified as parameters.
range: Creates an
intrange from the start integer specified as the first parameter (
start) and the desired number of integers specified as the second parameter (
count).
The latest example can be rewritten using
from_iterators instead of
from. The following lines show the use of
from_iterators to create a range from the pair of iterators
highest_scores_for_played_games.cbegin and
highest_scores_for_played_games.cend.
auto first_highest_score_for_played_games = from_iterators(highest_scores_for_played_games.cbegin(), highest_scores_for_played_games.cend()) >> select([](game const & g){return g.name; }) >> first_or_default();
The following C# code is the popular example of the use of the
IEnumerable.Range method. The code uses LINQ to generate a sequence of integers from 1 to 10 and then select their squares:
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
With Cpplinq, you can use
range to produce the same results in a very similar LINQ-style query. The following lines show the code for a C++ console application that uses a Cpplinq LINQ-style query with
range,
select, and
to_list. Then, the code displays the results in the console output.
#include "stdafx.h" #include "cpplinq.hpp" #include <iostream> #include <sstream> #include <string.h> int _tmain(int argc, _TCHAR* argv[]) { using namespace cpplinq; auto squares = range(1, 10) >> select([](int i) { return i * i; }) >> to_list(); for(auto num : squares) { std::wcout << num << std::endl; } return 0; }
I you are a big fan of LINQ-style queries, you probably don't like the idea of writing iteration code to perform an action per value in range. Cpplinq allows you to use
for_each and provide a lambda that specifies a function to be applied once per value in range. The following lines show a simplified version of the previous code that includes the instructions to display the results within the LINQ-style query by using
for_each. However, as happens in the original .NET LINQ implementation, you have to be careful with the things you code within the lambda specified in
for_each in order to avoid having performance problems.
using namespace cpplinq; range(1, 10) >> select([](int i) { return i * i; }) >> for_each([](int i) { std::wcout << i << std::endl; });
Working with Range Aggregators
A LINQ-style query implementation wouldn't be complete without the support of range aggregators. The only LINQ range aggregator that Cpplinq doesn't support is
LongCount.
The following lines show a LINQ-style query that uses the
where restriction operator and the
count range aggregator to calculate the total number of played games in our sample:
using namespace cpplinq; auto played_games_count = from_array(games) >> where([](game const & g) { return g.played_count > 0; }) >> count();
As you might guess, the
max range aggregator makes it easy to use a LINQ-style query to obtain the highest score for all the played games. Note that the query uses the
select project operator with a lambda expression that returns the desired field,
high_score, and then there is a chained call to the
max range aggregator to calculate the maximum value for this field:
auto highest_score = from_array(games) >> where([](game const & g) { return g.played_count > 0; }) >> select([](game const & g){return g.high_score; }) >> max();
Conclusion
The code for Cpplinq is easy to understand and extend, so you can also take advantage of it to extend Cpplinq to fit your specific needs. I'm sure you will enjoy working with LINQ-style queries with Cpplinq and C++11 lambdas. If you have ever worked in .NET and written LINQ code, you'll find you can now enjoy many of its benefits in C++.
Gaston Hillar is a frequent contributor to Dr. Dobb's. | http://www.drdobbs.com/database/data-compression-with-the-burrows-wheele/database/linq-like-list-manipulation-in-c/240166882?pgno=2 | CC-MAIN-2016-40 | refinedweb | 820 | 52.09 |
I’m working on altering the DS1307 RTC library for use with the MCP795XX.
The MCP795 has the first register set to hundredths of seconds and I won’t be using those so I adjusted the write and send pointers to the second register.
I’m a little confused about some of the other hex calls. I’m not sure if they need to be changed based on the different chip, or if they are machine code interrupts, as some of them seem to be. Just starting to work on the research the codes, my biggest one is…
#include <Wire.h> #include "DS1307RTC.h" #define DS1307_CTRL_ID 0x68
Just wanted to know if anyone knows what the 0x68 is in reference as neither the ds1307 or mcp795XX have anywhere close to that many registers.
Library: DS1307RTC Library, For Accessing Real Time Clock (RTC) Chips
MCP datasheet: | https://forum.arduino.cc/t/altering-an-rtc-library/252862 | CC-MAIN-2021-31 | refinedweb | 145 | 79.19 |
I'm kind of a person who likes to listen rather than reading. And I feel my productivity increases when listening rather than reading. As dev.to don't have such audio feature(which will be helpful if they bring it natively).
So, I built a tool that takes input any dev.to blogpost URL and outputs Audio which you can also download.
Tool:
You can check the working of tool in the below video
The workflow of this tool is to scrape the article/blogpost and generate audio using gTTS module.
Modules used:
- Requests - will allow us to send HTTP requests to get HTML pages
- BeautifulSoup - will help us parse the HTML pages
- gTTS - converts the text entered, into audio which can be saved as a mp3 file
- Streamlit - A Python library that makes it easy to create and share beautiful, custom web apps
Let's begin:
import all necessary modules
import streamlit as st import requests from bs4 import BeautifulSoup from gtts import gTTS
Getting the contents of a webpage into a variable
results = requests.get("")
In order to make content easy to understand, we are using BeautifulSoup and the content is stored in soup variable
soup = BeautifulSoup(results.text, "html.parser")
We use soup.find to get name of the blogpost and you can get class names by inspecting elements
Article=soup.find("div",{"class":"crayons-article__header__meta"}).find('h1').get_text()
To get name of the Author
Author=soup.find("div",{"class":"crayons-article__subheader"}).find('a').get_text()
To get article content
text=soup.find("div", {"id": "article-body"}).find_all(['p','h1','h2','h3','h4','h5','h6','ol','ul'])
With the content we also get HTML tags. So we need to remove all HTML tags.
def remove_html_tags(text): for item in text: try: blog.append(item.get_text()) except: pass
Now after scraping the content and cleaning, we need to create audio with the help of gTTS module.
gTTS module also supports other languages like French, Spanish etc..
from gtts import gTTS language = 'en' myobj = gTTS(text=Text, lang=language, slow=False) # Saving the converted audio in an mp3 file name "Audio" myobj.save("Audio.mp3")
This webapp is built using streamlit and deployed in herokuapp
Source Code:
import streamlit as st import requests from bs4 import BeautifulSoup from gtts import gTTS def app(): st.set_page_config(page_title="Audio Blog",page_icon="🎧") st.title("Generate Audio for dev.to blogposts") url=st.text_area("Enter any DEV.TO blog url ").strip() if st.button("submit"): if len(url)!=0: with st.spinner('Miracles take time to happen \n Just kidding 😂 \n Generating audio..'): results = requests.get(url) soup = BeautifulSoup(results.text, "html.parser") blog=[] try: Article=soup.find("div",{"class":"crayons-article__header__meta"}).find('h1').get_text() #st.write(Article) Author=soup.find("div",{"class":"crayons-article__subheader"}).find('a').get_text() #st.write(Author) intro="This blogpost {article} is written by {author}".format(article = Article, author = Author) blog.append(intro) text=soup.find("div", {"id": "article-body"}).find_all(['p','h1','h2','h3','h4','h5','h6','ol','ul']) def remove_html_tags(text): for item in text: try: blog.append(item.get_text()) except: pass remove_html_tags(text) Text="" for ele in blog: Text +=ele+" " myobj = gTTS(text=Text, lang='en', slow=False) myobj.save("Audio.mp3") audio_file = open('Audio.mp3', 'rb') audio_bytes = audio_file.read() st.success("Play or download the audio") st.audio(audio_bytes, format='audio/mp3') except: st.error("Enter a valid url") else: st.error("Enter a valid url") if __name__ == "__main__": app()
lemme know if you have any issues and feel free to send pull request if you had anything to add
Discussion (2)
This is cool, but I am afraid this won't be helpful while reading dev.to posts. Because this tool ignores code blocks, even if it considers code blocks, I am not sure I can follow along by "listening" to code, but this will be super helpful if we can point this to news websites etc
I agree with you but still I can get a overview of what it is | https://practicaldev-herokuapp-com.global.ssl.fastly.net/sunilaleti/building-an-audio-generator-for-dev-to-blogposts-1hgc | CC-MAIN-2021-17 | refinedweb | 668 | 50.63 |
#include <deal.II/base/parameter_handler.h>
The ParameterHandler class provides a standard interface to an input file which provides at run-time for program parameters such as time step sizes, geometries, right hand sides etc. The input for the program is given in files, streams or strings in memory using text like
Input may be sorted into subsection trees in order to give the input a logical structure, and input files may include other files.
The ParameterHandler class is discussed in step-29, step-33, and step-34.
In order to use the facilities of a ParameterHandler object, one first has to make known the different entries the input file may or may not contain. This is done in the following way:
Each entry is declared using the function declare_entry(). The first parameter is the name of the entry (in short: the entry). The second is the default answer to be taken in case the entry is not specified in the input file. The third parameter is a regular expression which the input (and the default answer) has to match. Several such regular expressions are defined in Patterns. This parameter can be omitted, in which case it will default to Patterns::Anything, i.e. a pattern that matches every input string. The fourth parameter can be used to document the intent or expected format of an entry; its value is printed as a comment when writing all entries of a ParameterHandler object using the print_parameters() function to allow for easier understanding of a parameter file. It can be omitted as well, in which case no such documentation will be printed.
Entries may be located in subsections which form a kind of input tree. For example input parameters for linear solver routines should be classified in a subsection named
Linear solver or any other suitable name. This is accomplished in the following way:
Subsections may be nested. For example a nonlinear solver may have a linear solver as member object. Then the function call tree would be something like (if the class
NonLinEq has a member variables
eq of type
LinEq):
For class member functions which declare the different entries we propose to use the common name
declare_parameters. In normal cases this method can be
static since the entries will not depend on any previous knowledge. Classes for which entries should logically be grouped into subsections should declare these subsections themselves. If a class has two or more member variables of the same type both of which should have their own parameters, this parent class' method
declare_parameters is responsible to group them into different subsections:
For the first example above the input file would look like the following:
The words
subsection,
set and
end may be either written in lowercase or uppercase letters. Leading and trailing whitespace is removed, multiple whitespace is condensed into only one. Since the latter applies also to the name of an entry, an entry name will not be recognized if in the declaration multiple whitespace is used.
In entry names and values the following characters are not allowed:
#,
{,
},
|. Their use is reserved for the MultipleParameterLoop class.
Continuation lines are allowed by means of the character
\, which must be the last character (aside from whitespace, which is ignored) of the line. When a line is a continuation (i.e., the previous line ended in a
\), then, unlike the default behavior of the
C preprocessor, all whitespace at the beginning of the line is ignored.
We propose to use the following scheme to name entries: start the first word with a capital letter and use lowercase letters further on. The same applies to the possible entry values to the right of the
= sign.
An input file can include other include files using the syntax
The file so referenced is searched for relative to the current directory (not relative to the directory in which the including parameter file is located, since this is not known to all three versions of the parse_input() function).
In order to read input there are three possibilities: reading from an
std::istream object, reading from a file of which the name is given and reading from a string in memory in which the lines are separated by
\n characters. These possibilities are used as follows:
You can use several sources of input successively. Entries which are changed more than once will be overwritten every time they are used.
You should not try to declare entries using declare_entry() and enter_subsection() with as yet unknown subsection names after using parse_input(). The results in this case are unspecified.
If an error occurs upon reading the input, error messages are written to
std::cerr and the reader function returns with a return value of
false. This is opposed to almost all other functions in deal.II, which would normally throw an exception if an error occurs; this difference in behavior is a relic of the fact that this class predates deal.II and had previously been written for a different project.
An alternative to using the hand-written input files shown above is to use the graphical user interface (GUI) that accompanies this class.
See the parameter_gui github repository for further details.
Each class gets its data out of a ParameterHandler object by calling the get() member functions like this:
get() returns the value of the given entry. If the entry was not specified in the input source(s), the default value is returned. You have to enter and leave subsections exactly as you did when declaring subsections. You may choose the order in which to traverse the subsection tree.
It is possible to avoid calls to enter_subsection() and leave_subsection() by supplying get() with a vector of strings representing the path from which to get a value. For example, the following two versions of get_parameters() will produce the same result:
The latter method allows the ParameterHandler reference to be
const.
It is guaranteed that only entries matching the given regular expression are returned, i.e. an input entry value which does not match the regular expression is not stored.
You can use get() to retrieve the parameter in text form, get_integer() to get an integer or get_double() to get a double. You can also use get_bool(). It will cause an internal error if the string could not be converted to an integer, double or a bool. This should, though, not happen if you correctly specified the regular expression for this entry; you should not try to get out an integer or a double from an entry for which no according regular expression was set. The internal error is raised through the Assert() macro family which only works in debug mode.
If you want to print out all user selectable features, use the print_parameters() function. It is generally a good idea to print all parameters at the beginning of a log file, since this way input and output are together in one file which makes matching at a later time easier. Additionally, the function also print those entries which have not been modified in the input file and are thus set to default values; since default values may change in the process of program development, you cannot know the values of parameters not specified in the input file.
It is often convenient to have something happen as soon as a parameter value is read. This could be a check that it is valid – say, that a file that is listed in the parameter file exists – or to initiate something else in response, such as setting a variable outside the ParameterHandler (as in the example shown below). In almost all cases, this "action" could also be initiated once all parameters are read via parse_input(), but it is sometimes convenient to do it right away.
This is facilitated by the add_action() function that can be called after declaring a parameter via declare_entry(). "Actions" are in essence pointers to functions that will be called for parameters that have associated actions. These functions take the value of a parameter as argument, and can then do whatever they want with it – e.g., save it somewhere outside the ParameterHandler object. (Exactly when the action is called is described in the documentation of the add_action() function.) Of course, in C++ one doesn't usually pass around the address of a function, but an action can be a function-like object (taking a string as argument) that results from calling such as a lambda function that has the form
and that is attached to a specific parameter.
A typical example of such an action would be as follows: let's assume that you have a program that declares a parameter for the number of iterations it is going to run, say
then one could obtain this parameter from a parameter file using a code snippet in
run() as follows:
This two-step process – first declaring the parameter, and later reading it – is a bit cumbersome because one has to first declare all parameters and at a later time retrieve them from the ParameterHandler object. In large programs, these two things also often happen in different functions.
To avoid this, it would be nice if we could put both the declaration and the retrieval into the same place. This can be done via actions, and the function would then look like this:
Here, the action consists of a lambda function that takes the value for this parameter as a string, and then converts it to an integer to store in the variable where it belongs. This action is executed inside the call to
prm.parse_input(), and so there is now no longer a need to extract the parameter's value at a later time. Furthermore, the code that sets the member variable is located right next to the place where the parameter is actually declared, so we no longer need to have two separate parts of the code base that deal with input parameters.
Of course, it is possible to execute far more involved actions than just setting a member variable as shown above, even though that is a typical case.
We propose that every class which gets data out of a ParameterHandler object provides a function named
get_parameters. This should be declared
virtual.
get_parameters functions in derived classes should call the
BaseClass::get_parameters function.
Experience has shown that in programs defining larger numbers of parameters (more than, say, fifty) it is advantageous to define an additional class holding these parameters. This class is more like a C-style structure, having a large number of variables, usually public. It then has at least two functions, which declare and parse the parameters. In the main program, the main class has an object of this parameter class and delegates declaration and parsing of parameters to this object.
The advantage of this approach is that you can keep out the technical details (declaration and parsing) out of the main class and additionally don't clutter up your main class with dozens or more variables denoting the parameters.
This is the code:
This is the input file (named "prmtest.prm"):
And here is the output of the program:
Here is some more internal information about the representation of parameters:
Logically, parameters and the nested sections they are arranged in can be thought of as a hierarchical directory structure, or a tree. Take, for example, the following code declaring a set of parameters and sections they live in:
We can think of the parameters so arranged as a file system in which every parameter is a directory. The name of this directory is the name of the parameter, and in this directory lie files that describe the parameter. These files are at the time of writing this documentation (other fields, such as those indicating "actions" may also exist in each directory):
value: The content of this file is the current value of this parameter; initially, the content of the file equals the default value of the parameter.
default_value: The content of this file is the default value of the parameter.
pattern: A textual representation of the pattern that describes the parameter's possible values.
pattern_index: A number that indexes the Patterns::PatternBase object that is used to describe the parameter.
documentation: The content of this file is the documentation given for a parameter as the last argument of the ParameterHandler::declare_entry call. With the exception of the
valuefile, the contents of files are never changed after declaration of a parameter.
Alternatively, a directory in this file system may not have a file called
value in it. In that case, the directory represents a subsection as declared above, and the directory's name will correspond to the name of the subsection. It will then have no files in it at all, but it may have further directories in it: some of these directories will be parameters (indicates by the presence of files) or further nested subsections.
Given this explanation, the code above will lead to a hierarchical representation of data that looks like this (the content of files is indicated at the right in a different font):
Once parameters have been read in, the contents of the
value "files" may be different while the other files remain untouched.
Using the ParameterHandler::print_parameters() function with ParameterHandler::XML as second argument, we can get a complete representation of this data structure in XML. It will look like this:
This representation closely resembles the directory/file structure discussed above. The only difference is that directory and file names are mangled: since they should only contain letters and numbers, every character in their names that is not a letter or number is replaced by an underscore followed by its two-digit hexadecimal representation. In addition, the special name "value" is mangled when used as the name of a parameter, given that this name is also used to name special files in the hierarchy structure. Finally, the entire tree is wrapped into a tag
ParameterHandler to satisfy the XML requirement that there be only a single top-level construct in each file.
The tree structure (and its XML representation) is what the graphical user interface (see above) uses to represent parameters like a directory/file collection.
Definition at line 840 of file parameter_handler.h.
List of possible output formats used for functions like ParameterHandler::print_parameters(). The options can be categorized into two groups:
Only one format option may be specified at the time. Any function that accepts an OutputStyle as an option will throw if you specify more than one.
A number of shortcuts of commonly used option combinations are provided. E.g., ShortPRM prints the parameters in the PRM format, while skipping the documentation.
Definition at line 858 of file parameter_handler.h.
Constructor.
Definition at line 47 of file parameter_handler.cc.
Destructor. Declare this only to have a virtual destructor, which is safer as we have virtual functions. It actually does nothing spectacular.
Inhibit automatic CopyConstructor.
Inhibit automatic assignment operator.
Parse each line from a stream until the stream returns the
eof condition or error to provide values for known parameter fields. The second argument can be used to denote the name of the file (if that's what the input stream represents) we are reading from; this is only used when creating output for exceptions.
If non-empty
last_line is provided, the ParameterHandler object will stop parsing lines after encountering
last_line . This is handy when adding extra data that shall be parsed manually.
If
skip_undefined is
true, the parameter handler will skip undefined sections and entries. This is useful for partially parsing a parameter file, for example to obtain only the spatial dimension of the problem. By default all entries and subsections are expected to be declared.
The function sets the value of all parameters it encounters in the input file to the provided value. Parameters not explicitly listed in the input file are left at the value they previously held, which will be the default value provided to declare_entry() unless one has previously read a different input file.
Each parameter value is matched against the pattern for this parameter that was provided to declare_entry(), and for each parameter all associated actions that may previously have been set by add_action() are executed. If a parameter does not satisfy its pattern, or if an associated action throws an exception, then the value provided for the parameter is not set and the current object reverts to the subsection it was in before the current function was called. No further processing of the input stream occurs, that is everything that comes after the parameter whose value does not satisfy its pattern is ignored.
Reimplemented in MultipleParameterLoop.
Definition at line 399 of file parameter_handler.cc.
Parse input from a specified parameter file
filename independently of the type of input file (prm, xml, json) being used. The code path selected by this function is extracted from the ending of the filename, so the user has to make sure that the content of the input file is consistent with its name.
The parameter
last_line will only be used for parameter files of .prm type. See the other parse_input function for documentation.
The user can specify whether parameters in the input file not added to the parameter handler will be skipped by
skip_undefined (enables partial parsing), and whether the code will assert that all parameters of the parameter handler declared with flag
has_to_be_set=true are indeed found in the input file.
If the function is called with
skip_undefined=true, it is recommended to also set
assert_mandatory_entries_are_found=true. For example, this ensures that parameters with typos in the input file will not be skipped, while such mistakes would otherwise remain unrecognized.
Definition at line 532 of file parameter_handler.cc.
Parse input from a string to populate known parameter fields. The lines in the string must be separated by
\n characters.
The function in essence reads the entire file into a stream and then calls the other parse_input() function with that stream. See there for more information.
Definition at line 560 of file parameter_handler.cc.
Parse input from an XML stream to populate known parameter fields. This could be from a file originally written by the print_parameters() function using the XML output style and then modified by hand as necessary, or from a file written using this method and then modified by the graphical parameter GUI (see the general documentation of this class).
Definition at line 700 of file parameter_handler.cc.
Parse input from a JSON stream to populate known parameter fields. This could be from a file originally written by the print_parameters() function using the JSON output style and then modified by hand as necessary, or from a separate program that knows how to write JSON format for ParameterHandler input.
Definition at line 756 of file parameter_handler.cc.
Clear all contents.
Definition at line 775 of file parameter_handler.cc.
Declare a new entry with name
entry, default and for which any input has to match the
pattern (default: any pattern).
The function generates an exception of type ExcValueDoesNotMatchPattern if the default value doesn't match the given pattern, using the C++ throw mechanism. However, this exception is only generated after the entry has been created; if you have code where no sensible default value for a parameter is possible, you can then catch and ignore this exception.
The parameter
documentation defaulting to an empty string is used to add a documenting text to each entry which will be printed as a comment when this class is asked to write out all declarations to a stream using the print_parameters() function. 784 of file parameter_handler.cc.
Attach an action to the parameter with name
entry in the current section. The action needs to be a function-like object that takes the value of the parameter as a (string) argument. See the general documentation of this class for a longer description of actions, as well as examples.
The action is executed in three different circumstances:
name, at the end of the current function. This is useful because it allows for the action to execute whatever it needs to do at least once for each parameter, even those that are not actually specified in the input file (and thus remain at their default values).
It is valid to add multiple actions to the same parameter. They will in that case be executed in the same order in which they were added.
Definition at line 830 of file parameter_handler.cc.
Declare a new entry name
entry, set its default value to the content of the variable
parameter, and create an action that will fill
parameter with updated values when a file is parsed, or the entry is set to a new value.
By default, the pattern to use is obtained by calling the function Patterns::Tools::Convert<T>::to_pattern(), but a custom one can be used. 2322 of file parameter_handler.h.
Create an alias for an existing entry. This provides a way to refer to a parameter in the input file using an alternate name. The alias will be in the current section, and the referenced entry needs to be an existing entry in the current section.
The primary purpose of this function is to allow for a backward compatible way of changing names in input files of applications for which backward compatibility is important. This can be achieved by changing the name of the parameter in the call to declare_entry(), and then creating an alias that maps the old name to the new name. This way, old input files can continue to refer to parameters under the old name, and they will automatically be mapped to the new parameter name.
It is valid to set the same parameter multiple times in an input file. The value that will ultimately be chosen in such cases is simply the last value set. This rule also applies to aliases, where the final value of a parameter is the last value set either through the current name of the parameter or through any of its possible multiple aliases. For example, if you have an input file that looks like
where
parm1_alias is an alias declared via
then the final value for the parameter called
parm1 will be 2, not 1.
Definition at line 866 of file parameter_handler.cc.
Enter a subsection. If it does not yet exist, create it.
Definition at line 927 of file parameter_handler.cc.
Leave present subsection.
Definition at line 941 of file parameter_handler.cc.
Check whether a subsection or a subsection path exists in current tree. The input parameter
sub_path is assumed to be relative to the currently selected path.
Definition at line 954 of file parameter_handler.cc.
Return value of entry
entry_string. If the entry was changed, then the changed value is returned, otherwise the default value. If the value of an undeclared entry is required, an
Assert will fail.
Definition at line 975 of file parameter_handler.cc.
Return value of entry
entry_string. If the entry was changed, then the changed value is returned, otherwise the default value. If the value of an undeclared entry is required, an
Assert will fail. If
entry_subsection_path is non-empty, the value will be gotten from the subsection represented by that path instead of the current subsection. The first string in
entry_subsection_path must be the name of a subsection of the current section, and each next string must be the name of a subsection of the one before it.
Definition at line 992 of file parameter_handler.cc.
Return value of entry
entry_string as
long int. (A long int is chosen so that even very large unsigned values can be returned by this function).
Definition at line 1013 of file parameter_handler.cc.
Return value of entry
entry_string as
long int. (A long int is chosen so that even very large unsigned values can be returned by this function). If
entry_subsection_path is non-empty, the value will be gotten from the subsection represented by that path instead of the current subsection.
Definition at line 1032 of file parameter_handler.cc.
Return value of entry
entry_name as
double.
Definition at line 1056 of file parameter_handler.cc.
Return value of entry
entry_name as
double. If
entry_subsection_path is non-empty, the value will be gotten from the subsection represented by that path instead of the current subsection.
Definition at line 1076 of file parameter_handler.cc.
Return value of entry
entry_name as
bool. The entry may be "true" or "yes" for
true, "false" or "no" for
false respectively.
Definition at line 1101 of file parameter_handler.cc.
Return value of entry
entry_name as
bool. The entry may be "true" or "yes" for
true, "false" or "no" for
false respectively. If
entry_subsection_path is non-empty, the value will be gotten from the subsection represented by that path instead of the current subsection.
Definition at line 111 1140 of file parameter_handler.cc.
Same as above, but an overload where the second argument is a character pointer. This is necessary, since otherwise the call to
set("abc","def") will be mapped to the function taking one string and a bool as arguments, which is certainly not what is most often intended.
The function throws an exception of type ExcValueDoesNotMatchPattern if the new value does not conform to the pattern for this entry.
Definition at line 11915 of file parameter_handler.cc.
Change the value presently stored for
entry_name to the one given in the second argument.
The parameter must already exist in the present subsection.
For internal purposes, the new value needs to be converted to a string. This is done using 16 digits of accuracy, so the set value and the one you can get back out using get_double() may differ in the 16th digit.
The function throws an exception of type ExcValueDoesNotMatchPattern if the new value does not conform to the pattern for this entry.
Definition at line 120128 of file parameter_handler.cc.
Print all parameters with the given
style to
out.
Before printing, all current parameters and subsections are sorted alphabetically by default. This behavior can be disabled setting the optional parameter
style to
KeepDeclarationOrder: in this case entries are printed in the same order as they have been declared.
In
PRM,
XML, and
JSON format, the output is formatted in such a way that it is possible to use it for later input again. This is most useful to record the parameters for a specific run, since if you output the parameters using this function into a log file, you can always recover the results by simply copying the output to your input file.
Besides the name and value of each entry, the output also contains the default value of entries if it is different from the actual value, as well as the documenting string given to the declare_entry() function if available.
By using the flag
Short in combination with
PRM,
XML,
JSON, or
LaTeX (or by using the shortcuts
ShortPRM,
ShortXML,
ShortJSON, or
ShortLaTeX), a reduced output can be generated, only containing the values and skipping the documentation.
In
XML format, the output starts with one root element
ParameterHandler in order to get a valid XML document and all subsections under it.
In
LaTeX format, the output contains the same information but in a format so that the resulting file can be input into a latex document such as a manual for the code for which this object handles run-time parameters. The various sections of parameters are then represented by latex section and subsection commands as well as by nested enumerations.
You can reference specific parameter sections and individual parameters by the labels that are generated automatically for each entry. The labels have the format
parameters:section1/subsection1 and
parameters:section1/subsection1/someentry. Because special characters can appear in the section and entry names, these will be "mangled". Here, all characters except
[a-zA-Z0-9] are replaced by
_XX, where
XX is the two-digit ascii code of the character in hexadecimal encoding (so a space becomes
_20 for example).
While this function escapes special LaTeX-specific characters (backslash, underscore, etc.) in most of the output (names, default values, etc.), the documentation string is passed as-is. This means you can use math environments and other formatting in the description, but you need to escape quotes, backslashes, underscores, etc. yourself.
In addition, all parameter names are listed with
\index statements in two indices called
prmindex (where the name of each parameter is listed in the index) and
prmindexfull where parameter names are listed sorted by the section in which they exist. By default, the LaTeX program ignores these
\index commands, but they can be used to generate an index by using the following commands in the preamble of the latex file :
and at the end of the file this:
Definition at line 1238 of file parameter_handler.cc.
Print all parameters to the file given by
filename with the given output style
style.
This function deduces the output format from the extension of the specified filename. Supported extensions are
prm,
xml,
tex, and
json. Hence, it is not necessary to specify an output format via the
style argument as long as one of these extensions is added to the filename. If an output format is specified in the
style parameter nevertheless, the output format has to be consistent with the filename extension.
If no extension is specified or the extension is not supported, the output format is deduced from the
style argument.
If neither the extension is supported, nor does the
style parameter contain a format specification, an assertion is thrown.
Definition at line 1342 of file parameter_handler.cc.
Print parameters to a logstream. This function allows to print all parameters into a log-file. Sections will be indented in the usual log- file style..
Definition at line 1745 of file parameter_handler.cc.
Log parameters in the present subsection. The subsection is determined by the
subsection_path member variable. This variable is controlled by entering and leaving subsections through the enter_subsection() and leave_subsection() functions..
In most cases, you will not want to use this function directly, but have it called recursively by the previous function.
Definition at line 1756 of file parameter_handler.cc.
Determine an estimate for the memory consumption (in bytes) of this object.
Definition at line 1997 of file parameter_handler.cc.
Write the data of this object to a stream for the purpose of serialization.
Definition at line 2284 of file parameter_handler.h.
Read the data of this object from a stream for the purpose of serialization.
Definition at line 2303 of file parameter_handler.h.
Write and read the data of this object from a stream for the purpose of serialization.
Test for equality.
Definition at line 2006 of file parameter_handler.cc.
Return a set of parameter names (including subsection names) corresponding to those entries of the parameter handler that have not been set by one of the functions parsing parameters from an input file or by an explicit call to one of the set() functions, but that have been declared as mandatory parameters that must be set (through the last argument of the declare_entry() function or add_parameter() function).
Definition at line 2031 of file parameter_handler.cc.
Asserts that those entries of the parameter handler with flag
has_to_be_set = true have been set. An exception is invoked if at least one of these parameters has not been set.
Definition at line 2045 of file parameter_handler.cc.
Return the string that identifies the current path into the property tree. This is only a path, i.e. it is not terminated by the path_separator character.
This function simply calls collate_path_string() with
subsection_path as argument
Definition at line 358 of file parameter_handler.cc.
Given the name of an entry as argument, the function computes a full path into the parameter tree using the current subsection.
Definition at line 366 of file parameter_handler.cc.
This function computes a full path into the parameter tree given a path from the current subsection and the name of an entry.
Definition at line 380 of file parameter_handler.cc.
Scan one line of input.
input_filename and
current_line_n are the name of the input file and the number of the line presently scanned (these are used in exception messages to show where parse errors occurred). This function will raise an exception if the line contains an undeclared subsection or entry, if the line's entry does not match its given pattern, or if the line could not be understood as a valid parameter file expression.
The function modifies its argument, but also takes it by value, so the caller's variable is not changed.
If
skip_undefined is
true, the parser will skip undefined sections and entries. This is useful for partially parsing a parameter file, for example to obtain only the spatial dimension of the problem. By default all entries and subsections are expected to be declared.
Definition at line 1802 of file parameter_handler.cc.
Print out the parameters of the subsection given by the
target_subsection_path argument, as well as all subsections within it recursively. This function is called from the print_parameters() function, and is implemented for all
style arguments other than XML and JSON (where we can output the entire set of parameters via BOOST functions). The
indent_level argument indicates how many spaces the output should be indented, so that subsections properly nest inside the output of higher sections.
Definition at line 1367 of file parameter.
Definition at line 1844 of file parameter_handler.h.
The separator used when accessing elements of a path into the parameter tree.
Definition at line 1733 of file parameter_handler.h.
Path of presently selected subsections; empty list means top level
Definition at line 1738 of file parameter_handler.h.
The complete tree of sections and entries. See the general documentation of this class for a description how data is stored in this variable.
The variable is a pointer so that we can use an incomplete type, rather than having to include all of the property_tree stuff from boost. This works around a problem with gcc 4.5.
Definition at line 1748 of file parameter_handler.h.
A map that stores a pair of boolean variables for each entry added to the parameter handler. The first bool describes whether the parameter has to be set according to the last argument of the functions declare_entry() or add_parameter(), and the second bool contains the information whether the parameter has been set by any of the functions parsing input parameters or by a set function of this class.
Definition at line 1758 of file parameter_handler.h.
A list of patterns that are used to describe the parameters of this object. Every nodes in the property tree corresponding to a parameter stores an index into this array.
Definition at line 1765 of file parameter_handler.h.
A list of actions that are associated with parameters. These are added by the add_action() function. Nodes in the property tree corresponding to individual parameters store indices into this array in order to reference specific actions.
Definition at line 1773 of file parameter_handler.h. | https://dealii.org/developer/doxygen/deal.II/classParameterHandler.html | CC-MAIN-2020-45 | refinedweb | 5,832 | 53 |
Earlier this year I was introduced by someone I work with to AutoMapper. At a very convenient time it turned out since I was in the middle of a couple of projects that I had to do a lot of run-of-the-mill gluing together of request between web services where there were very similar object models in play but which came from different services - so I was looking at writing a load of code that basically took a request from one side and re-formed it into a very similar request to push elsewhere. Not particularly fun, and I find one of the places I'm most like to make stupid mistakes are when I'm not 100% mentally switched on because the task at hand makes me feel like I'm being a robot!
So, for one of these projects I was getting stuck into; AutoMapper to the rescue!
AutoMapper is an "object-to-object" mapper which, well.. maps from one object to another! :) If the source and destination objects have identical structure but different namespaces then most times AutoMapper will be able to translate from one to another as-if-by-magic, and there are several conventions that are applied by the default mapper that perform simple object flattening and other tricks.
There's loads of introductory tutorials out there for AutoMapper so this is just a dead simple example to get across the gist - I can use one call to a CreateMap method and use a nice fluent coding style to tweak it how I want, then conversion between lists or arrays or enumerables of mappable types are automatically handled:
var data = new Employee() { Name = new Employee.EmployeeName() { Title = "Mr", First = "Andrew", Last = "Test", }, DateOfBirth = new DateTime(1990, 6, 14) }; Mapper.CreateMap<Employee, Person>() .ForMember(d => d.Name, o => o.MapFrom(s => s.Name.Title + " " + s.Name.First + " " + s.Name.Last)); var dataList = new Employee[] { data }; var translated = Mapper.Map<Employee[], List<Person>>(dataList); public class Employee { public EmployeeName Name { get; set; } public DateTime DateOfBirth { get; set; } public class EmployeeName { public string Title { get; set; } public string First { get; set; } public string Last { get; set; } } } public class Person { public string Name { get; set; } public DateTime DateOfBirth { get; set; } }
This doesn't even scratch the surface; it can handle nested types and complex object models, you can define custom naming conventions for property mappings, specify properties to ignore or map other than to the conventions, map onto existing instances rather than creating new, create distinct configuration instances, .. loads and loads of stuff.
An example of its use out-in-the-field is in the MVC Nerd Dinner demo project and Jimmy Bogard (who wrote AutoMapper) mentions how he uses it in his article "How we do MVC" -.
.. which sounds like a very sensible application for it to me! (The rest of that article's definitely worth a read, btw).
There was one gotcha using it that caught me out, but it made perfect sense when I reasoned it through afterward.
I was mapping from one large, most-flat object into another where the first was a subset of the second; it was an old legacy webservice where the interface accepted every property for several types of bookings, where maybe 60% of the properties were shared between types and then the rest were specific to different booking types. So a booking made through the web interface resulted in an HotelBooking being instantiated, for example, and this was mapped onto the "super" booking object of the legacy service interface.
var source = new Hotel( Guid.NewGuid(), // .. other properties "Test" // .. other properties ); Mapper.CreateMap<Hotel, Booking>(); var dest = Mapper.Map<Hotel, Booking>(source); public class Hotel { public Hotel(Guid id, /* .. other properties .. */ string network) { if ((network ?? "").Trim() == "") throw new ArgumentException("Null/empty network specified"); // .. other validation .. Id = id; //.. other properties.. Network = network; //.. other properties.. } public Guid Id { get; private set; } // .. other properties .. /// <summary> /// This will never be null /// </summary> public string Network { get; private set; } // .. other properties .. } public class Booking { public Guid Id { get; set; } // .. other properties public string NetworkType { get; set; } // .. other properties }
On the translated "dest" instance, the NetworkType property is "System.String" - er, what??
Well it turns out that AutoMapper finds that there is no NetworkType property to map from Hotel to Booking but sees that there is a "Network" value. It then tries to see if it can perform some object flattening by checking whether the Network value has a Type property which, being a string, it doesn't. But it then consider a property retrieval method rather than a standard property getter so it looks for a GetType() method which, since string inherits from objects, it does! So it takes the .Network.GetType() value and assumes we want this for the Booking.NetworkType value!
Like I said, it all makes perfect sense but it took me a little while to work out what was happening in this case :)
Did I mention AutoMapper is open source? This is great cos it let me have a poke around the source code and get a feel for what magic seemed to be going on!
My biggest problem is with scenarios where I want to do the opposite of the above - instead of translating from an "always-valid" internal object to a webservice class I'd like to be able to instantiate a class through its constructor, using data from a source class.
Now, AutoMapper does have some sort of support for using constructors for mapping - eg.
Mapper.CreateMap<Booking, Hotel>() .ConstructUsing(src => new Hotel(src.Id, /* .. other properties .. */));
But here I've got to manually map all of the properties from the source to arguments in destination's constructor! What I really want is all of that clever name convention malarkey done in AutoMapper to be applied to constructor arguments of destination types. I mean, argument names are always present in compiled C# code so it's not like that data is unavailable for examination by AutoMapper. And having conversions like this would save me having to write a lot of boring code at webservice boundaries!
Now, since I seem to think it's so easy - How Hard Can It Be? :) - I'm going to have a bit of a play around and see if I can slap something together to do this. If I don't end up reduced to tears (and maybe even if I do!) I'll see what I can do about posting the results!
Posted at 21:38. | http://www.productiverage.com/Archive/3/2011 | CC-MAIN-2017-13 | refinedweb | 1,085 | 59.64 |
Using the Java proxy for a web service requires different steps depending on whether you use it from within WebLogic Server (as in a JSP or servlet) or from outside WebLogic Server (as in a standalone Java application).
Note:You can also call a web service from a page flow via a Web Service control. This approach is simpler than using the proxy.
Note: You should not use a Web Service control to invoke a web service that resides in the same application. Invoking a web service via a Web Service control means marshalling the method parameters into a SOAP message on the calling end and unmarshalling the SOAP message on the receiving end, then again for the method return value. This is very inefficient when the invocation is local. You would usually be tempted to invoke a local web service if the called web service includes business logic you want to access.
In general, you should place business logic in custom Java controls instead of in web services. This allows you to access the business logic from various contexts in the application (web services, other controls, page flows) without incurring the cost of data marshalling and unmarshalling. Web Service controls should only be used to invoke web services that are truly external to your application.
To Use the Java Proxy from a JSP
If you want to use the web service proxy JAR from more than one project in your application, you can add it to the Libraries folder at the root of your application. Saving the JAR directly to the APP-INF/lib directory at the root of your application will automatically add the JAR file to the Libraries folder.
<%@ page import="weblogic.jws.proxies.*" %>
<% HelloWorld_Impl proxy = new HelloWorld_Impl(); %>
<% HelloWorldSoap soapProxy = proxy.getHelloWorldSoap(); %>
<%= soapProxy.Hello() %>
Note that you will need to download a new copy of the proxy if you change any of the signatures of the web service methods or callbacks.
For an example that demonstrates use of a web service Java proxy from a JSP page, see Java Client Samples.
To Use the Java Proxy from a Java Project in WebLogic Workshop
To Use the Java Proxy in a Separate Java Application
import weblogic.jws.proxies.*; public class Main { public static void main(String[] args) { try { HelloWorld_Impl proxy = new HelloWorld_Impl(); HelloWorldSoap soapProxy = proxy.getHelloWorldSoap(); System.out.println(soapProxy.Hello()); } catch (Exception e) { e.printStackTrace(); } } }
For examples that demonstrates use of a web service Java proxy from Java clients, see Java Client Samples.
WebLogic Workshop uses WebLogic Server's clientgen tool to generate the Java proxy for a web service, based on the web service's WSDL file. You may use the clientgen tool directly if you wish to customize the generated Java proxy. To learn more about clientgen, see the documentation for clientgen on.
The clientgen tool accepts several command line parameters. The only parameter set by WebLogic Workshop when generating a Java proxy from Test View is the packageName parameter, which is always set to weblogic.jws.proxies.
None. | http://docs.oracle.com/cd/E13226_01/workshop/docs81/doc/en/workshop/guide/howdoi/howUseTheJavaProxyForAWebService.html | CC-MAIN-2014-52 | refinedweb | 504 | 51.07 |
Approaches for implementing Autocomplete Feature
Reading time: 40 minutes
With the dawn of modern browsers and search engines, Autocomplete has been an interesting UX Feature that derives heavily from the existing concepts of the Data Structure and Algorithm to implement a simple thing: Suggesting the user a list of search phrases as he starts typing in the query box. With the huge volumes of data being processed around the world in real-time, Search Queries were required to be accurate and fast which lead to the use of more efficient algorithms that can be used to retrieve and rank search phrases depending on the given input. The Autocomplete Feature are also expected to possess some Typo-Tolerance as it can implement a spell check in case the given query has been mispelled
In this article, we will discuss the various approaches to implement an Autocomplete Feature using various algorithms, from the most naive ones to the others which are complex yet intriguing to implement at the same time. These approaches will help the reader to better understand the working of the Autocomplete Feature under the covers as we gently unveil the complexities of these algorithms within the layers.
The various approaches are:
- Linear Search (Brute Force)
- Binary Search Approach
- TRIE Data Structure
- Ternary Search Tree Approach
- Fuzzy Search
- Burkhard Keller Tree Approach
- Machine Learning Approach
We will now explore each technique in depth.
1. Linear Search (Brute Force)
Probably the most naive method to implement our Autocomplete Feature is the Linear Force where we can Brute Force through the entire list of search phrases looking for the best fit which can be returned back to the user as a Search Query is passed to it. In Linear Search Algorithm, the entire list of search phrases is searched for to check if any search phrase associated with the given query is present or not.
Time Complexity for this algorithm is O(N) where N is the number of search phrases in the corpus while Space Complexity is taken to be O(1). While this algorithm is good for providing search suggestions for a small number of elements, it is inefficient to implement where we have a large corpus of search phrases.
To improve the Time Complexity we can implement the concept of Levenshtein distance which can be understood as the value that is returned after two strings are passed and the minimum number of insertion, deletion and replacements are returned which are required to translate one string into the other. Levenshtein distance is also used in the Burkhard-Keller Trees for returning near-matches to a String query where the Time Complexity associated with the operation is O(NP²) where P is the length of the search query.
The associated Code in Python is as follows:
class LinearSearch(object): def __init__(self): self.data = [] def index(self, suggestions: Sequence[str]) -> None: for i in suggestions: self.data.append(i) def search(self, pre: str) -> Generator[str, None, None]: for i in self.data: if i.startswith(pre): yield i
2. Binary Search Approach
Binary Search is yet another efficient approach to implement the Autocomplete Feature using the "Divide and Conquer paradigm. Binary Search algorithm is regarded as one of the most popular algorithm in which the list, wherein the element is to be searched, is to be divided into two and the query element is compared to the middle element. To ensure that the element is efficiently searched, the list of search queries is sorted before it is processed. A Binary Search Algorithm can be implemented either using Iteration or using Recurssion with a time complexity of O(log N) where N is the number of search phrases.
Binary Search Approach is suitable for moderate number of Search Phrases but as the complexity of the Search Phrases increase, it gets inefficient with lack of Typo-Tolerance. In next section we will discuss the TRIE Data Structure which is much more efficient for implementing the Autocomplete Feature in a more efficient and lesser complex way.
The associated Code in Python is as follows:
from bisect import bisect_left class BinarySearch(object): def __init__(self): self.array = [] def index(self, suggestions: Sequence[str]) -> None: for i in suggestions: self.array.append(i) self.array.sort() def search(self, pre: str) -> Generator[str, None, None]: start_position = bisect_left(self.array, pre) for i in self.array[start_position:]: if i.startswith(pre): yield i else: break
3. TRIE Data Structure
TRIE Data Structure also known as the Prefix Tree or Radix Tree is remarked as an excellent Data Structure for processing and storing the Strings and is primarily used for word retrieval. The nodes in the TRIE Data Structure are used for storing the associate keys of strings and values that are being stored in the TRIE.
What makes a TRIE Data Structure so optimized for performing such actions? Unlike the popular Binary Trees, each node in TRIE can contain a maximum of 26 nodes which are pointers to the 26 different alphabets of English Language. The position of each node in a TRIE defines the key with which the node is associated. This makes the TRIE indexing suitable for maintaining the variable sized key values. The actual key values is never stored but the key values are implied through links. A TRIE of Order 26 can maintain a whole English dictionary.
As we insert keys in the TRIE Data Structure, each input key is inserted as an individual node and perform the role of an index to further child nodes. If our input is a prefix of an existing string present in the TRIE, then we can mark the new node as a leaf node to the pre-defined key. Otherwise, the new keys are constructed and the last node is marked as the Leaf Node. Search Operation is relatively easy in TRIE as a Search Operation starts from the Root Node and moves ahead by comparing characters. If any character does not exist, then no such string is found in the TRIE Data Structure.
In a TRIE Data Structure, the best Case Time Complexity has been described as O(1) while the Average and Worst Case is described as O(Length-Of-Key). The TRIE Data Structure can be optimized to support larger collection of words using Compact TRIE Data Structure Implementations.
The associated Code in Python is as follows:
class trieNode: def __init__(self): self.next = {} self.leaf = False def add_item(self, item): i = 0 while i < len(item): k = item[i] if not k in self.next: node = trieNode() self.next[k] = node self = self.next[k] if i == len(item) - 1: self.leaf = True else: self.leaf = False i += 1 def search(self, item): if self.leaf and len(item) == 0: return True first = item[:1] str = item[1:] if first in self.next: return self.next[first].search(str) else: return False def traversal(self, item): if self.leaf: print (item) for i in self.next: s = item + i self.next[i].traversal(s) def autocomplete(self, item): i = 0 s = '' while i < len(item): k = item[i] s += k if k in self.next: self = self.next[k] else: return 'NOT FOUND' i += 1 self.traversal(s) return 'END'
4. Ternary Search Tree Approach
Ternary Search Tree is an optimized TRIE Data Structure where the nodes can have a maximum 3 Child Nodes, unlike the TRIE where 26 nodes are optimally associated with a node. Each node in the Ternary Search Tree has three pointers: Left, Middle and Right along with an EndOfWord Bit and a Data Field where the character associated with the string is stored. The Left Pointer is used to point to the node whose value is comparatively lesser than the value in the current node while the Right Pointer is used to point to the point to the node whose value is comparatively greater than the value in the current node. The equal pointers points to the node whose value is equal to the current node value.
Ternary Search Tree is regarded as quite efficient compared to the earlier TRIE Data Structure and can perform insertion, deletion and search operation with the same efficiency as a Binary Search Tree. The Space Complexity associated with a Ternary Search Tree is equal to the length of the string that has been stored into it.
Insertion Operation is relatively easy in Ternary Search Tree and is similar to the one in Binary Search Tree. A character comparison is performed at each stage and the node character is compared to the character to be inserted which gives us three cases:
- If the Character to be inserted is smaller than node value, then move left.
- If the Character to be inserted is larger than node value, then move right.
- If the Character to be inserted is equal to the node value, then move to middle position.
The Search Operation in the Ternary Search Tree is also performed similar to the operation in Binary Search Tree. The next character in the query string is matched to the character present in the current node. The center child is looked upon recursively as the first letter from each string is removed.
The Worst Case Complexity for performing an Autocomplete Operation with Ternary Search Tree is O(N) while the average Time complexity is O(log N).
The associated Code in Python is as follows:
class Node(): def __init__(self, value=None, endOfWord=False): self.value = value self.left = None self.right = None self.equal = None self.endOfWord = endOfWord class Autocomplete(): def __init__(self, word_list): self.n = Node() for word in word_list: self.insert(word, self.n) def insert(self, word, node): char = word[0] if not node.value: node.value = char if char < node.value: if not node.left: node.left = Node() self.insert(word, node.left) elif char > node.value: if not node.right: node.right = Node() self.insert(word, node.right) else: if len(word) == 1: node.endOfWord = True return if not node.equal: node.equal = Node() self.insert(word[1:], node.equal) def all_suffixes(self, pattern, node): if node.endOfWord: yield "{0}{1}".format(pattern, node.value) if node.left: for word in self.all_suffixes(pattern, node.left): yield word if node.right: for word in self.all_suffixes(pattern, node.right): yield word if node.equal: for word in self.all_suffixes(pattern + node.value, node.equal): yield word def find(self, pattern): final_pattern = {pat: set([]) for pat in pattern} for pat in final_pattern.keys(): word = self.find_(pat) if word == None: return None else: completions = {x for x in word} return list(completions) def find_(self, pattern): node = self.n for char in pattern: while True: if char > node.value: node = node.right elif char < node.value: node = node.left else: node = node.equal break if not node: return None return self.all_suffixes(pattern, node)
5. Fuzzy Search
Autocomplete Feature can be implement using Fuzzy Search which is used to find the approximate matches for the search query and is used as a spell checker and in autocomplete operations by working on algorithms like Levenshtein distance, Damerau-Levenshtein distance, Bitap algorithm, Smith-Waterman algorithm to name a few. Fuzzy Search is currently implemented on various popular Search Engines like Google, Bing, Yahoo and Duck Duck Go.
Fuzzy Search is implemented using N-Gram Sequencing Technique where n-characters are sequenced in a larger string. Let us take a string "mobile" for which the 2-grams will be: ["mo","ob","bi","il","le"]. These n-grams will be indexed and is used for autocompletion and suggestion as these n-grams are compared with the prefixes.
N-grams index is used to identify the list of suitable search phrases and finally return the most appropriate ones that are found by performing filtering on the search phrases. N-grams technique is also used in N-gram tokenizer used in Elastic Search, wherein it breaks every search phrase into numerous N-grams tokens known as "shingles" and allows the autocomplete operation to suggest new phrases.
The associated Code in Python is as follows:
class NGramSuggester(object): def __init__(self, ngram_size=2): self.data = {} self.ngram_size = ngram_size def index(self, suggestions: Sequence[str]) -> None: for s in suggestions: grams = ngrams(s, self.ngram_size) for ngram in grams: if ngram not in self.data: self.data[ngram] = [s] else: self.data[ngram].append(s) def search(self, prefix: str, match_percentage: float=0.9): suggestions = {} grams = list(ngrams(prefix, self.ngram_size)) total_grams = len(grams) for ngram in grams: for s in self.data.get(ngram, []): if s in suggestions: suggestions[s] += 1 else: suggestions[s] = 1 for s, gram_count in suggestions.items(): percentage = gram_count * 1.0 / total_grams if percentage > match_percentage: yield s
6. Burkhard Keller Tree Approach.
Unlike other algorithms, BK-Tree rests its concepts on the Levenshtein distance which can be understood as the value that is returned after two strings are passed and the minimum number of insertion, deletion and replacements are returned which are required to translate one string into the other. Burkhard Keller Tree are also utilized in implementing the Auto-Complete Feature in many Software and Web Applications and is regarded as more efficient compared to the TRIE and Ternary Search Tree that we have discussed earlier.
BK-Tree is a Tree-Based Data Structure and like any other Tree Data Structure it consists of nodes and edges that connect them. In a BK-Tree, each node consist of the individual words in the dictionary and the number of nodes in a BK-Tree is equal to the number of the words that are being inserted into the dictionary. Each edge that connects the nodes possess an integer value that is corresponsing to the Levenshtein distance.
To construct a BK-Tree we can take any node as the root node and then we have to add some element to the root node, by calculating their Levenshtein Distance and adding them as a left node or the right node, in the same manner as will add nodes in any other Binary Tree.
In the Search Operation, our primary aim is to find all the words that are closest given to a query word. This means that we will take an integer 'N' which we will call as the radius. To find any node in the BK-Tree we will just compute the Levenshtein Distance from the query string to the string stored in the root node. If the value that is returned is less than the radius, then the rest of the nodes are recursively processed by selecting all the children of the root node.
The associated Code in Python is as follows:
from collections import deque class BKTree: def __init__(self, distance_func): self._tree = None self._distance_func = distance_func def add(self, node): if self._tree is None: self._tree = (node, {}) return current, children = self._tree while True: dist = self._distance_func(node, current) target = children.get(dist) if target is None: children[dist] = (node, {}) break current, children = target def search(self, node, radius): if self._tree is None: return [] candidates = deque([self._tree]) result = [] while candidates: candidate, children = candidates.popleft() dist = self._distance_func(node, candidate) if dist <= radius: result.append((dist, candidate)) low, high = dist - radius, dist + radius candidates.extend(c for d, c in children.items() if low <= d <= high) return result
7. Machine Learning Approach
With the rise in use-cases of Machine Learning and Deep Learning in industry, Autocomplete Operation can be automated and made faster thanks to access to more powerful algorithms and more computational power. For this purpose we can use Long Short-Term Memory (LSTM) algorithm which can perform beam predictions to suggest autocomplete operations with much more efficiency than standard N-Grams Search or any other algorithm. However most of the Machine Learning and Deep Learning algorithm depends on the type of data passed to it and hence developing any autocomplete software on Machine Learning Concepts require heavily cleansed code which can be made possible by removing comments, strings and blank lines and the model can be trained on tokenized code which is more efficient than character level prediction with byte-pair encoding.
With this, you have the complete knowledge of different approaches that can be taken for Text Autocompletion in general. Enjoy. | https://iq.opengenus.org/autocomplete-techniques/ | CC-MAIN-2020-24 | refinedweb | 2,716 | 55.24 |
VueJS as a Frontend for Rails
Stay connected parts of your frontend code.
Getting Started
Some brief setup instructions.
gem install rails --version "5.2.0.rc1" rails _5.2.0.rc1_ new vue_example --webpack=vue cd vue_example
From this point, you can start work on VueJS without CoffeeScript support (we'll add that later). Rails includes an example of both frontend VueJS integration and what's called a component. These files are available at
app/javascript/packs/hello_vue.js and the component at
app/javascript/hello.vue. If you would like to challenge yourself to learn the process of integrating these, this is a good place to start.
The Rails Vue Example
You may follow the instructions in this section if you wish to try Rails' small challenge. Comment out the existing code in
hello_vue.js and uncomment the code in the last section:
import TurbolinksAdapter from 'vue-turbolinks'; import Vue from 'vue/dist/vue.esm' import App from '../app.vue' Vue.use(TurbolinksAdapter) document.addEventListener('turbolinks:load', () => { const app = new Vue({ el: '#hello', data: { message: "Can you say hello?" }, components: { App } }) })
Create a route and controller to work with and add the root route to the config to point to it.
rails g controller LandingPage index
And add to the
config/routes.rb file:
root to: "landing_page#index"
You can test that this works by running
rails s and having your web browser load. From ther, the challenge is up to you to learn what HTML- and JavaScript-related code to put in the site template and landing page to get both VueJS examples to work. That's there for you to do, now let's go and do our own form implementation in VueJS.
Vue JS Rails Form Example
For this example, we're going to create a form for a writer to keep track of their own documents -- it will contain a subject, body of text, and the state of revision.
First, let's generate the scaffolding for the document resource.
rails g scaffold Document subject:string:index body:text state:integer:index
Then edit the migration file under
db/migrate and change the line for state to provide a default value.
t.integer :state, default: 0, null: false
Now we can run
rails db:migrate to update or database. Next we need to update our model for the different states the document may be in. Open up
app/models/document.rb and add the following:
class Document < ApplicationRecord enum state: [:concept, :alpha, :beta, :draft, :publish] end
At this point, we're ready to start seeing the changes we'll be making, so first we'll create a CoffeeScript file and then start a Rails server so we can refresh our browser to work with the results. In a new terminal window, run the following from your project directory:
touch app/javascript/packs/documents.coffee rails s
Now with a browser window open, navigate to. Here you can use the Rails CRUD for your document resource. We'll be replacing the form to be VueJS-specific.
To start, we'll need to first add the ability to insert our JavaScript pack into our site's header. So open your application template
app/views/layouts/application.html.erb and add the following between the
<head> and
</head> tags.
<% if content_for? :head %> <%= yield :head %> <% end %>
Now we have a hook we can use on any page if we use
content_for(:head) and give it a code block, which will be written to the head section of our specific pages.
Open up
app/views/documents/_form.html.erb and erase all the contents of the file. This form is used for new entries and updating existing entries in Rails for our documents. First, let's put in the header code block to load what will be our VueJS code.
<% content_for :head do -%> <%= javascript_pack_tag 'documents' %> <% end -%>
At this point, trying to load
localhost:3000/documents in our browser won't work; we need it to recognize our
.coffee file extension. You can stop the server running in the terminal with CTRL-C and run the following.
bundle exec rails webpacker:install:coffee
Caution: Be sure to do your new feature installations in small steps all while verifying they work before adding more features. Otherwise this, plus a bunch of
yarn addcommands before testing, can lead to this feature not working at all.
Now you can run
rails s again and bring your browser back to
localhost:3000/documents and see that the page loads without any errors. We can continue on to the form now. Let's update the same file we were just working on to the following.
<% content_for :head do -%> <%= javascript_pack_tag 'documents' %> <% end -%> <%= content_tag :div, id: "document-form", data: { document: document.to_json(except: [:created_at, :updated_at]) } do %> <label>Subject</label> <input type="text" v- <label>State</label> <select v- <%= options_for_select(Document.states.keys, "concept") %> </select> <label>Body</label> <textarea v-</textarea> <br /> <button v-on:Submit</button> <% end %>
Before writing the CoffeeScript implementation for our VueJS code, let's briefly go over what we have in the file above. The first block of code we've already discussed will load our CoffeeScript asset code in the header through our application template. The
content_tag will create a div that stores our current pages' document object as JSON. The document that's created or loaded in the controller gets converted there, and this is what the VueJS code will use.
The
v-model items are all VueJS-specific names our code will keep track of. For the select
field, I've found that the Rails
options_for_select is much easier to work with than VueJS'
v-for technique, as it's problematic trying to get it to select a
selected option. And yes, I've tried the half dozen variations of how-tos available on the web for it all to no avail. There is a multi-select add-on you could install with Yarn, but that's a bit excessive for our simple use case.
The
v-on:click will call the
Submit function in our Vue object (once we define it) to perform the actions defined there.
Before continuing on, I'd like to share how the basic VueJS
option implementation would work if we used that here instead.
<select v- <option v-for="state in <%= Document.states.keys.to_json %>" :value=state > {{ state }} </option> </select>
You should recognize the ERB template
<%= %>, which will have Ruby get our states of the document and prepare it as JSON. The
v-for is part of Vue's own DSL, which treats the content like normal for loop code. For every document state, this will duplicate the HTML
<option> tags and put the replacement word for the state variable on both the value parameter and in the
{{ }} place.
One last thing I'd like to point out that VueJS has is from their core documentation:
<my-component</my>
We haven't covered components yet, but what I'd like to point out in this example is that the use of
v-bind here will execute what's in the quotation marks as regular JavaScript. So each of these values gets assigned from the JS scope.
Now onto the CoffeeScript VueJS code for our form.
The Code
Now we need to install some Yarn dependencies for having Vue work with Turbolinks in Rails and for more convenient PUT/POST commands.
yarn add vue-resource vue-turbolinks
Now our VueJS code can be written in
app/javascript/packs/documents.coffee. You get extra credit if you've already realized that by using the word 'document' we've used a conflicting JavaScript keyword. Because this is the case, we'll use the variable
ourDocument in the script to keep things clear and working.
import Vue from 'vue/dist/vue.esm' import TurbolinksAdapter from 'vue-turbolinks' import VueResource from 'vue-resource' Vue.use(VueResource) Vue.use(TurbolinksAdapter) document.addEventListener('turbolinks:load', () -> Vue.http.headers.common['X-CSRF-Token'] = document .querySelector('meta[name="csrf-token"]') .getAttribute('content') element = document.getElementById 'document-form' if element != null ourDocument = JSON.parse(element.dataset.document) app = new Vue( el: element data: -> { document: ourDocument } methods: Submit: -> ) )
The event
turbolinks:load is the trigger to run this code whenever a page loads in Rails. This code needs to be executed within the
<head> section of web pages, or you'll get side effects of it not loading without a refresh.
The next line gets the CSRF token, which is needed to verify any data submitted to the server. It takes it from what Rails hands us and assigns it to a response header.
Next we have an assignment of an element with an id of
document-form. This is an id we've placed in our
content_tag earlier. The rest of this script is based off of this existing since we do a check
if element != null.
The
ourDocument variable is assigned the data we placed in the page as JSON in the
content_tag :div for the data section. It parses the JSON data, and we continue.
Next we create a Vue object instance in JavaScript(CoffeeScript) with its first parameter being the
element, which is the document form.
Under
methods, we have our
Submit function, which is triggered via the submit button on the page. The
if conditional that follows that is a check to see if it's a new object and we should use the Rails “new record” path, or if it's an existing object and we'll use PUT to update it.
The
@http,
put, and
then are all benefits from the
vue-resource Yarn package we installed earlier. It actually reads out pretty well as is. Just by looking at it, you can see it posts some data to a server URL and then gives us a response. The
response in parenthesis is a function parameter, and we have two paths for it. The first is the good server response path, and the other is an error situation.
This is surprisingly straight-forward once you know the parts. And with that, we have a VueJS form for our Rails site that works well and loads quickly.
About Components
One of the main attractions about VueJS is its components. What it provides is one location for each component you want to create to have the HTML, JavaScript, and CSS styles all in their own
vue file. These components boast that the styles won't collide with styles elsewhere on your site. They are well-contained and organized singular functional units of code that may be used most anywhere and can be potentially extended or included within other components. Think of components as the ultimate building block.
If you've done the challenge shown at the beginning of this post, or noticed the component example we breezed by, you most likely have discovered that components get their own XML/HTML tag. The example above is called
<my-component> and is valid for HTML documents. Doing the Rails provided example will show you just how easy it is to drop a component in place.
Summary
The possibilities with VueJS are pretty high as there are many add-on systems you can integrate with designed to make it work more like a full framework. So you can do as little or as much as you want with it -- you're given the liberty to choose however you like.
VueJS has excellent tools to work with for diagnosing both state and issue that may arise. You can get a browser plugin for Chrome or Firefox and even try out their Electron app. Check them out at vue-devtools. Enjoy!
Stay up to date
We'll never share your email address and you can opt out at any time, we promise. | https://www.cloudbees.com/blog/vuejs-as-a-frontend-for-rails | CC-MAIN-2022-40 | refinedweb | 1,966 | 62.98 |
Sub::Clean - Clean subroutines with an attribute
version 0.01
use Sub::Clean; sub whatever :Cleaned { return "This cannot be called as a method"; }
This module 'cleans' subroutines you mark with the
Cleaned attribute, preventing them being called from places they haven't been already been bound by the perl compiler.
The main advantage in this is that you can declare subroutines and use them in your code as functions, but prevent them from being called as a method. This is particularly useful if your superclass (maybe unbeknownst to you) has a method of the same name as the function which would normally be 'shadowed' by your method.
For example, this:
package Banner; sub text { "example text\n" } sub bar { "-"x20 . "\n" } sub message { my $class = shift; return $class->bar . $class->text . $class->bar } package PubBanner; use base qw(Banner); use Sub::Clean; sub text { bar() . "\n" } sub bar :Cleaned { return (("Cheers","Quark's","Moe's")[rand(3)]) } package main; print PubBanner->message();
Print out the right thing:
-------------------- Moe's --------------------
Rather than just printing three horizontal lines.
Please note that this module enables the
Cleaned attribute only in lexical scope of the
use Sub::Clean statement. This prevents namespace pollution.
Written by Mark Fowler <mark@twoshortplanks.com>
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
No bugs have been reported.
Please report any bugs or feature requests through the web interface at
The latest version of this module is available from the Comprehensive Perl Archive Network (CPAN). isit to find a CPAN site near you, or see
The development version lives at. Instead of sending patches, please fork this project using the standard git and github infrastructure.
namespace::clean allows you to clean your namespace by dividing your code up into sections that should be cleaned or not cleaned.
namespace::autoclean automatically can clean imported subroutines from other namespaces.
Lexical::Sub allows you to declare subroutines that only exist in lexical scope.
Attribute::Lexical was used to create lexical attributes. | http://search.cpan.org/dist/Sub-Clean/lib/Sub/Clean.pm | CC-MAIN-2014-23 | refinedweb | 342 | 63.9 |
Iḿ trying to install plotly & set up streaming, but i can seem to get past step 1 (installing plotly).
Every reference to plotly i try in python gives the same response:
import plotly
Traceback (most recent call last):
File “”, line 1, in
File “plotly.py”, line 1, in
import plotly.plotly as py # plotly library
ImportError: No module named plotly
plotly.version
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘plotly’ is not defined
I´ve read through this forum & updated pip & python, as well as put the correct username & API key in the credentials file, all to no avail.
Anyone got any ideas for a beginner? | https://community.plotly.com/t/installing-plotly/2841 | CC-MAIN-2020-40 | refinedweb | 110 | 70.43 |
Agenda
See also: IRC log, previous 2009-05-14
Ralph: I have an
addition to the agenda
... May not need a lot of discussion in today's telecon
<scribe> ACTION: Ben to put up information on "how to write RDFa" with screencast possibly and instructions on bookmarklet. [recorded in] [CONTINUES]
<scribe> ACTION: Manu to write summary for Semantic Web Use Cases for Ivan. [recorded in] [CONTINUES]
<scribe> ACTION: Mark create base wizard suitable for cloning [recorded in] [CONTINUES]
<scribe> ACTION: Mark to send Ben ubiquity related wizard stuff [recorded in] [CONTINUES]
Ben: It would be very useful to have ways to drop in RDFa on their pages.
<scribe> ACTION: Mark to send Ben ubiquity related wizard stuff [recorded in] [CONTINUES]
<scribe> ACTION: Mark write foaf examples for wiki [recorded in] [CONTINUES]
<scribe> ACTION: Michael to create 'RDFa for uF users' on RDFa Wiki [recorded in] [CONTINUES]
<scribe> ACTION: Ralph or Steven fix the .htaccess for the XHTML namespace [recorded in] [CONTINUES]
<Ralph> discussion
<scribe> ACTION: Ralph think about RSS+RDFa [recorded in] [CONTINUES]
<markbirbeck>
<Steven>
Mark: some of these tutorials look more like recipes to me
Manu: yes, I agree
Mark: I do think recipes are a great resource; lots of snippets for people to grab
Manu: could move snippets to a recipes section and link to Mark's blog
... might be nice for the RDFa wiki to have [copies of] everything
Mark: we could create some stub pages ala Wikipedia too, to enlist community help
Ralph: I'm not yet prepared to admit defeat on my RSS+RDFa ACTION :)
Ralph: I said
I'd talk with Ivan about an XG or IG.
... My sense of the discussion is that Ivan concurs that an XG is ok but he prefers an IG.
... A difference between an IG and XG for what they can publish is that an XG does not publish Working Drafts, whereas an IG can.
... There is no prohibition from an XG publishing something - it can publish an XG report.
... It's usually in the form of a straw-man proposal.
... There's no precedent for publishing multiple working drafts of an XG report that I can think of, but nothing should stop that from happening.
... IG takes a formal proposal to AC.
Steven: I'm
worried that people will get the wrong idea, XG is meant to incubate
and be a starter.
... an IG is meant to continue work... it's more process to get started and it seems to fit better with what we're doing.
... I don't see the AC not agreeing to IG.
Ben: Yes, seems like IG would be a good way to go.
Ralph: To
specifically carry forward the design discussions, I'd characterize
that as RDFa in HTML and that's a well-scoped task that we can give to
any group.
... I do think that an IG is beneficial and would be fairly easy to make happen.
Manu: +1 for IG
Ralph: IG expect
team contact resources - which is both good and bad. Depends on if we
have extra people to put on it that is interested.
... I'm certainly interested, but I'm afraid that I may not have the time.
Steven: I may have the time for the team contact role.
Ben: Sounds like
IG, even with the overhead, is the more appropriate direction.
... anybody else prefer XG?
Steven: We should make it clear that RDFa is a W3C technology and it should get resources from W3C going forward.
Manu: Where does the IG charter proposal have to come from?
Ralph: usually
comes from the activity lead, Ivan in this case, then to W3C management,
which approves and sends to AC to discuss and then to the Director for approval.
... Anybody can draft it.
Ben: I'm happy
to put some time into that... would be high on my priority list.
... We could do this on the wiki - draft the charter on the wiki.
<ShaneM> Note that our current structure continues under the XHTML 2 working group until the end of 2009.
Ralph: There is a charter template that we can put on the wiki.
<scribe> ACTION: Ben to author wiki page with charter template for RDFa IG. Manu to provide support where needed. [recorded in]
<Ralph> How to Creat an Interest Group
Ralph: Charter aggregator/generator is on that page.
Manu: the order
in the agenda is just random, not necessarily reflecting my preferences
... @token and profiles interact
... HTML+RDFa has gotten interest from others who want to see it pushed forward
... my preference would be to focus primarily on HTML+RDFa discussion
... @token and profiles discussion *may* help solve problems with HTML+RDFa but otherwise are secondary
Ben: different TF participants might work in parallel
<ShaneM> FWIW I feel the "issues" related to RDFa in HTML (4) are basically the same as any issues related to RDFa in HTML 5.
Mark: here's how
I work out what the priorities should be
... adoption does not seem to be hampered by the fact that we've written XHTML+RDFa, not HTML+RDFa
... there some subtleties such as nsprefixes not all in the same case, XML literals
... but this doesn't appear to be stopping people from using RDFa
... we're going in the right direction; HTML5 aside, what would we be doing next?
... I'd pay attention to avoiding fragmentation
... perhaps discussion on a core document that's neither HTML nor XHTML
... use that core document as a mechanism to address XML literals
<Steven> +1 to promulgation being a priority
<ShaneM> +1
Ben: is there a conflict between what we're promulgating right now in our examples with what's going on in the HTML WG?
Manu: I don't think any of us here think there's a conflict but that opinion isn't shared by some others
Ben: Shane's HTML4+RDFa document shows a mechanism that works with HTML5
Manu: some good issues -- mostly corner cases -- are being brought up though
Ben: yes, we should resolve the edge cases but that need not stop us from continuing to promulgate the examples
Manu: we haven't run a lot of our tests against HTML4 and HTML5 documents
Ben: I run all
my tests in Firefox with javascript
... maybe there's no conflict between fixing edge cases and further promulgation of examples
Manu: not sure
we currently have enough data to say
... not sure we can safely say there will be no issues
Ben: if folk are
doing wierd things such as not paying attention to case sensitivity,
that would be a conflict
... but new @rel values do not present hard conflicts
Shane: we should
avoid use cases where prefix names are anything other than lowercase
and examples that use XML literals
... it's OK for us to promote our Recommendation
... just avoid things we know are problems and we're fine
Ben: We're going
to have different priorities, some are going to focus on HTML+RDFa,
some are going to focus on @token, others RDFa Profile.
... Immediate priority is helping Sam Ruby help us with HTML+RDFa
<msporny>
Manu: my
suggested priorities ...
... issues page documents everything raised in the long thread
... case sensitivity and @xmlns are the two biggest issues
... several issues related to @xmlns; empty prefixes, underscores, etc.
Ben: those related issues I'd characterize as edge cases
<msporny>
Manu: regarding
requirements, there are quite a number of conflicting requirements
... I have not yet sorted through all of this
... Sam Ruby's request asking us to address his comments is reasonable
... we're slower to respond than some people prefer which is apparently interpreted as lack of transparency, even though we're being open
<ShaneM> FWIW Philip has said that we are responsive - it was Sam who said we were not responding to Philip
Ben: case
sensitivity is more important to address than some other comments
... some things that have been raised as comments are really non-issues
... I'll put some time into helping with these responses
Manu: I created the wiki page because people were complaining that we hadn't acknowledged some messages after 2-10 days
Ben: Can we set up an issue tracker for this stuff?
<scribe> ACTION: Ralph make a request for an RDFa issue tracker instance [recorded in]
Ben: We are going to be extremely transparent about this, as we have always been.
<scribe> ACTION: Manu to go through and categorize issues and requirements that we should address going forward. [recorded in]
Steven: Should we go back to weekly meetings?
Manu: +1 for weekly meetings.
Ben: Is that okay to go back to weekly meetings?
Steven: If people are thinking that we're slow about this stuff, we should step it up and meet weekly.
Mark: Yes, weekly sounds good.
Ben: Let's go to weekly meetings then.
<Ralph> [I'll send mail about issue-214] | http://www.w3.org/2009/05/28-rdfa-minutes.html | CC-MAIN-2014-35 | refinedweb | 1,480 | 69.41 |
Red Hat Bugzilla – Bug 1027414
RFE: Identify who created a group definition and when; public/hidden groups
Last modified: 2013-11-06 13:50:35 EST
Description of problem:
It's impossible to identify when a group was created, and by whom.
In some cases, there are groups created that are no longer used and thus just taking up space. When cleaning up, I'd like to know who to ask about them.
It'd also be good to have a group public or hidden (not really private, meaning just visible to your own account.) This is so certain users can create groups that they are interested in using themselves without polluting the namespace.
Version-Release number of selected component (if applicable): 4.9 | https://bugzilla.redhat.com/show_bug.cgi?id=1027414 | CC-MAIN-2018-26 | refinedweb | 124 | 60.65 |
Complex multi-repo builds with GitHub Actions and Camunda Cloud
BLUF (Bottom-line Up-front): GitHub Actions are AWESOME and will change your life, but you risk losing yourself in a microservices architecture of repos, or have to go monolith once you get a few dependent projects or cross service provider boundaries - unless you orchestrate. I show you how I did it in this article.
Get access to the Camunda Cloud Public Access Beta here. Use the Zeebe GitHub Action to orchestrate multi-repo builds with Zeebe and Camunda Cloud.
In this article:
- Preamble
- What are GitHub Actions?
- GitHub Actions: The Good
- GitHub Actions: The Bad
- GitHub Actions: The Ugly
- Custom CI with GitHub Actions and Camunda Cloud
- Zeebe GitHub Action
- Modelling the problem / solution
- Starting a Camunda Cloud workflow from GitHub
- Passing around an encrypted GitHub token
- Setting up Camunda Cloud to access the GitHub API
- Passing in a secret from Worker Variables
- Using workflow variables as string constants
- Triggering a GitHub workflow from Camunda Cloud
- Problems accessing the GitHub API
- Communicating a GitHub Workflow outcome to Camunda Cloud
- GitHub Matrix builds
- Multiple causes for an action
- Specialising HTTP Worker payloads
- Specialising GitHub Workflows
- Ad Infinitum: To Infinity, and Beyond!
- Live Stream
Preamble
Over the weekend, I did some work on an side-project, Magikcraft. It’s a platform for teaching kids to code in JavaScript, and it builds on an excellent Open Source project called ScriptCraft, written by Walter Higgins.
Since Microsoft bought Minecraft, the pace of development has increased, and there have been a lot of breaking changes to the APIs. Oracle have also deprecated the JavaScript engine - Nashorn - that we have been using since JDK 8, and introduced their new polyglot engine GraalVM.
Testing on and supporting all the various combinations of Minecraft server versions and JS runtimes has stretched the capacity of the ScriptCraft community, but there are many passionate users, including other downstream kids coding programs, like Code Makers, that use it.
It got to a breaking point with the latest Minecraft release, when a workaround patch we’d been relying on finally stopped working, and Walter let us all know that he was strapped for time and attention to give to the project. So I chipped in and built an automated building and testing infrastructure using GitHub Actions.
What are GitHub Actions?
“GitHub Actions” is the overall name given to a workflow automation capability on GitHub. I suppose it is not called “GitHub Workflows” because that namespace is already taken by the git-flow kinda stuff.
You have workflows, which you define in YAML files in a
.github/workflows folder in your GitHub repo. These workflows contain named jobs, which are made up of 1 or more named steps. The steps can use GitHub Actions, which are reusable modules of functionality, providing capabilities like installing build chains and runtimes, executing Docker commands, and so forth.
GitHub Actions: The Good
GitHub Actions let you define workflows in YAML that run in response to actions like a git push. You can use one of the many existing actions, or build your own.
The workflows run on Azure - no surprise there, since Microsoft bought GitHub. What was a surprise to me, however, is how fast they run. I created a matrix build that builds and publishes nine - yes, 9 - Docker images to Docker Hub. The equivalent build on Docker Hub takes up to an hour. On GitHub, it is done in minutes. There are some serious compute resources available on there.
It is so much faster that I moved the Docker image builds from Docker Hub’s automated builds to GitHub Actions using the Publish Docker GitHub Action.
GitHub Actions: The Bad
You can’t validate or test your workflows without pushing them to GitHub. There is no local executor like there is for CircleCI, and while there is a validator plugin for VS Code, I couldn’t get it to give me “required parameter” feedback for the Zeebe GitHub Action that I created.
This is offset by how fast GitHub Actions run, so the code-execute-debug cycle is bearable. If it weren’t this fast, that would be a serious problem - but I actually enjoyed the power of so much compute resources dedicated to Open Source while debugging, so it kept me going.
YAML - meh, as one product owner told me over dinner at the recent DevConf.CZ: “It’s the least worst thing we’ve come up with so far”, paraphrasing Churchill’s take on democracy. Of course, I was like: “Have you heard of this thing called BPMN?“
Sidenote: when I started teaching kids to code, many were using this thing called Scratch, which is a block-based programming language. I turned my nose up at it, saying: “That’s not real programming”, and proceded to teach them the difference between
) and
} and where to find them on the keyboard - like that’s real programming. My “Road to Damascus” moment was when an 8-year old kid came in and I coached him through making a combination lock guessing game, and he built a working prototype in thirty minutes with Scratch - because he was dealing purely with the logic of the program, and not struggling with syntax errors. The trickiest thing for him was state management, not balancing the right type of brackets.
GitHub Actions: The Ugly
Part of my contribution upstream to ScriptCraft has been integration with NPM, the JavaScript packaging ecosystem. The purpose of that is to unlock the innovation of the community to create, share, and discover others’ work - an essential dynamic in a vibrant Open Source community.
So, once I got automated builds, unit testing JavaScript in a dockerized Minecraft server in a GitHub action (seriously - your workflow can run for up to six hours - you could play Minecraft in a GitHub action), and publishing test images to Docker Hub, the obvious next question is:
how do I trigger a test run for downstream dependent packages when I publish a new image of the core API?
Yes, you can trigger GitHub actions in a downstream repository via webhook configuration (there is even a GitHub Action for it), but now you enter the rabbit hole of peer-to-peer choreography, with an attendant loss of visibility.
Is everything wired up? When you walk away from it for a week or two, or a month, and come back - how do you remember how it is all hooked up? Where do you go for the single point of truth for the system?
Even with three layers (base image, release package, image with release), and one dependent package, I’m having trouble remembering what triggers what and how.
“I push to this GitHub repo, that triggers Docker Hub, when that is done it should trigger a retest and rebuild of this other layer on GitHub, and that should then publish to Docker Hub, which should trigger all downstream package tests.” Pretty straight-forward, no? No.
Documentation is one attempt to address this - but is that really going to stay up to date?
Devolving responsibility is another way - package maintainers are responsible for triggering their own rebuilds / retesting. But again, there is a tight coupling to automate that, and it is opaque. And I already know that when I walk away from the small part that is already implemented, I will forget how it works and curse the idiot who wrote the documentation because it doesn’t make sense.
This is not a problem with GitHub Actions really, it is a characteristic of any complex system with multiple stakeholders, integrating disparate systems, with limited resources.
Custom CI with GitHub Actions and Camunda Cloud
It was right about then - 2am in the morning - that I remembered Ruslan’s recent article “Quick Serverless start to Camunda Cloud Public Beta”.
In the list of example use cases at the start he included “Custom CI/CD”.
Now, I always thought the “custom CI” example was contrived - I mean, isn’t that what CI systems literally do? Don’t they have this stuff built-in?
Spoiler: Yes, they do - but often using peer-to-peer choreography, and without a dependency graph - especially when you start to scale across a community or an ecosystem, or even just multiple service providers.
Zeebe GitHub Action
To solve this multi-repo build automation with Camunda Cloud, I wrote a Zeebe GitHub Action. It bundles the Zeebe Node client into a single file, and allows you to use it with declarative YAML in GitHub workflows to create workflow instances and publish messages back to Camunda Cloud from within GitHub Actions.
Modelling the problem / solution
OK, so let’s do this.
We going to create executable documentation of the system architecture that cannot go out of date, and crystallise it with the minimum number of moving parts to scale to more dependent packages.
We can use the GitHub API v3 - it’s an old school REST API left over from the days before GraphQL. It will give the whole thing a retro vibe, and we can call it directly from Camunda Cloud using the built-in HTTP Worker. I’m joking! We’re going to build a custom GraphQL client. No, we are not. REST is fine, and perfectly suited for this task. We are not requesting arbitrary related data over multiple calls, or introspecting an unknown schema, so GraphQL has no benefit here.
We can trigger a GitHub workflow over the API with a repository dispatch event.
First step, I model how I want the system to behave in the Zeebe Modeler - a desktop application for creating BPMN diagrams (apparently it is XML in the background, but seriously - it’s 2020, who needs to see that stuff?):
These are three dependent repositories that should trigger a rebuild / test in all downstream repos when they are updated.
The first one gets triggered in response to a push to a git repo, and has no other cause. This repo has a GitHub workflow that builds and pushes the base images to Docker Hub. When this GitHub workflow is complete, it communicates this back to Camunda Cloud by using the Zeebe GitHub Action to publish a message to Camunda Cloud.
Starting a Camunda Cloud workflow from GitHub
We need to correlate this message back to the running process instance, so we need a unique correlation id. We can get one by starting the Camunda Cloud workflow from GitHub on repo push using the Zeebe GitHub Action to create a workflow instance. When we start it, we’ll pass in a unique
buildid, which we will use to correlate messages to this particular workflow run (see this article for a great tutorial on message correlation in Zeebe).
Here is the GitHub workflow that is triggered by a push to the repo, and starts a workflow instance in Camunda Cloud.
name: Kick off Build Orchestration on: push: branches: - "master" jobs: startWorkflow: runs-on: ubuntu-latest steps: - name: Get current time uses: gerred/actions/current-time@master id: current-time - name: Create Zeebe Workflow uses: jwulf/zeebe-action@master with: client_config: ${{ secrets.ZEEBE_CLIENT_CONFIG }} operation: createWorkflowInstance bpmn_process_id: magikcraft-github-build variables: '{"buildid": "${{ github.sha }}-${{ steps.current-time.outputs.time }}", "gitHubToken": "Bearer {{GitHubToken}}", "TYPE_TEST": "TYPE_TEST", "TYPE_PUBLISH": "TYPE_PUBLISH" }'
The ZEEBE secret comes from the Camunda Cloud console client configuration, and is added to the GitHub repo as secrets, so that the GitHub Actions have access to them in the secrets context.
Click the copy button in the Cloud Console to copy the entire block, and paste it as-is into a new repo secret called
ZEEBE_CLIENT_CONFIG.
Passing around an encrypted GitHub token
We also need to get our GitHub Token into the workflow. We could put it into the variables of the Camunda Cloud workflow when we create it from the GitHub workflow (it is injected there as
${{ secrets.GITHUB_TOKEN }}). However, this will put it into the Camunda Cloud workflow variables in plaintext - which we would like to avoid if we can.
Luckily, we can. The Camunda Cloud HTTP Worker can store encrypted secrets and replace them at run-time from a template. So we can create a personal token on GitHub (make sure it has the repo scope). Then, add a
GitHubToken secret in the HTTP Worker “Worker Variables” dialog in the Camunda Cloud Console, and put the GitHub Token in there.
Setting up Camunda Cloud to access the GitHub API
Log into the Camunda Cloud console.
Go to your cluster, and click on “Worker Variables”. These are like secrets in CI systems - you can inject them by name, rather than putting secrets in your BPMN or code.
- Click on “Add Variable”, and create a new variable called
GitHubToken. Paste the token in there as the value.
Passing in a secret from Worker Variables
When we pass in our authorization header that will use the secret Worker Variable, it looks like this in the variables payload for a
createWorkflowInstance or
publishMessage call:
{ GitHubToken: "Bearer {{GitHubToken}}" }
The
Bearer part is important, so don’t forget it. The
{{GitHubToken}} part will be templated with the value from the Worker Variables when the HTTP Worker uses this variable. I should have called this variable
GitHubAuthHeader to make it clear what it is, and how it is distinct from the Worker Variable.
So you can think of it like this:
{ GitHubAuthHeader: "Bearer {{GitHubToken}}" }
The workflow’s
GitHubAuthHeader variable now contains an auth header, and the HTTP Worker will template in the value of the
GitHubToken secret from the Worker Variables.
So the on push workflow in the base image repo does nothing more than create a new workflow instance in Camunda Cloud, with a unique
buildid for this instance, and an authorization header for our GitHub API calls, containing the name of the encrypted secret to template in at runtime, and some string constants to allow us to specialise HTTP payloads via I/O mapping. What??
Using workflow variables as string constants
We create the Camunda Cloud workflow instance with some variables that will act as string constants for us in the workflow:
{ TYPE_TEST: "TYPE_TEST", TYPE_PUBLISH: "TYPE_PUBLISH" }
We don’t have the ability to specialise the payload of HTTP Worker calls with string constants in a BPMN model - but we can through variable mapping if we start the workflow with a known “enum” dictionary. Then we can specify a string constant by mapping one of these variables into the body.
There is always a way.
You can view this initial workflow on GitHub.
Triggering a GitHub workflow from Camunda Cloud
The first thing our Camunda Cloud workflow does is trigger another GitHub workflow in the base image repo, to rebuild and publish the base images to Docker Hub.
We trigger the workflow by posting a
repository_dispatch event to the base image repo via the GitHub API, using the Camunda Cloud HTTP Worker.
The service task that does this has the task type
CAMUNDA-HTTP.
It has two custom headers that are semantic for this worker:
method and
url.
We set method to
post for an HTTP POST request, and set the url to for the repository dispatch event endpoint for this repo.
Two of the workflow variables are also semantic for the HTTP worker:
body and
authorization.
The value of
body will be JSON parsed and sent as the body of the HTTP request, and the value of
authorization will be sent as the authorization header.
So we create I/O mappings in the Zeebe modeler to map the variable
gitHubToken (which contains our templated auth header string with GitHub token) to
authorization, and the
buildid (our unique correlation id) to
body.client_payload.buildid.
The
body.client_payload key can contain arbitrary data that will be available to the GitHub Actions that respond to this event. With access to the correlation key
buildid, they can publish messages back to Camunda Cloud that are correlated to this running workflow instance.
The
body.event_type key is required by the GitHub API, and here we can map one of our enum variables in:
TYPE_PUBLISH. This repo does not have specialised behaviours that we need to orchestrate, so we don’t bother testing the
event_type in the triggered workflow.
Problems accessing the GitHub API
If GitHub is responding with 404, if the URL is correct (double-check it!) - it means that you were not authenticated.
Typically, we send a 404 error when your client isn’t properly authenticated. You might expect to see a 403 Forbidden in these cases. However, since we don’t want to provide any information about private repositories, the API returns a 404 error instead.
You can debug this by pointing the HTTP Worker at to see the exact payload it is sending to the GitHub API.
Communicating a GitHub Workflow outcome to Camunda Cloud
We can publish a message to Camunda Cloud from the GitHub workflow after we push the base images to Docker Hub.
Here is the section of the base image repo’s publish workflow that communicates success back to Camunda Cloud: }} variables: '{"test_passed": "false"}'
(View it on GitHub).
However, execution halts in the GitHub workflow if the task fails. One way to deal with failure is to wrap every step in a GitHub workflow and test for failure, but that is clunky.
Instead, we will use a boundary interrupting timer to detect failure by timing it out. We could publish a message from somewhere else by listening to the repo webhooks, but we want to do this with zero additional infrastructure.
Our timeout task could trigger any notification behaviour, but let’s keep it zero-infra and raise an incident in Operate. We can do this by creating a CAMUNDA-HTTP task with an I/O mapping that we know does not exist.
In the I/O mapping we map
build_timed_out_set_true_to_retry to
dummy. When the token enters this task, it will raise an incident because the variable
build_timed_out_set_true_to_retry doesn’t exist. When you fix the issue with the build, you can set this variable to true in Operate and retry.
The I/O mapping for the task maps the
build_timed_out_set_true_to_retry variable to
dummy on output, so we can reuse this pattern elsewhere - the variable is still unset in the workflow.
This CAMUNDA-HTTP task, when it does run, just does a GET to Google. If that fails, then you have bigger problems.
GitHub Matrix builds
Matrix builds in GitHub workflows allow you to build or test multiple configurations with the same steps. By default the workflow halts on the first failure, but you can specify
fail-fast: false to have the build execute all combinations before announcing failure.
name: Publish Docker images on: [repository_dispatch] jobs: build_and_publish: runs-on: ubuntu-latest strategy: fail-fast: false matrix: baseimage: - { image: "oracle/graalvm-ce:19.3.1-java8", tag: graalvm } - { image: "openjdk:8u171-jdk-alpine3.8", tag: openjdk8 } minecraft: - { jar: paper-1.15.2, dockerfile: Dockerfile } - { jar: paper-1.14.4, dockerfile: Dockerfile } - { jar: nukkit-1.0, dockerfile: Dockerfile-nukkit } - { jar: nukkit-2.0, dockerfile: Dockerfile-nukkit } steps: - uses: actions/checkout@v2 - name: Publish Docker image to Registry uses: elgohr/Publish-Docker-Github-Action@2.12 env: BASEIMAGE: ${{ matrix.baseimage.image }} MINECRAFT_JAR: ${{ matrix.minecraft.jar }}.jar with: name: magikcraft/minecraft username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_PASSWORD }} dockerfile: Dockerfile tags: ${{ matrix.minecraft.jar }}-${{ matrix.baseimage.tag }} }}
We make the second step (_notify_CamundaCloud) - where we publish the success message to Camunda Cloud, depend on the first step (_build_andpublish) - the one where we publish the Docker images.
We do this by specifying
needs: build_and_publish in the second step. This prevents GitHub from parallelizing the tasks and optimistically reporting success back to our workflow in Camunda Cloud.
This ends the first repository’s automation. If this succeeds, then our dependent repository needs to retest, rebuild and publish Docker images, then trigger further dependents.
Multiple causes for an action
Our second repository can be rebuilt in response to two different events:
- A git push to its own code.
- A rebuild of the base images.
We model this by creating a message start event, and then in the on push workflow in the repository, we publish this message with the metadata that our workflow needs - the templated authorization header to get our GitHub token injected into the HTTP Worker, a unique buildid, and the string constants.
name: Test on: [push] jobs: test: runs-on: ubuntu-latest steps: - name: Get current time uses: gerred/actions/current-time@master id: current-time - name: Kick off workflow uses: jwulf/zeebe-action@0.2.0 with: client_config: ${{ secrets.ZEEBE_CLIENT_CONFIG }} operation: publishMessage message_name: MAGIKCRAFT_API_PUSH variables: '{"buildid": "${{ github.sha }}-${{ steps.current-time.outputs.time }}", "gitHubToken": "Bearer {{GitHubToken}}", , "TYPE_TEST": "TYPE_TEST", "TYPE_PUBLISH": "TYPE_PUBLISH"}'
From that point forward, the workflow in Camunda Cloud is identical, regardless of how we got here.
We use the same timeout pattern to detect failure, and run a matrix test in the next workflow we trigger from the Cloud.
Specialising HTTP Worker payloads
In this subprocess we have two distinct GitHub workflows in the same repo that we are triggering from Camunda Cloud using the repository dispatch event.
Our tests may fail on the new base images, or due to the new code we just pushed, so we don’t want to publish test containers if it does. So we have a test workflow and a publish workflow.
To get specialised behaviour in response to the repository dispatch event, we need to specialise the HTTP Worker task that calls the GitHub API. We do this by mapping one of the string constants from our enum dictionary in the variables to
body.event_type in the I/O Mappings for the task:
<bpmn:serviceTask <bpmn:extensionElements> <zeebe:taskDefinition <zeebe:ioMapping> <zeebe:input <zeebe:input <zeebe:input <zeebe:input </zeebe:ioMapping> <zeebe:taskHeaders> <zeebe:header <zeebe:header </zeebe:taskHeaders> </bpmn:extensionElements> <bpmn:incoming>SequenceFlow_0weo0p1</bpmn:incoming> <bpmn:outgoing>SequenceFlow_0a48581</bpmn:outgoing> </bpmn:serviceTask>
Specialising GitHub Workflows
We have two GitHub workflows that are triggered from the repository dispatch event. We can specialise the
event_type that we send with the event from Camunda Cloud with the HTTP Worker, now we need to specialise the GitHub workflows.
We can do this with a conditional:
jobs: test: if: github.event.action == 'TYPE_TEST' runs-on: ubuntu-latest
The
event_type from the API call appears in the GitHub workflow as
github.event.action.
You can debug
repository_dispatch events sent to a repository by creating a workflow like this:
name: Debug on: - repository_dispatch jobs: echo: runs-on: ubuntu-latest steps: - name: Debug run: echo "${{ toJson(github.event) }}"
View the two workflows on GitHub: test and publish.
Ad Infinitum: To Infinity, and Beyond!
The third subprocess is essentially the same thing repeated. To run unit tests inside Docker inside a GitHub Action, I took inspiration from this article: Github actions running javascript unit tests on docker. The Magikcraft and plugin unit tests actually run in JavaScript inside Minecraft inside Docker inside a GitHub Action - now orchestrated by Camunda Cloud.
It’s possible to extend this system further in either direction - for example, the base images are actually built in response to upstream dependencies updating, principally Minecraft server versions. That could be automated and added as a trigger to the whole process.
One thing that became apparent to me is the need to use a standard pattern, and as thin a shim as possible at each layer.
I discovered the idea of passing in string constants to specialise HTTP Worker payloads when I found myself replying to Camunda Cloud with a message that encoded knowledge in the GitHub workflow of where it was in the BPMN process flow - a clear symptom of tight coupling.
The Zeebe Action came about in order to lift a repeated pattern to a first-class concern - I started by creating a light-weight zbctl container and scripting it via BASH in GitHub Actions.
There is more lifting that can be done, and I am sure that as patterns emerge there will be less manual wiring of I/O mappings that will be required to accomplish this integration.
In the meantime, you can accomplish quite a lot with zero-infrastructure.
An important feature of designing systems like this is in their comprehensibility and responsiveness to change - their agility. It is not just “how easy is it to do?” it is “how easy is it to extend and modify the behaviour of the resulting system?“
For that, right now, I don’t have an answer. My intuition is that now that the basic components are in place and some patterns have emerged, it will be a flexible system.
Live Stream
Finally, here is a live stream of me working on this. | https://zeebe.io/blog/2020/02/camunda-cloud-github-actions/ | CC-MAIN-2020-16 | refinedweb | 4,107 | 59.23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.