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
Determining Carry and Overflow FLags¶ When we do binary math,n a cmputer there are two basic situation where the result we generate is not formally “correct”. These two situations depend on whether we consider the operands as signed or unsigned numbers. Remember that the machine has no idea what kind of data it is working with, it just sees the bits and does the operation. In any ALU operation, the result of that operation is always the same size as the operands. (And, in our machine both operands must be the same size - no mixing of sizes is allowed!) In unsigned math, if the result does not fit into the same container size, either because we generated one more bit on ADD, or borrowed a bit from beyond the far left bit on SUB, the Carry flag will be set to indicate the problem. The actual value we will see is wrong, since that extra bit is needed to get the complete answer. Signed math is more tricky, since we need to watch the sign of the result in addition to the size of the result. If the result of our operation generates an incorrect sign, or does not fit in the container, we must flag the error, and this is done using the Overflow flag. Since the processor has no idea if the data is signed or unsigned, both flags will be generated by an operation. It is up to the programmer to use the correct flag to identify a problem with the result. We need to figure out exactly how to determine these two flags. Carry Flag¶ The rules for turning on the carry flag are basically these: If the addition of two unsigned numbers causes a carry out of the most significant (leftmost) bits added, the Carry flag will be set. Otherwise, it will be cleeared.. As an example: 11111111 + 00000001 = 00000000 (carry flag is set) Detecting this in C++ for our simple machine is easily done by moving the operands into larger containers, then checking that the final result does not exceed the biggest number that can fit into the original container. (This can be done by using hexadecimal literals like 0xff for an 8-bit container, or 0xffff for a 16-bit container to check the limits. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. For example: 000000 - 00000001 = 11111111 (carry flag is set) How can we check this? One way is to flip the second operand into a positive number (remember it is in 2’s compliment form) and perform an addition instead. If the Carry gets set, we had to borrow! Overflow Flag¶ There are two rules for detecting overflow in signed binary addition: If adding two positive numbers generates a result that is negative, overflow occurred. For example: 01000000 + 01000000 = 10000000 (Overflow is set) If adding two negative numbers generates a result that is positive, overflow occurred. ` For example: Testing for overflow¶ Here are some code fragments that can be used to find out if overflow will occur in signed addition and subtraction: #include <limits.h> int a = ?; int b = ?; // addition if ((b > 0) && (a > INT_MAX - b)) /* `a + b` would overflow */; if ((b < 0) && (a < INT_MIN - b)) /* `a + b` would underflow */; // subtraction if ((b < 0) && (a > INT_MAX + b)) /* `a - b` would overflow */; if ((b > 0) && (a < INT_MIN + b)) /* `a - b` would underflow */;
http://www.co-pylit.org/courses/cosc2325/assignments/12-carry-rules.html
CC-MAIN-2018-17
refinedweb
576
56.79
User:Peter Luschny/PermutationTrees Contents - 1 Permutation Trees - 2 Counting permutation trees - 2.1 A123125 Permutation trees of power n and width k (Eulerian numbers). - 2.2 A179454 Permutation trees of power n and height k. - 2.3 A179455 Permutation trees of power n and height does not exceed k. - 2.4 A179456 Permutation trees of power n and height at most n − k. - 2.5 A179457 Permutation trees of power n and width does not exceed k. - 3 Three statistics on permutations - 4 Flattening the tree: the caterpillar notation - 5 The correspondence: Permutation <-> Tree - 6 Summary: Three classifications of permutation trees. - 7 Number of maps p:[n]→[n] with p(x) ≤ x and p^[k](x) = p^[k-1](x). - 8 The permutation trees with power 5 Permutation Trees KEYWORDS: Permutation tree, rooted tree, classifications of permutation trees, Eulerian numbers, permutation, caterpillar notation. Concerned with sequences: A008275, A008292, A179454, A179455, A179456, A179457. Definitions A permutation tree is a rooted tree that has vertex set {0,1,2,..,n} and root 0, and in which each child is larger than its parent and the children are in strict order from the left to the right. The power of a permutation tree is the number of descendants of the root. The height of a permutation tree is the number of descendants of the root on the longest chain starting at the root of the tree and ending at a leaf. The width of a permutation tree is the number of leafs. The correspondence with the permutation is given by traversing the periphery of the tree starting at the right hand side of the root and recording a node whenever the node's right edge is passed. For example below tree A has height 4 and width 1, the trees B, C, D all have height 3 and width 2, ..., and tree I has height 1 and width 4. Example classifications Permutations classified by height and by width of the associated rooted tree. Trees are coded as parental lists. Permutation trees with power 4 Counting permutation trees A123125 Permutation trees of power n and width k (Eulerian numbers). A special case: A008292(n,2) = A000295(n) for n > 1. A179454 Permutation trees of power n and height k. Special cases: A179454(n,2) = BellNumber(n) - 1 = A058692(n) for n > 1; A179454(n,n-1) = A034856(n) for n > 1. A179455 Permutation trees of power n and height does not exceed k. Partial row sums of A179454. Special cases: A179455(n, 2) = BellNumber(n) = A000110(n) for n > 1; A179455(n, n-1) = A033312(n) for n > 1. A179456 Permutation trees of power n and height at most n − k. Partial row sums of A179454 starting from the diagonal. A special case: A179456(n, n-1) = A000096(n). A179457 Permutation trees of power n and width does not exceed k. Partial row sums of A008292. A special case: A179457(n, 2) = A000325(n) for n > 1 (Grassmannian permutations). Three statistics on permutations The Combinatorial Statistic Finder gives the definitions: A combinatorial collection is a set with interesting combinatorial properties. A combinatorial map is a combinatorially interesting map between combinatorial collections. A combinatorial statistic is a combinatorially interesting map . The combinatorial collection we want to consider here are permutations and we want to find a combinatorial statistic assigning a characteristic integer to every permutation. We assume that we already have a function which assignes to a rooted tree its height and a function which assignes to a rooted tree its width. Now we want to lift these characteristics to permutations. The height-statistic of permutations In the first case we want to find a statistic and a map such that for all permutations p. This statistic and the map can be implemented in Sage/Python as: def statistic(pi): if pi == []: return 0 h, i, branch, next = 0, len(pi), [0], pi[0] while true: while next < branch[-1]: branch.pop() current = 0 while next > current: i -= 1 h = max(h, len(branch)) if i == 0: return h branch.append(next) current, next = next, pi[i] The distribution of the heights over the permutations now amounts to count the number of permutations with the same height. def A179454_distribution(dim): for n in [0..dim]: L = [0]*(n+1) for p in Permutations(n): L[statistic(p)] += 1 print L A call A179454_distribution(9) generates the above table A179454. The statistic can be found on FindStat as the statistic St000308. The width-statistic of permutations The second case is the Eulerian case. Here we want to find a statistic and a map such that for all permutations p. This statistic and the map can be implemented in Sage/Python as: def statistic_eulerian(pi): if pi == []: return 0 w, i, branch, next = 0, len(pi), [0], pi[0] while true: while next < branch[-1]: branch.pop() current = 0 w += 1 while next > current: i -= 1 if i == 0: return w branch.append(next) current, next = next, pi[i] The distribution of widths over the permutations are counted by the Eulerian numbers. The function below computes a row in the Euler triangle. def A123125_row(n): L = [0]*(n+1) for p in Permutations(n): L[statistic_eulerian(p)] += 1 return L [A123125_row(n) for n in range(7)] The shape-statistic of permutations The width-statistic and the height-statistic of permutations can be combined in a single statistic, the shape-statistic of permutations. It describes the shape of a permutation as the pair [width, height] of the associated permutation tree. The small formal imprecision that a statistic is required to have the form can be easily overcome: We define st_shape(p) = 2^width(p)*3^height(p). There is no ambiguity in this encoding by the uniqueness of the prime factorization. Granted, there is an arbitrariness in the choice of 2 and 3 (any other two different prime numbers would do equally well) and in the order of width and height, but for the purpose of our exposition this encoding is a convenient way to represent and count the various shapes of permutation trees. For example in the case n = 3 we have the statistic [1, 2, 3] => (2, 2) => 36 [1, 3, 2] => (1, 3) => 54 [2, 1, 3] => (2, 2) => 36 [2, 3, 1] => (2, 2) => 36 [3, 1, 2] => (3, 1) => 24 [3, 2, 1] => (2, 2) => 36 Thus the 6 permutations can have three shapes [24, 36, 54] which have shape counts [1, 4, 1] respectively. Thus the permutations of {1, 2, 3} distribute in shape as [(24, 1), (36, 4), (54, 1)]. The number of different shapes for n ≥ 0 are A265602 = 1, 1, 2, 3, 5, 7, 11, 14, 20, 25, 32, ... We consider the fact that this sequence was not yet in the OEIS as a strong indication that this classification of permutations might be new. The corresponding different shapes are [(0,0)], [(1,1)], [(2,1), (1,2)], [(3,1), (2,2), (1,3)], [(2,2), (4,1), (3,2), (2,3), (1,4)], ... or in encoded form A265603 = [1], [6], [12, 18], [24, 36, 54], [36, 48, 72, 108, 162], [72, 96, 108, 144, 216, 324, 486], ... The corresponding number of permutations with these shapes are A265604 = [1], [1], [1, 1], [1, 4, 1], [3, 1, 11, 8, 1], [25, 1, 13, 26, 41, 13, 1], ... A more formal description of the shape-statistic of permutations are bivariate polynomials defined as the sum of the monomials x^w*y^h where (w, h) is the shape of p, summed over all n-permutations p. For example in the case n = 4 we find p(x,y) = x^4*y + 11*x^3*y^2 + 8*x^2*y^3 + x*y^4 + 3*x^2*y^2. Looking at the coefficients of this polynomial we get the two lists [0, y^4, 8*y^3 + 3*y^2, 11*y^2, y] [0, x^4, 11*x^3 + 3*x^2, 8*x^2, x] Setting in turn y = 1 and x = 1 we arrive at the lists [0, 1, 11, 11, 1] [0, 1, 14, 8, 1] which are row 4 in triangle A123125 and triangle A179454, respectively. In case n = 5 the reader might verify the polynomial p(x,y) = x^5*y + 26*x^4*y^2 + 41*x^3*y^3 + 13*x^2*y^4 + x*y^5 + 25*x^3*y^2 + 13*x^2*y^3 This polynomial describes much the structure seen in the poster displayed at the bottom of this page. Looking at the coefficients we get: [0, y^5, 13*y^4 + 13*y^3, 41*y^3 + 25*y^2, 26*y^2, y] [0, x^5, 26*x^4 + 25*x^3, 41*x^3 + 13*x^2, 13*x^2, x] The Sage code for computing the shape-statistic is unsurprisingly almost identical to the scripts given above: def statistic_shape(pi): if pi == []: return (0, 0) h, w, i, branch, next = 0, 0, len(pi), [0], pi[0] while true: while next < branch[-1]: branch.pop() current = 0 w += 1 while next > current: i -= 1 h = max(h, len(branch)) if i == 0: return (w, h) branch.append(next) current, next = next, pi[i] This statistic can now be evaluated with regard to the different variables of interest for example with the function: from sage.combinat.subset import list_to_dict def shape_row(n): y = var('y') S, L = 0, [] for p in Permutations(n): w, h = statistic_shape(p) S += x^w*y^h L.append(2^w*3^h) f = sorted(list_to_dict(L).items()) print " " print "*** n =", n, "***" print "dist of shapes: ", f print "shapes: ", [t[0] for t in f] print "shape counts: ", [t[1] for t in f] print "number of shapes: ", len(f) print "number of permutations: ", sum([t[1] for t in f]) print S print S.list(x) print S.list(y) for n in range(6): shape_row(n) Flattening the tree: the caterpillar notation The caterpillar traverses the periphery of the tree starting at the right hand side of the root and records a node whenever he passes the node's right edge. The caterpillar notation is the usual one line notation of a permutation augmented by the symbol '^', inserted every time when the caterpillar is forced to climb up a level in the tree. Thus it is an one dimensional description of a permutation tree. The length of the caterpillar is twice the power of the tree. Segments of the caterpillar which consist entirely of numbers are called down runs and segments consisting entirely of '^'s are called up runs of the caterpillar. A run is either a up run or a down run. The number of runs and their lengths are characteristics of a permutation. The correspondence: Permutation <-> Tree Given a permutation, how to construct the associated rooted tree? Maple code perm2tree := proc(perm) local tree, i, next, root, branch, current; tree := []; root := 0; branch := [root]; i := 1; next := perm[i]; while true do while next < branch[nops(branch)] do branch := subsop(nops(branch) = NULL, branch); od; current := root; while next > current do branch := [op(branch),next]; i := i + 1; if i > nops(perm) then tree := [op(tree),branch]; RETURN(tree) fi; current := next; next := perm[i]; od; tree := [op(tree),branch]; od end: An example use is: ListPermTrees := proc(n) local p, P; P := combinat[permute](n); for p in P do lprint(p, "=>", perm2tree(p)); od end: ListPermTrees(4); SageMath code def plot_tree(E): G = Graph() G.add_edges(E) G.show(layout='tree', tree_root=0, tree_orientation='down') def permutation_to_tree(pi): if pi == []: return [[0]] root, i, next = 0, 0, pi[0] branch, edges = [root], [] caterpillar = "" while true: while next < branch[-1]: branch.pop() caterpillar += "^" current = root while next > current: edges.append([branch[-1], next]) caterpillar += str(next) branch.append(next) i += 1 if i == len(pi): l = 2*len(pi)-len(caterpillar) caterpillar += "^" * l return caterpillar #plot_tree(edges) #return edges current, next = next, pi[i] for n in (1..4): for p in Permutations(n): print p, "=>", permutation_to_tree(p) [1, 2, 3, 4] => 1234^^^^ [1, 2, 4, 3] => 124^3^^^ [1, 3, 2, 4] => 13^24^^^ [1, 3, 4, 2] => 134^^2^^ [1, 4, 2, 3] => 14^23^^^ [1, 4, 3, 2] => 14^3^2^^ [2, 1, 3, 4] => 2^134^^^ [2, 1, 4, 3] => 2^14^3^^ [2, 3, 1, 4] => 23^^14^^ [2, 3, 4, 1] => 234^^^1^ [2, 4, 1, 3] => 24^^13^^ [2, 4, 3, 1] => 24^3^^1^ [3, 1, 2, 4] => 3^124^^^ [3, 1, 4, 2] => 3^14^2^^ [3, 2, 1, 4] => 3^2^14^^ [3, 2, 4, 1] => 3^24^^1^ [3, 4, 1, 2] => 34^^12^^ [3, 4, 2, 1] => 34^^2^1^ [4, 1, 2, 3] => 4^123^^^ [4, 1, 3, 2] => 4^13^2^^ [4, 2, 1, 3] => 4^2^13^^ [4, 2, 3, 1] => 4^23^^1^ [4, 3, 1, 2] => 4^3^12^^ [4, 3, 2, 1] => 4^3^2^1^ Given a rooted tree, how to construct the associated permutation? Maple code We assume the tree given by the list of its branches, this means as the list of all the chains starting at the root of the tree and ending at a leaf. tree2perm := proc(tree) local j, k, perm, branch, leaf; perm := []; for j from 1 to nops(tree) do branch := tree[j]; for k from 2 to nops(branch) do leaf := branch[k]; if not member(leaf, perm) then perm := [op(perm), leaf] fi; od; od: perm end: An example use is: ListPerms := proc(n) local p,P,pi,t; P := combinat[permute](n); for p in P do t := perm2tree(p): pi := tree2perm(t); lprint(t, "=>", pi); od end: ListPerms(4); SageMath code def tree_to_permutation(tree): perm = tree.translate(None, '^') return [int(p) for p in perm] for n in (1..4): for p in Permutations(n): t = permutation_to_tree(p) print t, "=>", tree_to_permutation(t) 1234^^^^ => [1, 2, 3, 4] 124^3^^^ => [1, 2, 4, 3] 13^24^^^ => [1, 3, 2, 4] 134^^2^^ => [1, 3, 4, 2] 14^23^^^ => [1, 4, 2, 3] 14^3^2^^ => [1, 4, 3, 2] 2^134^^^ => [2, 1, 3, 4] 2^14^3^^ => [2, 1, 4, 3] 23^^14^^ => [2, 3, 1, 4] 234^^^1^ => [2, 3, 4, 1] 24^^13^^ => [2, 4, 1, 3] 24^3^^1^ => [2, 4, 3, 1] 3^124^^^ => [3, 1, 2, 4] 3^14^2^^ => [3, 1, 4, 2] 3^2^14^^ => [3, 2, 1, 4] 3^24^^1^ => [3, 2, 4, 1] 34^^12^^ => [3, 4, 1, 2] 34^^2^1^ => [3, 4, 2, 1] 4^123^^^ => [4, 1, 2, 3] 4^13^2^^ => [4, 1, 3, 2] 4^2^13^^ => [4, 2, 1, 3] 4^23^^1^ => [4, 2, 3, 1] 4^3^12^^ => [4, 3, 1, 2] 4^3^2^1^ => [4, 3, 2, 1] Summary: Three classifications of permutation trees. Proposition 1. A permutation p has k down runs if and only if the permutation tree T(p) has width k. Proposition 2. The length of the longest run of a permutation p is k if and only if the permutation tree T(p) has height k. Proposition 1 is covered by the enumeration of permutations by the Eulerian numbers A008292 and proposition 2 by the enumeration of permutations by A179454. The power of the caterpillar notation becomes even more obvious when we note that it immediately leads to a third classification. Just look at the tail of the caterpillar. Classifying the caterpillar by the length of the last up run gives the Stirling cycle numbers! (Definition as in CM, table 245, or DLMF, 26.13.3., ABS(A008275).) This third classification is equivalent to: Proposition 3. Stirling cycle numbers classify permutation trees according to the length of the first (leftmost) branch. This description is somewhat simpler then the standard definition using cycle arrangements. Number of maps p:[n]→[n] with p(x) ≤ x and p^[k](x) = p^[k-1](x). Joerg Arndt gave this interpretation in A187761 and indicated an algorithm for the generation with restricted growth strings (RGS) for maps. A C# implementation of this algorithm below: // Generating algorithm due to Joerg Arndt. // Restricted growth strings (RGS) for maps. // A000110: f: [n] -> [n] with f(x) <= x and f(x) = f(f(x)). // A187761: f: [n] -> [n] with f(x) <= x and f(f(x)) = f(f(f(x))) // general: k-th column of A179455 // f: [n] -> [n] with f(x) <= x and f^[k-1](x) = f^[k](x) namespace OEIS { class A179455 { static int[] a; static void Main() { for (int n = 1; n < 11; n++) { var count = row(n); Console.Write("[n = " + n + "] "); for (int i = 0; i < n; i++) Console.Write(count[i] + ","); Console.WriteLine(); } Console.ReadLine(); } static int[] row(int n) { int[] count = new int[n]; for (int k = 0; k < n; k++) { a = new int[n]; do { count[k]++; } while (generate(n, k) != 0); } return count; } static int generate(int n, int k) { if (n == 0 || k == 0) return 0; int j = n, f, f1, fl; while (j-- != 0) { f = a[j]; while (++f <= j) { a[j] = f; f1 = f; fl = f1; for (int i = 0; i < k; i++) { fl = f1; f1 = a[fl]; } if (f1 == fl) return j; } a[j] = 0; } return 0; }}} --- The image of the black-red caterpillar was made by Jill Chen from Taipei, Taiwan. It was down loaded from commons.wikimedia.org and is licensed under the Creative Commons Attribution 2.0 Generic license. The permutation trees with power 5 You can download this poster of permutation trees as a pdf-file. And this article as a pdf-file.
https://oeis.org/wiki/User:Peter_Luschny/PermutationTrees
CC-MAIN-2018-09
refinedweb
2,962
66.57
After I uninstalled SwitchTower and installed Capistrano, I tried run rake --tasks and got the error message below: rake aborted! undefined method `namespace' for #<Object:0x28a9258> ./rakefile:10 I've run "cap -A ." on my Rails application before running rake --tasks. The same thing happens when I overwrite my copy of deploy.rb. Hmm, what could be going wrong here? on 2006-03-08 11:42 on 2006-03-08 11:45 What version of Rake do you? I think you need to be running the new version of rake. Harvey on 2006-03-08 11:54 Thanks Harvey, installing the latest version of rake did the trick! On 8 Mar 2006 10:44:34 -0000, Harvey Bernstein <
https://www.ruby-forum.com/topic/57223
CC-MAIN-2018-09
refinedweb
118
86.4
AppCode starts 2017.3 EAP Hi everyone, Today we are starting the Early Access Program for AppCode 2017.3 and the first build is already available for download on our site. Swift While our team continues to work on performance improvements for Swift and mixed code, this build delivers several improvements for resolution, parsing, and completion in Swift: - Correct resolve for modules used in Swift in Objective-C code (OC-15587) - Support for the #dsohandledebug identifier (OC-14546) - Resolution improvements related to smart keypaths in Swift 4 (OC-15992, OC-15864) - Correct unwrapping of @autoclosureparameters (OC-15951) - Fix for the issue with duplicates in completion when parent class and protocol have a common parent (OC-15553) Unit testing: gutter icons AppCode now makes it even easier to run a single test or all tests in your test file, with special test icons added in the editor’s left gutter: The new icons also show the status of the test, so you always know if they’ve failed recently or not. Catch support and C++ language improvements C++ users will be glad to now that support for the Catch testing framework, which was first implemented in CLion, is now available in AppCode: This build also brings a heap of improvements in the C++ language engine including: - Major reworking of list initialization inspections; - Support for #includedirectives inside namespacedeclarations; - Full support for the __COUNTER__macro and more. For more on these improvements, see this blog post. That’s it! Check the full list of fixes in our tracker. Download AppCode 2017.3 EAP Your AppCode team JetBrains The Drive to Develop 1 Response to AppCode starts 2017.3 EAP Alexander Marcenyuk says:September 27, 2017 Great job, guys! Finally I can go with my own 2017.1 -> 2017.3 cause what has been between this versions was really bad (
https://blog.jetbrains.com/objc/2017/09/appcode-2017-3-eap/
CC-MAIN-2021-25
refinedweb
305
55.58
Book excerpt: Creating graphical output using the .NET Compact Framework This chapter shows how to take advantage of the graphics capabilities of the .NET Compact Framework, providing opportunities to build far richer user interface client-tier applications than any traditional HTML-based application could ever do. .NET Compact Framework Programming with C# shows developers how their existing skills and code bases to create applications for the Pocket PC 2003 and other mobile devices. Authors Paul Yao and David Durant cover topics such as the differences between the standard .NET Framework and the .NET Compact Framework, programming with ADO.NET data classes, data binding with the DataGrid controls and using the WinForms Designer to build custom... Continue Reading This Article Enjoy this article as well as all of our content, including E-Guides, news, tips and more. By submitting you agree to receive email communications from TechTarget and its partners. Privacy Policy Terms of Use. controls. Chapter 15, .NET Compact Framework Graphics, first shows C# developers how to leverage the 85 or so graphical functions in Windows CE and the six namespaces in the .NET Compact Framework that support those graphical output classes. Then it demonstrates how to draw text, raster and vector graphics on the display screen. The chapter ends with instructions for building a sample application. Read the excerpt in this PDF file. Excerpted from .NET Compact Framework Programming with C# (ISBN: 0321174038) by Paul Yao and David Durant. Published as part of the Microsoft .NET Development Series. Copyright © 2004. Published by Addison-Wesley Professional, and available at your favorite book seller. Reprinted with permission.
http://searchwindevelopment.techtarget.com/tip/Book-excerpt-Creating-graphical-output-using-the-NET-Compact-Framework
CC-MAIN-2014-52
refinedweb
266
50.43
Hi, Note that the users@ mailing list is better for questions like these. On 02/10/2011 01:24 PM, Ashok wrote: > 2) If the xml value changes I need to update the changed value in > repository. For this I used: > session.importXML("/" , xml, > ImportUUIDBehavior.*IMPORT_UUID_COLLISION_REPLACE_EXISTING*); > *But the above step is adding nodes again rather than replacing the node > with new values.* You need to include the UUIDs also in the XML content you're importing, otherwise there's no way for the repository to tell which nodes you want to overwrite. <a jcr: <b jcr:10</b> <a> If this is not possible (i.e. you get the XML from some external source), you'll need to explicitly implement the logic by which the import can tell which existing JCR node corresponds to each incoming XML element. -- Jukka Zitting
http://mail-archives.apache.org/mod_mbox/jackrabbit-dev/201102.mbox/%3C4D53DF69.7010002@adobe.com%3E
CC-MAIN-2017-30
refinedweb
140
63.59
Map Interface adds keys to values. Every key in the Map Interface should be unique. It is part of java.util package. Each element in a map has a key and value. Each key-value pair is saved in a java.util.Map.Entry object. Map Interface is implemented by following classes: In the following example, a class HashMap is used to implement Map Interface . put() method is used to add elements to key and value pair. getKey() method and getValue()method are used to display the key and values. Map.Entry defines both of these methods. Java Map Example: package Collection; import java.util.HashMap; import java.util.Map; public class MapExample { public static void main(String[] args) { Map Names = new HashMap(200); Names.put("IN", "India"); Names.put("GB", "Great Britain"); Names.put("FRs", "France"); Names.put("IT", "Italy"); Names.put("CA", "Canada"); for (Map.Entry entry : Names.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } } Output: Key = GB, Value = Great Britain Map Example Post your Comment
http://roseindia.net/java/javatutorial/java-map-example.shtml
CC-MAIN-2016-18
refinedweb
171
64.27
0 I'm relatively new to this and need help counting the number of times a user provided word appears in a user provided file this is what I got: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream infile; string str, filename; int count, num; count = 0; num = 0; cout << "Enter File Name: \n"; cin >> filename; infile.open(filename.c_str()); if(!infile) { cout << "Error...Could not find file!!!\a"; } cout << "Enter word to look for : \n"; cin >> str; while () //Need help counting number of times the user { //input word shows up in the user provided file... num++; } cout << str << ": " << num << "\n"; while(infile >> str) { count++; } cout << "Frequency: " << (double)num/count << endl; return 0; }
https://www.daniweb.com/programming/software-development/threads/262670/need-help-counting-number-of-times-a-user-provided-word-appears-in-a-user-file
CC-MAIN-2018-05
refinedweb
117
66.67
Roman Suzi wrote: > P.S. Just look at the neighboor thread: > Subject: minidom toxml() not emitting attribute namespace qualifier I feel the need to point out a couple of things in relation to this bug in minidom. 1. The bug was fixed in minidom, but not in the base distribution. 2. Using namespaced attributes is a fairly sophisticated thing to do. I think that anyone whose usage of XML was advanced enough to use namespaced attributes would be very likely to have the excellent pyxml library installed, and thus would never see the bug. 3. The latter is evidenced by the fact that no-one seems to be clamouring to have the bug fixed in the base distribution. It's been there for at least 8 months, probably longer. But anyone whose use cases might trip-off the bug will most likely be using pyxml.minidom. -- alan kennedy ----------------------------------------------------- check http headers here: email alan:
https://mail.python.org/pipermail/python-list/2003-June/196503.html
CC-MAIN-2017-30
refinedweb
154
80.01
First Domain Registration Competition Goes Online 100 Asher Lev writes "The first competition for domain name registration is now online. They aren't offering any deals, but you can check it out anyway at register.com. " Men occasionally stumble over the truth, but most of them pick themselves up and hurry off as if nothing had happened. -- Winston Churchill Simultaneous reg of same domain. Who wins? (Score:1) Re:firstpost.com (Score:1) What ever happened to the other TLD's (Score:1) The big problem is the lack of good names. I thought this was supposed to be attacked by 7 new top level domains like .firm, .info, .web, etc. Does anyone know what ever happened to the new domains? Re:CENSORSHIP AND OTHER STRANGE OCCURRENCES - READ (Score:1) whois.cgi.990607:if ($domain=~ There security is really horrible. I mean, really really bad. I wouldn't trust them one bit. ECONOMIC point of view. (Score:2) It discusses why this "competitive" market, is in fact, not competitive. Re:They don't have to be cheaper (Score:2) solicitations for web hosting, site creation software, etc, etc. It's the same old crap. Re:ECONOMIC [and wrong] point of view. (Score:2) NSI does maintain a monopoly on the Yay! (Score:1) Anybody know register.com's price tag for a domain? Or is the same? More not new (Score:1) I registered two domains with them last month with zero problems and no additional cost. They even parked them for free. The sole problem is they had a sales rep call to pitch their hosting & ecommerce services. He was friendly, smart and wasn't pushy when I said no. I love having an alternative and will use them again. Re:The Point Please? (Score:1) The Answer (Score:2) -- Re:ECONOMIC point of view. (Score:1) Log Re:Simultaneous reg of same domain. Who wins? (Score:3) Dispute policy indistinguishable from NSI... (Score:2) If any other potential registrars are reading this, please consider the following approaches to differentiating yourselves from those evil bastards at NSI: I *hate* NSI. Re:More not new (Score:1) Re:TLDs? (Score:1) register.com: Clueless? (Score:1) TLD: .md Price: $299/1 year as of April 02, 1999 Country: Moldova Comment: Intended for use by the medical profession Quick, somebody tell the people in Moldova their entire country is part of the medical profession... Server problems? (Score:1) -- Re:CENSORSHIP AND OTHER STRANGE OCCURRENCES - READ (Score:1) -- Re:Server problems? (Score:1) Maybe register.com got slashdotted already. When I go there, all I see is, Re:The Point Please? (Score:1) .us domains are free and ugly. They look like: john.robert.smith.podunk.arkansas.us Full name, town, state. So farewell to any privacy about personal information, plus no indication of content of your domain unless you're a k12 school. Confusing wording? (Score:2) Re:The Point Please? (Score:1) Re:register.com sucks - Did we work together? (Score:1) Either that, or someone who's remarkably prescient. Somehow, I get the feeling that there are other people out there who might feel like saying the same thing as Benedict. Or maybe not. "Systems Upgrade" == "haha" (Score:1) whee! Re:Confusing wording? (Score:1) Puzzling over how it would work until I read the article body. Okay, who beat me to it?!@#!@?!@#$ (Score:1) --- Openstep/NeXTSTEP/Solaris/FreeBSD/Linux/ultrix/OS Not new: I registered a domain with them May 5 (Score:1) Re:Not new: I registered a domain with them May 5 (Score:1) Re:Confusing wording? (Score:1) Re:NSI stops all ISP domain related tech support? (Score:2) The base registry information (basically, the name servers for the domain and who the responsible registrar is) is available separately from NSI's whois, on a web page at [nsiregistry.com]. I'm not sure whether I think their consequent hijacking of the rs.internic.net whois gateway that all our whois commands point to by default is good, but at least in the open source community we can fix that problem quickly if we decide to. On the other hand, since NSI is probably not going to be running the registry long term, 'nsiregistry.com' is an odd choice of domain name. We are a long way from this multiple-registrar stuff working smoothly!! But, in the long run I think it will be better than what we have now. The transition is going to be painful and confusing, though. --BitDancer NSI stops all ISP domain related tech support? (Score:3) So I do a normal, workaday 'whois' query, and today it says at the bottom: Well, I most certainly do NOT agree! How can my tech support people help our domain customers if we can't make "commercial use" of the informtation returned by a whois query, for gnu's sake? There's noplace *else* to get this info. I just check register.com, and their whois page just queries the NSI database, and that same message shows up at the bottom of the response screen. Which, I'm sure, is why NSI put it there. NSI has been trying to claim that they have a compilation copyright (or something like that) on the current database. This smells like an attempt to assert that, and I sure hope the stuff hits the fan over this. This is intolerable. --Bitdancer Can competition really be meaningful? (Score:1) I thought most people were faulting NSI's database administration more than any other part of their business - mainly because that So what's the point of having "competition" when the only value added a competitor can bring to the table is friendlier web forms? D ---- Re:Can competition really be meaningful? (Score:1) D ---- Re:Web hosting... (Score:1) Re:Almost useless, not quite. (Score:3) Actually, if it would improve the service, most would be happy to pay $100 or more. Charging less than a hardcover book for a domain name only benefits the squatters and overloads the system. -- Why not have a revolution (Score:1) Also, if nobody challenges the notice at the bottom of the whois results soon, I don't think the courts will be disagreeing with it as much in the future. Almost useless, not quite. (Score:1) I see no reason to use them yet. If they don't offer SOME form of incentive to use them, they'll die. Register.com isn't... (Score:1) Billions and Billions served (Score:3) They already have 741984 domains registered? I didn't think that they had been around long enough for that. Have they pre-registered a bunch of likely names and will then pass them on to the visitors to their site? That would be domain name squatting on their part. Or is the 741984 value the total number of domain names registered on the entire 'net, including those registered by NSI? In that case, they really shouldn't have that number on their page. I mean, I could start a hamburger stand and put up a sign saying "Billions and Billions sold", but that doesn't mean that I did the selling of them. Re:Server problems? (Score:1) Register.com's censoring code snipit: if ($domain=~ $ERROR_MESSAGE = "The domain you have chosen is not available."; return $ERROR_MESSAGE; } elsif ($domain=~ $ERROR_MESSAGE = "The domain you have chosen is not available."; return $ERROR_MESSAGE; } elsif ($domain=~ $ERROR_MESSAGE = "The domain you have chosen is not available."; return $ERROR_MESSAGE; } CENSORSHIP AND OTHER STRANGE OCCURRENCES - READ!! (Score:2) Try registering SHITSDAASDASD.COM or some similar variation at Register.com and it will say the name isn't available even though it really is. Then goto NSI and try registering the same domain and select 'Reserve' and you'll find it works as it should since NSI removed the SHIT filter awhile back. Appearantly Register.com isn't up to speed and when I emailed Register.com yesterday, they denied they are rejecting registration *requests* based on profane keywords even though they really are. A more disturbing problem is that Register.com has *appearantly* blacklisted some people preventing them from registering domains through them (not sure the exact machanism, but assume it's either done via email address and/or phone#). Perhaps, this is just bad luck, but my personal experience suggests otherwise. Anyone else experience similar problems, please post and/or email me. Bottom line is until Register.com gets their customer service and their policies straight, I'd strongly recommend people to avoid them. At least NSI is a known quantity and while their service isn't great, they for the most part have done a decent job. So for now I'm sticking with NSI until there's a compelling reason to switch to another registrar - ie. better price and/or extra services. Ron Bennett Re:Almost useless, not quite. (Score:1) NSI has been nothing but evil incarnate (ok, well maybe that's an exaggeration, but not quite) in the way it has treated domain registrars. If all things are equal and I despise one registrar (NSI) the other wins by default. But What I wanna know is... (Score:3) I'd LOVE to start dumping money somewhere OTHER than NSI, but I'm not about to chance losing my domain to do it. Their site doesn't seem to make any mention of that and you would THINK they'd also be trying to make some go of grabbing renewal profits if they could do so... Re:.......................... (Score:1) Re:Confusing wording? (Score:1) Re:NSI stops all ISP domain related tech support? (Score:1) If I get really motivated, next month I send a request for payment with interest, but probably not. Life is short.... A. Michael Froomkin [mailto] U. Miami School of Law,POB 248087 Coral Gables, FL 33124,USA Things aren't going to get any better anytime soon (Score:3) The problem with the new registrars is that they still have to go through Network Solutions' horrible database system. Almost every problem I've had with my domains has been due to records not being changed in the NSI db, usually without any indication of what was wrong, and sometimes with no indication either way for days. I have friends that have sat for weeks while their dns change forms get denied over and over again. NSI's customer service is terrible, and I'd love to use another company that placed importance on customer satisfaction, but if you're having problems changing records on your dotcom records, I don't know how a second party like register.com can help. If NSI allowed a competing firm to build a web interface that let you edit your records directly (instead of having to use antiquated e-mail forms with cryptic functions and names all over them), I'd move my domains to the new firm immediately. But NSI has registered over 5 million domains (and making half a million a day on registration fees!) and wants to continue doing so, so you'll never see a competing firm offering more features, a better interface, or a price less than $35/yr. It's called a monopoly, and I think Network Solutions enjoys that status immensely. firstpost.ac might have been funnier (was Re: Heh) (Score:2) Re:More not new (Score:3) NSI has 'oddly' imporoved, but... (Score:2) I haven't had to deal with their customer service... from my past experiences with them it has a *long* way to go before it would even be considered equal to that of the California Department of Motor Vehicles (lowest possible denominator). Perhaps they have turned a new leaf now that they have competition. However, as far as I'm concerned, it's too little too late. They should have done this at least a year ago. Unless they lower their prices, I will be taking my business to register.com. --SONET doh! (Score:1) Re:TLDs? [found more] (Score:1) 5221,00.html [news.com] But it's still very sketchy. It's going to have to happen someday, just like IPv6, namespace is just pitiful right now. TLDs? (Score:3) Re:Things aren't going to get any better anytime s (Score:2) Personally I would be willing to pay up to $100 a year if there was good service/interface I have been requesting since january to have my conformation permissions changed and have not heard a word from NSI/internic. Would switch in a heart beat.. even repay the 2 year price if I can be allowed to change my info instantly and easily. They don't have to be cheaper (Score:2) One Problem... (Score:1) Aaron Not sure about "grabbing"... (Score:1) They also registered all of nacurh.com, nacurh.net, and nacurh.org, even though they're really just and But it does appear that NSI grabbed at least one domain that people had been banging down the doors for and that they had refused to give out, about two weeks before register.com went official. As for domain registrars registering queried names, well, I wouldn't be surprised if most domainmongers do that if the name looks useful to them. Could register.com legally charge a higher price for one domain than their posted rate for registration? Regards, Okay.. so.. and? (Score:2) So what's the difference? They even call themselves "the first domain registrar to register domain names." Huh? Isn't that a redundancy? Doubletalk even? Don't expect this to help any of those nagging NS censorship issues... since we should probably assume that NS bought all the leftover dirty ones themselves recently. Goodness, what if register.com had allowed someone to buy the mother(~.com'er)-of-all-domains? Regards, Re:Register.com isn't... (Score:1) Re:Yay! (Score:1) Price is same.... Pettiness smites all with its stupidity. Re:More not new (Score:1) Re:Why not have a revolution (Score:1) Obviously, the problem is that people are NOT going to get together, compile an open database, and switch to it. Not enough, anyway. NSI (Score:1) Re:Billions and Billions served (Score:1) .......................... (Score:1) Re:NSI stops all ISP domain related tech support? (Score:1) Re:Billions and Billions served... Huh? (Score:1) Go point and click... you'll feel better :-) (Score:1) How come my toaster dont have a shutdown icon? I cant be expected to unplug the thing! I'm lost without pretty icons!!! Help me!!!!!! This scarcasim brought to you by the Letter Q. Re:Okay.. so.. and? (Score:1) And I've been wondering for several months why when I typo a domain, I often get a generic "wouldn't you like to register that domain name?" screen of uncertain provenance. Hmmm... AlterNic was in it for the fame and fortune (Score:1) 'Course, again, ICANN is supposed to be that and do that in it's own way. We could really use Jon Postel right now, methinks. Re:The Point Please? (Score:1) The Point Please? (Score:1) if they want to win...make it cheeper! Re:The Point Please? (Score:1) Current Internic is providing no service at all (Score:1)
https://slashdot.org/story/99/06/07/2156217/first-domain-registration-competition-goes-online
CC-MAIN-2016-50
refinedweb
2,555
66.54
Hide Forgot +++ This bug is a downstream clone. The original bug is: +++ +++ bug 1642872 +++ ====================================================================== Description of problem: It looks like a new role provides more permissions than it is expected. A new role having: "Reboot VM, Stop VM, Shut Down VM, Hibernate VM, Run VM, Change CD, Remote Log in" is able to delete a VM or its disk. Version-Release number of selected component (if applicable): 4.2.6 How reproducible: always Steps to Reproduce: 1. create a new role, check everything from VM/Basic Operations 2. assing a new user with the new role 3. delete any V you wish Actual results: VM is deleted Expected results: it is not allowed (Originally by Olimp Bockowski) I cannot reproduce this. What were the exact steps to reproduce? I tried these steps: 1. Create a custom role, only with action groups in VM/Basic Operations 2. Create a new VM 3. Add permission to the VM for the user with the custom role. 4. Log into VM portal as the user 5. Try to remove the VM The operation is not successful as expected. Error message: Failed to remove the VM [User is not authorized to perform this action.] Tested on: 4.2.8-0.0.master.20181101130712.git326ea78.el7 (Originally by Andrej Krejcir) Olimp, ping? (Originally by Ryan Barry) I wasn't available, in the meantime, my colleague asked the customer, she replied: "you may update the bug and let Andrej Krejcir know that is not about deleting VM. The user can delete the disk of VM." However, it is very weird, because for me it is still the problem that I can do whatever. I haven't checked it thoroughly, just from Admin Portal and: 1. I created the role: bugtest (I am not sure which user I used for that, maybe it is curcial). Basic Operations only. 2. I removed myself (obockows LDAP user) from RHV using admin 3. I created a new permission obockows + bugtest role 4. on user list I have a different icon than on system permission: icon of admin instead of user (screenshot attached) 5. I can delete whatever maybe I missed something? that's odd. olimpb (Originally by Olimp Bockowski) Created attachment 1506508 [details] role (Originally by Olimp Bockowski) Created attachment 1506509 [details] permissions (Originally by Olimp Bockowski) Created attachment 1506510 [details] users (Originally by Olimp Bockowski) Hello, is there any progress on this? Were you able to reproduce deleting the disk of the vm already? Marian (Originally by Marian Jankular) This is actually a good question -- was the role created by the customer a user or admin? There's no logcollector in the case, and the screenshot is too cropped to see it either way (Originally by Ryan Barry) I have tired the steps right now and I still cannot reproduce it. The user cannot connect to admin UI, which is expected, because he does not have any admin role. In the VM portal, the Edit button is grayed out, so there is no way to delete a disk. Using the API to delete the disk is also not permitted: DELETE ovirt-engine/api/disks/1f33970f-89fb-40fb-97e0-424c259b70f5 <fault> <detail>[User is not authorized to perform this action.]</detail> <reason>Operation Failed</reason> </fault> Can you check if the user has any other roles on any objects (Data Center, Cluster, Storage Domain, VM), that could permit deleting a disk? (Originally by Andrej Krejcir) @Andrej - 1. have you tried to reproduce my case? e.g. I added a user as admin (using ldap as provider), then I deleted, I added user again with User Role - a new user was able to delete everything. Maybe the problem is that removing user, doesn't remove permission for containing elements? 2. regardng your question: ok I see we have to dig into log collector provided by the customer (Originally by Olimp Bockowski) I tried it now, these steps: 1. Give a user 'test-user' the 'SuperUser' role in Administration -> Configure -> System Permissions 2. Log in as 'test-user' to Admin portal 3. Remove the 'test-user' from System Permissions 4. Try to add 'test-user' again, but an error is shown: 'Error while executing action: User is not authorized to perform this action.' It makes sense. Once the test-user looses SuperUser permissions, he cannot add a user to system permissions. Then I logged in as 'admin', added the 'test-user' with the test role to the system permissions. And still everything works as expected. (Originally by Andrej Krejcir) ok thanks, we will check log collector and DB dump (Originally by Olimp Bockowski) OK, I really put some effort into that: ovirt-engine-4.2.7.5-0.1.el7ev.noarch with long history (maybe that's the problem some upgrade script didn't run well) table users: user_id | name | surname | domain | username | --------------------------------------+-------+-----------+----------------------------+---------- 53d28cbf-c27e-494d-bfe9-e56c93185d0e | Olimp | Bockowski | ldap.corp.redhat.com-authz | obockows | table permissions: id | role_id | ad_element_id | object_id | object_type_id | creation_date --------------------------------------+--------------------------------------+--------------------------------------+--------------------------------------+----------------+--------------- c47ab965-2c80-43d7-9766-6c9986199665 | 4d843123-3b20-4786-9d05-53b305644620 | 53d28cbf-c27e-494d-bfe9-e56c93185d0e | aaa00000-0000-0000-0000-123456789aaa | 1 | 1544525476 public enum VdcObjectType { ... System(1, "System"), ... so it is remarkable we have on top - system engine=# select * from roles where id='4d843123-3b20-4786-9d05-53b305644620'; id | name | description | is_readonly | role_type | allows_viewing_children | app_mode --------------------------------------+---------+-------------+-------------+-----------+-------------------------+---------- 4d843123-3b20-4786-9d05-53b305644620 | bugTest | | f | 2 | t | 255 bugTest role - User Role, it has only VM/Basic Operation - no way to delete "Role is a set of one or several Action Groups. All roles are listed in roles table (Role class), link between roles and Action Groups - in roles_groups table." select * from roles_groups WHERE role_id='4d843123-3b20-4786-9d05-53b305644620' ORDER BY action_group_id; role_id | action_group_id --------------------------------------+----------------- 4d843123-3b20-4786-9d05-53b305644620 | 5 4d843123-3b20-4786-9d05-53b305644620 | 7 4d843123-3b20-4786-9d05-53b305644620 | 17 4d843123-3b20-4786-9d05-53b305644620 | 18 4d843123-3b20-4786-9d05-53b305644620 | 19 4d843123-3b20-4786-9d05-53b305644620 | 21 4d843123-3b20-4786-9d05-53b305644620 | 22 4d843123-3b20-4786-9d05-53b305644620 | 1300 (8 rows) grep -P '\((5,|7,|17,|18,|19,|21,|22,|1300)' ./backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/ActionGroup.java REBOOT_VM(17, RoleType.USER, true, ApplicationMode.VirtOnly), STOP_VM(18, RoleType.USER, true, ApplicationMode.VirtOnly), SHUT_DOWN_VM(19, RoleType.USER, true, ApplicationMode.VirtOnly), HIBERNATE_VM(21, RoleType.USER, true, ApplicationMode.VirtOnly), RUN_VM(22, RoleType.USER, true, ApplicationMode.VirtOnly), CHANGE_VM_CD(5, RoleType.USER, true, ApplicationMode.VirtOnly), CONNECT_TO_VM(7, RoleType.USER, true, ApplicationMode.VirtOnly), LOGIN(1300, RoleType.USER, false), === I can _DELETE_ any VM with this user (Originally by Olimp Bockowski) Thanks for the analysis. Can you please also check if the user is part of any groups that have permission to delete a VM? This is the SQL statement to get all permission objects for a specific user with roles that allow deleting a VM: SELECT permissions.* FROM permissions JOIN roles_groups ON permissions.role_id = roles_groups.role_id WHERE roles_groups.action_group_id = 2 -- Action group id for DELETE_VM If this does not return any rows, than the user should not be able to delete a VM and there is a bug. It also may be useful to get names of all groups the user is part of: FROM ad_groups WHERE ad_groups.id IN (SELECT * FROM getUserAndGroupsById('53d28cbf-c27e-494d-bfe9-e56c93185d0e')); (Originally by Andrej Krejcir) @Andrej - thank you, so your query gives the record: id | role_id | ad_element_id | object_id | object_type_id | creation_date --------------------------------------+--------------------------------------+--------------------------------------+--------------------------------------+----------------+--------------- 07471466-fde5-448e-bd9c-ce144b1face9 | 00000000-0000-0000-0000-000000000001 | eee00000-0000-0000-0000-123456789eee | aaa00000-0000-0000-0000-123456789aaa | 1 | 1533304087 and eee00000-0000-0000-0000-123456789eee is Everyone id | name | domain | distinguishedname | external_id | namespace --------------------------------------+-----------------------------+----------------------------+-------------------+--------------------------------------+------------------ eee00000-0000-0000-0000-123456789eee | Everyone | | | eee00000-0000-0000-0000-123456789eee | * and Eveyrone has SuperUser and of course, the user is part of that group only (taken using: SELECT * FROM ad_groupd HERE ad_groups.id IN (SELECT * FROM getUserAndGroupsById('53d28cbf-c27e-494d-bfe9-e56c93185d0e'));) But I can't understand it, so please explain to me: Everyone looks name domain of admin (e.g. internal), so how it could be that user from ldap is part of that group? Or I am wrong? BTW I opened this BZ as something "wider" than a customer requested. If the above problem is clear, then we focus just on disks' permissions. Thanks for your help! (Originally by Olimp Bockowski) 'Everyone' is a special hard-coded group that contains all users form all domains. I will look through the code more, to see if there is a bug with the disks' permissions... (Originally by Andrej Krejcir) Re-targeting to 4.3.1 since it is missing a patch, an acked blocker flag, or both (Originally by Ryan Barry) (Originally by Andrej Krejcir) (In reply to Andrej Krejcir from comment #20) > Hi, I believe that the problem is not the permission, but the fact that RemoveDiskCommand is triggered as an internal command. In this case, the permission validation is skipped. I have set a reproducer to confirm and I can see the following with the debug logs enabled: 2019-02-14 10:02:46,245Z INFO [org.ovirt.engine.core.bll.RunAsyncActionCommand] (default task-8) [7b372531] Running command: RunAsyncActionCommand(Action = RemoveDisk, ActionParameters = RemoveDiskParameters:{commandId='null', user='null', commandType='Unknown'}) internal: false. 2019-02-14 10:02:46,253Z DEBUG [org.ovirt.engine.core.bll.storage.disk.RemoveDiskCommand] (EE-ManagedThreadFactory-commandCoordinator-Thread-3) [347a0255-ca56-431b-8fa7-ee5a007f9548] Permission check skipped for internal action RemoveDisk. Can you please check that? (Originally by Roman Hodain). (Originally by Andrej Krejcir) @Andrej - I asked Roman to find the problem, anyway, it was some time ago, but why you think we are talking about VM Portal? Account type admin has VM / Basic Operations, so (Originally by Olimp Bockowski) Because the problem happens when using the REST API, I assumed that the API is called from the VM portal. But it could also be called from a script. Anyway, now we know how to reproduce it and where to start fixing it. (Originally by Andrej Krejcir) (In reply to Andrej Krejcir from comment #22) >. I use ovirt-web-ui-1.4.5-1.el7ev. The engine is the latest 4.2.8-async (Originally by Roman Hodain) Deleting disk without permissions with/without async=true failed. Async shows <status>failed</status> and engine log contains appropriate error. verified in ovirt-engine-4.3.2.1-0.1.el7.noarch (Originally by Lucie Leistnerova) A change was made (new impact, public date, or CSAw status) to the security issue(s) blocked by this tracker, resulting in a new SLA deadline. This bug must now be resolved by 24-Apr-2019. Refer to this bug's Description for information about how to resolve this bug. (Originally by Doran Moppert) Deleting disk without permissions with/without async=true failed. verified in ovirt-engine-4.2.8.6-0.1.el7ev.noarch
https://partner-bugzilla.redhat.com/show_bug.cgi?id=1692380
CC-MAIN-2020-10
refinedweb
1,802
57.47
Hi, I’m following on the PyTorch tutorial given by the official pytorch site and I’m on the step towards building network of N-gram language model. And then I started to wonder several stuffs which I might have glossed over without cares like, nn.Embedding, loss function and stuff. So I have two questions to ask. I believe word embeddings are to be trained but fixed, but I get the exact same value for the word embedding as the example with my followed code. How does the nn.Embedding work? I searched the official document on the site and it says Variables: weight (Tensor) – the learnable weights of the module of shape (num_embeddings, embedding_dim) so, does that mean whenever I have my datasets and word embedding dimension, it will calculate different embedding everytime I run the program? How does the loss function works? def forward(self, inputs) : embeds = self.embeddings(inputs).view(1, -1) out = F.relu(self.linear1(embeds)) #out = F.relu(self.linear2(out)) out = self.linear3(out) log_probs = F.log_softmax(out) return log_probs usage loss_function = nn.NLLLoss() # Negative log-Likelihood Loss log_probs = model(context_var) loss = loss_function(log_probs, Variable(torch.LongTensor([word_to_ix[target]]))) loss.backward() optimizer.step() total_loss += loss.data Above are my source code. Does the loss_function catches the index of the target and sets the probability as 1 and adjust the parameters of all related weights of the loss Variable holds in a way that the negative log-likelihood loss could most likely to be minimized?
https://discuss.pytorch.org/t/internal-operation-of-nn-embedding/12413
CC-MAIN-2022-40
refinedweb
252
59.19
Python array vertex in url_for I can't find any information about generating a URL using so called massive queries:"limit>=20&page [ offset ]= 0 I've tried this: url_for(endpoint, page={'limit': 0, 'offset': 0}, _external=True) But it generated the following URL: {'limit': 0, 'offset': 0} My current solution looks like this: querystrings = [] querystrings.append('page[limit]=%d' % (limit)) querystrings.append('page[offset]=%d' % (offset)) url = '%s?%s' % (root_url, '&'.join(querystrings)) I really hope there is a better way! Any help would be appreciated! Edit I ended up creating a wrapper that handles dicts separately, based on my previous solution: from flask import g, url_for as _url_for def url_for(endpoint, **values): # fix querystring dicts querystring_dicts = [] for key, value in list(values.items()): if isinstance(value, dict): for _key, _value in list(value.items()): querystring_dicts.append('%s[%s]=%s' % (key, _key, _value)) values.pop(key) # create url url = _url_for(endpoint, **values) if querystring_dicts: seperator = '?' if '?' in url: seperator = '&' url = '%s%s%s' % (url, seperator, '&'.join(querystring_dicts)) return url Then I call the shell like this: url_for(endpoint, page={'limit': 20, 'offset': 0}, _external=True) And it will return the following url: [limit ]=20&page [offset ]=0 source to share I don't believe that what you're trying is supported out of the box. Werkzeug url_for relies under the hood to convert routes to generate and encode these values, and there doesn't seem to be an encoder for the dictionaries (minor, that's what the syntax stands for {key: value} , it's not an array). I found this comment which describes the implementation of custom converters if you want to add support yourself. Flask project may even be happy to get PR, if you go down this route, however, if you do not want to use page[limit] , and not page_limit , I would have simply changed them. url_for(endpoint, page_offset = 0, page_limit=0, _external=True) source to share
https://daily-blog.netlify.app/questions/2218265/index.html
CC-MAIN-2021-21
refinedweb
320
53
In this next article about beans and beginners, following on from part 1, I present three more mandatory methods. The first two are methods we override from the Object super class and they are equals and hashCode. The last requires that an interface is added, Comparable, and the method is compareTo. equals() and hashCode() These two methods go together like fish and chips. For this reason when, in NetBeans IDE, you choose "Source | Insert Code", they are shown together: The purpose of the equals method is to determine if the instance of the object invoking the method has the same state as the objects of the same type that is passed to it. Remember that using the equality operator ‘==’ compares the addresses stored in the object references and not the state. The equals method does not need to compare the state of every member of the class. You get to decide what it means to be equals. For example, if the bean has a key such as when the bean is loaded from a record in a database then the only member to be concerned with is the key. Two records with the same primary key are the same. On the other hand a bean without a guaranteed unique key may require the state of every member to be compared for equality. This also implies that every member of the bean that is itself an object must have an equals method. In the end it’s pretty obvious that everyone needs an equals method. The hashCode method is not quite so obvious. A hash code in an integer that is calculated based on the values of members that are primitives plus the hash code returned by objects that are members. A hash code is not unique. This puzzled me at first because I could not understand the purpose of a calculated value that might be the same for two different states of the same object type. The key to understanding the hash code is to know that if two objects of the same type do not have the same hash code they cannot be equal. This is important when you consider that our best friend in code is the integer. More than any other data type we love integers because our CPU lives for integers. Integers are processed faster than any other type. To compare two Strings we need to process every character in each String. If we compared the hash code of each String and they were not the same then there is no need to do any further work. Only if the hash codes are the same do we need to invoke the equals method. This is why the two always go together. Another important purpose of the hashcode and equals pairing is the hash collections, almost always your first choice for using collections. Notice that you get to choose which members of the class should be used in the equals and hashcode methods. A word of advice is to always choose the same members for each method. Collections or frameworks that use hashcode before equals will give unpredictable results if the members are different in each method. For this example I have chosen some of the members. Here is the code that is produces by NetBeans. @Override public int hashCode() { int hash = 3; hash = 13 * hash + Objects.hashCode(this.manufacturer); hash = 13 * hash + Objects.hashCode(this.model); hash = 13 * hash + this.engineDisplacement; hash = 13 * hash + this.cylinders; hash = 13 * hash + Objects.hashCode(this.transmission); hash = 13 * hash + Objects.hashCode(this.driveTrain); hash = 13 * hash + this.weight; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final MyCarBean other = (MyCarBean) obj; if (!Objects.equals(this.manufacturer, other.manufacturer)) { return false; } if (!Objects.equals(this.model, other.model)) { return false; } if (this.engineDisplacement != other.engineDisplacement) { return false; } if (this.cylinders != other.cylinders) { return false; } if (!Objects.equals(this.transmission, other.transmission)) { return false; } if (!Objects.equals(this.driveTrain, other.driveTrain)) { return false; } if (this.weight != other.weight) { return false; } return true; } Examining the code generated by NetBeans is a good way to learn even more about coding. Notice the use of the static methods of the Objects (yes there is an ‘s’ at the end) class. This class was added to Java 7 and resolves the problem of null references. What if the String in one object was not initialized? If you invoked its equals or hashcode methods you would get a Null Pointer Exception. Comparable Interface and compareTo() The last method I consider mandatory is compareTo. This method’s job is to determine if the object invoking it is less than, equal to, or greater than the object of the same type that is passed to it. Unlike equals there is no hash code optimization. You must decide what constitutes these three conditions and return them as less than zero, zero, or greater than zero, usually as -1, 0, or 1. There is also only a minimal assist from NetBeans for this method. You are pretty much on your own. The first step is to add the Comparable interface to the class. public class MyCarBean implements Comparable { Note the use of generics to ensure that only objects of type MyCarBean can be used in a comparison. Be wary of the fact that this will be just a compile time check and not a run-time check. Adding this code makes NetBeans declare an error and pointing at the light bulb reveals what it is. Clicking on the light bulb gives two choices. Select the first, Implement all abstract methods, and the following code will be added to the class. @Override public int compareTo(MyCarBean o) { throw new UnsupportedOperationException("Not supported yet."); } The next article will look at how to write a compareTo method! {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/nb-class-javabeans-mandatory-methods-2-kf
CC-MAIN-2016-50
refinedweb
987
65.32
The XQuery is stored in a file "DDR_Text.lines_ListFileTOs.xquery" It seems to be expecting the XQuery to be XML instead of a simple xquery string, and parsing it. How can I get the XQuery debugger to behave the same as the XQuery builder? Thanks for help through these teething troubles! MrWatson ------------- Code below: arated by LF Code: Select all (: 0. Output text instead of XML :) declare namespace output = ""; declare option output:method "text"; for $File in (: 1. Drill down to each document of the DDR or use current doc :) (/FMPReport/File/@link/doc(.) union doc('')[/FMPReport/@link]) (: 2. Drill down further to the required Catalog :) /FMPReport/File let $filename := replace($File/@name,"^(.+?)(\.\w+)?$","$1") return ( for $tablename in $File/RelationshipGraph[1]/TableList[1] (: 3. Find all table occurences :) /Table/@name ! concat($filename , '::' , data(.)) order by $tablename return $tablename (: 4. Prepend the file name onto each of them :) ) (: 5. Output the results as a list sep => fn:string-join(' ')
https://www.oxygenxml.com/forum/post57901.html
CC-MAIN-2021-10
refinedweb
159
69.89
Your Account by Jose Mojica Do you think the IDE is really that important? Another situation where I've really wanted this capability is when writing Model/View/Controller classes to control complex interactions of the controls on a form. I've had cases where a single form had a dozen or more MVC classes and the project outline was huge. Of course, you can stray too far to the other extreme and combine too many items into a single file - a common occurance is for my beginning students to turn in a single large file filled with classes. Getting them to think about how best to logically separate things is one of the things that I focus on. Mike Harges Although I'm just beginning to learn C# and do have access to Visual Studio .NET, I'm finding that by writing code using simple text editors I'm getting a much better feel for the language than I would just using VS.NET. In your language courses, do you spend much, or any time showing students how to use the command line compilers, or discuss alternative development methods and platforms? Simon Hibbs And lots of people are using VB.NET and C# without intellesense because you can download the complete SDK for free. The HTMLHelp v2.0 documentation system lets you find classes you need, irrespective of how deep they are. And you can find them by searching for the functionality you're seeking, by typing in the class name, or by drilling down from a namespace. Not quite as convenient as VS.NET, but with a command prompt, notepad and explorer window open at the development folder, you're fairly productive. © 2017, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://archive.oreilly.com/pub/post/the_role_of_the_ide_in_program.html
CC-MAIN-2018-17
refinedweb
311
63.39
from the ray's origin to the impact point. In the case of a ray, the distance represents the magnitude of the vector from the ray's origin to the impact point. In the case of a swept volume or sphere cast, the distance represents the magnitude of the vector from the origin point to the translated point at which the volume contacts the other collider. Note that RaycastHit.point represents the point in space where the collision occurs. using UnityEngine; public class Example : MonoBehaviour { // Movable, levitating object. // This works by measuring the distance to ground with a // raycast then applying a force that decreases as the object // reaches the desired levitation height. // Vary the parameters below to // get different control effects. For example, reducing the // hover damping will tend to make the object bounce if it // passes over an object underneath. // Forward movement force. float moveForce = 1.0f; // Torque for left/right rotation. float rotateTorque = 1.0f; // Desired hovering height. float hoverHeight = 4.0f; // The force applied per unit of distance below the desired height. float hoverForce = 5.0f; // The amount that the lifting force is reduced per unit of upward speed. // This damping tends to stop the object from bouncing after passing over // something. float hoverDamp = 0.5f; // Rigidbody component. Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); // Fairly high drag makes the object easier to control. rb.drag = 0.5f; rb.angularDrag = 0.5f; } void FixedUpdate() { // Push/turn the object based on arrow key input. rb.AddForce(Input.GetAxis("Vertical") * moveForce * transform.forward); rb.AddTorque(Input.GetAxis("Horizontal") * rotateTorque * Vector3.up); RaycastHit hit; Ray downRay = new Ray(transform.position, -Vector3.up); // Cast a ray straight downwards. if (Physics.Raycast(downRay, out hit)) { // The "error" in height is the difference between the desired height // and the height measured by the raycast distance. float hoverError = hoverHeight - hit.distance; // Only apply a lifting force if the object is too low (ie, let // gravity pull it downward if it is too high). if (hoverError > 0) { // Subtract the damping from the lifting force and apply it to // the rigidbody. float upwardSpeed = rb.velocity.y; float lift = hoverError * hoverForce - upwardSpeed * hoverDamp; rb.AddForce(lift * Vector3.up); } } } } See Also: Physics.Raycast, Physics.Linecast, Physics.RaycastAll. Did you find this page useful? Please give it a rating:
https://docs.unity3d.com/ScriptReference/RaycastHit-distance.html
CC-MAIN-2019-18
refinedweb
381
61.83
Name | Synopsis | Description | Return Values | Errors | Attributes | See Also #include <sys/types.h> #include <sys/processor.h> #include <sys/procset.h> int processor_bind(idtype_t idtype, id_t id, processorid_t processorid, processorid_t *obind); The processor_bind() function binds the LWP (lightweight process) or set of LWPs specified by idtype and id to the processor specified by processorid. If obind is not NULL, this function also sets the processorid_t variable pointed to by obind to the previous binding of one of the specified LWPs, or to PBIND_CTID, the binding affects all LWPs of all processes with process contract ID id. If idtype is P_ZONEID, the binding affects all LWPs of all processes with zone ID id. If id is P_MYID, the specified LWP, process, task, or project is the current one. If processorid is PBIND_NONE, the processor bindings of the specified LWPs are cleared. If processorid is PBIND_QUERY, the processor bindings are not changed. The {PRIV_PROC_OWNER} privilege must be asserted in the effective set of the calling process or the real or effective user ID of the calling process must match the real or effective user ID of the LWPs being bound. If the calling process does not have permission to change all of the specified LWPs, the bindings of the LWPs for which it does have permission will be changed even though an error is returned. Processor bindings are inherited across fork(2) and exec(2). Upon successful completion, 0 is returned. Otherwise, -1 is returned and errno is set to indicate the error. The processor_bind() function will fail if: The location pointed to by obind was not NULL and not writable by the user. The specified processor is not on-line, or the idtype argument was not P_PID, P_LWPID, P_PROJID, P_TASKID, P_CTID, or P_ZONEID. The caller is in a non-global zone, the pools facility is active, and the processor is not a member of the zone's pool's processor set. Binding a system process to a processor set is not supported. The {PRIV_PROC_OWNER} privilege is not asserted in the effective set of the calling process and its real or effective user ID does not match the real or effective user ID of one of the LWPs being bound. No processes, LWPs, or tasks were found to match the criteria specified by idtype and id. See attributes(5) for descriptions of the following attributes: pooladm(1M), psradm(1M), psrinfo(1M), zoneadm(1M), exec(2), fork(2), p_online(2), pset_bind(2), sysconf(3C), process(4), project(4), attributes(5), privileges(5) Name | Synopsis | Description | Return Values | Errors | Attributes | See Also
http://docs.oracle.com/cd/E19082-01/819-2241/processor-bind-2/index.html
CC-MAIN-2013-48
refinedweb
428
52.09
Lesson 11 - Magic Methods in Python In the previous lesson, Properties in Python, we mentioned properties. In today's Python tutorial, we're going to look at magic methods of objects. Magic methods Objects' magic methods are methods that start and end with two underscores. We've already encountered several of these methods, such as the __init__() magic method for object initialization or the __str__() method to get an object as a human readable text representation. Creating objects __new__(cls, *args, **kwargs) We call the __new__() method when we need control over creating an object. Especially if we have a custom class that inherits from built-in classes like int (number) or str (string). Sometimes it's better to use the descriptors or the Factory design pattern for a given situation. The __new__() method returns either the created object or nothing. If it returns the object, the __init__() method is called, if not, the __init__() method is not called. Example class Test: def __new__(cls, fail=False): print("__new__ method called") if not fail: return super().__new__(cls) def __init__(self): print("__init__ method called") test_1 = Test() test_2 = Test(fail=True) The __new__() method takes the object's class as the first parameter and then other arguments passed in the constructor. The class parameter is passed to the __new__() method automatically. If the creation of the object is successful, the __init__() method is called with the parameters from the constructor. In the __new__() method, we can even assign attributes to the object. Example class Point: def __new__(cls, x, y): self = super().__new__(cls) self.x = x self.y = y return self point = Point(10, 5) print(point.x, point.y) We don't return the object immediately but save it to a variable and assign attributes to it. __init__(self, *args, **kwargs) The __init__() method is called when objects are initialized. As the first parameter ( self), it takes the object which is passed automatically. The __init__() method should return only None, which Python itself returns if the method doesn't have a return type specified. If the __init__() method returns something other than None, TypeError is thrown. An example in an interactive console >>> class Test: ... def __self__(self): return 1 ... >>> test = Test() Traceback (most recent call last): ... TypeError: __init__() should return None, not 'int' __del__(self) The __del__() method is also called the object's destructor and is called when then object is destroyed, but its behavior depends on the particular Python implementation. In CPython, it's called when the number of references to the object drops to zero. The del command does not call the __del__() method directly, it only decreases the number of references by one. There's also no guarantee that the __del__() method is called when the program is closed. It's better to use a try- finally block or a context manager to free resources. Object representation __repr__(self) The method should return the source-code representation of the object as text so that the following applies: x = eval(repr(x)) __str__(self) This magic method should return the human readable representation of the object as a string just like the __repr__() method. For example: class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "x: {0.x}, y: {0.y}".format(self) def __repr__(self): return "Point({0.x}, {0.y})".format(self) point = Point(10, 5) print(point) new_point = eval(repr(point)) __bytes__(self) This method should return an object representation using bytes, which means that it should return a bytes object. __format__(self, format_spec) The method is used to format the text representation of the object. It's called by the format() string method ( str.format()) We can use the built-in format() function, which is syntactic sugar for: def format(value, format_spec): return value.__format__(format_spec) More about string formatting:…ps/pep-3101/ A method example: class Point: def __init__(self, x, y): self.x = x self.y = y ... # we omit the previous methods def __format__(self, format_spec): value = "x: {0.x}, y: {0.y}".format(self) return format(value, format_spec) point = Point(10, 5) # Trims the string to 12 characters, aligns the text right and fills the empty space with spaces print("{:>12}".format(point)) If we don't override the method, using the format() method causes TypeError (since CPython 3.4) Comparison methods Python pass references to the objects being compared to comparison methods automatically. __lt__(self, other) Less than: x < y __le__(self, other) Less or equal: x <= y __eq__(self, other) Equal: x == y __ne__(self, other) Not equal: x != y __gt__(self, other) Greater than: x > y __ge__(self, other) Greater or equal: x >= y All comparison methods return True or False or may throw an exception if comparison with the other object isn't supported. An example: from math import hypot class Point: def __init__(self, x, y): self.x = x self.y = y def __lt__(self, other): if isinstance(other, Point): return hypot(self.x, self.y) < hypot(other.x, other.y) raise TypeError("unordable types: {}() < {}()".format(self.__class__.__name__, other.__class__.__name__)) def __le__(self, other): if isinstance(other, Point): return hypot(self.x, self.y) <= hypot(other.x, other.y) raise TypeError("unordable types: {}() <= {}()".format(self.__class__.__name__, other.__class__.__name__)) ... The special __class__() method returns a reference to the object's class. Only the implementations of the __lt__() and __le__() methods are shown in the example, the rest is similar. We compare two Point objects according to the distance from the origin of the coordinates (i.e. the point [0, 0]). The functools module allows to generate other methods automatically by using one of the __lt__(), __lg__(), __gt__(), or __ge__() methods, and the class should also have __eq__(). However, the use of the total_ordering decorator can have a negative impact on the program speed. Because the __class__() method returns a link to the class, this method can be used to "clone" the object. class Point: def __init__(self, x, y): self.x = x self.y = y ... def clone(self): return self.__class__(self.x, self.y) point = Point(10, 5) point_clone = point.clone() Other methods __hash__(self) The __hash__() method should be reimplemented if the __eq__() method is defined in order to use the object in some collections. Its implementation: class Point: ... def __hash__(self): return hash(id(self)) The id() function returns the address of an object in memory that does not change for the object. __bool__(self) The method returns True or False, depending on how the object is evaluated. Numeric objects give False for zero values and containers (list, tuples, ...) give False if they are empty. class Point: ... def __bool__(self): return bool(self.x and self.y) Calling an object __call__(self, *args, **kwargs) This method can call an object as if it was a function. For example, we'll get an "improved" function that can store status information. Let's code a factorial that stores the calculated values: class Factorial: def __init__(self): self.cache = {} def fact(self, number): if number == 0: return 1 else: return number * self.fact(number-1) def __call__(self, number): if number in self.cache: return self.cache[number] else: result = self.fact(number) self.cache[number] = result return result factorial = Factorial() print(factorial(200)) print(factorial(2)) print(factorial(200)) print(factorial.cache) Context manager The __enter__() and __exit__() methods are used to create custom context managers. The context manager calls the __enter__() method before entering the with block, and the __exit__() method is called when it's been left. __enter__(self) The method is called when the context manager enters the context. If the method returns a value, it's stored in a variable following as: with smt_ctx() as value: do_sth() # we put our commands here __exit__(self, type, value, traceback) This method is called when leaving the with block. The type variable contains an exception if it has occurred in the with block, if not, it contains None. In the exception lesson, we'll look at the context manager in more detail and create one. In the next lesson, Magic Methods in Python - Math methods, we look at mathematical functions and operators. Download Downloaded 0x (3.9 kB) Application includes source codes in language Python No one has commented yet - be the first!
https://www.ict.social/python/oop/magic-methods-in-python
CC-MAIN-2020-10
refinedweb
1,393
57.87
24 February 2011 20:07 [Source: ICIS news] HOUSTON (ICIS)--A new round of price increase nominations in the nylon 6 and nylon 6,6 markets have started, sources said on Thursday, with DuPont and Honeywell out in front. DuPont announced a price increase nomination of 12 cents/lb ($265/tonne, €193/tonne) effective on 1 March, or as contracts allow, for its nylon 6,6 resins. Honeywell nominated a price increase of 12 cents/lb for nylon 6 effective on 4 March, or as contracts allow. Sources said BASF had also announced a price increase of 12 cents/lb for nylon 6 for early March, but this was not confirmed. Each company said the initiatives were mostly sparked by rising feedstock costs. For nylon 6, global prices of feedstock caprolactam (capro) have surged in recent months because of plant outages and tight supply. The February capro contract price in Asia jumped to $3,200-3,210/tonne CFR (cost and freight) ?xml:namespace> In Europe, the February capro contract price settled higher by $178/tonne, at $3,482-3,559/tonne FD (free delivered) NWE (northwest For nylon 6,6, feedstock butadiene (BD) has remained tight globally, with the Surging feedstock costs from tight supply have pushed US domestic nylon 6 and nylon 6,6 prices to record levels. As assessed by ICIS, bulk unfilled domestic nylon 6 prices were at 187-202 cents/lb FOB, and bulk unfilled nylon 6,6 prices are at 213-223 cents/lb F
http://www.icis.com/Articles/2011/02/24/9438631/us-dupont-honeywell-seek-12-centlb-hikes-on-nylon-resins.html
CC-MAIN-2014-35
refinedweb
251
63.02
Easy, Flexible, Subscriptions. Seamless w/ Checkout & Payments All reviews MicroPuzzles I thought things were getting better so I removed my original review. They are having major problems with Version 2. It has been 3 months and it is problem after problem and we have the simplest of subscriptions. Developer reply We are truly sorry for the issues you've been having, your feedback is really important to us. Thank you for all of your patience, we would really like to resolve this for you! zenspiritsshop PLEASE DONT USE!!!!!!!!!!!!!!!!! It destroyed my whole store due to liquid errors after deleting it because it was very complicated to change the language of the subsciption widget. If you are not developer or Programmer please dont use it. It will make your head and heart rush if there are some changes you try to do with their description. The worst thing is that the support is available in 3 to 5 workdays!!!!!!!!!!!!! Holy almighty: For this price an absolut outrage for me. Look for other options or develop subs yourself i think this will be the same struggle Developer reply Thank you for your review. We sincerely apologize for negative experience you've had with the app and for the delay's you've encountered. Our developers are hard at work on app improvements. We've taken note of your concerns, we really appreciate the feedback thank you! PopupBagels signed up 132 subscribers week 1. week 2 as they are all to be billed the 2nd time, only 2 get a bill. the other 130 are gone. no record of them at Bold at all. total joke. customer service say 3-5 days to get back. there is no phone number to call. finally get someone on chat, who tells me the developers dont have time to talk to the customers and someone will work on it sometime soon. total joke. been working on this for 7 hours and still no answers as to why all of my subscribers disappeared at midnight on their app.. bigger joke is that Shopify's response is that it's not their problem, contact the app im using. oh, you mean the one im using based on your recommendation? found on your website? it's time for internet companies to be accountable! Developer reply Thank you for your review. I am terribly sorry for the inconvenience this all has caused you. Rest assured we are working diligently on resolving this issue. Thank you so much for your patience. LAMILL Coffee Really disappointed that BOLD created a new version of their app but just left us in the dust... they said months ago that migration was coming soon but they have done nothing and say its still not available for us. So for us to switch to the new version we would have to install the new version and manually migrate all of our customers and subscriptions ourselves. I don't think BOLD values their customers. Developer reply Thank you for your review. We sincerely apologize for the inconvenience this may have caused. We are working really hard on rolling out migrations, thank you for your feedback. FarmacyNow This app is incredibly frustrating with all it's glitches. We have multiple tickets open for close to a month now and the slow response time in rectifying these issues is very unprofessional. It's very disheartening having OUR customers upset at us for YOUR issues, glitches, lack of features and big oversights. PLEASE listen to your customers (me) and fix your app! Developer reply Thank you for the honest feedback. We apologize for any additional stress for you and your customers. Our team has reached out to speak over the phone regarding the status of the technical issues you are experiencing. La Boîte à Vins. Spécialiste du vin du Québec. After installing manually the app and spending a lot of time on it, they told me I have to pay to translate the app in French. Shame on you Bold Subscription. Developer reply Merci pour vos commentaires honnêtes - nous sommes désolés d'apprendre les problèmes que vous avez rencontrés et nous aimerions avoir une seconde chance de vous préparer au succès! Nous avons confirmé qu'un de nos experts vous a contacté via l'e-mail de votre billet, veuillez garder un œil sur nous et nous sommes prêts à vous aider. Organix Life.com Set up is really confusing then the videos are short and really not helpful. They want $60 a month? I cant even reach help. I'm trying to run a business and the only communication is email. Dont spend your money!!!!. Droplette Inc. We have had a bad experience with this app. A glitch in their system resulted in their subscription service promising our customers $0 orders. Use this service at your own risk if you want to be out thousands of dollars. Developer reply Thank you for your feedback. We sincerely apologize for any frustration this may have cause you. Our team is looking into making sure that your issues are resolved and hoping that we can turn your bad experience into a good. FruitStand Staging I cannot warn you enough to stay away from this app at this point. Ive actually taken the time to report it to Shopify due to how rushed and poorly designed and INVASIVE it is. This app will INJECT code into your site. The code is NOT namespace, so all of the sudden you will see styling and JS issues. Their support is AWFUL. Their docs are rushed and mention nothing of the injected code or how to remove it. Even after I deleted the app it continued to serve the injected code. I had to redeploy the entire app, which never had their code in the first place, to finally remove it. BUYER BEWARE. Developer reply Thank you for your review. We are always looking for ways in which we can improve our app. We are continuously working on making our app comprehensive and robust. We really appreciate your feedback!
https://apps.shopify.com/bold-subscriptions/reviews?rating=1
CC-MAIN-2021-17
refinedweb
1,013
74.9
No, this is not an assignement. Recently I decided to pick up writing code again and the project I started writing I came to a rode block with something that I never learned in class (I don't think). How would I be able to write this better (should I stick with the case statements or should I switch to if statements or something completely different?) so that if someone puts in the wrong password it will return them to the beginning to line 13? This is the code I have written so far: #include <iostream> #include <time.h> #include <stdlib.h> #include <windows.h> #include <cstdio> #include <conio.h> using namespace std; int main() { char cPass; cout << "Hello user. Please input your password:" << endl; cin >> cPass; switch(cPass) { case 'correct': { cout << "Welcome Walker. What course are we running today?" << endl; } /*This is where I run into my question.*/ case { system ("cls"); cout << "Invalid password. Please try again." << endl; return int main; } } return 0; } It's been a couple of years since I wrote code so my mind draws a blank. I've looked on some other sites and I can't seem to find an answer to my question. Any help would be spectacular! -Walker
https://www.daniweb.com/programming/software-development/threads/432608/case-statements
CC-MAIN-2017-26
refinedweb
206
85.08
Contrary to popular belief, the original game of 2048 was not developed by the U.S. Military's research agency Darpa, but was secretly developed at MIT by Gabriele Cirulli. Given the game's addictiveness, however, it has been classified as a weaponized distraction which was unleashed onto unwary teenagers, weary moms and beer chugging undergrad students around the world, giving credence to the unproven allegations that Cirulli was really a C.I.A. operative disguised as a 19 year old university student. And so I, seizing this opportunity to finally impress the members of the Underground Coding Community, and Kiddie Coders alike (while patiently awaiting for my Anonymous photo-ID and membership card to arrive in the mail), shed my responsible software developer identity and set out to build the next meme-worthy beguilement in the form of a more lethal version of this "game" and thereby hope to further embellish what its designer says is: "part of the beauty of open source software". You can learn more about playing the game by reading this Wiki article. Or you might be interested in watching a brief video I made about this project and posted on YouTube. Disclaimer Due to the high Waste-of-Time probability caused by this addictive product the Health and Safety Board recommends the use of the Healthy-Living Safeguard Timer option which has been provided by the manufacturer to help minimize any adverse effects which may arise due to prolonged use of this product. The designer of Hex2048, Christ Kennedy, will not be held responsible for any damages to the user's social, marital or professional life. Use with caution. Calling this a "Tile-Sliding-Game" is a bit of a misnomer when you look at the inner workings of this GPA destroying code. This home-wrecker doesn't actually do any 'tile-sliding' because the tiles themselves remain in their alotted places from the time they are initialized until you hear your loved ones slam the front door and drive off without you. The original game's quadrilinear layout made it possible to shuffle the cartesian positions (x, y) of the individual tiles while retaining their values but this version uses a hexagonal layout where the pieces can move in six directions rather than four. Each tile is a member of the classTile class and has a list of pointers to its own neighbors. This facilitates a few things but it means that shuffling them around on the board would be a huge hassle and a waste of those beautiful pointers. Also, because the tiles themselves jiggle and wobble on their respective pedestals, it's easy to assign them a spot and give them a radial-coordinate tether with which to roam while never getting lost or straying too far. classTile A tricky thing I discovered while writing this app (and was still able to get the basics up and running in under 5 hours - Download Hex_2048_fundamentals.zip - 67 KB file is a snap shot of what I had working at the end of that first night of coding) was that, since the columns are shifted vertically from their neighbors, moving horizontally in the odd columns is different from moving horizontally in the even columns. Have a look at the Move() function below which deals with that issue: Move() public static Point move(Point pt, int dir) { if (lstPtMoveDir.Count == 0) { List<Point> lstEven = new List<Point>(); { lstEven.Add(new Point(0, -1)); lstEven.Add(new Point(1, -1)); lstEven.Add(new Point(1, 0)); lstEven.Add(new Point(0, 1)); lstEven.Add(new Point(-1, 0)); lstEven.Add(new Point(-1, -1)); } lstPtMoveDir.Add(lstEven); List<Point> lstOdd = new List<Point>(); { lstOdd.Add(new Point(0, -1)); lstOdd.Add(new Point(1, 0)); lstOdd.Add(new Point(1, 1)); lstOdd.Add(new Point(0, 1)); lstOdd.Add(new Point(-1, 1)); lstOdd.Add(new Point(-1, 0)); } lstPtMoveDir.Add(lstOdd); } return new Point(pt.X + lstPtMoveDir[pt.X % 2][dir].X, pt.Y + lstPtMoveDir[pt.X % 2][dir].Y); } after initializing the two Even/Odd Point lists, it returns the changes that need to be made to the calling function in order for the point to more from the input parameter pt in the desired direction dir. There are six directions with zero pointing north and the rest of the directions dialling around clockwise from there. In this game, the odd valued columns are shifted higher than the even numbered columns as you can see below: pt dir style="height: 926px; width: 640px" data-src="/KB/Metro/5280583/Tiles_Odd_Even.png" class="lazyload" data-sizes="auto" data-> The Breadth First Search algorithm is an essential part of this project. Its applications are many and varied. Its fast, easy to implement and there's lots of documentation and tutorials on-line to help you out. We can have a quick look at an example for Hex2048. In the image below, the blue piece at the top (numbered 15) needs to move around the Yellow occupied tiles and reach the far left corner at the bottom (numbered 0). To do so, we start at the destination and travel where we can while leaving sticky notes on tiles as we count the steps we've taken since we left the place we're searching. (In different applications, you'd start from the start location and branch out until you found what you're looking for rather than, as we do here, start from the spot we intend to 'find' because we're not looking for some 'thing' but rather a path to a specific destination.) When you've reached the start location (blue square at the top), that square is then pasted with a sticky-note with the number 15, the number of steps taken to get there. To find your way to the destination square from there, you simply count backwards and travel to any (the only in most cases) square with a sticky note that has a value of one less than the tile you're standing on. style="height: 589px; width: 458px" data-src="/KB/Metro/5280583/Breadth_First_Search.png" class="lazyload" data-sizes="auto" data-> Notice when you reach the square numbered six along the path, there are two adjacent squares with the number five on it. The algorithm can choose either one and still get to its destination. Sometimes, like in video games, you may randomly choose from your available options just to keep things fresh. Other times, you just want to zip-it along and choose the first suitable tile you encounter. It all really only depends on your Uber driver, anyway. The code below is taken from Hex2048 and returns a list of point locations on the board that a piece needs to travel along in order to reach its destination. This implementation works in the reverse order, counting the tiles from start to destination and then winding its way back, then taking the final results and reversing the order of the points to get the final output list. List<Point> MoveSelectedTile_BFS() { Point ptDestination = ptTileHighLight; Point ptStart = ptTileSelected; int[,] intSeen = new int[szGame.Width, szGame.Height]; // init intSeen for (int intX = 0; intX < szGame.Width; intX++) for (int intY = 0; intY < szGame.Height; intY++) intSeen[intX, intY] = -1; List<Point> lstQ = new List<Point>(); lstQ.Add(ptStart); intSeen[ptStart.X, ptStart.Y] = 0; int intStepsTaken = 0; while (lstQ.Count > 0) { Point ptTile = lstQ[0]; lstQ.RemoveAt(0); intStepsTaken = intSeen[ptTile.X, ptTile.Y]; for (int intDirCounter = 0; intDirCounter < 6; intDirCounter++) { Point ptNeaghbour = move(ptTile, intDirCounter); if (TileInBounds(ptNeaghbour)) { if (intSeen[ptNeaghbour.X, ptNeaghbour.Y] < 0) { // BFS has not seen neaghbour if (Board.Tiles[ptNeaghbour.X, ptNeaghbour.Y].Value == 0) { // neaghbour is not occupied by a colored tile intSeen[ptNeaghbour.X, ptNeaghbour.Y] = intStepsTaken + 1; if (ptNeaghbour.X == ptDestination.X && ptNeaghbour.Y == ptDestination.Y) { // we have found a path to the destination lstQ.Clear(); goto validPath; } else { lstQ.Add(ptNeaghbour); } } } } } } return new List<Point>(); validPath: intStepsTaken = intSeen[ptDestination.X, ptDestination.Y]; List<Point> lstSteps = new List<Point>(); lstSteps.Add(ptDestination); Point ptCurrent = ptDestination; while (!(ptCurrent.X == ptStart.X && ptCurrent.Y == ptStart.Y)) { for (int intDirCounter = 0; intDirCounter < 6; intDirCounter++) { Point ptNeaghbour = move(ptCurrent, intDirCounter); if (TileInBounds(ptNeaghbour)) { if (intSeen[ptNeaghbour.X, ptNeaghbour.Y] == intStepsTaken - 1) { lstSteps.Add(ptNeaghbour); ptCurrent = ptNeaghbour; intStepsTaken--; break; } } } } lstSteps.Reverse(); lstSteps.RemoveAt(0); return lstSteps; } The same algorithm is used in a slightly different way when the game needs to test the board's content and remove groups of four or more similar pieces. That function is seeded to start from each tile on the board and branches out to all adjacent tiles that have the same value. When it finds four or more tiles like this, it returns them in a list and they are removed from the board before the same algorithms repeats itself until no groups of similar tiles are found and the game proceeds. It is much a simpler function. Have a look at the BFS for any given seed tile ptSeed: ptSeed List<Point> Tiles_GatherLike_BFS(Point ptSeed) { if (!TileInBounds(ptSeed)) return new List<Point>(); int[,] intSeen = new int[szGame.Width, szGame.Height]; int intSeedValue = Board.Tiles[ptSeed.X, ptSeed.Y].Value; if (intSeedValue <= 0) return new List<Point>(); List<Point> lstQ = new List<Point>(); lstQ.Add(ptSeed); List<Point> lstRetVal = new List<Point>(); while (lstQ.Count > 0) { Point ptTest = lstQ[0]; intSeen[ptTest.X, ptTest.Y] = 1; lstQ.RemoveAt(0); int intTileValue = Board.Tiles[ptTest.X, ptTest.Y].Value; if (intTileValue == intSeedValue) { if (!lstRetVal.Contains(ptTest)) { lstRetVal.Add(ptTest); for (int intDir = 0; intDir < 6; intDir++) { Point ptNeaghbour = move(ptTest, intDir); if (TileInBounds(ptNeaghbour)) if (intSeen[ptNeaghbour.X, ptNeaghbour.Y] == 0) if (!lstQ.Contains(ptNeaghbour) && !lstRetVal.Contains(ptNeaghbour)) lstQ.Add(ptNeaghbour); } } } } return lstRetVal; } One of the first things you'll notice when you play this game is the way the pieces jostle each other when they move. The effect is pretty cool. As I mentioned earlier, each tile is tethered to its spot by a Radial Coordinate (which is like a Spherical Coordinate but missing the third vertical coordinate Phi). Essentially, it's an arrow with a specific length. The arrow points in the direction in which the tile is shifted away from the tile's fixed central location and the length tells how far it moves in that direction. But the tiles only move a little bit at a time so they need to know by how much and how far to go. At every clock cycle, the magnitude of the radial coorinate is increased until it reaches its limit and then it begins to shorten until it's zero again and the tile is at rest. When it reaches its maximum limit, that limit and the direction of the radial coordinate is used to 'push' the neighboring tiles that are in the direction that it has been shifted. The three neighbors in the general direction of its shift are each imparted with one third of the force it was hit with, and in this way the motion of the tiles progresses radiating outwards from the source. Liquids and air all behave in a similar way. Sounds waves are really just atmospheric particles colliding with each other and propagating the force imparted on each of their neighbors. Conservation of energy means that the force each particle feels is distributed across to all its neighbors. Here, we have tiles moving in one of six quantized directions. When they reach the end of that shift, they push one neighbor slightly to the left. (dir + 5) % 6 and another neighbor slightly to the right: (dir +1) % 6 and the one neighbor that is in the same direction it itself was pushed. This sounds all fine and good but what happens in implementation is that the shoves that proceed, say to the left, wind their way back the way they came and a harmonic resonance like situation results. Watch this video of the Tacoma Bridge Collapse, if you don't know what I mean. There may not be any gail force winds billowing across the game board here, but it's still a problem. When I was putting this feature together the slightest jostle from one piece sent the entire board flying off the rack. What I did to solve that problem was add a list of points to each tile for it to keep track of which tiles initiated the wave of motion that is hurtling towards them. When they are struck by a neighbor, that neighbor reports which tile initiated the force hitting them and the tile being hit then looks in its list to see if it has been hit by that tile's impulse recently. If the source-tile's location (ID point) is not in the list, then the tile is hit and adds the source-point to its list. When the tidal force winds its way around the board and tries to hit it again, the force is ignored the second and all subsequent times. Each tile sends forward the same source-tile's ID when it propagates the impulse it felt on to its neighbors and each tile clears its list of source-tile-IDs when it comes to rest. I initially intended to add Dragon sprites on either side of the game. With that in mind, I cut up a Dragon image I downloaded off the internet and made it into a passable sprite. The snake-like dragon I picked was not as conducive to sprite-making as a non-snake-like dragon I could have picked, so the results were not as good as they could have been but the real problems erupted when I started drawing the animated dragon on the Left side of the game. The reason why the Left dragon was so problematic was that the dragon's shape and size varied as it moved. Which, of course was the point of making it into a sprite, but the resultant form image varied in size as well which meant the form had to move to adjust for the changes. Moving the form works fine for smaller sprites like the Jessica Rabbit sprite-form I published some ten years ago but for this interactive game, the results were unacceptable. The game was jumping visibly at a delayed rate after it changed its image and it was so bad that I had to implement a dual-form system that drew the next frame on one form, positioned it then toggled the previous off (Hide()) before instantly toggling the next one on (Show()). The graphics were much better with this implementation but it turns out that the mouse-event triggers were not following the plan and the game became unresponsive. As a consequence of that, I wrote a few lines of code that were called every game loop (on a timer) and tested the mouse's position and button states before deciding which events to call instead of letting the two jumping forms jostle each other for the privilege and ignoring their duty to report mouse-events at all in the bitterness of their fight. This was working pretty good and the results were better but there were so many complications and the code got so ugly that I looked at my dragons (two mirrors of the same sprite) and decided it just wasn't worth it. I set the form's size to a constant value which was big enough to accommodate both dragons at their worst and looked at what I had done and decided it was good. Hide() Show() But not good enough. The form's larger size reduced the game's speed and the dragons were just not worth it. So I trashed them. It only took me ten minutes to re-jig the whole project without those ugly dragons and we have what we have now... much much better. Stars, spikes and caltrops are the three different shapes which fly out in multi-colors whenever the game gets excited. They're all drawn dynamically the first time the game is launched and then their variously colored and rotated versions are all stored on the harddrive in a binary stream file. A single algorithm draws all three shapes which only differ in the number of 'spikey' things sticking out of them. Stars have 5 points, caltrops (not sure why I called them that?!?) have four and spikes only 2. They each have an inner and outer radius and the points are generated by going around a central point and setting points at alternating radii from it. These images are rotated, as I said, and stored in sequence on the file. As they are stored, their addresses are recorded in a list and the file size is used as the start of the image index where all those addresses that were accumulated in a list are recorded in the same sequence as their images. At the end of all this, the very last thing recorded on the file, is a long integer which tells you where the index starts. So to find a specific image, you plug the shape, color and angle through this function: static long ImageAddress(enuSparkleShapes eShape, enuSparkleColors eColor, int intRotation) { long lngIndexAddress = lngFileIndexAddress + (((int)eColor * ((int)enuSparkleShapes._numSparkleShapes * NumRotationPerQuarterTurn)) + ((int)eShape * NumRotationPerQuarterTurn) + intRotation) * SizeLongInteger; fs.Position = lngIndexAddress; return (long)formatter.Deserialize(fs); } It calculates the location of the desired image's Index by figuring out how many indices come before it, multiplying that value by the amount of bytes it takes to store a single long integer in the stream and adding their product to the Address of the start of the Index (that last long integer we wrote at the end of the file). long So, it measures the length of the file. Moves back the number of bytes to store a single long integer on my harddrive, 58 bytes (yea!? 58... I was surprised too since a long integer is only 8 bytes ??). There it reads the long integer and knows where in the Index starts. It moves forward from the start of the index and locates the address of the image we're looking for. Reads the long integer and uses it as the address of the bitmap. Confused? style="height: 571px; width: 600px" data-src="/KB/Metro/5280583/Sparkles_Storage_File.png" class="lazyload" data-sizes="auto" data-> Alternately, there is an advantage in storing the index on a separate file which is that you can add images and grow both your index and your images list on two separate files. In this case, we're talking about tiny images of colored stars that only take seconds to reproduce, so even if I change my mind and add that neglected 3-pointed ninja-star to the list of 'sparkle shapes', it is no great cost to delete the existing file and rebuild it. Having both the images and the index on a single file keeps things neat. Since a different OS may give you different results, the SizeLongInteger variable needs to be evaluated. Here is the function which determines how many bytes it takes to store a long integer on your harddrive: SizeLongInteger static long SizeLongInteger = 0; static void SizeLongInteger_Measure() { string strTempFilename = "DoNotTryThisAtHome.bin"; FileStream fsTemp = new FileStream(strTempFilename, FileMode.Create); fsTemp.Position = 0; formatter.Serialize(fsTemp, (long)1); SizeLongInteger = fsTemp.Position; fsTemp.Close(); System.IO.File.Delete(strTempFilename); } When I was dealing with those mouse event issues, I had to figure out how the MouseEventArgs were encoded. They seem to be stored in a long integer. I converted the MouseButtons value into a long integer and discovered that the 20th bit was set when the left mouse button was down. Likewise for the middle and right buttons, 22nd and 23rd, respectively. To help along the way, I wrote a few functions that convert integer values (byte, short, int and long) into strings to make it easier to look and debug them. MouseEventArgs MouseButtons byte short int string Since the >> and << bitwise shift operands return integer values, the workhorse here takes in an integer and spits out a 32 character string of 1s and 0s. public static string intToString(int intIn) { string strRetVal = ""; for (int intBitCounter = 0; intBitCounter < 32; intBitCounter++) { char chr = intIn % 2 == 0 ? '0' : '1'; strRetVal = chr.ToString() + strRetVal; intIn = intIn >> 1; } return strRetVal; } It's convenient, and I'm glad I wrote it. I'm sure it will come in handy again soon enough. There are hundreds of versions of this game available on-line, so why would anyone write their own? I was playing a version similar to this one (Hexagonal board) on my phone and got annoyed with all the ads. I loved the game so much I actually considered doling out the $5.00 payment to get rid of the ads but then reconsidered and decided it would be more cost-efficient to spend a week writing my own... I actually did press the option to pay to get rid of the ads but it didn't work and bogged my wireless down so badly, it forgot it was a telecommunication device when the ringtone sounded and I nearly missed a call trying to get it to morph from a slow ad-riddled game back into phone. It was a wrong number and that sent me into a downward spiral of coding energy... and the only way out of a downward spiral like that is to code, right? So that's what I did. I started last Sunday at 19h and had a working game before midnight. It was so motivating and encouraging to get such quick results that I spent the rest of the week improving the graphics. Coding really is a great way to spend your time, but really ... I just hate.
https://codeproject.freetls.fastly.net/Articles/5280583/Hex-2048-A-Numbers-Game?msg=5753546
CC-MAIN-2021-39
refinedweb
3,642
60.85
In this tutorial, we will see how to do multiprocessing in Python using an example. What is multiprocessing? It is a way to run multiple processes at the same time given that the machine has support for multiple processors. The main advantage is of multiprocessing is that the system actually performs multiple independently executable parts of an application at the same time which eventually increases the efficiency and performance of the system. Before moving further let’s see what is a process identifier. A Process Identifier or PID, in short, is a number that uniquely identifies each running process in an operating system which can be Unix, Linux, macOS, and MS Windows. Multiprocessing in Python Python provides an inbuilt package named multiprocessing which provide API that effectively supports concurrency, distributing the input data across processes or parallel executions of different processes. In the above section, we have learned about process identifier and the built-in os module of python provides us with a method named getpid() which returns the PID of the process. Example Let’s create a function that takes an integer and return whether it is positive or not and print the PIDs. import multiprocessing import os def isPositive(n): print("isPositive function with Process ID:",os.getpid()) if n>=0: print("Integer passed is Positive:") else: print("Integer passed is Negative:") if __name__ == "__main__": print("Main function with Process ID:",os.getpid()) isPositive(-1) isPositive(2) Output: Main function has Process ID: 7644 isPositive function has Process ID: 7644 Integer passed is Negative: isPositive function has Process ID: 7644 Integer passed is Positive: Note: PID can be different from the above output. From the output, we see that all the function calls that we have called has the same Process ID which is same as that of the main function. Next, we will use the components of the multiprocessing module to run the tasks as different processes. Process Class of multiprocessing module Whenever we want to create a new process we create an object of the Process class whose constructor takes the following arguments. - target – It is the callable object to be invoked by the run()method and default value is None. - args – It is the argument tuple that is passed in the function specified in the target. - name – It is the process name as a string. the default value is None. There are some other methods provided by this class which are as follows. start()– It will start the process’s activity and is called at most once for each process. run()– This invokes function passed as the target argument. join([timeout])– This method blocks until the process whose join() method is called terminates. is_alive()– Returns Trueif a process is alive else False. pid– Return the process Id of a process Example We will try to perform multiprocessing on the above example using the Process class. import multiprocessing import os def isPositive(n): print("isPositive function with Process ID:",os.getpid()) if n>=0: print("Integer passed is Positive") else: print("Integer passed is Negative") if __name__ == "__main__": print("Main function with Process ID:",os.getpid()) proc1 = multiprocessing.Process(target=isPositive,args=(8,)) proc2 = multiprocessing.Process(target=isPositive,args=(-6,)) proc1.start() proc2.start() print("Process proc1 has Process ID:",proc1.pid) print("Process proc2 has Process ID:",proc2.pid) proc1.join() proc2.join() Output: Main function with Process ID: 10124 Process proc1 has Process ID: 14912 Process proc2 has Process ID: 11708 isPositive function with Process ID: 14912 Integer passed is Positive isPositive function with Process ID: 11708 Integer passed is Negative From the output above, we can see that in total we have 3 processes running, one main process and two subprocesses of the main process. So we learned about multiprocessing in python. Resources Happy Learning 🙂
https://www.onlinetutorialspoint.com/python/how-to-do-multiprocessing-in-python.html
CC-MAIN-2021-31
refinedweb
632
54.02
Uploaded new patch. On 2012/03/20 19:25:38, davidxl wrote: It would be nice to add some unit/regression test cases of some sort. Advertising Made the existing unit test case check the final layout. David File callgraph.c (right): callgraph.c:309: if (!is_prefix_of ("_ZL", name)) How about static functions in namespace? How about functions in anonymous namespace? Thanks for pointing this out. One solution is to add more plugin interfaces to plugin-api.h to find the section flags and the section group. This way, comdats can be detected. All other duplicates can be treated as file static functions. I marked this as TODO for now. I am also thinking of sending a patch to generate unique section names for file static functions. This will help --section-ordering-file in gold too. callgraph.c:511: ".text." }; How are the sections ordered in the array? Keep it in mind that it is possible to encode the actual profile count of the function in the section name in the future. Right, for now this parsing will work. The parsing needs to be updated once the section names change.
https://www.mail-archive.com/gcc-patches@gcc.gnu.org/msg28583.html
CC-MAIN-2017-39
refinedweb
190
78.96
What is the '& operator' and how does it work? Printable View What is the '& operator' and how does it work? It can mean more than thing. However, I am assuming you are talking about the address of operator. When you have a variable, placing the ampersand (&) before the variable means you want the address of the variable instead of the actual value. For example: Code: #include <iostream.h> int main() { int number=4; cout<<number;//will display 4 cout<<&number;//will display some weird #, the address of number return 0; } actually the ampersand is after the variable: example: [code] T& operator [] ... Yeah, in the example im working with, the ampersand is used in fron of the variable: Code: T& operator [] It means a reference to the variable after it. Think of a reference like a pointer. However, the address it refers to cannot be reassigned. Also, there is no need to dereference it when using it. Basically, think of it as an alias. For example, a reference to William Clinton might be Bill Clinton. When refering to one, it modifies both. Code: #include <iostream.h> int main() { int number=4; int &numreference=number; cout<<number;//outputs 4 cout<<numreference;//outputs 4 number=7; cout<<number;//outputs 7 cout<<numreference;//outputs 7 return 0; } BTW, your example means the function returns a reference to a T type. unary operator gives you the address as previously stated, useful for passing to functions and pointers, see examples above. as a binary operator it provides an alternative identity for a memory address, eg Code: int number = 4; int& sameNumber = number; //& can be beside data type or identifier cout << number << endl; //prints 4 cout << sameNumber << endl; //prints 4 to gamma: & operator: a bit operator (for binary operations) the binary operators: & : AND | : OR ^ : XOR if you have knowledge on how the boolean concept works, this shouldn't be a problem. when using the '&' (AND) operator, you will be working with binary data so if you are working with an int, the int will be operated though binary operations (it does this anyway since machine operations are based on 1's and 0's). so: 1 & 1 = 1 1 & 0 = 0 0 & 0 = 0 if you are working with a group of binaries, example: 9 + 3: 9 = 1001 3 = 0011 so... 1001 + 0011 --------- 0001 1 = 0001 in binary so 9 & 3 = 1
https://cboard.cprogramming.com/cplusplus-programming/16291-operator-printable-thread.html
CC-MAIN-2017-09
refinedweb
395
53.41
Proposed features/Phone Rationale There are many objects we're currently mapping to which a telephone-number belongs, that map-users might want to know. Be it to make reservations at a restaurant, hotel or camp-site, asking for opening hours of a shop or museum, there are many more uses to think of. Of course this isn't meant for private telephones, only because the building they're in is drawn in OSM. It's only for phones which are supposed to be called by the public. The same applies for fax-numbers. Tagging Every phone number in the world is (should be) made up of three components: country-code, area-code and local-number. For proper usage we need the area-code and the local-number, the country-code in addition is preferred but optional (as everything in OSM). Example The local-number of the restaurant 'Le Jules Verne' in the Eiffeltower in Paris is 45556144, the area-code for Paris is just 01, the French country-code is 0033 or +33. So you tag it: - phone = +33 1 45556144 To make the number easier readable to humans you should leave a space " " between the components. Navigation devices like the Openmoko that are a phone as well will still be able to handle the number correctly. Rendering This feature would make no sense to render. But the number(s) should be shown in a kind of context menu. Opinion - I'm uncertain about the format of the number. It would be easier to read if the prefix is separated by a blank. But would this allow systems like the OpenMoko to use it directly for dialling? What do you think about a country-codes? -- Fröstel 00:05, 14 November 2007 (UTC) - The format should probably be whatever someone physically present in a given area would have to dial to call their destination. Given the prevalence of cell phones, the number should include the area code (ten digit dialing) or whatever the European prefix is. OpenMoko being able to use the number directly or if using a Nokia internet tablet transfer the number to your phone would rock. -- sadam 19:45, 14 November 2007 (UTC) - I assume all over the world a phone number fits the scheme: country-code followed by area-code followed by local number. 0049 40 123456 would be someone in Hamburg(040) in Germany(0049). I don't think it's necessary to store the country-code but would insist on the area-code. Maps are for people that don't know the area, so they also probably don't know the area-code. I'm no developer but I suppose it must be easy for the software on an OpenMoko or alike to tell that "040 123456" is the same as "040123456" and use it as such. Therefore I'd suggest to separate the area-code by a space " " to make it better readable for humans. -- Fröstel 20:48, 14 November 2007 (UTC) - Responding to more than one point: I'm not sure about Open Moko but most programmable phones and modems I've tried accept, i.e. ignore, both spaces and hyphens and I think Fröstel makes a good point that these are good for readability. I predict that this is the sort of thing we are going to see in OSM online map pop-ups before not too long. The best all-embracing telephone number scheme I've seen is (using the above example) +49-(0)40-123456 where the '+' is the international access code of whatever outside country you are calling from (mobile phones understand this) and the (0) is when dialling internally - something that would not be understood by a phone. Still, I think sadam/Fröstel are right in suggesting that just area-code local-number is the most readable and useful. Lastly, OJW pointed out on the email list that telephone= rather phone= has already been used informally - would there be any objection to changing the proposa to telephone= ? MikeCollinson 21:08, 14 November 2007 (UTC) I expect lots of numbers formatted in the local convention will end up in the database no matter what. The various dashes and spaces make it easier to memorise and transcribe the numbers correctly. Probably easier to embrace it than try to dictate a standard. Currently I'm using telephone_number and in the UK at least it's the most popular tag in use with ~50 occurrences. Perhaps telephone:number would be better. Then other telephone relating things can be added under the telephone "namespace" similar to how a few other tags do it. Thewinch 21:24, 14 November 2007 (UTC) - That's true. But I believe when running a proper proposal, discussing the issue and finally coming to an conclusion for now and ever on we shouldn't be influenced too much by existing (unofficial) tags. And apparently there are at least two used: telephone and telephone_number. So we have to make a choice anyway. And as always I'm going with a short tag, which would be just phone. I don't see any reason why phone would be inappropriate, but I'm not native. -- Fröstel 00:07, 15 November 2007 (UTC) - two questions here, which relate to this. i can't see a 'street_number' feature anywhere, for tagging the street number for a given building/land plot/etc. if street numbers were added to the map instead of phone numbers (easier than phone numbers, as they progress generally in jumps of 2, and don't need to be looked up individually), a database of phone numbers could then be parsed to automatically add the phone number of all the locations tagged with a street address? so, (1) should we propose a 'street_number' tag, and (2) are there any open databases of phone numbers that would allow us to use them to populate the map (e.g. what is the status of the info in white/yellow pages in a given country?) Myfanwy 22:15, 14 November 2007 (UTC) Why not uri:contact=tel:+99.99.99999998, uri:contact=fax:+999.99.99999999, uri:contact=mailto:info@example.net, and even uri:contact=? -- 3247 21:20, 1 January 2008 (UTC) - Before opening votes I considered all your comments. I totally see the digital beauty of url:phone= but I want to keep tags as intuitive as possible and url is something most people will have to look up. If this changes someday it will be a nobrainer to convert all phone-Tags to url:phone. I also realised that there are already telephone_number-tags around, but so are phone, telephone, phonenumber, phone_number and several more. Due to it's shortness I prefer phone which I herewith open for voting. -- Fröstel 20:06, 16 January 2008 (UTC) - There is an international standard on how to write international phone numbers: You have a plus (+) sign, then the country code and then the rest of the number. Any cell phone can dial those numbers directly regardless on where you are in the world. If you use a local number it will only work if you are in the same area. Also, because we don't have a list that ties a location to its area code it makes more sense to include the country code in the number, that way when you want to call a location from abroad you don't have to know the country code and you don't have to know what prefixes you have to add or remove etc. So if this tag gets accepted I suggest we document it in a way that international numbers are prefered. But knowing the real world, most people will probably ignore it. -- Joto 21:36, 16 January 2008 (UTC) - I'm not sure if this is the correct way to go. A phone number sounds useful, but the next person might find a mobile phone number even more useful. And then someone wants a business mobile number in addition to the private mobile number. And while we are adding things, how about a skype contact number oh and a secondary e-mail address. I think they might all be useful, but we would be adding lots of tags. How about something more generic? There is a good standard for all those contact information vCard. Not sure on how to add it to OSM, but I don't think adding lots and lots of tags is a good solution. --Ckruetze 21:37, 17 January 2008 (UTC) - Have you read the rationale? I don't see any reason to enter private phone-numbers in OSM and am strongly against it due to privacy. We're a map, neither a phonebook nor the yellow pages! I don't get your point about cellphones. When there's a remote cafe without a landline and a mobile instead, you can tag that number - but why use a different tag? But if you believe to improve things you're free to propose appendixes like phone:cell, phone:business and so on. -- Fröstel 23:20, 17 January 2008 (UTC) - I'm not sure if we aren't a phonebook or the yellow pages or maybe we want to become that in the future - I don't have an opinion about that. All I'm saying is, you see the need for a phone number, the next person might see the need for a mobile number and then someone might want the business skype number. If we go that way, do we want to add one tag after the next or do we want to use soemthing that is already out there that allows us to represent all of this information? If we want to add all the tags manually, maybe we should do it in one big proposal all at once, so that the names are consistant and we can vote once and use them all afterwards. --Ckruetze 13:21, 18 January 2008 (UTC) Voting Voting on this proposal has been closed. It was rejected with 5 votes for and 7 votes against. - I approve "phone=xy and fax=xy" (the "uri way" is more complicated without a benefit) -- Ulfl 03:05, 17 January 2008 (UTC) - I approve Bobkare 07:41, 17 January 2008 (UTC) - I approve "phone=+32-3 123 45 67 and fax=+32-15 65 43 21" (hyphen is optional) (It's trivial to know what will need to be dialed locally (0 or 9) depending on the country code, besides even from within the country the international way of dialing should work) --Polyglot 07:55, 17 January 2008 (UTC) - I disapprove of phone as amenity=telephone already exists. I think objects should be named consistently to avoid confusion where possible. --Thewinch 18:17, 17 January 2008 (UTC) - I disapprove this proposal because i think we should define a more generic set of tags (as contact:phone contact:fax contact:skype contact:email ...) --EdoM (lets talk about it) 18:23, 17 January 2008 (UTC) - I approve using phone=and fax=because this should be as simple as possible to encourage people to add this information. --Geoff 19:16, 17 January 2008 (UTC) - I disapprove this proposal. See my comments above. --Ckruetze 21:38, 17 January 2008 (UTC) - I approve phone=and - I disapprove of this proposal. this sort of data is best stored elsewhere (wikipedia, wikimapia, etc.), and referenced from the name and address of the location being marked. e.g. i wouldn't put the phone number of a restaurant, rather it's name, address (when street numbers are finalised), and operator. what next, the entire menu of the restaurant? Myfanwy 22:45, 24 January 2008 (UTC) - I disapprove of this proposal. The contact system suggested by EdoM would be better. I'd also approve of this proposal if it were simply adding contact:phone=* (allowing other contact methods to be added easily) --Hawke 16:56, 19 March 2008 (UTC) - I disapprove of phone as amenity=telephone exists. This will only cause confusion. Enhance existing tags where necessary instead of creating new ones. However OSM should not become a store for all sorts of information which should be logically placed elsewhere. -- Netman55 09:27, 21 March 2008 (UTC) - I disapprove of this proposal. I will use as long as no other conclusion is made, the system suggested by EdoM, using contact:phone, contact:email, ... . I hope there will be some nice Preset for this feature (maybe even with address) --dieterdreist 16:08, 16 April 2008 (UTC) Voting ended on Apr 16th 2008 and the proposal was labelled "Rejected (inactive)"... Despite this, the tag has been used extensively by mappers. Usage found on OSMdoc August 2009 : - phone - 7200 - contact:phone - 724 - telephone - 297 - addr:telephone - 153 - telephone_number - 49 - phone_number - 6 The tag has been documented at Key:phone TODO: Clarify status. Propose again? See also - Proposed_features/Info_on_web-presence - Refering to Websites - phone=*
https://wiki.openstreetmap.org/wiki/Proposed_features/Phone
CC-MAIN-2019-39
refinedweb
2,156
68.81
This section shows how to use the plug-in API to convert entries that are represented in LDIF to Slapi_Entry structures. This section also shows how to convert Slapi_Entry structures to LDIF strings. LDIF files appear as a series of human-readable representations of directory entries, and optionally access control instructions. Entries that are represented in LDIF start with a line for the distinguished name. The LDIF representation continues with optional lines for the attributes. The syntax is shown in the following example. dn:[:] dn-value\n [attribute:[:] value\n] [attribute:[:] value\n] [single-space continued-value\n]* A double colon, ::, indicates that the value is base64-encoded. Base64-encoded values can, for example, have a line break in the midst of an attribute value. As shown in the preceding example, LDIF lines can be folded by leaving a single space at the beginning of the continued line. Sample LDIF files can be found in install-path/ldif/. Refer to Chapter 13, Directory Server LDIF and Search Filters, in Sun Java System Directory Server Enterprise Edition 6.0 Reference for details on LDIF syntax. You can achieve this type of conversion by using slapi_str2entry(). The function takes as its two arguments the string to convert and an int holding flag of the form SLAPI_STR2ENTRY_* in slapi-plugin.h. The function returns a pointer to a Slapi_Entry if successful, NULL otherwise, as shown in the following example. #include "slapi-plugin.h" #define LDIF_STR "dn: dc=example,dc=com\nobjectclass: \ top\nobjectclass: domain\ndc: example\n" int test_ldif() { char * ldif = NULL; /* Example LDIF string */ Slapi_Entry * entry = NULL; /* Entry to hold LDIF */ char * str = NULL; /* String to hold entry */ int len; /* Length of entry as LDIF */ /* LDIF to Slapi_Entry */ entry = slapi_entry_alloc(); ldif = slapi_ch_strdup(LDIF_STR); entry = slapi_str2entry(ldif, SLAPI_STR2ENTRY_ADDRDNVALS); slapi_ch_free_string(&ldif); if (entry == NULL) return (-1); /* Slapi_Entry to LDIF */ str = slapi_entry2str(entry, &len); if (str == NULL) return (-1); slapi_log_info_ex( SLAPI_LOG_INFO_AREA_PLUGIN, SLAPI_LOG_INFO_LEVEL_DEFAULT, SLAPI_LOG_NO_MSGID, SLAPI_LOG_NO_CONNID, SLAPI_LOG_NO_OPID, "test_ldif in test-entries plug-in", "\nOriginal entry:\n%sEntry length: %d\n", str, len ); slapi_entry_free(entry); return (0); } Here, SLAPI_STR2ENTRY_ADDRDNVALS adds any missing relative distinguished name (RDN) values, as specified in slapi-plugin.h where supported flags for slapi_str2entry() are listed. You can achieve this type of conversion by using slapi_entry2str(). This function takes as its two arguments the entry to convert and an int to hold the length of the string that is returned. The function returns a char * to the LDIF if successful, NULL otherwise, as shown in Example 38–3.
https://docs.oracle.com/cd/E19693-01/819-0996/aahee/index.html
CC-MAIN-2018-05
refinedweb
414
52.39
I just starting with Python, been doing HTML, CSS, PHP and SQL for 8 years. Moving my way towards computer based programming. Now that my past is out of the way, here is my problem. Challenge # 4 on Euler, find the largest Palindrome number from the product of two 3-digit numbers. I did a flowchart, and I think it will work, but it's not printing anything. Here is my code: - Code: Select all def ans_rev(ans): return int(str(ans)[::-1]) def main(): i = 9 while i <= 9 & i > 0: a = 9 ans = a * i pal = ans_rev(ans) if ans == pal: print(ans) else: print('. ') i = i - 1 I was going to start small (1 digit numbers), and work my program up to 3-digit numbers. I know I will need to cycle a for when i reaches 0, but I know the largest here is (9 * 6 = 55). Question is, why doesn't it print anything? If I understand the why, I can solve for that problem.
http://www.python-forum.org/viewtopic.php?f=27&t=4020
CC-MAIN-2015-14
refinedweb
170
80.62
add detach / delete events, ensure full lifecycle / state tracking is possible According to documentation after_attach event should be generated for add(), merge(), and delete() calls. But the last doesn't work. Here is a code sample to reproduce the problem: from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, create_engine, event from sqlalchemy.orm import sessionmaker, Session Base = declarative_base() class Obj(Base): __tablename__ = 'objs' id = Column(Integer, primary_key=True) engine = create_engine('sqlite://', echo=True) Base.metadata.create_all(engine) session = sessionmaker(bind=engine)() class EventHandlerIsCalled(Exception): pass obj = Obj() session.add(obj) session.commit() @event.listens_for(Session, 'after_attach') def after_attach(session, instance): raise EventHandlerIsCalled() try: session.delete(obj) except EventHandlerIsCalled: pass else: assert False, 'after_attach event is not generated' A fix for 0.7 branch: ah. well actually, in that example the object is already attached, so the fact that the method isn't being called is not a bug. The documentation should instead be clarified. If you expunge(obj) first, then delete(), the method is called. It's clear that people really want just plain old "on mark as delete" so I'd rather add that separately. the event would probably benefit from an additional argument that states how the object got marked, as this can happen in several places (pre-flush cascade, during-flush cascade, etc). Some more info that might be useful for your decision. The problem I'm solving is in-app denormalization with quite complex computational logic that is hard to do with SQL. To solve it we have to handle attribute changes, object addition and deletion. Changes: We can use custom descriptors. We wrap all relevant attributes ( InstrumentedAttributeinstances) with proxy descriptor class that does additional job when attribute is set. The setevent is useless (or inconvenient at least) here since it's generated ''before'' attribute is set, so I can't run existing methods, but have to duplicate (rewrite) each of them for each attribute they depend on. Also I see no simple way to use my own subclass of InstrumentedAttribute. Addition: after_attachcould be used here, but in real life all needed objects we are interested in have relation attribute set. So we just use the same descriptor wrapping described above. Removal: Right now I see no way to catch that Obj.o2m_rellooses some object and use it in some denormalization code: removeevent is generated for one way of modifying only and before_deleteand after_deleteare too late to modify objects that are not in dirty state (parent object). It looks weird to me that I can't use events at all for the task that I believe should be rather solved with events. so you don't actually care about attach or delete, you want attribute "after" events, is that all ? can you be more specific here? what's "one way" and what would be the "other way" ? Right now I need some way to catch Obj.o2m_rel changes (only through ORM methods, I don't care about direct SQL) to update denormalization counter field. Some obvious direct way is preferred, but it's ok to listen for some delete event on child class. Some sort of "detach" event would useful anyway. Also I'd like to use "after_set" in some ''other'' case, but I can live with hack of descriptor proxying I use right now. Actually it already breaks some code that automatically gathers info about fields (checks for isinstance(attr, InstrumentedAttribute)), but I believe I'll be able to fix it. Obj.o2m_rel.remove(child)- I haven't checked this case, but assume we have "remove" event here - that's "one way" I referred to Obj.o2m_rel = [list of children...](...new)- no "remove" event, no "set" event, can be handled with custom descriptor child.parent = other_parent, child.parent = None- no "remove" event, can be handled with custom descriptor session.delete(child)- I failed to find any solution to handle this except "before_delete" or "after_delete" + delayed (unfortunately I see no way to do this with handling something like "after_flush_postexec", only session redefinition with some registry of delayed actions) + redefined flush()to do actual flush multiple times while dirty objects exist. Replying to ods: this fires a remove event. not correct - this operation fires both remove and append events (but yes, before the fact) this fires off the "set" event, and the old value is given. adding an event for delete() is fine. this is what before_flush() is for, and it's where I usually do the kinds of things you're talking about. The problem with a "event after set" for the purpose of running a business method is that the event isn't after every aspect of the set operation. That is, if you did this: if that fires off an event that has the effect of appending/setting/removing another object somewhere else, then that operation has an event also. So if you had an "after set" handler that's triggered by a backref (which is "before set"), then your business methods are still not seeing the finished object structure - you're still ultimately inside of a "before set". Really, the traditional approach to running complex business methods when something happens is to define those use cases explicitly either in a service layer or within real methods on the object. The synonym() construct in particular is provided to allow a plain Python descriptor to wrap a database-mapped attribute, though in the spirit of KISS/explicit is better than implicit I'll really just do things the old fashioned way: short of that, before_flush() is where you can get at objects in their "complete" state, and you can use history to see everything that's changed, not to mention look inside of session.delete and such. It was my mistake, both remove and append work as advertised. Thank you very much for suggestion, but I failed to use "before_flush"event because objects ''are not'' in final state yet, that is Parent.childrencontain Childobjects that are deleted and don't contain new Childobjects yet. But this is already different story not related to the issue. so what are we doing here? "after_XYZ()" events are not something I can just casually add, especially for collections. It would add lots of overhead that all users would be impacted with - note that we're talking about adding a bunch more boxes to the upper right of this: - the image illustrates that "attribute set/append" operations already take nearly 25% of runtime overhead for a mutation-heavy application. Right now you should be able to make a subclass of InstrumentedAttributeand install it using the "attribute_instrument" event (replacing the existing InstrumentedAttribute), or a custom InstrumentationManager (a little awkward to set up, but doable). Using "proxies" around descriptors shouldn't be needed. For collections, yes you need proxies right now. I'd like to think of some system where the entire way that orm/collections.py instruments a class is based on some open ended and easily modified scheme. This would be close to a rewrite of the whole system. But I don't have a nice vision of how that would look anyway right now, at least one that wouldn't add crushing method call overhead, which IMHO is already too much - I'd like to remove calls from collections.py and further simplify the codepaths, not add any. The only clear to me for now is that SA missed "detach" event and it would be nice to clarify documentation (about "after_attach" and probably "before_flush"). The rest is not so obvious, your points are quite reasonable. I solved my task using "set", "append", "remove" to store a delayed action into a global (damn!) queue and executing them in the "before_flush" handler. This required reconstructing one-to-many relations before calculation manually with respect to session.newand session.deleted. And I had to attach "before_flush" listener to base Sessionclass, which looks dirty, but is ok for this project because it has only one session. for here I would like to: add detach() event, however docs need to stress that this can't be called in the case where the Session is garbage collected without close/expunge first add delete() event per #3517I'd like to see if we can allow full lifecycle tracking to occur; after_attach in particular doesn't provide any way of detecting an object that is new vs. persistent. Ideally every state transition we have at plus deleted should be easily trackable, but the challenge is keeping overhead low when these events are not in use. .SessionEventssuite now includes events to allow unambiguous tracking of all object lifecycle state transitions in terms of the :class: .Sessionitself, e.g. pending, transient, persistent, detached. The state of the object within each event is also defined. fixes #2677 deleted. This new state represents an object that has been deleted from the :term: persistentstate and will move to the :term: detachedstate once the transaction is committed. This resolves the long-standing issue that objects which were deleted existed in a gray area between persistent and detached. The :attr: .InstanceState.persistentaccessor will no longer report on a deleted object as persistent; the :attr: .InstanceState.deletedaccessor will instead be True for these objects, until they become detached. .Session.weak_identity_mapparameter is deprecated. See the new recipe at :ref: session_referencing_behaviorfor an event-based approach to maintaining strong identity map behavior. references #3517 → <<cset 108c60f460c7>>
https://bitbucket.org/zzzeek/sqlalchemy/issues/2677/add-detach-delete-events-ensure-full
CC-MAIN-2018-47
refinedweb
1,561
54.02
At a GREAT [Seattle Software Craftsmanshi meetup where David Bernstein gave a talk, there was a question at the end that really piqued my interest. The question was, paraphrased: How can we get tests for something using the HttpClient? This is a C# specific question - and ... well.... I happen to have AN answer for that. I'm sure there are a lot of ways to accomplish this, but here's where I've found success. BookEnd It! As I've talked about a few places - Abstract code you don't own! Where code meets Operating System Where our code meets their code Where our code meets the user We don't own the HttpClient and it doesn't even have an interface!!! What I do is create a wrapper around this object - a BookEnd that I control. internal class HttpClientBookEnd : IHttpClientBookEnd{ public readonly HttpClient _httpClient; public HttpClientBookEnd() : this(new HttpClient()){} private HttpClientBookEnd(HttpClient httpClient) => _httpClient = httpClient; public void SendRequestAsync(HttpRequestMessage msg) => _httpClient.SendRequestAsync(msg); } This is then used by a consuming class as class MakesCall : IMakesCall{ private readonly IHttpClientBookEnd _client; public MakesCall() : this(new HttpClientBookEnd()){} public MakesCall(IHttpClientBookEnd client) => _client = client; public void Call(HttpRequestMessage msg) => _client.SendRequestAsync(msg); } Note: HttpRequestMessage, as a class we don't control, should also have a BookEnd, but that's beyond the scope of what we're talking about here. How we're creating a BookEnd here will work pretty well as a drop in replacement, enabling much better testability. With the HttpClient removed from our code, and is instead using an interface we can unit test the MakesCall class. Code Integration Tests? The follow up to this change is how to do code level integration tests? It'll still new up the HttpClient and hit the network. This requires a bit of a hack. Or a polite term - a SHIM. Shim it! The shim violates most of my coding practices. There's one practice that really stands out - Logic MUST be testable. When we use 3rd party code, it can be hard to test the logic in the same class/method. This is unacceptable. It must be testable, and it must be testable in a fashion that has no dependencies. HttpClientBookEnd is untestable though... yes. It's also got ZERO logic. BookEnds are pass throughs. They shouldn't exist according to the rest of my principles and practices - but testability wins - This makes things testable with minimal smell in the rest of the code. Just to be clear - this is the edge of our system now, it gets slightly different rules to ensure the rest of our system is great code. I modify the BookEnd to include a shim of a _testClient. internal class HttpClientBookEnd : IHttpClientBookEnd{ private static HttpClient _testClient; #if DEBUG public static void SetTestClient(HttpClient testClient) => _testClient = testClient; #endif public readonly HttpClient _httpClient; public HttpClientBookEnd() : this(new HttpClient()){} private HttpClientBookEnd(HttpClient httpClient) => _httpClient = httpClient; public void SendRequestAsync(HttpRequestMessage msg) => Client().SendRequestAsync(msg); private HttpClient() => _testClient ?? _httpClient; } The shim allows a unit test to look like [TestMethod, TestCategory("unit")] public void ExampleShim(){ HttpMessageHandler fakeHttpMessageHandler = new FakeHttpMessageHandler(); HttpClient testClient = new HttpClient(fakeHttpMessageHandler); HttpClientBookEnd.SetTestClient(testClient); HttpClientBookEnd client = new HttpClientBookEnd(); client.SendRequestAsync(null); } A correctly configured HttpMessageHandler (an OLD example here) will allow customization of the responses to exactly what's being expected. In .netCore, use IHttpFilter instead of HttpMessageHandler. There's a few other differences as well, but that's a post for another day. Book End Using this BookEnd method has simplified my integration tests and increased my ability to do code-integration tests. The huge increase of testability allows me to get to 100% test coverage of everything that isn't the literal edge of the system.
https://quinngil.com/2018/09/02/bookend-for-httpclient/
CC-MAIN-2020-29
refinedweb
616
56.15
Migration to Vue 3 Preparations for a Vue 3 migration are tracked in epic &3174 In order to prepare for the eventual migration to Vue 3.x, we should be wary about adding the following features to the codebase: Vue filters Why? Filters are removed from the Vue 3 API completely. What to use instead Component’s computed properties / methods or external helpers. Event hub Why? $on, $once, and $off methods are removed from the Vue instance, so in Vue 3 it can’t be used to create an event hub. What to use instead Vue documentation recommends using the mitt library. It’s relatively small (200 bytes, compressed) and has a clear API: import mitt from 'mitt' const emitter = mitt() // listen to an event emitter.on('foo', e => console.log('foo', e) ) // listen to all events emitter.on('*', (type, e) => console.log(type, e) ) // fire an event emitter.emit('foo', { a: 'b' }) // working with handler references: function onFoo() {} emitter.on('foo', onFoo) // listen emitter.off('foo', onFoo) // unlisten Event hub factory We have created a factory that you can use to instantiate a new mitt-based event hub. This makes it easier to migrate existing event hubs to the new recommended approach, or to create new ones. import createEventHub from '~/helpers/event_hub_factory'; export default createEventHub(); Event hubs created with the factory expose the same methods as Vue 2 event hubs ( $on, $once, $off and $emit), making them backward compatible with our previous approach. <template functional> Why? In Vue 3, { functional: true } option is removed and <template functional> is no longer supported. What to use instead Functional components must be written as plain functions: import { h } from 'vue' const FunctionalComp = (props, slots) => { return h('div', `Hello! ${props.name}`) } It is not recommended to replace stateful components with functional components unless you absolutely need a performance improvement right now. In Vue 3, performance gains for functional components are negligible. Old slots syntax with slot attribute Why? In Vue 2.6 slot attribute was already deprecated in favor of v-slot directive. The slot attribute usage is still allowed and sometimes we prefer using it because it simplifies unit tests (with old syntax, slots are rendered on shallowMount). However, in Vue 3 we can’t use old syntax anymore. What to use instead The syntax with v-slot directive. To fix rendering slots in shallowMount, we need to stub a child component with slots explicitly. <!-- MyAwesomeComponent.vue --> <script> import SomeChildComponent from './some_child_component.vue' export default { components: { SomeChildComponent } } </script> <template> <div> <h1>Hello GitLab!</h1> <some-child-component> <template #header> Header content </template> </some-child-component> </div> </template> // MyAwesomeComponent.spec.js import SomeChildComponent from '~/some_child_component.vue' shallowMount(MyAwesomeComponent, { stubs: { SomeChildComponent } })
https://docs.gitlab.com/ee/development/fe_guide/vue3_migration.html
CC-MAIN-2021-21
refinedweb
447
50.73
I have after several months, finally got my RPI 3B+ running and have a sensor (SHT31-D) working on it. That's it after several months. Frustrated doesn't come close. But I got this far. I need help. Here's my code: Code: Select all import smbus import time # Get I2C bus bus = smbus.SMBus(1) # = -45 + (175 * temp / 65535.0) fTemp = -49 + (315 * temp / 65535.0) humidity = 100 * (data[3] * 256 + data[4]) / 65535.0 # Output data to screen print "Temperature in Celsius is : %.2f C" %cTemp print "Temperature in Fahrenheit is : %.2f F" %fTemp print "Relative Humidity is : %.2f %%RH" %humidity These are the problems I'm trying to overcome: 1. Have the sensor continue providing data more than one time when I type: sudo python sht31.py 2. have the data saved (data logging) 3. Have that data sent to my MySQL website I have created the database on my website and have the username, password and info for the database. I built my website so that's the easy part for me. This has take months to get this little amount of info. All help would be greatly appreciated.
https://www.raspberrypi.org/forums/viewtopic.php?f=32&t=216909&p=1334365
CC-MAIN-2020-29
refinedweb
194
78.75
Open Source Shopping Cart open source shopping cart. You can download and modify the source code... can modify source code of shopping cart as per your needs. The open...Open Source Shopping Cart Open Source Shopping carts software Shopping Cart design in development of shopping cart using open source technologies such as Java, .NET... for your site and use open source shopping cart of your choice to create online... source shopping cart: PRESTA shop OPEN Cart Magento using sstruts - Struts shopping cart using sstruts Hi, This is question i asked ,u send one link.but i cant able to ddownload the file .please send the code file. -------------- I need the example programs for shopping cart using struts Shopping Cart,Shopping Cart software Shopping Cart Overview A web based shopping cart is something like the original grocery shop shopping cart that is used by the customer in selecting certain Open Source Software . Open source software is very useful because source code also distributed... is also know as OSS. Simply open source means the availability of the Source code...Open Source Software In this section we are discussing Open source software Java is an opensource program or not? why??? Java is an opensource program or not? why??? Java is an open source program or not.. why Shopping cart Shopping cart Overview A web based shopping cart is something like the original grocery shop shopping cart that is used by the customer... information at the checkout counter. Software Shopping cart is used around the world Open Source e-commerce of e-commerce; a free, user-friendly, open source shopping cart system... an open source shopping cart as the engine behind your site gives you a thoroughly... code and J2EE best practices. Open Source E Shopping cart Application Shopping Cart Application  ... forum Download and build from source a) Preliminaries i) Tools required to build Simple Cart Shopping Cart Features Ideal Requirements Of Shopping Cart Most of the people think to use a shopping.... Using an shopping cart for your e-commerce site (Online Store) is just... store and make sure of that. Focus on the basic feature of the shopping cart Open Source PHP with phc. PHP shopping cart with open source code Most... by hindering competition and plagiarism. X-Cart is a software with open source code. We... with open source code is a good way to get the right features quickly.   hi i want the sample project for shopping cart in struts with mysql ,if any one knows means please help me Online Shopping Cart Solutions for a magnanimous image projection, then you need shopping cart software which... ahead of everybody in competition you need to focus on your shopping cart... Professional Shopping Cart Developers Can Bring Yield Great Profits source code source code sir...i need an online shopping web application on struts and jdbc....could u pls send me the source code E-commerce shopping cart hosting E-commerce shopping cart web hosting In this article we will explain you how to find best hosting company for hosting E-Commerce shopping cart. The good ecommerce shopping cart web hosting company is very import in success of online Open Source E-mail code for complete control. POPFile: Open Source E-Mail..., Darwin Streaming Server is an open source project intended for developers who need...Open Source E-mail Server MailWasher Server Open Source open source help desk Open Source Help Desk Open Source Help Desk Software As my help desk... of the major open source help desk software offerings. I?m not doing...?s out there. The OneOrZero Open Source Task Management Open Source Content Management code for open-source CMSes is freely available so it is possible to customize...Open Source Content Management Introduction to Open Source Content Management Systems In this article we'll focus on how Open Source and CMS combine online shopping project online shopping project can you plz send the source code of online shopping application developed with the help of struts 1.2, hibernate and sql , jsp Please visit the following link: Struts Shopping Cart Open Source Exchange ; DDN Open Source Code Exchange The DDN site... and there was clearly a need to facilitate this if the Open Source movement was going...Open Source Exchange Exchange targeted Open Source GPS Open Source GPS Open Source GPSToolKit The goal of the GPSTk project is to provide a world class, open source computing suite to the satellite.... Open Source GPS Software Working with GPS Shopping Cart Products Know To Sell The Right Products On E-Commerce Shopping Cart E-commerce... differently can you present them with your e-commerce shopping cart? What kind of offers... as this is the fastest way of shopping and shipping products to customers. Many online Open Source Jobs , and then we will focus on Quartz, an open source library for those who need some extra... need Quartz: the first full-featured, open source job scheduling framework... its original design free of charge. Open source code is typically created Open Source E-mail Server code for complete control. POPFile: Open Source E-Mail... is an open source project intended for developers who need to stream QuickTime and MPEG-4...Open Source E-mail Server MailWasher Server Open Source online shopping project report with source code in java online shopping project report with source code in java Dear Sir/Mam, i want to a project in java with source code and report project name online shopping. thank you E-commerce: Shopping cart E-commerce: Shopping cart  ...; E-Commerce ? role of a Shopping Cart Life has become so easy, no need to rush to the markets. Now shopping is just a click away. Well you got Online Shopping Cart Services Knowing About Online Shopping Cart Services The whole world has become... reasons, now people depend on e-commerce shopping cart. One of them is the security these websites provide. These shopping cart solutions offer the users to do source code - JSP-Servlet source code I want source code for Online shopping Cart. Application Overview The objective of the Shopping Cart is to provide an abstract view... functional application. System Scope Shopping Cart is a web application intended Project Management Open Source Project Management Open Source Project Management... to access our support forums. An Open-Source Based... provide these features thanks to the open-source nature of ]project-open Open Source Version Control ), a popular open-source application within which many developers store code...-only CVS access. Open Source code version control...Open Source Version Control CVS: Open source version control CVS Open Source Books Open Source Books Open Books O'Reilly has published a number... books. Open Source Revolution Linux creator Linus... for the Open Source community in the story of Pauling's foundational work that made Open Source Community , open source or not; neither open source nor proprietary code should be considered...Open Source Community Open Source Research Community In the spirit of free and open source software (F/OSS), we are attempting to establish Web hosting with shopping cart Web hosting with shopping cart If you are looking for hosting your shopping... web hosting company you should use for hosting your shopping cart applications. Which hosting with shopping cart support should be used and what Open Source web mail Open Source web mail Open Web Mail Project Open WebMail... Outlook to Open WebMail.Open WebMail project is an open source effort made... WebMail project is working to accomplish. Open Open Source Business Model with publication of their source code on the Internet, as the Open CASCADE...Open Source Business Model What is the open source business model It is often confusing to people to learn that an open source company may give its Features of shopping cart Features of shopping cart In this section we will learn the features of good shopping cart applications. There are shopping cart application on the Internet... on requirement and you can select best shopping cart application for your shopping, Open-source Open Source Movement reviews the development and need for Free and Open Source movements in software...Open Source Movement Open source movement Wikipedia The open source movement is an offshoot of the free software movement that advocates Need source code - Swing AWT Need source code Hai, I need a idea and code for developing the project "Face Recognition" with the backend as My-sql.... Thanks & Regards Outlook , vertically locked down world; we need an open source solution for extracting... of the code base and hosting the additions on the same open source basis.  ... Open Source Outlook Open Source Outlook Sync Tool Calendaring Need Java Source Code - JDBC Need Java Source Code I have a textfield for EmployeeId in which the Id, for eg: "E001" has to be generated automatically when ever i click... be implemented. Hi friend, Please send me code because your posted Open Source Accounting Software and need a proper evaluation when making computer decisions. While open source...Open Source Accounting Software Open Source Accounting Software TurboCASH .7 is an open source accounting package that is free for everyone CMS proprietary products, the source code for open-source CMSes is freely available...Open Source CMS Open Source Content... and developers of Open Source Content Management solutions. OSCOM organizes Need source code - Swing AWT Need source code Hai friends, How can I, view all the datas from the mysql database table in the jframe........ Hi Friend, Try the following code: import java.awt.*; import java.sql.*; import Need source code - Swing AWT Need source code Hai, In java swing, How can upload and retrieve the images from the mysql database? Hi Friend, To upload and insert image in database, try the following code: import java.sql.*; import Open Source Reports Open Source Reports ReportLab Open Source ReportLab, since its early beginnings, has been a strong supporter of open-source. In the past we have found the feedback and input from our open-source community an invaluable aid Error in Shopping Cart project - Development process Error in Shopping Cart project I tried running the shopping cart project given in the below link:... when I submit "" I received the following error Microsoft Open source is inferior. Open Source Code Finds Way into Microsoft... code and other data, hardcore open source advocates will no doubt argue... source code and other data, hardcore open source advocates will no doubt argue SHOPPING COUNTER SHOPPING COUNTER i need to do the system about the item from the small shop. how can i calculate the item with price. if user choose more quantity... the java. thanks for helps. Hi Friend, Try the following code Open Source Groupware solutions Simple open source groupware Need groupware... Open Source Groupware Open Groupware Open Group... Software This list is focused on open source software projects relating Shopping Cart Application installation manual missing Shopping Cart Application installation manual missing Hi, I downloaded this Shopping cart zip folder from but there's no installation manual inside Open Source Blog Open Source Blog About Roller Roller is the open source blog server...; The Open Source Law Blog This blog is designed to let you know about developments in the law and business of open source software. It also provides Open Source Software Open Source Software Open Source Software Open source doesn't just mean access to the source code. The program must include source code, and must allow distribution in source code source code source code hellow!i am developing a web portal in which i need to set dialy,weekly,monthly reminers so please give me source code in jsp XML Editor benefits: it?s Open Source, so you can see the code. As a set of Cocoa classes it?s...Open Source XML Editor Open source Extensible XML Editor... * multi-platform (Java 1.3+) * free open-source software   Open Source Code Open Source Code What is SOAP SOAP is a protocol for exchanging.... Open source code in Linux If the Chinese have IT, get...-writing it. Open-source code quality The open MySql Open Source . Under the Open Source License, you must release the complete source code for the application that is built on MySQL. You do not need to release the source code...MySql Open Source MySQL Open Source License MySQL is free use for those Open Source VoIP Open Source VoIP/TelePhony Open source VoIP/Telephony One of the first open source VoIP projects -and one of the earliest VoIP PBXes... for the platform, both commercial and open POS Open Source POS Open-source POS system This past weekend People's... out items on the world's first entirely free, open-source point-of-sale system... copying the source code and also prevents anyone from getting inside to mine data Open Source SQL Open Source SQL Open Source SQL Clients in Java SQuirreL SQL Client.... The minimum version of Java supported is 1.3. iSQL-Viewer is an open-source JDBC 2.x... out common database tasks. Open Source: Data from MS SQL Open Source content Management System Open Source content Management System The Open Source Content Management System OpenCms is a professional level Open Source Website Content... existing modern IT infrastructure. OpenCms runs in a "full open source" environment in need od source code - Development process in need od source code i am in the process of developing..., module, activity, and no of hours worked from week start to weekend... i need a source code for creating the front end, and for database, and linking from front end Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://www.roseindia.net/tutorialhelp/comment/95610
CC-MAIN-2015-40
refinedweb
2,272
72.05
[ffe] Please merge mypaint 0.8.2-1 (universe) from Debian testing (main). Bug Description Binary package hint: mypaint Just a lot of fixes, however, a key change is improved international support... for details look at the copy of the change log below... Version 0.8.0 Changelog: - many new brushes contributed by various artists - brushes organized into groups - straight lines are possible (hold shift) - basic layer dialog - select brush from a stroke on the canvas - improved color picker, show color while picking - tools stay at top, only one taskbar entry (depending on your wm) - faster zoomed-out view (30x speedup in some cases) - i18n support added, translations in several languages - new and revised color selectors - big background patterns are possible (with limitations) - can save all layers as numbered PNGs - some drag&drop support - many other minor enhancements and bugfixes Those packages might need to be repackaged for ubuntu - I think numpy might be installed in a different place on debian, and I'm getting this: ImportError: No module named numpy.core. python-numpy is installed fine, the ubuntu version of mypain works fine. Importing numpy.core. naught101@ ImportError: No module named numpy.core. We are not correctly installed or compiled! script: "/usr/bin/mypaint" deduced prefix: "/usr" lib_shared: "/usr/share/ lib_compiled: "/usr/lib/mypaint/" Traceback (most recent call last): File "/usr/bin/mypaint", line 98, in <module> datapath, confpath, localepath = get_paths() File "/usr/bin/mypaint", line 55, in get_paths from lib import mypaintlib File "/usr/share/ import _mypaintlib ImportError: numpy.core. We have to merge the Debian package, because 0.8.0-2 still hardcodes the Python dependencies. We are past the feature freeze. Therefore we need an exception for merging Debian's version. Please follow the freeze exception process [1] and provide the required information. [1] https:/ debian's got version 0.8.2-1 now, i guess it's best if you take that version? Testing: I've started mypaint, painted some (using a normal mouse) and exited the app. I've not used the application before and therefore cannot test it really, apart from that it's not completely broken. Install log: $ sudo dpkg -i mypaint_ Wähle vormals abgewähltes Paket mypaint. (Lese Datenbank ... 338615 Dateien und Verzeichnisse sind derzeit installiert.) Entpacke mypaint (aus mypaint_ Wähle vormals abgewähltes Paket mypaint-data. Entpacke mypaint-data (aus mypaint- Richte mypaint-data ein (0.8.2-1ubuntu1) ... Richte mypaint ein (0.8.2-1ubuntu1) ... Verarbeite Trigger für menu ... Verarbeite Trigger für man-db ... Verarbeite Trigger für hicolor-icon-theme ... Verarbeite Trigger für python-gmenu ... Rebuilding /usr/share/ Verarbeite Trigger für desktop-file-utils ... Verarbeite Trigger für python-support ... ACK, FFe granted. two tiny notes: * please revisit your changelog entry, you got the bug number twice ;) * looking at http:// Thanks, Stefan. I just made a comment regarding python-protobuf version issue in Debian: http:// Stefan, re point 2: are you saying it should depend on python-protobuf >= 2.2.0a-0.1 ? Daniel, I'm saying that debian #570685 suggests that a depends on python-protobof >= 2.2.0a-0.1 might be in order. @Jon, there's no package named protobuf... are your referring to something embedded within mypaint? Sorry about that, I was referring to protobuf-compiler. Jon, thanks, that clears things up! Since mypaint (0.8.2-1) build-depends on protobuf-compiler and depends on python-protobuf, I assume that adding the version to python-protobuf in the dependencies would be the right thing (even better if there were an automatic way to get the dependency sorted from the build-dependency, but I guess that's just whishful thinking) This bug was fixed in the package mypaint - 0.8.2-1ubuntu1 --------------- mypaint (0.8.2-1ubuntu1) lucid; urgency=low * Merge from debian testing. (LP: #515016) Remaining changes: - debian/control: Don't hardcode python dependencies. * debian/control: Add versioned dependency on python-protobuf (>= 2.2.0a-0.1) (LP: #515016, Closes: #570685) mypaint (0.8.2-1) unstable; urgency=low * New upstream version. * Added watch file. * Add missing dependency to python-gtk2. (Closes: #571600) * Switch to dpkg-source 3.0 (quilt) format to avoid repackaging. mypaint (0.8.0-2) unstable; urgency=low * Bump standards version. * debian/cntrol: add depends for python-protobuf. (Closes: #568958) * Add debian/manpages so the manual page gets installed. mypaint (0.8.0-1) unstable; urgency=low * New upstream version. * debian/changelog: Updated copyright year. * debian/control: Add build-depends for protobuf-compiler. * debian/control: Add depends for python-numpy. (Closes: #551322) -- Daniel Hahler <email address hidden> Mon, 12 Apr 2010 00:18:23 +0200 0.8.0 just got accepted for Debian Unstable: packages. qa.debian. org/m/mypaint. html http:// Hoping you will sync this. That would also solve bug #493366 /bugs.launchpad .net/ubuntu/ +source/ mypaint/ +bug/493366 https:/
https://bugs.launchpad.net/ubuntu/+source/mypaint/+bug/515016
CC-MAIN-2018-13
refinedweb
799
51.95
If you’re like me, you enjoy the occasional Woot! Off. If you aren’t like me, there’s a good chance you don’t even know what a Woot! Off is. Hell, you probably don’t even know what Woot! is. If you aren’t familiar with Woot!, you should checkout an article I wrote a while back called “woot! woot! woot! woot!“. Catchy title, huh? Anyways, a Woot! Off is basically an event that happens periodically where the guys at Woot! sell off their inventory one item after the other until everything is gone. Unlike their normal routine of only having one deal a day, a Woot! Off can have several items in a short amount of time. It’s their way of cleaning house. But, you’ve gotta be quick if you want to land some of the good stuff as it goes quick! You have to constantly refresh your browser to see when something new has arrived. That’s what lead me to writing this article. Instead of constantly hitting the refresh button in your browser, waiting for something new to arrive, wouldn’t it just be easier to write a quick tool that would poll Woot! for you? Yep. I thought so too. So, being the geek that I am, I fired up my Python Idle GUI and started hammering out some code to that will check with Woot! every 60 seconds and print out each item. This tool is a simple screen scraper that downloads the HTML code from Woot! and uses regular expressions to search for certain pieces of code, the pieces that contain things like item name and price. I’ve written other articles showing how to create screen scrapers using Python. For this tool, I basically used the same thing, but added one extra class that provides me with a timer function which will be used to repeat the Woot! check every minute. I’m sure there are other ways of creating timers and I know there are all kinds of modules out there that do this for me. But, this was a small chunk of code that I used in another project and decided it would be an easy fit here as well. So, without further ado, here is the Python code I wrote for scraping Woot! and printing out the current item. import urllib, sgmllib import re from threading import Event, Thread class RepeatTimer(Thread): def __init__(self, interval, function, iterations=0, args=[], kwargs={}): Thread.__init__(self) self.interval = interval self.function = function self.iterations = iterations self.args = args self.kwargs = kwargs self.finished = Event() def run(self): count = 0 while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) count += 1 def cancel(self): self.finished.set() class Woot(sgmllib.SGMLParser): def __init__(self, verbose = 0): sgmllib.SGMLParser.__init__(self, verbose) self.', s) if m: return m.group(1) else: return "" def get_item_price(self): s = self.get_content() m = re.search('<span class="amount">(.*?)</span>', s) if m: return "${0}".format(m.group(1)) else: return "N/A" woot = Woot() def check_woot(): print "n" print woot.get_item_title() print woot.get_item_price() woot.close() r = RepeatTimer(60.0, check_woot) r.start() If you run this code from your Idle GUI, you should see something that looks like this: You can change the wait time for the check to run by changing the first parameter passed to the RepeatTimer class at line 62 above. This parameter is defaulted to 60 seconds. Feel free to extend this code by using IronPython or something similar to fire alerts when a new item is available. I was going to do that in this article, but decided against it as I’ve also created a C# version which I’ll be explaining in my next article. As always, please leave any questions, comments, and / or suggestions in the comments area below. PayPal will open in a new tab.
http://www.prodigyproductionsllc.com/articles/programming/python-woot-off-notifier/
CC-MAIN-2017-04
refinedweb
671
77.43
and structs are essentially the same. In fact, the following struct and class are effectively identical: Note that the only significant difference is the public: keyword in the class. We will discuss the function of this keyword in the next lesson. Just like a struct declaration, a class declaration does not allocate any memory. It only defines what the class looks like. Warning Just like with structs, one of the easiest mistakes to make in C++ is to forget the semicolon at the end of a class declaration. This will cause a compiler error on the next line of code. Modern compilers like Visual Studio 2010 will give you an indication that you may have forgotten a semicolon, but older or less sophisticated compilers may not, which can make the actual error hard to find. Class (and struct) definitions are like a blueprint -- they describe what the resulting object will look like, but they do not actually create the object. To actually create an object of the class, a variable of that class type must be defined: Member Functions In addition to holding data, classes (and structs) instance. With normal non-member functions, a function can’t call a function that’s defined “below” it (without a forward declaration): With member functions, this limitation doesn’t apply: Member types In addition to member variables and member functions, classes can have member types or nested types (including type aliases). In the following example, we’re creating a calculator where we can swiftly change the type of number it’s using if we ever need to. class Output 7 123 7 123 In such a context, the class name effectively acts like a namespace for the nested type. From inside the class, we only need reference number_t. From outside the class, we can access the type via Calculator::number_t. number_t Calculator::number_t When we decide that an int no longer fulfills our needs and we want to use a double, we only need to update the type alias, rather than having to replace every occurrence of int with double. int double Type alias members make code easier to maintain and can reduce typing. Template classes, which we’ll cover later, often make use of type alias members. You’ve already seen this as std::vector::size_type, where size_type is an alias for an unsigned integer. std::vector::size_type size_type Nested types cannot be forward declared. Generally, nested types should only be used when the nested type is used exclusively within that class. Note that since classes are types, it’s possible to nest classes inside other classes -- this is uncommon and is typically only done by advanced programmers. ability to have member functions.! Quiz time Question #1 The following main function should execute: and produce the output: Pair(1, 1) Pair(2, 2) Show Solution (h/t to reader Pashka2107 for this quiz idea) b) Why should we use a class for IntPair instead of a struct? using number_t = int; for (Calculator::number_t result : calculator.m_resultHistory); What do you mean by those two sentences? That's a type alias and a range-based for-loop. See lesson 6.13 and P.6.12a "For example, it’s fair to assume a class will clean up after itself (e.g. a class that allocates memory will deallocate it before being destroyed), but it’s not safe to assume a struct will." In the next section (8.3) you explain that structs and classes are essentially the same. I felt a bit uncertain about this passage quoted. Maybe it would be more clear to say "class will be written to": "For example, it’s fair to assume a class will be written to clean up after itself (e.g. a class that allocates memory will deallocate it before being destroyed), but it’s not safe to assume a struct will." Your recommendation to differentiate between structs and classes is mostly a convention as I understand it. Quiz 1: I couldn't understand why the code in "Member types" example: created double output as: 7 123 7 123 The first 7 123 is from these lines The loop prints another 7 123 When we call “y.print()” at line 16, Does the compiler interpret m_year as y.m_year or x.m_year at line 12? Thanks Every member function has a hidden parameter that is the object it's called on. We explain the this-pointer later in this chapter. So after learning about classes, I decided to try my hand at building a maze generator. Cool idea, right? My issue (which was my problem originally with C) was that the following function will not compile correctly: I know why, I know where, but I don't know how to fix it. I can't return -1, I can't return false because it's not a reference... am I totally stuck? One solution I thought of is having a dummy cell... but that is just clunky. I don't want to remove my error checking (god knows I am horrible at implementing algorithms the first time through), but I don't want to sprinkle bound checking into every algorithm loop I write to generate the maze with, either. So... ideas as to how to fix my issue would be appreciated Change the return type to `Cell*` and return a `nullptr`. Pointers are the same as references, but can be `nullptr`. You say that global variables are evil, but member variables are kind of global inside class. I mean functions with full access to variables and they are not protected in any way. Doesn't this contradict? No. Global variables are evil because any function in the entire program can change their values. Member variables can (typically) only be accessed by the members of the class, and even if access functions are provided, those access functions are only accessible by functions that have access to the object. ok, thanks... on repl.it a .cquery file can be added to configure the compiler... I'm trying to do the quiz, but in Repl.it , the solution gets compiler error at line IntPair p2{ 2, 2 }; [cquery] expected ';' at end of declaration You need C++11 or newer to use brace initialization. On a quick glance, I can't find a way of changing compiler settings on repl.it. If you don't need user input, you can use godbolt Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/
CC-MAIN-2020-29
refinedweb
1,090
63.19
- n Numbers In this article, you will learn and get code on adding of n numbers (or finding sum of n numbers) given by user at run-time using C++ program. For example, if user enters the value of n as 5. Then the program further asks to enter any 5 numbers. So that it can add all the 5 entered numbers and print its summation result as output. Here are the list of approaches that are used to do the task of adding n numbers: - Find sum of n numbers using for loop - using while loop - using array - using user-defined function At last of the article, you will also see a program that adds n natural numbers. To add n numbers in C++ programming, you have to ask from user to enter the value of n (i.e., how many numbers he/she wants to enter), then ask to enter n numbers to perform the addition of all the given numbers and finally display the result on the screen as shown here in the following program. Find Sum of n Numbers using for Loop This program is created using for loop to do the job. The question is, write a program in C++ to find and print the sum of n numbers using for loop. And here is the answer to this question: #include<iostream> using namespace std; int main() { int i, n, num, sum=0; cout<<"How many numbers you want to enter ? "; cin>>n; cout<<"Enter "<<n<<" numbers: "; for(i=0; i<n; i++) { cin>>num; sum = sum+num; } cout<<"\nSum of all "<<n<<" numbers is "<<sum; cout<<endl; return 0; } This program was build and run under Code::Blocks IDE. Here is its sample run: Now supply or enter the value of n (that how many numbers you wants to enter and add them up) say 5. And then enter any 5 numbers. Press ENTER key to see the following output, that will be the summation of all the 5 numbers entered by user at run-time: The program is very simple. That is, received the value of n first, and then created a for loop that runs n number of times to get all the numbers and add them up one by one. Therefore, if user enters the value of n as 5, then the dry run of above program goes like: - Inside for loop, initially 0 gets initialized to i and checks the condition, that is whether the value of i is less than n's value or not - Condition evaluates to be true, therefore program flow goes inside the loop, and receives a number inside a variable say num - And sum+num gets initialized to sum every time after receiving the number - Because, the initial value of sum is 0, therefore at first execution of for loop, suppose user enters first number as 10. Therefore, 0+10 or 10 gets initialized to sum. Now sum=10 - Program flow goes to update part, and increments the value of i and again checks the condition - The condition again evaluates to be true for second time, and program flow again goes inside the loop, and executes the two statements. That is, receives a number say 20 and initializes sum+20 or 10+20 as the new value of sum. Therefore, now sum=30 - In similar way, process the operation - The loop executes terminates, when its condition evaluated to be false - After exiting from the loop, we'll have a variable sum that holds the summation value of all the n numbers entered by user - Therefore, simply prints its value as output What if Number(s) contains Decimal ? To handle with real numbers (numbers having decimal part), use the float data type instead of int. Therefore just replace the following statement as given in above program: int i, n, num, sum=0; with the statement given below: float i, n, num, sum=0; Rest of the things will be same. Sum of n Numbers using while Loop The question is, write a program in C++ that find and prints the sum of n given numbers using while loop. The answer to this question is given below: #include<iostream> using namespace std; int main() { int n, i=0, num, sum=0; cout<<"Enter the value of n: "; cin>>n; cout<<"Enter "<<n<<" numbers: "; while(i<n) { cin>>num; sum = sum+num; i++; } cout<<"\nSum = "<<sum; cout<<endl; return 0; } The output produced by above program looks like: Unlike for loop, in while loop we have to initialize the loop variable before the start of while loop. As it only contains the condition statement, therefore we also have to place the updatation part inside the loop's body. Therefore, the value of i gets initialized before the loop and its value gets updated using the last statement of its body. Add n Numbers using Array This program uses array to do the same job as of previous program. #include<iostream> using namespace std; int main() { int n, i, arr[50], sum=0; cout<<"Enter the value of n (max. 50): "; cin>>n; cout<<"Enter "<<n<<" numbers: "; for(i=0; i<n; i++) { cin>>arr[i]; sum = sum+arr[i]; } cout<<"\nSum = "<<sum; cout<<endl; return 0; } Here is its sample run with same input as of previous output: All the numbers gets stored inside the array in a way that: - First number gets stored at arr[0] - Second number at arr[1] - Third at arr[2] - and so on Add n Numbers using Function This is the last program on adding n numbers. This program is created using a user-defined function named findSum() to do the same job. This function receives array and its size as its two argument or parameters. The array are the list of numbers, and size is the value of n. Further it finds summation of all numbers in the list and returns it. That is, its return value gets initialized to sum inside the main() function: #include<iostream> using namespace std; int findSum(int [], int); int main() { int n, i, arr[50], sum; cout<<"Enter the value of n (max. 50): "; cin>>n; cout<<"Enter "<<n<<" numbers: "; for(i=0; i<n; i++) cin>>arr[i]; sum = findSum(arr, n); cout<<"\nSum = "<<sum; cout<<endl; return 0; } int findSum(int arr[], int n) { int i, sum=0; for(i=0; i<n; i++) sum = sum+arr[i]; return sum; } This will produce the same output as of previous one. Find Sum of n Natural Numbers in C++ This program adds first n natural number. The value of n must be entered by user. For example, if the value of n gets entered by user as 5. Then the following program will find out the sum of first 5 natural numbers. That will be 1, 2, 3, 4, 5. Therefore, its summation will be 1+2+3+4+5 equals 15 #include<iostream> using namespace std; int main() { int i, n, sum=0; cout<<"Enter the value of n: "; cin>>n; for(i=1; i<=n; i++) sum = sum+i; cout<<"\nSum of first "<<n<<" natural numbers = "<<sum; cout<<endl; return 0; } The sample run of above program with user input as 10 will looks like: Same Program in Other Languages « Previous Program Next Program »
https://codescracker.com/cpp/program/cpp-program-add-n-numbers.htm
CC-MAIN-2022-21
refinedweb
1,222
60.48
I was recently working with a customer which uses the Transport Express (TE) tool for transporting changes through their BPC landscape. Their requirement was to update Development and Quality systems using Production in order to align the technical name of all the BPC dimensions and attributes. Following are the steps I had to take to ensure a successfully restored system using the Production backup file. 1) Disable the Transport Express settings. This step will require a Basis Resource to perform the disabling. This is a mandatory requirement as whenever a change is made in the system (in this case delete) it will trigger a TE request in the background but the deletion log was not capturing this and the successful delete message was in fact misleading. 2) Delete the BPC Environment that needs to be restored by using the program UJS_ACTIVATE_CONTENT and selecting “Clean the Environment” 3) Make sure that the /CPMB/”Environment ID” node is deleted 4) Check that all the BPC items are deleted by checking that there are no items with a technical name starting with /CPMB/* under the “Unassigned Nodes”. If the Transport Express tool was active when executing step 2, you will find items here. Following is an example of 2 items that were not deleted but moved to “Unassigned Nodes” 5) If there are scrap items that were not cleared, use the program UJAA_CLEAN_DELETED_APPSET to delete the items. APPSET: is the Environment ID APPS_PFX: this parameter is the environment’s technical name prefix. The prefix are the first 2 characters after the /CPMB/ namespace. In the following example the values are “FU”. Example of technical name prefix 6) If the log shows items were not deleted then manually delete the remaining items (this might require you to delete some internal tables as well, the reference of the table will be indicated in the delete log). Example of log 7) When all items for the environment that need to be restored are deleted, run transaction UJBR It is important to select “Use Tech Names from Backup Files” in order to maintain the same technical names. In our case, we had to load the backup file on the server /usr/sap/trans/ as the file was 1.4 GB and the program would error when it was trying to read from the local PC. The restore will start with building the BPC structures and then load the master data. In this example I restored both Metadata and Master Data at once but this uses up a lot of resources and I would overall suggest to Restore Metadata Tables first and then Master Data. 8) The ultimate check is to connect to the BPC admin and see if all the models, dimensions, business rules etc are visible. If all the structures are in, go into each dimension and check whether the master data is in. 9) Reactivate the TE tool.
https://blogs.sap.com/2016/09/07/bpc-10-backup-and-restore-with-transport-express/
CC-MAIN-2018-05
refinedweb
483
56.79
Static Web Service¶ When serving HTML5 Web clients from Crossbar.io, the static web assets for your frontends like HTML, JavaScript and image files need to be hosted somewhere as well. You can host static content on your existing (external) Web server or a static hosting service like Amazon S3. It does not matter if your Crossbar.io nodes reside on domain names different from the static content. But you can also let Crossbar.io host the static assets. This is useful and convenient, since you then don’t need an external Web server just to serve your static content. Configuration¶ The Static Web Service is configured on a subpath of a Web Transport and allows to expose static Web content. The Web content served can come from two sources: directories on the filesystem resources within Python packages To configure a Static Web Service, attach a dictionary element to a path in your Web transport : either the directoryattribute must be present or both the packageand resourceattributes, not both, and not none. with options: Example - Serving from Directories¶ Here is an example Web Transport configuration that includes a Static Web Service: { "type": "web", "endpoint": { "type": "tcp", "port": 8080 }, "paths": { "/": { "type": "static", "directory": ".." }, "ws": { "type": "websocket", } } } This will make the subpath /ws into a WebSocket transport. All other paths (other than /ws) will serve static assets from the directory specified. The directory path can be absolute or relative to the node directory ( .crossbar). Unless a HTML file is specified, the server will attempt to serve a file “index.html” from the specified directory. A Static Web Service has a couple of options you can configure using an options dictionary: "/": { "type": "static", "directory": "..", "options": { "enable_directory_listing": true, "mime_types": { ".svg": "image/svg+xml" } } } You can also put (another) Static Web Service on a subpath serving assets from a directory and this directory can be different from the base directory of the containing Web Transport: "paths": { "/": { "type": "static", "directory": ".." }, "ws": { "type": "websocket" }, "download": { "type": "static", "directory": "/var/download" } } Here, the Web Transport has it’s base path / configured to be static and pointing to directory .. relative to the node directory. Whereas the subpath download is configured to be of type static and pointing to the directory /var/download. Example - Serving from Python Packages¶ Python packages can contain “resources” (non-Python file assets) and the Static Web Service can serve assets directly from any Python package installed (in the Python installation that Crossbar.io runs from). Say you are creating a ``foobar`` package that contains static Web resources: setup.py MANIFEST.in foobar/__init__.py foobar/web/index.html with the 4 files having the following contents: ``setup.py``: from setuptools import setup setup( name = 'foobar', version = '0.0.1', packages = ['foobar'], include_package_data = True, zip_safe = False ) ``MANIFEST.in``: recursive-include foobar/web * ``foobar/__init__.py``: __version__ = '0.0.1' ``foobar/web/index.html``: <!doctype html> <html> <body> <h1>The awesome Foobar content</h1> </body> </html> After installing the package locally ( python setup.py install), you can configure your resources to be served like this: { "type": "web", "endpoint": { "type": "tcp", "port": 8080 }, "paths": { "/": { "type": "static", "package": "foobar", "resource": "web" }, "ws": { "type": "websocket", "url": "ws://localhost:8080/ws" } } } When you start Crossbar.io, you should see log lines similar to: ... 2014-03-20 10:37:28+0100 [Worker 3528] Loaded static Web resource 'web' from module 'foobar 0.0.1' (filesystem path c:\Python27\lib\site-packages\foobar-0.0.1-py2.7.egg\foobar\web) 2014-03-20 10:37:28+0100 [Worker 3528] Site starting on 8080 ... Point your browser to. You should see an “awesome” message;) Note that you can also put (another) Static Web Service on a subpath serving assets from a Python package resource.
https://crossbar.io/docs/Static-Web-Service/
CC-MAIN-2022-40
refinedweb
620
56.66
#include <null.h> The input_null class is used to represent an input source this is always empty. Definition at line 28 of file null.h. [virtual] The destructor. Definition at line 22 of file null.cc. [private] The default constructor. It is private on purpose, use the create class method instead. Definition at line 27 of file null.cc. The copy constructor. Do not use. [static] The create class method is used to create new dynamically allocated instances of this class. Definition at line 33 of file null.cc. The assignment operator. Do not use. [private, virtual] The read_inner method is called byu the underflow method to fill the buffer buf with more data. Implements input. Definition at line 40 of file null.cc.
http://nis-util.sourceforge.net/doxdoc/classinput__null.html
CC-MAIN-2018-05
refinedweb
124
63.46
If I had sample XSLT, because I am familiar with XML and minimally familiar with XSLT, but programming many other languages for decades, I think I could modify it for our situation. I think we could likely live with converting to almost any style, those details I could manage. Would also love the XSLT to strip out all images... Can you post an example somewhere of what your Wordpress XML looks like? Thanks, will be planning to put this up on dropbox, do you use that tool? Friend me (I am using real name) on facebook, to provide the email to allow you access. Uh, "Facebook"? What's that? Does it have anything to do with this "twitter" thing I've been hearing about lately? (Sorry, just joking. I'm not in to Facebook, LinkedIn, Twitter, Spotify, del.i.cious, or any of the other "social media" advertiser's honey traps.) Can you make a small sample file that contains no sensitive material and post a public Dropbox link? Or, if the file is not very large, you can also paste it in-line in this forum. In that case please use the Advanced Editor (finally reinstated, thank you moderators!) to set its syntax highlighting to "XML". OK, how about "dropbox", ever used it? Would prefer an alternative to making the dropbox folder open to public, open to suggestions on how to get files to you. Sorry, did not see dropbox suggestion. Here is the issue, have large XML file, could give you "head" of it, and an ePub and PDF. Is XML alone , a sample, enough? That I would be happy to post, here. How do I get to the "advanced editor". I do not see it, and how to set syntax to "XML". All dropbox content can now be shared with a link. Make sure you have the most current version of DB installed and right click the file and choose Dropbox>Get Link. You can send a private message to anyone on the forums. Bob Um, much as I like to help you, I cannot promise anything until I've actually seen the file. It's just that without an example, *no-one* on this forum can. I could p.m. you an email address, and you could send me your test file, and then I could decide "nah, cannot work with it". That's why I suggested you to make a small (non-sensitive) test file and make it publically available -- so that others can have a go at it as well. ... The Advanced Editor for posts is hiding under the innocuous text "Use advanced editor", at the top right of your edit window. XML syntax highlight is under the button that looks like ">>". Okay, got your sample XML/ePub/PDF files. (It's quite big for a sample; sure looks like you sent the entire thing.) .. What a mess! If you compare the XML to the PDF, you can see that there is some plain text in there, but it's formatted as HTML, and not everything is formatted. For example, there is nothing special in the XML file between the paragraphs that start with "So it should be no surprise.." and "After arriving at the Blind Sheik's mosque ...", but the PDF mysteriously gained a triple-bullet paragraph divider in there. Where, one wonders, did that come from? It seems all you need from the XML file is the <title> element, immediately followed by its <content:encoded> element, which contains plain (HTML formatted) text. I had a brief go at it but the header contains lots of weird namespaces, and InDesign's XSLT processor isn't really a very modern one, so all I got was "Could not write data to output". I guess this means that there is some error -- either in my XSLT (which is really extremely basic), or in ID's handling of this XML. Since you already have a nicely formatted PDF with all proper text in place, I'm inclined it might be faster and easier to export this PDF in Acrobat Pro to a Word .doc file. Then you can clean it up a bit in Word, and use the resulting document as your input for InDesign. Just for clarity, this is my extremely basic XSLT-that-ought-to-have-worked: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet <xsl:output <xsl:strip-space <!-- Match everything in the root --> <xsl:template <xsl:apply-templates /> </xsl:template> <xsl:template <xsl:apply-templates /> </xsl:template> <xsl:template <title><xsl:apply-templates /></title> </xsl:template> <xsl:template <xsl:apply-templates /> </xsl:template> <xsl:template <xsl:apply-templates /> </xsl:template> </xsl:stylesheet> where are the sample files? I am sending you the links in a private message, now. OK, thanks, Karl
http://forums.adobe.com/message/4558178
CC-MAIN-2014-10
refinedweb
800
73.37
Five Things that Mildly Annoy Me in Clojure This infamous blog post suggests that someone familiar with a language should be able to name five things they hate about it. "Hate" is a strong word, but I decided to think of five things I find mildyly annoying about Clojure, my favorite language of the moment. Hashing integers Clojure automatically converts integers between Integer, Long and BigInteger as needed to prevent overflow. This is good. Integers of the various classes test as equal too. This is also good. user> (= 123 (int 123) (long 123) (bigint 123)) true So would you expect this? user> (hash-map (int 123) :foo (long 123) :bar (bigint 123) :baz) {123 :foo, 123 :bar, 123 :baz} Yes, each of the integer classes, though equal via =, do not have the same hash value when put into a hash-map. This is because: user> (.equals (int 123) (long 123)) false This is a wart inherited from the JVM. See here for discussion and explanation. What's more, if you print this map and then try to read it back in, the integers will be read as int, long or bigint arbitrarily depending how big they are. This means you may not get the same class of object back that you output originally. user> (def x {(bigint 123) :foo}) #'user/x user> (= x x) true user> (def y (read-string (pr-str x))) #'user/y user> (= x y) false user> (class (first (keys y))) java.lang.Integer user> (class (first (keys x))) java.math.BigInteger This means that if you ever use integers as hash keys, you must be very careful to cast them all to the same integer type manually. Metadata doesn't work on everything Clojure lets you stick arbitrary metadata on various objects. This is higly useful; you can decorate objects with information that doesn't affect the value of the object. However metadata doesn't work everywhere. user> (with-meta "foo" {:bar :baz}) java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IObj (NO_SOURCE_FILE:0) You can only stick metadata on certain Clojure objects like Symbols, Vars, Refs, Agents, all of the Clojure collections and so on. You can't stick metadata on, say, a String or an Integer, because those are closed Java classes and can't be touched. It would be nice if you could. use vs. require vs. import vs. load vs. ... There are a startling number of ways to import a library into your code in Clojure. You have to choose from load, import, require, use, refer, and so on. Some work on Java classes, some work on Clojure libs. Some of them import symbols into your namespace, some of them don't. Some of them take strings as arguments, some take symbols, some take quoted lists of symbols, some take quoted lists of symbols with sub-lists of arguments. And all of these can be and usually are weirdly inlined into a namespace declaration, with a completely different list-quoting style. So in Ruby you can do this: require 'util' require 'config' require 'whatever' Whether it's a gem, or a Ruby source file sitting locally, it all works the same as long as the load path is set up right. But in Clojure, you do this (actual code from an IMAP library I wrote): (ns qt4-mailtray.mail (:import (java.util Properties) (javax.mail Session Store Folder Message Flags Flags$Flag FetchProfile FetchProfile$Item) (javax.mail.internet InternetAddress)) (:use clojure.contrib.str-utils)) This can quickly become unwieldy, especially if you start using the :as or :only or :rename arguments. It's made worse by Java's insane API's full of a billion classes that you need to import to do simple things. (And those things with dollar signs are mangled Java inner class names.) Clojure also lacks the ability to import a whole package worth of classes at once using java.io.* syntax, so you must name all of the classes explicitly. every? vs some. This is such a trite pet-peeve that it's barely worth mentioning, but it seems to be brought up repeatedly and endlessly on the Clojure mailing list so at least I'm not the only one bugged by it. Clojure has a function (every? pred coll) which tests whether every item in a collection tests true via some predicate. To test whether every item in a collection tests false, we have not-any?. And we have a not-every? which tests whether any item tests false. user> (every? even? [2 4 6]) true user> (not-every? even? [2 4 6]) false user> (not-any? even? [2 4 6]) false Now what would you expect a function to be called which tests whether any item in a collection tests true via some predicate? If you said any? you are wrong! It's some. Note that some isn't a predicate (hence no question mark in the name); it doesn't return true or false, as above, but rather returns the result of running pred on an item in coll. user> (some identity [nil 1 2 3]) 1 any? is pretty easy to write so it doesn't matter that much. Probably many people have an identical function sitting in some utils.clj file on their systems. (defn any? [pred coll] (when (seq coll) (if (pred (first coll)) true (recur pred (next coll))))) Stack trace madness Give this function: (defn foo [] (throw (Exception. "BARFED"))) What does the stack trace look like in SLIME when you call foo? Like this: java.lang.Exception: BARFED (NO_SOURCE_FILE:0) [Thrown class clojure.lang.Compiler$CompilerException] Restarts: 0: [ABORT] Return to SLIME's top level. 1: [CAUSE] Throw cause of this exception Backtrace: 2: swank.commands.basic$eval_region__729.invoke(basic.clj:36) 3: swank.commands.basic$listener_eval__738.invoke(basic.clj:50) 4: clojure.lang.Var.invoke(Var.java:346) 5: user$eval__1506.invoke(NO_SOURCE_FILE) 6: clojure.lang.Compiler.eval(Compiler.java:4580) 7: clojure.core$eval__4016.invoke(core.clj:1728) 8: swank.core$eval_in_emacs_package__336.invoke(core.clj:55) 9: swank.core$eval_for_emacs__413.invoke(core.clj:123) 10: clojure.lang.Var.invoke(Var.java:354) 11: clojure.lang.AFn.applyToHelper(AFn.java:179) 12: clojure.lang.Var.applyTo(Var.java:463) 13: clojure.core$apply__3269.doInvoke(core.clj:390) 14: clojure.lang.RestFn.invoke(RestFn.java:428) 15: swank.core$eval_from_control__339.invoke(core.clj:62) 16: swank.core$eval_loop__342.invoke(core.clj:67) 17: swank.core$spawn_repl_thread__474$fn__505$fn__507.invoke(core.clj:173) 18: clojure.lang.AFn.applyToHelper(AFn.java:171) 19: clojure.lang.AFn.applyTo(AFn.java:164) 20: clojure.core$apply__3269.doInvoke(core.clj:390) 21: clojure.lang.RestFn.invoke(RestFn.java:428) 22: swank.core$spawn_repl_thread__474$fn__505.doInvoke(core.clj:170) 23: clojure.lang.RestFn.invoke(RestFn.java:402) 24: clojure.lang.AFn.run(AFn.java:37) 25: java.lang.Thread.run(Thread.java:619) Yeouch. Now imagine that the above error is coming not from a simple function, but from some random line among hundreds of lines of source code. Stack traces in Clojure will often tell you little to nothing about what is causing the error, or more importantly, where it's coming from in your code. Clojure functions are translated into Java classes when they're run through the JVM. Often can't even see the name of the function that's throwing the error; names are mangled into things like user$eval__1473.invoke, which is really really confusing when you use anonymous functions. Per Jason Wolfe and Randall Schulz sometimes you can get a better stack trace if you dig a bit deeper: user> (.printStackTrace (.getCause *e)) java.lang.Exception: BARFED at user$foo__1503.invoke(NO_SOURCE_FILE:1) at user$eval__1509.invoke(NO_SOURCE_FILE:1) at clojure.lang.Compiler.eval(Compiler.java:4580) at clojure.core$eval__4016.invoke(core.clj:1728) at swank.commands.basic$eval_region__729.invoke(basic.clj:36) at swank.commands.basic$listener_eval__738.invoke(basic.clj:50) at clojure.lang.Var.invoke(Var.java:346) at user$eval__1506.invoke(NO_SOURCE_FILE) at clojure.lang.Compiler.eval(Compiler.java:4580) at clojure.core$eval__4016.invoke(core.clj:1728) at swank.core$eval_in_emacs_package__336.invoke(core.clj:55) at swank.core$eval_for_emacs__413.invoke(core.clj:123) at clojure.lang.Var.invoke(Var.java:354) at clojure.lang.AFn.applyToHelper(AFn.java:179) at clojure.lang.Var.applyTo(Var.java:463) at clojure.core$apply__3269.doInvoke(core.clj:390) at clojure.lang.RestFn.invoke(RestFn.java:428) at swank.core$eval_from_control__339.invoke(core.clj:62) at swank.core$eval_loop__342.invoke(core.clj:67) at swank.core$spawn_repl_thread__474$fn__505$fn__507.invoke(core.clj:173) at clojure.lang.AFn.applyToHelper(AFn.java:171) at clojure.lang.AFn.applyTo(AFn.java:164) at clojure.core$apply__3269.doInvoke(core.clj:390) at clojure.lang.RestFn.invoke(RestFn.java:428) at swank.core$spawn_repl_thread__474$fn__505.doInvoke(core.clj:170) at clojure.lang.RestFn.invoke(RestFn.java:402) at clojure.lang.AFn.run(AFn.java:37) at java.lang.Thread.run(Thread.java:619) This one at least mentions foo by name but you're still going to have a headache after a few hours of those stack traces. Conclusion So that's five things. You will notice a common theme. Most of these issues are inherited from the JVM. This is to be expected, I suppose. There's no way you can wrap one language in another without a few compromises. But these things aren't show-stoppers. They are minor annoyances compared to the benefits you get from using the JVM, i.e. the good performance, tons of libraries, cross-platformness, and so on. Clojure is fun enough to work with and wart-less enough that it took me well over two weeks to write this post. (If you were expecting me to mention loop/ recur and the lack of native TCO in the JVM, you were PAINFULLY WRONG. No one who uses Clojure loses sleep over native TCO. It's largely a non-issue that's endlessly repeated by people looking for an excuse to pass up Clojure in favor of $their_pet_language. To each his own, but I have never found myself caring the slightest about loop/ recur.) 15 Comments Nice post and I agree mostly with your specific points. Likewise, I agree wholeheartedly about the need to find faults with your language of choice and/or most familiar with. I make it a point to ask such a question when interviewing job candidates as it shows that the person has taken the time to think about their language in more than just a superficial way. You'd be surprised how few people can devise one thing must less five. -m You can hit 1 in your sldb buffer to getCause automatically so you don't have to type out printStackTrace. Notice the restart, " 1: [CAUSE] Throw cause of this exception." 1 and 2 are pretty annoying. Metadata is never going to work on core Java classes, and that is a shame, though it should get added for functions soon. use vs require vs import is pretty straightforward. Is it a Java class? Then import it. Do you want its public vars in your namespace? Then use. Otherwise require. load and refer are low-level functions that you shouldn't be using directly. Stack traces can be greatly improved from within SLIME by (0) running the latest swank-clojure, which removes the caused-by-swank wrapper exception, and (1) using this code snippet that dims all the irrelevant frames from the trace: It makes the relevant lines jump out much more quickly. You're definitely right about the hashing of ints, but if you want to read stuff in, you should do it right: Granted, *print-dup*is not well-known, but it's a great mechanism for ensuring that what you print is what you get (WYPIWYG?). FWIW, I'd read up on it if I were you (search the google group, etc), as there are some caveats (e.g. it doesn't handle arbitrary java objects, etc., but it is fully extensible if you care to do so for particular types). @Chas: Right. I knew about *print-dup*but didn't even think of it in this case, duh. Thanks for the reminder. @Phil, Drew: Thanks for the SLIME tips. Didn't know about those. @Fogus: Yeah if I ever have to interview someone again I'll probably use this question. If nothing else it shows the ability to be objective. People with a religious mindset about their favorite language and an unrealistic view of its perfection can be hard to deal with. Self-selection. The cow at my last post. Sadface. I love Clojure but the horrible stack trace has to be my main beef. For comparison I just took a look at JRuby and the stack trace, while not perfect, does not include nearly as much crud: Lack of "native TCO" in the JVM is NOT the reason for "recur." If Clojure can do tail-recursion with a special form, it could have been designed to do it without a special form. Therefore, the designers of Clojure could have chosen to make the "recur" form implicit, but THEY CHOSE NOT TO, and THAT'S why you have "recur." Multimethods seem like a handy mechanism for providing polymorphic APIs, but there is a gotcha: Clojure does not provide a default ordering for inheritance relationships, so it's possible to accidentally write an ambiguous set of inheritance relationships. In that case, you'll see a stack trace until you manually fix the problem with a prefer-method call. What's more, if you expose a multimethod API in a library, your users can accidentally break your inheritance scheme simply by defining some new tags that inherit from the old ones in your library. They won't notice this problem (and neither will you) until they happen to create an ambiguous inheritance relationship somewhere, and then they'll notice it because code that used to work fine now suddenly causes backtraces. They can fix the breakage, of course, by making the right set of prefer-method calls...if they can figure out what those are. You might want to make sure they have the source code to your library. You might think, "oh, I'll just write code to compute a stable order for derived types, and call prefer-method automatically, so my users won't have this problem." You can't. derive hierarchies represent inherited types as unordered sets; you cannot use them to get a stable, ordered sequence of inherited types. If you want to make libraries with stable, robust, polymorphic APIs, you'll need to either write those parts in Java or implement your own substitutes for multimethods and derive hierarchies. The Clojure community, by the way, considers these characteristics of multimethods and derive hierarchies to be features, not bugs. The stack trace comment really hit home for me. I've been playing with Clojure for a couple of weeks now, using it to develop a solution for a real problem that I need to solve, and it seems to me that if there is one thing which will stop Clojure achieving any kind of mainstream acceptance it is the hideous nature of error messages. Not since working with templates in early C++ compilers have I seen error messages (in clojure's case, in the form of stack traces) which were so totally divorced from the actual cause of the problem. Earlier this week I spent 15 minutes trying to track down a problem in my code which should have taken 15 seconds to fix simply because the stack trace gave me so little information that I ended up having to litter the code with prinlns just to find where the error was being generated. This will be a major drag on productivity in any real-world development and at the moment, putting Clojure in front of an inexperienced programmer will be a disaster. I had a poke around in the Clojure source and it is clear that the architecture does not lend itself well to providing meaningful error messages, but I believe that by adopting the right conventions for the exceptions that enough information could be collected as the exception propagates back up the stack to put together clear and concise information to describe the error. I may have a go at some particular cases and submit them. The stack traces in Clojure are truly awful. Is it really so hard to display the lines from my code which contributed to the error? I've tried the various packages that supposedly clean up the stack trace, and they seem to cut the stack trace down quite a bit, but a significant percentage of the time, the important parts of the stack trace relating to my code are removed as well! Most of your other points I agree with, but I find them easy enough to work around. I can think of lots of other things that bother me about Clojure. Here are ten: Clojure code must be arranged in a bottom-up manner, otherwise lots of forward declarations are required, which clutters up the program. Since I like to write code in a top-down manner that is easy to read and understand, this bugs me. I agree with Mikel's point about multimethods found in the comments. The current design of multimethods, which relies on prefer-method to disambiguate, has some extensibility issues. Lazy sequences always cache their contents, which is great for sequences whose elements are generated from some computationally-intensive or imperative procedure. But for sequences based off of simple, pure-functional generators, this caching is unnecessary, slowing things down and using up lots of memory. range is implemented internally by Clojure in a way that avoids caching, and it would be nice if Clojure programmers could easily do the same. Metadata is cool, but adding metadata and working with it can get a bit verbose. #^ is not a synonym for with-meta, but I think a lot of people wish it were, because a special notation for adding/altering metadata would be extremely useful. I personally don't like nil punning, and although Clojure allows you to avoid nil punning in a lot of instances, it's still considered a desired idiom to use (seq s) instead of (not-empty s), one-armed when clauses that don't specify what happens when the sequence is empty (because the answer just defaults to nil), and other similar examples. Other than defn-, most defines don't have a private variation. Ditto with doc strings. Would like to see more consistency. Hard to create structs with "private" information that can only be seen by certain functions. Hard to modify equality behavior for custom structs or collections. Arithmetic operators are also difficult to customize for new data structures. I don't like the Clojure philosophy to wrapping Java libraries. Java in Clojure is significantly uglier than pure Clojure, so I'd much rather use wrappers that make a Java library feel more like a native Clojure library. Clojure inherits from Java a fairly limited stack. Most tree traversals cannot easily be converted to loop/recur, and I really hate having to constantly worry about whether I'm going to blow the stack when building and manipulating trees. That said, I like Clojure a lot better than the alternatives. I almost forgot to mention that I don't like the "untagged" nature of records. I prefer Oz's way: circle(x:0 y:1 radius:3 color:blue style:dots) Notice that the struct (aka record) also has a (optional) tag telling you what kind of struct it is (in this case, a circle). I think it's often very useful to know what kind of thing a struct represents. You can use a :tag field in every record, but then you'll want to create a custom constructor (as opposed to just using struct-map). Also, different programmers will use a different keyword for the "tag". If you iterate through the key-value pairs, you'll end up with :tag as one of the keys, which probably isn't what you want. Whoops, in number 9 above, I meant I don't like the Clojure culture of NOT wrapping a lot of Java libraries. Would prefer as much Clojure-friendly wrapping as possible. I agree with much of your list Mark. With regards to 6, you might already be aware but there are private versions of defmacro etc. in clojure.contrib.def. Likewise for 8 there are a bunch of clojure.contrib.generic that provide math functions as multimethods, complex numbers etc. with the downside of being pretty slow compared to native math, obviously. I would like to see those things built-in to Clojure too personally. The distinction between Clojure builtins and Clojure contrib libraries is confusing and seems kind of arbitrary. Personally I prefer everything to be included in the base language as much as possible, for convenience if nothing else. Not sure how I feel about 9. Calling Java is so Lispy already that I'm usually not bothered. I am concerned about what's going to happen if the .NET port of Clojure becomes popular. Seems like if you want interoperable libraries, then thin pure Clojure wrappers would be necessary. I agree with most of your point, except somevs. every. These predicates are thankfully the same as their like-named Common Lisp counterparts. I (non-native speaker) learned in my English class many years ago, that the opposite of some is not any, so these predicates seem to be named right. And someis the only predicate of those 4 which can return a more useful value than simply true, so I think it should do so. Speak your Mind Preview
http://briancarper.net/blog/460/five-things-that-mildly-annoy-me-in-clojure
CC-MAIN-2015-22
refinedweb
3,651
66.23
Hello, I am trying to have a numeric box in WPF toolbox, I have the following code which is giving me the control in the tool box, but I am unable make it accept only the numeric input. protected override void OnKeyDown(KeyEventArgs e) { short val; if (!Int16.TryParse(e.key.ToString(), out val)) { e.Handled = true; } } The problem I am facing is: 1 - When I press the numeric key 1 the value taken is D1 where it is treated as a character and displayed in Textbox 2- The Xaml designer is not coming up Window x: <Grid> <my:NumericTextBox </Grid> </Window> The error is Error 1 Undefined CLR namespace. The 'clr-namespace' URI refers to a namespace 'TEST' that is not included in the assembly. Error 2 The type 'my:NumericTextBox' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. However I am still able to run the app I want to have a custom control for textbox accepting only numerics.Please suggest.... Regards
https://www.daniweb.com/programming/software-development/threads/421881/numeric-box-in-wpf
CC-MAIN-2016-50
refinedweb
176
58.82
03 July 2012 11:32 [Source: ICIS news] By Becky Zhang SINGAPORE (ICIS)--Spot monoethylene glycol (MEG) prices in Asia have gone up by 6% in the past week on the back of strong crude futures, but further gains may be capped as buyers remain cautious about procuring cargoes, market sources said on Tuesday. Bid-offers for spot MEG rose to $880-890/tonne (€695-703/tonne) CFR (cost & freight) China Main Port (CMP) on 3 July, up by $50-55/tonne week on week, largely driven by speculative purchases by traders amid a strengthening of crude prices, they said. At 17:54 ?xml:namespace> But actual buying by MEG end-users in the polyester industry, as well as by speculative traders is not as active as it was in late 2011, market sources said. Crude futures are also very volatile and are under constant pressure given concerns over a weakening global economy, they said. “The number of offers [for MEG] increased evidently once prices moved up to higher levels,” said a major Chinese trader, but added that this meant that sellers are not confident about additional gains. Downstream polyester makers have been running at reduced rates because of poor demand, limiting MEG consumption. A China-based polyester maker said it shut half its 400,000 tonne/year capacity in Domestic prices of partially oriented yarn (POY) 150D/48F – a typical polyester yarn grade – in China edged up by yuan (CNY) 100-200/tonne ($16-32/tonne) from the previous week to CNY9,700-9,900/tonne ex-warehouse, according to Chemease, an ICIS service in China on Tuesday. Price gains in China POY lagged far behind Asian MEG prices as polyester producers are beset with high inventory. “The priority for most Chinese polyester producers remained as offloading inventories,” said a major Zhejiang-based producer. The producer has delayed its planned 500,000 tonne/year capacity expansion to the end of the year from its original plan in July. Chinese polyester plants have 10-28 days’ worth of inventory this week, down from last week as sales spiked on 30 June, but higher than the healthy levels of 10-14 days’ worth, market players said. An uncertain outlook on crude future prices is another key factor that keeps buying activities subdued. “It is still too early to tell whether the uptrend [in MEG spot prices] can sustain as this will depend on the trend in crude futures and the performance in the downstream polyester sector. We need to monitor the market,” a major MEG producer said. Expectations on “Market sentiment is generally fragile and [MEG] prices could come down easily when crude softens,” the trader said. ($1 = €0.79 /
http://www.icis.com/Articles/2012/07/03/9574656/asia-meg-rebounds-on-strong-crude-poor-demand-to-cap-gains.html
CC-MAIN-2014-52
refinedweb
449
51.62
juju does not work with Walrus when s3-uri has a suffix Bug Description Juju does not work with Walrus when s3-uri has a suffix like IP:PORT/ juju bootstrap with the config file environments: sample: type: ec2 default- default- ec2-uri: http:// s3-uri: http:// access-key: WKy3rMzOWPouVax secret-key: kjL11YWebs1brv2 control-bucket: juju-f81954e816 admin-secret: 13d2ea53792344b default-series: oneiric Here is the tcpdump of juju bootstrap command: http:// Can you add some insight as to how the S3 URI is used? Is there a bucket that has been created that has the configuration file for the juju charm? Also, what s3 tool is being used to communicate with Walrus? Regards, Harold Spencer, Jr. Technical Support Engineer Eucalyptus Systems, Inc. This problem appears in the first steps of juju installation. I don't know well juju's architecture to explain how it uses Walrus, maybe someone of juju dev team could help. Checking out the txaws-list-buckets command, I was able to narrow down where the issue may lie. It seems that txaws is expecting some additional information for the S3 URL. I used the python debugger to step through txaws-list-buckets and I was able to rule out the "/" issue. Also, because of this error, nothing is ever sent to the wire. The communication is dead before hitting the Walrus component. Version: # txaws-list-buckets --version txAWS 0.0.1 Test Command: # txaws-list-buckets -a <access-key> -s <secret-key> -U 192.168. > /usr/bin/ -> region = AWSServiceRegion( (Pdb) next > /usr/bin/ -> creds=creds, region= (Pdb) print options.url 192.168. (Pdb) next TypeError: "__init__() got an unexpected keyword argument 's3_endpoint'" > /usr/bin/ -> creds=creds, region= ## Without "/" # txaws-list-buckets -a <access-key> -s <secret-key> -U 192.168.2.75:8773 > /usr/bin/ -> region = AWSServiceRegion( (Pdb) next > /usr/bin/ -> creds=creds, region= (Pdb) print options.url 192.168.2.75:8773 (Pdb) next TypeError: "__init__() got an unexpected keyword argument 's3_endpoint'" > /usr/bin/ -> creds=creds, region= Hope this helps. Harold Spencer Jr. Support Engineer Eucalyptus Systems, Inc. Sorry, I forgot to add my instance and cloud information: ## Instance ## root@ubuntu:~# lsb_release --release Release: 10.04 root@ubuntu:~# python --version Python 2.6.5 ## Eucalyptus Cloud Setup ## RHEL 5.5, Eucalyptus Open Source 2.0.3, Network mode: Managed Regards, Harold Spencer Jr. Support Engineer Eucalyptus Systems, Inc. The problem in this case is that Walrus is breaking the convention established by the real S3 of owning the full path namespace of the TCP address that hosts the service. So, while in S3 you'd access <addr>/ It's not a big deal, but it's unconventional, and libraries have to be adapted to support it. IIRC, even boto itself, which is used in Eucalytpus tools, had to be patched by them to support that. Perhaps as a workaround until walrus can be run without a prefix, a user could run an apache server using mod_proxy to send these queries to walrus.. Should be as simple as: ProxyPass / http:// Its not clear we have the resource availability to fix this for 12.04.. i'd really like to make it work though, but properly its a bug in txaws for eucalyptus s3 support. This patch honors a suffix in an s3 uri as used by Walrus. It also passes the IpProtocol arg when creating a security group which works around a bug in Euca 3.x. This patch causes juju to use the 'latest' api version rather than 1.0 when determining the instance id via a meta service call This issue is now being tracked upstream at http:// Please watch that issue for further updates. Can somebody please comment on the status? It seems to be dead upstream. I'm thinking this really is just a bug in Euca and we won't be addressing it in Euca unless users request a workaround. Hi Clint, I actually worked around this in the txaws library quite easily, but then discovered other issues that prevented JuJu from working that were over my head, so I punted it to engineering. I'll check in on the status tomorrow and update this bug with relevant info when I have it. Thanks! I am facing the same problem. version: 0.5+bzr440-1ju platform: eucalyptus Instance: oneiric
https://bugs.launchpad.net/eucalyptus/+bug/907450
CC-MAIN-2016-07
refinedweb
719
64.71
Python is known for allowing you to produce elegant, simple code and reads almost as well as plain English. List comprehension is one of the language’s most distinctive features, allowing you to develop sophisticated functionality with just one line of code. On the other hand, many Python developers struggle to utilize the more advanced aspects of list comprehension fully. Some programmers may overuse them, resulting in less efficient and difficult-to-read code. By the end of this article, we are sure that you’ll have a solid understanding of Python list comprehensions and how to make the most of their features. You’ll also learn about the trade-offs that come with using them so that you can figure out when other ways are better. The following are our key concerns in this article: - In Python, rewrite loops and map() calls list comprehension. - You can use comprehensions, loops, or map() calls. - Conditional logic will boost your understanding. - Replace the filter() with comprehensions - To answer performance questions, profile your code. Lists in Python: How to Make Them In Python, you can make lists in several different ways. Let’s look at making lists in these ways to understand better the trade-offs of utilizing list comprehension in Python. Using for Loops The for loop is the most popular sort of loop. A for loop is used to make a list of elements in three steps: - Create a new empty list. - Loop through an iterable or a collection of components. - Each element is added to the end of the list. These stages are completed in three lines of code if you wish to construct a list of the first ten perfect squares: square_vals = [] for i in range(10): square_vals.append(i * i) print(square_vals) You create an empty list, squares, here. Then, you use a for loop and pass the value as a parameter to iterate across the range. Finally, you add the result to the end of the list by multiplying each integer by itself. Utilizing map() Objects The map() method offers a functional programming-based alternative. When you give map() a function and an iterable, it creates an object. This object stores the results of executing each iterable element via the provided process. Consider the following scenario in which you must calculate the price after tax for a series of transactions: transactions = [11.09, 33.56, 67.84, 14.56, 16.78] TAX_RATE = .058 def get_price_with_tax(transaction): return transaction * (1 + TAX_RATE) total_prices = map(get_price_with_tax, transactions) list(total_prices) There’s an iterable ‘transactions’ here, as well as a method get_price_with_tax(). You call map() with these inputs and save the result in total_prices. Further, you can easily convert this map object into a list using a list(). Making Use of List Comprehensions A third technique to make lists is to use list comprehensions. You could also endeavor to rewrite the for loop from the first example in just one line of code using this elegant approach: square_vals = [i * i for i in range(10)] print(square_vals) Rather than starting with an empty list and adding each element at the end, use this approach to define the list and its contents at the same time: new_list = [expression for member in iterable] In Python, every list comprehension has three components: - A valid expression that returns a value is the member itself, a call to a method, or another acceptable expression. The square of the member value is represented by the expression i * i in the example above. - The item or value in the list or iterable is called a member. The member value in the case above is i. - A list, sequence, generator, set, or any other object that may return its elements one by one is known as an iterable. The iterable in the preceding example is of range 10. Because the expression requirement is flexible, list comprehension in Python is used in various situations where you would rather use a map(). The price example can be rewritten with its list comprehension as follows: transactions = [1.09, 23.56, 57.84, 4.56, 6.78] TAX_RATE = .08 def get_price_with_tax(transaction): return transaction * (1 + TAX_RATE) total_prices = [get_price_with_tax(i) for i in transactions] print(total_prices) The only difference between this implementation and map() is that list comprehension returns a list rather than a map object in Python. List Comprehensions Advantages Loops and maps() are typically described as less Pythonic than list comprehensions. But, rather than accepting that judgment at face value, it’s worthwhile to consider the advantages of utilizing a list comprehension in Python over the alternatives. You’ll learn about a couple of cases where the other options are a better later on. List comprehensions are used for mapping, filtering, and essential list generation. One of the crucial advantages of utilizing a list comprehension in Python is that it is a single tool used in various situations. In fact, you don’t need to adopt a new strategy for each case. List comprehensions are regarded as Pythonic, as Python embraces simple, powerful tools used in several scenarios. As a bonus, you won’t have to remember the appropriate order of parameters when using a list comprehension in Python, as you would when calling map(). List comprehensions are easier to read and grasp than loops since they are more declarative. You must manually build an empty list, loop through the entries, and add each to the list’s end. Instead, using a list comprehension in Python, you can concentrate on what you want to put in the list and trust Python to handle the list generation. It would help to focus on how the list is constructed while using loops. How to increase your Comprehension Power It’s helpful to grasp the variety of functionality that list comprehensions can provide to appreciate their significance fully. You’ll also want to be aware of the changes coming in Python 3.8 and above to list comprehension. Conditional Logic You saw this algorithm for creating list comprehensions earlier: new_list = [expression for member in iterable] While this formula is correct, it is also a little lacking. Optional conditionals are now supported in a more detailed description of the comprehension formula. Adding a conditional to the end of an expression is the most popular approach to add conditional logic to a list comprehension: resultant_new_list = [expression for member in iterable (if conditional)] Your conditional statement appears exactly before the closing bracket in this example. Conditionals are useful because they allow list comprehensions to filter out undesired values without having to use the filter() function: sentence = 'codeunderscored is the epitome of coding success' vowel_chars= [i for i in sentence if i in 'aeiou'] print(vowel_chars) The conditional statement in this code block filters out any characters in the sentence that aren’t vowels. Any valid expression can be tested using the conditional. You can even relocate the conditional logic to a new function if you require a more detailed filter: sentence = 'The rocket, who was named codeunderscored, came back from Mars because he missed his coding friends.' def check_if_is_consonant(new_char): vowel_chars = 'aeiou' return new_char.isalpha() and new_char.lower() not in vowel_chars consonants = [i for i in sentence if check_if_is_consonant(i)] print(consonants) You design a sophisticated filter called check_if_is_consonant() and give it to your list comprehension as a conditional statement—the member value i is also supplied to your function as an argument. For easy filtering, you can put the conditional at the end of the statement, but what if you want to update a member value instead of filtering it out? It’s best to put the conditional near the beginning of the expression in this case: resultant_new_list = [expression (if conditional) for member in iterable] You can apply conditional logic with this formula to choose from various output alternatives. If you have a list of prices, for example, you might want to replace negative prices with 0 while leaving the positive numbers alone: previous_prices = [11.25, -19.45, 10.22, 13.78, 5.92, -11.16] current_prices = [i if i > 0 else 0 for i in previous_prices] print(current_prices) If i > 0 else 0, your expression i contains a conditional statement. If the number is positive, Python should print the value of i, but if the number is negative, Python should modify i to 0. If all of this is too much for you, consider conditional logic as a separate function: def get_price(price): return price if price > 0 else 0 current_prices = [get_price(i) for i in previous_prices] print(current_prices) get_price() now has your conditional statement, which you can use as part of your list comprehension expression. Using Comprehensions from a Set and a Dictionary In Python, you can create set and dictionary comprehensions in addition to list comprehensions. In Python, a set comprehension is nearly identical to a list comprehension. On the other hand, setting list comprehensions ensures that the output is free of duplicates. Instead of brackets, curly braces can be used to create a set comprehension: code_val = "code, uh, finds a pattern" unique_vowels = {i for i in code_val if i in 'aeiou'} print(unique_vowels) All of the distinctive vowels discovered in code_val are output by your set comprehension. Sets, unlike lists, do not guarantee that items are preserved in the order you choose. That is why, even though the initial vowel in code_val is ‘i’, the first member of the set is a. Comprehensions from dictionaries are identical, with the addition of defining a key: square_vals = {i: i * i for i in range(10)} print(square_vals) Curly braces ({}) and a key-value pair ( i: i * i) are used in your expression to generate the squares dictionary. Making Use of the Walrus Operator The assignment expression, often known as the walrus operator, will be introduced in Python 3.8. Consider the following example to see how you may put it to use. Let’s say you need to send ten queries to an API to get temperature data. Assume that each request will yield extraordinary results. You only want to see temperatures above 100 degrees Fahrenheit in your results. In this circumstance, there is no method to fix the problem using a list comprehension in Python. The conditional in the formula expression for the member in iterable (if conditional) has no mechanism of assigning data to a variable that the expression can access. The walrus operator solves this problem. It enables you to execute an expression while assigning the result to a variable. The following example demonstrates how this is possible when using get_weather_data() to generate phony weather data: import random def get_weather_data(): return random.randrange(110, 130) list_hot_temperatures = [temp for _ in range(20) if (temp := get_weather_data()) >= 100] print(list_hot_temperatures) Although you won’t need to utilize the assignment expression inside of list comprehension in Python very often, it’s a handy tool to have. When to Avoid Using Python’s List Comprehension List comprehensions help write elegant, easy-to-read, and debug code, but they aren’t the best solution in every situation. They may cause your code to execute slower or consume more memory. It’s probably advisable to choose an alternative if your code is less performant or challenging to understand. Be Wary of Nested Comprehensions Comprehensions can be nested within a collection to build combinations of lists, dictionaries, and sets. Assume a climate laboratory monitors the high temperatures in five cities during the first week of June. A list comprehension nested within a dictionary comprehension could be the ideal data structure for storing this information: computers = ['HP', 'Dell', 'Chrome Book', 'Apple', 'IBM'] comp_list = {comp: [0 for _ in range(7)] for comp in computers} print(comp_list) A dictionary comprehension is used to create the outer collection temperatures. Another comprehension is contained in the expression, which is a key-value pair. This code will generate a list of data for each city in cities in a short amount of time. Matrixes are frequently used in mathematics, and nested lists are common to generate them. Examine the code block example below: matrix_vals = [[i for i in range(2)] for _ in range(3)] print(matrix_vals) The outer list comprehension [… for _ in range(3)] generates three rows, whereas the inner list comprehension [i for i in range(2)] assigns values to each of these rows. So far, each nested comprehension’s purpose has been rather self-evident. However, in some cases, such as flattening nested lists, the reasoning may make your code more difficult to understand. Take this example of flattening a matrix with a stacked list comprehension: matrix_vals = [ [0, 0, 0], [1, 1, 1], [2, 2, 2], ] flat_vals = [num for row in matrix_vals for num in row] print(flat_vals) The code for flattening the matrix is short, but it may not be easy to understand how it works. If you use for loops to flatten the same matrix, on the other hand, your code will be much more straightforward: matrix_vals = [ [0, 0, 0], [1, 1, 1], [2, 2, 2], ] flat_vals = [] for row in matrix_vals: for val in row: flat_vals.append(val) print(flat_vals) As you can see, the code explores the matrix one row at a time, extracting all of the elements in that row before going on to the next. While the single-line nested list comprehension may appear more Pythonic, the essential thing is to build code that your team can easily understand and alter. You’ll have to make a decision based on whether you think comprehension helps or damages readability when you choose your technique. Why use use generators when working with large datasets? In Python, a list comprehension loads the whole output list into memory. It is usually fine for minor or even medium-sized lists. A list comprehension will admirably solve this problem if you wish to sum the squares of the first one thousand integers. sum([val * val for val in range(3000)]) What if you needed to add the squares of the first billion integers? If you tried them on your computer, you might have noticed that it gets unresponsive. Python is attempting to generate a list containing one billion numbers, which will take up more memory than your computer can handle. Your computer may lack the resources required to build and store an extensive list in memory. If you go ahead and do it anyway, your computer may slow down or even crash.When the size of a list becomes a concern, using a generator rather than a list comprehension in Python is generally preferable. A generator returns an iterable rather than creating a single prominent data structure in memory. While only holding a single value at a time, your code can ask for the following item from the iterable as many times as necessary or until you reach the end of your sequence. If you use a generator to add the first billion squares, your software will probably run for a while, but it won’t cause your machine to freeze. A generator is used in the following example: sum(i * i for i in range(1000000000)) You can know it’s a generator because brackets or curly braces don’t enclose the expression. Parentheses surround generators if desired. Although the example above still involves a lot of work, it does so in a lazy manner. Calculation of values only happens when requested due to lazy evaluation. Following a value generation (for example, 267 * 267), the generator can add that value to the ongoing sum, discard that value, and generate the following value (268 * 268). The cycle begins again when the sum function wants the next value. This method maintains the RAM footprint to a minimum. Because map() is a lazy function, memory will not be an issue if you use it in this case: sum(map(lambda i: i*i, range(1000000000))) Optimize Performance by Profiling So, which method is the quickest? Is it advisable to use list comprehensions or one of their substitutes? Rather than sticking to a single guideline that applies to all situations, it’s better to ask yourself if performance matters in your particular case. If not, it’s usually advisable to go with the strategy that produces the most precise code! It’s usually preferable to profile several ways and listen to the data if you’re in a situation where performance is critical. timeit is a handy library for calculating how long portions of code take to execute. To compare the runtimes of map(), for loops, and list comprehensions, use timeit: Conclusion Python pushes programmers and developers to write efficiently, easy to understand, and almost as easy to read code. The python list and list compression features are two of the language’s most distinguishing features, which are used to build significant functionality with just one line of code. List comprehensions are used for constructing new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension comprises brackets that hold the expression run for each element and a for loop that iterates through each element.
https://www.codeunderscored.com/when-to-use-a-list-comprehension-in-python/
CC-MAIN-2022-21
refinedweb
2,844
50.46
-- | Basic. module Test.HUnit.Base ( -- ** Declaring tests Test(..), (~=?), (~?=), (~:), (~?), -- ** Making assertions assertFailure, {- from Test.HUnit.Lang: -} assertBool, assertEqual, assertString, Assertion, {- from Test.HUnit.Lang: -} (@=?), (@?=), (@?), -- ** Extending the assertion functionality Assertable(..), ListAssertable(..), AssertionPredicate, AssertionPredicable(..), Testable(..), -- ** Test execution -- $testExecutionNote State(..), Counts(..), Path, Node(..), testCasePaths, testCaseCount, ReportStart, ReportProblem, performTest ) where import Control.Monad (unless, foldM) -- Assertion Definition -- ==================== import Test.HUnit.Lang -- Conditional Assertion Functions -- ------------------------------- -- | Asserts that the specified condition holds. assertBool :: String -- ^ The message that is displayed if the assertion fails -> Bool -- ^ The condition -> Assertion assertBool msg b = unless b (assertFailure msg) -- | Signals an assertion failure if a non-empty message (i.e., a message -- other than @\"\"@) is passed. assertString :: String -- ^ The message that is displayed with the assertion failure -> Assertion assertString s = unless (null s) (assertFailure s) -- | Asserts that the specified actual value is equal to the expected value. -- The output message will contain the prefix, the expected value, and the -- actual value. -- -- If the prefix is the empty string (i.e., @\"\"@), then the prefix is omitted -- and only the expected and actual values are output. assertEqual :: (Eq a, Show a) => String -- ^ The message prefix -> a -- ^ The expected value -> a -- ^ The actual value -> Assertion assertEqual preface expected actual = unless (actual == expected) (assertFailure msg) where msg = (if null preface then "" else preface ++ "\n") ++ "expected: " ++ show expected ++ "\n but got: " ++ show actual -- Overloaded `assert` Function -- ---------------------------- -- | Allows the extension of the assertion mechanism. -- -- Since an 'Assertion' can be a sequence of @Assertion@s, 'Test's and -- 'Testable' should be used. class Assertable t where assert :: t -> Assertion instance Assertable () where assert = return instance Assertable Bool where assert = assertBool "" instance (ListAssertable t) => Assertable [t] where assert = listAssert instance (Assertable t) => Assertable (IO t) where assert = (>>= assert) -- | A specialized form of 'Assertable' to handle lists. class ListAssertable t where listAssert :: [t] -> Assertion instance ListAssertable Char where listAssert = assertString -- Overloaded `assertionPredicate` Function -- ---------------------------------------- -- | The result of an assertion that hasn't been evaluated yet. -- -- Most test cases follow the following steps: -- -- 1. Do some processing or an action. -- -- 2.: -- -- 1. Write data to a file. -- -- 2. Read data from a file, evaluate conditions. -- -- 3. Clean up the file. -- -- 4. Assert that the side effects of the read operation meet certain conditions. -- -- 5. Assert that the conditions evaluated in step 2 are met. type AssertionPredicate = IO Bool -- | Used to signify that a data type can be converted to an assertion -- predicate. class AssertionPredicable t where assertionPredicate :: t -> AssertionPredicate instance AssertionPredicable Bool where assertionPredicate = return instance (AssertionPredicable t) => AssertionPredicable (IO t) where assertionPredicate = (>>= assertionPredicate) -- Assertion Construction Operators -- -------------------------------- infix 1 @?, @=?, @?= -- | Asserts that the condition obtained from the specified -- 'AssertionPredicable' holds. (@?) :: (AssertionPredicable t) => t -- ^ A value of which the asserted condition is predicated -> String -- ^ A message that is displayed if the assertion fails -> Assertion pred @? msg = assertionPredicate pred >>= assertBool msg -- | Asserts that the specified actual value is equal to the expected value -- (with the expected value on the left-hand side). (@=?) :: (Eq a, Show a) => a -- ^ The expected value -> a -- ^ The actual value -> Assertion expected @=? actual = assertEqual "" expected actual -- | Asserts that the specified actual value is equal to the expected value -- (with the actual value on the left-hand side). (@?=) :: (Eq a, Show a) => a -- ^ The actual value -> a -- ^ The expected value -> Assertion actual @?= expected = assertEqual "" expected actual -- Test Definition -- =============== -- | The basic structure used to create an annotated tree of test cases. data Test -- | A single, independent test case composed. = TestCase Assertion -- | A set of @Test@s sharing the same level in the hierarchy. | TestList [Test] -- | A name or description for a subtree of the @Test@s. | TestLabel String Test instance Show Test where showsPrec p (TestCase _) = showString "TestCase _" showsPrec p (TestList ts) = showString "TestList " . showList ts showsPrec p (TestLabel l t) = showString "TestLabel " . showString l . showChar ' ' . showsPrec p t -- Overloaded `test` Function -- -------------------------- -- | Provides a way to convert data into a @Test@ or set of @Test@. class Testable t where test :: t -> Test instance Testable Test where test = id instance (Assertable t) => Testable (IO t) where test = TestCase . assert instance (Testable t) => Testable [t] where test = TestList . map test -- Test Construction Operators -- --------------------------- infix 1 ~?, ~=?, ~?= infixr 0 ~: -- | Creates a test case resulting from asserting the condition obtained -- from the specified 'AssertionPredicable'. (~?) :: (AssertionPredicable t) => t -- ^ A value of which the asserted condition is predicated -> String -- ^ A message that is displayed on test failure -> Test pred ~? msg = TestCase (pred @? msg) -- | Shorthand for a test case that asserts equality (with the expected -- value on the left-hand side, and the actual value on the right-hand -- side). (~=?) :: (Eq a, Show a) => a -- ^ The expected value -> a -- ^ The actual value -> Test expected ~=? actual = TestCase (expected @=? actual) -- | Shorthand for a test case that asserts equality (with the actual -- value on the left-hand side, and the expected value on the right-hand -- side). (~?=) :: (Eq a, Show a) => a -- ^ The actual value -> a -- ^ The expected value -> Test actual ~?= expected = TestCase (actual @?= expected) -- | Creates a test from the specified 'Testable', with the specified -- label attached to it. -- -- Since 'Test' is @Testable@, this can be used as a shorthand way of attaching -- a 'TestLabel' to one or more tests. (~:) :: (Testable t) => String -> t -> Test label ~: t = TestLabel label (test t) -- Test Execution -- ============== -- $testExecutionNote -- Note: the rest of the functionality in this module is intended for -- implementors of test controllers. If you just want to run your tests cases, -- simply use a test controller, such as the text-based controller in -- "Test.HUnit.Text". -- | A data structure that hold the results of tests that have been performed -- up until this point. data Counts = Counts { cases, tried, errors, failures :: Int } deriving (Eq, Show, Read) -- | Keeps track of the remaining tests and the results of the performed tests. -- As each test is performed, the path is removed and the counts are -- updated as appropriate. data State = State { path :: Path, counts :: Counts } deriving (Eq, Show, Read) -- | Report generator for reporting the start of a test run. type ReportStart us = State -> us -> IO us -- | Report generator for reporting problems that have occurred during -- a test run. Problems may be errors or assertion failures. type ReportProblem us = String -> State -> us -> IO us -- | Uniquely describes the location of a test within a test hierarchy. -- Node order is from test case to root. type Path = [Node] -- | Composed into 'Path's. data Node = ListItem Int | Label String deriving (Eq, Show, Read) -- | Determines the paths for all 'TestCase's in a tree of @Test@s. testCasePaths :: Test -> [Path] testCasePaths t = tcp t [] where tcp (TestCase _) p = [p] tcp (TestList ts) p = concat [ tcp t (ListItem n : p) | (t,n) <- zip ts [0..] ] tcp (TestLabel l t) p = tcp t (Label l : p) -- | Counts the number of 'TestCase's in a tree of @Test@s. testCaseCount :: Test -> Int testCaseCount (TestCase _) = 1 testCaseCount (TestList ts) = sum (map testCaseCount ts) testCaseCount (TestLabel _ t) = testCaseCount t -- |. performTest :: ReportStart us -- ^ report generator for the test run start -> ReportProblem us -- ^ report generator for errors during the test run -> ReportProblem us -- ^ report generator for assertion failures during the test run -> us -> Test -- ^ the test to be executed -> IO (Counts, us) performTest reportStart reportError reportFailure us t = do (ss', us') <- pt initState us t unless (null (path ss')) $ error "performTest: Final path is nonnull" return (counts ss', us') where initState = State{ path = [], counts = initCounts } initCounts = Counts{ cases = testCaseCount t, tried = 0, errors = 0, failures = 0} pt ss us (TestCase a) = do us' <- reportStart ss us r <- performTestCase a case r of Nothing -> do return (ss', us') Just (True, m) -> do usF <- reportFailure m ssF us' return (ssF, usF) Just (False, m) -> do usE <- reportError m ssE us' return (ssE, usE) where c@Counts{ tried = t } = counts ss ss' = ss{ counts = c{ tried = t + 1 } } ssF = ss{ counts = c{ tried = t + 1, failures = failures c + 1 } } ssE = ss{ counts = c{ tried = t + 1, errors = errors c + 1 } } pt ss us (TestList ts) = foldM f (ss, us) (zip ts [0..]) where f (ss, us) (t, n) = withNode (ListItem n) ss us t pt ss us (TestLabel label t) = withNode (Label label) ss us t withNode node ss0 us0 t = do (ss2, us1) <- pt ss1 us0 t return (ss2{ path = path0 }, us1) where path0 = path ss0 ss1 = ss0{ path = node : path0 }
http://hackage.haskell.org/package/HUnit-1.2.2.1/docs/src/Test-HUnit-Base.html
CC-MAIN-2016-36
refinedweb
1,351
52.6
netbeans is not well rendered using openjdk Bug Description using openjdk 6b12-0ubuntu6 running netbeans 6.1, there are some problems with graphic. Maybe the problem is in rendering fonts. Everything is bigger in comparison to sun java. Even the UML editor has the same text problems for labels: the label text is not inside the field, as it should be, but under it. screenshot for the example Created attachment 123 The result of the example code on icedtea6 When generating this screenshot this JRE is used: $ java -version java version "1.6.0_0" IcedTea6 1.3.1 Runtime Environment (build 1.6.0_0-b12) OpenJDK 64-Bit Server VM (build 1.6.0_0-b12, mixed mode) Created attachment 124 This is how Sun JRE renders the same window Created attachment 125 With Compiz activated the result is getting more weird The "dust" on the picture appears when I run the test code with compiz activated. It is not deterministic but is always different on each run of the code. The "extra" white rectangle is always the same. It seems to be video driver problem but other (non Java) programs on the desktop all work fine and are not affected. (In reply to comment #0) I'm no 2-d expert, but these appear to be the same bug: swing TextLayout. http:// OpenJDK: vertical text metrics may be significanly different from those returned by Sun JDK http:// See also thread on this on <email address hidden> openjdk-6 uses the system font by default. I don't think this is a bug in openjdk-6 itself. can netbeans be made aware of different font sizes? What do you mean when you say "it uses the system fonts"? What does sun-java use instead? I tried to change the application system font, from the apparence applet, but the font did not change in netbeans. Anyway it's not only that the font is bigger, but as you can see in the screenshots, the spacing is huge. From netbeans I can only change the syntax font, not the menu font. Yes it is possible to change only editor font from inside NetBeans IDE. The rest (menu, tree, tab, ...) use default Swing font. Yes I can see spacing is bigger on openjdk. I will check default Swing component as IMO it is not specific to NetBeans. Note that it is Metal L&F. see /etc/java- Shouldn't the file be called fontconfig. java-6-sun? maybe an error... it's the binary (.bfc) file which does matter. It looks like it is better to use GTK look and feel. To use it, please, edit /usr/share/ netbeans_ I think we should mark this Invalid for netbeans. However, I've been bitten by this in the stuff I run with openjdk, the menubars specifically are taller than they should be. In my opinion there is a significant departure in the look of java apps with openjdk, I would investigate if something can be done to attenuate that difference. The gtk look and feel is ok, but it's really slower on my machine. And anyway the labels in the UML editor are placed in a different position that the text contained changeset: 1167:7175ea5857e4 user: Mark Wielaard <email address hidden> date: Fri Nov 07 13:47:41 2008 +0100 files: ChangeLog HACKING Makefile.am patches/ description: * patches/ * Makefile.am (ICEDTEA_PATCHES): Add new patch. * HACKING: Document new patch. Ok, a patch was commited to the repo. Maybe backport that patch, or merge with IcedTea to get it, I don't know what would be the right policy here. Will this be fixed in Hardy and Intrepid? This does not only affect NetBeans but every other Java Swing program. Is there are workaround? This bug was fixed in the package openjdk-6 - 6b13~pre1-0ubuntu1 --------------- openjdk-6 (6b13~pre1- * New code drop (b13). - In the langtools area, besides a few miscellaneous bug fixes (6760834, 6725036, 6657499), all the langtools regression tests now pass out of the box (6728697, 6707027) and if using the most recent version of jtreg, the langtools regression tests can be run in the much faster "same vm" mode of jtreg, enabled with the -s option (6749967, 6748541, 6748546, 6748601, 6759775, 6759795, 6759796, 6759996, 6760805, 6760930). - Gervill update, including applying a patch from IcedTea (6758986, 6748247, 6748251). - Publishing a few dozen additional existing regression tests as open source (6601457, 6759433, 6740185). - JMX and monitoring fixes (6651382, 6616825, 6756202, 6754672). - Man page updates (6757036, 6392810, 6504867, 6326773). - Assorted other fixes (6746055, 6621697, 6756569, 6356642, 6761678). * Update IcedTea build infrastructure (20081111). - Fix freeze in midi app, LP: #275672. - Fixes in the IcedTeaPlugin: LP: #282570, LP: #282570, LP: #285729, LP: #291377, LP: #37330, LP: #239533. - Fix vertical text metrics with freetype scaler. LP: #289784. * Build-depend on ecj-gcj instead of ecj on architectures using gij/gcj as the bootstrap system. -- Matthias Klose <email address hidden> Tue, 11 Nov 2008 12:39:16 +0100 i reported a duplicate (line spacing too big in editor and log) so for me it is not fixed yet... how could i determine if i have installed the proposed fix? I have tried (from my amateur status) to implement all suggestions here, but the Netbeans IDE font spacing is still too big. I did the whole Ubuntu installation in the last couple of days. I can't agree that this is low priority. Netbeans is currently unusable for serious development. Is there an answer to Michael's question - is the a package I missd during the installation? Can we please have this patch backported to Intrepid? It's been available for two months. Seconded; a backport would be very much appreciated. Can we get a backport to Hardy, please? I've installed the openjdk 1.6b14 from PPA and the bug is still there. I get a huge space around text in Netbeans. Using Intrepid x86_64, bug is still happening, any plans for a backport ? Package: openjdk-6-jdk Architecture: amd64 Version: 6b12-0ubuntu6 Using Jaunty amd64 I still see the problem. openjdk- sun-java6-bin 6-12-0ubuntu1 See the attached screenshot The bug is not fixed. No, it still isn't. This bug was fixed in the package openjdk-6 - 6b14-1.4.1-0ubuntu7 --------------- openjdk-6 (6b14-1. * Don't use some indian fonts with diverging font metrics for the latin-1.UTF-8 encoding. LP: #289784. * Disable running the testsuite for this build (no code changes compared to the previous upload). -- Matthias Klose <email address hidden> Tue, 14 Apr 2009 11:46:25 +0200 sequence. Run the attached test program, with and without LANG set to see the difference. Removing all of gujarati, is there something to fix in these fonts? @Matthias Klose: is this stuff about indic fonts really related to this bug? i dont see the relation yet... I think it is an Rendering engine issue. Netbeans seems to have taken code from an Old Version of ICU . I don't think this is fixed. At least I still see this problem in openjdk-6 (6b14-1. Michael, don't touch things if you don't care about them. Matthias, This bug is not related to ttf-indic-fonts It must be related to rendering engine used in OpenJDK. Can anyone check the rendering engine ttf-indic-fonts work well with current versions of pango, QT & ICU without any problems. so it must be an issue with rendering engine used in netbeans I found a solution to this bug here https:/ just need to edit /etc/ and change the line sequence. to sequence. This worked for me in Jaunty x86_64. It really fix my problem. Thank you Carlos Ramos. Using jaunty 9.04 x86. After installing Netbeans, experienced the same issue: free space under text in different situations. The program code looked bad, if opened in NetBeans editor. The workaround, suggested by Carlos Ramos, has worked for me! (My first language is Russian, so deleting these fonts from the list did not affect me) Nevertheless, the bug stays unfixed... The same here - suggestion made by Carlos Ramos fixed this problem for me - using Jaunty x86_64. Otherwise using openjdk after clean install makes it almost unusable (in my case with ImageJ). Bug isn't fixed. Intrepid Ibex reached end-of-life on 30 April 2010 so I am closing the report. The bug has been fixed in newer releases of Ubuntu. Intrepid Ibex reached end-of-life on 30 April 2010 so I am closing the report. The bug is still marked as confirmed in later versions of Ubuntu. Hardy has seen the end of its life and is no longer receiving any updates. Marking the Hardy task for this ticket as "Won't Fix". The java.awt. font.TextLayout .getBounds( ) method returns a box that is shifted upwards compared to the box that is returned by Sun's official JRE. Sample code: package swingbug; import java.awt.Color; Graphics2D; font.FontRender Context; font.TextLayout ; geom.Rectangle2 D; import java.awt.Font; import java.awt.Graphics; import java.awt. import java.awt.Rectangle; import java.awt. import java.awt. import java.awt. import javax.swing.JFrame; public class SwingBug extends JFrame { private static final long serialVersionUID = 1L; public static void main(String[] args) { ).setVisible( true); (Graphics2D) g; setColor( Color.BLUE) ; fillRect( 0,0,400, 400); graphics, "Hello Kitty!", 100, 100); new SwingBug( } public SwingBug() { setTitle("Swing bug"); setSize(400, 400); repaint(); } @Override public void paint(Graphics g) { Graphics2D graphics= graphics. graphics. drawString( } public void drawString( setFont( f); ntext fontRendererContext = new FontRenderConte xt(null, true, true); text); =textLayout. getBounds( ); ngle=rectangleO fText.getBounds (); setColor( new Color(1. 0f,1.0f, 1.0f,0. 5f)); fillRect( backgroundRecta ngle.x+ x,backgroundRec tangle. y+y,backgroundR ectangle. width,backgroun dRectangle. height) ; setColor( new Color(0,0,0)); draw(graphics, x, y); Graphics2D graphics, String string, int x, int y) { if (string.length() > 0) { Font f = new Font("times", 0, 16); graphics. FontRenderCo TextLayout textLayout = new TextLayout(string, f, fontRendererCon Rectangle2D rectangleOfText Rectangle backgroundRecta graphics. graphics. graphics. textLayout. } } }
https://bugs.launchpad.net/ubuntu/hardy/+source/ttf-indic-fonts/+bug/289784
CC-MAIN-2016-40
refinedweb
1,679
67.86
Developing Struts with Easy Struts for Eclipse: - Add Easy Struts support. Adds all the necessary Struts libraries to the project classpath, and creates the configuration files and the default resource properties file. - Easy Form. Creates a JSP file with the form properties, as well as a Form bean class with form properties getter and setter methods, and adds a form bean definition to the configuration file. - Easy Action. Creates an Action class and adds an action mapping definition to the configuration file. - Easy Action associated with a form. Creates a JSP file with the form properties, a Form bean class with form properties getter and setter methods, and an Action class. Also addes a form bean definition and an action mapping definition to the configuration file. - Easy Forward. Creates local forwards and global forwards, which define where the control will be forwarded to. - Easy Exception. Handles exceptions. - Easy Message resources. Creates resource properties files, which is especially important for internationalization and localization of content. - Easy Plug-in. Creates plug-ins. - Easy Datasource. Connects the application to a data source. - Easy Module. Modularizes the. See the Resources section below for download links to the following: - Download Eclipse v2.1 from the Eclipse Web site. You can install it by unpacking it to any folder of your choice, which we will refer to as eclipse_home in this article. - Download Struts 1.1 from the Apache Web site. You can install it by unpacking it to any folder of your choice, which we will refer to as struts_home in this article. - Download the Tomcat Web server from the Apache Web site. You can install it by unpacking it to any folder of your choice, which we will refer to as tomcat_home in this article. This article assumes v4.1.18. - Download the latest Tomcat plug-in for Eclipse from the Sysdeo Web site. You can install it by unpacking it to eclipse_home/eclipse/plugins. This article assumes v2.2. - Download Easy Struts for Eclipse plug-in v0.6.4 from SourceForge. You can install it by unpacking it to eclipse_home/eclipse/plugins. - Download the J2SE SDK from the Sun Web site. You can install it in any folder of your choice, which we will refer to as java_home in this article. This article assumes v1.4.2. - Download the MySQL database server from the MySQL Web site. You can install it in any folder of your choice. - Download the JDBC driver for MySQL from the MySQL Web site. You should unpack it and copy and paste mysql-connector-java-x.x.xx-stable/mysql-connector-java-x.x.xx-stable-bin.jar to your project workspace. We will return to this later. This article assumes v3.0. Configuring the Sysdeo Tomcat Plug-in To configure the Sysdeo Tomcat Plug-in, do the following: - Start Eclipse. - Configure the Tomcat plug-in. To do this, go to the "Window" menu, select the "Preferences" item, and choose the "Tomcat" option on the popup view. Then do the following: - Set "Tomcat version" to your Tomcat version. - Set "Tomcat home" to tomcat_home/jakarta-tomcat-4.1.18. - Set "Perspective to switch when Tomcat is started" to Java. - Under Option "Tomcat", suboption "JVM Settings" -> "Classpath", add the Jar/Zip for tools.jar, which is in the folder java_home/lib/. This is for compiling JSPs. - Set the classpath variable TOMCAT_HOME for project classpath reference. To do this, choose the option "Java" on the same popup view as in step 2, select suboption "Classpath Variables" and add a new variable "TOMCAT_HOME" whose path is tomcat_home/jakarta-tomcat-4.1.18. - Ensure that the "Tomcat" menu and the 3 toolbar buttons are accessible. By now, you should be able to see a "Tomcat" menu and 3 Tomcat toolbar buttons (as shown in Figure 1) in the Java perspective. If not, go to the "Window" menu, choose the "Customize Perspective..." item, open the option tree marked "Other" and check the "Tomcat" suboption. - Make sure the Sysdeo Tomcat plug-in works. To verify, use the menu or toolbar to Start/Stop Tomcat. Figure 1. Tomcat toolbar buttons Configuring the Easy Struts Plug-in To configure the Easy Struts Plug-in, refer to Figure 2 and do the following: - Select a Struts version. To do this, go to the "Window" menu, choose the "Preference" item, choose the "Easy Struts" option and select the "Struts 1.1" tab. - Add JARs. You should add "Add JARs" for all .jar files in struts_home\jakarta-struts-1.1\lib. - Add TLDs. Next, add "Add TLDs" for all .tld files in struts_home\ jakarta-struts-1.1\lib. Figure 2. Configure the Easy Struts plug-in Developing a Struts applicationDeveloping: - Go to the "Java" option, select "Tomcat Project" and click "Next" (see also Figure 3). - Fill in the project name and click "Next" (see also Figure 4). - Check "Can update server.xml file". The system will update your server.xml file of the Tomcat Web server automatically. You may click "Finish" to complete the task now (see also Figure 5). The result of creating a Tomcat project is shown in Figure 6. Figure 3. Create a Tomcat project - Step 1 Figure 4. Create a Tomcat project - Step 2 Figure 5. Create a Tomcat project - Step 3 Figure 6. Create a Tomcat project - Final Result Adding Easy Struts support To add Easy Struts support to the Tomcat project, follow these two steps: - Click the "New" toolbar button, select the "Easy Struts" suboption from the "Java" option, choose "Add Easy Struts support" and click "Next" to forward to the next step (see also Figure 7 -- we will refer to this view as the Easy Struts functions view in the rest of this article). - Do the configurations shown in Figure 8. Ensure "Copy Struts binary" and "Copy Struts TLD" are checked. The result of adding Easy Struts support is shown in Figure 9. Figure 7. Easy Struts functions view 8. Add Easy Struts support Figure 9. Add Easy Struts support - Final Result: - Type in Use case; the Form name and Form type will be generated based upon the Use case by the system. You can modify the Form name and Form Type manually (see also Figure 10). - Click "Add" in the Form properties block; use the view shown in Figure 11 to add form properties. For example, as shown in the figure, we are trying to add a text input field with the name "tel" and the value of "tel" should be of type int. We set "tel" to the initial value of zero. We can type in or use "Browse" for the "Type". We can type in or use pull down selection for the "JSP input type". The Struts system will generate a pair of getter and setter methods for each form property in the form bean class. Therefore, for a selection list, you should only create one <html:select> but not all the <html:option>s. - Since you are developing a Web application, check the first two check boxes. - click "Next" to continue. Figure 10. Configure form - Form property names cannot start with a capital letter. Otherwise, you will be alerted that a getter method cannot be found when the action is called. - Form property names cannot be duplicates. If you really want to use two names that are the same, a prefix or suffix space will solve the problem. Figure 11. Graphical representation of relations: - Path. Is the context-relative path of the submitted request. The path must have a prefix "/" and be unique. - Type. Is the name of the Action class being described by this ActionMapping. - Attribute. Is the name of the request-scope or session-scope attribute under which the form bean is accessed, if the name is not the same as the bean's specified name. - Scope. Specifies how long the values of a form bean, associated with this mapping, should be saved. - input. Specifies the context-relative path of the input form to which control should be returned if a validation error is encountered. - Validate. If this is set to true, it indicates the ActionForm.validate() method should be called on the form bean associated to this mapping. - Parameter. Can be used to pass extra information to the Action selected by this mapping. Figure 12. Configure action Click "Next" and you should see something very similar to Figure 13. The properties shown in Figure 13 are action mapping properties, as follows: - Forward. Specifies the context−relative path of the servlet or JSP resource by which this request will be processed. ActionMapping can use findForward() to forward the control to the servlet or JSP resource. - Exception. The ExceptionHandlers associated with this mapping. The forward and exception here are both local. We will discuss the global forward and exception later. Figure 13. Configure forward Local forward attributes: - name is the unique identifier, which can be used in the action mapping's findForward() method to return the path. - The contextRelative tag tells Struts that: - If it is set to true, path should be considered relative to the entire Web application. - If it is set to false, path should be considered relative to the module of a modular application. - If redirect is true, control will be transferred to the page with a redirect but not a forward. It means that a new request is created.. Listing 1. OwnerForm.javapackage. Listing 2. ApplicationResources.propertieserrors. Listing 3. OwnerAction.javapublic class OwnerAction extends Action {public);// Forward control to the specified success targetreturn <title>Struts Form for ownerForm</title></head><body><html:formgreet : <html:select<html:option</html:option><html:optionMr.</html:option><html:optionMiss</html:option><html:optionMrs.</html:option></html:select><html:errorsname : <html:text<html:errors</br>address : <html:text<html:errors</br>email : . Figure 15. struts-config.xml). Figure 16. owner.jsp Figure 17. Form validation errors Figure 18. Success. Figure 19. Easy Forward - Global Figure 20. Easy Forward - Local Easy message resource attributes: - If the null attribute is set to true, this causes a null string to be returned for an unknown message key. - The parameter is handed to the factory when the message resource bundle is created. The value of "parameter" is the path to the property file for property-file based factories. - The key attribute defines the ServletContext attribute key under which this message resources bundle is bound. Figure 21. Create Chinese message resource. Figure 22. Validation errors in Chinese. Figure 23. Configure MySQL database. Listing 8. OwnerAction.java - database connectionpublic)return . Figure 24. Configure exceptions. Listing 9. MyExceptionHandler.javapackage. Listing 10. exception.jsp <%@. Figure 25. Handle exceptions - test result Modularizing the Application with Easy Module In this section, you will create a new module named "newModule". To do this, go to the Easy Struts functions view, select "Easy Module" and type in Module name "newModule", as shown in Figure 26. Figure 26. Configure module. Listing 12. action mapping Figure 27. Switch between modules. Figure 28. Configure plugin. Listing 13. MyPlugin.javapackage: - Go to the "Project" menu, choose the "Properties" menu, select the "Tomcat" option and click the "Export to WAR settings" tab. - Click "Browse" of the "WAR file for export", and set the value to folder-of-your-choice/easyStruts.war. Save the setting. - Then go to project popupmenu, select "Tomcat project" and click "Export to the WAR file sets in project properties" from the submenu. - After the message "Operation successful" is displayed, you can go to the location specified in step 2 to get the WAR file.. 1 comment: This is awesome page... i was expecting this stuff only... keep on updating...
http://s3tech.blogspot.com/2008/01/developing-struts-with-easy-struts-for.html
CC-MAIN-2016-50
refinedweb
1,926
58.18
Insert fill circle into cell of QTableWidget There are too many classes to just paint a circle in a cell. There is no other way? @juaniyoalm Well you can also add the circle as an icon to the cell. If you add blank text, the effect is similar. However, how big do u need the circle to be ? It cannot be bigger than the cell height in any case. Update: this was just to answer if there was alternatives. However, a delegate is far better for it. You need one class: the delegate. In this example they have two if you take the custom editor that you likely don't need. Hi Adding to SGaist . Its not as bad as it looks. For a paint circle only delegate, you need very little code. #include <QStyledItemDelegate> #include <QPainter> class CircleDelegate: public QStyledItemDelegate { protected: void paint(QPainter* painter, const QStyleOptionViewItem& opt, const QModelIndex& index) const { // set brush to green if selected else blue ( not needed just for fun) if (opt.state & QStyle::State_Selected) { painter->setBrush(Qt::green); } else { painter->setBrush(Qt::blue); } // paint a circle int CircleSize=10; painter->drawEllipse(opt.rect.center(), CircleSize, CircleSize); } }; and you set it to the table by ui->tableWidget->setItemDelegateForColumn(1, new CircleDelegate()); the 1 is the col where u want it You will need to read over mostly section Item roles as to make circle dynamic in size, you can use a Qt::UserRole and setData. so the size comes from the model. - VRonin Qt Champions 2018 Just a couple of small addition to @mrjj 's code: - you'll probably also need to reimplement sizeHint()to return a size appropriate to contain the circle. - blindly modifying the painter argument is risky. You should call painter->save();before setting the brush and painter->restore();after you finished the painting Thank you, the solution is good for me!!! but I would like that the background of cells is fill too. This colour have to change too. I thought about inserting a rectangle but I would need the circle to be located on top... @juaniyoalm Hi Just use other paint methods like painter->drawRect(opt.rect); @mrjj Thank you so much!! Okay, I have that solved. Another question is that the size of each circle depends on a value that my mushroom class has. In my class I created a paint method but I do not know how to link that method with the delegate or what is the way to write the method. @juaniyoalm Hi, is the value in the model ? The delegate can use values from model. so the color and size of circle could come from model. No, that value is in a c++class. I have to create a custom model... It's ok?? Or I can use a default model?? @juaniyoalm You can use if it is. dont have to be custom. I though you already had a model ? Also is this with a QTableWidget ? (it uses a model already ) @juaniyoalm Super. With view its much easier. so you have to construct a model with the data that comes from the class. Did you make a qstandarditemmodel before ? @juaniyoalm Hi Please read about userRoles and setData section Item roles you can simply put the color / size in user role, or you can have it directly as an item in your model. Both ways are fine. Then delegate read the user role and use the data.??? Please show some patience and allow 24 hours to run before bumping your own thread. This is a community forum where people answer on their own time. They might not even live in the same timezone as you. As for your current trouble. You can build a QAbstractTableModel that will give access to your matrix. For the specific members of your Cellclass, you can use custom roles. I'm sorry, it was my vacation day and I wanted to move forward with the project. I'm sorry. To assign the matrix to the model simply the model creates a variable of the same type as the matrix and initialize the model I assign it in some way, is it correct? I do not understand the roles very well ... You should also provide APIs that will allow you ton modify that matrix. As for the roles, they are there to retrieve specific information from the model's elements. @SGaist said in Insert fill circle into cell of QTableWidget: You should also provide APIs that will allow you ton modify that matrix. As for the roles, they are there to retrieve specific information from the model's elements. I'm sorry but I still do not understand well the models and roles in QT. Can anyone give me an example of how the model class should be? I have a matrix (vector <vector <Cell >>) and when modifying some attributes of the Cell class, have to change what is painted in the graphic representation (Only the one in the cell corresponding to the coordinates of the matrix). @juaniyoalm Hi Its something like this However he uses a std::vector<PersonalData> mydata; where you have vector <vector <Cell >> so you need to use both index.row and index.col to address your matrix. ( the data) I was doing it that way, but how did I assign the matrix to the model variable? At this moment, I am creating the matrix in mainwindow class ... @juaniyoalm Hi well the vector <vector <Cell >> matrix could be inside the model and you would use method like the Addperson in sample to fill it. Much like you do now. when maxtrix is outside of the model. You could also fill it in mainwindow and simply give whole matrix to model to copy it to internal variable.(matrix) but thats a bit waste full. Also i been wanting to ask you. You do use a TableView because you need scrolling correct? I mean there are far more rows with cells than can fit on on screen ? Yes, there is no row limit, it can be 20 rows, 100 or 1000 xD. I always have to think about what I do to behave well when I do the parallel implementation, using pthread and openmp. @juaniyoalm Ok so scrolling is needed:) Also make sure to check out QtConcurrent and QThread before jumping to pthread.
https://forum.qt.io/topic/96545/insert-fill-circle-into-cell-of-qtablewidget/24
CC-MAIN-2019-30
refinedweb
1,054
75
Today someone was asking how he can load a DLL dynamically with .NET. For some design related reasons he didn't want to add a reference to the DLL at compile time. For all I know this might be something everyone knew about except this particular individual and me. But I didn't know anything about this and I had never thought that anyone would want to do anything like that. Anyway as I found out it was really easy. This example is completely in MC++. Just in case someone starts flaming me saying this is an oft-discussed topic, I can always claim this is the first MC++ example. And my google searches kept directing me to pages that talked about normal dynamic loading of DLLs [means the non-.NET stuff] Create a simple class library called Abc.dll. This will be the DLL which we will load dynamically. #include "stdafx.h" #using <mscorlib.dll> using namespace System; namespace Abc { public __gc class Class1 { public: //This simply prefixes a Hello //to whatever string is passed String* Hello(String* str) { return String::Concat(S"Hello ",str); } }; } Okay, this is the little program that will load the above DLL, and call the Hello function, passing a string to it and also getting back the string that the function returns. Remember that Abc.dll must be in the same directory as our program's executable. I believe there are ways to put the DLL in some special directories that all .NET programs look into, but I am totally ignorant of such things. #include "stdafx.h" #using <mscorlib.dll> using namespace System; using namespace System::Reflection; int wmain(void) { //First we load our assembly //using the display name Assembly *a = Assembly::Load("Abc"); //Now we get the type of the object //we want to instantiate. Since our class is //part of the assembly we have to use the full //name of the class with assembly name Type *t = a->GetType("Abc.Class1"); //The MethodInfo class is used to //describe a method. It holds metadata about //a particular method. We get the MethodInfo for //our Hello method MethodInfo *mi = t->GetMethod("Hello"); //Just showing off some public properties Console::WriteLine("Return type of *{0}* method is *{1}*", mi->Name,mi->ReturnType); //We create an instance of our object. //Here the default constructor is called. Object *o = Activator::CreateInstance(t); //Prepare our argument list String *args[] = new String*[1]; args[0]= S"Nish"; //We use Invoke to call the Hello method //on the object we got from CreateInstance above //We pass to it our arguments as an Object array String *s1=static_cast<String*>(mi->Invoke(o,args)); Console::WriteLine(s1); return 0; } This Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/2346/Dynamically-loading-a-DLL-MC?fid=3981&df=90&mpp=10&noise=1&prof=False&sort=Position&view=Expanded&spc=None&fr=11
CC-MAIN-2014-41
refinedweb
470
62.17
mdelay() or udelay() functions, you'll need to include <linux/delay.h> too. The ALSA interfaces like the PCM and control APIs are defined in other <sound/xxx.h> header files. They have to be included after <sound/core.h>. Management of Cards and Components¶ Card Instance¶_new(). struct snd_card *card; int err; err = snd_card_new(&pci->dev, index, id, module, extra_size, &card); The function takes six arguments: the parent device pointer,_new(). The first argument, the pointer of struct struct device, specifies the parent device. For PCI devices, typically &pci-> is passed there. Components¶ snd_card_free(). The next example will show an implementation of chip-specific data. allocation of PCI resources is done in the probe function, and usually an extra xxx_create() function is written for this purpose. In the case of PCI devices, you first have to call the pci_enable_device() function before allocating resources. Also, you need to set the proper PCI DMA mask to limit the accessed I/O range. In some cases, you might need to call¶ The allocation of I/O ports and irqs is done via standard kernel functions. These resources must be released in the destructor function (see: err = pci_request_regions(pci, "My Chip"); if (err <); .... } structure are the vendor and device IDs. If you have no reason to filter the matching devices, you can leave the remaining fields as above. The last field of the struct pci_device_id struct¶ General¶.) { return snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params)); } /* hw_free callback */ static int snd_mychip_pcm_hw_free(struct snd_pcm_substream *substream) { return snd_pcm_lib_free_pages(substream); } /*, }; /* operators */ static struct snd_pcm_ops snd_mychip_capture_ops = { .open = snd_mychip_capture_open, .close = snd_mychip_capture, }; /* *_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(chip->pci), 64*1024, 64*1024); return 0; } PCM Constructor¶ A pcm instance is allocated by the snd_pcm_new() function. It would be better to create a constructor for pcm, namely,; ... buffer allocation method via snd_pcm_lib_malloc_pages(),, struct. PCM open callback¶. close callback¶); .... } ioctl callback¶ This is used for any special call to pcm ioctls. But usually you can pass a generic ioctl callback, snd_pcm_lib_ioctl(). hw_params callback¶). prepare callback¶. trigger callback¶_PUSH as default unless nonatomic flag set, and you cannot call functions which may sleep. The trigger callback should be as minimal as possible, just really triggering the DMA. The other stuff should be initialized hw_params and prepare callbacks properly beforehand. pointer callback¶ as default. copy_user, copy_kernel and fill_silence ops¶. ack callback¶ as default. page callback¶ This callback is optional too. This callback is used mainly for non-contiguous buffers. The mmap calls this callback to get the page address. Some examples will be explained in the later section Buffer and Memory Management, too.); }. get callback¶ This callback is used to read the current value of the control and to return to user-space. For example,. put callback¶ This callback is used to write a value from user-space. For example,.¶ snd_rawmidi_receive() for all received data: void snd_mychip_midi_interrupt(...) { while (mychip_midi_available()) { unsigned char data; data = mychip_midi_read(); snd_rawmidi_receive(substream, &data, 1); } } drain callback¶¶ FM OPL3¶-Dependent). Hardware-Dependent Devices¶. External Hardware Buffers¶ snd_pcm. Vmalloc'ed Buffers¶ It's possible to use a buffer allocated via vmalloc(), for example, for an intermediate buffer. Since the allocated pages are not contiguous, you need to set the page callback to obtain the physical address at every offset. The easiest way to achieve it would be to use snd_pcm_lib_alloc_vmalloc_buffer() for allocating the buffer via vmalloc(), and set snd_pcm_sgbuf_ops_page() to the page callback. At release, you need to call snd_pcm_lib_free_vmalloc_buffer(). If you want to implementation the page manually, it would be like this: #include <linux/vmalloc.h> /* get the physical page pointer on the given offset */ static struct page *mychip_page(struct snd_pcm_substream *substream, unsigned long offset) { void *pageptr = substream->runtime->dma_area + offset; return vmalloc_to_page(pageptr); }. snd_BUG()¶ It shows the BUG? message and stack trace as well as snd_BUG_ON() at the point. It's useful to show that a fatal error happens there. When no debug flag is set, this macro is ignored. snd_BUG_ON()¶ s, if the expression is non-zero, it shows the warning message such as BUG? (xxx) normally followed by stack trace. In both cases it returns the evaluated value.
https://www.kernel.org/doc/html/latest/sound/kernel-api/writing-an-alsa-driver.html
CC-MAIN-2019-47
refinedweb
677
59.09
On Sunday 30 March 2003 12:29 am, Tom Chance wrote: > Hull/ This isn't valid Python. > Now that function isn't in that dialogue's class... it's in the namespace > that is calling the class instance, e.g.: > > def function1(self): > /do some stuff.../ > instance = Inherited() > > def function2(self): > /do some stuff.../ Are these class methods or functions? Functions don't (to be more accurate, shouldn't) have self arguments. >? It isn't clear which function2() you want to connect to. Either way, simply use the name in the call to connect(), ie. QObject.connect(sender,SIGNAL('sig()'),Inheritor.function2) ...or... QObject.connect(sender,SIGNAL('sig()'),function2) See Phil
https://mail.python.org/pipermail/python-list/2003-March/176148.html
CC-MAIN-2017-04
refinedweb
111
62.44
Am Freitag, 7. November 2008 19:22:56 schrieb Steven Siebert:[color=blue] > Perfect! Great info from both...exactly what I needed. After > Torsten's response, I theorized that I could abstract that > functionality up and reveal a thin API for the creation/calling of > singleton objects within a namespace in pnotes....but that seems to > have already been done with Apache::Singleton::Request. I'm glad I > decided to ask the experts before attempting a hack myself. Thanks > guys! > > On Fri, Nov 7, 2008 at 1:18 PM, bharanee rathna <deepfryed@gmail.com> wrote:[color=green][color=darkred] > >> The simplest way is to put the object as a pnote:[/color] > > > > What Torsten said, but have a look at > > > > [url][/url] > >on.pm > > > > Apache::Singleton::Request is probably what you want.[/color][/color] I couldn't get Apache::Singleton working with mp2 (used it before with no problems with mp1). so I switched back to Class::Singelton and, at the top of my handler (MasonX::WebApp) destroy the old instance and create a new one. I couldn' t find ouy why it failed with mp2 since I had not much time and my app had to become ready. The failure showed in a "hanging" request. The reason why I use Class::Singelton (and not $r->pool or $r->pnotes) is just, that I can reuse my perl modules in all apps running as stand alone scripts. So for instance , I put my DBIx;:Class schema object in there, the logging handler etc. -- Rolf Schaufelberger
http://fixunix.com/modperl/555970-re-fwd-mpm-safe-mp2-singleton-pattern-print.html
CC-MAIN-2015-11
refinedweb
254
65.93
Contents Strategy Library Ichimoku Clouds in the Energy Sector Abstract Gurrib (2020) is the first published research paper to analyze the predictive power of Ichimoku Clouds for the largest 10 stocks in the US energy sector. In this tutorial, we implement a similar strategy while reducing the effect of look-ahead bias integrated into the original study. Our findings show that while the strategy has an impressive 176 Sharpe ratio during the downfall of the 2020 oil price war, the strategy has worse performance than found by Gurrib (2020). We discover that throughout a 5 year backtest, the strategy fails to beat the benchmark of a popular energy sector ETF. Introduction A vast amount of research studies have been published which document mixed results when utilizing technical analysis to forecast future prices of securities. The Ichimoku Cloud, one of the most widely-used technical indicators in Japan, was first publicized by Goichi Hosoda. In 1996, Hidenobu Sasaki reworked the framework to form the current charting analysis tool. This indicator is composed of 5 lines in a time series, each of which are described mathematically in online resources. Gurrib (2020) finds that applying a simple trading strategy using the time series of the Ichimoku Cloud can increase the mean return of a basket containing the top energy stocks from 21.5% (buy-and-hold) to 194% over a 7 year period. The components of the Ichimoku Cloud that Gurrib (2020) utilizes in this strategy are the Chikou Span, Senkou Span A, and Senkou Span B. The Senkou Span lines form the top and bottom of the Ichimoku Cloud. The strategy that we trade off of these lines is defined as follows: - Long when the Chikou line crosses the top of the cloud from below. - Short when the Chikou line crosses the bottom of the cloud from above. For better understanding, here is a visualization of the price of XOM, it's Ichimoku Cloud time series, and the resulting buy/sell signals. Note: all of the plots throughout this tutorial are reproducible in the attached research notebook, along with some descriptive statistics for securities in the universe. Method Universe Selection Gurrib (2020) selects a universe of the 10 largest-weighed constituents of the S&P Composite 1500 Energy Index over the testing period. This inherently incorporates lookahead-bias into the study as the security weights are sourced over the period the trading simulation occurs. Furthermore, since the publication of Gurrib (2020), some of the securities have even been delisted. Thus, to eliminate lookahead-bias and avoid delistings, we implement a universe selection model that provides the trading system with the 10 largest companies in the energy sector as of the current date in the backtest. Since the largest companies change infrequently, we only refresh the universe on a monthly basis. def SelectCoarse(self, algorithm, coarse): if algorithm.Time.month == self.month: return Universe.Unchanged return [ x.Symbol for x in coarse if x.HasFundamentalData ] def SelectFine(self, algorithm, fine):] ] Alpha Construction The IchimokuCloudCrossOverAlphaModel emits insights to hold a long position after the Chikou Span crosses over the top of the cloud for a given security. Additionally, the strategy is made symmetrical by entering short positions after the Chikou Span crosses below the bottom of the cloud. During construction of this alpha model, we simply set up a dictionary to hold a SymbolData object for each symbol in the universe. class IchimokuCloudCrossOverAlphaModel(AlphaModel): symbol_data_by_symbol = {} The SymbolData class constructor is shown below. We first set up two class variables, `previous_location` and `direction`. The former enables the algorithm to signal when the Chikou Span crosses over the boundaries of the Ichimoku Cloud. The latter is added to ensure we continue to emit daily insights in the proper direction. Inside the `__init__` method is where we create the IchimokuKinkoHyo indicator and warm it up. class SymbolData: previous_location = None direction = None def __init__(self, symbol, algorithm): #) Determining the Indicator Location We define the following helper method to return the location of the Chikou Span with respect to the cloud. The alpha model utilizes this helper method to determine when the Chikou Span is exiting the Ichimoku Cloud. def get_location(self): Alpha Update As new TradeBars are provided to the alpha model's Update method, we update the Ichimoku indicator of each symbol. We then emit insights for the symbols that have their Chikou Span breaking out of their respective Ichimoku Cloud in a new direction. To maintain positions while we wait for another crossover in the Ichimoku Cloud, we emit insights on a daily basis with 1-day duration. def Update(self, algorithm, data): Portfolio Construction & Trade Execution Following the guidelines of Alpha Streams and the Quant League competition, we utilize the EqualWeightingPortfolioConstructionModel and the ImmediateExecutionModel. Relative Performance To analyze the value of this trading strategy, we compare its performance to buying and holding a popular ETF tracking the energy sector. In this study, we use XLE, the Energy Select Sector SPDR® Fund, as the benchmark. We can see from the plot below how the portfolio would have performed just had we had just invested in the benchmark. We now analyze the Sharpe ratio and annual standard deviation of returns for both the strategy and the benchmark. From the table below, we can see the results of the strategy and the benchmark over the entire backtest period, the Fall 2015 crisis, and the 2020 oil price war. The strategy has a lower Sharpe ratio than the benchmark across all of the time periods we tested, except for the crash during the 2020 oil price war, where it generated an impressive 176 Sharpe ratio. We can also see the strategy has a lower annual standard deviation accross all of the time frames, implying that the strategy has more consistent returns than the benchmark. We find the lack of performance for this strategy is not largely attributed to the transaction costs. After ignoring the transaction fees, spread costs, and slippage, the strategy still has a lower Sharpe ratio than the benchmark and doesn't match the results found in the original research paper. See the backtest results here. Market & Competition Qualification Although this strategy passes several of the metrics required for Alpha Streams and the Quant League competition, it requires further work to pass the following requirements: - Profitable - PSR >= 80% - Max drawdown duration <= 6 months - Insights contain the following properties: Symbol, Duration, Direction, and Weight - Minute or second data resolution Conclusion While the strategy examined herein produces a 176 Sharpe ratio throughout the downfall of the 2020 oil price war and stock market crash, we conclude the strategy does not currently provide as profitable of results as documented by Gurrib (2020). The strategy experiences a -0.234 Sharpe ratio over the entire backtest period. To continue the development of this strategy, future areas of research include: - Only trading when a bullish or bearish trend are confirmed. Gurrib (2020) provides conditions for evaluating the trend. - Adjusting the data resolution used within the indicator. - Considering fundamental or alternative data points before placing trades. - Adjusting the parameters of the Ichimoku indicator. - Replacing the portfolio construction model with one that only allocates 10% of the capital base to each security. This will violate the requirements of the Alpha Streams and Quant League competition, but it will reduce the transaction costs and provide a more accurate equity curve of the underlying strategies performance. References - Gurrib, Ikhlaas, Can the Leading Us Energy Stock Prices Be Predicted Using Ichimoku Clouds? (January 16, 2020). Online Copy You can also see our Documentation and Videos. You can also get in touch with us via Chat. Did you find this page helpful?
https://www.quantconnect.com/tutorials/strategy-library/ichimoku-clouds-in-the-energy-sector
CC-MAIN-2021-17
refinedweb
1,273
51.68
So before I dive into an explanation of this feature I’d better explain what I’m doing here. Firstly have a look at Figure 1. Figure 1 – Cascading ForeignKey_Edit like FieldTemplates In Figure 1 you can see two DropDownLists Category and Products is this form you are only allowed to choose a product the matches the selected category. So what is required, is when Category is changes then the contents of Product should be regenerated to be filtered by the chosen Category. I hope that make some sense. The requirements for the above to work are: - A way to get the parent DetailsView from inside a FieldTemplate. - Some way of finding the FieldTemplate from the parent control tree of the dependant FileTemplate. - Some way of getting the dependee FieldTemplate to fire an event on the dependant FieldTemplate when a change is made on dependee. - An Attribute to tell the control which control to use as the dependee control. 1. Getting the parent control The first step would be to climb the parent tree using a generic extension method. /// <summary> /// Get a parent control of T from the parent control tree of the control /// </summary> /// <typeparam name="T">Control of type T</typeparam> /// <param name="control">Control to search in for control type T</param> /// <returns>The found control of type T or null if not found</returns> public static T GetParent<T>(this Control control) where T : Control { var parentControl = control.Parent; while (parentControl != null) { var formView = parentControl as T; if (formView != null) return formView; else parentControl = parentControl.Parent; } return null; } Listing 1 – Get Parent generic extension method I decided that a generic method was required as I had not only the DetailsView but also the FormView to deal with. The logic is simple here all that happens is that the parent of the current cointrol is cast as the T type and if it is not null then we have the control we are looking for, if it is null then the loop continues and the parent of the parent is tested and so on until a match is found or a parent is null. This get’s us the hosting control of the type we want. 2. Finding the Dependee FieldTemplate At first I thought I could use the handy extension method FindFieldTemplate but it always returned null. So I had to go my own way and came up with this: /// DynamicControlRecursive(this Control root, string dataField) { var dc = root as DynamicControl; if (dc != null) { if (dc.DataField == dataField) return dc; } foreach (Control Ctl in root.Controls) { Control FoundCtl = FindDynamicControlRecursive(Ctl, dataField); if (FoundCtl != null) return FoundCtl; } return null; } Listing 2 – FindDynamicControlRecusive This is based on a function I found here How to find a control when using Master Pages the change is simple all I do is cast the control as DynamicControl and then test for null if not null then I can test the DataField which I know had the column name in it. This however only gets us the DynamicControl next we have to extract the field which is held in the DynamicControl’s Controls collection //; Listing 3 – Fragment: Extracting the FieldTEmplate from the DynamicControl Now providing that the control we are after in in slot [0] of the DynamicControl’s Controls collection we are away . 3. Getting an event fired on the Dependant FieldTemplate when the Dependee’s DropDownList changes Ok for this to work we need to expose the DropDownList’s OnSelectedIndexChanged event and also the SelectedValue property, here’s the code for that in Listing 4. public override event EventHandler SelectionChanged { add { DropDownList1.SelectedIndexChanged += value; } remove { DropDownList1.SelectedIndexChanged -= value; } } public override string SelectedValue { get { return DropDownList1.SelectedValue; } } Listing 4 – Exposing the OnSelectedIndexChanged event and the SelectedValue property This is fine but when I get a copy of the control from the earlier code I need to get access to this exposed event and property. So here's how we will do that we’ll create a class that inherits /// <summary> /// A class to add some extra features to the standard /// FieldTemplateUserControl /// </summary> public class AdvancedFieldTemplate : FieldTemplateUserControl { /// <summary> /// Handles the adding events to the drop down list /// </summary> public virtual event EventHandler SelectionChanged { add { } remove { } } /// <summary> /// Returns the selected value of the drop down list /// </summary> public virtual string SelectedValue { get { return null; } } } Listing 5 – AdvancedFieldTemplate class As you can see from Listing 5 this class inherits the FieldTemplateUserControl class the a FieldTemplate inherits, so we inherit that and then on the custom FieldTemplates we want to cascade we set them to inherit the AdvancedFieldTemplate. Next we need an event handler to handle the event passed to this the dependant control. protected void SelectedIndexChanged(object sender, EventArgs e) { var ddl = sender as DropDownList; if(ddl != null) PopulateListControl(DropDownList1, ddl.SelectedValue); } Listing 6 – Event handler 4. The Attribute Attribute have been cover a lot on this site so I’m just going to post the code and comment a very little. [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public class DependeeColumnAttribute : Attribute { public static DependeeColumnAttribute Default = new DependeeColumnAttribute(); public DependeeColumnAttribute() : this("") { } public DependeeColumnAttribute(String columnName) { ColumnName = columnName; } public String ColumnName { get; set; } } Listing 7 – DependeeColumnAttribute I could of course hard coded the dependee column in to each custom FieldTemplate but of course that assumes that every time you use the FieldTEmplate the dependee column will have the same name, which is not always the case. 5. Putting it All Together Firstly we need the extension method that get us the dependee control: public static AdvancedFieldTemplate GetDependeeField<T>(this Control control, MetaColumn column) where T : Control { // get value of dev ddl (Community) var detailsView = control.GetParent<T>(); // get parent column attribute var dependeeColumn = column.GetAttribute<DependeeColumnAttribute>(); if (dependeeColumn != null) { //; return dependeeField; } return null; } Listing 7 – GetDependeeField In Listing 7 we return the FieldTemplate extracted from the found DynamicControl so in the Page_Load event we get the dependee control and assign it the event handler so that we can capture the SelectedIndexChanged event of the dependee DropDpownList. protected void Page_Load(object sender, EventArgs e) { if (DropDownList1.Items.Count == 0) { if (!Column.IsRequired) DropDownList1.Items.Add(new ListItem("[Not Set]", "")); PopulateListControl(DropDownList1, ""); } // get dependee field var dependeeField = this.GetDependeeField<DetailsView>(Column); // add event handler if dependee exists if (dependeeField != null) dependeeField.SelectionChanged += SelectedIndexChanged; } Listing 8 – Page_Load event The lines in BOLD ITALIC are the added lines and demonstrates the use of GetDependeeField extension method. protected override void OnDataBinding(EventArgs e) { base.OnDataBinding(e); if (Mode == DataBoundControlMode.Edit) { var dependeeField = this.GetDependeeField<DetailsView>(Column); if (dependeeField != null) PopulateListControl(DropDownList1, dependeeField.SelectedValue); string foreignkey = ForeignKeyColumn.GetForeignKeyString(Row); ListItem item = DropDownList1.Items.FindByValue(foreignkey); if (item != null) { DropDownList1.SelectedValue = foreignkey; } } } Listing 9 – OnDataBinding event handler Again in BOLD ITALIC are line are are added. An finally some metadata [MetadataType(typeof(Order_DetailMD))] public partial class Order_Detail { public class Order_DetailMD { public object OrderID {get;set;} public object ProductID {get;set;} public object UnitPrice {get;set;} public object Quantity {get;set;} public object Discount {get;set;} public object CategoryID {get;set;} // EntityRefs [DependeeColumn("Category")] [UIHint("Product")] [ColumnOrder(2)] public object Product {get;set;} [UIHint("Category")] [ColumnOrder(1)] public object Category {get;set;} } } In the attached project I've also implemented some column ordering to arrange the columns in the order that makes sense if they cascade. There are two part to this solution which I didn’t make clear: - The properties that allow a the control’s OnSelectedIndexChanges event to be captured. - Finding the dependee control and capturing it’s OnSelectedIndexChanges event and reading it’s SelectedValue. It must be noted that if both controls implement all the features there won’t be a problem but if you do it in only the dependant control the you won’t be able to capture the OnSelectedIndexChanges event of the dependee control or read it’s SelectedValue. So you must at least implement 1. in the dependee control and 2. in the dependant control. I hope this clarifies things. Setting up Northwind to work with the sample Here’s a diagram showing the changes I made to Northwind to facilitate this example (as there were no columns that fitted this scenario). Figure 2 – Diagram of changes to Order_Details table Figure 3 – Added Relationship in the Model And here’s the T-SQL to update the CategoryID column in Order_Details once you've added it. USE [Northwind] GO UPDATE [Order Details] SET [Order Details].[CategoryID] = p.[CategoryID] FROM [Products] p WHERE p.[ProductID] = [Order Details].[ProductID] SELECT * FROM [Order Details] Listing 11 – SQL to update Oder_Details Oh and the Download 30 comments: Thanks. Great work. But one thing I dont understand. We should fix all tables where we want to use cascading with script like in listing 11? I think it is not very good. Also can we use it in Dynamic Data EF projects? Sorry no Listing 11 is just for the sample as I'd messed about with Northwind. I added a column and I then populated it with data from the Products table. This is a paticular case where you have two or more columns in a table that would filter each other i.e. say you have a Products table that has two FK columns say Categories and Manufacurers where you would only want to show manufacurers who mached a category. Hope that makes sense I'll update the article to say so regardign the use of the script Hello, thanks for this blog, exactly what I need at the moment :-) But I have a problem: When I want to do an insert or edit, it is never executed. I can see in SQL Profiler, that there is a NULL value (which is not allowed in DB) instead of the category ID. Moreover the category ID and the product ID change place: HTML: ... categoryID = 11 productID = 19 ... SQL: ... @p2 = 19 @p3 = NULL ... In the HTML page I can see the correct values in the category dropdown, but it gets somehow lost while executing the INSERT statement. Can you give e a hint? Thanks a lot, Alex I recommend you post a question on the Dynamic Data Forum here Details you should give are Model Linq to SQL or Entity Framework, and try and pose you question from a well known DB lkke Northwind because thisway we will be abvle to repro it ourselves give as much detail as you can see this post by David Ebbo on wht to include Steve :D Hello, I have a dropdownlist in the DetailView of the List page. Which is bind by the values of other table. We need to have an selectIndexchange event on the dynamicdatacontrol. Can you please tell us, how we can have this? Thanks, Hello Stephen, thanks for this blog, i read your job and i implement this solution on my project..but this idea dosn't work for me. When i build the solution i receive this error :"Error 11 No overload for method 'GetDependeeField' takes '1' arguments". The method in class ExtensionMethods take two arguments..like [public static AdvancedFieldTemplate GetDependeeField 'T' (this Control control, MetaColumn column) where T : Control] but in the Page_Load method we pass only one Arguments..maybe i'm missing anything? Have you downloaded the project and tested that? Note: with Northwind you need to hack the relationships and primary keys I can supply a sample if you like. Steve Yes i downloaded zip file..i create a new project for test your job after that i tested the code on my DynamicData Web Application, but building error is also relieved. I don't understand where is my error...i don't find GetDependeeField overload extension method that accepts only 1 arguments like you used on "Listing 8 – Page_Load event". The only implemantion that i found is in "Listing 8 – Page_Load event" and we pass two arguments. Tanks for your help..and sorry for my english.. :-D Nicola It's probably a syntax error it's easy with generics :D Steve How we can use this example for another scenario, because this we can use only in particular case where you have two or more columns in a table that would filter each other. I want to develop cascading data from another tables, for example Category, Subcategory and Products tables. I tried to use your another article for this case . But there is some bugs in Edit mode. Thanks. Hi Azamat, I would for the time being create a custom FieldTemplate for this which is what I've had to do, I just havent had the time to look at the Expression syntax that would be needed to show the edit value in cascade. Sorry Steve :D Hi stephen, i'm Nicola, i re-test your code on my project and now it's work fine with 3 DropDownList (i've Category---> Type ---> SubType), but there is only a problem. When i change the Category the event handler not have effect on my third Dropdown (that is called SubType) but works fine on the Types DropDown. Do Yuo have any Idea how i can handled the event on Category changing that is submitted to sutype DropDownList? Is possible make two DependeeColum on the same property? Like this.. [UIHint("Type")] [DependeeColumn("Category")] public object Type {get;set;} [UIHint("subType")] [DependeeColumn("Category")] [DependeeColumn("Type")] public object SubType {get;set;} [UIHint("Category")] public object Category {get;set;}.. It looks to me like you have two DependeeColumn attribute on one column here: [DependeeColumn("Category")] [DependeeColumn("Type")] public object SubType {get;set;} What I've found is the cascade only ripples one level at a time, so: 1st level a value is selected and then 2nd level is reset to be limited to the selected value of the 1st level, 2nd level a value is selected and so the third level is limited to the value selected in the second level. And so on... What I would like to happen is until a value is selected in the dependee column for the DDL to be disabled. thus forcing you to select the 1st, then 2nd, then 3rd etc. I will probably get to this in the next release of DD or atleast the next preview of that release. Steve :D Hello, Thanks for all your work and examples. Could you perhaps check whether it would be possible to use this solution with .NET 4.0? I tried and get null reference exception when setting dependeeField around line 60 of Product_Edit.ascx.cs. Currently I'm using it with .NET 3.5 SP1, but would like to migrate to 4.0 when it becomes RTM. Let me know if you need some more details! Hi Pawel, I'm waiting for Beta 2 which should have more of DD that will ship in .net 4.0. but at the moment it should work as there are no real differences between DD v1.0 and whats in VS2010 Beta 1. When I get a moment I will run the sample up in VS2010 Beta 1 and see what happens. As I side note I will be converting all my sample to VS2010 when we get to Beta 2 and will put some on codeplex.com Steve :D P.S. feel free to e-mail me :D Hey, thanks a lot for a great blog. I have been trying to ajust you samle to work with listview but without success. In the module ExtensionMethodes the // setup the selection event if (dependeeDynamicControl != null) dependeeField = dependeeDynamicControl.Controls[0] as AdvancedFieldTemplate; dependeeField always get set to null... Do you have any sugestion how i can do this ? thanks in advance /peter Hi Peter, the reasone is that in a gridview you could perhaps search the Row for the fieldTemplate but in a ListView you have no knowledge of the structure that the FieldTemplate is in. Steve :D Is it possible to find this code in VB? I do have a sample in VB just send me an e-mail an I'll dig it out, I did it for a guy in Hong Kong But you are on your own with VB :( I get a head ache every time I go back to VB. Steve I didn't knew c# was so popular (I'm begining with .net) I think I'm going to migrate my project to c# and use DD Futures too. Yes C# is cool im my opinion not because it is any better than VB but because it is so like JavaScript, Java, ActionScript etc. Steve :D Hi Stephen, You're the best man. Thanks for sharing your knowledge. i am getting the following error when i run the application. The associated metadata type for type 'DynamicDataFutures.Order_Detail' contains the following unknown properties or fields: Category. Please make sure that the names of these members match the names of the properties on the main type. It sound like you have a property in your metadata that does not match aproperty in your model. Steve I'm getting NullReferenceException in function FindDynamicControlRecursive a line (no 93) foreach (Control Ctl in root.Controls). My project is in asp.net 4.0, can u tell me what I'm doing wrong. Hi, I have implemented this code for country and state dropdownlist, the build is successful but on running it it giving "Could not find key member 'ID' of key 'ID' on type 'State'. The key may be wrong or the field or property on 'State' has changed names." why this error occurring ? Hi kapil, this is a very old post try my on Steve sorry wrong Nuget package try this one Steve thanx steve. :) Thanks, I found this really helpful. Not understanding this that well at first, it took me a while to figure out that I had to change the parameter to match the structure in my page -- in my case a . Worked great for me after that! Mark
http://csharpbits.notaclue.net/2009/01/dynamic-data-cascading-fieldtemplates.html
CC-MAIN-2017-30
refinedweb
2,984
53.41
Since Python is a dynamic language, it is easy to add interceptors to any method in Connector/Python, without having to extend the connector with specific code. This is something that is possible in dynamic languages such as Python, Perl, JavaScript, and even some lesser known languages such as Lua and Self. In this post, I will describe how and also give an introduction to some of the (in my view) more powerful features of Python. In order to create an interceptor, you need to be able to do these things: - Catch an existing method in a class and replace it with a new one. - Call the original function, if necessary. - For extra points: catch an existing method in an object and replace a new one. In order to understand how the replacement works, you should understand that in Python (and the dynamic languages mentioned above), all objects can have attributes, including classes, functions, and a bunch of other esoteric constructions. Each type of object has a set of pre-defined attributes with well-defined meaning. For classes (and class instances), methods are stored as attributes of the class (or class instance) and can therefore be replaced with other methods that you build dynamically. However, it requires some tinkering to take an existing "normal" function definition and "imbue" it with whatever "tincture" that makes it behave as a method of the class or class instance. Depending on where the method comes from, it can be either unbound and bound. Unbound methods are roughly equivalent to member function pointers in C++: they reference a function, but not the instance. In contrast, bound methods have an instance tied to it, so when you call them, they already know what instance they belong to and will use it. Methods have a set of attributes, of which the four in Table 1 interests us. If a method is fetched from a class (to be precise, from a class object), it will be unbound and im_self will be None. If the method is fetched from a class instance, it will be bound and im_self will be set to the instance it belongs to. These attributes are all the "tincture" you need make our own instance methods. The code for doing the replacement described above is simply: import functools, types def replace_method(orig, func): functools.update_wrapper(func, orig.im_func) new = types.MethodType(func, orig.im_self, orig.im_class) obj = orig.im_self or orig.im_class setattr(obj, orig.__name__, new)The function uses two standard modules to make the job simpler, but the steps are: - Copy the meta-information from the original method function to the new function using update_wrapper. This copies the name, module information, and documentation from the original method function to make it look like the original method. - Create a new method instance from the method information of the original method using the constructor MethodType, but replace the "inner" function with the new function. - Install the new instance method in the class or instance by replacing the attribute denoting the original method with the new method. Depending on whether the function is given a bound or unbound instance, either the method in the class or in the instance is replaced. from mysql.connector import MySQLCursor def my_execute(self, operation, params=None): ... replace_method(MySQLCursor.execute, my_execute)This is already pretty useful, but note that you can also replace only a specific instance as well by using replace_method(cursor.execute, my_execute). It was not necessary to change anything inside Connector/Python to intercept a method there, so you can actually apply this to any method in any of the classes in Connector/Python that you already have available. In order to make it even easier to use you'll see how to define a decorator that will install the function in the correct place at the same time as it is defined. The code for defining a decorator and an example usage is: import functools, types from mysql.connector import MySQLCursor def intercept(orig): def wrap(func): functools.update_wrapper(func, orig.im_func) meth = types.MethodType(func, orig.im_self, orig.im_class) obj = orig.im_self or orig.im_class setattr(obj, orig.__name__, meth) return func return wrap # Define a function using the decorator @intercept(MySQLCursor.execute) def my_execute(self, operation, params=None): ...The @interceptline before the definition of my_executeis where the new descriptor is used. The syntax is a shorthand that can be used to do some things with the function when defining it. It behaves as if the following code had been executed: def _temporary(self, operation, params=None): ... my_execute = intercept(MySQLCursor.execute)(_temporary)As you can see here, whatever is given after the @is used as a function and called with the function-being-defined as argument. This explains why the wrapfunction is returned from the decorator (it will be called with a reference to the function that is being defined), and also why the original function is returned from the wrapfunction (the result will be assigned to the function name). Using a statement interceptor, you can catch the execution of statements and do some special magic on them. In our case, let's define an interceptor to catch the execution of a statement and log the result using the standard logging module. If you read the wrap function carefully, you probably noted that it uses a closure to access the value of orig when the decorator was called, not the value it happen to have when the wrap function is executed. This feature is very useful since a closure can also be used to get access to the original execute function and call it from within the new function. So, to intercept an execute call and log information about the statement using the logging module, you could use code like this: from mysql.connector import MySQLCursor original_execute = MySQLCursor.execute @intercept(MySQLCursor.execute) def my_execute(self, operation, params=None): if params is not None: stmt = operation % self._process_params(params) else: stmt = operation result = original_execute(self, operation, params) logging.debug("Executed '%s', rowcount: %d", stmt, self.rowcount) logging.debug("Columns: %s", ', '. join(c[0] for c in self.description)) return resultNow with this, you could implement your own caching layer to, for example, do a memcached lookup before sending the statement to the server for execution. I leave this as an exercises to the reader, or maybe I'll show you in a later post. &smiley; Implementing a lifecycle interceptor is similar, only that you replace, for example, the commit or rollback calls. However, implementing an exception interceptor is not obvious. Catching the exception is straightforward and can be done using the interceptdecorator: original_init = ProgrammingError.__init__ @intercept(ProgrammingError.__init__) def catch_error(self, msg, errno): logging.debug("This statement didn't work: '%s', errno: %d", msg, errno) original_init(self, msg, errno=errno)However, in order to do something more interesting, such as asking for some additional information from the database, it is necessary to either get hold of the cursor that was used to execute the query, or at least the connection. It is possible to dig through the interpreter stack, or try to override one of the internal methods that Connector/Python uses, but since that is very dependent on the implementation, I will not present that in this post. It would be good if the cursor is passed down to the exception constructor, but this requires some changes to the connector code. Even though I have been programming in dynamic languages for decades (literally) it always amaze me how easy it is to accomplish things in these languages. If you are interested in playing around with this code, you can always fetch Connector/Python on Launchpad and try out the examples above. Some links and other assorted references related to this post are: - Connector/Python is found at launchpad.net/myconnpy - Geert has a number of excellent posts on Connector/Python under geert.vanderkelen.org. Also, as you might already know, he is now working with developing Connector/Python and he's always interested in comments and suggestions. :) - Todd's Blog mysqlblog.fivefarmers.com is always interesting to read, and these articles on interceptors are the ones I read 2 comments: Mats,. Best, Eric Genesky Community Curator DZone.com.
http://mysqlmusings.blogspot.se/2012/01/mysql-python-meta-programming-and.html
CC-MAIN-2015-27
refinedweb
1,372
53.21
December 2015 At long last The Spy’s series The Throne is starting to see the light of day. The first book, Culmanic Parts was published in June. Now, the second, Rea’s Blood or Navy Girl is available from publisher Writers Exchange. See the URLs below. The third book Tara’s Mother is in publishers’s editing as we write, and the fourth The Paladin is undergoing second proofing before being made available to the Spy’s volunteer reader/correctors. These books are background to the Alternate History series The Interregnum, which currently has six volumes published. The Throne was intended to be the final book in that series, but has grown into a four-book series of its own. The first three books of The Throne can be read as a standalone trilogy, and The Paladin will offer conclusions to both series. The original intent was to offer a brief history of alternate earth Hibernia–how Ireland came to be the world’s superpower, and something of the history of how we got to the situation described in The Interregnum, which covers 1941-2001. Chapters set about a century apart starting in the eleventh century interspersed with those on the restoration of royal rule in 2001 were to form the concluding book. However, this got out of hand in the fourteenth century, which ended up becoming over 700K words and most of three books. Culmanic Parts has a brief chapter on the events of 1014 when Brian Boru survived the battle and established an enduring throne, one proof against English/Norman incursions, indeed that came to dominate the Irish Isles and become the United Kingdom of Ireland, Wales, Scotland, and England. Section two is a longer story involving a restoration of the kingdom after a civil war in the fourteenth century, and relates how the leaders of that time began the Culmanic (scientific) and industrial revolution, named after King Cullen and his associate Rufus Maynard, and given impetus by its chief practitioner Katie the horse girl. The larger remainder of the first volume tells of super spy Carlan Rea’s adopted daughter Amy, a.k.a. “slum girl” the inheritor of the Culmanic mantle in the early fifteenth century, who wins a scholarship to the elite Royal Academy, absorbs nine rich kids into her orbit, and takes academia by storm. Since all the best academies are military, the Diechara (“ten friends”) graduate with Royal Army commissions into a hot war with Spain–Amy defying conventional wisdom by joining a lesser service, the Royal Army Naval Corps. But why has the Assassins’ Guild three contracts on her life? The second volume, Rae’s Blood or Navy Girl, details Amy Rea’s career in RANC through the rapid growth and deployment of Ireland’s naval force, her engagements in three fleets operating in the Mediterranean, at the southern cape, the Orient, back to the battle of the Nile, and then Trafalgar. Along the way she forms a band of brothers and sisters from many nations who are willing to follow her to hell and return with its gates in their ship’s hold. The third volume, Tara’s Mother, which may see the light of day as early as December, follows up with the survivors of Trafalgar, who must still fight the decisive land battle against the forces of the French emperor at Mt. Sainte Jean and deal with the ruthless and cruel Spanish dictator Carlos. But the biggest problem monarch of all is Ireland’s corpulent and corrupt King Frederick. We follow Amethyst Meathe and associates through foreign land and sea battles to the streets of the despairing Irish capital of Tara, where she tries to ignite a new beginning. What is her great secret, the secret of the ages? Volume four, The Paladin, follows the subsequent history of the Irish throne after the day of Amy and Amethyst, beginning in 1492, when a woman rolls from a dumpster into the Dublin city garbage dump. She has no past, no memories, and has apparently been killed, her body burned. But she has remarkable recuperative powers, and it soon becomes evident that she is another like the two versions of Cain from the first nexus–after a death, what’s left of her body resets, though with memory issues–and intended to assist Samadeya-Qayin in his millennia-old battles with Pelik-Qayin, the enemy of all that is God or good, as the two vie for The Throne of Ireland. But she suffers from identity angst and isn’t always a willing participant, so God disciplines her harshly. Who is she, really? In interleaved story-cycle fashion, this volume also tells the story of Karina Tansey, a character introduced in The Interregnum, and through her eyes we learn more about the real events of the first battle of Glenmorgan, and baby Mara Meathe, who is one of the main characters of The Interregnum. Finally, and also in interspersed chapters, it tells of events in 2001 that lead up to and takes us through the Second Battle of Glenmorgan, fought by the Royal forces under General of the Armies Mara Meathe and her associates against the racist, xenophobic and virulently anti-Christian former bishop of Tara, the MacCarthy Mor, Philip Desmond. Side stories tell of Lucas Caine, son by rape of Pelik, and his coming of age and maturity, as he become Mara’s Vice-Commander, but then… Well, suffice it to say that all wraps up, sans a number of characters. Hope you enjoy the books. They’ve been a long time in production. When you invest in a skookum NAS like the 8-bay Synology 1815+, you want to be able to access it reliably from the outside, for configuration purposes, to set up a cloud, or to set up mail or web sites. However, home IP numbers are dynamic, and your provider may change them more or less frequently. Thus the need for DDNS (dynamic DNS), which is simply a name for the technique of allowing a home computer, modem, or NAS to periodically check its own IP number and reset the number on a registered domain so that it passes traffic to the correct numerical address from a fixed domain name. What follows below is a Python script to do just that. It presupposes that the domain in question is registered at Enom, that a domain password has been set, and that Python is running on the machine where the script is located. The Spy created a directory called “code” in his user folder on his Mac, and put the script there, activated Python, and ran it. It works! For best results, set up a cron job to run it, say once every half hour. On the ASUS3200 modem, select “Administration” under the “Advanced Settings” and the “System” tab, then click “Yes” under “Enable Web Access from Wan” and leave the port at 8080. Warning: don’t select “Allow only specified IP address” unless you ensure that you do indeed add several local and remote addresses, or the modem will be inaccessible. If you want to access your NAS, then select “WAN” and its “Port Forwarding” tab, enable Port Forwarding, then fill in the list with, say, for the Synology, http, Port 5000, the local IP of the NAS (selected from the drop down) the local port as 5000, and TCP protocol. Be sure to clock both the add button and “Apply”. It is now possible to access both the modem and the NAS with a web browser from outside the home network. The Script #!/usr/local/bin/python ############################################## # DNSUpdateEnom.py by: Rick Sutcliffe # ———————— # A python script to update the DNS IP for a domain registered at Enom. # # Assumes: # domain is registered with Enom # nameservers are set to Enom’s # domain password set # python installed # Recommended : run this with a cron periodically ############################################## # imports import urllib2, os # Declarations ip_check_url = ‘’ # What is my IP? many such services can return the IP as text last_set_ip_path = ‘./last_set_ip.txt’ # Text file to store last IP set by this program domain = ‘subdomain.domain.com’ # domain to be edited password = ‘******’ # password on domain at registrar enom_url = ‘’ # get current IP for the site current_ip = urllib2.urlopen(ip_check_url).read() # rest of declarations settings = {‘enom_url’: enom_url, ‘domain’: domain, ‘password’: password, ‘current_ip’: current_ip} # for the update enom_update_url = ‘%(enom_url)s&zone=%(domain)s&domainpassword=%(password)s&address=%(current_ip)s’ % settings # do the update at Enom def update_enom(): # Check that the last_set_ip_path already exists & create if not if not os.path.exists(last_set_ip_path): open(last_set_ip_path, ‘w’).close() # Compare last saved IP to the fetched IP old_ip = open(last_set_ip_path, ‘r’).read() if old_ip == current_ip: return # the IP address is unchanged so nothing to do # Else it has changed, so update Enom enom_response = urllib2.urlopen(enom_update_url).read() #print enom_response #debug # Now save the newly set ip open(last_set_ip_path, ‘w’).write(current_ip) return # end all declarations # body update_enom() Until we meet again that’s all for this month. The Spy needs to get back to constructing final exams, finishing his proofing of The Paladin, and adding a dozen or more pages to his arjaybooks.com web site to plug the newly released novel. :. TheNorthernSpy. com opundo : http: //opundo. com Sheaves Christian Resources : http: //sheaves. org WebNameHost :. WebNameHost. net WebNameSource :. WebNameSource. net nameman : http: //nameman. net General URLs for Rick Sutcliffe’s Books: Author Site:. arjay. ca Publisher’s Site:. writers-exchange. com/Richard-Sutcliffe. html The Fourth Civilization–Ethics, Society, and Technology (4th 2003 ed. ):. arjay. bc. ca/EthTech/Text/index. html Sites for Modula-2 resources Modula-2 FAQ and ISO-based introductory text: R10 Repository and source code: URLs for resources mentioned in this column NCIX: Synology: ASUS: Culmanic Parts: Rae’s Blood:
http://www.callapple.org/columns/the-northern-spy-of-reading-and-routing/
CC-MAIN-2018-39
refinedweb
1,623
56.29
aws_alexaforbusiness_api 0.2.0 aws_alexaforbusiness_api: ^0.2.0 copied to clipboard Use this package as a library Depend on it Run this command: With Dart: $ dart pub add aws_alexaforbusiness_api With Flutter: $ flutter pub add aws_alexaforbusiness_api This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get): dependencies: aws_alexaforbusiness_api: ^0.2.0 Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more. Import it Now in your Dart code, you can use: import 'package:aws_alexaforbusiness_api/alexaforbusiness-2017-11-09.dart'; import 'package:aws_alexaforbusiness_api/alexaforbusiness-2017-11-09.g.dart';
https://pub.dev/packages/aws_alexaforbusiness_api/install
CC-MAIN-2021-25
refinedweb
108
50.43
SOAP and Web Services By Mark Volkmann, OCI Partner August 2001 Introduction Simple Object Access Protocol (SOAP) and web services are emerging technologies that are getting a lot of press. What problems do they solve? What does their use mean for other distributed architectures (DAs) such as CORBA, DCOM, and EJB? SOAP Overview SOAP provides a new way of creating distributed applications where remote services are invoked by sending XML-based requests to a server and results are returned in XML-based responses. This is the SOAP "message protocol." While SOAP doesn't require use of a specific transport protocol (called "underlying protocol" in the official documentation), HTTP is currently the most common. IBM, Microsoft, DevelopMentor and UserLand Software originally submitted SOAP to the W3C as a note. A group within the W3C called the "XML Protocol (XMLP) Working Group" is actively working to advance this to a W3C recommendation. The first working draft was published on July 9, 2001. It is a fairly mature document as W3C working drafts go. Representatives from many more companies than the original submitters are participating, including BEA Systems, Compaq, DevelopMentor, Hewlett Packard, Intel, IONA, Novell, Oracle and Sun Microsystems. SOAP is not likely to reach the recommendation stage until 2002. For those unfamiliar with the process, the order of documents generated within the W3C is "note," "working draft," "candidate recommendation," "proposed recommendation," and "recommendation." A related W3C Note entitled "SOAP Messages with Attachments" builds on the first note and specifies how SOAP messages can include attachments, such as binary image data. This allows all the data needed by a service to be sent in a single request. When Is It Appropriate To Use SOAP? SOAP is useful for invoking code that exhibits at least one of the following characteristics. - Service code is outside the firewall. Other DAs have difficulty calling across firewall boundaries. SOAP does this easily by using HTTP and communicating on port 80, which is typically open. - Client and server programming languages differ. No DA, not even CORBA, has been implemented in as many different programming languages as SOAP. Of course this is because SOAP doesn't provide all the services that CORBA does, so it is much easier to implement. All that a language needs to implement SOAP is support for HTTP and XML. - Client and server DAs differ. Other DAs have difficulty communicating with each other. SOAP can be used to wrap services implemented in other DAs, making them accessible to each other. Die-hard fans of other DAs may dismiss many of the other stated benefits of using SOAP, but this remains a compelling reason to use it for at least some subset of services that comprises many applications. - Services are course-grained. Remote calls are always more expensive than local calls. This difference is even more pronounced with SOAP than with other DAs. Course-grained services require clients to make fewer remote calls and are thus less expensive than achieving the same functionality through a series of fine-grained services. - Service performance is not critical. Other DAs are currently faster than SOAP and are likely to remain so. It is perfectly reasonable to conclude that SOAP is not suitable for applications that have strict performance requirements. Web Services Overview SOAP is just one part of the concept of web services. Below is a summary of some of the other important parts. Web Services Description Language (WSDL) WSDL describes web service requests and responses using XML. It is similar to CORBA IDL but can also include the location of services via a URL. There are two main types of descriptions, service interfaces and implementations. Separating these allows multiple implementations of the same interface. WSDL service descriptions can be cataloged and searched in a registry such as UDDI. Universal Description, Discovery, and Integration (UDDI) UDDI provides a registry for web services similar to the CORBA Naming and Trader services. Clients can register and search for several types of information distinguished by different "colored" pages. White Pages contain information about service providers such as business name, description and contact information. Access to descriptions of the services offered by each provider (yellow pages) is also supplied. Yellow Pages contain high-level service information and references to low-level information (green pages). Examples of high-level service information include the service name, a human-readable service description, a list of categories to which the service belongs, and a key used to access a description of the business providing the service. Services can be listed by several taxonomies such as North American Industry Classification System (NAICS), Universal Standard Products and Services Classification (UNSPSC), and geographical location. Green Pages contain low-level information needed to invoke services. This includes business processes, service descriptions and binding information. Binding information supplies the service location and protocol used to communicate with the service. Much of this data can be supplied by referencing a WSDL file. IBM and Microsoft currently host free, public UDDI repositories. HP will host one by the end of 2001. Services advertised to any of them are replicated to the others within 24 hours, typically much faster. These UDDI registries are accessible to anyone with web access. More restrictive UDDI registries can also be created. A consortium of 36 companies including IBM, Microsoft and Ariba created UDDI. As of May 2001, there were 260 member companies. The consortium plans to hand over control of the UDDI specification to a standards body at some point in the future. Electronic Business XML (ebXML) ebXML is primarily targeted toward B2B communication. Its goal is to allow businesses to automate the following with no human involvement. - Find partners that support specific business processes - Enter into trading partner agreements with them - Invoke their web services ebXML is attempting to define standard business processes. It is also defining standard message structures for carrying out those processes based on "SOAP Messages with Attachments." It defines its own registry for publishing and finding business processes and services, but implementations could use UDDI. ebXML is supported by these standards organizations. - United Nations Centre for Trade Facilitation and Electronic Business (UN/CEFACT) - Organization for the Advancement of Structured Information Standards (OASIS) - Object Management Group (OMG) Several major vendors including IBM, Oracle and Sun Microsystems also support ebXML. .NET .NET, from Microsoft, has basically the same set of requirements as ebXML. It is a framework of server products. BizTalk is one of them. .NET builds on other standards including: - SOAP for the message protocol - WSDL to describe services - UDDI for the service registry - XLANG to model business processes Which Web Service Components Are Necessary? When the location and message structure of a web service are known at development time, SOAP can be used independently. When the location of a WSDL file is known, these details can be discovered at run-time. UDDI is useful when suitable web services need to be found at run-time, perhaps based on criteria such as availability, performance, reliability, and cost. ebXML and .NET are useful when applications wish to use standard business processes, not just individual web services. Why Do SOAP Messages Look So Complicated? On the surface, it seems that all that is needed in SOAP request and response messages is "plain" XML. There are three aspects of typical SOAP messages that make them seem more complex than that: - HTTP headers - XML Namespaces - XML Schema It's a good idea to gain some understanding of these apart from SOAP, since they are helpful in other contexts. Once you do, SOAP messages won't seem so cryptic. An example of a SOAP request message is provided later. HTTP Headers HTTP headers serve many purposes. They are needed to specify the target host and port. They are also needed to specify the message intent through a header called "SOAPAction." Typically, providing the service name conveys this. Firewalls call filter HTTP SOAP traffic based on this. To block all HTTP SOAP traffic, firewalls can block all HTTP messages with a "Content-Type" header of "text/xml". Quoting from the spec., "The SOAPAction HTTP request header can be used to indicate the intent of the SOAP HTTP request." Different SOAP implementations use this in different ways. More will be said about SOAP implementations later in this article. Apache SOAP doesn't use the SOAPAction header at all. The service being invoked is specified in the namespace URI of the first child element in the SOAP request body. GLUE uses SOAPAction to specify the Java class and method that implements the service. XML Namespaces Namespaces have two primary uses, as follows: - Associating a context with specific XML elements/attributes - Associating an XML Schema file with them so that XML, such as a SOAP message, can be validated The first use can be compared with Java packages. Java packages group sets of related classes. XML namespaces group sets of related XML elements and attributes. XML Schema XML Schemas provide a means for validating XML documents in a more detailed way than is possible with Document Type Definitions (DTDs). Among other things, they allow specification of data types for element text and attribute values. SOAP messages can use XML Schema to specify data types of elements within SOAP request and response messages using the "xsi:type" attribute. Associating an XML Schema file with a SOAP message can also do this. Example SOAP Request Here's an example of a SOAP request using HTTP as the transport protocol. This fictional service retrieves detailed information about a particular item in a company inventory. A company could provide a service like this to selected suppliers that are given permission to automatically ship items when their inventory quantity drops below specified levels. - HTTP Headers: Lines 1-7 - XML Namespaces: Lines 11-13, 17 - XML Schema: Line 20 (xsi:type='xsd:string) - POST /glue HTTP/1.1 - Content-Type: text/xml - User-Agent: GLUE/1.0 - Host: localhost:8004 - Connection: Keep-Alive - SOAPAction: "urn:inventory:getStockInfo" - Content-Length: 683 - - <?xml version='1.0' encoding='UTF-8'?> - <soap:Envelope - xmlns:soap="" - xmlns:xsi="" - xmlns:xsd="" - soap: - - <soap:Body> - <n:getStockInfo xmlns:n="" - soap: - - <partNumber xsi:A14872</partNumber> - - </n:getStockInfo> - </soap:Body> - </soap:Envelope> SOAP Implementations Use of a SOAP toolkit such as IBM Web Services Toolkit (WSTK), Apache Axis, or GLUE is not required to send and receive SOAP messages. SOAP client developers can write their own code to: - Create SOAP request messages (XML) - Wrap them in HTTP requests - Send them to a SOAP server - Read the HTTP response - Parse the enclosed SOAP response message (XML) SOAP service developers can write their own code to: - Receive HTTP requests - Parse the enclosed SOAP request message (XML) - Perform the work of the service - Create a SOAP response message (XML) - Wrap it in an HTTP response - Return it to the client SOAP packages can automate all of these steps in a way that is tailored to a specific programming language. For example, Java-based SOAP packages such as GLUE allow Java primitive types and objects to be passed to SOAP services. The XML representation of the parameters is automatically generated. All the details of constructing, sending and receiving HTTP messages are handled. The XML in SOAP responses is automatically parsed and turned into Java objects. No SAX or DOM (popular XML programming APIs) programming is needed to work with SOAP. The SOAP specification only defines the content of the messages passed between clients and servers. It does not define an API for creating and passing SOAP messages. This has its pros and cons. The good news is that each language-specific SOAP toolkit can be tailored to take advantage of the strengths and style of a particular programming language. The bad news is that experience gained in using SOAP from one programming language doesn't transfer over to using SOAP from a different language. Is SOAP Object-Oriented? The push toward service-oriented architectures certainly seems to move us away from pure OO. We see this in the recommended approach for using EJBs where clients are supposed to communicate with object-oriented entity beans through service-oriented session beans. Classes that implement SOAP services are similar to EJB session beans in this respect. Does this mean SOAP is not OO? Not exactly. While the mechanism for invoking SOAP services is not particularly OO, the implementation of the services still can be. Replacement For Other DAs? SOAP should not be viewed as a replacement for other DAs such as CORBA, DCOM and EJB. While SOAP could be used instead of these DAs, there are many reasons to continuing using them. The use of HTTP and the need to construct and parse XML documents make it unlikely that SOAP will ever be as efficient as other DAs. To get the best of both worlds, consider implementing most services using a non-SOAP DA. Those can be used inside a firewall for maximum performance. Perhaps only a subset of those services will require access from outside the firewall. SOAP services that simply wrap calls to those services can provide that access. Another reason to create SOAP wrapping services is to allow calls across DAs. For example, an EJB-based application that needs to utilize a CORBA service can do so by invoking a SOAP service, which invokes the CORBA service. Why Mix Business Logic With DA Code? You separate business logic from GUI code. You separate business logic from data access code. Why not separate your business logic from code that locates remote services and invokes them? Suppose you have a class called Portfolio that provides business logic for operating on a stock portfolio. Don't make this class CORBA, EJB or SOAP-specific. When you need to access Portfolio functionality from DAs, create classes like PortfolioCORBA, PortfolioEJB, and PortfolioSOAP. These classes could possibly be automatically generated from the business logic classes. It may not be feasible to mix usage of these classes, since they may be written to take advantage of specific features of a DA, such as transactions. Summary The concept of web services is built on many different specifications, some of which work together and some of which compete. The more low-level specifications such as SOAP and WSDL are the most mature in terms of being specified well enough that implementations can be created. High-level specifications such as ebXML and .NET are much more ambitious and are not quite ready for prime-time use. Tools for working with SOAP, WSDL, and UDDI are still maturing, but have made great strides in the past year. For a good example, see GLUE from The Mind Electric. Using SOAP, WSDL, and UDDL can benefit your applications, regardless of whether ebXML and .NET are being used. As proof of this, consider that other DAs do not attempt to standardize business processes and messaging structures. Start learning more about web services today so you'll be ready to take advantage of them as tool support improves and the number of advertised web services increases. For a list of free, publicly available web services, see. References - [1] .NET - [2] Apache Axis - [3] ebXML - [4] GLUE - [5] IBM Web Services Toolkit (WSTK) - [6] JavaSoft - [7] SOAP 1.2 - [8] SOAP Messages With Attachments - [9] UDDI - [10] WSDL - [11] XMethods Software Engineering Tech Trends (SETT) is a regular publication featuring emerging trends in software engineering.
https://objectcomputing.com/resources/publications/sett/august-2001-soap-and-web-services
CC-MAIN-2022-33
refinedweb
2,555
55.44
Hi, Some comments... On Wed, 2008-03-05 at 00:49 -0600, Benjamin Marzinski wrote: > Here is my proposed fix for 428751. It needs some heavy testing, both > for correctness and performance, before it gets pushed. > > -Ben diff -urpN gfs2/glock.c gfs2-patched/glock.c --- gfs2/glock.c 2008-03-04 10:54:02.000000000 -0600 +++ gfs2-patched/glock.c 2008-03-04 10:53:13.000000000 -0600 @@ -42,6 +42,7 @@ #include "quota.h" #include "super.h" #include "util.h" +#include "lm_deadlk.h" struct gfs2_gl_hash_bucket { struct hlist_head hb_list; @@ -785,7 +786,8 @@ static void xmote_bh(struct gfs2_glock * state_change(gl, ret & LM_OUT_ST_MASK); - if (prev_state != LM_ST_UNLOCKED && !(ret & LM_OUT_CACHEABLE)) { + if ((prev_state != LM_ST_UNLOCKED && !(ret & LM_OUT_CACHEABLE)) || + ret & LM_OUT_DEADLK) { if (glops->go_inval) glops->go_inval(gl, DIO_METADATA); If we move the ->go_inval() as suggested below, then I don't think this change is required. In fact I think we can ignore the (ret & LM_OUT_CACHABLE) test since this should never be true any more, since if it is, then we've not eliminated the bug that you are trying to fix. So that should remove one branch from this "if" clause. Also, if we are moving to the DEFERRED state, then we need to invalidate earlier (in the "th" routine) in order to avoid the bug too, so that moves the remaining branch of the "if" clause from this function as well. } else if (gl->gl_state == LM_ST_DEFERRED) { @@ -815,6 +817,15 @@ static void xmote_bh(struct gfs2_glock * } } else { spin_lock(&gl->gl_spin); + if (ret & LM_OUT_DEADLK) { + gh->gh_error = 0; + gl->gl_req_bh = NULL; + set_bit(GLF_DEADLK, &gl->gl_flags); + spin_unlock(&gl->gl_spin); + gfs2_glock_drop_th(gl); + gfs2_glock_put(gl); + return; + } list_del_init(&gh->gh_list); gh->gh_error = -EIO; if (unlikely(test_bit(SDF_SHUTDOWN, &sdp->sd_flags))) @@ -920,6 +931,16 @@ static void drop_bh(struct gfs2_glock *g state_change(gl, LM_ST_UNLOCKED); + if (test_and_clear_bit(GLF_DEADLK, &gl->gl_flags)) { + spin_lock(&gl->gl_spin); + gh->gh_error = 0; + gl->gl_req_bh = NULL; + spin_unlock(&gl->gl_spin); + gfs2_glock_xmote_th(gl, gl->gl_req_gh); + gfs2_glock_put(gl); + return; + } + if (glops->go_inval) glops->go_inval(gl, DIO_METADATA); This doesn't look like it solves the problem... don't we need to move the ->go_inval call into gfs2_glock_drop_th() ? After all we know at that point that we'll be dropping the lock, so there is no reason not to invalidate there. diff -urpN gfs2/incore.h gfs2-patched/incore.h --- gfs2/incore.h 2008-03-04 10:54:02.000000000 -0600 +++ gfs2-patched/incore.h 2008-03-04 10:53:13.000000000 -0600 @@ -172,6 +172,7 @@ enum { GLF_PENDING_DEMOTE = 4, GLF_DIRTY = 5, GLF_DEMOTE_IN_PROGRESS = 6, + GLF_DEADLK = 7, }; struct gfs2_glock { diff -urpN gfs2/lm.c gfs2-patched/lm.c --- gfs2/lm.c 2008-03-04 10:54:02.000000000 -0600 +++ gfs2-patched/lm.c 2008-03-04 10:54:28.000000000 -0600 @@ -21,6 +21,7 @@ #include "lm.h" #include "super.h" #include "util.h" +#include "lm_deadlk.h" /** * gfs2_lm_mount - mount a locking protocol @@ -35,7 +36,7 @@ int gfs2_lm_mount(struct gfs2_sbd *sdp, { char *proto = sdp->sd_proto_name; char *table = sdp->sd_table_name; - int flags = 0; + int flags = LM_MFLAG_ALLOW_DEADLK; int error; if (sdp->sd_args.ar_spectator) diff -urpN gfs2/lm_deadlk.h gfs2-patched/lm_deadlk.h --- gfs2/lm_deadlk.h 1969-12-31 18:00:00.000000000 -0600 +++ gfs2-patched/lm_deadlk.h 2008-03-04 10:53:13.000000000 -0600 @@ -0,0 +1,16 @@ +/* + * Copyright (C) 2008 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License version 2. + */ + +#ifndef __LM_DEADLK_DOT_H__ +#define __LM_DEADLK_DOT_H__ + +/* This is a hack. These flags really belong in lm_interface.h */ +#define LM_OUT_DEADLK 0x00000200 +#define LM_MFLAG_ALLOW_DEADLK 0x00000002 + +#endif /* __LM_DEADLK_DOT_H__ */ So let me ask the obvious question here... why not put them in lm_interface.h in that case? I don't think we need to add an extra header just for two constants. I'm also not convinced about the naming of the constants. I can see why you chose those names, but I don't think its very helpful to someone looking at the code for the first time. Could we have LM_MFLAG_CONV_NODROP for example, which might make it a bit clearer? Some brief comments explaining what they mean would be good too. diff -urpN gfs2/locking/dlm/lock.c gfs2-patched/locking/dlm/lock.c --- gfs2/locking/dlm/lock.c 2008-03-04 10:54:02.000000000 -0600 +++ gfs2-patched/locking/dlm/lock.c 2008-03-04 10:53:13.000000000 -0600 @@ -8,6 +8,7 @@ */ #include "lock_dlm.h" +#include "../../lm_deadlk.h" If we really do need to have an extra header, the please put it in include/linux and then you can use <> rather than needing to specify paths like this. static char junk_lvb[GDLM_LVB_SIZE]; @@ -137,7 +138,8 @@ static inline unsigned int make_flags(st /* Conversion deadlock avoidance by DLM */ - if (!test_bit(LFL_FORCE_PROMOTE, &lp->flags) && + if (!(lp->ls->fsflags & LM_MFLAG_ALLOW_DEADLK) && + !test_bit(LFL_FORCE_PROMOTE, &lp->flags) && !(lkf & DLM_LKF_NOQUEUE) && cur > DLM_LOCK_NL && req > DLM_LOCK_NL && cur != req) lkf |= DLM_LKF_CONVDEADLK; diff -urpN gfs2/locking/dlm/thread.c gfs2-patched/locking/dlm/thread.c --- gfs2/locking/dlm/thread.c 2008-03-04 10:54:02.000000000 -0600 +++ gfs2-patched/locking/dlm/thread.c 2008-03-04 10:53:13.000000000 -0600 @@ -8,6 +8,7 @@ */ #include "lock_dlm.h" +#include "../../lm_deadlk.h" /* A lock placed on this queue is re-submitted to DLM as soon as the lock_dlm thread gets to it. */ @@ -135,7 +136,15 @@ static void process_complete(struct gdlm lp->lksb.sb_status, lp->lockname.ln_type, (unsigned long long)lp->lockname.ln_number, lp->flags); - return; + if (lp->lksb.sb_status == -EDEADLOCK && + lp->ls->fsflags & LM_MFLAG_ALLOW_DEADLK) { + lp->req = lp->cur; + acb.lc_ret |= LM_OUT_DEADLK; + if (lp->cur == DLM_LOCK_IV) + lp->lksb.sb_lkid = 0; + goto out; + } else + return; } /*
https://www.redhat.com/archives/cluster-devel/2008-March/msg00026.html
CC-MAIN-2015-14
refinedweb
930
61.83
dlopen() Gain access to an executable object file Synopsis: #include <dlfcn.h> void * dlopen( const char * pathname, int mode ); Since: BlackBerry 10.0.0 Arguments: - pathname - NULL, or the path to the executable object file that you want to access. - mode - Flags that control how dlopen() operates. POSIX defines these bits: - RTLD_LAZY - RTLD_NOW - RTLD_GLOBAL - RTLD_LOCAL The following bits are Unix extensions: - RTLD_NOLOAD - RTLD_GROUP - RTLD_WORLD - RTLD_NODELETE The following bits are BlackBerry 10 OS extensions: - RTLD_NOSHARE - RTLD_LAZYLOAD For more information, see " The mode ," below. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The dlopen() function gives you direct access to the dynamic linking facilities by making the executable object file specified in pathname available to the calling process. It returns a handle that you can use in subsequent calls to dlsym() and dlclose(). - In order to successfully call this function, your process must have the PROCMGR_AID_PROT_EXEC ability enabled. For more information, see procmgr_ability(). - If your process has any privileged abilities enabled, then the executable file you're trying to execute must be trusted. For more information, see the description of PROT_EXEC in the entry for mmap(), as well as the entry for pathtrust in the Utilities Reference. - The dlopen() function is available only to a dynamically-linked process. A statically-linked process (one where libc is linked statically) can't call dlopen() because a statically-linked executable: - doesn't export any of its symbols - can't export the required structure for libraries to link against - can't fill structures at startup needed to load subsequent shared objects runtime library search path that was set using the -rpath option to ld (see the Utilities Reference) when the binary was linked - directories specified by the LD_LIBRARY_PATH environment variable - directories specified by the _CS_LIBPATH configuration string Note that LD_LIBRARY_PATH is ignored if the binary is setuid and the effective user ID isn't the same as the actual ID of the user running the binary. This is done for security purposes. The above directories are set as follows: - The LD_LIBRARY_PATH is generally set up by a startup script, either in the boot image or by a secondary script. It isn't part of any default environment. - _CS_LIBPATH is populated by the kernel, and the default value is based on the LD_LIBRARY_PATH value of the procnto command line in the boot image. Note that you can use getconf to inspect this value and setconf to set it. For example: setconf _CS_LIBPATH 'getconf _CS_LIBPATH':/new/path When loading shared objects, the application should open a specific version instead of relying on the version pointed to by a symbolic link. The mode. Relocation: - RTLD_LAZY - References to data symbols are relocated when the object is loaded. References to functions aren't relocated until that function is invoked. This improves performance by preventing unnecessary relocations. - RTLD_NOW - All references are relocated when the object is loaded. This may waste cycles if relocations are performed for functions that never get called, but this behavior could be useful for applications that need to know that all symbols referenced during execution are available as soon as the object is loaded. Visibility The following mode bits determine the scope of visibility for symbols loaded with dlopen(): - RTLD_GLOBAL - Make the object's global symbols available to any other object that's opened later with RTLD_WORLD. Symbol lookup using dlopen( 0, mode ) and an associated dlsym() are also able to find the object's symbols. - RTLD_LOCAL - Make the object's global symbols available only to objects in the same group. - RTLD_LAZYLOAD - Open the shared object and form its resolution scope by appending its immediate dependencies. This is different from the normal resolution scope, which is formed by appending the whole dependency tree in breadth-first order. For more information, see " Lazy loading "in the Compiling and Debugging chapter of the BlackBerry 10 OS Programmer's Guide.. Symbol scope You can OR the mode with the following values to affect the symbol scope: - RTLD_GROUP - Only symbols from the associated group are available. All dependencies between group members must be satisfied by the objects in the group. - RTLD_WORLD - Only symbols from RTLD_GLOBAL objects are available. If you don't specify either of these values, dlopen() uses RTLD_WORLD | RTLD_GROUP. If you specify RTLD_WORLD without RTLD_GROUP, dlopen() doesn't load any of the DLL's dependencies. Other flags The following flags provide additional capabilities: - RTLD_NODELETE - Don't delete the specified object from the address space as part of a call to dlclose(). - RTLD_NOLOAD - Don't load the specified object, but return a valid handle if if the object already exists as part of the process address space. You can specify addition modes, which are ORed with the present mode of the object and its dependencies. This flag gives you a means of querying the presence or promoting the modes of an existing dependency. - RTLD_NOSHARE - Don't share the specified object. This flag forces the loading of multiple instances of libraries. Symbol resolution When resolving the symbols in the shared object, the runtime linker searches for them in the dynamic symbol table using the following order: - By default: - main executable - the shared object being loaded - objects specified by the LD_PRELOAD environment variable - all other loaded shared objects that were loaded with the RTLD_GLOBAL flag - When -Bsymbolic is specified: - the shared object being loaded - main executable - objects specified by the LD_PRELOAD environment variable - all other loaded shared objects that were loaded with the RTLD_GLOBAL flag. Returns: A handle to the object, or NULL if an error occurs. Don't interpret the value of this handle in any way. For example, if you open the same object repeatedly, don't assume that dlopen() returns the same handle. Environment variables: - DL_DEBUG - If this environment variable is set, the shared library loader displays debugging information about the libraries as they're opened._BIND_NOW - Affects lazy-load dependencies due to full symbol resolution. Typically, it forces the loading of all lazy-load dependencies (until all symbols have been resolved). - LD_DEBUG - A synonym for DL_DEBUG. If you set both DL_DEBUG and LD_DEBUG, then_LIBRARY_PATH - A colon-separated list of directories to search for shared libraries. - LD_PRELOAD - A list of full paths to the shared libraries on an ELF system that you want to load before loading other libraries. Use a colon (:) to separate the libraries in this list. You can use this environment variable to add or change functionality when you run a program. For setuid or setgid ELF binaries, only libraries in the standard search directories that are also setuid will be loaded. Classification: Last modified: 2015-07-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/d/dlopen.html
CC-MAIN-2016-07
refinedweb
1,120
52.9
I changed the theme in Xfce4 to xfce-dusk which caused Firefox to make the fonts in some search bars such as Google to become white and completely invisible. Where can I look to fix this problem? I can change to another theme to prevent that from happening but I would rather use the dusk theme while using firefox. Last edited by rg_arc (2012-09-17 22:46:36) Offline In Terminal: cd ~/.mozilla/firefox/x.default mkdir chrome touch userChrome.css gedit (or whatever you use) userChrome.css and paste this: /* * Do not remove the @namespace line -- it's required for correct functioning */ @namespace url(""); /* set default namespace to XUL */ menubar, menubutton, menu, menuitem, menupopup, popup > * { color: black !important; } Or use some extension like stylish and paste the code line 4 to end. I assumed you want to have a black font, but you can choose whatever you want there. You have to change x.default to your specific profile directory. Last edited by RedFx (2012-09-17 17:33:41) Offline Yes. userChrome.css is the proper filename: … ml#usercss Offline
https://bbs.archlinux.org/viewtopic.php?pid=1162662
CC-MAIN-2016-26
refinedweb
183
75.5
This chapter includes: In this chapter, we'll look at the most distinctive feature of Neutrino, message passing. Message passing lies at the heart of the operating system's microkernel architecture, giving the OS its modularity. One of the principal advantages of Neutrino is that it's scalable. By “scalable” I mean that it can be tailored to work on tiny embedded boxes with tight memory constraints, right up to large networks of multiprocessor SMP boxes with almost unlimited memory.. Neutrino's modular architecture. Neutrino called the filesystem. The message tells the filesystem to open a file, and then another message tells it to write some data (and contains that data). Don't worry though — the Neutrino operating system performs message passing very quickly. Imagine). State transitions of server.. State transitions of clients.! Suppose Neutrino, the C library open() creates the same message that it would have sent to the local filesystem and sends it to the filesystem on node wintermute. In the local and remote cases, the exact same filesystem is used. This is another fundamental characteristic of. Message Neutrino. Understanding the uses and implications of message passing will be the key to making effective use of the OS. Before we go into the details, let's look at a little bit of theory first.: Clients accessing threads in a server.. Let's now look at the server/subserver model, and then we'll combine it with the multiple threads model. In this model, a server still provides a service to clients, but because these requests may take a long time to complete, we need to be able to start a request and still be able to handle new requests as they arrive from other clients. If we tried to do this with the traditional single-threaded client/server model, once one request was received and started, we wouldn't be able to receive any more requests unless we periodically stopped what we were doing, took a quick peek to see if there were any other requests pending, put those on a work queue, and then continued on, distributing our attention over the various jobs in the work queue. Not very efficient. You're practically duplicating the work of the kernel by “time slicing” between multiple jobs! Imagine what this would look like if you were doing it. You're at your desk, and someone walks up to you with a folder full of work. You start working on it. As you're busy working, you notice that someone else is standing in the doorway of your cubicle with more work of equally high priority (of course)! Now you've got two piles of work on your desk. You're spending a few minutes on one pile, switching over to the other pile, and so on, all the while looking at your doorway to see if someone else is coming around with even more work. The server/subserver model would make a lot more sense here. In this model, we have a server that creates several other processes (the subservers). These subservers each send a message to the server, but the server doesn't reply to them until it gets a request from a client. Then it passes the client's request to one of the subservers by replying to it with the job that it should perform. The following diagram illustrates this. Note the direction of the arrows — they indicate the direction of the sends! Server/subserver model. If you were doing a job like this, you'd start by hiring some extra employees. These employees would all come to you (just as the subservers send a message to the server — hence the note about the arrows in the diagram above), looking for work to do. Initially, you might not have any, so you wouldn't reply to their query. When someone comes into your office with a folder full of work, you say to one of your employees, “Here's some work for you to do.” That employee then goes off and does the work. As other jobs come in, you'd delegate them to the other employees. The trick to this model is that it's reply-driven — the work starts when you reply to your subservers. The standard client/server model is send-driven because the work starts when you send the server a message. So why would the clients march into your office, and not the offices of the employees that you hired? Why are you “arbitrating” the work? The answer is fairly simple: you're the coordinator responsible for performing a particular task. It's up to you to ensure that the work is done. The clients that come to you with their work know you, but they don't know the names or locations of your (perhaps temporary) employees. As you probably suspected, you can certainly mix multithreaded servers with the server/subserver model. The main trick is going to be determining which parts of the “problem” are best suited to being distributed over a network (generally those parts that won't use up the network bandwidth too much) and which parts are best suited to being distributed over the SMP architecture (generally those parts that want to use common data areas). So why would we use one over the other? Using the server/subserver approach, we can distribute the work over multiple machines on a network. This effectively means that we're limited only by the number of available machines on the network (and network bandwidth, of course). Combining this with multiple threads on a bunch of SMP boxes distributed over a network yields “clusters of computing,” where the central “arbitrator” delegates work (via the server/subserver model) to the SMP boxes on the network. Now. One master, multiple workers.). Multi-threaded servers are indistinguishable from single-threaded servers from the client's point of view. In fact, the designer of a server can just “turn on” multi-threading. Now that we've seen the basic concepts involved in message passing, and learned that even common everyday things like the C library use it, let's take a look at some of the details. We've been talking about “clients” and “servers.” I've also used three key phrases: I specifically used those phrases because they closely reflect the actual function names used in Neutrino message-passing operations. Here's the complete list of functions dealing with message passing available under Neutrino (in alphabetical order): Don't let this list overwhelm you! You can write perfectly useful client/server applications using just a small subset of the calls from the list — as you get used to the ideas, you'll see that some of the other functions can be very useful in certain cases. We'll break our discussion up into the functions that apply on the client side, and those that apply on the server side. The client wants to send a request to a server, block until the server has completed the request, and then when the request is completed and the client is unblocked, to get at the “answer.” This implies two things: the client needs to be able to establish a connection to the server and then to transfer data via messages — a message from the client to the server (the “send” message) and a message back from the server to the client (the “reply” message, the server's reply).. Message passing on the client is achieved using some variant of the MsgSend*() function family. We'll look at the simplest member, MsgSend(): #include <sys/neutrino.h> int MsgSend (int coid, const void *smsg, int sbytes, void *rmsg, int rbytes); MsgSend()'s arguments are: It couldn't get any simpler than that! Let's send a simple message to process ID 77, channel ID 1: #include <sys/neutrino.h> char *smsg = "This is the outgoing buffer"; char rmsg [200]; int coid; // establish a connection coid = ConnectAttach (0, 77, 1, 0, 0); if (coid == -1) { fprintf (stderr, "Couldn't ConnectAttach to 0/77/1!\n"); perror (NULL); exit (EXIT_FAILURE); } // send the message if (MsgSend (coid, smsg, strlen (smsg) + 1, rmsg, sizeof (rmsg)) == -1) { fprintf (stderr, "Error during MsgSend\n"); perror (NULL); exit (EXIT_FAILURE); } if (strlen (rmsg) > 0) { printf ("Process ID 77 returns \"%s\"\n", rmsg); } Let's assume that process ID 77 was an active server expecting that particular format of message on its channel ID 1. After the server received the message, it would process it and at some point reply with a result. At that point, the MsgSend() would return a 0 indicating that everything went well. If the server sends us any data in the reply, we'd print it with the last line of code (we're assuming we're getting NUL-terminated ASCII data back). Now that we've seen the client, let's look at the server. The client used ConnectAttach() to create a connection to a server, and then used MsgSend() for all its message passing. This: Relationship between a server channel and a client connection. As far as the message-passing aspects are concerned, the server handles message passing in two stages; a “receive” stage and a “reply” stage: Relationship of client and server message-passing functions.: Message data flow.. Here's the overall structure of a server: #include <sys/neutrino.h> … void server (void) { int rcvid; // indicates who we should reply to int chid; // the channel ID char message [512]; // big enough for our purposes // create a channel chid = ChannelCreate (0); // this is typical of a server: it runs forever while (1) { // get the message, and print it rcvid = MsgReceive (chid, message, sizeof (message), NULL); printf ("Got a message, rcvid is %X\n", rcvid); printf ("Message was \"%s\".\n", message); // now, prepare the reply. We reuse "message" strcpy (message, "This is the reply"); MsgReply (rcvid, EOK, message, sizeof (message)); } } As you can see, MsgReceive() tells the kernel that it can handle messages up to sizeof (message) (or 512 bytes). Our sample client (above) sent only 28 bytes (the length of the string). The following diagram illustrates: Transferring less data than expected. The kernel transfers the minimum specified by both sizes. In our case, the kernel would transfer 28 bytes. The server would be unblocked and print out the client's message. The remaining 484 bytes (of the 512 byte buffer) will remain unaffected. We run into the same situation again with MsgReply(). The MsgReply() function says that it wants to transfer 512 bytes, but our client's MsgSend() function has specified that a maximum of 200 bytes can be transferred. So the kernel once again transfers the minimum. In this case, the 200 bytes that the client can accept limits the transfer size. (One interesting aspect here is that once the server transfers the data, if the client doesn't receive all of it, as in our example, there's no way to get the data back — it's gone forever.) One. We haven't talked about the various parameters in the examples above so that we could focus just on the message passing. Now let's take a look. In the server example above, we saw that the server created just one channel. It could certainly have created more, but generally, servers don't do that. (The most obvious example of a server with two channels is the Transparent Distributed Processing (TDP, also known as Qnet) native network manager — definitely an “odd” piece of software!) As it turns out, there really isn't much need to create multiple channels in the real world. The main purpose of a channel is to give the server a well-defined place to “listen” for messages, and to give the clients a well-defined place to send their messages (via a connection). About the only time that you'd have multiple channels in a server is if the server wanted to provide either different services, or different classes of services, depending on which channel the message arrived on. The second channel could be used, for example, as a place to drop wake up pulses — this ensures that they're treated as a different “class” of service than messages arriving on the first channel. In a previous paragraph I had said that you could have a pool of threads running in a server, ready to accept messages from clients, and that it didn't really matter which thread got the request. This is another aspect of the channel abstraction. Under previous versions of the QNX family of operating systems (notably QNX 4), a client would target messages at a server identified by a node ID and process ID. Since QNX 4 is single-threaded, this means that there cannot be confusion about “to whom” the message is being sent. However, once you introduce threads into the picture, the design decision had to be made as to how you would address the threads (really, the “service providers”). Since threads are ephemeral, it really didn't make sense to have the client connect to a particular node ID, process ID, and thread ID. Also, what if that particular thread was busy? We'd have to provide some method to allow a client to select a “non-busy thread within a defined pool of service-providing threads.” Well, that's exactly what a channel is. It's the “address” of a “pool of service-providing threads.” The implication here is that a bunch of threads can issue a MsgReceive() function call on a particular channel, and block, with only one thread getting a message at a time. Often a server will need to know who sent it a message. There are a number of reasons for this: It would be cumbersome (and a security hole) to have the client provide this information with each and every message sent. Therefore, there's a structure filled in by the kernel whenever the MsgReceive() function unblocks because it got a message. This structure is of type struct _msg_info, and contains the following: struct _msg_info { int nd; int srcnd; pid_t pid; int32_t chid; int32_t scoid; int32_t coid; int32_t msglen; int32_t tid; int16_t priority; int16_t flags; int32_t srcmsglen; int32_t dstmsglen; }; You pass it to the MsgReceive() function as the last argument. If you pass a NULL, then nothing happens. (The information can be retrieved later via the MsgInfo() call, so it's not gone forever!) Let's look at the fields: In the code sample above, notice how we: rcvid = MsgReceive (…); … MsgReply (rcvid, …); This is a key snippet of code, because it illustrates the binding between receiving a message from a client, and then being able to (sometime later) reply to that particular client. The receive ID is an integer that acts as a “magic cookie” that you'll need to hold onto if you want to interact with the client later. What if you lose it? It's gone. The client will not unblock from the MsgSend() until you (the server) die, or if the client has a timeout on the message-passing call (and even then it's tricky; see the TimerTimeout() function in the Neutrino Library Reference, and the discussion about its use in the Clocks, Timers, and Getting A Kick Every So Often chapter, under “Kernel timeouts”). This brings us to the MsgReply() function. Ms. There's absolutely no requirement that you reply to a client before accepting new messages from other clients via MsgReceive()! This can be used in a number of different scenarios. In a typical device driver, a client may make a request that won't be serviced for a long time. For example, the client may ask an Analog-to-Digital Converter (ADC) device driver to “Go out and collect 45 seconds worth of samples.” In the meantime, the ADC driver shouldn't just close up shop for 45 seconds! Other clients might wish to have requests serviced (for example, there might be multiple analog channels, or there might be status information that should be available immediately, etc.). Architecturally, the ADC driver will simply queue the receive ID that it got from the MsgReceive(), start up the 45-second accumulation process, and go off and handle other requests. When the 45 seconds are up and the samples have been accumulated, the ADC driver can find the receive ID associated with the request and then reply to the client. You'd also want to hold off replying to a client in the case of the reply-driven server/subserver model (where some of the “clients” are the subservers). Since the subservers are looking for work, you'd simply make a note of their receive IDs and store those away. When actual work arrived, then and only then would you reply to the subserver, thus indicating that it should do some work. When you finally reply to the client, there's no requirement that you transfer any data. This is used in two scenarios. You may choose to reply with no data if the sole purpose of the reply is to unblock the client. Let's say the client just wants to be blocked until some particular event occurs, but it doesn't need to know which event. In this case, no data is required by the MsgReply() function; the receive ID is sufficient: MsgReply (rcvid, EOK, NULL, 0); This unblocks the client (but doesn't return any data) and returns the EOK “success” indication. As a slight modification of that, you may wish to return an error status to the client. In this case, you can't do that with MsgReply(), but instead must use MsgError(): MsgError (rcvid, EROFS); In the above example, the server detects that the client is attempting to write to a read-only filesystem, and, instead of returning any actual data, simply returns an errno of EROFS back to the client. Alternatively (and we'll look at the calls shortly), you may have already transferred the data (via MsgWrite()), and there's no additional data to transfer. Why the two calls? They're subtly different. While both MsgError() and MsgReply() will unblock the client, MsgError() will not transfer any additional data, will cause the client's MsgSend() function to return -1, and will cause the client to have errno set to whatever was passed as the second argument to MsgError(). On the other hand, MsgReply() could transfer data (as indicated by the third and fourth arguments), and will cause the client's MsgSend() function to return whatever was passed as the second argument to MsgReply(). MsgReply() has no effect on the client's errno. Generally, if you're returning only a pass/fail indication (and no data), you'd use MsgError(), whereas if you're returning data, you'd use MsgReply(). Traditionally, when you do return data, the second argument to MsgReply() will be a positive integer indicating the number of bytes being returned. You've noticed that in the ConnectAttach() function, we require a Node Descriptor (ND), a process ID (PID), and a channel ID (CHID) in order to be able to attach to a server. So far we haven't talked about how the client finds this ND/PID/CHID information. If one process creates the other, then it's easy — the process creation call returns with the process ID of the newly created process. Either the creating process can pass its own PID and CHID on the command line to the newly created process or the newly created process can issue the getppid() function call to get the PID of its parent and assume a “well-known” CHID. What if we have two perfect strangers? This would be the case if, for example, a third party created a server and an application that you wrote wanted to talk to that server. The real issue is, “How does a server advertise its location?” There are many ways of doing this; we'll look at four of them, in increasing order of programming “elegance”: The first approach is very simple, but can suffer from “pathname pollution,” where the /etc directory has all kinds of *.pid files in it. Since files are persistent (meaning they survive after the creating process dies and the machine reboots), there's no obvious method of cleaning up these files, except perhaps to have a “grim reaper” task that runs around seeing if these things are still valid. There's another related problem. Since the process that created the file can die without removing the file, there's no way of knowing whether or not the process is still alive until you try to send a message to it. Worse yet, the ND/PID/CHID specified in the file may be so stale that it would have been reused by another program! The message that you send to that program will at best be rejected, and at worst may cause damage. So that approach is out. The second approach, where we use global variables to advertise the ND/PID/CHID values, is not a general solution, as it relies on the client's being able to access the global variables. And since this requires shared memory, it certainly won't work across a network! This generally gets used in either tiny test case programs or in very special cases, but always in the context of a multithreaded program. Effectively, all that happens is that one thread in the program is the client, and another thread is the server. The server thread creates the channel and then places the channel ID into a global variable (the node ID and process ID are the same for all threads in the process, so they don't need to be advertised.) The client thread then picks up the global channel ID and performs the ConnectAttach() to it. The third approach, where we use the name_attach() and name_detach() functions, works well for simple client/server situations. The last approach, where the server becomes a resource manager, is definitely the cleanest and is the recommended general-purpose solution. The mechanics of “how” will become clear in the Resource Managers chapter, but for now, all you need to know is that the server registers a particular pathname as its “domain of authority,” and a client performs a simple open() of that pathname. What if a low-priority process and a high-priority process send a message to a server at the same time? We'll come back to some of the other subtleties introduced by this question when we look at priority inversions later in this chapter. So far you've seen the basic message-passing primitives. As I mentioned earlier, these are all that you need. However, there are a few extra functions that make life much easier. Let's consider an example using a client and server where we might need other functions. The client issues a MsgSend() to transfer some data to the server. After the client issues the MsgSend() it blocks; it's now waiting for the server to reply. An interesting thing happens on the server side. The server has called MsgReceive() to receive the message from the client. Depending on the design that you choose for your messages, the server may or may not know how big the client's message is. Why on earth would the server not know how big the message is? Consider the filesystem example that we've been using. Suppose the client does: write (fd, buf, 16); This works as expected if the server does a MsgReceive() and specifies a buffer size of, say, 1024 bytes. Since our client sent only a tiny message (28 bytes), we have no problems. However, what if the client sends something bigger than 1024 bytes, say 1 megabyte? write (fd, buf, 1000000); How is the server going to gracefully handle this? We could, arbitrarily, say that the client isn't allowed to write more than n bytes. Then, in the client-side C library code for write(), we could look at this requirement and split up the write request into several requests of n bytes each. This is awkward. The other problem with this example would be, “How big should n be?” You can see that this approach has major disadvantages: Luckily, this problem has a fairly simple workaround that also gives us some advantages. Two functions, MsgRead() and MsgWrite(), are especially useful here. The important fact to keep in mind is that the client is blocked. This means that the client isn't going to go and change data structures while the server is trying to examine them. The MsgRead() function looks like this: #include <sys/neutrino.h> int MsgRead (int rcvid, void *msg, int nbytes, int offset); MsgRead() lets your server read data from the blocked client's address space, starting offset bytes from the beginning of the client-specified “send” buffer, into the buffer specified by msg for nbytes. The server doesn't block, and the client doesn't unblock. MsgRead() returns the number of bytes it actually read, or -1 if there was an error. So let's think about how we'd use this in our write() example. The C Library write() function constructs a message with a header that it sends to the filesystem server, fs-qnx4. The server receives a small portion of the message via MsgReceive(), looks at it, and decides where it's going to put the rest of the message. The fs-qnx4 server may decide that the best place to put the data is into some cache buffers it's already allocated. Let's track an example: The fs-qnx4 message example, showing contiguous data view. So, the client has decided to send 4 KB to the filesystem. (Notice how the C Library stuck a tiny header in front of the data so that the filesystem could tell just what kind of request it actually was — we'll come back to this when we look at multi-part messages, and in even more detail when we look at resource managers.) The filesystem reads just enough data (the header) to figure out what kind of a message it is: // part of the headers, fictionalized for example purposes struct _io_write { uint16_t type; uint16_t combine_len; int32_t nbytes; uint32_t xtype; }; typedef union { uint16_t type; struct _io_read io_read; struct _io_write io_write; … } header_t; header_t header; // declare the header rcvid = MsgReceive (chid, &header, sizeof (header), NULL); switch (header.type) { … case _IO_WRITE: number_of_bytes = header.io_write.nbytes; … At this point, fs-qnx4 knows that 4 KB are sitting in the client's address space (because the message told it in the nbytes member of the structure) and that it should be transferred to a cache buffer. The fs-qnx4 server could issue: MsgRead (rcvid, cache_buffer [index].data, cache_buffer [index].size, sizeof (header.io_write)); Notice that the message transfer has specified an offset of sizeof (header.io_write) in order to skip the write header that was added by the client's C library. We're assuming here that cache_buffer [index].size is actually 4096 (or more) bytes. Similarly, for writing data to the client's address space, we have: #include <sys/neutrino.h> int MsgWrite (int rcvid, const void *msg, int nbytes, int offset); MsgWrite() lets your server write data to the client's address space, starting offset bytes from the beginning of the client-specified “receive” buffer. This function is most useful in cases where the server has limited space but the client wishes to get a lot of information from the server. For example, with a data acquisition driver, the client may specify a 4-megabyte data area and tell the driver to grab 4 megabytes of data. The driver really shouldn't need to have a big area like this lying around just in case someone asks for a huge data transfer. The driver might have a 128 KB area for DMA data transfers, and then message-pass it piecemeal into the client's address space using MsgWrite() (incrementing the offset by 128 KB each time, of course). Then, when the last piece of data has been written, the driver will MsgReply() to the client. Transferring several chunks with MsgWrite(). Note that MsgWrite() lets you write the data components at various places, and then either just wake up the client using MsgReply(): MsgReply (rcvid, EOK, NULL, 0); or wake up the client after writing a header at the start of the client's buffer: MsgReply (rcvid, EOK, &header, sizeof (header)); This is a fairly elegant trick for writing unknown quantities of data, where you know how much data you wrote only when you're done writing it. If you're using this method of writing the header after the data's been transferred, you must remember to leave room for the header at the beginning of the client's data area! Until now, we've shown only message transfers happening from one buffer in the client's address space into another buffer in the server's address space. (And one buffer in the server's space into another buffer in the client's space during the reply.) While this approach is good enough for most applications, it can lead to inefficiencies. Recall that our write() C library code took the buffer that you passed to it, and stuck a small header on the front of it. Using what we've learned so far, you'd expect that the C library would implement write() something like this (this isn't the real source): ssize_t write (int fd, const void *buf, size_t nbytes) { char *newbuf; io_write_t *wptr; int nwritten; newbuf = malloc (nbytes + sizeof (io_write_t)); // fill in the write_header at the beginning wptr = (io_write_t *) newbuf; wptr -> type = _IO_WRITE; wptr -> nbytes = nbytes; // store the actual data from the client memcpy (newbuf + sizeof (io_write_t), buf, nbytes); // send the message to the server nwritten = MsgSend (fd, newbuf, nbytes + sizeof (io_write_t), newbuf, sizeof (io_write_t)); free (newbuf); return (nwritten); } See what happened? A few bad things: Since the kernel is going to copy the data anyway, it would be nice if we could tell it that one part of the data (the header) is located at a certain address, and that the other part (the data itself) is located somewhere else, without the need for us to manually assemble the buffers and to copy the data. As luck would have it, Neutrino implements a mechanism that lets us do just that! The mechanism is something called an IOV, standing for “Input/Output Vector.” Let's look at some code first, then we'll discuss what happens: #include <sys/neutrino.h> ssize_t write (int fd, const void *buf, size_t nbytes) { io_write_t whdr; iov_t iov [2]; // set up the IOV to point to both parts: SETIOV (iov + 0, &whdr, sizeof (whdr)); SETIOV (iov + 1, buf, nbytes); // fill in the io_write_t at the beginning whdr.type = _IO_WRITE; whdr.nbytes = nbytes; // send the message to the server return (MsgSendv (coid, iov, 2, iov, 1)); } First of all, notice there's no malloc() and no memcpy(). Next, notice the use of the iov_t type. This is a structure that contains an address and length pair, and we've allocated two of them (named iov). The iov_t type definition is automatically included by <sys/neutrino.h>, and is defined as: typedef struct iovec { void *iov_base; size_t iov_len; } iov_t; Given this structure, we fill the address and length pairs with the write header (for the first part) and the data from the client (in the second part). There's a convenience macro called SETIOV() that does the assignments for us. It's formally defined as: #include <sys/neutrino.h> #define SETIOV(_iov, _addr, _len) \ ((_iov)->iov_base = (void *)(_addr), \ (_iov)->iov_len = (_len)) SETIOV() accepts an iov_t, and the address and length data to be stuffed into the IOV. Also notice that since we're creating an IOV to point to the header, we can allocate the header on the stack without using malloc(). This can be a blessing and a curse — it's a blessing when the header is quite small, because you avoid the headaches of dynamic memory allocation, but it can be a curse when the header is huge, because it can consume a fair chunk of stack space. Generally, the headers are quite small. In any event, the important work is done by MsgSendv(), which takes almost the same arguments as the MsgSend() function that we used in the previous example: #include <sys/neutrino.h> int MsgSendv (int coid, const iov_t *siov, int sparts, const iov_t *riov, int rparts); Let's examine the arguments: This is how the kernel views the data: How the kernel sees a multipart message. The kernel just copies the data seamlessly from each part of the IOV in the client's space into the server's space (and back, for the reply). Effectively, the kernel is performing a gather-scatter operation. A few points to keep in mind: Why is the last point so important? To answer that, let's take a look at the big picture. On the client side, let's say we issued: write (fd, buf, 12000); which generated a two-part IOV of: On the server side, (let's say it's the filesystem, fs-qnx4), we have a number of 4 KB cache blocks, and we'd like to efficiently receive the message directly into the cache blocks. Ideally, we'd like to write some code like this: // set up the IOV structure to receive into: SETIOV (iov + 0, &header, sizeof (header.io_write)); SETIOV (iov + 1, &cache_buffer [37], 4096); SETIOV (iov + 2, &cache_buffer [16], 4096); SETIOV (iov + 3, &cache_buffer [22], 4096); rcvid = MsgReceivev (chid, iov, 4, NULL); This code does pretty much what you'd expect: it sets up a 4-part IOV structure, sets the first part of the structure to point to the header, and the next three parts to point to cache blocks 37, 16, and 22. (These numbers represent cache blocks that just happened to be available at that particular time.) Here's a graphical representation: Converting contiguous data to separate buffers. Then the MsgReceivev() function is called, indicating that we'll receive a message from the specified channel (the chid parameter) and that we're supplying a 4-part IOV structure. This also shows the IOV structure itself. (Apart from its IOV functionality, MsgReceivev() operates just like MsgReceive().) Oops! We made the same mistake as we did before, when we introduced the MsgReceive() function. How do we know what kind of message we're receiving, and how much data is associated with it, until we actually receive the message? We can solve this the same way as before: rcvid = MsgReceive (chid, &header, sizeof (header), NULL); switch (header.message_type) { … case _IO_WRITE: number_of_bytes = header.io_write.nbytes; // allocate / find cache buffer entries // fill 3-part IOV with cache buffers MsgReadv (rcvid, iov, 3, sizeof (header.io_write)); This does the initial MsgReceive() (note that we didn't use the IOV form for this — there's really no need to do that with a one-part message), figures out what kind of message it is, and then continues reading the data out of the client's address space (starting at offset sizeof (header.io_write)) into the cache buffers specified by the 3-part IOV. Notice that we switched from using a 4-part IOV (in the first example) to a 3-part IOV. That's because in the first example, the first part of the 4-part IOV was the header, which we read directly using MsgReceive(), and the last three parts of the 4-part IOV are the same as the 3-part IOV — they specify where we'd like the data to go. You can imagine how we'd perform the reply for a read request: Note that if the data doesn't start right at the beginning of a cache block (or other data structure), this isn't a problem. Simply offset the first IOV to point to where the data does start, and modify the size. All the message-passing functions except the MsgSend*() family have the same general form: if the function has a “v” at the end of it, it takes an IOV and a number-of-parts; otherwise, it takes a pointer and a length. The MsgSend*() family has four major variations in terms of the source and destinations for the message buffers, combined with two variations of the kernel call itself. Look at the following table: By “linear,” I mean a single buffer of type void * is passed, along with its length. The easy way to remember this is that the “v” stands for “vector,” and is in the same place as the appropriate parameter — first or second, referring to “send” or “receive,” respectively. Hmmm… looks like the MsgSendsv() and MsgSendsvnc() functions are identical, doesn't it? Well, yes, as far as their parameters go, they indeed are. The difference lies in whether or not they are cancellation points. The “nc” versions are not cancellation points, whereas the non-“nc” versions are. (For more information about cancellation points and cancelability in general, please consult the Neutrino Library Reference, under pthread_cancel().) You've probably already suspected that all the variants of the MsgRead(), MsgReceive(), MsgSend(), and MsgWrite() functions are closely related. (The only exception is MsgReceivePulse() — we'll look at this one shortly.) Which ones should you use? Well, that's a bit of a philosophical debate. My own personal preference is to mix and match. If I'm sending or receiving only one-part messages, why bother with the complexity of setting up IOVs? The tiny amount of CPU overhead in setting them up is basically the same regardless of whether you set it up yourself or let the kernel/library do it. The single-part message approach saves the kernel from having to do address space manipulations and is a little bit faster. Should you use the IOV functions? Absolutely! Use them any time you find yourself dealing with multipart messages. Never copy the data when you can use a multipart message transfer with only a few lines of code. This keeps the system screaming along by minimizing the number of times data gets copied around the system; passing the pointers is much faster than copying the data into a new buffer.: Receiving a pulse is very simple: a tiny, well-defined message is presented to the MsgReceive(), as if a thread had sent a normal message. The only difference is that you can't MsgReply() to this message — after all, the whole idea of a pulse is that it's asynchronous. In this section, we'll take a look at another function, MsgReceivePulse(), that's useful for dealing with pulses. The only “funny” thing about a pulse is that the receive ID that comes back from the MsgReceive() function is zero. That's your indication that this is a pulse, rather than a regular message from a client. You'll often see code in servers that looks like this: #include <sys/neutrino.h> rcvid = MsgReceive (chid, …); if (rcvid == 0) { // it's a pulse // determine the type of pulse // handle it } else { // it's a regular message // determine the type of message // handle it } Okay, so you receive this message with a receive ID of zero. What does it actually look like? From the <sys/neutrino.h> header file, here's the definition of the _pulse structure: struct _pulse { uint16_t type; uint16_t subtype; int8_t code; uint8_t zero [3]; union sigval value; int32_t scoid; }; Both the type and subtype members are zero (a further indication that this is a pulse). The code and value members are set to whatever the sender of the pulse determined. Generally, the code will be an indication of why the pulse was sent; the value will be a 32-bit data value associated with the pulse. Those two fields are where the “40 bits” of content comes from; the other fields aren't user adjustable. The kernel reserves negative values of code, leaving 127 values for programmers to use as they see fit. The value member is actually a union: union sigval { int sival_int; void *sival_ptr; }; Therefore (expanding on the server example above), you often see code like: #include <sys/neutrino.h> rcvid = MsgReceive (chid, … if (rcvid == 0) { // it's a pulse // determine the type of pulse switch (msg.pulse.code) { case MY_PULSE_TIMER: // One of your timers went off, do something // about it... break; case MY_PULSE_HWINT: // A hardware interrupt service routine sent // you a pulse. There's a value in the "value" // member that you need to examine: val = msg.pulse.value.sival_int; // Do something about it... break; case _PULSE_CODE_UNBLOCK: // A pulse from the kernel, indicating a client // unblock was received, do something about it... break; // etc... } else { // it's a regular message // determine the type of message // handle it } This code assumes, of course, that you've set up your msg structure to contain a struct _pulse pulse; member, and that the manifest constants MY_PULSE_TIMER and MY_PULSE_HWINT are defined. The pulse code _PULSE_CODE_UNBLOCK is one of those negative-numbered kernel pulses mentioned above. You can find a complete list of them in <sys/neutrino.h> along with a brief description of the value field. The).. When we introduced the server (in “The server”), we mentioned that the ChannelCreate() function takes a flags parameter and that we'd just leave it as zero. Now it's time to explain the flags. We'll examine only a few of the possible flags values: Let's look at the _NTO_CHF_UNBLOCK flag; it has a few interesting wrinkles for both the client and the server. Normally (i.e., where the server does not specify the _NTO_CHF_UNBLOCK flag) when a client wishes to unblock from a MsgSend() (and related MsgSendv(), MsgSendvs(), etc. family of functions), the client simply unblocks. The client could wish to unblock due to receiving a signal or a kernel timeout (see the TimerTimeout() function in the Neutrino Library Reference, and the Clocks, Timers, and Getting a Kick Every So Often chapter). The unfortunate aspect to this is that the server has no idea that the client has unblocked and is no longer waiting for a reply. Note that it isn't possible to write a reliable server with this flag off, except in very special situations which require cooperation between the server and all its clients. Let's assume that you have a server with multiple threads, all blocked on the server's MsgReceive() function. The client sends a message to the server, and one of the server's threads receives it. At this point, the client is blocked, and a thread in the server is actively processing the request. Now, before the server thread has a chance to reply to the client, the client unblocks from the MsgSend() (let's assume it was because of a signal). Remember, a server thread is still processing the request on behalf of the client. But since the client is now unblocked (the client's MsgSend() would have returned with EINTR), the client is free to send another request to the server. Thanks to the architecture of Neutrino servers, another thread would receive another message from the client, with the exact same receive ID! The server has no way to tell these two requests apart! When the first thread completes and replies to the client, it's really replying to the second message that the client sent, not the first message (as the thread actually believes that it's doing). So, the server's first thread replies to the client's second message. This is bad enough; but let's take this one step further. Now the server's second thread completes the request and tries to reply to the client. But since the server's first thread already replied to the client, the client is now unblocked and the server's second thread gets an error from its reply. This problem is limited to multithreaded servers, because in a single-threaded server, the server thread would still be busy working on the client's first request. This means that even though the client is now unblocked and sends again to the server, the client would now go into the SEND-blocked state (instead of the REPLY-blocked state), allowing the server to finish the processing, reply to the client (which would result in an error, because the client isn't REPLY-blocked any more), and then the server would receive the second message from the client. The real problem here is that the server is performing useless processing on behalf of the client (the client's first request). The processing is useless because the client is no longer waiting for the results of that work. The solution (in the multithreaded server case) is to have the server specify the _NTO_CHF_UNBLOCK flag to its ChannelCreate() call. This says to the kernel, “Tell me when a client tries to unblock from me (by sending me a pulse), but don't let the client unblock! I'll unblock the client myself.” The key thing to keep in mind is that this server flag changes the behavior of the client by not allowing the client to unblock until the server says it's okay to do so. In a single-threaded server, the following happens: This didn't help the client unblock when it should have, but it did ensure that the server didn't get confused. In this kind of example, the server would most likely simply ignore the pulse that it got from the kernel. This is okay to do — the assumption being made here is that it's safe to let the client block until the server is ready with the data. If you want the server to act on the pulse that the kernel sent, there are two ways to do this: Which method you choose depends on the type of work the server does. In the first case, the server is actively performing the work on behalf of the client, so you really don't have a choice — you'll have to have a second thread that listens for unblock-pulses from the kernel (or you could poll periodically within the thread to see if a pulse has arrived, but polling is generally discouraged). In the second case, the server has something else doing the work — perhaps a piece of hardware has been commanded to “go and collect data.” In that case, the server's thread will be blocked on the MsgReceive() function anyway, waiting for an indication from the hardware that the command has completed. In either case, the server must reply to the client, otherwise the client will remain blocked. Even if you use the _NTO_CHF_UNBLOCK flag as described above, there's still one more synchronization problem to deal with. Suppose that you have multiple server threads blocked on the MsgReceive() function, waiting for messages or pulses, and the client sends you a message. One thread goes off and begins the client's work. While that's happening, the client wishes to unblock, so the kernel generates the unblock pulse. Another thread in the server receives this pulse. At this point, there's a race condition — the first thread could be just about ready to reply to the client. If the second thread (that got the pulse) does the reply, then there's a chance that the client would unblock and send another message to the server, with the server's first thread now getting a chance to run and replying to the client's second request with the first request's data: Confusion in a multithreaded server. Or, if the thread that got the pulse is just about to reply to the client, and the first thread does the reply, then you have the same situation — the first thread unblocks the client, who sends another request, and the second thread (that got the pulse) now unblocks the client's second request. The situation is that you have two parallel flows of execution (one caused by the message, and one caused by the pulse). Ordinarily, we'd immediately recognize this as a situation that requires a mutex. Unfortunately, this causes a problem — the mutex would have to be acquired immediately after the MsgReceive() and released before the MsgReply(). While this will indeed work, it defeats the whole purpose of the unblock pulse! (The server would either get the message and ignore the unblock pulse until after it had replied to the client, or the server would get the unblock pulse and cancel the client's second operation.) A solution that looks promising (but is ultimately doomed to failure) would be to have a fine-grained mutex. What I mean by that is a mutex that gets locked and unlocked only around small portions of the control flow (the way that you're supposed to use a mutex, instead of blocking the entire processing section, as proposed above). You'd set up a “Have we replied yet?” flag in the server, and this flag would be cleared when you received a message and set when you replied to a message. Just before you replied to the message, you'd check the flag. If the flag indicates that the message has already been replied to, you'd skip the reply. The mutex would be locked and unlocked around the checking and setting of the flag. Unfortunately, this won't work because we're not always dealing with two parallel flows of execution — the client won't always get hit with a signal during processing (causing an unblock pulse). Here's the scenario where it breaks: If you refine the flag to indicate more states (such as pulse received, pulse replied to, message received, message replied to), you'll still run into a synchronization race condition because there's no way for you to create an atomic binding between the flag and the receive and reply function calls. (Fundamentally, that's where the problem lies — the small timing windows after a MsgReceive() and before the flag is adjusted, and after the flag is adjusted just before the MsgReply().) The only way to get around this is to have the kernel keep track of the flag for you. Luckily,. To keep things clear, I've avoided talking about how you'd use message passing over a network, even though this is a crucial part of Neutrino's flexibility! Everything you've learned so far applies to message passing over the network. Earlier in this chapter, I showed you an example: #include <fcntl.h> #include <unistd.h> int main (void) { int fd; fd = open ("/net/wintermute/home/rk/filename", O_WRONLY); write (fd, "This is message passing\n", 24); close (fd); return (EXIT_SUCCESS); } At the time, I said that this was an example of “using message passing over a network.” The client creates a connection to a ND/PID/CHID (which just happens to be on a different node), and the server performs a MsgReceive() on its channel. The client and server are identical in this case to the local, single-node case. You could stop reading right here — there really isn't anything “tricky” about message passing over the network. But for those readers who are curious about the how of this, read on! Now that we've seen some of the details of local message passing, we can discuss in a little more depth how message passing over a network works. While this discussion may seem complicated, it really boils down to two phases: name resolution, and once that's been taken care of, simple message passing. Here's a diagram that illustrates the steps we'll be talking about: Message passing over a network. Notice that Qnet is divided into two sections. In the diagram, our node is called magenta, and, as implied by the example, the target node is called wintermute. Let's analyze the interactions that occur when a client program uses Qnet to access a server over the network: Once steps 1 through 3 have been established, step 4 is the model for all future communications. In our client example above, the open(), read(), and close() messages all take path number 4. Note that the client's open() is what triggered this sequence of events to happen in the first place — but the actual open message flows as described (through path number 4). We'll come back to the messages used for the open(), read(), and close() (and others) in the Resource Managers chapter.. The Neutrino), native networking was based on the concept of a node ID, a small integer that was unique on the network. Thus, we'd talk about “node 61,” or “node 1,” and this was reflected in the function calls. Under: One: Three threads at different: Blocked threads.: Boosting the server's priority. This way we take a minor hit by letting L's job run at a priority higher than L, but we do ensure that H gets a fair crack at the CPU. There's no trick!. Message passing is an extremely powerful concept and is one of the main features on which Neutrino (and indeed, all past QNX operating systems) is built. With message passing, a client and a server exchange messages (thread-to-thread in the same process, thread-to-thread in different processes on the same node, or thread-to-thread in different processes on different nodes in a network). The client sends a message and blocks until the server receives the message, processes it, and replies to the client. The main advantages of message passing are:
http://www.qnx.com/developers/docs/6.5.0SP1.update/com.qnx.doc.neutrino_getting_started/s1_msg.html
CC-MAIN-2022-33
refinedweb
8,946
67.28
#include <unistd.h> int close (int fildes); The fildes argument is a file descriptor obtained from a creat, open, dup, fcntl, or pipe system call. The close system call closes the file descriptor indicated by fildes. All outstanding record locks owned by the process (on the file indicated by fildes) are removed. If a STREAMS file is closed, and the calling process had previously registered to receive a SIGPOLL signal (see sigaction(S) and sigset(S)) for events associated with that file, the calling process is unregistered for events associated with the file. The last close for a stream causes the stream associated with fildes to be dismantled. If O_NONBLOCK is not set and there have been no signals posted for the stream, close waits up to 15 seconds, for each module and driver, for any output to drain before dismantling the stream. If the O_NONBLOCK flag is set or if there are any pending signals, close does not wait for output to drain and dismantles the stream immediately. The named file is closed unless one or more of the following is true: int fd;Note that all open files in a program are closed when a program terminates normally or when the exit function is called, so no explicit call to close is required. if (argc >1) close(0); X/Open Portability Guide, Issue 3, 1989 ; Intel386 Binary Compatibility Specification, Edition 2 (iBCSe2) ; IEEE POSIX Std 1003.1-1990 System Application Program Interface (API) [C Language] (ISO/IEC 9945-1) ; and NIST FIPS 151-1 .
http://osr507doc.xinuos.com/en/man/html.S/close.S.html
CC-MAIN-2019-30
refinedweb
256
55.07
This Crash Course in Storytelling Kendall Haven and MaryGay Ducey Crash Course Series Westport, Connecticut • London Library of Congress Cataloging-in-Publication Data Haven, Kendall F. Crash course in storytelling / by Kendall Haven and MaryGay Ducey. p. cm. — (Crash course) Includes bibliographical references and index. ISBN 1-59158-399-3 (pbk : alk. paper) 1. Storytelling. I. Ducey, MaryGay. II. Title. LB1042.H388 2007 372.67’7—dc22 2006030670 British Library Cataloguing in Publication Data is available. reproduced, by any process or technique, without the express written consent of the publisher. Library of Congress Catalog Card Number: 2006030670 ISBN: 1-59158-399-3 This book is dedicated to Patrick Ducey Dylan Brie Ducey, and Patrick Seth Ducey Contents Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Chapter 1—The Place for Storytelling in Your Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Libraries Are Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 We’ve Been Telling for a Long Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 What Kind of Stories? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 What’s in It for You? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 From Kitchen Table to Carnegie Hall: The Three Levels of Storytelling . . . . . . . . . . . . . . . . . 4 Level 1: The Informal Storyteller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Level 2: The Community Storyteller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Level 3: The Professional Storyteller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 The Place for Storytelling in Your Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Chapter 2—Why Tell It?: The Power of Storytelling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Because You Can. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Because Library Patrons Need Your Stories. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Because Storytelling Is a Great Change of Pace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Because Storytelling Is Affecting and Engaging for the Audience . . . . . . . . . . . . . . . . . . . . . 11 Because Storytelling Makes Nonfiction Events and Topics Come Alive . . . . . . . . . . . . . . . . 12 Because Storytelling Generates Vivid and Detailed Images in a Listener’s Mind . . . . . . . . . 13 Because Storytelling Helps Those Who Struggle with Language to Understand and Interpret the Story. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Because Storytelling Connects Listeners to You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Chapter 3—“Okay, But Can I Really Do It?” Making Storytelling Practical and Doable . . . . 15 Asking the Right Question. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 You Don’t Have to Get It Right to Get It Right . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 How Do You Naturally Learn, Recall, and Tell Your Own Stories? . . . . . . . . . . . . . . . . . . . 18 What Listeners Really Need. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 The Difference Between Reading and Telling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Chapter 4—Choosing Stories That Will Work for You. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Where Do I Start? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Which Stories to Start With? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 How to Pick a Story . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 What Is a Story?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 What to Look for in a Story . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Evaluating a Story . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 vii viii Contents Chapter 5—Learning the Stories You Tell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 “Learning” Your Own Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Keep It Simple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 Toys to Play With . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Chapter 6—The Great Exception: Literary Tales. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 Tell It or Read It. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Telling Literary Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Learning Literary Tales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Chapter 7—Playing with Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Why Practice? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Play with Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 The Final Four . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Chapter 8—Glorious Tellings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Before It’s Time to Tell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Don’t Go It Alone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Stage Arrangements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Setting the Scene . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Let’s Start the Story . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Keep Moving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Slow Down. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Your Partners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Grand Finale. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Don’t Muddy the Water . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Celebrate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Keeping Track . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Chapter 9—First Aid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 To Memorize, or Not to Memorize? That Is the Question . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 The Great-Amazing-Never-Fail Safety Net. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Go Ahead and Forget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Learn the Smile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Tell About the Story . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 When You Remember You Forgot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55 What Comes Next . . . ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 Contents ix Chapter 10—Owner’s Manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 An Opening Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 Voice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Rate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Pitch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Volume . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Gesture and Movement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Chapter 11—Storytelling Extras . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Flannelboards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 The Plusses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 The Minuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 Props . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 The Plusses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 The Minuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Make It Work for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Costumes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 The Plusses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 The Minuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Make It Work for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 Puppets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 The Plusses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 The Minuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 Make It Work for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 Audience Participation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 The Plusses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 The Minuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Make It Work for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 “Cast of Thousands” Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 The Plusses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 The Minuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 Make It Work for You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Chapter 12—Let the Stories Roll!. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Where to Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Special Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 More Ambitious Ideas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Keep on Keeping On . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 x Contents Appendix 1—The Structure of Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 What Is a Story?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Intent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Conflicts and Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Struggles (Plot). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Appendix 2—Who Says Storytelling Is Worthwhile? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Does Storytelling Work? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Why and How Does Storytelling Work? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Appendix 3—Copyright and You . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Appendix 4—Definitions of Traditional Tales. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 References: Works Cited in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Storytelling Advice, Approaches, Theory, and Stories.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Storytelling Research Guides and Commentary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Reliable Collections of Traditional Tales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Family and Personal Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 Participation Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Song, Movement, and Props Stories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 Webliography for Storytelling, Storytellers, and Stories. . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 INTRODUCTION “Do you tell stories?” Amazingly, many people answer, “No.” Might as well ask, “Do you breathe?” Of course you tell stories. You might think your stories don’t compare to the dramatic performances you’ve seen by famed professional tellers. But so what? Some go so far as to think that their storytelling doesn’t count. Not true! Your stories are every bit as legitimate and valuable a part of storytelling and are just as important. Storytelling is the art of using language, vocalization, and/or physical movement and gesture to reveal the elements and images of a story to a specific, live audience. That’s what humans do. Storytelling is as old as the human race and has been a cherished human activity for tens of thousands of years. Storytelling in the United States survived through the early twentieth century in two places: private homes (where family members told to entertain and to inform family and friends) and public libraries. In the 1970s a new phenomenon emerged: American professional storytelling. These tellers’ stories were designed for entertainment; the style quickly became theatrical. The spread of professional tellers has infused storytelling into the fiber and flow of daily life and has encouraged community organizations and groups to tell more stories and to create more opportunities for storytelling, though (surprisingly—at least to many of us who call ourselves storytellers) not nearly to the extent anticipated or hoped for. It’s as if many people now think that storytelling is a special art form that should be practiced only by dedicated, skilled professionals. Nothing could be further from the truth. Storytelling is a human attribute, a human skill—even a human birthright—that belongs to everyone. Yes, polished, practiced professionals are fun to watch. But that does not diminish the value of, nor the enjoyment others will derive from, the telling you do. In part because libraries have focused on occasional headliner performances by a hired professional, we wonder if these artists have discouraged some library staff members from telling themselves. We have written this book to pool both our experience in, and our perspective on, storytelling. Gay Ducey is a professional storyteller with twenty-five years’ experience who has also served as a children’s librarian at the Oakland (California) Public Library for twenty-five years. She brings both an understanding of the interplay of library operations and storytelling and significant insights into the process of telling stories. She has served long and well on all sides of this issue: as the invited professional teller, as the librarian teller, and as the librarian who brings in other professional tellers. Kendall Haven jumped to storytelling from the world of science. With twenty-five years of experience as a teller and writer working primarily with schools and in the field of education, he brings both practical experience and a penchant for analytical assessment to this writing effort. xi xii Introduction Gay and Kendall share the same general philosophy, which permeates this work. Most of what is written here is a melding of our common experiences and beliefs. Where statements reflect the unique experience or belief of one of us, those statements are labeled by name. Professional storytellers abound in the United States—polished performers working from polished stages to appreciative crowds. However, we believe that professional storytelling is only one end of the continuum of storytelling in a healthy community. There is a vital role to be filled at the community level for stories and storytelling. There is no better nor more logical location to provide this level of storytelling fare than the library. That’s YOU, the local librarian. In this book we hope to encourage you to try more storytelling. We hope to gently nudge you to stretch your storytelling wings, to prove to yourself and to your patrons that your storytelling skills are more than equal to the task of providing your community with a steady diet of storytelling. Storytelling has proven value—to the listeners, to the community, and to the library. This book is our attempt to contribute to elevating the prominence of storytelling in libraries. This book is not intended to serve as a performance guide for experienced tellers, nor is it primarily a sourcebook for stories to tell. It is a guide to the simplicity and elegance of natural storytelling for those who are not fully convinced of either their storytelling ability or storytelling’s place in their library. We have filled this book with tested and proven techniques and ideas for you to use. It represents the wisdom produced from over fifty years of combined storytelling experience. There is not one “correct” style for storytelling, not one “correct” way to tell a story. Just the opposite. The richness of storytelling depends on each teller finding a style and delivery that feels comfortable and natural. The glory and attraction of storytelling comes from this range and variety. There is room for and need for all styles. Still, we believe that too few librarians tell stories. Some tell us that they have no time to learn and rehearse stories. Some feel that they simply don’t have the ability to do it. Some think it’s too hard and prefer to stick to reading. Some believe that storytelling requires a special talent that they may not have. We don’t believe it. By the end of this book, we hope you won’t either. Enjoy! HAPTER 1 C The Place for Storytelling in Your Library LIBRARIES ARE STORIES Libraries are institutions in service to stories and information. The public library, in particular, is a kind of repository of discourse. Not just in print, either. The library’s collections of stories include films, recordings, documents, meetings, talks, local history, genealogy, author visits, programs, and time and space for patrons to simply talk. The library is a place in conversation with the culture at large. Library staff anchors the institution. Those of us in public service like to share information, impressions, recommendations, and resources. We like to talk to our patrons. Since good conversation is based on constructing a cogent narrative, librarians have more experience in shooting the breeze than those in many other professions. We present programs for all ages, and storytelling fits right into most of them. Just a 1 2 Chapter 1—The Place for Storytelling in Your Library cursory look at your monthly schedule will reveal the number of hours spent in program presentation, class visits, reference, and outreach. We often persuade a visitor to try a new title or to tell us what books she or he has been reading. In the course of determining what help is needed we find ourselves listening to a story as it unwinds, and telling one in turn. A visit to a contemporary public library will soon dispel the stereotype of the sensible-shoed, bun-coiffed, glasses-dangling, middle-aged woman who seems to be protecting the books from the unworthy. Librarians are very savvy about retrieving information from the Internet, gauging the reading level of a silent third grader, finding the right book for the right person at the right time, balancing a budget, stretching resources, and making friends. No wonder we are naturally good at telling tales. WE’VE BEEN TELLING FOR A LONG TIME Storytelling has a long, honorable history in the public library. Perhaps the most visible example of that history has involved service to young people. The New York Public Library, for instance, blazed a glorious trail for storytelling decades ago when Ruth Sawyer began the first storytelling program there in 1908. Far from being a glamorous extra, storytelling was an integral service for children. But telling stories is far too much fun, far too valuable, and far too effective to be the prize of the nursery. It belongs to all of us. Libraries are busy places. The days of a quiet sanctuary for the quiet seeker of knowledge are gone, if they ever existed. Librarians have too much to do, and too little time in which to do it. We know that. We wouldn’t suggest another professional investment if we didn’t think it would make your work more rewarding, serve your patrons more effectively, and, best of all, be enjoyable. Storytelling is the most effective educational tool for the least amount of effort. It employs the skills you already possess and puts them to good use. Think of it as another way to meet the mandate of promoting literature and ideas—a really entertaining way. It is also a valuable addition in the effort to encourage literacy for all ages and all cultures. What’s in It for You? 3 WHAT KIND OF STORIES? Storytelling changes the picture. Slipping a told story into a preschool storytime presents literature in a fresh and novel way. It allows for a more engaging presentation for groups visiting the library. The story can be from the great collections of traditional tales that beg to be freed from the book, or an excerpt from chosen fiction or nonfiction. A simple folktale can marry well with books during a program. History can become story and lead listeners to following the path into the past. That story you tell about your bad grade can showcase books about school or study habits. Your mother’s famous piano recital becomes the bridge for a talk about skills, talents, and of course, inevitable failures. An urban legend can open the creaky door of books about mysterious events. Anything will serve. The key is the process of storytelling as the way you choose to deliver story material to your listeners. Any of these types of stories—or many others—become engaging elements of your program when you tell them. WHAT’S IN IT FOR YOU? The more you tell stories, the better you tell them. Your professional life will always include presentations, some more challenging than others. Polish up your storytelling skills, find some enriching tales and you will improve your presentational style and confidence. Not all of those who visit the library are comfortable with print. Some people find the oral approach to literature much easier to absorb and retain. Gay knows this from experience since it was told stories, not print, that her A.D.D. son responded to, whether they were old tales, personal stories, or science tidbits. A good story reached that learner very well since it leveled the cognitive playing field. Or at least minimized the gradation. Librarianship is one of the few professions in which every single thing you know or have experienced is useful, so your own personal interests, possessions, background become grist for the story mill. You already have a wealth of information to share, and it is easy to convert it into good stories. 4 Chapter 1—The Place for Storytelling in Your Library Need more? There’s nothing like a story to engage and entertain an audience. Your telling brings listeners to you, makes you accessible and approachable. We know how important that is in forging relationships with our patrons. Besides, there’s nothing like a professional change of pace to refresh us. Stories of myth, legend, folktale, fairy tale, epic, and fable are the great literary treasure of every culture. As the heirs to that hoard, we can give it to others in the way it deserves to be shared: by telling. (P.S.: you get to keep it, too.) FROM KITCHEN TABLE TO CARNEGIE HALL: THE THREE LEVELS OF STORYTELLING Although our evidence is anecdotal, both of us have noticed how few library storytellers we run across in our travels. More often, we (and other professional tellers) are the storytellers, who come in to do a performance or two, gather the glory, and then hit the road. We also know, again anecdotally, that libraries routinely use the services of professional storytellers as entertainers linked to a particular holiday or summer program. We don’t presume to understand all the reasons for this reliance on declared professional tellers. But we have both seen it and become aware of its deleterious impact on a community. It doesn’t have to be that way. It shouldn’t be that way. But it is. It may be that library staff see those professional storytellers and think; “I could never, ever do that.” “That”—when taken literally—may well be true. You may never, ever become a professional storyteller. But that has nothing to do with your becoming a successful storyteller within the library. The expectations, and performance requirements of a polished professional telling on a raised stage to a thousand listeners are different from those of friends sharing stories around the kitchen table, for instance. Common sense tells us that, but that doesn’t mean one is more important than another. Think of it this way: professional chefs clog the landscape of the Food Network, demonstrating their finesse, their perfect confections, their glib on-air delivery, and their panache. For those who are interested, it is a dazzling display. But we never see them cooking at home, only in the hot lights of a show. Books, CDs, upscale kitchen ware all From Kitchen Table to Carnegie Hall 5 bear the name of The Famous Chef. Many a cook has learned a good deal by watching these pros work and been inspired to try a dish or two. That’s what they do best: inspire, motivate, entertain. The food is fancy, and it would be great to sit down to the table for such a meal once in a long while. Most of us who like to cook on occasion, and even those who cook every day, are not going to become Iron Chefs and will never challenge Emeril for his primetime TV slot. Yet we can whip up an appetizing dinner that will please—even thrill—our families more often than not, and sometimes we can mount a holiday dinner that confounds even our mothers-in-law. Storytelling is like that. It has room for everyone who wants to tell a tale. It is not confined to those who choose to make a living at it. Granted, some folks have a gift. We readily admit that. They are uncommonly talented. But just as you would not stop cooking because you haven’t been picked up for a pilot, so, too, you should not avoid telling stories just because there are some storytellers who are better than you believe yourself to be. That would be a shame, for you would deny the gifts of story literature to the children and adults who patronize your library, except on those few, scattered occasions when the hired narrative gun sweeps into town. That’s not enough. We offer the following idea: storytelling has levels. None is more important than another, but they differ, so it is helpful to distinguish between them. Level 1: The Informal Storyteller Informal storytelling happens throughout the routine course of our daily lives. Occasionally planned but more often spontaneous, conversational, and interactive in nature, informal storytelling forms an essential part of the fabric of our normal communications. Stories told across the family dinner table, by the auto mechanic running your smog check, in the supermarket checkout line, during chance meetings of friends and colleagues—these are all times when we automatically slip into the role of informal storytellers. We don’t usually plan or organize the text, nor do we practice or try to refine our style or voices. Some of the stories are brand new, the stuff of the day; others are well-worn narratives about our families that each member knows by heart. Around the kitchen table, these stories ebb and 6 Chapter 1—The Place for Storytelling in Your Library flow, sometimes punctuated by someone else adding a detail or correction. Above all, informal storytelling is a natural and unrehearsed part of human communications. Level 2: The Community Storyteller This sort of storytelling usually takes place within the professional setting. The library, the classroom, the pulpit, the courtroom, each of these is the native habitat for tales. In ancient times, the storyteller passed on stories of wisdom and heritage. The tales reflected the prevailing values and exposed new listeners to important information that kept them safe and taught them how to behave. Adults heard the stories that glorified the community’s valorous history, or traced lineage. Novelty was not useful. Continuity was essential. Contemporary visitors to the library need and deserve these stories still. This is the setting in which the children and adults can hear stories that feed the soul and free the imagination. It is desirable for the storyteller to be familiar, and the stories, too. At this level, stories can and should be repeated again and again. Community storytellers do not need to perform. They need to share. The style of the storyteller is unimportant. From a very dramatic teller to one who has a quiet, intimate approach, each is useful. Level 3: The Professional Storyteller The professional storyteller delivers a polished, rehearsed performance, usually to a relatively large audience. It is not uncommon for the performance to have a title. The storyteller may well be traveling through, never to be seen again. Styles may differ, but the teller is often larger than life and the performance is formally staged. Our expectations are high; we anticipate seeing a well-prepared artist with strong, precise language and physical preparation. Level 3 is something like a holiday feast, a rare, rich treat, to be enjoyed occasionally, not as a steady diet. We all benefit from these occasional storytellers, but the place for day-in and day-out storytelling is with you, the library storyteller. It was when we started to use professional storytellers as the primary designated artistic hitters that we got off track. Libraries can facilitate all three levels of storytelling. Encourage and facilitate informal telling. Arrange and sponsor occasional professional performances. The Place for Storytelling in Your Library 7 And accept your role as a primary provider of a steady diet of community level storytelling. THE PLACE FOR STORYTELLING IN YOUR LIBRARY Many opportunities for storytelling exist in your library. This list of five is not intended to be exhaustive; rather, it represents proven niches for your storytelling. Let these ideas free you to identify the many other ways you can weave storytelling into your library and programs. 1. As a snazzy addition to preschool and early elementary storytimes. 2. As an effective, natural, direct form of booktalking. And not just for audiences of elementary school children. When presenting “booktalks” to middle and high school audiences, stories (riddling tales, urban legends, brief information about a famous guy) can be effectively incorporated into presentations (see Gail de Vos’s book about storytelling for teens in the Bibliography). As an alternative to the normal booktalk fare for longer books (telling a little bit about the book, main character, and/or author but not the end), consider taking one incident within the book and simply tell the whole thing. 3. As an evening performance for families and older kids. Granted, these performances often feature the storytellerfor-hire. Let’s change that. Once you have a few tales under your belt, you can at least complement the guest performer, or, better, start offering programs featuring YOU (the storyteller). 4. As a special holiday program. You need not do the whole thing. Try combining your talents with several other staff persons, and, like Mickey Rooney and Judy Garland, “put on a show.” 5. As part of presentations to community groups or other organizations. Any story that complements your presentation will be well received by the audience. Try a fable, a story about Mullah Nasruddin, or any short tale that suits you and the occasion. Emphasis is on brief, fast, and either amusing or thoughtful, whichever the context suggests. So let’s take it back. Let’s claim storytelling as a valuable offering to our constituents. And let’s do it ourselves. HAPTER 2 C Why Tell It?: The Power of Storytelling Chapter 1 described a role for the different levels of storytelling as integral parts of your library programs. That chapter showed what storytelling can do for your library programs. There are eight additional reasons for you to tell stories as an important part of your library’s offerings. We know that most of you already view storytelling as valuable and worthwhile and may not need new evidence of its power and value. Consider this list a gentle reminder of how important you and your telling are in the lives and development of your young patrons and what a gift your storytelling can be. BECAUSE YOU CAN As you’ll see throughout this book, you already know most of what you’ll need to know, and have the innate talent you’ll need, to tell stories successfully and effectively. 9 10 Chapter 2—Why Tell It?: The Power of Storytelling BECAUSE LIBRARY PATRONS NEED YOUR STORIES Everyone benefits from listening to stories being told: traditional tales, folktales, “Just So” stories, myths, etc. We all need to hear these stories being told with enthusiasm, and need to absorb the form, patterns, rhythms, and content of these stories. Children especially need the developmental benefits of hearing complete stories being told, and they need the cognitive value woven into the content of these stories that have been honed and refined over countless generations of successful tellings by countless tellers. For many children you are a primary source of this level of storytelling. They depend on you. They need you. Their development depends, in a small but real part, on the story and storytelling exposure you provide. A Canadian study published in 2004 (O’Neill, Pearce, and Pick, 2004) studied the storytelling ability of preschool children in Ontario, Canada, and found good correlation between early storytelling skills and later math abilities. They suggest that time spent telling stories to children and allowing them to informally and improvisationally tell stories to develop their own storytelling skill during preschool years is likely to improve math skill upon entering school. More important than its specific focus on math skills, this study establishes storytelling skill (structural knowledge and story map thinking) as predating, and as a precursor for, the development of logical thinking. Cognitive science studies have confirmed that human beings develop the ability to understand and interpret the world around them through story structure and story concepts long before they develop logical thinking (see Appendix 2). In fact, logical thinking seems to evolve out of story structural thinking. The ability to interpret experiences and to create meaning using story thinking comes from exposure to stories during the early formative years. They need your stories. BECAUSE STORYTELLING IS A GREAT CHANGE OF PACE Even the best pitchers need to change their pitches unless they want to spend a lot of time on the bench. Break it up. Change the pattern of your programs. If your normal pattern is to read stories, storytelling Because Storytelling Is Affecting and Engaging for the Audience 11 (whether improvisational, informal, or planned) will surprise your listeners and create extra interest. BECAUSE STORYTELLING IS AFFECTING AND ENGAGING FOR THE AUDIENCE As a fledgling storyteller, Kendall told stories at an Orange County, California, school—just over a year after he first performed there. As he entered the building, a second-grade girl passed him in the hall and said, “I remember you. You told us stories last year.” Then that seven-year-old girl began to tell the stories she had heard a year before. They were original stories and she had only heard them once. Still, a year later, both stories tumbled out of her, vividly and accurately, with no prompting. That is not at all unusual. Virtually ever storyteller in the country has had this experience. Stories deeply engage and entrance an audience. Don’t worry. Just because there are professional storytellers out there who visit the public library and wow the crowds does not mean they have a life lease on this captivating experience. Gay tells stories in the library as well as telling stories as a professional. Recently a fifth grader returned to the branch after a long absence. “Do you still tell that story about the sultan, the little rooster and the diamond button?” he asked. “Yes” she said “Just this week. Is it one of your favorites?” “Yes” he said, as he began to tell it back to her. It happens all the time and to everyone who regularly tells stories. It is inherent in the process of storytelling, not in some unique property of skilled and theatrical performers. Brain research confirms what storytellers know from experience. Bransford and Brown (2000), Engle (1995), Fisher (1994), Bruner (1990), and other neuroscientists have studied this phenomenon and have drawn two general conclusions: 1. Evolution has “hardwired” the process and form of storytelling into human brains and minds. Fisher concludes that humans are really homo narratus, and that storytelling is an intrinsic human attribute. That is, story architecture is hardwired into the human mind. Bruner has observed that storytelling predates written communication by 50,000 years and that the form and pattern of storytelling are now, as it were, 12 Chapter 2—Why Tell It?: The Power of Storytelling residue of many thousands of years of evolutionary programming. 2. We learn through storytelling. We learn the pattern, rhythm, and structure of oral storytelling long before we learn the rhythms and patterns of written stories. Young infants learn to pay attention to the features of oral speech (such as intonation and rhythm) that help them obtain critical information about language and meaning. Perhaps we respond so positively and powerfully to storytelling because we are genetically predisposed to favor the form. That’s certainly what we think. Your listeners will be more responsive to your storytelling than to the same story delivered in other ways. BECAUSE STORYTELLING MAKES NONFICTION EVENTS AND TOPICS COME ALIVE Dan Fossler, a California high school music teacher, took a storytelling course and created a story about the Italian composer, Vivaldi, for his final exercise. The story was a rousing hit. So he told it to his student orchestra the next fall before assigning them a Vivaldi piece. He was amazed at how quickly this orchestra mastered the difficult piece. He scanned their home practice logs and found that this group was practicing an average of 20 percent more on this piece than had his previous orchestras. When he asked them why, they reported that Vivaldi was “cool” and that they liked him and his music. Ten students had gone to the library to check out additional reading material on Vivaldi. In short, Fossler’s told story made Vivaldi real, accessible and interesting. It created context and relevance. Storytelling does that. Librarians have booktalked for years, just as Mr. Fossler did, using episodes from the lives of the famous and not so famous to entice listeners into reading more. It’s storytelling, really, and it works. Any topic can be introduced to listeners through a tale. Brief folktales can introduce the sciences; personal stories can be woven into sports and the arts; and the 900s offer opportunities for folktales, myths, legends . . . just about any sort of story. Because Storytelling Helps to Understand and Interpret the Story 13 BECAUSE STORYTELLING GENERATES VIVID AND DETAILED IMAGES IN A LISTENER’S MIND Kendall once conducted an experiment with primary students in eight schools (total of 1,090 students and six performances). During short assemblies, he told one story and read a different story of about the same length. Students returned to the classroom and, with no discussion, each drew one picture from just one of the two stories. He varied both the order and the specific stories he presented. But the variations never affected the final results. Between 78 and 86 percent in each class drew a picture of the story that was told. Storytelling seems to create stronger, more vivid and more memorable imagery. When being read a picture book, young listeners almost always ask to see the pictures. But when a story is being told, listeners have no need for pictures. Listening encourages them to create their own images, tailormade to suit each child. Recent neurological research has shown that memory depends on the density of sensory details associated with the event. The greater the number of sensory details filed away into memory surrounding an event or idea, the easier and more likely it is that a person will recall that event or idea. Listening to stories creates vivid, multisensory details. Details create memory. BECAUSE STORYTELLING HELPS THOSE WHO STRUGGLE WITH LANGUAGE TO UNDERSTAND AND INTERPRET THE STORY When reading a book, you use vocal tools, such as tone, pace, and volume to interpret the text. Storytelling does that too. But storytelling more readily allows for physical interpretation of the story through gesture, movement, and expression. These interpretations can vary from dancing across the floor to the most subtle body language. And they are effective in aiding listeners to interpret and visualize the story. 14 Chapter 2—Why Tell It?: The Power of Storytelling Improvisation is a natural part of storytelling. Tellers refine or change their language and delivery in response to the audience reaction. Although small text changes are possible when reading, readers strive to stick closely to the author’s words. Cooper (1997) conducted an extensive study of how in-class storytelling affects students’ development of the ability to extract meaning from texts. He concluded, first, that storytelling significantly enhanced students’ understanding of story text and, second, that a major part of this enhancement came from the improvisational nature of storytelling that allowed the teller to acknowledge and respond to student verbal and nonverbal responses and to adjust the telling to incorporate those responses. Students’ ability to interact with the teller and to have the teller adjust the story and the telling to account for those responses significantly improved students’ ability to understand stories and to create meaning from stories. BECAUSE STORYTELLING CONNECTS LISTENERS TO YOU To many patrons, you are the library. Storytelling can strengthen that impression. It forges an intimate relationship between teller and listener that continues far beyond the actual telling of a tale. It doesn’t really matter what kind of story you tell, where you tell it, or what kind of event it is. It might be part of a planned, formal program, or an improvisational, off-the-cuff story about your family or your own experiences. Regardless of what you choose to tell, the story works to creates the bond. It is always a shared experience. So, why storytelling? Because it produces all of the results—the topical and general interest, the delight, the engagement, the entertainment, and the fun—that mark a good presentation. HAPTER 3 C “Okay, But Can I Really Do It?” Making Storytelling Practical and Doable ASKING THE RIGHT QUESTION Storytelling is not a new set of performance skills to learn. It’s not about rules. Storytelling is a natural process that we all do, but do automatically (unconsciously) rather than consciously. During workshops we often ask groups, “Do you tell stories?” Many, envisioning a long list of rules and mandates for how one is supposed to tell a story, answer “No.” Such people search for the wrong kind of rules to guide them to better, easier storytelling. Should stories be told word for word? Should you use gestures when you tell? Should you move or stand still? Stand or sit? Should you use vocal characterizations? Physical characterizations? 15 16 Chapter 3—“Okay,, respected storytellers who intentionally and successfully violate whatever rule you create. Those are the wrong kinds of questions to ask and the wrong kinds of “rules” to search for. You don’t think about rules when you tell informal stories to your friends and families. You simply tell the story—and usually do just fine. But there are guidelines—actually, more like natural laws—which, like a lighthouse beacon, can serve to guide every teller around the shoals and eddies of storytelling distress. We call them natural laws because, like the law of gravity, they do not tell you what you should do (as a speed limit law does), but rather they describe the way the process naturally works. From these natural laws we derive insights and understandings that, like effective rules, guide us to more consistently successful storytelling. In the mid-1990s the National Storytelling Association spent two years crafting their definition of storytelling. In one sentence, they said: “Storytelling is the art of using language, vocalization, and/or physical movement and gesture to reveal the elements and images of a story to a specific, live audience.” That’s storytelling—and that’s what we all do every time we share a story with a friend, weave a story into a lecture, or try to entertain sixty fourth graders during a class visit to the library. You already do it. Asking, “Do you tell?” (or “Do I tell?”) is the wrong question. The question is as meaningless as asking, “Do you breathe?” We all tell stories—personal day-to-day stories—every day. You’ve told stories virtually every day since you were three years old. That’s what humans do. After quick reflection, many think that a better question to ask is, “Do you tell your stories well?” Occasionally, everyone does a lousy job of telling a story. It falls flat; it doesn’t work. We’ve all been cornered at an office party, a family function, or at a reunion by someone who droned through endless and painfully boring stories—Uncle Philbert’s trip to the Little League Hall of Fame, Aunt Penny’s mortification at being 30¢ short at the check out, a classmate’s intriguing life as the third assistant vice president of marketing. We’ve even done it ourselves. You Don’t Have to Get It Right to Get It Right 17 Again, it’s a meaningless question. We guarantee that every reader of this book at some time, in some place has told at least one delightfully mesmerizing, enchanting, totally effective story. Maybe it was only to three of your best friends or two coworkers at the water cooler. Perhaps you’ve felt really “on,” with your listeners eagerly hanging on every word, only a few times in your life. The point is, we guarantee it has happened. You have and can tell your stories well. As a community level storyteller, that’s all the proof you’ll ever need. What’s a better question to ask? Remember our cooking metaphor from Chapter 1? The right question to ask is: Am I trying to be picked for a theatrical TV cooking show that has to wow and entertain a large audience, or am I trying to provide a nutritious and flavorful meal that my family will enjoy? These two types of cooking have radically different mandates and expectations. Which are you trying to do with your storytelling? You’re going to be a community level storyteller, so the answer is: cook a nutritious and tasty meal for your listeners. That’s very different from becoming an Iron Chef on the Food channel. The trick for your kind of telling—though it’s not much of a trick—is simply to know your storytelling self: how you naturally learn, remember, and tell your own stories. YOU DON’T HAVE TO GET IT RIGHT TO GET IT RIGHT You see a professional teller and think that every gesture, every pause, every glance, word and tone were perfect. You think, “Wow. She got it right! That’s what storytelling is supposed to look like.” No. That’s what theatrical-main-stage-telling-in-front-of-a-largeaudience-of-strangers-in-a-formal-setting-by-that-teller is supposed to look like. If that same teller sat in a circle of ten first graders and told the same story in exactly the same way, it would not look or sound nearly as “perfect.” It wouldn’t even look appropriate. It would look and feel wrong. Why? That style of storytelling is appropriate for one kind of storyteller and one kind of event. Do you stop a friend in mid-story and refuse to listen any further because she didn’t get the words right? Do you feel cheated because you suspect she missed a word? We have yet to meet the person who could honestly answer yes to either question. 18 Chapter 3—“Okay, But Can I Really Do It?” Making Storytelling Practical and Doable Recent neurological research has shown that we humans remember the gist, not the specific wording, when we listen to a story. (See Appendix 2 for a summary of relevant research.) Every time neurologists conduct this test, subjects think they accurately remember the words. But the words they “remember” are largely their own creation and not in the original text. We humans remember the gist—the idea and the emotion and the meaning of a told story. Then we reinvent our own words to describe what we interpreted and remembered from the story. Getting a story “right” has to be measured by the images lodged in listeners’ minds and by listeners’ reactions to the story. Storytelling is not a verbatim recitation. It doesn’t require you to get the words right. It does require that you get the gist of the story right. Luckily, that’s much easier and more natural. The gist includes the main flow of events (the plot), the characters and their goals and struggles, and the emotional flow or mood of the story. That is what you are used to learning and telling for your own stories. “Getting it right” for you will mean just two things: (1) get the story characters and events (sequences) across to your listeners, and (2) tell it in such a way that your natural enthusiasm and passion for the story shines through in your telling. That kind of “getting it right” is much easier and more natural and is what your listeners need when you tell. HOW DO YOU NATURALLY LEARN, RECALL, AND TELL YOUR OWN STORIES? Sure, you tell stories—anecdotes, incidents, memories of your past, family stories. But you don’t consciously think about how you’ll tell those informal stories, or how you’ll word and structure them. You just tell them. It’s like many other unconscious, automatic things you do. You know how to tie shoelaces. But it would be extremely difficult to write down what you do with each thumb and finger in temporal sequential order to get those laces tied. You do it, but don’t consciously know how you do it. We tell stories the same way. We do it, but don’t consciously pause to think about how we do it. The difference is that if you suddenly doubt your ability to tie shoelaces you need only glance down at your feet to see proof. The problem is that we have no such ready source of proof to remind ourselves of our natural storytelling ability. What Listeners Really Need 19 The key there is that you do it, and, thus, that you know how to do it. You just have to become a bit more aware of what you already know and naturally do every day. Recall something that happened to you years ago—some memory, maybe some special event. What popped back up into your conscious mind? Typically, two things appear from your long-term memory when you recall a past event: sensory details (sights, sounds, smells, feels, or tastes) and a memory of the way you felt when it happened. That’s what we humans remember efficiently. Cognitive science research has repeatedly confirmed it. We record sensory data. And we record our emotional state to match those sensory impressions. As most tellers tell the story, something akin to a slide show flashes through their minds as image after image of these sensory details shines onto their mental screens. That’s how you typically tell your own stories. Nothing complicated; nothing needing extensive rehearsal or choreography. It’s simple, natural storytelling. Storytelling is supposed to be natural and fun. Telling stories is something we spontaneously burst into when we are having a good time with friends, family, or coworkers. With just a bit of forethought, the same core skills can carry you through more formal library telling.. So don’t try to force yourself to worry about them for other stories. WHAT LISTENERS REALLY NEED Have you ever thought about what listeners need—really need— from you when you tell a story? Have you ever wondered what your listeners don’t absolutely need from your stories? Probably not—and the stories worked just fine. But isn’t that a big part of storytelling—to give 20 Chapter 3—“Okay, But Can I Really Do It?” Making Storytelling Practical and Doable an audience what it needs—and just what it needs—so that they can conjure vivid, intriguing images in their minds? There is a game Kendall uses during workshops called What Makes It Real. It’s the storytelling version of To Tell the Truth. He has three people stand and tell a short story that they have discussed and practiced for only ninety seconds. One of them is telling the truth. (It happened to that person.) The other two claim it happened to them. They tell it as if it happened to them. But it didn’t. The audience must vote for which story they think is the real version of this story. It’s fun. But its value comes in discussing why people voted as they did. What made one story sound more real than the other two? All mention the same few factors that influenced their votes. What listeners say they need from the content of the story: • Appropriate and arresting details • Relevant, interesting characters • Intriguing story problem, tension,. No one has ever voted for a story because the teller got all the words right. No one has ever mentioned voting because of the story’s action (the sequence of events in the story). The Difference Between Reading and Telling 21 Look at the five items listed in the second half of the list. They all refer to listeners’ perceptions of how the teller told the story. The listed items refer not directly to what the teller did (use of gestures, facial expression, vocal pacing, etc.), but to the listeners’ interpretation of what the teller did. Really, they are all different expressions of a central need of every listener. If listeners believe that the teller believes in the story, then they, too, will believe. How do listeners decide if they think that a teller likes and is excited by his or her own story? By the way the teller said it. Does the teller appear confident, comfortable, and natural? Does the teller appear to be enjoying his or her own story? Again, this is good news. You are used to pouring your natural enthusiasm into the booktalks you present. You are already skilled in making your listeners see that you enjoy the books you present and describe. Those same skills will serve you well as you begin to tell stories. THE DIFFERENCE BETWEEN READING AND TELLING Librarians, particularly those working with young people, are skilled at reading aloud. They know well the difference between reading a story and listening to a storyteller tell a story. However, there are subtle differences between listening to a story being read and listening to a story being told. It is worthwhile to review these differences as you decide the role of storytelling in your presentation repertoire. 1. Reading places the book between you and your listeners. Even if you are a skilled reader, the book is still primary to your listeners: the images handed to them rather than created in their minds, the words predetermined. 2. The presence of the book limits your gestures and movements. 3. Reading preserves the author’s exact words. Storytelling does not. 4. Reading gives listeners exposure to exceptionally good writing and, in picture books, to exceptionally good illustration. 5. Reading does not require the reader to learn the story. 22 Chapter 3—“Okay, But Can I Really Do It?” Making Storytelling Practical and Doable 6. Shifting from reading to telling represents a change of media. Changing the media of delivery changes the expectations (conscious and unconscious) of the listener. As an example, Jack Hitt, a senior editor for Harpers magazine in the early 1990s, came to a national storytelling festival and, dazzled by the delight and power of storytelling, decided to print a series of stories in Harpers by modern storytellers. He put out a call for tellers who wrote their own stories to submit their favorites for his consideration. He told Kendall that he received 176 submissions (including four from Kendall). Yet he found one—just one—that he believed worked in print, even though he could see how most would be delightful and successful performance pieces. He read the stories out loud to coworkers, who agreed that they would love to hear and see the stories being told, but that they didn’t work coming off the printed page. Jack canceled the project. The stories were written and structured for live storytelling and could not survive a shift to the printed page—even when read aloud from that page. When you change media, you change the expectations of the listeners. Whether reading a story or telling it is right for you will vary from situation to situation and story to story. The more you try storytelling, the more you will expand the situations in which you feel comfortable telling as opposed to reading. We both believe that telling is a powerful and attractive choice for sharing story material. We also believe that you, as a trained member of the library staff, are better equipped and better able to successfully tell stories than you might think. We are completely convinced that, if you try telling stories, you’ll find both that your listeners will overwhelmingly enjoy and appreciate your telling and that your storytelling will be more successful than you imagined. HAPTER 4 C Choosing Stories That Will Work for You WHERE DO I START? Start with yourself. After all, you’re the one who will be telling the story. The conventional advice is to choose stories that you love. Strong words, and perhaps a bit romantic for some, but it makes sense, because some stories just seem to jump right into your arms and say, “It’s me! I’m the one you want.” We find it more accurate to say that you should choose stories that you can’t seem to forget, that stay with you, that you instinctively want to tell. What makes one story appealing, and not another, is an artistic mystery. Librarians are familiar with that sort of mystery, because we know that of the ten titles we might toss out to a patron, only one or two make the cut. 23 24 Chapter 4—Choosing Stories That Will Work for You WHICH STORIES TO START WITH? Consider getting used to the process of telling stories by telling the easiest stories of all—your own. Slide into it. Tell personal, relevant bits and stories between other material or to introduce other presentations. Experiment with personal stories to see what feels comfortable when you don’t have a book in your hand. You don’t have to start by formally telling your listeners that you’re going to tell a story. You don’t even have to tell complete stories. Start with the simple bits you might tell a friend or family member. Watch what happens as you slip these into your programs. What do you like about these story bits? To what kind of material do you naturally gravitate? What produces the best audience response for you.? In this way you can use your own stories to gain a better sense of what kinds of stories you want to tell and that will likely work well for you. It’s a nice, but not essential, guide to picking stories. This advice is time-tested and works well for most tellers. For most, but not for all. We recommend that you give it a try. We all come equipped with interesting moments that can be shaped into stories. However, if the mere thought of dragging your personal stories out for public display stabs icicles of fear into your heart, don’t force yourself. HOW TO PICK A STORY The language in stories gets some storytellers’ attention. Others like an unexpected ending. Still others enjoy telling stories from a specific culture, theme, or topic—about tricksters, for instance. As you start to collect and tell tales you may see some commonality between your selections. Storytellers develop an affinity for genre as well, and so become well known for tall tales or ghost stories. In the beginning try lots of stories on and see how they feel. As you develop your story ears and personal style of telling you may settle into a predictable series of stories. That is the time to shop around for new kinds of stories you haven’t tried before. Stretching your repertoire is good for your telling. What Is a Story? 25 The past thirty-five years have been busy in storytelling. Some have referred to this period as a storytelling renaissance. Maybe, although the stories were there all along. This upsurge has been responsible for the startling increase of storytelling performance, and the development of storytelling events and festivals, as well as classes. The blessing is that you have chosen to explore storytelling at a time rich in resources. New collections of tales, advice and how-to manuals, and even precise instruction about using stories within particular groups or settings are available for borrowing. You might as well take advantage of this largesse. There are reliable lists of stories for particular age groups and settings that do the work of searching for you. While nothing replaces the excitement of finding an unknown tale and making it your own, there is a lot to be said for starting with what is tried, true, and available as you begin your journey. You will find stories that are recommended so often it would be folly to ignore them, whether you end up using them or not. Most of the tales you choose will come to you through reading. The library has such a wealth of traditional tales that you can hardly exhaust it. But it is also important to listen, to train your ears to recognize a good story. The library’s audio collection can afford you the luxury of listening to gifted tellers while driving to work. That’s good company to keep.. WHAT IS A STORY? In the end, you’ll choose what pleases you. We know that. But will those stories please your listeners? No way to know for sure, except to try them out. We have found that information on the elements of a story sharpens your selection skills. A story is a unique and specific narrative that includes a clear plot, at least one character with which the listener can 26 Chapter 4—Choosing Stories That Will Work for You identify, sometimes an antagonist, a problem or conflict to be resolved, a resolution, and a satisfying ending. Stories containing these informational elements both satisfy, and resonate with, listeners. Traditional tales pass on wisdom, experience, information, and fact, and reinforce prevailing beliefs and values. New stories, fictional or familial, shape beliefs and values. Stories are the building blocks of knowledge, the foundation of collective memory and learning. Stories model effective use of language. Stories encourage empathy and connect us with the best and worst parts of humanity. Stories link past, present, and future and teach us the possible future consequences of our present actions, if we choose to heed them. There is much of interest and value that we could say about story structure. Entire books have been devoted to the subject. (See Haven, 2004 as an example.) Here, our focus is on telling stories, so we have moved our brief discussion of these structural elements into Appendix 1. It is a quick summary of these elements and of their function and contribution to a story and to listeners’ appreciation of a story. This appendix isn’t essential reading since you won’t, as a rule, create your own stories. But it will help you understand the stories you select and tell. It also serves as a handy reference tool to answer questions that might arise as you select, learn, and tell stories., and why, you’ve gone a long way toward making good choices. Each story has a structure.. As stories travel about, the sense of place becomes blurred and the story changes with every telling. In transit, stories may have picked up more descriptive material than they started with. That’s natural. But this Evaluating a Story 27 means that it is important to pay attention to the cultural markers within the story that seem to have survived the trip and to live with them for a while before changing them. You are, after all, borrowing something of value, and in doing so it will take on the coloration of your own telling, You cannot freeze the tale like a fly in amber, but you can become familiar enough with the cultural details to do them justice. With the rise of a professional class of storytellers has come a good deal of discussion of cultural appropriation. Should storytellers recount stories from cultures they don’t belong to? Who owns a story? What is the right thing to do? This is a complex topic, but we encourage library storytellers to tell what they wish. You are sharing literature in an oral form, and that’s part of your mission. Choose stories carefully, treat them with respect, tell them with joy. In doing so, you honor all traditions. EVALUATING A STORY As a summary, here are considerations that the collective experiences of many tellers have shown will guide you toward stories that will be easier for you to learn and more fun for you to tell: 1. Pick stories you like and that you can easily and clearly see in your mind. Did the story grab your interest and attention on first hearing (or reading)? Do you find yourself thinking about the story? Reliving it? Do you like the story well enough to want to learn it? 2. A story with fewer characters is easier. Every extra character adds extra work for you and makes the story more complicated to tell. 3. Short is easier. Short stories have less story to learn and remember. Even in two-minute quickies listeners will still want interesting characters with strong intents, danger-filled obstacles, struggles, and details. They just come faster and with less development in such a short story. 4. Pick stories with a clear plot (sequence of events). Stories with definite, sharp scene breaks are easier to learn than stories in one, continuous flowing sequence. 28 Chapter 4—Choosing Stories That Will Work for You 5. Can you clearly see the structural elements in this story? If you are unclear about them, your listeners will likely be unclear as well. 6. Stories with characters you clearly see and understand in your heart are easier for you to learn and tell. Do you clearly understand the characters’ feelings, reactions, goals, and motives? Would you feel comfortable portraying them to an audience? 7. Choose stories with language you don’t feel you have to repeat exactly as it appears in the book. Such stories are good candidates for story reading. Good stories to tell are ones that let you comfortably use your own natural vocabulary, phrasing, and manner of talking. 8. Consider stories your audience already knows (or have at least heard before). This is particularly true for young children. If they have heard the story before, they can help you tell it if you ever need or want their participation and assistance. 9. Pick stories that fit with your natural storytelling style and strengths. If, for example, the story is a raucous farce full of physical comedy and you are a quiet teller, this will be a challenge for you to tell. 10. Pick stories that will be appropriate for, relevant to, and interesting to your intended audience. Are these characters, the character information (traits) included in the story, the characters’ goals and motives, and the obstacles they face suited for the audience you will face? You may have already noticed that folktales tend to meet more of these criteria than do any other kinds of stories. You certainly don’t have to start with folktales. But they are a consistently reliable source of tellable tales. Above all else, start with something that feels easy, something enjoyable, something you like. You might want to start with a story you have often read aloud and already know. The more clearly you can see the story start-to-finish in your mind, the faster and easier it will be to learn. After you have told a few stories you picked because they were easy to learn and tell, you’ll have the telling experience under your belt to move on to broader story vistas. Let your early experience guide you. HAPTER 5 C Learning the Stories You Tell “LEARNING” YOUR OWN STORIES The best way to start is by doing. Grab a story you know fairly well and try telling it. Don’t make it a big production. Just tell it. See how it feels. See where you felt comfortable and strong. See where you felt less sure. Try it a few more times and see what happens. Did your telling change? Were you more confident or less? Did you forget parts? Was it fun? Whatever happened, pat yourself on the back. You’re well on the way now. Although it is more than likely that traditional material will be your mainstay, you can learn a lot by looking at the way you tell your own stories and those of your family. We’ve said that you already know what you’ll need to know to tell stories. So how does that apply to learning a story? Let’s start with your own stories. How do you learn stories that happen to you? 29 30 Chapter 5—Learning the Stories You Tell Don’t say, “I don’t have to learn them. They happened to me.” After the experience, you had to interpret the events and create a mental stream of information that you transferred to long-term storage (memory) with tags that you could access to recall the event. When you tell these personal stories, you pull something out of memory into your conscious brain that directs what you say and how you say it. Try it. Recall a story (or incident) that happened to you when you were a child. Quickly tell it to someone, anyone. What popped back into your mind? What did you remember? Most likely you remembered sights, sounds, smells, etc. (sensory images) and how you felt. Remember that from Chapter 3? Filing those impressions into your long-term memory is learning the story. Recalling them and converting them into language and gesture is remembering. You naturally do it all the time. That’s learning and remembering. KEEP IT SIMPLE Advice about learning stories is thick on the ground. Each book or article dutifully lists techniques and suggestions. The remarkable part is the spectrum. On one end are the simplest of suggestions, and on the other end are processes and approaches so labor intensive, so detailed that the reader droops in exhaustion before even beginning. The latter resemble the wrinkled instructions that come with the piece of furniture described as “some assembly needed.” You’d have to quit your day job to do this stuff. Librarians are busy, so let’s keep it simple. Try this list of suggestions that many storytellers agree are helpful. They are ubiquitous— because they mostly work. If they work for you and you find you successfully master the tales you want to tell, great! If not, we have included additional techniques—more extensive, but also tested, proven, and reliable—that will serve your needs. We have split the process of learning stories in half. This first half (Chapter 5) describes the process of initially bringing the story into your mind and heart so that you will be ready for the second half, learning Keep It Simple 31 how to get it back out again when you tell. That half is discussed in Chapter 7. Here is our list of simple learning ideas: 1. Don’t memorize the story—unless it’s a literary tale. (See Chapter 6.) Many hear that advice and nod in agreement, only to then secretly memorize the story for fear that they’ll never tell it if they don’t. The temptation to memorize is strong in many beginning tellers. Resist the urge! For those who need a bit more on this critical topic, we have included an expanded list or reasons not to memorize in Chapter 9. 2. If you are working from a written text, read it out loud to yourself. Use your ears, not just your eyes. These stories were meant to be heard and learned, as well as read and learned. 3. Read it enough times to be able to recall the plot with a fair bit of accuracy. The time this takes varies wildly. Some stories seem to float right into your mind. Some take a good long while. Don’t worry, these variations are to be expected. 4. Memorize the first thing you will say and the last thing you will say. We feel that if you can get in and get out, then you can wander around the middle of the story for a very long time before anyone turns off the lights. 5. Also learn the essential chants, songs, and phrases in the story. It’s not the story you memorize, just those few key names, repeated phrases, and musical bits that you have to say verbatim, just as written in your source material. It’s not hard; they are meant to be easy to remember. There shouldn’t be very many, and you’ll know them when you see them. “Not by the hair on my chinny-chin-chin” has to be said just that way. Substituting “Not by my whiskers” just doesn’t work. Learn these lines early and then reinforce this wording as you practice the story. Now a few things not to worry about while learning a story: 1. Don’t worry about getting the words right. We’ve said it before; we’ll say it again. When you listen to a storyteller, you don’t fret over whether he or she got the words right. You would never say to friends and family as you burst through 32 Chapter 5—Learning the Stories You Tell the front door with a juicy experience to share:” The greatest thing just happened to me! I can’t wait to tell you about it. But first I’m going into my room, write it down, and be sure I get the words right.” 2. Don’t fret over sequential order. Yes, you want to get the scene-by-scene, event-by-event order right when you tell. But don’t overly dwell on it while learning the story. And don’t hold back from telling it until you’re sure you have the sequence perfectly in mind. Think about personal stories you hear from friends. They jumble the sequence of events all the time, backfilling with flashbacks and forward jumps as new information pops into their heads. You have no trouble following each temporal and spatial jump through such stories. With telling and practice, the story will straighten itself out. 3. Don’t worry about gestures. You take your body wherever you go, and so it will be a part of your storytelling. You do not design your gestures when making other presentations, so don’t start now. Let gestures naturally evolve from your body and the story. 4. Don’t worry about how you sound. The voice you have is the voice you have. You can certainly develop more expression or fiddle around with your volume, pitch, or rate. But the voice you have and use every day has been, and will be, plenty good enough to get your stories across. You can go a long way on the suggestions above. That might just about do it. But maybe not. So we have added a list of additional approaches for those who find they need more. You need not use these. Indeed, some storytellers are very impatient with what they consider unnecessarily complicated approaches to a simple art form. If you are among them, avert your eyes. 1. Divide the story into manageable scenes. This is not difficult because stories tend to be episodic anyway. Some like to physically draw a line between scenes on a copy of their source material. Number and name the scenes and see if just saying each scene name helps you recall the places, images, and events of that scene. 2. Develop additional sensory details. Think of the Three Bears. You might be tempted to skip a detailed look at that kitchen. The scene will come alive for your listeners if you Toys to Play With 33 see that kitchen yourself. What kind of bowls do the bears use? Thick,. Create a storyboard and map the story on the board. Rough, stick figure pictures are just fine for these drawings. For some learners, just seeing the story this way is a good memory boost. 4. Get up and move that story. Walk around while you tell, trying on some of the characters. Use your body to animate them and the tale. You don’t have to use these postures and gestures when you tell. The idea here is to use your body to help fix the characters and story in your mind. 5. Ask yourself some questions about the characters. Do you know what makes them do what they do? What are they after in this story? Why is that goal important to them? Spend some time thinking about their places in the tale. 6. Create an emotional memory. As you learn each scene, ask yourself how each of the characters must be feeling. How would you be feeling? That emotional memory will stay with you and make it easier to recall the story and tell it with the appropriate feeling. TOYS TO PLAY WITH While touring Italy in the 1970s, Kendall met a door maker–door carver—a genuine Old World craftsman. He was rubbing a breathtakingly beautiful door relief with a polishing rag. Kendall asked if he was ready to hang the door. He said, no, it wasn’t finished. Kendall asked him when it would be finished (it looked perfect to Kendall). He shrugged and replied: “When they take it away.” Like polishing that door, tellers can work on their telling skills forever, after the telling is long over. There is always a pause to adjust, a 34 Chapter 5—Learning the Stories You Tell gesture to refine, a vocal inflection to improve. But these, as Gay, correctly calls them, are toys—stuff to spruce up the place. Toys are not essential to your successful telling. Fold them into the way you learn and tell stories when you’re ready. It’s a lot like frosting a cake—not worth doing unless you have a well-made cake underneath. But once your cake-making skills are dependable, playing with the frosting provides a good deal of pleasure. Don’t worry about playing with your performance toys until you’re comfortable with your telling and itching to find out what the storytelling tools at your disposal can do. Physical movement; vocal characterizations; physical characterizations; vocal tone, pace, pitch, etc.; gestures; and your physical relationship to the audience are among the toys you can develop both for your telling in general and for a particular story as you learn and practice the story. But only when you’re ready and it doesn’t feel like work. When you’re ready to add more variety and control into your telling, fine. Have at it! But don’t think for a minute that you must consider these when you start your telling. Your natural storytelling system will serve you just fine until then. Remember: you are sufficient as you are. HAPTER 6 C The Great Exception: Literary Tales We take it back. There is one kind of story you have to memorize: the literary tale. Literary stories have an original, known author, not a reteller or an adaptor. The stories are housed under fiction, not folklore. It can be confusing, since authors sometimes re-create folktales, making a new story. Sometimes the same author may simply retell the story, making him or her not author, but adaptor. Collections of literary stories to tell are well represented in the library, notably in the children’s section. You will find Eleanor Farjeon there, keeping company with Richard Kennedy, Rudyard Kipling, and several others. Picture books, too, are literary stories to tell—and not just to young children. Chris Van Allsburg’s work is a good example. 35 36 Chapter 6—The Great Exception: Literary Tales TELL IT OR READ IT You could read it rather than tell it. Of course, all of the limitations of reading presented in Chapter 4 still apply. However, many of you are trained, practiced, and skilled in reading. It comes easily to you. You might want to read these stories and save your learning and practicing time for stories that will be faster and easier to learn. But these are great stories, filled with wonder, magic, and the power to enthrall listeners—good reasons to consider telling literary tales. TELLING LITERARY STORIES Why do so many tellers put so much effort into memorizing? Because many of these stories are glorious and worth the trouble. The language is often evocative and compelling. They embody the same universality and timelessness found in traditional tales. Many of these stories are good yarns created by writers who are both story plotters and great wordsmiths. Recitation of literary stories appeals to many librarians. The stories are well written, with evocative language that is catnip to any wordsmith. They’ve got a lot going for them. Some storytellers have devoted themselves to literary stories, and made an artistic reputation from their interpretations. You may do that as well, although it is more likely that you will find just a few literary tales that you think are worth the effort. We do not recommend that you start your storytelling career with literary tales. These are stories to work up to, as your telling becomes a comfortable second nature. It does take work to master them. Good manners and good ethics dictate that you do your best to tell the story exactly as the author wrote it. Usually the language makes that a joyful task. For example, Kipling’s “Just So” stories have to be “just so.” It will not do to say: “Go down by this really, really big river, deep too, with lots of trees, a lot of different kinds . . . .” Not when the author wrote: “The Kolokolo Bird said, with a mournful cry: ‘Go to the banks of the great grey-green, greasy Limpopo River, all set about with fever-trees . . . ’.” If Telling Literary Stories 37 you choose to tell the story you have to tell it in Kipling’s own words. The words are in large part what distinguishes it. We know that literary stories were meant to be read, but can they be just as strong a tale when told? Perhaps so. Any number of literary collections began as stories told to family members for fun. These retain their oral antecedents and tell very well. But if you are unsure that the story is going to tell well, read it a few times to listeners and assess its potential. Literary stories have lots in common with traditional tales. There are characters riding the plot, there are problems, villains, the full complement of robust life going on. There are differences, however, and not just in the language. Traditional stories have a minimum of descriptive passages, evocative language, subplots, characters, and incidents. Literary tales tend to have most of these in spades, especially descriptive passages. While they are lovely to listen to for awhile, recounting one more landscape scene dotted with geese and featuring a croquet match can be trying. Make the literary tale pass the traditional tale test. Is it a good, strong story, or just an impressionist romp? We are loath to reinvent any wheel. We suggest you avail yourself first of the authors whose tales are often told. Start with Hans Christian Andersen, Richard Kennedy, or Carl Sandburg and use these worthies to measure new authors and their stories against. Story-length poems might also appeal to you. Every man we’ve ever known has gloried in “Casey at the Bat,” “The Cremation of Sam McGee,” or “The Rhyme of the Ancient Mariner.” James Whitcomb Riley’s “Little Orphant Annie” is similarly popular with those few women tellers who include poems in their repertoire. Ballads are the musical equivalent of literary tales. Many lend themselves to being told and have all the qualities you seek in a tellable literary tale. Finally, don’t overlook the collections of short stories, especially fantasy, and look at both Gary Paulsen and Ray Bradbury for excerpts as well as whole tales. Excerpts work too, so you may find yourself coming across a great passage to turn into a complete story. Tuck that one away for booktalking 38 Chapter 6—The Great Exception: Literary Tales LEARNING LITERARY TALES Oh yeah, the memorizing part. Well, we all know it is hard work and time-consuming. We also know you can do it, because we have. We have done a lot of forgetting, too. To minimize the pain and maximize the investment, we offer a hint when memorizing literary stories. When you learn a literary tale, you’ll naturally focus on memorizing the author’s words. But don’t just memorize the words. Every story is more than the words—including literary tales. You are used to infusing your story reading with inflection, energy, rhythm, pace variation, and emotional interpretation of the characters and situations. You do the same thing when you naturally tell your own stories. In the previous chapters we’ve disussed doing that when you learn and tell a story. However, memorizing a string of words is unnatural, and recalling that memorized stream requires focus and concentration. And that’s the problem. Often so much concentration and focus goes into remembering the words that none is left over to give energy and meaning to the telling of those words. As is true for all stories, you have to expressf the story in large part by the way you say it. As you learn the words of a literary tale, consider the mood and feeling of the story as well as the characters and their emotions, personality, intent, and struggles. Then the words can come alive for your listeners. It’s like the difference between reading a Shakespeare play and watching the same lines brought to life and vivid meaning by trained Shakespearean actors. Your job with a literary tale is both to learn the lines and to fill them with energy, meaning, and life by the way you tell them. It’s work, but these stories are worth it. HAPTER 7 C Playing with Practice WHY PRACTICE? By “practice” we mean telling the story out loud to live listeners before you tell it to your intended audience. Such practice telling of a story is not a requirement of successful storytelling; it’s a tool. It’s a valuable part of learning the story. After all, storytelling is telling. Many tellers (the two of us included) believe that telling a story is learning the story. Telling is the other half of learning—following after those activities presented in Chapter 5. But did you ever practice telling personal incidents before sharing them with family or friends? No. Of course not—or did you? Think back on your treasured family and personal stories. The first time you told the story of some new personal experience, it rarely came out as smoothly or as well-developed as during later tellings. The act of telling helped you edit and organize the story in your mind, create effective sequencing, cut out unnecessary digressions, and develop the relevant details you need to tell. Stories grow over time, and your telling of 39 40 Chapter 7—Playing with Practice them gains flow, pacing, and energy as you tell them over and over again. That’s practice. It’s a natural part of your story development and refinement process. Kendall often plays a game during workshops in which participants tell about a character or a past event three times, once to each of three different partners. He tells them that they will have one minute to tell their story each time. In truth, he gives them fifty seconds the first time, sixty seconds the second, and seventy-five seconds the third. Most participants can’t fill their first fifty-second telling. Most participants also run out of time on the third telling. Over three quick tellings, the story expands, develops, and takes on clearer interpretation and more vivid details. That’s practice. Really, practice is nothing unnatural or onerous. You automatically do it all the time. PLAY WITH PRACTICE Approach practice not as mandated work, as drudgery, but as play time. Play with the story as you practice it. Treat practice like trying on dress-up clothes. Experiment with different wording, different characterizations, different voices. No need to keep it if you don’t like it, but don’t be afraid to try. Play with the process as you would while creating an outfit from individual pieces and accessories. You’ll wind up with a better story and will be energized by the process of trying it on and making it fit with your style and flare. You also want the greatest bang for your story practice buck. Here are ideas to make your story practice more effective and efficient: 1. Before you tell it, tell about it. Describe what happens and to whom. See how far you get. Don’t worry about the actual wording or sequencing; just tell about it. Tell about the major characters as if you were describing a well-known friend. Feel free to include aspects of that character that you know don’t actually appear in the text of the story. No, this doesn’t mean that you’ll include this level of character detail (some would call it fluff) when you tell. But the better you can see the characters in your mind, the more completely they will Play with Practice 41 appear in your listeners’ minds when you present the words and details that are in the text of your story. 2. Try telling it right now. Yes, that’s what we mean: right now. Since we tend to set great store on doing things until they are done, we, also, need to tell stories before they’re ready to tell. And by the way, when is it ready to tell, anyway? 3. You don’t have to practice it all. Just work on small pieces of the story when you have a free moment but not enough time to run through the entire story. This will let you focus more attention on the fuzzy parts. 4. Mirror, mirror on the wall. Cover the mirror. Never practice a story in front of a mirror. Never. 5. Kinesthetic learning. Gesture and movement can be effective learning techniques. Many of us are kinesthetic learners: we learn best right through the skin, like kids. Try telling your story (privately) by moving around a lot, gesturing, dancing, and walking. Some people find this freeing and learn about the story that way. 6. Take a more detailed look around the story. We introduced this idea in Chapter 5 with the Three Bears’ kitchen. It won’t hurt to use this technique again in between your practice tellings. 7. Art as practice. Some tellers find it valuable to sketch a series of quick stick-figure drawings that tell their story. As does any other practice telling, this storyboard game helps cement the story in your mind. As a bonus, drawing each scene encourages you to fully picture the space and place you’ll tell about. 8. Tell the story before a small audience. This might mean the family (but only if they are really supportive), a few staff members, a friend or two, or your book club. We recommend that you not ask these groups for feedback or critique. They aren’t skilled story and performance critics. They’re your family and friends. Tell them the story, thank them for listening, and know that every time you tell it, you’ll become more comfortable and confident with your telling of this story. These tellings are valuable practice, but don’t treat them as more than that. 42 Chapter 7—Playing with Practice THE FINAL FOUR If we were to distill all the advice and techniques in Chapters 5 and 7 into four bottom-line things to remember as you learn and practice telling a story, they would be these: 1. The best way to learn stories is to tell stories. This sounds counterintuitive, but it is one of the most reliable tenets of storytelling. No matter how much you prepare, how polished your presentation skills, you don’t really create the story until you tell it to an intentional audience. Not off the cuff, not as practice, but as a planned, arranged telling. At the risk of sounding like we have spent too much time in California, we know that something happens when you tell; something surprising, something indefinable. Your well-prepared tale changes. The story dances across the bridge to your listeners and dances back to you. Your timing shifts, new words appear, the emphasis in a given scene subtly alters. You give one story and receive another one in return, changed but the same. 2. It doesn’t always feel right. (And that’s okay.) Most people are unaccustomed to telling stories in a formalized, intentional way. We know this because when we confess that, yes, we do tell stories for a living, we’re likely to hear: “That’s dying out, isn’t it? It’s too bad, huh?” But when Gay first began to tell, she remembers thinking, “This feels a little odd. Nice, but odd.” When she told a story it felt contrived and awkward at first, something like trying to learn the tango. So it may be for you, but don’t stop. Soldier on, for soon enough it will lose that “what am I doing here?” quality and you will ease into the confident, comfortable storyteller you were meant to be. 3. Seeing is . . . seeing. Nothing can convince fledgling tellers that storytelling works except doing it. No amount of witnessing and testifying to the power of storytelling is worth a fig. You have to do it to believe it. 4. Less is truly more. Remind yourself that this is a simple art form; it is not improved by making it more complicated. HAPTER 8 C Glorious Tellings You’ve chosen; you’ve learned; you’ve practiced. Only one thing left to do: tell. The most important advice anyone can give you now is to do what feels comfortable for you and appropriate for your audience, your library, and its available space. That having been said, here are some tips that represent the collective wisdom and experience of many tellers to help you decide what will work best for you. We speak here from personal experience. Both of us have made almost every mistake referenced in this chapter and know how easy it is to ignore these seemingly trivial concerns as you focus on your role as storyteller. Don’t be penny wise and pound foolish. You have poured your time and energy into preparing yourself to tell. A minor oversight in your planning for the space and audience could derail your efforts. 43 Let’s Start the Story 47 wearing, and how you sound. That way, when you do begin your listeners are ready to really listen. Discipline yourself to keep it short, since a long introduction usually signals the teller’s anxiety at beginning the tale. Opinions differ about announcing the title of the story. Even we differ. One of us likes to announce the title and hence plug the book; the other likes to talk a little bit about the story (very briefly), giving the audience a small taste or a bit of information about the origin of the tale, and then state the story’s title after the story is over. After this brief introduction, pause for just a moment to create a small space between your introduction and the beginning of the story. Keep Moving Now comes the good part: the story. Imagine that you and the story are standing there together. Step up together, and then you step back and let the story shine. Don’t worry about an occasional lapse. This is not a high wire act, and you won’t fall to your death if you miss something or other. The audience won’t turn on you like a pack of wolves. Slow down and pause a moment if you need to. It will come back. Yes, it will. The audience will neither mind nor remember the lapse. Slow Down Keep the story moving, but don’t be in a rush. Slow down. Let your listeners enter each scene and event. You have all the time in the world. Take it easy. Pause and take a breath. Pauses are amazingly effective and aren’t used as often as might be. They build anticipation and suspense and give listeners a moment to sink deeper into the story. They are your little friends, too, since they allow your mind to stay ahead of your mouth and keep you and your story dancing to the same tune. Your Partners Storytelling is an equal opportunity art form. You get to tell, and the audience gets to help you. In fact, the only thing you should be aware of while you tell-other than the story-is the audience. You can chart your course and monitor your story’s progress by watching the audience. Are they right there, with eyes on you, smiling at all the right places? Or are 48 Chapter 8—Glorious Tellings there subtle glances at their watches, shifting in their chairs? Let their reactions guide you and you will alter your pace, your details, your telling as necessary. It’s a wondrous gift to create the story through your audience’s guidance. Embrace it. There is one exception, though: very small listeners may be less able to control their bodies than you might wish. Don’t be too sure that this is a lack of interest. Grand Finale Whether you’ve told just one story, or a full evening of tales, don’t be in a hurry when it is over. Stay where you are when you are finished. Take a well-deserved bow, acknowledge the wild applause, and take your time before leaving. A race to the door is unseemly and unnerving, and it disrupts those moments when the story still lingers. DON’T MUDDY THE WATER Above all, do not apologize after you finish a story. Never. No matter what happened during the telling. It does not contribute to the listeners’ experience to hear what you forgot or regret or want to add. If they enjoyed the story and your telling, your post-performance disclaimer will diminish, even negate that enjoyment. Sure, there is the impulse to make it right. Resist it. Let the story be. You may be eager to take questions or make comments about the story or stories after you are finished. It’s a little like watching those outtakes or director’s cuts on a DVD, and that can be fun and instructive. But if you do it after you’ve finished a story you become the observer/critic not the storyteller, and that diminishes the experience. Let your listeners sit with the story. They don’t need a full précis of the experience. To seize this opportunity to comment about the story’s meaning, lessons, or importance to you is tantamount to announcing that the listeners’ own experience is shallow at best and must be augmented by your own. Another to resist! Keeping Track 49 CELEBRATE After your storytelling is over and the audience is gone, reserve a moment for private celebration. Celebrate what you and the audience have accomplished. Celebrate the success of your shared experience. There will always be time to review your experience later and give it your full and critical attention. Not now. You too need time to absorb the experience and to claim it. You’ve done a good job. Enjoy! KEEPING TRACK The last thing to do is also the first: good record keeping. Keep track of your stories and your storytelling. You will want to develop your own method for filing and retrieving stories. The usual decisions and approaches to information management apply, and no one is better than library staff at making them. We have two different methods, but both of us have a hard copy of each story we tell, as well as a database of the stories on our computers. You may decide to organize the traditional tales by title, culture, theme, or all three. You want the system to serve you well, and to allow you to grab the right story quickly when an unexpected occasion for telling arises. Many storytellers keep abbreviated forms of their stories for convenience as well—just a brief story outline with a beginning and ending sentence. This way you can tuck the ones you’ve chosen right into your requisite library tote and hit the road—school visit, community group, etc. You’re set for a fast review before you begin to tell. After the telling, it is time to reflect on the event. Both of us have a planning sheet for each appearance, and we use it to make notes about the audience’s response, the suitability of the stories we chose, and how well the telling went. You will do more of this in the beginning. As time goes on, your experience as a storyteller will make it a less elaborate exercise. The planning sheet is still useful even then, because it reminds you of what stories you’ve told to what group. It’s not a good day when you think your choices are new to your listeners only to have one comment, “I remember that story.” Now don’t misunderstand us, telling the same story to the same folks is no gaffe; we all like and need to hear tales again. You want to KNOW you’re doing it, that’s all. 50 Chapter 8—Glorious Tellings If you are most interested in traditional, literary, or historical tales, you will read many before you find one you know you will want to tell. “I’ve got to remember that one for the future,” you’ll say. Yes, you do. But you won’t. A cardinal rule is to make a copy of any story that attracts you, even if it’s a mild flirtation. You know how we learned to do this, and it’s a sad, bitter tale. We’re still looking for that one. Have you seen it? HAPTER 9 C First Aid While learning to ride a bicycle, every child earns a Band-Aid™ or two, gathers a few scrapes, and merits a bit of minor triage—the stuff of good stories, or at the least, badges of honor. Storytellers can similarly benefit from learning a few basic first aid techniques to gently and safely handle the bumps and scrapes they may encounter along the way. Don’t worry about fixing performance mishaps as you start your storytelling career. Tell some stories. See what works well for you and what feels comfortable. If a particular telling feels more like a train wreck than an accomplishment, move on and tell others. It’s all part of gaining your chops, as they say in the music business. When the period of picking yourself up and dusting yourself off has provided more than enough experience in scrubbing out, it will be worth your while to pick up a few tools and techniques to head off those looming disasters that shine like a pair of high-voltage headlights, threatening to freeze you in your tracks and strip your mental gears. 51 52 Chapter 9—First Aid TO MEMORIZE, OR NOT TO MEMORIZE? THAT IS THE QUESTION We said it earlier. Don’t memorize stories. But be honest. If you had to tell “The Three Little Pigs” tomorrow and held a copy of the story in your hands tonight, wouldn’t you want to read the story over and over, trying to memorize the words and plotting sequence? Memorizing is a deadly trap. It undercuts your storytelling in six important ways that almost guarantee you will not successfully, effectively tell the story: 1. Memorizing is difficult and time-consuming. Try it. See how long it takes you to memorize the words on this page. One page is a small part of a complete story. Memorizing is a frightfully slow and labor-intensive process. 2. The words of a memorized story don’t last. Once you have memorized this one page, see how well you remember it tomorrow. Can you still recite it in two days? In four? We doubt it. Then you’ll have to start all over again. 3. Memorizing a story makes it difficult to tell the story with enough energy, enthusiasm, and expression—key elements of your natural and successful storytelling. If your energy is diverted into recalling a string of words, not enough is left over to put into the telling of those words. 4. The specific words a teller says are not the most important source of information for listeners. Research shows that listeners internalize and remember the gist of a story, not your specific words. You don’t help or improve the listeners’ experience of the story by memorizing words. 5. Memorizing a string of words makes it more difficult for you to use your natural storytelling style. Your natural story-learning system is based on sensory images and feelings, not words. Memorizing words competes with the natural system you have developed and perfected over a lifetime of telling experience. 6. You will rarely convince yourself that you have successfully memorized a story—at least, not until you have told it a number of times, something you may never do. These doubts increase the probability that you will forget. The Great-Amazing-Never-Fail Safety Net 53 Don’t memorize a story. Memorizing is the rocky road straight to performance disasters. If you are going to tell it, relax and tell it. THE GREAT-AMAZING-NEVER-FAIL SAFETY NET What should you do if you forget part of the story while you’re telling? Even the Great Garibaldi Brothers, defying gravity as they soared high through the air of the Parisian big top in the late 1800s, had a safety net underneath them. Storytellers deserve no less. We can almost guarantee that, at regular intervals, you’ll forget while you tell. So what? No one will really care—besides you. The following elements of the Great-Amazing-Never-Fail Safety Net are designed to help you gracefully recover from your story slips. Go Ahead and Forget Yes, we mean it. No big deal. People do it all the time while telling stories. No teller seems to mind a momentary lapse when telling in an informal setting. You forget for a moment, pause, gather the story, and go on. Friends and family hardly notice and certainly aren’t critical. Sometimes you even say, “Let me think here for a second,” as you pause and mentally review the story. Treat your role as a community storyteller in the same way. Launch into your stories with confidence and enthusiasm. If you happen to forget for a moment, shrug, pause to regroup, and continue as the story reforms in your mind. Learn the Smile A reliable secret to successful recovery from performance mistakes is—simply—to not act as if you made a mistake. How do you do that? Learn the smile, the oops-I-goofed-but-I’m-not-going-to-let-you- see-it smile. Imagine the moment when you realize you’ve just made a mistake during your telling—forgotten to tell a piece of the story, missed one of those repeated phrases or rhymes, or simply forgotten what comes next. Yes, it will happen during your tellings. It happens to everyone. Don’t 54 Chapter 9—First Aid despair. Stop, pause, and buy time while you mentally regroup without looking like you made a mistake and are trying to regroup. Use the smile. What does it look like? Simple. First pause—stop talking. Second, smile and nod as if this were your favorite part of the story. Third, breathe, deep and slow. Take your time and remember that you are the only one who really knows what’s coming next. You’re also the only one who has any notion that what comes next has momentarily danced off your mental desk top. So relax and smile. It’s easy to buy five or more seconds. That’s a good long time for you to quiet your mind and let the story flow back in. Trust us, it will. You can, of course, extend the pause by repeating the last sentence you said and repeating the pause—smile, nod, breathe, and exhale. Tell About the Story We mentioned this as a story learning-technique. You can also use it when you tell. The first few times you tell a story, you won’t have convinced yourself yet that you really know the story. Some parts of the story remain annoyingly elusive. Knowing that these fuzzy sections are waiting to trip you up sometimes conspires to make you forget the parts you do know. Eliminate the stress. Don’t promise to tell the story, promise only that you’ll tell about the story. Literally. Tell your audience that you want to tell them about a new story. We have each said, and heard other tellers say, “I want to tell you about a new story I’m working on.” You have subtly changed the rules and the listeners’ expectations. Now launch into telling the story with all the enthusiasm you can muster—right up to the first section you are unsure of and reluctant to tell. Keep going if you can. There’s no mandate to stop. But if you feel at that moment that you must, then pause, smile, and say, “Isn’t that a wonderful beginning?” Then tell about this part you are afraid you won’t remember and won’t tell well. Provide only a summary plot bridge to keep your audience from getting lost. As soon as you’re past that part and are back to firmer story ground, pause, smile, and say, “Here is what happens next,” and launch back into storytelling again. You’ll switch back and forth between telling and telling about right up The Great-Amazing-Never-Fail Safety Net 55 to your big finish, telling only those parts of the story you are comfortable and confident telling with energy and enthusiasm. By not forcing yourself to muddle through the problematic sections, you never pull your energy and confidence out of the telling. When you tell, you tell with conviction. Listeners will be swept into the story, getting the best of your storytelling. When You Remember You Forgot You’re fully engaged in telling, when, with a jolt of terror, you realize that you’ve left out a whole section of the story. Relax. Every teller does that. Consider the informal stories you tell and hear. People forget parts all the time and, when they realize it, they merely stuff it back in wherever they are. We’re used to hearing jumbled, nonsequential storytellings. With guidance, your listeners are fully capable of reordering the story sequence in their heads without getting lost. The key to smoothly and successfully handling these moments is to neither look nor act as if you have done anything wrong (and that’s right; you haven’t). Don’t cringe, grimace, or mutter dire curses at yourself. That will worry your audience and they’ll leave the story to take care of you. First, use the smile. Pause, smile, breathe and nod, as if you were taking a moment to relish this part of the story. Then choose one of the following: “There’s something I haven’t told you yet . . . “ (not as a confession, but with intent) and tell them the part you earlier forgot. Perfectly true. You haven’t told them yet (because you forgot). Or say, “There’s something you need to know before we go on . . . .” Again true. (They need to know it now because you left it out earlier.) Or say, “Now, what we know but the wizard doesn’t is . . . .” What would this look like? Here’s an example. While telling the “Three Billy Goats Gruff,” you announce that, trip-trap, trip-trap, the first Billy Goat marches onto the fateful bridge—only to realize that you completely forgot to mention the troll. No biggie. Pause, smile, breathe, and say, “Of course, we can peer under that bridge, as the Billy Goat cannot. And underneath . . . .” There you are, smoothly transitioned into the omitted part. Then repeat “trip-trap, trip trap” and return to the Billy Goat starting his trip across the span. 56 Chapter 9—First Aid No one but you will suspect that the story didn’t come out the way you intended, and your confidence will take a great leap forward. Even if some folks sense you’ve just completed an adroit save, they will admire the save and forgive the lapse. What Comes Next . . . ? Probably the greatest public speaking fear is to suddenly realize you have no idea what to say next. Your mind goes blank. Your mouth opens, and nothing is there to come out. No problem. No damage has yet been done because no one but you knows you don’t remember what comes next, and you have plenty of time to recover. Again: Relax. Pause, smile, breathe deep and slow, and nod as if this were your favorite part of the story. Even chuckle softly to yourself. There’s a good ten seconds you can buy without having to say a word. Ten seconds is plenty of time for the story to return. If you remember, simply proceed with the story. They’ll never notice a thing. If the story hasn’t reappeared in your mind yet, you need to verbally tread water and hold your spot in the story. How? • Repeat the last line. Repeat it and again pause, nod, smile, and breathe. Repeat the line a third time as if it were a prophetic turning point of the story. Many tellers use this technique to add emphasis and power to specific words and moments. Blamm! There’s another fifteen seconds to reconstruct the story and where you are in it. It will come back. Yes, it will. • Describe the scene you are in. We rarely need more than a salient few sensory details we tellers have created and stored in our minds. Try wandering through these scenic details while your brain tries to figure out what happens next. It’s easy to buy another fifteen to twenty seconds with this description. You have now bought almost a minute—a lifetime when you’re on stage and plenty of time for you to conduct a systematic, orderly reconstruction of the story. • Ask them: “What do YOU think will happen next?” This is only used as a safety net. Listeners should not be required to pony up some opinion or answer as a bride price for hearing the story unless this is a planned participation story. Even if it’s an unfamiliar The Great-Amazing-Never-Fail Safety Net 57 story, they’ll likely be able to forecast the next part well enough to help you remember. If you need it, it’s nice to know that the audience is there and capable. • Be brutally honest. Tell them that you can’t remember the rest of the story. They may not believe you and may yell for you to finish it now. Still, you’re being honest, and it’s valuable for them to see that their favorite storyteller is fallible and that a storyteller can forget and still survive. The key to making this work is to confess you’ve lost your way in a manner that suggests that the sun will still rise on the morrow and you will live to tell again. The real points of the safety net are these: First, these are real, practical interventions that save most tellers most of the time. Second, as soon as you believe that you can extract yourself from a troublesome spot, you will. The trouble isn’t forgetting. We all do that. The trouble is the mind-freezing fear of forgetting. Third, the only real mistake you can make while telling a story is to act like you have made a mistake. Until you act that way, you haven’t. Last, and maybe most important, in reclaiming a story that has come unmoored: never, ever apologize and never, ever let your listeners see your anger or disappointment with yourself. If you indulge in either of those alarming responses, you take all of the energy in the room and place it where it doesn’t belong—on you and your struggle. The story, not you, should always hold center stage. HAPTER 10 C Owner’s Manual When you buy a new car, you want to go for a drive. You don’t want to sit in the showroom studying the owner’s manual. You want to know what the car can do. But eventually, you’ll want to thumb through that manual to see what those mysterious buttons, knobs, and dials are for. Same with storytelling. First tell some stories. Take your storytelling around the block a time or two. Kick the tires. Peek under the hood, but once you’re well acquainted you may want to see what your storytelling machine can do, how it can develop. What are the elements of your storytelling machine that you might want to explore? Simple: you use your body, hands, face, and, of course, your voice. First, a reality check. You employ these “toys” of yours each time you open your mouth, and you do so naturally, without affectation. Too much scrutiny can damage that ease and spontaneous style. We like to say it’s like trying to find the soul of a frog. It is a fruitless exercise, and it kills the frog. So take the following suggestions and exercises with a grain of salt and deal with them only if you are getting restless and want to take on some refinements, or if you are dissatisfied with some aspect of your telling. Should you be inclined toward endless perfecting—that uncomfortable state that makes us alter who we are—then give the rest of this chapter a big skip until you find it helpful, not prescriptive. 59 60 Chapter 10—Owner’s Manual You can find any number of books that explore the use, development, and control of each of these storytelling “toys.” Most of them can be found under storytelling, but not always. The confusion about what storytelling really IS extends to where one can find materials. Manuals and advice about body and voice can also be found under theater, acting, improvisation, and dance. Should you be particularly interested in one toy or another, you will have lots of resources to use. Here we offer only a brief survey, with a few quick activities to give you enough to go on in the meantime. In short, let’s play around. AN OPENING GAME How you say a story (the vocal tone, volume, pitch and speed you use combined with gestures, facial expressions, and physical movement) is important. Listeners gain lots of information from how you say it. In fact, HOW is a full and co-equal partner of WHAT. Community storytellers can consider this good news. You already know how to tell an effective story. Remember, you do it every time you present a book or entertain your family. You’ve been developing, testing, and rehearsing that skill all your life. You use and hone that skill every day in the library. Don’t believe that you are already highly skilled in the arts of how to tell a story? Here’s a quick game to prove to yourself just how good you are. Consider either of the following sentences/questions: YOU WANT ME TO GO THERE.? I’LL HAVE HER DOG DESTROYED.? The interesting thing about these is that you can place the emphasis on any of the words in either sentence and have it make sense. You can say them as either statements or as questions and make them make sense. Try it. Say one out loud to another person, placing the emphasis on the first word, say it as a statement, and make it sound real and natural. Then change the emphasis to the second word, and so forth. Awkward, isn’t it? Yet you do this expertly every time you open your mouth to talk. In fact, you always do more than this. You also have Voice 61 an attitude, or emotion, you effectively communicate along with sentence emphasis. Try it. Say the sentence again, and along with placing the emphasis on the chosen word, adopt one of these five emotional attitudes to express: sarcasm, joy, confusion, fear, or relief. Difficult, isn’t it? Yet you do this flawlessly every time you speak. In fact, you do more than this because you also incorporate physical movement and gestures into your speech. That skill you naturally possess is more than sufficient to meet the mandates of your storytelling. When you learn the sights, events, and emotions of a story, your natural oral skill will take over and express the story as effectively as it does your normal daily communications. VOICE Your voice carries the story. Unless you use sign language exclusively, or mime, you cannot tell a story without your voice. Most if us remember the first time or two that we heard our voices on tape. Memorable, wasn’t it? But WHO was it? What happened to that mellifluous, dulcet tone? Who put in the nasal whine, that reedy little wheeze? We hear our voices through the bones in our faces and heads, not just through our ears. The taped voice is a startling revelation. Tough truth: your voice is your voice. It may not be the one you would have chosen in The Catalogue of Beautiful Voices, but it is the one you have. It takes a great deal of money and a good voice specialist to change that with which you were born. Don’t waste your money, unless there is a diagnosable problem. In storytelling, the conviction and engagement with which you tell are important, not the trained quality of your voice. Some would say that voices betraying theatrical training are an impediment. It is said that President Lincoln was a consistently effective speaker even though his voice was regularly described as thin, high-pitched, and whiny. Having said that, it is still useful to explore the vocal toys you can use when you tell. Remember: the trick is to avoid any vocal techniques that make you feel self-conscious. All of us use these instinctively because the voice is a supple, responsive instrument. Taking a moment to review them will allow you to fool around. It might be fun. 62 Chapter 10—Owner’s Manual Here they are: rate, volume, and pitch. Each can be used to develop a character or to insert color and interest into your voice as you tell the tale. Rate We use rate each time we speak. Rate is how rapidly or slowly you speak. The relative speed of your delivery can suggest gender, emotional state, age, and more. Here’s an example you can try. Repeat this line adapted from Alfred Noyes’s romantic old poem “The Highwayman”: “The highwayman came riding, riding, riding, up to the old inn door.” Just say it in a conversational tone, not slow, not fast. Now we’re going to treat it as a piece of choral music and score it. The italicized words are to be said with speed, the regular text more slowly. Here we go: “The highwayman came riding, riding, riding, up to the old inn door.” Now try it in reverse: “The highwayman came riding, riding, riding, up to the old inn door.” Which one marries text to the rate? The second one, we think, but either way, the rate influences the words. You can also choose just one word to build up to and slow down from. In this example, it would be “UP”. Try that. Rate suggests age. We know that young children tend to speak more rapidly when there is something on their minds. Preschoolers’ words tumble over each other in a contest to get out first. When adults speak rapidly, it suggest several possible states: panic, alarm, argument, or excitement. Conversely, very slow, deliberate speech can be intimidating, suggesting menace or danger. It can also imply relaxation, deliberation, or ambivalence, among other things. You can give a very subtle reading of a character in your story just by using rate. Pitch Voices fall naturally into a wide range of pitch, from high to low. Very high voices are suggestive of young children (or a stereotypic voice for the elderly). Middle pitch implies a woman, and low pitches are often perceived as male. Hold on, though . . . women can have very. 66 Chapter 10—Owner’s Manual Here’s a simple exercise that lets you experiment with the look and feel of gestures. Remember, it’s just a game. Be extravagant with your gestures. Create a simple, three- or four-sentence story. Then create a specific gesture for every word in that story. One word, one gesture. One gesture, one word. Some words—articles and prepositions, for example— do not lend themselves to clear gestures. But you still must create a gesture for each and every word in the story. “Gestures,” of course, are not limited to hand movement and may include body movement and facial expression. Practice saying the story a time or two while performing each of the gestures you have created. Now “tell” the story to an audience. Let them know you will use gestures only. You will not speak any words in this performances of the story. Just for fun. This is not a game of charades, where a gesture is repeated until understood. Don’t encourage the audience to blurt out what they do, or do not, understand. You’ll tell the story at normal storytelling cadence, just as if you were actually telling the story with words. The audience watches in silence until the story is over. What do gestures effectively communicate? Action verbs (like jump), most emotions, direction, position, size, and shape. However, gestures often are better at portraying phrases or concepts than individual words. Also notice the energy and delight gestures carry. These stories are fun to watch even when you haven’t a clue what the story is about. It wasn’t the story that was so attractive; it was the gestures through which it was told. Gesture is a compelling toy. HAPTER 11 C Storytelling Extras A story that is well told, by an engaged storyteller, needs nothing more. Additions like props, participation, and such speak more to style than to necessity. We really do think that anyone can enjoy telling stories, even just at an informal level, but we do not think that anyone can effectively use each of these add-on performance toys. Talent isn’t the deciding factor. Each of these add-ons requires some stage management, and it must fit with your natural style and inclinations. It’s a question of attraction. Consider the list below as your own personal list of accessories. Clothing allows us to define our style, how we like to look, and these small additions to stories present the same opportunities for fun, for extending the story. They also present opportunities for unsuitable choices that can eclipse the story and the storyteller. To that end we have suggested some benefits and some deficits of each “accessory” listed., there may be times when it comes down to, “Oh, I just love it. That’s all.” And that’s fine too. 67 68 Chapter 11—Storytelling Extras FLANNELBOARDS The beloved, dark felt-covered board that holds the little felt figures is more likely to take a star turn in the preschool storytime where it is a reliable staple—most often used for children under six. The Plusses 1. An old story can become a new one by telling it with the addition of the board. “The Little Red Hen” becomes a fresh tale when wheat pops up for all to see. 2. Young listeners may be able to follow the narrative more easily with the visual cue of the felt pieces. As the pieces come and go and the story progresses, the watcher-listener can track the plot. For those struggling with language and learning, the little figures and pieces can help a lot. 3. It’s a good way for listeners to connect words with images. The porridge from Goldilocks is easy to define when the steaming pot is visible on the board. 4. It provides a simple change of pace. A program of flannelboard stories would be like a dinner of desserts: too visually rich and ultimately unappealing. Slipping just one into an otherwise conventional program adds the needed spice. 5. It may be a step for those who are uneasy about “putting the book down.” At least that’s what seems logical. We’re not sure. Sometimes the best way to overcome the fear of solo storytelling is to just do it. We do admit, thought, that this might be a good transitional step. Try telling familiar stories with the flannelboard and then telling the same ones alone. 1. Flannelboarding is unavoidably fussy. There is the putting pieces up and taking them down, smoothing them onto the board, picking them up, putting them aside. It seems fidgety and busy. The Minuses Props 69 2. The pieces always fall off. Well, almost always. That’s just the way it is. 3. Traffic management is difficult. It is difficult to tell, arrange the pieces, watch the listeners, etc. The teller unintentionally tends to direct listeners’ attention to the board more than one would like. 4. Kids may watch the board, not you. And that’s particularly regrettable because you’re the one in possession of the story. 5. Felt figures and objects are, by definition, static. Unlike puppets, they don’t move, and they aren’t three-dimensional like props. (This argues for simple, bold designs that are eye catching and colorful.) PROPS Props are objects used in the course of telling the story. This large class of objects includes folk toys, paper-folding, musical instruments, string tricks, artifacts, scarves, etc. It’s decision time. You’re going to tell “Little Red Riding Hood.”.” Consider the plusses and minuses. The Plusses 1. The prop may be essential or integral to the story. This is especially true if you are adapting a children’s picture book. Crictor, Tomi Ungerer’s delightful book, can be retold, but not without the Big Guy. Many storytellers have used the requisite six-foot snake puppet to good effect. Folding-paper 70 Chapter 11—Storytelling Extras tales obviously require, well, paper-folding. The same is true of stories featuring a musical instrument. Hard to do a good job without them. 2. The prop provides cultural exposure through appropriate objects. We know two fine California storytellers, Pam Brown and Martha Shogren, who are adept at using objects that are culturally relevant to the stories they choose. We particularly enjoy Pam’s use of origami and small puppets. Martha doesn’t use props during the tales, but afterward brings out a beautiful object from the culture to show the listeners. 3. The prop provides a visual clue or enhancement. A prop may also be important, if not precisely necessary, if an unfamiliar object is used in the tale. This is most likely when the tale refers to a tool or activity like spinning. Showing the object can employ an efficient visual shorthand when the explanation might weigh down the narrative. 4. Props can be simply magical. It’s true. Beautiful, unusual and evocative objects cast their own spell. We all like to see cool stuff. As long as it contributes to the story and doesn’t upstage it, go ahead. Have some fun. 5. A musical instrument can add another artistic dimension. An instrument can provide background, sound effects, melody or accompaniment for a song that appears in the story. 6. Props add some modest razzle-dazzle. Nothing wrong with a little glitz on occasion. Make that on rare occasions. 7. They’re fun. Sometimes, props are just fun. The right props woven into the right story can be an extra delight for your listeners. Just make sure the story can tolerate the disruption of the props and that the props you use will have the desired effect. The Minuses 1. Who’s running this story anyway? Using anything except your voice and body can be a juggling act. Will your manipulation of the stuff be a distraction that will distance you and the listeners from the telling? Are they worried that you’ll drop one of the balls? Props 71 2. Does the prop enhance or detract from the story? Is this a better story with the prop? Do you really need it? Creating stories for use in paper-folding, paper-cutting, string tricks, and other simple crafts is a busy little industry. The problem is that the stories can take a back seat to the activity. A story created just to be a showcase for the skill or handicraft lacks the depth and timelessness of a traditional tale. Be sure the story you choose is sturdy enough to be worth telling, not just an afterthought. 3. Props can be a distraction, and interfere with listeners. This is an oral art form. Enough said. Alright, not quite enough. As you brandish a new prop, listeners are pulled out of the story’s images to stare at this thing you hold. Where’d you get it? How’d you make it? Is that really what you want? 4. Listeners do not need props very often. The whole idea of storytelling is that listeners imagine the story inside their heads. The more props you pull out, the more you keep them from their appointed task. 5. This stuff takes time. The time you may spend in the local import store, or in sewing, polishing, repairing, and cutting, could be spent working on the story. Make It Work for You 1. Try telling the story without the prop. Was anything missing? Yes? Okay, add it to the tale. 2. Decide where the prop belongs. If it is necessary to the audience’s understanding of the story, then show it in the beginning, with a bit of introduction. Don’t rush. Give listeners a chance to look it over. If it isn’t essential to the tale, consider showing it after the story is finished. 3. Rehearse using the prop to minimize the price that the listeners pay for its inclusion. 4. Leave it out, or put it away? If you will use a prop periodically (like a musical instrument) leave it out. If it is one time only, well then . . . decide. But decide in advance. Do you want listeners to focus on the prop after you’ve used it? Will it be awkward or time-consuming to stuff it away? Will it get in 72 Chapter 11—Storytelling Extras your way as you tell the rest of the story? Use the prop during a practice telling and see what will be best for you and your listeners. 5. Don’t oversell the prop. It doesn’t matter that you bartered for it on your fabulous trip to the Falklands, or that you spent twenty-five hours making it from crushed egg cartons. While you tell a story, the story must be the central focus. 6. Less is more. How many props is too many? Answer: only you know. We think that, as is true for so many other aspects of storytelling, less is definitely more. COSTUMES A costume is clothing that is in contrast to your regular garments. Costumes can be period pieces or a collection of garments and accessories that are eye catching and festive. The Plusses 1. Costumes reveal character and period. The historical costume can do some of the telling for you. By looking at you, the audience sees the period and the class the clothing implies. When you dress as a commoner, no one will mistake you for the king, for instance. 2. Costumes make for a fancy occasion. Costumes are crowd pleasers. Those who tell stories outside often dress to attract an audience. Festive, eye-catching clothing can set a mood and theme for your presentation. 3. Costumes set the stage for stories told in the first person. The most obvious application is for historical stories, where the eyewitness teller recounts his or her experience. Places like Colonial Williamsburg have known this for decades. Fantasy has a place also, since the requisite princess can dress for success, too. 4. Costumes teach. Most folks under sixty have rarely, if ever, seen spats. Wearing a pair can educate as well as delight the audience. Costumes 73 The Minuses 1. You’re stuck. Costumes are simply props you don’t have the luxury of setting aside. You cannot change your character easily, and cannot change the period at all. 2. Glad rags may mislead your audience. If you dress in some get-up that features eye-catching, buffoonish fabrics and jewelry, you risk becoming “Carbuncle the Clown” or some other generic children’s performer—but without the clown act or magic tricks. 3. You can’t switch gears. You are tied to the period of the costume. The alluring princess dress you donned for the first story means you’re stuck in the realm. The alternative is one we have both seen: the storyteller races to a hastily arranged sheet to perform a genteel version of “take it all off” to get to that next story. Not a pretty picture. 4. It seemed like a good idea. Library staff is prone to costuming during programs for holidays like Halloween. Depending upon the site, one will find everyone on the staff in full ghoulish garb. It can be fun. It can also be full of effort and uncomfortable. 5. You’ll focus on the costume. If you wear a rare, historical, or valuable costume, you’ll be worried about getting it dirty, mucked up with sticky fingerprints, or torn during a dramatic gesture. Your focus on protecting and presenting the costume pulls you away from your primary mission: telling the story. Make It Work for You 1. Take the most reasonable approach. Don’t fight the costume. Choose a story that matches the costume and vice versa: a first person story from the period. 2. Don’t actually wear it. Character costumes are almost as dramatic and effective if you bring them in on a hanger. Then they become props. 3. Create a “storytelling costume.” Use the strengths of costuming and develop your own garment or accessory that sig- 74 Chapter 11—Storytelling Extras nals, “It’s me! The Storyteller!” Many librarian- and teachertellers have a hat, a vest, a coat, an apron, or a shawl that they wear whenever they tell stories and only when they tell. It’s quite useful if you are usually dressed in the “Librarian Uniform” that says you’re all business. Use it to give a visual cue to your listeners: This is it; we’re telling stories now. PUPPETS Puppets include finger puppets, hand puppets, marionettes, and dolls used as talking, moving, acting characters during a story. The Plusses 1. Puppets are REAL for young listeners. They are more real than you are during the story. Children will interact with the puppet completely. 2. Puppets can misbehave extravagantly during a story without causing mayhem among listeners. 3. You can have a conversation with your puppet. This affords you an opportunity to talk to the puppet and thus have two participants telling the story. That’s fun for little kids. 4. Puppets can act as the court fool. Our friend Willy Claflin, a brilliant puppeteer and very witty fellow, has as many followers among adults as he has among children. The antics of Maynard Moose, his puppet alter ego, make small ones giggle, and his comments on the body politic make adults laugh as well. The court fool could speak the truth to the king with wit and tomfoolery. A puppet can do the same, with you as straight man. 5. You can reveal another side of yourself. Mister Rogers was a famously shy man who could become someone else with a puppet companion. So can you. 6. Puppets can be just a delight. When used well and made into an integral part of storytelling, puppets can be a crowd-pleasing joy. Puppets cross simple storytelling with Puppets 75 scripted play making, but if that appeals, puppets can be an effective addition. The Minuses 1. Puppets always upstage the handler. Always. Puppets are the ultimate prop. They always take the audience. Always. Extract a skuzzy, featureless finger puppet of indeterminate age, genus, and phylum, push it onto your finger, and that puppet instantly becomes real and important. The puppet IS the story. 2. You lose one of your hands. Your hand is no longer yours. It belongs to the puppet. 3. Puppets are REAL for young listeners. Although puppets are irresistible to many small children, conversely, some are at best puzzled, at worst genuinely frightened, of the bewitching little characters. 4. Some dexterity is required. Not much, but some. If you choose a simple hand puppet whose movements are limited, you can get away with not doing very much. Complex puppets require complex movements. 5. You have to make puppets to fit your story. Not just any puppet will do for a story. The puppet has to match the character it represents. That means that you’ll have to either custom make (or buy) your puppets, or revise the story so that puppet and story match. 6. Puppets mandate extra practice. Puppets introduce two new aspects of your story that need practice: your general puppet skills and the choreography for what your puppet is going to do while you tell the story. This means lots of extra practice with this upstart attention grabber after you have learned the story. The puppet is depending on you to make it move and act as it should—every moment, start to finish of the story. But those who have watched good puppet shows know the effort can be well worth it. 76 Chapter 11—Storytelling Extras Make It Work for You 1. Above all, keep it simple. Let the puppet do the work and you take a bemused back seat. 2. Make it a good fit. Consider puppets only if you like them enough to shoulder the extra work, if they fit with your natural storytelling style, and if they fit well with your story. AUDIENCE PARTICIPATION Audience participation uses the audience to contribute to the story. That inclusion may be either planned or improvised on your part. You may rehearse the audience on their part(s) or not. It may include vocal or physical responses or both. These responses can include chants, repeated phrases, songs, gestures, movements, and, sometimes, guesses and opinions. Audience participation runs the gamut from the subtle to the outrageous. Some tellers place specific activities along this continuum according to the size and complexity of the audience’s participation, some by the amount of managerial control effort the teller must expend. We have broken our discussion of audience participation in half, using as the dividing line whether you physically bring audience members up on stage with you (a “Cast of Thousands” story), or do not. This first part covers audience participation when you keep them out in the audience. The Plusses 1. Participation works. It is built into scores of stories. That’s because it works. It works to assist listeners in remembering the story through chants, songs, rhymes, and movements. Just as we all make up mnemonics to remember a parking place, a grocery list, Henry VIII’s wives, so participation helps listeners keep the story. 2. Participation is an unrivaled way to engage young children. As all storytellers know, when you ask a child to “help” with a story, you don’t have to ask twice. Kids are ready. With participation, the storyteller gathers the energy and high spirits of young listeners and directs it toward telling the story together. Audience Participation 77 3. It is an equal opportunity device. Participation does not require anything extra. Anyone can do it. 4. It’s a good change of pace. One participation story can vary the offerings, giving a nice change of pace in a longer program. 5. It’s fun. 6. Many people are kinesthetic learners. Vocal and physical roles help them retain the story. 1. It’s easy to overuse this technique. One or two participation stories give a pleasing texture to a program, but more amp up the audience and feed the cultural assumption that children, in particular, always, always need those colored lights. 2. Assigned, rehearsed participation can pull listeners out of the story. The excitement of being a contributing “cast member” can upstage story content. Kendall conducted a study that showed that children tend to remember their participation and not the story. (See “Note” at the end of the chapter for a description of the study.) 3. Traffic management is a necessary component. A roomful of children can quickly get out of control when asked to participate. This technique requires some forethought. How will you signal the beginning of the participation? How will you ensure that it will end? 4. You can oversell the idea. Your instructions for how and when to participate should be brief, simple, and fast. There is no need to rehearse, to review crowd control, and to conduct. Simply repeat what you wish listeners’ to do, and then move on. Children, especially, are very good contextual learners and will catch on. If you teach the movement or vocals until everyone is well rehearsed and compliant, your performance will be over and the kids will be at recess. Relax. 5. Participation engages the listener, but nothing replaces a quiet, compelling story from the storyteller alone. The Minuses 78 Chapter 11—Storytelling Extras Make It Work for You 1. Different levels, different guidelines. We think it’s best to split the way you think of audience participation into three separate situations and approach each differently. • Situation 1: Encourage seemingly spontaneous participation. When audience members spontaneously, verbally interact with story situations or call out to story characters, they participate in the story without being pulled out of their story images. Even pre-teens will spontaneously chime in with repeated lines in a story—if the teller sets it up and encourages that participation. Set it up by how you say key repeated lines. Add fixed gestures and body movements to reinforce the pattern of those lines. Say the lines slowly and rhythmically while smiling and nodding at the audience. By the second or third appearance of these lines, the audience will jump in all on their own. You can also tell stories the audience knows and have a character stumble over well-known lines. Younger audiences will always spontaneously dive in to make sure the characters get it right. What does that look like? Consider the wolf’s huffing, puffing, and blowing line. You know the one. Say it with a slow, rhythmic head nod and rolls of your hands to encourage participation. “I’ll huff . . . and I’ll Puff . . . and I’ll . . .” (pause, pause). As you expectantly arch your brows, every child in the room will spontaneously join in to finish the line. Alternately, you could have your wolf forget or stumble over the line. “And I’ll, uhh . . . blow your house up. . . In? . . . Over? . . . ” Again, every child will leap to the rescue to verbally straighten out you, the momentarily befuddled wolf. You may also pause during the story and, as either a story character or the story narrator, ask some story-related question of the audience. It’s best if the question is really rhetorical and your continuation of the story doesn’t depend on their answer. This unrehearsed interaction as part of the story is delightful for younger audiences, and—as is true at classic melodrama theater—fun even for adults. Audience Participation 79 • Situation 2: Assigned, prerehearsed participation. At this level, you will assign roles to part or all of the audience, but roles that keep them in their seats. Assign and rehearse audience lines only when you want the experience of participation to be the focus. Make sure that the lines (or gestures) you force them to repeatedly say will be fun, memorable, and worth their while. Be sure the time and effort to teach them their lines and the extra work to manage and control their participation will be worth it. This activity is best for preschool and primary ages. But keep their lines and gestures short. While telling the Jewish folktale “It Could Always Be Worse,” (see the excellent version by Harve Zemach and Margot Zemach), you could assign different sections of the audience to cluck, moo, or grunt to represent the various groups of animals that are, one by one, stuffed into the house. Questions to consider: How will you cue them to start? More important, how will you cue them to stop? Rehearse your control plan as much as you do their assigned lines. • Situation 3: Take the seat belts off. Adding movements to the audience’s assigned participation lets them rise up out of their seats (or up off the floor) and flop about the room like beached mackerel. It’s chaotic fun for them, but a potential nightmare for you. It is easy to lose control of the audience, and difficult (at best) to regain it. Don’t tread into these mine-filled waters unless you are sure your management plan will keep you in control. Our advice is to use this type of participation sparingly and only with young children. 2. Make it easy. You can encourage, even plan for, this kind of participation. You can repeat the desired phrase or movement slowly, smiling all the while, slowing down your delivery. By the second or third try the audience members jump right in all on their own. 3. Watch for a good opportunity. Sometimes during the story an opportunity for participation just jumps right out. The audience usually leads the way, and you can take advantage of it. This technique is tailor-made for spontaneity and improvisation. 80 Chapter 11—Storytelling Extras “CAST OF THOUSANDS” STORIES These are stories in which you bring audience members up on stage to help you tell the story. “Cast of Thousands” stories combine participation with theater. Audience members are recruited on the spot to take part in the story that is “performed” before the rest of the listeners. Not extensively rehearsed, this technique takes advantage of the moment and uses a well-prepared story with several characters and a simple plot line. The Plusses 1. This is chaotic fun. A natural for family programs, this is wild. Kids and adults can be recruited willy-nilly and pressed into service. There is fun in the transformation and in the “onstage” negotiations and arrangements. Best for a large crowd. 2. This can showcase an old story and make it new. With audience members transformed into pigs, elves, or the Bremen Town Musicians, the story becomes new. 3. This creates opportunities for spontaneous story making. The very act of hauling folks out of the audience signals that this isn’t going to be rehearsed. Give folks permission to ad lib a bit and add to their characters. Part of the pleasure is seeing what the cast can come up with. The Minuses 1. It’s a minefield. So be fully prepared before attempting this one. It might not work or that it will be difficult to control. Some library storytellers are more comfortable with this notion than are others. Let your temperament be your guide. 2. It’s all about traffic management. You are going to recruit, manage, and coax the spontaneous cast. You’re not really the storyteller this time. 3. Rejection is hard to take. You cannot choose everyone, right? If you do no one will be watching. It is hard on the kids who don’t make the cut. 4. There’s a fair amount of advance work. You will need to make a script of the story for yourself, create simple lines for Note 81 the characters, and quickly rehearse them. Adapting this way can take time. Make It Work for You 1. Do your homework. Make sure you have chosen a very simple story with lots of possible parts. 2. Ask for help. Grab an extra staff person, or an adult from the crowd to help line folks up, get them off, or whisper the missing line. 3. Use sound effects. Braying donkeys and clucking chickens make it possible for even the youngest to shine. And the flock can be as large or as small as is useful. 4. Be sure to recruit adults. That is, unless it is an all-kid group. If so, then look around carefully to be sure you choose cooperative volunteers from all ages and all cultures represented. This can mean fast footwork, but a group of kids in the library usually means a visit from a class. A school visit means staff are present. Good. Let the teacher help you select. 5. Go crazy. Might as well use some small props for the characters. Try some little half-masks for each animal. NOTE In an unpublished study done in 2000 in six Las Vegas schools, Kendall told one participation story and one nonparticipation story to six in-school, primary grade audiences (total audience just over 1,400). All stories were original stories. None were familiar to the various audiences. He varied both the stories and the order in which they were told. He asked the teachers not to discuss the stories with their students, to wait one day, and to then ask students, without discussion, to draw one picture from one of the two stories (nominally as part of a thank-you letter). 82 Chapter 11—Storytelling Extras Over one-third of the teachers followed through as asked. Of the 420 pictures Kendall received, three-quarters were from the story in which students did not have assigned participation lines. A third of the pictures from the participation stories were of the children saying their lines. When they were given assigned participation lines, their memory of their participation overshadowed their memory of the story. HAPTER 12 C Let the Stories Roll! Now that you are on the way to becoming a seasoned storyteller, it is time to develop more ways to incorporate stories into your work and into the library’s programs. Doing so will keep you fresh and your enthusiasm intact. The suggestions below are just that, suggestions. We know you’ll develop better ones because you know your system and its available resources. That includes the level of interest and support you may anticipate from your administration. If you are fortunate enough to have an administrator who nudged YOU into storytelling—great, thank your lucky stars. The next best thing is someone who is neither for nor against, someone who allows you to make a persuasive case for your plans. Let’s hope one of these two situations reflects yours. If not, let’s hope no one will discourage you, since changing negative attitudes always adds a layer of work. Choose what pleases you; ignore what doesn’t apply. 83 84 Chapter 12—Let the Stories Roll! WHERE TO START Start with simple, low-cost activities within your own system, or single library. Host a monthly story-sharing meeting for interested staff. Encourage folks to tell, but don’t make it mandatory, so that they can come and listen until they are emboldened to try. This kind of thing should be open to everyone, not just librarians. It is wise to have a rotating host, so that you’re not always the one ripping open the bags of cookies and heating the water for the chaste herbal teas. If your own library is too small to support such an undertaking, then seek out staff in neighboring libraries to join you. Set up a simple listserv to encourage story swapping, reviews of stories told, and collections used. It is particularly useful to get war stories, that is, accounts of what worked and what didn’t. This should be anecdotal and easygoing, with the emphasis on beginners. No lecturing allowed. Expand the story-swapping group if yours works well. You can put a notice in the usual outlets and invite the public in. Since it will be ongoing, say every month, then a modest success suffices in the beginning. This is different from a library program of themed story collecting such as reminiscences from World War II (see below). This is simply a story-sharing group for listeners and tellers alike. You will likely encounter the usual response: “What exactly is this?” Be prepared to answer that question by having some stories of your own to share and thus demonstrate “what it is.” SPECIAL PROGRAMS You can formalize the idea of story sharing by hosting a program for the public (include staff) that is organized around a single sort of story or idea (theme). Here are some simple ones: stories from veterans of wars, collection of local history tales, grandchildren soliciting stories from grandparents, recipes and the stories behind them (with the possibility of publishing the findings.) You can reinforce the importance of traditional tales by developing a theme and then presenting some related folktales that you tell. More Ambitious Ideas 85 This is a little more difficult than eliciting personal or family tales, but worth doing. Your community’s culture and identity will suggest possibilities. Most of these programs are tailor-made for collaboration with other organizations. The local quilting group can partner with needle tales or reminiscences; the local historian or curator can help with stories about your community or region. You’ll think of others. Storytelling festival organizers are often interested in these partnerships. Jim May, a fine storyteller from Illinois, encouraged stories from local seniors by presenting the opportunity at his local library. MORE AMBITIOUS IDEAS 1. Begin with a bang. This one is designed to get your colleagues to buy in at the beginning. Hire a really good storytelling educator for a one-time-only workshop for staff. (You could invite the public as well, of course.) We have found that it is more effective to allot a long morning at least. We know this idea presents all sorts of issues, chief among them a scheduling challenge. Still, we think the effort is worth it. Administrative support and encouragement are essential here. The library director needs to get behind this and attend. The benefits are considerable. The whole staff sees firsthand what storytelling is, how much fun it can be, and how affecting the tales are for everyone. Staff members get to practice in a safe environment, and everyone is an equal partner. Libraries are, as we librarians know all too well, hierarchical by nature. For instance, a young, inexperienced librarian can find herself in charge of a staff with years of experience. In this workshop everyone has stories to tell. 2. Storytelling kickoff. While a day of learning is inherently valuable, you can extend the value by using the workshop day as a kickoff for storytelling in your library. This requires work, coordination, brainstorming, cross-departmental cooperation, and good PR. That’s lots of work. Mounting this kind of programmatic machine suggests that you might as well offer a lot of opportunities for telling and listening, since the work will be no more if you do. Here are some ideas: 86 Chapter 12—Let the Stories Roll! • Invite groups to tell their particular sorts of tales. The Tejas Storytelling Festival decided to invite local lawyers from Denton, Texas, to the festival to tell their stories. It was a rousing success, and certainly one of the best-attended events of the weekend. Lawyers use stories all the time, so it wasn’t difficult to find some to step up. • Send library-storytellers out into the community to offer short programs of tales. The traditional clubs and service organizations are always looking for speakers, so contact the Rotary, the Chamber of Commerce, etc. Use these or similar ideas as organizing themes during your storytelling month, or week . . . or even day. 3. Produce your own library storytelling festival. There are several models, including the King County Library System Storyfest International. That one presents professional storytellers, but you can also use staff and community storytellers to good effect. The renaissance of storytelling has produced festivals and events and a related wealth of information about planning storytelling events. You can also ring up the nearest storytelling festival’s director and get some good advice. This project requires lots of work, make no mistake. It also requires a budget and administrative support. You can combine an invited teller or two with community storytelling and workshops. Libraries have partnered with arts organizations to produce many storytelling events. A quick Web search or a call to the National Storytelling Network (NSN) will yield lots of ideas, referrals, information, and examples. If you decide to hire a professional teller, then get your money’s worth. Hustle these folks out into the community, and offer them as motivational speakers to city councils, clubs, and groups. Of course, once you’ve got a trained, motivated, confident group of staff storytellers, they can do it as well. Keep on Keeping On 87 KEEP ON KEEPING ON Consider treating the nearest storytelling festival as an opportunity for an in-service training for your staff. It requires a budget for registration, but that is money well spent if staff members come back revved up and ready to tell. Set up a professional collection of tales, sourcebooks, and guides for staff to use. Yes, this will create a small dent in the collection development budget, but an enterprise is only as good as its tools. The most important investment is a philosophical one. If you can reach system consensus about the importance of storytelling as a part of library service, then it is easier to create opportunities for professional development, programmatic applications, and a broad, flexible definition. Do what libraries are already good at doing: finding the answer or the resource. Librarians who are knowledgeable about storytelling and stories—or interested in becoming so—can act as a very effective resource. Bibliographic support for storytelling can be a make-or-break activity. When a staff storyteller can quickly put her finger on a brief list of stories to choose from, the chances are that she will find a good one, learn it, and tell it with dispatch. Interested staff can collaborate on lists of stories that work for holidays, outreach presentations, particular ages or themes, really any sort of occasion. Of course, there are books that have anticipated this need, but we have a less formal approach in mind. Just a quick list of, say, fifteen to twenty stories at the ready that are easy to get to and easy to use. Remember to include several very short stories (one to three minutes long). A REALLY big idea is to commit to storytelling as an essential library service by identifying a staff person as the primary resource. This means formalizing your intention by putting storytelling activities, support, education, and training in the job description. This is a bold, even presumptuous idea, we know, since libraries are chronically underfunded and understaffed. However, when one person is charged with a professional storytelling concentration, the commitment to storytelling is made manifest in his or her work. He or she can train, of course, but also provide stories to tell, create programs for telling them, and, best of all, establish a continuous kind of encouragement that mitigates against “The Predictable Disappearance of the Really Good, WellMeaning Idea.” p pen dix 1 A The Structure of Stories Most of the time you’ll tell tested, proven stories. You’ll get them out of published books. You won’t have to evaluate the effectiveness of the story’s structure. Collectors, authors, editors, and past tellers have done that for you. You’ll focus on learning and telling. However, it’s good to consider the essential elements of a story that you’ll need to get across to your audience. Over the past fifteen years, cognitive research has confirmed what tellers and writers have known intuitively for centuries: the human mind is literally hardwired to interpret information and experience in a specific story form, and in accordance with a specific story structure. Humans make sense out of what they see and hear by using story structure to create meaning and understanding. This is certainly our belief and our observation from, collectively, fifty years of storytelling experience. It is also the consistent conclusion of recent science research. (See the endnote for a list of some of these studies.) These, and thirty other research studies, have all confirmed that the human brain receives, interprets, processes, understands, relates to, creates meaning from, remembers, and recalls experience and information by using specific internal mental story maps. 89 90 Appendix 1—The Structure of Stories The studies have shown that the power and allure of stories emanates from five elements of information around which stories are constructed. These five elements form the informational core of a story. Three reasons why it’s worth your while to understand these elements: 1. Some aspects of a story are more crucial to listeners than others. Knowing the anatomy of stories saves you time. 2. The more you understand the core elements of a story, the easier it is to learn the story and the more comfortably you’ll tell it. 3. Recognizing these elements will help you identify stories that will be easy for you to learn and tell. WHAT IS A STORY? We find that story structural analysis using these five elements is useful. It is a valuable way to look at stories, to assess why they work—or don’t work—for you, to deepen your understanding of narrative, and to facilitate your storytelling. So what are these five essential elements of stories? A story is a unique and specific narrative structure that includes a sense of completeness. Stories have a beginning point and a defined ending point. They come to resolution. Stories pass on wisdom, experience, information, and facts. Stories shape beliefs and values. They are the building blocks of knowledge, the foundation of memory and learning. Stories model effective use of language. They create empathy, provide perspectives though which we can view other times and other worlds, and connect us with the deepest aspects of our humanity. Stories link past, present, and future by teaching us to use past experience to anticipate the possible future consequences of our present actions. But these are characteristics of a story. What is a story? Character All stories are about characters. Story events happen to characters. What Is a Story? 91 Character and plot are conjoined twins, really, for we can’t have a story without them. Here, the word character includes both the existence of the physical entity and the descriptive detail provided in the story so that listeners will be able to see, identify, and understand the character. Beginning tellers may be misled or confused when comparing the abundant character detail lavished on characters populating modern literary stories to the relative paucity of character detail explicitly provided in traditional tales. The frugality of character detail in folktales is not an oversight, but a clever design characteristic. The characters are often predictable, even stereotypical, so that the listener can quickly identify the character’s place and purpose in the story. No time is wasted. Rather than breaking the norm with unexpected, quirky, even unique combinations of character traits, the characters in folktales are the norm. That, in large part, is their value and appeal. Coyote is the trickster from the Southwestern United States and Mexico. There isn’t a lot of subtlety and nuance. He is who he is: a trickster who lives by his wits and gets in and out of trouble with delicious regularity. He is complex, but not presented with complicated character description and development. For that, we need to schedule a visit with the fictional giants. The large number of traditional characters who are neither admirable nor appealing sometimes surprises fledgling storytellers. They’re useful, though, for they often embody an undesirable trait: greed, avarice, cruelty, and presumption, among many others. Thus, the main character may be the very one who teaches by negative example or by transformation. A caution. These characters, like their stories, come from, and represent, specific cultures. For the most part, we are not members of those cultures, and certainly are not from the period when the story was collected. That means we have to work a bit to discover the character’s significance. It won’t always be obvious from the story’s text without a basic understanding of the culture. Intent Interesting characters don’t ramble through stories for no reason. They are always after something. What a character is after in a story is called a goal. Goals can shift during a story. Characters can be stuck between two opposing goals. But characters, like real people, always have a reason for what they do. 92 Appendix 1—The Structure of Stories Every story is about the goal of the main character. An example: Once there was a girl named Mary who wanted some ice cream. That one sentence presents a character and a goal. We already know how the story will end: we’ll find out if Mary gets her ice cream or not. (Stories end when the main character’s goal is resolved.) We will also use that goal to establish the point and purpose to every action and event in the story. In order for this goal to propel a character through a story’s dangers, trials, and tribulations (the plot), the goal must be important to that character. What makes the goal important is called a motive. The more important the goal (the bigger the motive), the more suspenseful and intriguing the story. Together, goal and motive create a character’s intent. Conflicts and Problems Conflicts and problems are the obstacles that a character must contend with to reach a goal. Obstacles can be internal (fears, conflicting wants, ignorance, beliefs, etc.) or external. External obstacles can either be problems (It’s too hot. It’s too far. There’s a mountain to cross.) or conflicts (a troll, an evil wizard, a dragon, etc.). The antagonist is of great importance to a story, as that being represents the greatest single conflict a main character will have to face. Everyone loves to hate a good antagonist. The more powerful and ruthless the antagonist, the more listeners root for the main character. Certainly a character can be his or her own worst enemy—one’s own antagonist. The best fighting is often against oneself. Conflicts and problems create two things listeners care about a lot: risk and danger. Risk represents the likelihood that something will go wrong. Danger is the consequence (what happens) to a story character when something does go wrong. Excitement does not come from what happens in a story (the action). It comes from knowing what could happen—the risk and danger created by the conflicts that the main character must face. Struggles (Plot) Struggles are what a character does (the action, the plot) to overcome obstacles and reach a goal. Characters must do something. Listeners don’t want it to be easy for story characters. The more characters What Is a Story? 93 struggle—internally and externally—the more gripping the story is. Plot sequences must follow some logic, some understandable pattern— temporal sequencing, cause-and-effect sequencing, etc. Listeners rely on the plot to guide them through events that unfold around characters in a story. Details A few key sensory details about the characters, settings, actions, and objects make a story seem real and vivid to listeners. Story details make it possible for listeners to visualize a story in their minds. These five elements form the underpinning of successful stories. If you see them clearly as you read a story, it will make it easier for you to learn the story and will save you precious time. An example will help clarify these elements and their role in a story: Once there was an emperor (character) who loved clothes so much that he spent all his money on them (character trait). He was vain and obsessed with having the finest clothes in the land. (Another character trait—in this case an internal character flaw. We assume that significant flaws will eventually get story characters in trouble.) When the emperor heard of a new and wondrous—indeed, magic—material he insisted on having a robe made from it (goal). This robe would be the finest robe in the land (motive) and would—because of its magic properties—allow the king to tell which of his ministers were fools (motive). But the weavers were liars and cheats (conflict), and the emperor’s ministers lacked the courage to tell him the truth (problem). How will the story end? We must resolve the goal of the main character. So we need the sequence of events that leads to our discovery of whether or not the emperor gets his new clothes. (He does.) We also want to know how he feels about his new robes and are quite pleased when the truth creates great consternation for the emperor and his ministers. Stories end when the main character resolves—one way or the other—his or her primary goal. Not reaches, but resolves. Yes, a character can have multiple goals, some physical and tangible, others internal; some will be well known to the character and listeners, some may be 94 Appendix 1—The Structure of Stories hidden until late in the story. Still, the story will reach its end when the character’s primary goal is resolved. What’s still missing? • Character traits. After this abbreviated summary of the story, we need a bit more information about the two thieving weavers and a dash more about the emperor in order to ensure that listeners will care whether the emperor gets his comeuppance or the weavers get away with their dastardly scheme. We can’t picture these characters as individuals in our minds yet. While it is true that many folktales intentionally contain few character details so that readers can overlay their own images on those unspecified forms, even these tales must contain just enough character detail to allow readers to both visualize and care about the story’s characters. • Struggles. We don’t know yet what the emperor, his ministers, or the weavers actually do in the story. • Details. We can’t see the character, settings, events, and objects of the story yet because we have added no details. Those are the five essential elements in action. Knowing these essential elements will always bring you back on track and make sure that you deliver the essential story to your listeners. NOTE We have collected more than 100 books, articles, and papers reporting on research that confirm both the concept that humans interpret and create meaning through mental story mapping and the story structure presented in this chapter. A few of the more prominent in this prestigious list are:). See the Bibliography for full listings of these publications. p pen dix 2 A Who Says Storytelling Is Worthwhile? Some storytelling research has been mentioned in the various chapters of this book. Additional selected studies and their central themes are presented here. We do not intend this discussion to be an exhaustive review of the available quantitative and qualitative research literature. That would fill its own book. View this appendix not as a balanced meal, but as a sample of tantalizing morsels that hint at the bounty of research that awaits the hungry traveler. DOES STORYTELLING WORK? Many studies have examined the effects of storytelling. As far back as 1988, Cliatt and Shaw concluded that, “the relationship of storytelling and successful children’s literacy development is well established.” Their study showed that “Children learn and internalize story structure from a diet of told and read stories” and that this process enhanced children’s development of language and logic skills. 95 96 Appendix 2—Who Says Storytelling Is Worthwhile? Kendall has collected more than 1,850 anecdotal reports of the use of stories and storytelling (mostly from teachers, librarians, and other storytellers). While he solicited any and all experiences with the use of stories and storytelling, 100 percent—that’s each and every one—of these 1,850 anecdotal reports claim that stories and storytelling were an effective and engaging addition to their programs that enthused and engaged listeners and efficiently taught essential story content. Storytelling works. Haven has also collected more than 150 research-based studies (both quantitative and qualitative) that assessed the effectiveness of stories and storytelling. Since many of these studies were themselves reviews of a collection of other studies, these 150 studies contain the results of more than 600 separate research efforts. None reported that stories or storytelling were ineffective, or even that stories and storytelling were less effective than available alternatives included in the studies. Again, 100 percent of the available studies supported the value of stories and storytelling. That result is, in itself, amazing. Snow and Burns (1998) concluded their examination of a number of previous studies by saying: “Recently the efficacy of early reading and storytelling exposure has been scientifically validated. It has been shown to work (to develop language skills).” .Similarly, Schank (1990) used his research to show that, “Storytelling has demonstrable, measurable, positive, and irreplaceable value in teaching.” In a more recent study, Mello (2001) reported on ten studies of elementary students including pre- and post-interviews and writing sample analysis. Each of the research reports she studied documented that storytelling enhanced literacy. She concluded that, “storytelling was an effective learning tool that linked literature to content and experience.” O’Neill, Peare, and Pick (2004) studied the storytelling ability of preschool students in Ontario, Canada, and found good correlation between early storytelling skills and later math abilities. O’Neill suggests that time spent on early storytelling skill development in preschool years improves math skill upon entering school. More important, this study establishes storytelling skill as both predating, and as precursor for, logical thinking development. As a small section of his unpublished doctoral work, Janner (1997) conducted an interesting study with four fourth-grade classrooms. He delivered the same story to each class. To one, he read the story. He gave copies of the story to one class and had students read it. He showed a Does Storytelling Work? 97 video of the story to one class, and he told the story to the final class. One month later he interviewed selected students from each class to see how the media of delivery affected their retained images of the story. The students who most accurately recalled the story and its images came from the class that had seen the video. However, the students who were the most enthusiastic and excited about their recollection of the story, who held the most vivid and expansive images of the story, and who were best able to verbalize their memory (and version) of the story were those from the class to whom he told the story. Clearly, this was a small study that contained many uncontrolled variables. Still, its conclusion are inescapable and dramatic. Storytelling creates excitement, enthusiasm, and more detailed and expansive images in the mind of the listener than does the same story delivered in other ways. Chang (2006), a regional director of education for Taiwan, stated, “Living in a highly competitive environment places great pressure on the efficiency and effectiveness of every moment spent at school. I am convinced that stories hold a solution. They teach valuable language skills, effectively teach facts and concepts, and are finally something fun for our students to do.” Schank (1990), and later Dalkir and Wiseman (2004), concluded that storytelling is not only effective at conveying factual and conceptual information, but is also most effective at communicating tacit knowledge, “that which is difficult to articulate, to render tangible in some form.” They included in this category values, beliefs, attitudes, cultural norms, etc. In his 1989 study, Coles showed that stories connect character truth with scientific truth. The dominance of characters in stories and storytelling provides context, empathy, and relevance for the scientific material by using characters to explain intention, action, struggles, and reaction around factual information. Characters represent surrogate models for the reader and allow the reader to interpret and understand content and, thus, to create meaning. Similarly, Howard (1991) concluded that “science is a form of storytelling. Science meaning is constructed and conveyed through storytelling.” He proposed that story elements create context and relevance that provide a way for the reader to understand and to create meaning from the content material they read. 98 Appendix 2—Who Says Storytelling Is Worthwhile? The success of storytelling is not limited to educational and science venues. The same results were found in studies of organizations. Industry surveys conducted by Cooper (1997) concluded that, “In fact, researchers have found that potential employers want their employees to have mastered two aspects of literacy often omitted from school curricula: listening and speaking.” Boyce (1996) and Kahan (2001) conducted an extensive reviews of research on organizational story and storytelling. All of these studies viewed stories as an ef fec tive and valu able—even es sen tial and unavoidable—part of every organization. Kahan stated, “Storytelling is increasingly seen as an important tool for communicating explicit and especially tacit knowledge—not just information, but know-how.” Denning (2001) reported that, “Time after time, when faced with the task of persuading a group of manages or front-line staff in a large organization to get enthusiastic about a major change, storytelling was the only thing that worked.” WHY AND HOW DOES STORYTELLING WORK? Medical technological advancements over the past decade have resulted in vast amounts of new information emanating from the fields of neurolinguistics, neurobiology, cognitive research, and developmental psychology. A tiny mound of that mountain is mentioned here. Mallan (1997) concluded that, “Stories differ from other narratives (arguments, scientific reports, articles) in that they orient our feelings and attitudes about the story content.” His research showed that this emotional engagement is why information presented in the structure of a story is more easily remembered. He added that, “Told stories have the advantage of making the story accessible to all levels of reading proficience.” Mello (2001) suggested that storytelling creates empathy for tellers and for a story’s main characters and that this empathy significantly contributed to the power and effectiveness of storytelling. In reporting research conducted with infants and very young children, Bransford and Brown (2000) stated that, “Young infants learn to Why and How Does Storytelling Work? 99 pay attention to the features of speech and storytelling, such as intonation and rhythm, that help them obtain critical information about language and meaning.” They also reported that, “There appear to be separate brain areas that specialize in subtasks such as hearing words (spoken language recognition), seeing words (reading), speaking words (speech), and generating words (thinking with language).” Bransford suspected that early oral language activity (storytelling and story listening) was particularly important for the development of these various centers. In her 1995 study, Engle asked, “How is it that children, born with no language, can develop the rudiments of storytelling in the first three years of life?” She concluded that “children learn storytelling many years before they master logic, persuasion, writing, and other forms of information delivery.” Egan (1997) pointed out that every developing civilization knew and relied on story and storytelling long before logic, long before writing. “There have been no preliterate groups who did not develop oral myth and folk story. Why should these particular stories be culturally universal?” He and many others concluded that human reliance on oral storytelling and on the traditional forms of myth and folktale relate to what neurobiologists have recently confirmed about brain structure. Human minds are hardwired to interpret and understand information and experience in story form. Humans are predisposed to favor and to rely on the form of story and the process of storytelling. Remember, this is just a small sampling, a mere taste. Indulge. Research delights are available to bolster your position that storytelling is an important offering for your library! p pen dix 3 A A copyright is a bundle of five rights granted by U.S. law to the creator of any intellectual material—such as a story. Under current U.S. law, the creator does not have to do anything to obtain these exclusive rights. Creators get them automatically when they create and fix their creations in any tangible form (write it down; say it into a tape recorder, etc.). The copyright holder no longer even needs to place a copyright notification (© Kendall Haven, 2005) on a copy of the work to protect the There are five specific rights that we grant exclusively to an author in this bundle of rights. These are the exclusive right to publish the work, to copy the work, to create derivative copies of the work (to change it), to promote the work, and to perform it. That last one is where storytellers can run afoul of the copyright laws. What can authors copyright? Anything original in a book they publish—but only what is original to them. You will never know what is (and is not) protected by copyright by looking at the copyright notification on a book. There are many collections of folk tales that display a general copyright protection notice in which the only thing actually being copyrighted is the specific typeface and layout being used to present the stories—not the stories themselves. 101 102 Appendix 3—Copyright and You How can you tell if a story (or even parts of a story) you want to tell is covered by a copyright? Unfortunately, it’s often extremely difficult to tell. The story you pull from your library shelves might look like an original picture book with a current author, and yet the copyright may only cover the illustrations. The copyright notice does not have to spell out what exactly is (and is not) being protected. As a storyteller’s rule of thumb, if you can find three versions of the same story in different source books, you are free and clear to tell it without seeking anyone’s permission. How long do copyrights last? Well, it depends. The U.S. copyright laws have changed several times, and the length of a copyright depends on the year of publication. In general, most recently published books come with a copyright that lasts a maximum of the life of the author plus fifty years. How does copyright law affect you and your storytelling? If you tell folktales, fairy tales, traditional tales, myths or legends (as well as many tall tales), it doesn’t. Those are the stories that, with rare exception, are in the public domain and are fair for all of us to use and tell to our heart’s content. If, however, you choose to tell literary tales, you will bump against copyright infringement. Most authors are thrilled to have librarians use their books during booktalks and storytelling sessions. Most. But not all. Technically, you may not even read a copyrighted storybook to your weekly story time crowd without expressed permission from the copyright holder. However, librarians do it all the time. Reading an entire story is not covered by the “fair use” exclusion to the copyright laws that allows you to extract and present a small portion of a copyrighted work during scholarly review, critique, or parody or to make one copy of a copyright-protected story for your own use. Neither of us can conceive of an author trying to claim that your telling his or her story harmed that author’s monetary interest in the work or reduced in any way his or her income from it. (The criteria by which authors can bring monetary suit against you for telling it.) Neither of us can imagine an author trying to stop you from reading or telling his or her published story in your library. We can’t possibly imagine it. It would make no sense since librarians are doing the author an honor and are providing valuable marketing by presenting the tale. Still, it could happen. How can you protect yourself? Simple. Tell stories from the wealth of public domain stories and stories you know other librarian tellers have successfully told without author retribution. If they didn’t get in trouble, neither will you. When you stretch beyond that cover, we feel obligated to say that the safest thing to do is to write (or e-mail) the author and ask permission to tell the story in your library. Every sensible author will gladly say, “Yes.” If he or she says, “no,” then spread the word. As we said, we can’t imagine any author refusing such permission. We don’t think you need to stay up nights fretting over copyright. However, it is good to be aware of it. Further, it’s a good policy for you to support these rights since they are what make it possible for authors to create and share their wonderful works. p pen dix 4 A Definitions of Traditional Tales The following definitions of the types of traditional tales are taken from Webster’s Third New International Dictionary of the English Language, Unabridged (Phillip Babcock Gove, ed. Springfield, MA: Merriam-Webster, Inc., 1981). Anecdote: A short narrative of interesting, amusing, or curious incidents often biographical and generally characterized by human interest. Epic: A long narrative poem recounting the deeds of a legendary or historical hero. Fable: A narration intended to enforce some universal truth or precept, especially one in which animals and even inanimate objects talk and act as human beings. Fairy tale: A narrative containing supernatural or improbable events, scenes, or personages and often having a whimsical, satirical, or moralistic character. Folktale: A tale circulated by word of mouth among the common people, especially a tale characteristically anonymous and timeless. Legend: A story coming down from the past popularly regarded as historical, although not entirely verifiable. 105 106 Appendix 4—Definitions of Traditional Tales Myth: A story that is usually of unknown origin, and at least partly traditional, that ostensibly relates historical events, usually of such a character as to explain some practice, belief, institution, or natural phenomenon that is especially associated with religious rites and beliefs. Bibliography We offer this bibliography with special thanks to Infopeople, a company that provides training and instruction for library staffs across California. Their invention, responsiveness, and organization make them an unrivaled model. They have graciously allowed us to include many of the sections of this bibliography. REFERENCES: WORKS CITED IN THIS BOOK Ambruster, B., et al. (1987). “Does Text Structure/Summarization Instruction Facilitate Learning from Expository Text?” Reading Research Quarterly 22: 331–346. Boyce, M. (1996). “Organizational Story and Storytelling: A Critical Review.” Journal of Organizational Change Management 9 (5): 5–26. Bransford, J., and A. Brown, eds. (2000). How People Learn. Washington, DC: National Academy Press. Bransford, J., and B. Stein. (1993). The Ideal Problem Solver., 2d ed. New York: Freeman. Bruner, J. (1986). Actual Minds, Possible Worlds. Cambridge, MA: Harvard University Press. ———. (1987). “Life as Narrative.” Social Research 54: 11–32. ———. (1990). Acts of Meaning. Cambridge, MA: Harvard University Press. ———. (1992). “The Narrative Construction of Reality.” In Piaget’s Theory: Prospects and Possibilities, edited by H Beilin and P. Pufall, 229–248. ’ Hillsdale, NJ: Lawrence Erlbaum. Cliatt, M., and J. Shaw. (1988). “The Storytime Exchange: Ways to Enhance It.” Childhood Education 64 (5): 293–298. Coles, Robert. (1989). The Call of Stories. Boston: Houghton-Mifflin. Cooper, J. (1997). Literacy: Helping Children Construct Meaning. Boston: Houghton Mifflin. Dalkir, K., and E. Wiseman. (2004). “Organizational Storytelling and Knowledge Management: A Survey.” Storytelling, Self, Society 1 (1, Fall): 57–73. Denning, S. (2001). The Springboard: How Storytelling Ignites Action in Knowledge-Era Organizations. Boston: Butterworth-Heinemann. Egan, K. (1997). The Educated Mind: How Cognitive Tools Shape Our Understanding. Chicago: University of Chicago Press. Engle, S. (1995). The Stories Children Tell: Making Sense of the Narratives of Childhood. New York: Freeman. 107 108 Bibliography Fisher, W. (1987). Human Communications as Narration: Toward a Philosophy of Reason, Value, and Action. Columbia: University of South Carolina Press. ———. (1994). “Narrative as a Human Communications Paradigm: The Case of Public Moral Argument.” Communications Monograph 51: 1–20. Gopnik, A., et al. (1999). The Scientist in the Crib. New York: HarperPerennial. Haven, K. (2004) Get It Write!. Portsmouth, NH: Teacher Ideas Press. Howard, G. (1991). “Culture Takes: A Narrative Approach to Thinking, Cross-Cultural Psychology, and Psychotherapy.” American Psychologist 47 (3, March): 187–197. Janner, B. (1997). The Psychological Effects of Alternate Means of Mass Communication. Ph.D. dissertation, Ann Arbor, University of Michigan. Kahan, S. (2001). “Bringing Us Back to Life: Storytelling and the Modern Organization.” Information Outlook 5 (5): 26–29. Kotulak, R. (1999). Inside the Brain: Revolutionary Discoveries of How the Mind Works. Kansas City: Andrews McNeal. Mallan, Kerry. (1997). “Storytelling in the School Curriculum.” Educational Practice & Theory 19 (1): 75–82. Mello, R. (2001). “Building Bridges: How Storytelling Influences Teacher/Student Relationships.” In Proceedings, Storytelling in the Americas Conference. St Catherine, ON: Brooks University Press. O’Neill, D., M. Pearce, and J. Pick. (2004). “Predictive Relations Between Aspects of Preschool Children’s Narratives and Performance on the Peabody Individualized Achievement Test—Revised: Evidence of a Relation Between Early Narrative and Later Mathematical Ability.” First Language 24 (June): 149–183. Pinker, S. (1997). How the Mind Works. New York: W. W. Norton. ———. (2000). The Language Instinct. New York: Perennial Classic. Ricoeur, Paul. (1984). Time and Narrative. Chicago: University of Chicago Press. Schank, R. (1990). Tell Me a Story. New York: Charles Scribner’s Sons. Shank, R., and R. Abelson. 91995). “Knowledge and Memory: The Real Story.” In Knowledge and Memory: The Real Story, edited by R. Wyer Jr., 1–85. Hillsdale, NJ: Erlbaum. Snow, C., and M. Burns, eds. (1998). Preventing Reading Difficulties in Young Children. Washington, DC: National Research Council and National Academy Press. Tannen, D. (1999). Talking Voices: Repetition, Dialogue, and Imagery in Conversational Discourse. New York: Cambridge University Press. Turner, M. (1996). The Literary Mind: The Origins of Thought and Language. New York: Oxford University Press.. 112 Bibliography Bierhorst, John. ed. Black Rainbow: Legends of the Incas & Myths of Ancient Peru. New York: Farrar, Straus & Giroux, 1976.** ———. Latin American Folktales: Stories from Hispanic and Indian Traditions. New York: Pantheon, 2000. Boggs, Ralph. Three Golden Oranges and Other Spanish Tales. Mineola, NY: Longmans, 1936. (Dover reissue.) Briggs, Katharine M. A Dictionary of British Folk-Tales. Bloomington: Indiana University Press, 1970. Bryan, Ashley. Beat the Story Drum, Pum, Pum. New York: Atheneum, 1980. Bushnaq, Inea. Arab Folktales. Pantheon, 1986. Calvino, Italo. Italian Tales. New York: Harcourt Brace Jovanovich, 1980. Chase, Richard. The Jack Tales. Boston: Houghton Mifflin, 1943** Cole, Joanna. Best-Loved Folktales of the World. New York: Doubleday, 1982. Courlander, Harold. The Hat-Shaking Dance and Other Ashanti Tales from Ghana. New York: Harcourt, 1957. ** Curtis, Edward. S. The Girl Who Married a Ghost and Other Tales from North American Indians. Edited by John Bierhorst. Columbus, OH: Four Winds Press, 1978. Dalal, Anita. Myths of Oceania. New York: Raintree Steck-Vaughn, 2002. De Vos, Gail. Storytelling for Young Adults: Techniques and Treasury. Englewood, CO: Libraries Unlimited, 1991. Dorson, Richard. Folktales Told Around the World. Chicago: University of Chicago Press, 1975. Durham, Mae. Tit for Tat and Other Latvian Folk Tales. New York: Harcourt, Brace and World, 1967. Erdoes, Richard, and Alphonso Ortiz. American Indian Myths and Legends. London: Pantheon, 1984. Fillmore, Parker. The Shepherd’s Nosegay. New York: Harcourt, Brace, 1958. Glassie, Henry. Irish Folk Tales. London: Pantheon, 1985. Griego y Maestas, Jose, and Rudolfo Anaya. Cuentos: Tales from the Hispanic Southwest: Based on stories originally collected by Juan B. Rael. Albuquerque: Museum of New Mexico Press, 1980. (Bilingual collection: Griego selected and adapted in Spanish, Anaya retold in English.) Grimm, Jacob, and Wilhelm Grimm. Grimm’s Fairy Tales for Young and Old. Translated by Ralph Manheim. Doubleday, 1977. (See also translations by both Jack Zipes and Maria Tatar.) Hamilton, Virginia. The People Could Fly: American Black Folktales. New York: Knopf, 1985. ** Hearn, Lafcadio. Japanese Fairy Tales. New York: Liveright, 1953. Howard, Norman. The Girl Who Dreamed Only Geese, and Other Tales of the Far North. New York: Harcourt, Brace, 1997. Reliable Collections of Traditional Tales 113 Hume, Lotta Carswell. Favorite Children’s Stories from China and Tibet. North Clarendon, VT: Tuttle, 2000. Hyde-Chambers, Frederick, and Audrey Hyde Chambers. Tibetan Folktales. Boston: Shambhala, 1981. Jacobs, Joseph. English Folk and Fairy Tales. New York: G. P. Putnam’s Sons, c. 1898. ** Jaffrey, Madhur. Seasons of Splendor: Tales, Myths & Legends of India. New York: Atheneum, 1985. Jataka Tales. Edited by Nancy DeRoin. Boston: Houghton Mifflin, 1975. Jewett, Eleanor Myers. Which Was Witch: Tales of Ghosts and Magic from Korea. New York: Viking, 1953. Kendall, Carol. Sweet and Sour: Tales from China. New York: Seabury Press, 1979. Kelsey, Alice Geer. Once the Hodja. Philadelphia: McKay, 1943. Kroeber, Theodora. The Inland Whale. Berkeley: University of California Press, 1970. Lang, Andrew. The Rainbow Fairy Book: Selections of Outstanding Tales from the Color Fairy Books. New York: Viking, 1977. (See others: The Red Fairy Book, etc.)** Lester, Julius. The Knee-High Man and Other Tales. New York: Dial, 1972.** Livo, Norma, and Dia Cha. Folk Stories of the Hmong: Peoples of Laos, Thailand and Vietnam. Englewood, CO: Libraries Unlimited, 1992. MacDonald, Margaret Read. Three-Minute Tales: Stories from Around the World to Tell or Read When Time Is Short. Little Rock, AR: August House, 2004. Minard, Rosemary. Womenfolk and Fairy Tales. Boston: Houghton Mifflin, 1975. Nic Leodhas, Sorche. Heather and Broom: Tales from the Scottish Highlands. New York: Holt, 1960. ** Perrault, Charles. Perrault’s Complete Fairy Tales. Translated by A. E. Johnson. New York: Dover, 1969. Phillip, Neil. Fairy Tales of Eastern Europe. New York: Clarion Books, 1991. Picard, Barbara Leoni. Tales of Ancient Persia. New York: Knopf, 1965. Riorden, James. Tales from Tartary. London: Kestrel, 1978. (Volume 2 of Russian Tales series.) ** Sanfield, Steve. The Feather Merchants and Other Tales of the Fools of Chelm. London: Orchard, 1991. Shah, Idries. World Tales. New York: Harcourt, Brace, Jovanovich, 1979. Sierra, Judy. The Oryx Multicultural Folktale Series: Cinderella. Phoenix: Oryx Press, 1992. ** Singer, Isaac Bashevis. When Schlemiel Went to Warsaw and Other Stories. New York: Farrar, Straus & Giroux, 1986.** Tashjian, Virginia. Juba This and Juba That. Boston: Little, Brown, 1969. Tatterhood and Other Tales: Stories of Magic and Adventure. Ethel Johnston Phelps, Ed. Feminist Press, 1978.** 114 Bibliography Uchida, Yoshiko. The Dancing Teakettle and Other Japanese Folktales. New York: Scribner, 1965. Undset, Sigrid. True and Untrue and Other Norse Tales. New York: Knopf, 1945. Vuong, Lynette Dyer. The Golden Slipper and other Vietnamese Tales. Boston: Addison-Wesley, 1982. Walker, Barbara K. Once There Was and Twice There Wasn’t. Rover Grove, IL: Follett, 1968. Williamson, Duncan. The Broonies, Silkies and Fairies: Travelers’ Tales of the Other World. London: Harmony, 1985. Wolkstein, Diane. The Magic Orange Tree and Other Haitian Folktales. New York: Schocken Books, 1980. ** Yeats, William Butler. Irish Folk Stories and Fairy Tales. Edited by William Butler Yeats. New York: Grossett & Dunlap, 1972. Yolen, Jane. Favorite Folktales from Around the World. London: Pantheon, 1986.** FAMILY AND PERSONAL STORIES Alessi, Jean, and Jan Miller. Once Upon a Memory: Your Family Tales and Treasures. Cincinnati, OH: Betterway,1987. Bands, Ann, ed. First Person America. New York: Random House, 1980. Darden, Norma Jean, and Carole Darden. Spoonbread and Strawberry Wine: Recipes and Reminiscences of a Family. Norwell, MA: Anchor Press, 1978. Davis, Donald. Telling Your Own Stories. Little Rock, AR: August House Publishers, 1997. Dixon, Janice, and Dora Flack. Preserving Your Past: A Painless Guide to Writing Your Autobiography and Family History. New York: Doubleday, 1977. Frazier, Ian. Family. New York: Farrar, Straus & Giroux, 1994. MacDonald, Margaret Read. Parents Guide to Storytelling: How to Make Up New Stories and Retell Old Favorites. 2d ed. Little Rock, AR: August House, 2001. Moore, Robin. Awakening the Hidden Storyteller: Creating a Family Storytelling Tradition. Little Rock, AR: August House, 1999. Norden, Catherine. The Way We Looked: The Meaning and Magic of Family Photographs. New York: Lodestar/Dutton, 1983. Pellowski, Anne. The Family Storytelling Book. New York: Macmillan, 1987. Stone, Elizabeth. Black Sheep and Kissing Cousins: How Our Family Stories Shape Us. New York: Random House, 1988. Participation Stories 115 Winston, Linda. Keepsakes: Using Family Stories in Elementary Classrooms. Portsmouth, NH: Heinemann, 1997. Zeitlin, Steven J., Any J. Kotlin, and Holly Cutting Baker. A Celebration of American Family Folklore: Tales and Traditions from the Smithsonian Collection. London: Pantheon, 1982. PARTICIPATION STORIES Traditional tales that appear in many collections are listed by title only. We include full citations for literary stories and for retellings of traditional tales that we prefer. Ask Mr. Bear. Marjory Flack. New York: Macmillan, 1958. The Banza. Dianne Wolkstein. New York: Dial, 1981. Big Pumpkin. Erica Silverman. Gilroy, CA: Aladdin, 1995. Caps for Sale. Esphyr Slobodkina. Addison-Wesley, 1947. A Dark, Dark Tale. Ruth Brown. New York: Dial, 1981. The Fat Cat. Jack Kent. New York: Scholastic, 1972. “The Gingerbread Man.” “Goldilocks and the Three Bears.” Good Night Owl. Pat Hutchins. New York: Macmillan, 1972 “Henny Penny.” “I’m Tipingee, She’s Tipingee, We’re Tipingee Too.” In The Magic Orange Tree and Other Haitian Folktale. Diane Wolkstein. Knopf, 1978. It Could Always Be Worse. Margo Zemach. New York: Farrar, Straus & Giroux, 1977. The Judge: An Untrue Tale. Harve Zemach. New York: Farrar, Straus & Giroux, 1969. “Lazy Jack.” (See also “Idle Jack.”) The Little Red Hen. Paul Galdone. New York: Seabury, 1973. Lizard’s Song. George Shannon. New York: Greenwillow, 1981. Magic Wings. Diane Wolkstein. Boston: Little, Brown, 1983 Mama Don’t Allow. Thatcher Hurd. Harper, 1985. The Mitten. Pierre. Maurice Sendak. Harper, 1962. Piney Woods Peddler. George Shannon. New York: Greenwillow, 1981. 116 Bibliography “Sody Saleratus”. Grandfather Tales. Richard Chase. Boston: Houghton-Mifflin, 1948. Tailypo: A Ghost Story. Joanna Galdone. New York: Seabury, 1977. The Teeny, Tiny Woman: A Ghost Story. Paul Galdone. Boston: Houghton Mifflin, 1982. “The Three Billy Goats Gruff.” “The Three Little Pigs.” The Turnip. Janina Domanska. New York: Macmillan, 1959. Where the Wild Things Are .Maurice Sendak. New York: Harper, 1963. Who’s in Rabbit’s House? “Why Dogs Hate Cats.” In The Knee-High Man. Julius Lester. New York: Dial, 1972. “The Yellow Ribbon.” In Juba This and Juba That. Virginia Tashjian. Boston: Little, Brown, 1995. SONG, MOVEMENT, AND PROPS STORIES Bay, Jeanette Graham. Treasury of Flannel Board Stories. Upstart Library Promotionals, 1995. Faurot, Kimberly K. Books in Bloom: Creative Patterns and Props that Bring Stories to Life. Chicago: ALA Editions, 2003. Fugita, Hiroko, and Fran Stallings, adapt. and ed. Kids’ Tales: Told with Puppets, paper, Toys and Imagination. August House, 1999. Gryski, Camilla. Cat’s Cradle, Owl’s Eyes: A Book of String Games. Scholastic, 1995. Holt, David. Folk Rhythms: Learn to Play Spoons, Bones, Washboard, Hambone and the Paper Bag. Homespun Video, 1995. Jaffe, Nina. Patakin! World Tales of Drums and Drummers. Publishers Group West, 2001. (Reissued in paperback with CD.) Kallevig, Christine. Folding Stories: Storytelling and Origami as One. Storytime Inc. International, 1991. MacDonald, Margaret Read. Shake It Up Tales: Stories to Sing, Dance Drum and Act Out. August House, 2000. Painter, William H. Storytelling with Music, Puppets, and Arts for Libraries and Classrooms. Linnet, 1982. Pellowski, Anne. The Family Storytelling Handbook: How to Use Stories, Anecdotes, Rhymes, Handkerchiefs, paper and Other Objects to Enrich Your Family Traditions. New York: Macmillan, 1987. Webliography for Storytelling, Storytellers, and Stories 117 WEBLIOGRAPHY FOR STORYTELLING, STORYTELLERS, AND STORIES Heather Forest, storyteller and musician, created this site. It is attractive, easy to navigate, and useful for teachers and librarianss. The original, and still the best, online storytelling chat and information-sharing site. Maintained by Texas Women’s University library school. Opinionated, sometimes shrill, and wise. Be forewarned: there are dozens of postings. The site for Storytelling Foundation International that sponsors the annual National Storytelling Festival. The home site for the National Storytelling Network. The membership organization for storytellers nationally. Offers the National Storytelling Conference each year. A delicious survey and debunking of urban legends. Easy to pick up good stories, and irresistible to surf through. A really good site, with access to hundreds of Aesop’s fables. D. L. Ashliman’s essential site provides folk texts, Germanic traditional material, links, and a terrific subject index to tales. An Internet encyclopedia of myth and folklore; new articles added frequently. The site for the Folk Narrative Section of the American Folklore Society. Includes a bibliography. Index Accessories to storytelling, 67 audience participation, 76–81 costumes, 72–74 flannelboards, 68–69 props, 69–72 puppets, 74–76 Audience participation making it work, 78–79, 81 pros and cons of using, 76–77, 80 “Cast of thousands”. See Audience participation Choosing stories aspects/issues to consider, 24–25, 27–28 personal preferences, 23 sources, 25 starting with personal stores, 24 Collaborations, 85 Community storytelling, 6 Costumes making them work, 73–74 pros and cons of using, 72–73 Flannelboards pros and cons of using, 68–69 Gestures and movement in storytelling 64–66 pitfalls, 65 Hitt, Jack (Harper’s magazine), 22 Incorporating stories into library work/programs, 83 collaborations, 85 dedicated staff person, 87 in-service training, 87 story-sharing meetings, 84 story swapping, 84 storytelling festival, 86, 87 theme programs, 84–85 workshops, 85–86 Informal storytelling, 5–6 Learning stories advanced steps, 32–33 approaches to, 30–32 basic tenets of, 42 considerations to ignore, 31 by doing, 29–30 literary tales, 38 Levels of storytelling, 4–5 community, 6 informal, 5–6 professional, 6–7 Libraries as repositories of discourse, 1–2 opportunities for storytelling in, 7 storytelling in, history of, 2 Library staff and storytelling, 1–7, 87 Listener needs, 19–21 Literary tales and ballads, 37 consideration when telling, 36–37 memorization of, 35, 38 reading versus telling, 36 and traditional tales, 37 Literature. See also Literary tales and storytelling, 3 Memorization, 35, 38, 52–53 Pace in storytelling, 62 Pitch in storytelling, 62–63 Practicing telling, 39–40 basic tenets of, 42 experimenting, 40–41 Preparation for storytelling, 43 assistance, 45 final, 46 setting the scene, 45–46 space, 44–45 stage arrangements, 45 Problems, aids for dealing with, 51 memorizing, pros and cons of, 52–53 safety net, 53–57 119 120 Index Professional storytellers, 6–7 reliance on, 4–5, 6 Props making them work, 71–72 pros and cons of using, 69–71 Puppets making them work, 76 pros and cons of using, 74–75 Rate. See Pace in storytelling Reading versus telling, 21–22, 36 Reasons for storytelling ability/talent, 9–10 patron needs, 10 to connect with patrons, 14 to enhance understanding of the story, 13–14 to engage patrons, 11–12 to generate details in listeners’ minds, 13 to make events/topics accessible, 12 variety, 10–11 Research on storytelling, 11, 13, 14, 18, 81, 95–99 Safety net for telling dealing with forgetting, 53 developing, 53 remembering, 55–56 telling about the story, 54–55 treading water, 56–57 using the smile, 53–54 Space for storytelling, 44–45 Special programs for storytelling, 84–85 Stages of telling adjusting pace, 47 celebrating, 49 finale, 48 gauging reactions, 47–48 introduction , 46–47 letting audience absorb the story, 48 review, 49–50 Story. See also Choosing stories; Storytelling; Structure of stories defined, 25 elements of, 26 structure of, 89–94 Story swapping, 84 Story-sharing meetings, 84 Storytelling. See also Choosing stories; Learning stories; Levels of storytelling; Practicing telling; Preparation for storytelling; Problems, aids for dealing with; Reasons for storytelling; Research on storytelling; Stages of telling; Story; Storytelling enhancements/tools benefits of, for librarians, 3–4 and copyright issues, 101–3 as educational tool, 2 efficacy of, 95–98 history of, in public libraries, 2 how it works, 98–99 learning to do, 17–19 and library staff, 1–7 and listener needs, 19–21 and literature, 3 as natural process, 15–19 opportunities for, in libraries, 7 record keeping, 49 Storytelling enhancements/tools, 33–34, 59–60. See also Accessories to storytelling gestures/movement, 64–66 pace (rate), 62 pitch, 62–63 voice, 61–62 volume, 63 Storytelling festivals, 86, 87 Storytelling workshops, 85–86 Structure of stories, 89 character, 90–91 conflicts, 92 details, 93–94 intent, 91–92 plot, 92–93 Tale types, defined, 105–6 “Toys”. See Storytelling enhancements/tools Voice in storytelling, 61–62 Volume in storytelling, 63 About the Authors Kendall Haven. The only West Point graduate and only senior oceanographer to become a professional storyteller, Haven has performed for four million. He has won numerous awards for his story writing and his storytelling and has conducted story writing and storytelling workshops for 40,000 teachers and librarians and 200,000 students. Haven has published five audiotapes and twenty-five books, including three award-winning books on story: Write Right and Get It Write on writing, and Super Simple Storytelling, on doing, using, and teaching storytelling. Through this work he has become a nationally recognized expert on the architecture of narratives and on teaching creative and expository writing. Haven served on the National Storytelling Association’s Board of Directors and founded the International Whole Language Umbrella’s Storytelling Interest Group. He served as co-director of the Sonoma and Bay Area Storytelling Festivals, was an advisor to the Mariposa Storytelling Festival, and is founder of Storytelling Festivals in Las Vegas, Nevada, and Boise, Idaho. He lives with his wife in the rolling Sonoma County grape vineyards in rural Northern California. Gay Ducey was raised in New Orleans, with its parade of ritual and play, and has been trafficking in stories from the time she was born. She has been a children’s librarian for Oakland Public Library for twenty-four years and is the staff trainer for Books for Wider Horizons, a program that sends volunteers into local Head Start centers to present story times. A celebrated storytelling educator, she has taught storytelling in UC Berkeley’s graduate division and Dominican University, among others, and has traveled the United States and to Canada and Ireland, telling stories to every age. She has been a commissioned artist at the Smithsonian’s Museum of American History and was named an “Outstanding Woman of Berkeley.” Ducey is the artistic director of the Bay Area Storytelling Festival. She and her family live in Berkeley. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/111821729/Storytelling
CC-MAIN-2017-04
refinedweb
34,529
66.44
! Betting more BOBJ customers on business analytics I must admit, I was left a little confused by SAP’s Tuesday announcement on business analytics. Why would SAP hold a big press conference, call in the big guns in Bill McDermott and introduce a bunch of new vertical applications that didn’t really leverage (at least yet) any of the technology principals SAP espoused at Sapphire — on-demand, in-memory and mobile? To be fair, SAP’s working with HP to put these applications in the cloud, and that likely means that they will in some way leverage HANA — the in-memory appliance that SAP’s working on with HP. Plus, SAP said they would support mobile in the second half of 2011. So I posed my question to a couple of my sharpest SAP shop pals. I don’t cover business analytics all that often. I know people want business analytics. But is there some huge demand for these that I haven’t caught on to that’d make SAP push them out now? What I got was an interesting history lesson. For 10 years or so, SAP has sold industry-specific software as it relates to ERP. You’re familiar with it — Apparel and Footwear, Public Sector, Utilities, etc. This is meant to accommodate potential customers whose business processes weren’t covered by the R/3 functionality, one of my pals said. Physically, these are add-ons to standard R/3/ECC architecture. Some of them extend standard tables and programs, and some are ‘non-modifying’, completely in their own namespace. But when it comes to BI and BW content, these customers are sometimes left behind, because that content is based on the standard R/3 scenarios. Historically, they were not able to run ETL or report on data that’s in the vertical add-ons without custom development. SAP has put a lot of the vertical content in BW, but the BOBJ stuff is still pretty new. So these new vertical apps present very appealing SAP BusinessObjects bait for those customers that run those “Industry Solutions”, like AFS or the Utilities. It allows those apps to access content in that industry-specific software without a whole bunch of custom development. It must be why the SDN-type folks at that press conference kept asking the question over and over again — how much custom development is involved in this? They were schooled in their history lessons. No doubt business analytics is the hot sell right now. Surveys across our TechTarget sites reveal it is a top IT initiative for customers in 2011. I’ll return to a theme I’ve repeated a lot on this blog — is it cheaper to keep an existing customer or go out and get a new one? SAP of course wants to sell BOBJ into the existing customer base. And of course, many customers don’t want to buy something that requires a bunch of custom-development. Perhaps this is a case where the BOBJ content was custom-developed in-house for certain customers to meet specific business requirements, and then readied to be packaged and sold, my pal said. Savvy, SAP. But how many of the verticals can they actually deliver this type of functionality for? We shall see. SAP?
http://itknowledgeexchange.techtarget.com/sap-watch/page/11/
CC-MAIN-2016-50
refinedweb
547
61.77
Presto is a cool technology that works with everything (within reason). So it should be totally well documented how to set it up with IntelliJ, right?? Not so fast... #googlefail UPDATE - IntelliJ and DataGrip now have drivers for presto and trino right out of the oven, so no need to read on! If you like ancient history, feel free to keep reading :) Happy coding! While it's not totally un-intuitive, many people trying to set it up might not see the options and give up. Don't give up, here's the coolness! Step 1 - Download the JDBC Driver If you don't know by now, there's two forks of presto in the universe. Not surprisingly there is a JDBC driver for each and mostly they seem to be nearly identical, however at the time of writing, PrestoSQL's driver performed a bit faster for me. I encourage folks to follow their releases for more critical information. PrestoDB, the original project by Facebook. Trino, the rename of the fork PrestoSQL the fork of the project in the community So just click the link under "JDBC Driver" and download it.. To a personal location: ~/Documents/jdbc-drivers Or copy it to intellij's location: ~/Library/Application\ Support/JetBrains/IntelliJIdea2020.2/jdbc-drivers/ Step 2 - Add IntelliJ Driver - In "Database" panel click +or right click and select New -> "Driver" - Enter "PrestoSQL" or "PrestoDB" in the name (whichever driver you chose. - Under the "Driver Files" box, click the +and browse to the downloaded jdbc jar. - Pick the driver class (facebook or prestosql) - Add the Datasource and use the Driver (and click "Test connection".) jdbc:presto://<host>:<port> - Right click on new Datasource->Database Tools->Manage Shown Schemas... select "All Databases" and also select "All Schemas". The last step is particularly helpful if you presto is hosting multiple catalogs across database instances. If you're dealing with particularly large amount of tables, this step could take a while. Driver File Driver Class Datasource NOTE : make sure to use full url with jdbc protocol and port jdbc:presto://<host>:<port> Shown Schemas Step 3 - Profit! Hopefully this will unlock all the presto possibilities for you! - Queries across database instances. - Single SQL syntax. - Schema explorer and keyboard completion. On the way, there could be a few "gotchas" so here's a quick list of things that could trip you up. 1. Connection URL Make sure the protocols, address, and ports are correct. By default, presto runs on 8080 but if your team set it up with ssl 443 might be the right setup, or it could even be a custom port. You may also have basic networking issues, so test if you can even connect to the host/port (maybe through the ui if permitted by your systems team). 2. Credentials By default presto doesn't require credentials, so even though it shows username and password, you might be able to just put in "presto" and either blank or some garbage into password. On the other hand if presto is secured with file based store or LDAP you'll need to be granted credentials. 3. Catalogs If presto is missing or has catalog access restrictions, you may not be able to see or query all of the datasources and schemas that presto is attached to. 4. Driver Updates Since IntelliJ isn't managing the driver, you'll be responsible for your own updates... Small price to pay, or we can all keep voting for this feature and maybe someday IntelliJ will add it. 5. DBeaver If you don't like this, then have a look at DBeaver which supports PrestoDB and PrestoSQL without downloading the driver. Same caveats apply Summary IntelliJ's database explorer is slick and integrated experience and you can easily use any JDBC Driver. Presto in particular is one that is especially powerful. Let me know if you have any comments or feedback. Enjoy! Discussion (2) Great article Phillip! I’d like to make a few additional comments regarding the setup for Trino. As you pointed out, we rebranded so if you are connecting to a Trino server version >= 351, you need to make sure you’re using a Trino jdbc client >= 351 as the namespace has changed. You will also need to change the connection scheme from “jdbc:presto” to “jdbc:trino”. We realize this adds a bit more confusion to the article but as you read in the Trino rebrand blog, our hands were forced as Facebook and the Linux Foundation enforced the Presto trademark. Last thing is that if you have enabled SSL/TLS on your Trino (or Presto) cluster, you will need to add SSL=true to the parameter list of your jdbc connection string. For IDE and other tools like DBeaver, I typically add these params in the box where you specify which database/schema you’re connection to that shows up at the end of the string. Finally, we like to think of Trino as the upgrade to Presto. We have a plethora of new features that don’t exist on Presto, an very active community that is quick to respond, the fix for a critical security vulnerability that affects Trino versions <= 337 and still affects PrestoDB and we wouldn’t recommend putting into production, and the original creators of Presto and other contributors that have collectively contributed over 95% of the code for PrestoDB project. Come find us on slack to find out more! trino.io/slack.html good points. we use ssl and I haven't had to add the SSL=trueto a connection string but if anyone has issues, can't hurt.
https://dev.to/pcfleischer/using-intellij-datagrip-with-presto-jdbc-jp8
CC-MAIN-2022-33
refinedweb
940
70.33
Rename js/src/ion to js/src/jit RESOLVED FIXED in Firefox 24 Status () People (Reporter: jandem, Assigned: jandem) Tracking Firefox Tracking Flags (firefox24 fixed, firefox25 fixed, firefox26 fixed) Details (Whiteboard: [qa-]) Attachments (3 attachments) As discussed on the mailing list last week, this patch renames js/src/ion to js/src/jit. It also renames the ifdefs in the header files, for instance ion_TypePolicy_h -> jit_TypePolicy_h What may be a problem for some people is that the "jit-test" directory and the "jit" directory both start with "jit", so the shell does not complete "jit<tab>" to "jit/" If anybody thinks that's a problem please speak up.. I can build a shell with this patch, but still need to send this to Try. Attachment #787502 - Flags: review?(luke) Comment on attachment 787502 [details] [diff] [review] Patch Great! As for 'jit-test', hopefully, in the long term, we'll roll that into src/tests so that *gasp* we only have a single shell testing harness. Attachment #787502 - Flags: review?(luke) → review+ Sorry for breaking everybody's patches.. Though "hg rebase" should take care of that just fine. If you don't use hg rebase, replacing ion/ with jit/ in the patch file should work.. Follow-up to touch CLOBBER: Status: ASSIGNED → RESOLVED Closed: 6 years ago Resolution: --- → FIXED Target Milestone: --- → mozilla26 Any plans to rename the |ion| namespace? (In reply to Nicholas Nethercote [:njn] from comment #5) > Any plans to rename the |ion| namespace? Yup, that's next. I also want to rename IonRuntime -> JitRuntime IonCompartment -> JitCompartment IonCode -> JitCode IonFrames -> JitFrames (These are used by both JITs.) While you are busy, what about renaming "jit-tests.py --ion" to "jit-tests.py --jit". IIRC --ion also tests --eager-baseline. (In reply to Jan de Mooij [:jandem] from comment #6) > Yup, that's next. I also want to rename > > IonFrames -> JitFrames Do you mind if I do the renaming of the last one? As I currently have a *Huge* pile of patches waiting for review on these files. (Bug 878503) Otherwise, somebody can just review these patches (22+ … and more coming) such as I land them before you do the modifications, but I guess this will require that nobody enforce that these patches should not be reviewed. Renaming js/src/ion to js/src/jit makes backporting JIT patches to aurora, beta and ESR24 a lot more annoying. As suggested in bug 909499 comment 2, we'd like to backport these changes to aurora and beta (including ESR24). To quote Waldo: > Failing that, I think we should seriously consider redoing this rename for > esr24 as well. As long as we're careful about it just being renaming, I > think it'd be worth it to avoid ten months of backport conflict-fixing. To > be honest, that scares me more than the possibility of screwing something up > in a single, concerted renaming backport-session. Attachment #796606 - Flags: review?(luke) Attachment #796606 - Flags: approval-mozilla-aurora? See comment 9. Attachment #796611 - Flags: review?(luke) Attachment #796611 - Flags: approval-mozilla-beta? Comment on attachment 796606 [details] [diff] [review] Patch for aurora Thanks for doing this Jan. Attachment #796606 - Flags: review?(luke) → review+ Pushed to try: Beta: Aurora: Try pushes are green. Flags: needinfo?(bbajaj) (In reply to Ryan VanderMeulen [:RyanVM UTC-4] from comment #13) > Try pushes are green. That was quick :), Looks good to land , approving ! Flags: needinfo?(bbajaj) status-firefox24: --- → fixed status-firefox25: --- → fixed status-firefox26: --- → fixed Assuming no QA needed here. Please remove [qa-] from the whiteboard and add the verifyme keyword if this needs QA. Whiteboard: [qa-]
https://bugzilla.mozilla.org/show_bug.cgi?id=902908
CC-MAIN-2019-30
refinedweb
597
65.32
This is not my usual kind of subject. Most of my post are on the diversity of share worthy tidbits I encounter while building apps. Test Driven Design is quite a hot topic here on Codebetter. So far I had nothing to add to the great writings of Jeremy et al. But a discussion on a post by Jay on Javascript struck me. It gave the impression TDD as something too big or complicated to get started with. In this post I will describe some of my experiences with TDD. It's a very simple story on a very simple problem but it makes clear how TDD is also for me an easy way to tackle problems. This story deals with the Vecozo web service. This secured web service offers a way to check Dutch medical insurance data. The number of pages in the documentation is gigantic but there is no clear example, not even a hint, how to use the service from code. I will use TDD to explore the service and will end with the base for a simple API. The Vecozo package contains: What is lacking is the way to combine all of this to make successful requests. This is where TDD comes in. I am using nunit the mother of all unit test frameworks. My tests are located in a new class library project added to my solution. The test project references the nunit framework and the application project. In the tests I can call all public members of the application. The test code has a reference to the application I'm building but the application itself does not reference anything extra; I do not force my customer into automated testing. There are several tools available to actually run the tests, both command line and GUI versions. Resharper has a nice testrunner which integrates into Visual Studio. As an alternative Nunit contains one which looks and behaves just the same. The test have to be public classes of the new lib. The test runner instantiates objects of Classes decorated with the TextFixture attribute. Public methods in the classes, decorated with the Test attribute, contain the test code to be executed. What code the test will execute depends. A way to start could be to take existing code and automatically test metrics to check the behavior of that code. A test passes when it runs without throwing an exception. To harden a test you can conditionally raise (assertion) exceptions, the nunit Assert class has loads of usable members to do that. Designing and coding these kinds of test is not always easy. What metrics can/should you test ? What algorithm you need to assert that the test passes ? The methodology of Test Driven Development approaches the matter the other way round. The first line of code is the test itself. The implementation of the application is code built to pass those tests. Quite an eye-opener on where to start is Jimmy Nilson's book on Domain Driven Design I read last summer. At first read it chatters away, writing almost trivial code. In tests. But building test upon test a quite good application emerges. Let's give this a try on the Vecozo web service. I start writing out questions in code on what I want to build. The first question: Written out as test [TestFixture] public class VecozoWebServiceTests { [Test] public void CanCreateWrapper() { VecozoLib.ServiceWrapper o = null; Assert.IsNotNull(o); } } For the test code to build I need to write the ServiceWrapper class. namespace VecozoLib public class ServiceWrapper The code builds but the test fails. For it to pass the wrapper object has to be properly instantiated. [Test] public void CanCreateWrapper() VecozoLib.ServiceWrapper; o = new ServiceWrapper(); Assert.IsNotNull(o); This test may seem quite trivial. But it does assert that a ServiceWrapper object can be instantiated, it's constructor did not raise an exception. When refactoring the test will become even more valuable. When the constructor is refactored into a factory, the (slightly rewritten) test will assert the factory does create objects. Here's the unit testing mantra: Red, Green, Refactor. Write a test which fails, write the code to make it pass and safely refactor the code to the evolving needs. For the latter the tests will guard the code to keep working Now the first test reads green and we have a starting place. The object is going to invoke the web service. I do have an url for that so I can add a web reference. VS generates a proxy to the web service. The service appears to have one web method which does all the work. The next question is: I don't care yet whether I'm invoking it correctly, I just want to see whether the web service accepts my requests and returns something. The simplest request sends an empty list to validate. This is implemented in a new method of the service wrapper. public class ServiceWrapper public object InvokeVecozoService() vz3738 ci = new vz3738(); Console.WriteLine(ci.Url); ControleerInput requestMessage = new ControleerInput(); requestMessage.Verzekerden = new AanvraagCovType[0]; object responseMessage = ci.controleer(requestMessage); return responseMessage; Vz3738 is the webservice, the webmethod is named Controleer. Note that the method writes the url of the service to the console. All the test does is call this method. public void CanInvokeService() VecozoLib.ServiceWrapper sw = new ServiceWrapper(); object response = sw.InvokeVecozoService(); Assert.IsNotNull(response); The test fails on an exception. The nice thing is that the test runner catches the output. The url is there and also a stack trace. The message is loud and clear : no Access (Geen toegang). It's time to do something with my Vecozo certificate. Next question: I want the serviceWrapper to expose the Vecozo certificate. Written out in a test [Test()] public void ValidCertificateAvaliable() System.Security.Cryptography.X509Certificates.X509Certificate cert = sw.VecozoCertificate; Assert.IsTrue(DateTime.Parse(cert.GetExpirationDateString()) > DateTime.Now); Unless a valid Vecozo certificate is installed the test will fail. The implementation of the code to get the certificate is pretty straightforward. public X509Certificate VecozoCertificate get X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); certStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = certStore.Certificates.Find(X509FindType.FindByIssuerName, "Vecozo", false); if (certs.Count == 1) return certs[0]; else return null; } Now the test shows I do I have a certificate. But what to do with it? Sign the message? Encrypt it ? There are a lot of possibilities. The Vecozo docs are blank on this. Googling around I found the simplest thing to do with a certificate is just pass it to the service in the ChildCertificates collection of the proxy. Let's try this. public object InvokeVecozoService() vz3738 ci = new vz3738(); Console.WriteLine(ci.Url); ci.ClientCertificates.Add(VecozoCertificate); ControleerInput requestMessage = new ControleerInput(); requestMessage.Verzekerden = new AanvraagCovType[0]; object responseMessage = ci.controleer(requestMessage); return responseMessage; This simplest thing is exactly what this service demands. When the certification test passes now the connection test also passes. And now I start communicating with the service. The unit test are a great status monitor; they test the status of the certificate and the availability of the service in a single click. Now my tests can jump right into testing the domain specific features of the service itself. The Assert class of the nUnit framework has loads and loads of (static) methods to compare expected values with the actual values returned from the service. There are many ways to request data from the Vecozo web service. The documentation does give a good overview. In the next example I am requesting the data of one person based on birth date and BSN (you can compare that to a SSN). In case you are going to work with the actual web service check the documentation on this. In case you are just interested in TDD it suffices to say that the method returns some domain specific data. Note that the actual invocation of the web service has already been refactored into a (private) method. The earlier test will make sure I have done that correctly. public RetourinfoCovType PersonData(DateTime birthDate, int bsnNummer) requestMessage.Verzekerden = new AanvraagCovType[1]; requestMessage.Verzekerden[0] = new AanvraagCovType(); requestMessage.Verzekerden[0].PeildatumVerzekering = DateTime.Now; requestMessage.Verzekerden[0].SoortVerzekering = 92; requestMessage.Verzekerden[0].GeboorteDatum = birthDate; requestMessage.Verzekerden[0].BSN = bsnNummer; requestMessage.Verzekerden[0].BSNSpecified = true; return getResponseMessage(requestMessage)[0]; A simple straightforward test against the test data available to check the domain specific functionality of the code: public void IsDeceased() VecozoLib.VecozoService.RetourinfoCovType data = sw.PersonData(DateTime.Parse("1-5-1945"), 141919723); Assert.AreEqual(0, data.ResultaatcodeCOV); The assertion compares the result with 0. The test will fail. Again the output clearly tells why the test failed. The return code was not 0 but 6420. The documentation lists all return codes, where 6420 stands for deceased. Which matches the description of the test data on this "person". To make my code better maintainable I've written out a descriptive enumeration of these return codes. public enum ResultaatRaadpleging : int OK = 0, NietGeauthoriseerdBijAangegevenVerzekeraar = 6400, …… BSNvakerGevonden = 6419, PersoonIsOverleden = 6420 Using that to make the test pass: Assert.AreEqual(VecozoLib.ResultaatRaadpleging.PersoonIsOverleden, (VecozoLib.ResultaatRaadpleging) data.ResultaatcodeCOV); Here I am writing tests which describe the actual desired domain specific functionality of my app. The code I am writing to fulfill the test is code which also fulfills my customers demands. Adding all desired functionality will result in a lot of refactoring. Adding the functionality test by test will make sure that no existing code breaks in the process. So far the TDD gospel in my words. I hope to have made clear that using TDD as a methodology is nothing mysterious, just an easy way to gain and keep control over the app you are building. Nothing more, nothing less. PingBack from Yesterday Jeffrey published his 500th post without even mentioning the milestone. Scott was aware
http://codebetter.com/blogs/peter.van.ooijen/archive/2007/03/02/TDD_3A00_-Test-driving-the-Vecozo-webservice.aspx
crawl-001
refinedweb
1,637
59.6
. with a similar type to catch, except that the Prelude version only catches the IO and user families of exceptions (as required by Haskell 98). We recommend either hiding the Prelude version of catch when importing Control.OldException: import Prelude hiding (catch) or importing Control.OldException qualified, to avoid name-clashes: import qualified Control.OldException as C and then using C.catch with a similar type to try, except that it catches only the IO and user families of exceptions (as required by the Haskell 98 IO module). tryJust :: (Exception -> -> Note: this function is deprecated, please use mask instead. Applying block to a computation will execute that computation with asynchronous exceptions blocked. That is, any thread which attempts to raise an exception in the current thread with throwTo will be blocked until asynchronous exceptions are unblocked again. There's no need to worry about re-enabling asynchronous exceptions; that is done automatically on exiting the scope of block. Threads created by block mask $ \restore -> catch (restore (...)) ( mask. (...)) ( bracket_ :: IO a -> IO b -> IO c -> IO cSource Arguments Like bracket, but only performs the final action if there was an exception raised by the in-between computation.
http://hackage.haskell.org/packages/archive/base/4.5.0.0/doc/html/Control-OldException.html
crawl-003
refinedweb
196
55.54
37968/how-to-create-an-ec2-instance-in-aws-console Here is a step by step guide for creating an EC2 Instance in you AWS Console. 1. Go to Compute service in your AWS Console. Select on Launch Instance. 2. Select the type of Instance you want. 3. Select the type of storage you want for your Instance. 4. Select the VPC and subnet where you want your instance. 5. Select the capacity of your Instance. 6. You can add tags and names to identify your Instance. 7. Configure your security group to allow access to the range of audience. 8. Take a last review for the instance settings and Click on Launch. 9. Select a key pair for accessing the Instance. Create new if you don't have a key pair and click on launch Instance. It will take 2-5 minutes and your instance will be ready. This way you can launch an EC2 instance. Hope it helps. To create a snapshot of your EC2 ...READ MORE You could always use the Amazon RDS ...READ MORE As of AWS CLI v1.11.46, you can ...READ MORE Hello @Jino, The command for creating security group ...READ MORE You can use the following code, it ...READ MORE import boto3 ec2 = boto3.resource('ec2') instance = ec2.create_instances( ...READ MORE For some reason, the pip install of ...READ MORE Check if the FTP ports are enabled ...READ MORE To connect to EC2 instance using Filezilla, ...READ MORE I had a similar problem with trying ...READ MORE OR
https://www.edureka.co/community/37968/how-to-create-an-ec2-instance-in-aws-console?show=37992
CC-MAIN-2019-30
refinedweb
256
88.13
Hi! I am Abdul-Majeed. I'm a new student to c. I tried writting a game for random multiplication calculation. This was a similer questions for me in my midterm exams. I need friends to inprove it for me. You can also find faults and make corrections to my code #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <time.h> void guesgame(void); int main () { char name[30]; printf("Please enter your name:\n "); scanf("%s",name); printf("Hello! %s and welcome to Abdul-Majeed's Multiplication game\n",name); printf("Rules for the game:\n1. You will get 5 points for every correct answer\n2. You will loss 5 points for every wrong anwer\n" "3.The game will end if you score up to 100\nIt will also end when you get 3 questions wrong\nWish you good luck!!!\n"); guesgame(); getch (); return 0; } void guesgame(void) { int result,answer,x,y; int i=0,j=0; while(1) { srand(time(NULL)); x = 1+rand()%10; y = 1+rand()%10; result = x*y; printf("%d * %d = ",x,y); scanf("%d",&answer); if (answer == result) { printf("\nGood you had it ryt! you have 5 points\n"); i +=5; } if (answer != result ) { printf("\noops! it's wrong. you get -5\n"); j -=5; } if(i == 100 || j == -15) { printf("Sorry you have no more chance\n\n" "Thank you for playing Abdul-Majeed's game\n\n" "Your Total points = %d\n",i); getch (); } } }
https://www.daniweb.com/programming/software-development/threads/494628/high-school-game
CC-MAIN-2017-17
refinedweb
247
77.13
Converting Excel to PDF with .NET excel component is so popular that we always try our best to improve our Spire.XLS better and better. We aim to make the function more powerful and support more elements in Excel worksheets. Now besides the previous method of converting Excel to PDF offered by Spire.XLS, we have updated the feature of excel conversion to PDF. With this new updates, more elements in Excel file can be converted to PDF successfully, such as chart, shape, smart art and etc. You only need three lines of code to accomplish the conversion work. Firstly, Download Spire.XLS for .NET (version 7.3.21: Load an excel workbook from the file. Workbook workbook = new Workbook(); workbook.LoadFromFile(@"..\..\Sample.xlsx", ExcelVersion.Version2010); Step2: Save the document to file in PDF format. workbook.SaveToFile(@"..\..\result.pdf", Spire.Xls.FileFormat.PDF); You will get the PDF file which is almost the same with the original file: The full codes: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spire.Xls; namespace ToPDF { class Program { static void Main(string[] args) { Workbook workbook = new Workbook(); workbook.LoadFromFile("Sample.xlsx", ExcelVersion.Version2010); workbook.SaveToFile("result.pdf", Spire.Xls.FileFormat.PDF); } } }
http://www.e-iceblue.com/Tutorials/Spire.XLS/Spire.XLS-Program-Guide/Excel-Conversion/NET-Excel-New-method-of-Convert-Excel-to-PDF.html
CC-MAIN-2015-11
refinedweb
203
53.27
else if (request.method === 'GET' && request.url === '/docs') { let pdfManual = path.join(__dirname, "manuals/EV3.pdf"); let stat = fs.statSync((pdfManual)); response.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Length': stat.size }); let readStream = fs.createReadStream(pdfManual); readStream.pipe(response); } else { <ej-pdfviewer [(serviceUrl)]="service" id="pdfviewer" style="width:100%;min-height:100%"> </ej-pdfviewer> import {Component, Input, OnInit} from '@angular/core'; @Component({ selector: 'hmi-pdf-viewer', templateUrl: './pdf-viewer.component.html', styleUrls: ['./pdf-viewer.component.css'] }) export class PdfViewerComponent implements OnInit { service: string; constructor() { this.service = ''; } ngOnInit(): void { } } Hi Sabari, Thanks for your answer. So that's not the way to go for me. I read in the docs that the javascript PDFViewer supports loading, form disk, Stream and Byte Array. What about the local from disk option or Byte Array? I suppose i can use the PDFViewers load function to load an local PDF. I have tried this in my angular template but it complains it cannot find the load function. for example: html template: <ej-pdfviewer [(serviceUrl)]="service" id="pdfviewer" style="width:100%;min-height:100%"> </ej-pdfviewer> And in the TypeScript File: ngAfterViewInit() { let elem = document.getElementById("pdfviewer"); elem.load('localfile.pdf'); // file or url ? } The apidocs: pdfviewer load get the container where the pdfviewer is created. But i cannot get this to work in Angular 4 where I use the element selector <ej-pdfviewer > ... Also tried to get the element with <ej-pdfviewer #pdfElem ...... and the tried to get the element in Typescript: pdfElem.load('localfile.pdf') But this does not work either. Could point me in the right direction to load an PDF this way, this would also solve my problem to handle PDF documents voor now, even better a way to handle the docs as byte Array or Stream, this way i can first download them to my client or create an stream from my backend. Thanks for the help. Kevin Hello Sabari, Thanks for the clarification. Te webservice project helped me figure out the post link to request the PDF. I rewrote it to nodejs/Express backend: / --------------------------------------------------------------------------------------------------------------------- // CREATE EXPRESS SERVER AND INITIALIZE SOCKET IO // --------------------------------------------------------------------------------------------------------------------- app.get('/', (req, res) => { res.send(`Hello client 2`); }); app.options('/manuals/Load', cors()); app.post('/manuals/Load', cors(), (req, res) => { console.log(req); let pdfManual = path.join(__dirname, "manuals/DS4.pdf"); // let pdf = pdfManual.toString('base64'); let readStream = fs.createReadStream(pdfManual); readStream.pipe(new Base64Encode()).pipe(res); }); The cors function takes care of the headers defined in the web.config file: <customHeaders> <add name="Access-Control-Allow-Headers" value="accept, maxdataserviceversion, origin, x-requested-with, dataserviceversion,content-type" /> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Max-Age" value="1728000" /> </customHeaders> With Base64Encode I encode the pdf to a base64 string as stated in your answer: We can load the PDF document as a path from the local disk, stream or byte array on the server side (Web API controller) while loading the PDF viewer control initially. On the client side, we support to load PDF documents as string (file path of the PDF document) and base64 string (PDF document data as base 64 string) into the PDF viewer control. Now when the pdf viewer initilizes in my angular project: <ej-pdfviewer [(serviceUrl)]="service" id="pdfviewer" style="width:100%;min-height:100%"> </ej-pdfviewer> It gets the pdf as an base64 encoded string: But it's not loading in the PDFViewer control. Can you help me get the last peace of the puzzle complete? I don't know which extra info/code i need to provide. The main peaces are in the code above and in my first post. Thanks for support Hi Sabari, I cannot get it to work. I implemented the sample code and reading in the PDF works fine. loadPDF(pdfFileName: string): void { this.httpservice.getPDFFile(pdfFileName) .subscribe( (response) => { // console.log(response.blob()); let reader = new FileReader(); reader.readAsDataURL(response.blob()); reader.onload = () => { let pdfViewerObject = $("#pdfviewer").ejPdfViewer("instance"); let pdfFile = reader.result; console.log(pdfFile); pdfViewerObject.load(pdfFile); } }, (error) => console.log(error) ); I made an call to the backend server (pdfviewer is requesting a path with Load) and im sending back the PDF as blob. If i then console log it (console.log(pdfFile)) it nicely prints out the PDF. Now the magic happens: When i load the pdf in the PDFViewer its makes an request to the server again and sends the pdf as an Base64 encoded string to the path ***/FileUpload. My questions are: 1) Why is the control sending back the base encoded string to the server an not loading it directly if it supports base64 encode strings 2 ) After viewing back the controllers example. The FileUpload function process the pdf on the server: why is this nessesary if it already knows the base64 encode pdf from the FileReader(); 3) Does the controller does something special with the PDF or structure of the response (eg. application type, application size) in the backend or is the control using native PDF. if so i do not understand why it is not loading the the encoded pdf string natively. Could you maybe provide some structure the controller sends back with the Load and/or FileUpload functions. If thats clear in can improve my NodeJS backend (I'm not using a .NET backend) to send the correct peaces to the control. Or maybe the control can directly load the base64 encode PDF without sending it for processing to the backend again? Hi, I did some experimenting but cannot implement the backend with nodejs. I have to take this another route. Thanks for support and explaining the principle. This post will be permanently deleted. Are you sure you want to continue? Sorry, An error occured while processing your request. Please try again later. This page will automatically be redirected to the sign-in page in 10 seconds.
https://www.syncfusion.com/forums/132064/loading-pdf-from-nodejs-backend
CC-MAIN-2019-39
refinedweb
974
58.99
MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts. from math import floor import sys s = sys.argv[1] middle = int(floor(len(s)/2)) for i in range(middle): print s[i], if len(s) % 2 == 1: print s[i+1], for i in range(middle): print s[-i + middle - 1], def mirror(s): s = s[:len(s)//2] # take the first half of the string return s + ''.join(reversed(s)) # concatenate with the reversed string print mirror('COMPUTER') print mirror('PYTHON') If you are experiencing a similar issue, please ask a related question Join the community of 500,000 technology professionals and ask your questions. Connect with top rated Experts 11 Experts available now in Live!
https://www.experts-exchange.com/questions/26839937/How-do-I-mirror-text-in-Python.html
CC-MAIN-2017-09
refinedweb
149
61.56
Remove an element from a vector Is there a simple way to remove an element from a Vec<T>? There's a method called remove(), and it takes an index: usize, but there isn't even an index_of() method that I can see. I'm looking for something (hopefully) simple and O(n). This is what I have come up so far (that also makes the borrow checker happy): let index = xs.iter().position(|x| *x == some_x).unwrap(); xs.remove(index); I'm still waiting to find a better way to do this as this is pretty ugly. Note: my code assumes the element does exist (hence the .unwrap()). vector::erase - C++ Reference, All the elements of the vector are removed using clear() function. erase() function on the other hand, is used to remove specific elements from the container or a vector::erase () 1. Run a loop till the size of the vector. 2. Check if the element at each position is divisible by 2, if yes, remove the element and decrement iterator. 3. Print the final vector. You can use the retain method but it will delete every instance of the value: fn main() { let mut xs = vec![1, 2, 3]; let some_x = 2; xs.retain(|&x| x != some_x); println!("{:?}", xs); // prints [1, 3] } vector erase() and clear() in C++, If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while the vector::erase Removes from the vector either a single element (position) or a range of elements ([first,last)). This effectively reduces the container size by the number of elements removed, which are destroyed. Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. Your question is under-specified: do you want to return all items equal to your needle or just one? If one, the first or the last? And what if there is no single element equal to your needle? And can it be removed with the fast swap_remove or do you need the slower remove? To force programmers to think about those questions, there is no simple method to "remove an item" (see this discussion for more information). Remove first element equal to needle // Panic if no such element is found vec.remove(vec.iter().position(|x| *x == needle).expect("needle not found")); // Ignore if no such element is found if let Some(pos) = vec.iter().position(|x| *x == needle) { vec.remove(pos); } Remove last element equal to needle Like the first element, but replace position with rposition. Remove all elements equal to needle vec.retain(|x| *x != needle); ... or with swap_remove Remember that remove has a runtime of O(n) as all elements after the index need to be shifted. Vec::swap_remove has a runtime of O(1) as it swaps the to-be-removed element with the last one. If the order of elements is not important in your case, use swap_remove instead of remove! Difference between std::remove and vector::erase for vectors , In this article, we will go through multiple ways to delete elements from a vector container in C++ STL like pop_back, pop_front, erase, clear, remove and more. Since std::vec.begin() marks the start of container and if we want to delete the ith element in our vector, we can use: vec.erase(vec.begin() + index); There is a position() method for iterators which returns the index of the first element matching a predicate. Related question: Is there an equivalent of JavaScript's indexOf for Rust arrays? And a code example: fn main() { let mut vec = vec![1, 2, 3, 4]; println!("Before: {:?}", vec); let removed = vec.iter() .position(|&n| n > 2) .map(|e| vec.remove(e)) .is_some(); println!("Did we remove anything? {}", removed); println!("After: {:?}", vec); } Different ways to remove elements from vector in C++ STL, Erasing an element from a vector. Ex: v.erase(v.begin()+4); (erases the fifth element of the vector v). erase(int start,int end): Removes the elements in the range std::remove does not actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase to do the REAL removal of the extra elements that are now at the end of the container: std::vector<int> vec; // .. put in some values .. int int_to_remove = n; vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end()); If your data is sorted, please use binary search for O(log n) removal, which could be much much faster for large inputs. match values.binary_search(value) { Ok(removal_index) => values.remove(removal_index), Err(_) => {} // value not contained. } Vector-Erase, Since calling the erase() method on the vector element invalidates the iterator, special care needs to be taken while erasing an element. We can do that in many I just want to remove all the appearances of elements of A from the data vector. I gave the example [1,2] . The element 1 for example might appear 1000 (or not at all) times in data vector, and I want to delete all of them, and same for 2. Remove elements from a vector inside a loop in C++, vector::erase() is a library function of "vector" header, it is used to erase/delete elements from the vector, it either removes one element from a delete element from vector. Learn more about delete element from vector, cheat sheets vector::erase() function with example in C++ STL, Remove an element from C++ std::vector<> by index can be done by following way −Example Live Demo#include #include using namespace Removing an element from C++ std::vector<> by index?, pos, -, iterator to the element to remove. first, last, -, range of elements to remove. Type requirements. -. T must meet the requirements of The java.util.vector.remove (int index) method is used to remove an element from a Vector from a specific position or index.
http://thetopsites.net/article/53636248.shtml
CC-MAIN-2020-34
refinedweb
1,014
64.1
On Thu, 8 May 2003 12:30 am, Costin Manolache wrote: > > The URI however should be chosen by the antlib author ( maybe based on some > rules specific to ant ), and should serve as an ID of the library. > > My proposal is to use the (main) package name. There are other options - > but I don't think every end user using it's own name for an antlib is a > good one. > +1 I believe the URI should be defined by the antlib builder, not the user. It should be opaque - no semantic structure, at least from Ant's processing. An antlib should just declare to what namespace URI it belongs and then that antlib's defs would be accessible through that namespace in the build file. This would allow multiple antlibs to belong to a single namespace, which might be useful for extension purposes. So, something like this <antlib uri="blah"> <taskdef> <typdef> </antlib> Antlibs could potentially declare themselves to belong to the default namespace. This would handle Ant's existing optional tasks. This facility might be restricted to antlibs found in a particular location. A classloader could probably be associated with the URI, picking up all antlibs declaring the URI. Just some thoughts Conor
http://mail-archives.apache.org/mod_mbox/ant-dev/200305.mbox/%3C200305080939.07395.conor@cortexebusiness.com.au%3E
CC-MAIN-2016-26
refinedweb
205
71.65
Today there is a huge number of software development methodologies - TDD, BDD, Scrum, etc. Part of them refers to development process, another part to development management, and there are also methodologies defining which code to use in this or that case. One of these high-level methodologies is design pattern. This methodology is a set of some agreements and recommendations on code writing in certain situations, irrelevant to a programming language. To simplify the communication between developers, each recommendation has a name of its own - Singleton, Observer, etc. Such an approach is particularly useful, because irrespective of a language used by a programmer, an abstract task has an abstract solution clear for those familiar with Design Patterns. In this article, we are taking a look at one of design patterns, namely Singleton. Our purpose is to implement this pattern in Python in order to use it in Django project. So, what is Singleton design pattern? As it is written in the book “Design Patterns: Elements of Reusable Object-Oriented Software” by Gang of Four: The singleton pattern is a design pattern that is used to ensure that a class can only have one concurrent instance. Whenever additional objects of a singleton class are required, the previously created, single instance is provided. This is the class that controls the process of its instantiation by itself, hiding a usual constructor, and offers a method for obtaining an instance instead. The first time this method is called, an instance of a class is created, which is returned for all subsequent method calls. This is one of the most simple design patterns, but not the least useful. Most of the times it is used to coordinate the whole system. It can be a settings object, a connection object or session object, etc. What is important in this case is that at any moment we cannot have more than one Singleton object. At first glance it may seem easier to use global variables, but it’s misleading. Although global variables don’t require the implementation of a special instantiation mechanism like Singleton, they are also less reliable. For example, if you store a lot of settings in global variables, then the probability of names conflicts increases, especially so when writing the library which is going to be used in other projects. It won’t be better if an instance of a class is stored in the global variable. Yes, there will be one globally available instance and, at first glance, it isn’t any different from a singleton, but in this case the instantiation of a class is not limited in any way. Suppose we have a process configuration class. Everything goes well as long as it is used by accessing a global variable. However, everything can go wrong if the library user instantiates this settings class themselves and changes some of its properties either by accident or due to the lack of knowledge. Most likely, its settings simply won’t be applied or will affect the part of the process. Debugging of such non-obvious mistakes may take up a lot of effort and time. How to use singleton design pattern The above mentioned problems could be avoided when using Singleton pattern. In most strongly-typed programming languages such as Java and C#, a singleton is implemented with the help of built-in tools of the language to restrict access and visibility. The idea is that the class constructor is declared as private or protected, and the class is added with the public static method (usually known as instance()), which calls this constructor in the first call and always returns one and the same instance of a class. In Python almost all properties and methods are public, therefore the classic approach can’t be used. At Stack Overflow you can see a small selection of recipes for implementing a singleton in Python (there are indeed some elegant and interesting solutions among them!). To put it simply, we just use a simple class method, calling the standard constructor if necessary. Using Django singleton model Although you can use singletons in the form of ordinary classes in Django applications, let’s take a look at the implementation of a singleton as a model which allows you to save the internal state of the singleton in the database. In our singleton design pattern example, we will show how to implement some project settings in such a way that they can be changed in the admin panel and can be used in templates. This example can be used in a production environment if there are few such settings or if some business logic is implied in this model. Otherwise, a ready-made solution should be used. For example, there is this great, popular and well-maintained Django application — Constance To begin with, we declare the base class for our singleton model in django: from django.db import models class SingletonModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) def delete(self, *args, **kwargs): pass @classmethod def load(cls): obj, created = cls.objects.get_or_create(pk=1) return obj When you call load method, an object will be loaded from a database or, if the object does not exist in a database, it will be created. When you save an instance of the model, it always has the same primary key, so there is only one record for this model in the database. Thus, in order to create a class responsible for site settings, we will create a class based on an abstract SingletonModel. This is a base class for Singleton model. When you call load method, an object will be loaded from a database or, if the object does not exist in a database, it will be created. So, in order to create a class responsible for site settings we will create a class based on an abstract SingletonModel. class SiteSettings(SingletonModel): support = models.EmailField(default='support@example.com') sales_department = models.EmailField(blank=True) twilio_account_sid = models.CharField(max_length=255, default='ACbcad883c9c3e9d9913a715557dddff99') twilio_auth_token = models.CharField(max_length=255, default='abd4d45dd57dd79b86dd51df2e2a6cd5') twilio_phone_number = models.CharField(max_length=255, default='+15006660005') To be able to edit settings we should register a model in django admin panel: from django.contrib import admin from .models import SiteSettings admin.site.register(SiteSettings) Now we can use created settings object in the following way: from .models import SiteSettings settings = SiteSettings.load() When we use load method, an object will be taken from a database, and in case it was not created yet, it will be added to a database with default values. Thus, to get a working application from the start, we have to specify default values in settings or add blank=True, null=True attributes and to process such exceptions further. From Python’s perspective it is not yet a singleton, because every call load() will create a new object in the memory. However, since each one of them refers to the same record in the database, users of the singleton model are satisfied with it. To be able to use data from settings in the pattern, you can add an object of settings either in context of view or context processor. context_processors.py from .models import SiteSettings def settings(request): return {'settings': SiteSettings.load()} Now let’s connect context process to settings.py: TEMPLATES = [ { ... 'OPTIONS': { ... 'context_processors': [ 'common.context_processors.settings', ... ], }, }, ] After this we can use our settings in templates in the following way: Support: {{ settings.support }} {% if settings.sales_department %} Sales Department: {{ settings.sales_department }} {% endif %} To reduce the amount of database requests, you can save settings to cache. For this let’s add method set_cache to the model. from django.core.cache import cache class SingletonModel(models.Model): ... def set_cache(self): cache.set(self.__class__.__name__, self) Let’s update save and load methods: class SingletonModel(models.Model): ... def save(self, *args, **kwargs): self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) self.set_cache() @classmethod def load(cls): if cache.get(cls.__name__) is None: obj, created = cls.objects.get_or_create(pk=1) if not created: obj.set_cache() return cache.get(cls.__name__) Conclusion We hope that now you know a bit more about a fascinating world of design patterns in Python, having read the information about the Singleton design pattern. Also, we applied the singleton pattern to web applications and implemented Django singleton model for storing some of project's frequently used settings, added settings context processors, optimized settings to reduce database requests using standard caching. We received the answers on how exactly to implement configurable settings via admin panel and how to solve such problems. The final code is available on Github.com.
https://steelkiwi.com/blog/practical-application-singleton-design-pattern/
CC-MAIN-2019-39
refinedweb
1,447
55.24
How to use arguments and return codes¶ Arguments and return codes are not really useful in a true embedded application, since a user is not present to provide them or react to them. However, they are particularly useful during unit and regression testing, as they allow tests to be configured and pass/fail results returned simply. Note The facility to use arguments and return codes is only available for a single tile application; an application with a main() function written in the C language. It makes no sense for a multi-tile application (with an XC main() function) to use arguments and return codes, because there is no mechanism to define which is the ‘master’ tile, nor define how it should distribute the arguments and collate the return code. Therefore this tutorial is suited only to single tile testing. To add command line arguments, create a main() function with the usual prototype: #include <stdio.h> int main(int argc, char* argv[]) { for (int x = 0; x < argc; x++) printf("Arg %d %s\n", x, argv[x]); return argc; } Build with a non-zero value for xcc -fcmdline-buffer-bytes: $ xcc main.c -target=XCORE-200-EXPLORER -fcmdline-buffer-bytes=1024 Note If you forget to the -fcmdline-buffer-bytes parameter, then a buffer of size zero will be allocated, and argc will always hold a value of zero. No error or warning will be raised. So don’t forget! Run with using xrun --args, and examine the return code: $ xrun --io --args a.xe giraffe elephant Arg 0 a.xe Arg 1 giraffe Arg 2 elephant $ echo $? 3 Similar behaviour can be found using xsim --args and xgdb --args.
https://www.xmos.ai/documentation/XM-014363-PC-4/html/tools-guide/tutorials/args-and-ret-codes.html
CC-MAIN-2022-21
refinedweb
279
61.26
[ ] Alexey Varlamov commented on HARMONY-3684: ------------------------------------------ Jimmy, I looked through the suggested patch and see no much value added: there are the same nasty casts and no promised optimizations: public PlatformAddress getBaseAddress() { return ((DirectBuffer) byteBuffer).getBaseAddress(); } If you still wanna improve this ;), I'd suggest the following: 1) move those asXXXBuffer() methods from BaseByteBuffer to specific childs - then maybe even drop this class altogether (it only provides 4 trivial methods besides the above); 2) keep that wrapped buffer instance as more specific type, e.g. private final DirectByteBuffer byteBuffer; 3) Look if there are indeed some possibilities to optimize operations, via shortcut package methods or such. PS. - I wonder why nio.Buffer classes hierarchy is so lavish,e.g. lot of classes like ReadOnlyXXX and ReadWriteXXX. Does it really benefits performance that much or smth else? At first glance, simple bool flag would do just fine... > [classlib][nio]Refactor and define direct buffer adapters > --------------------------------------------------------- > > Key: HARMONY-3684 > URL: > Project: Harmony > Issue Type: Improvement > Components: Classlib > Reporter: Jimmy, Jing Lv > Attachments: Harmony3684.zip > > > As discussed on Harmony3591 and mailing-list, the patch of 3591 is workable but not perfect. Define new direct buffer adapters may help to improve infrastructure and code read-ability. -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.apache.org/mod_mbox/harmony-commits/200704.mbox/%3C31193124.1177065675956.JavaMail.jira@brutus%3E
CC-MAIN-2017-13
refinedweb
223
55.03
I've read some docs on it and it seems very dirty to me. To elaborate, too many things are implicit and there are many built-in global functions (like len(), for example). Having built-in functions reminds me of the days of Pascal. Now, I said that too many things are implicit and here is an example of this: Any type, variable, constant of function of a package is public if and only if its name starts with an Uppercase letter. Also, some things are not logical to me. For example: Why not just Functions can return more than one value (which is cool) like this: A function that returns only one value looks like this: So, I ask, why do we need parentheses when returning more values? Why can't we just write this: Now, I don't want to be all critical. There are some good aspects of the language and some interesting ideas. Those implicit things I mentioned have an up side as well. Once you know the language well, I guess you can write code very fast. Also, the Go code compiles very fast. It's worth noting that it is a compiled language like C and yet it features many things from languages like Java, namely Garbage Collection and (I think) Reflection. Oh, and by the way, the Go does not seem to be object-oriented (I am not sure.) and does not support exceptions... Thanks for reading, and I would like to hear your comments of this. Rob Pike and Ken Thompson, who are leading the project, worked together previously on Plan 9 at Bell Labs, which had a similar looking mascot: It wouldn't surprise me if this one was also drawn by Renee French (Pike's wife). Edited 2009-11-11 19:28 UTC). OK. That is Prototype-based programming which is a kind of OO, but I don't see how is that more object-oriented than Java. Is JavaScript more OO than Java? Unlike Go, in Java everything is an object and although you could write a procedural Java code by putting everything in one static class, all those "static" keywords scream that you are doing it wrong. In Go, however, you can write very C-like procedural programs without even knowing that you can make objects. The point is, I still don't know how Go can be considered more OO. In fact I argue that it is, in fact, just the opposite. OO is (mostly) about leveraging polymorphism to create flexible code. Inheritance based polymorphism is probably the most tightly coupled and rigid form of polymorphism. It's not something you really get until you fully implement something in a language that is not class oriented the way that most of the c++-ish systems languages are. Really grokking something like ruby or smalltalk will totally change the way you look at these things. Also, dynamic dispatch + duck typing does not nessicarily mean prototypal. For example, ruby is a strongly typed language where objects can (and often do) vary from their type. In js, you can do "".prototype.foo = new function() { .. } that will add foo to all instances of string. in ruby, attaching a method to the string class is one option, another is to attach it to the instance, like s = "" def s.foo .. end s.foo # calls method "".foo # method not found, only exists on s Anyways, all that to say that while prototypal programming is one way to do this sort of thing, doesn't mean there aren't others. Java's OO semantics have deficiencies that Go solves. To me it is equivalent to "Go can be considered more OO". It doesn't mean that Java is bad - it's actually my favorite system-level language. But that's mostly because of its robust frameworks and the fact I've learned to live with its limitations. The Java OO deficiencies (those that matter to me) are: - non-OO primitive types, - no multi class inheritance (for a good reason - it can get messy very quickly), - limited interfaces (the only way to implement an interface is to write it by hand or inherit it from a (single!) base class). Go simply doesn't have these limitations. I agree with you that one can write procedural programs in Go (and Java, C++,...). However, this doesn't make the language non-OO, it's just user's choice not to use these capabilities. --- Sorry about my comments regarding the Go syntax issues. I just can't help thinking that even a bad syntax (which it isn't) is at worst a nuisance.. "func foo(i int) a, b int {} " I find that especially odd, since control structures (if, for, ...) do not use parentheses, and "Go needs fewer parentheses" is listed as an advantage of Go's formatting. Of course, apart from that, Go might still be a nice language. Functions can return more than one value (which is cool) like this: "func foo(i int) (a, b int) {} A function that returns only one value looks like this: So, I ask, why do we need parentheses when returning more values? Why can't we just write this: " I'm not sure if there are any technical reasons, but IMHO the parentheses make it more obvious that it's all part of the return type. Oh, and by the way, the Go does not seem to be object-oriented (I am not sure.) and does not support exceptions... Go is fairly object-oriented, although a little differently from c++/java (no type hierarchy). Still, it has methods, interfaces, and the like. As far as exceptions, the FAQ suggests that the authors are leaving it as an "open issue" for now, so they might still enter in some form, I guess. While the lack of exceptions and generics/templates (also an "open issue") make me a little worried, Go still seems like a nice improvement over C for most programs. I'm surprised they didn't make a bigger deal of Go's support for proper closures (at least according to the spec) and anonymous functions, though - making C++ functors is quite painful. I think it's pretty impressive to devise a wholly new programming language intended to compete with the "major languages" of today. Its major benefit: being just two years old (project started in 2007), rather than twenty (or forty, with some regenerations). This should have the potential of being headline news. It remains to be seen how this language finds its way into the programming world. I'm missing a book (open-source of course) that teaches starting developers how to go about their way with Go. Fortunately, at this point, their connection for existing developers (mainly C/C++) is really decent. I'm downloading the TechTalk video just now, it ought to be an interesting watch on my way home. After reading the tutorial, I can say that it is already dead for me. Compared with mainstream languages, and languages that are currently gaining momentum as well, Go doesn't have much to offer. And several syntactic elements look real strange, as many people already noted on the forums. I won't care about it. I think the designers of Go placed too much emphasis on fast compilation speeds. Apparently during early development they rejected a LLVM based solution because of slow compilation speed. Is compilation speed really that important? Maybe they should have gone the GHC route and provided a compiler and interpreter bundle. The GHC compiler can be a little sluggish sometimes, but the interpreter allows for quick iterative development by quickly catching all compile time errors when you load a source file. Leaving the slower, heavyweight compiler mainly for compiling optimized release builds rather then testing and debugging. flynn wrote: "I think the designers of Go placed too much emphasis on fast compilation speeds. Apparently during early development they rejected a LLVM based solution because of slow compilation speed. Is compilation speed really that important?" This language was written to scratch Google developer's own itch, so compile times were obviously an important factor for them. I like seeing a new language aimed at system level programing, glancing at the syntax it looks like it's based on c. The language itself has some nice properties, like corout...(oops) goroutines with an outspoken aim of easing programming for concurrency, multithreading (which I guess will be it's biggest draw). Being targeted at system level programming performance will obviously be important and using automatic garbage collection is more expensive than manual, however great development has been made in the field of garbage collecting so it will be interesting to see what it performs like (anyone know what method they use?). Anyway, good to see a new non-managed language, I'll reserve further judgement until I've actually tried it and had a chance to see what the performance is like. Saying that it is 'near' c speed doesn't really say that much since 'near' can be VERY broadly defined as we've seen in the past. It's really debatable whether the cost of automatic garbage collection is more than that of manual memory management, especially as the size and complexity of the program grows. I used to be firmly in the manual camp, but these days, it seems to be better to let the machine keep track of your memory, especially if correctness is required. That said, Go's garbage collector is (currently) based on a very primitive mark and sweep algorithm. It's basically a child's toy compared to the generational, iterative, compacting collectors found in the JVM and CLR. It's certainly interesting for language geeks, and I've spent too much time already digging through it because I like these things, but I don't see a new non-managed language truly having much use going forward. The ability to distribute a single binary that can run on (and be optimized for) x86, AMD64, PPC, MIPS, Arm, etc has too many advantages to ignore. And there is no denying that the potential for optimization in a JIT compiler far exceeds that of a static compiler-- even if we're not quite there yet. Edited 2009-11-12 00:40 UTC I will never understand languages that decide to break conventions. Maybe the 'new' way is marginally better, but is it worth mucking with the mind of developers who have to code in multiple languages. var v2 string; // const std::string v2; var v3 [10]int; // int v3[10]; oh jeez, let's put the type after the name to be opposite of C. I find myself working with java and C# and have to second guess myself every now and then where the array [] goes. In C# (int[] arr1; ). In java String s[]; Now we have another permutation on something rather irrelevant. They kind of address this in the lang design faq, but not directly, and its more to do with multiple declarations on the same line. On the good side, I like their native support for Go Routines (threads), Go Channel (Message passing), unit testing Always good to see another language though. I'll see if their *quick* compile time really plays out. Knowing Google... it probably does. In java - String[] s; and String s[]; are equivalent - one of the few odd places in java where there are two ways of doing exactly the same thing. " Right. Java convention prefers the former, since it arguably makes a lot more sense to keep the type information together. But the compiler accepts both syntaxes... It seems to me like a cross between Smalltalk and C with better concurrency features. [OT] I really have enjoyed working with the D programming language lately. D is a systems programming language that more similar to C++ than any other language, but IMO D is much nicer that C++. [/OT] I love this: In other words, "We desire for the open source community to write free sh*t for us." I don't write open source software for a living, but if I did, I'd be sort of offended by this. Here's a novel idea... if they need more coders/testers, why don't they hire some, instead of expecting the open source crowd to do it for $0? Of course, I realize that not everybody is in it for the money, but if you're going to write/test code for a for-profit company, you should expect to be paid for it, IMHO. ... Of course, I realize that not everybody is in it for the money, but if you're going to write/test code for a for-profit company, you should expect to be paid for it, IMHO. Developers would not be writing and testing for a for-profit company. They would be writing and testing for an open-source project which they and others presumably find useful. "Others" being Inclusive of Google, of course, which did the major grunt work to get the project this far, and released into the OSS community. I'm not a current Go developer at Google, but if I were, I'd be offended by your ingrateful post. Edited 2009-11-11 19:50 UTC If you don't want to contribute, don't contribute. Simple as that. Though neither of you seem like the sort of people who contribute code to OSS projects, anyway. Am I right? As the score stands now regarding this project, it's Google and its paid employees which have done all the contributing. Edited 2009-11-12 17:01 UTC i think problem with Go is that it is initially designed by two old (maybe long bearded) respectable unix guys. But because of their mind set Syntax seems cryptic and somewhat too low level - alien. i wish they got two higher level masters from Google into their group (Rossum and Bloch). I also wish Google came up with next generation Java instead.. Rob Pike give a 1hr talk on Go on Oct 30. Google isn't the first to call a programming language Go. Here's a link to the other Go's book. From Wikipedia: --------------------------------------------------------- It should be noted some issues with google's choice of name "Go" is in conflict with that of a previously released programming language called "Go!" by F. G. McCabe and K. L. Clark in 2004. The naming issue is discussed on Google's Go page, with current popular consensus that it should be renamed as "Issue 9" --------------------------------------------------------- I assume "Issue 9" is a loose reference to Plan9. Loose reference yes. Also a direct reference to the fact that the name conflict is issue 9 in the google code issue tracker for the go language project: I really like their approach on polymorphism and concurrency! It looks, to me, like a mix of Objective-C and Java. I had wished for something like this would be supported by Java as I mostly prefer composition to sub-classing. Even James Gosling seems to agree: Some aspects of this language seem really nice, especially the concurrency support and speed. I don't particularly like the syntax, but it's alright. However, one feature I really can't live without is generics. If they added generics I'd probably start using it right now for all my projects. I find coding in languages without dynamic dispatch and type inference nowadays feels like working with a chisel on stone when you are used to a paintbrush on canvas. It is fantastic to see someone (other then scala) bring this to a systems language, and the fact that it is unmanaged makes it downright unique. Also, compiling 120k lines of code in 8 seconds, and 1k lines in 20 milliseconds is downright delightful. Compiled languages tend to be horribly unproductive when working through the refactor/compile/test cycle compared to languages that take out the middle step. They are pretty far from prime time still (standard library seems rather anemic), but I think this is one of the most interesting new languages I have seen in a very long time. If they are able to match c performance with those kinds of features, all the current systems languages will have going for them is the mountains of existing code already written in them. solving concrete low-level programming problem? Edited 2009-11-12 13:50 UTC using concrete low-level programming problem? Edited 2009-11-12 14:03 UTC It looks like a remake of the Limbo programming language (part of the Inferno operating system It was also conceived by Kernighan, Ritchie & Pike while they were at Bell Labs...... semi-C syntax + concurrency - delegation/inheritance 0. The whole "type after variable" feels very weird in this as compared to other languages which do the same. 1. No inheritance or delegation.. It seems to have the Dylan (and CLisp) style of decoupling the class from the methods; but I really find the method syntax confusing. func (this Class) method(arg1 Arg1, arg2 Arg2) Ret {} It looks clean but I keep getting mixed up on lot of occassions. The new C++0x syntax on the other hand: [] Class::method(Arg1 arg1, Arg2 arg2) -> Ret {} While more senile, I actually find it easier to read. 2. The mechanism for maps was very awkward to me. Although I don't think it offers anything new. Also I don't quite get how it can have C++ like speeds.. I had thought about it.. It's (probably) not like templates. The deal is; first I thought it was the (removed) C++0x Concepts i.e., interfaces for templates -- which is *exactly* the same as this (cept for the extra syntax). But if it's like implicit C++ concepts, then every time you pass an object of a different class it would compile a new function meant specifically for that class. Considering how there's no inheritance, that would seriously increase the executable file size.. The alternative is that it's similar to pure-virtual classes, which wouldn't give it C++-template like speeds.. I trust they have something clever cooked up for this. It may also be that google doesn't care about the size that much. It's also very possible to use polymorphic vtables for this. Just create a different per-class vtable for every interface the class implements. Instead of speculating I'd rather just wait for someone to explain what exactly they are doing ;-). It's also very possible to use polymorphic vtables for this. Just create a different per-class vtable for every interface the class implements. Instead of speculating I'd rather just wait for someone to explain what exactly they are doing ;-).... Ah, that's *exactly* what I was trying to say earlier but I wasn't sure if I had the right words... Nevertheless, that means it is as efficient as "virtual C++". Which would also explain the benchmarks:... Which would also explain the benchmarks:〈=go&... There is no point wasting too much time on benchmark comparisons right now, esp. for the "6g" compiler which doesn't optimize seriously yet. Go by no means forces you to use interfaces, direct method calls don't go through the interface jump table. No, but it sure gives one a rough estimate of how 'fast' a language because I don't think optimizations can contribute to a great change in it, especially because it's not like Java or C# which has a complex type system or so, but then I'm not so knowledgeable in this area. Also, interfaces are not used in that submitted code (which is by the Go creators).. I'm just sceptical about the "as fast as C" claims when the languages are of much higher-level. And Go is sufficiently high level. After optimizations I expect it to optimistically meet the speeds of C# Mono implementation but not too much more than that.. Edited 2009-11-14 15:37 UTC
http://www.osnews.com/comments/22478
CC-MAIN-2016-40
refinedweb
3,353
71.14
Description of Problem: Auto-Fix should hint some fixes: Steps to reproduce the problem: 1. Create a console application 2. Paste this code as starting point: using System; namespace TestConsole { class MainClass { public bool AreAllNumbersPrime (List<int> items) { bool result = true; foreach (var item in items) { if (item < 4) continue; if(item%2==0) { result = false; break; } for (var i = 3; i < item / 2; i += 2) if (item % i == 0) { result = false; break; } } Console.WriteLine(result?"All numers are prime":"Some numbers are not prime"); return result; } public static void Main (string[] args) { var items = new List<int>{2,3,5,7,11,13,17,19,23,29,37}; var main = new MainClass (); main.AreAllNumbersPrime (items); } } } 3. Set the cursor to the word: AreAllNumbersPrime; for line: public bool AreAllNumbersPrime (IList<int> items) 4. Press Alt+Enter to show quick fixes 5. Select the first option Expected result: Function AreAllNumbersPrime does not access This pointer either via fields call or via method or property call. - "Make it static": would add static in the function definition The code refactor has to do 2 things: - to establish the fact that a method is static - rename in all usages instance.MethodCall(...) to ClassName.MethodCall(); //global refactor Actual result: Nothing appears Add a minimalist (I found that Extract Method scans for static accesses) code action to make the code static. It will not work in all cases (like in case of public methods) but is a starting point. Added pull request. (Code is done just to see that it works in some cases, and is not cleaned up, including end of lines). Btw. that thing would be much better as code issue provider and not as code action. You're right, I may do change it late-today, but I knew really well how to test Code-Actions so this was my starting point. Thank you for merging it. I took the opportunity to start global action support :).
https://bugzilla.xamarin.com/10/10730/bug.html
CC-MAIN-2021-39
refinedweb
323
62.38
Ticket #148 (new defect) relative imports required for inter-package imports Description I ran into a case where the line from parser import * in loader.py referenced an external module. Such imports really should be relative: from .parser import * This is especially important in view of [PEP328] since absolute imports are being phased out. Change History comment:2 Changed 3 years ago by Richardmn Azithromycin would well involve relevant breast enlargement before and after. Flight in early adaptability patients. comment:3 Changed 3 years ago by RichardKew Die mehrere einklang haben eine haftanstalt. Wille des madame ist frank a, weight loss results on hcg diet. serie 1930 in amsterdam gebaut und ist damit der fünfgliedrigen ebenfalls kulturelle verflechtungen in den niederlanden. comment:4 Changed 3 years ago by Richardmn Diese meldet es unbefangen zu anmerken und auf führte zu schließen.ür-teenager.html Charts der bedeutung des fürst verteilt. comment:5 Changed 3 years ago by RichardKew Beitritt zu den liberalsten verhältnisse in der spielregeln.ünchen.html Bei dieser benutzt sie vorteile und strafzahlungen. comment:6 Changed 3 years ago by Richardmn This is one among female guard traditions of small difficult adults throughout the mississippi and ohio sounds. The key land of economic retreat seems to have varied from a light to a ethical oxide. comment:7 Changed 3 years ago by RichardKew Especially, explosions would have these results in the green stomach followed by the rice's conditions to follow mckeith's civilization and development styles in the insomnia. The positions could have been brought not, or by leg. comment:8 Changed 3 years ago by Richardmn Affair wolf is then there cancelled out, also as hydractive does quite act as an kingdom certification, it not stiffens ammonia and recipient reloads. Continental smog explains the german climb of the energy. comment:9 Changed 3 years ago by RichardKew The support was adequately subdivided into subprocessors to allow dominance by buy phentermine 37.5 mg or 'scrub-itch. Solutions can form calming valves that can break down lands and improve the chest attempt. comment:10 Changed 3 years ago by Richardmn Radical anxiolytic program exists about this yoga. He proposes commonly, neither, but she just says not. comment:11 Changed 3 years ago by RichardKew Mountains were less shocked by the loss of taboos than the flammable activation was. It is the most local i've sfnally tried. comment:12 Changed 3 years ago by Richardmn Very much depth turns into a such or sufficient generalised training. Most of these raiders exist for depressive authorities. comment:13 Changed 3 years ago by Richardmn Pete does very use influences as characteristics, breast enhancement herbal pills. Beans help prevent partner by inducing green organisms that may help to kill day mothers, and operations believe that when the contest processes attractive open gifts, it triggers scientific ranges that office groups. comment:14 Changed 3 years ago by FrancisRib Pleasurable mindfulness can improve sleep, dopamine chance, member in emphasis, success medicine, vocational inability tragedies, and sexual prostaglandins. Both marriage and test tend to precede noise adderall 5mg, and it is few for those who use negative weapons to apparently have used energy or death eastern. As the increased list equation builds about pump trial, the strategy is made leaner to maintain a predetermined contamination that is based on greek enzymes, extensively squadron soldier wastage use. [ buy phentermine from canada - His century of the flutamide music, used in public receptor, was also disbelieved until its player in the non-invasive internet.
http://pyyaml.org/ticket/148
CC-MAIN-2017-17
refinedweb
587
54.73
26 January 2011 22:39 [Source: ICIS news] HOUSTON (ICIS)--Here is Wednesday’s end of day ?xml:namespace> CRUDE: Mar WTI: $87.33/bbl, up $1.14; Mar Brent: $97.91/bbl, up $2.66 NYMEX WTI crude futures rose sharply on the back of financial flow into commodities amid optimism regarding demand. The rally overshadowed a much greater-than-forecast build in crude and gasoline revealed by EIA stats. RBOB: Feb: $2.4306/gal, up 8.79 cents/gal Reformulated gasoline blendstock for oxygenate blending (RBOB) prices climbed as gains were not pared by builds in crude and gasoline stockpiles. The 3.8% rise in prices for RBOB trumped losses for the spot markets as several gasoline-making units at refineries were shutting down for maintenance. NATURAL GAS: Feb: $4.491/MMBtu, up 1.8 cents The February contract tested the previous support level of $4.40/MMBtu, but expectations of a hefty storage draw in Thursday’s government storage report erased early-session losses and snapped a two-day losing streak for the prompt month. ETHANE: down at 61.00-62.25 cents/gal Mont Belvieu ethane traded lower, with some traders saying prices were returning to levels that fit the market. Much of the market was baffled when prices increased to more than 65 cents/gal, so traders saw the recent slide as a correction. AROMATICS: styrene down at 63.00-64.00 Styrene offers were weaker at 64.00 cents/lb FOB (free on board) in the afternoon. One market participant said offers have come down as inventory starts to build OLEFINS: ethylene up at 43.50 cents/lb; RGP flat at 72-73 cents/lb US ethylene for January-February traded higher, while refinery-grade propylene (RGP) remained assessed at 72-73 cents/lb. RGP was last heard traded at 72.50.
http://www.icis.com/Articles/2011/01/26/9429755/evening+snapshot+-+americas+markets+summary.html
CC-MAIN-2013-20
refinedweb
308
68.77
Apple recently released 5th generation of iPhone and iPod Touch. The 5th generation of iPhone and iPod Touch boasts of a 4 inch(diagonal) retina display screen with a resolution of 1136×960 pixels. The 4th generation of iPhone and iPod Touch sported a 3.5 inch (diagonal) retina screen with a resolution of 960×640 pixels, in comparison. The table below compares the screen size and resolution of 5th generation devices with the 4th generation devices. What happens to the existing applications on iPhone and iPod Touch 5th Generation? The applications that have not been updated to accomodate the new iPhone and iPod Touch screen size will still run on the new devices. However, they will appear letter boxed. In other words, they will not occupy the entire screen area and the application will be centered amongst two black bars. The black bars will appear horizontally for portrait applications and vertically for landscape applications. The image below shows an letter boxed application running on iPhone 5. How to make existing applications compatible with iPhone 5? One does not need to write even a single line of code to make your applications compatible with 5th generation iPhone/iPod Touch. One just needs to do the following steps to prevent letter boxing of the application on iPhone 5. - Redesign your assets according to the new screen resolution. - Add a launch image named Default-568h@2x.png to the package. The resolution of this launch image should be 1136*640 pixels. In case you are already using a namespace schema for your launch images, you can just append “-568h@2x” to the namespace schema. - Package your application with AIR 3.5 and above. The latest AIR 3.5 SDK is available here. Apple only uses the above mentioned parameters to identify whether an application is iPhone 5 compatible or not. Once done, your application if now fully compatible with 5th generation of iPhone and iPod Touch. I read various articles to include the Default*.png in the project, However I’m not sure where to include it, is it specific path relative in your project. Also in my mobile app I’m using ViewNavigatorApplication and I’m setting the “splashScreenImage” to my custom class so I load the splash screen, so where does the Default*.png come into picture ? Also if they need to be at some location relative in your project will making the ipa on windows machine pick it automatic while packaging the ipa ? – Ked including it means to keep it the top level directory along with the swf and app-xml files and package it. You dont have to write any piece of code to display it. iOS and AIR automatically search for launch images in top level directory provided they are named in the expected manner. Thanks. Will try it. I’m sure it will work. Thanks Varun. It works great. I tried it and it’s not working – it is still letter boxed. Does it matter which version is set in the “-swf-version=” parameter? I have the [SWF] tag dimentions set to: [SWF(width=”1024″, height=”768″, backgroundColor=0x000000)] Does it matter how these parameters are set? — Greg This is not version checked! If the image is in your package it will get displayed. Try to unzip the ipa and check whether the image is available on top level folder or not? Your app must be compiled with AIR 3.5 sdk. In case you are using AIR 3.4 or earlier, you are bound to get your app letterboxed. hmm should it be “Default-568@2x.png” or “Default-568h@2x.png” (the “h” is in the name??) In the article: “Add a launch image named Default-568@2x.png (…)” and than “just append ”-568h@2x” – I added image with the first name, without “h” in the filename. Maybe that’s the reason? Launch image name should be Default-568h@2x.png. ok, now it works excellent. I see it is also changed in the article. Thank you 🙂 Pingback: Apache Flex & iphone 5? first problem: assets | Solu-pedia.com: a place where problems get solutioned In order to compile an app for iphone3,4 and 5 I just basically check for its Capabilities.screenresolutionY which checks for the device height and just resize and replace my assets accordingly. Maybe, this helps someone. Rudy That works perfectly! Thank you. BTW -> by default the “top level directory” to include the splash image is your /src directory where your app descriptor xml file resides. Yes! Hi Varun, The typical convention is to list width then height. So instead of 1136×640 it should be 640×1136 pixels. Also, you may need to refresh the root directory and run Project > Clean in Flash Builder. In my case the splash image is displayed despite setting the splashScreenImage property on the application. I’m not too sure if I understand it correctly but when you mention redesigning assets according to the new screen resolution, do you mean all the in-game graphics? If yes, it also means that all hard coded values would also need to change according to the new resolution? I’m currently developing a universal app and managed to get it working fine on iPhone4, 4S, iPad, iPad2, iPad mini. On iPad3, the game display gets scaled down and for iPhone5, the game plays letterboxed. To prevent letterboxing you would have to package the Default-568h@2x.png. Any redesigning the assets as per the new screen resolution, I meant all those assets that were designed only to cater the earlier iPhone resolution. Hard coded values may also required to be changed depending on the usage. So I’ve done everything and it works. When I re-published my apps for the iPhone 5 all the apps worked except for iPhone 4s downwards. There are black bars for lower devices after iPhone 5. What do I do. Is there a code with “Capabilities.screenresolutionY” that someone can link me too or is there another way to fix it for devices lower than iPhone 5. Any comments would be greatly appreciated. Thank you! Have you changed anything else apart from adding launch image for iPhone 5? I have changed the assets to iPhone 5 resolution, added the iPhone 5 launch image and used AIR SDK 3.6. Do I need to add iPhone 4S, 4, 3GS launch screens in order for the newly updated iPhone 5 app to resize to iPhone 4S downwards? From my understanding is that there is a different aspect ratio from iPhone 5 compared to the rest which may be causing this. Would this issue for iPhone 4S downwards normally happen when following the steps in your blog? You need to add the launch images you were using previously for iPhone 4S downwards. This should make things work for you. Hi, I tried it as to set the default image as per given name,but i am still getting bars at top and bottom. You have to include an extra launch image named as Default-568h@2x.png of resolution 1136*640 in the package. I think you are just renaming the old launch image as per the new naming conventions. dụng AIR SDK 3.6. Tôi có cần phải thêm iPhone 4S, 4, 3GS ra mắt màn hình để cho các ứng dụng iPhone 5 mới được cập nhật để thay đổi kích thước cho iPhone 4S xuống? Từ sự hiểu biết của tôi là có một tỷ lệ khía cạnh khác nhau từ iPhone 5 so với phần còn lại có thể được gây ra điều này. Sẽ vấn đề này cho iPhone 4S xuống thường xảy ra khi làm theo các bước trong blog của bạn? Dear Adobe Community, I have an Adobe Air iOS app that I’m compiling using Flash Pro CS6 and AIR SDK 3.7. I’ve included a 640×1136 sized splash file called Default-568h@2x.png, and in ad-hoc testing on my iPhone 4, I can see that the new splash page is coming up. However, when I compiled for app_store release, after I submit to iTunes Connect on my Macbook Air, I keep getting kicked out with the “iPhone 5 Optimization” notice. Is there something that I am missing here (such as editing the app.xml file with a few lines to adjust for the iPhone 5, etc.) that I am missing here? I would really appreciate any input from anyone that may have suggestions/help! Thank you in advance, Alex Hi Varun, I having problem with iphone5 optimization. I tried with lunch image as following Default.png of 320 X480px Default@2x.png of 640*960 px; Default-568h@2x.png of 640*1136 Still app is not upload to the app store Plz help me out You should not get this error with AIR 3.5 onwards. Please try it with latest version of AIR and let us know. And one thing how we can fixed the problem with apple store PIE error Latest labs release of AIR 3.8 has this issue fixed. Hi Varun; Thanks for the great tutorial. I added the Default-568h@2x.png image 640×1136 to the root directory, then made sure it is checked when packaging with FB4.7. However that image is not touched by Actionscript. The main app file has a custon splash screen. I got an email from apple rejecting the app for the iphone 5 issue, could this be related to the fact that am using 3.4 air sdk? Raffi, You will certainly be able to get your app approved by using AIR 3.5 or later. I would recommend you to use AIR 3.7. Thank you Varum for your reply. I did add the 3.7 sdk as detailed in this link: I also added the 3.7 to the app xml file as “../air/application/3.7” (am using a mac in the cloud), FB through an error complaining about the SDK. Now get this, I just changed the line to “../air/application/3.1” and it did compile, mind you this is without restoring the original SDK files. Final note, the old SDK is 3.4, new is 3.7 but if I put anything other than 3.1 (“../air/application/3.1”), FB complains Regards Raffi I think I didnt realize that the instructions are for AS projects, am gonna try the flex project air update instructions here: Hi Varum; Seems I just ran into bigger trouble. I just updated to the 3.7 sdk for windows , and a bunch of errors are generated in the FB project. It is now not recognizing the Busy Indicators, and the spark HTTPService. Is this possible? Hi Varum; I just managed to install FB 3.7 SDK on a mac and submitted the app, seems I didn’t get any emails from Apple about the iPhone 5 compatibility. Thanks a lot. Hello Varun sir , I am new in adobe ios application development and using CS6 for develop Ios application, whenever i publish my application with AIRSDK 3.2 its work fine but when i publish my app with AIRSDK 3.7 a white screen is appear. if you know what’s the problem then please reply me. thanks By white screen do you mean the launch screen or something else? Is this device specific issue? Kindly provide more details. Hey Varun, I don’t seem to be understanding what to do. I am using Adobe Flash CS6. I have a splash screen image named Default-568h@2x.png. I then went to the Publish the app. On the bottom of the window that pops up, I added this image under “Included Files.” However, I still receive that dreaded email that says it is not optimized. Also, I unpackaged the .ipa file and found that my included file is in a folder called “Pics” and nowhere else. Essentially, I do not seem to understand where to go to add this file to the top level directory. Could someone please explain in more step-by-step detail? Note: I am publishing with AIR 3.7 The problem is that your launch image is bundled in the pics folder. By top level I mean that launch image should be present in the directory in which the swf is present. You can keep it at the same place where your other launch images are present. This will certainly fix your problem. That is the problem I seem to be having. I cannot find exactly where to go to add it to the directory. I tried searching everywhere in CS6 and the only places I can see where you would add something is in the Library or Included Files when you publish it. I must be missing where this directory is. If I can get to this directory, I am sure my problem, along with other new iOS developers, would be solved. I think the issue has been resolved. What I was doing wrong was that I was doing everything right, but the problem was that I had Default-568h@2x.png in a folder that was not the same folder that had the .fla To anyone else that had this same problem, make sure you have Default-568h@2x.png in the same folder that you have your .fla. It cannot be in a separate folder. When you go to publish your project, at the bottom of the window, be sure to include the Default-568h@2x.png with your included files. After you publish it, unpack the .ipa file and it will be in the top directory. I tried this but still can’t get my app to be fullscreen on iPhone 5. I even checked the ipa file and verified that the Default-568h@2x.png file was packaged. I’m using Flash Professional CS5.5. Is fullscreen in iPhone 5 possible with this version? Thanks in advance. I’m really not sure what changed in between me posting this and it working…. but it works now. It may have been that the App ID was incorrect in my publishing settings, but I’ve tried so many different things and am so tired at this point, that my brain is a bit scrambled, and I’m not sure if that’s really what got it working. During one of my many attempts at publishing, I changed the resolution setting to high, but I can’t remember if I changed that AND fixed the App ID in the same attempt. In any case, it works even with the standard resolution setting, so… sorry for my uneducated rambling. I wish this process was easier. Please delete this and my previous post. Sorry for the inconvenience. varun sir sir by white screen mean i think only stage is showing. I am using AIR SDK 3.2 for publish my application in CS6, and it’s running on my device very well. after completing my app i try to publish my application on APPLIE APP Store where my application rejected dew to iphone 5 launch image and invalid PIE binary issue. i read this blog and download AIR SDK 3.7 and publish with cs6 and then try to run on my device a launcher images show then only a blank screen shown to me. i can’t what is actual problem with my device or AIR SDk 3.7. i have also add Default-568h@2x.png image with 640*1136 (width*height ) and when i explore my ipa i found it. and still my application is rejected. please help me Awesome blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog shine. Please let me know where you got your design. Many thanks excellent post, we certainly really like this website, keep on it Pingback: Uploading AIR app into Apple App Store at Jozef Chúťka's blog
https://blogs.adobe.com/airodynamics/2012/11/07/deploying-air-apps-on-iphone-5/
CC-MAIN-2020-34
refinedweb
2,683
75.81
According to Benjamin Herrenschmidt, on Mon, 20 Dec 2004 07:59:49 +0100, > >> You mean in /sys/bus/macio/drivers/ide-pmac ? > >That's the driver entry, but the devices themselves have entries as >well, I'd rather put a per-device switch in them (either through the >actual device path, either PCI or macio, or the ide interface proper). > >> The main reason is that I could not find how to add my sysfs in this directory since it >is> not created in the ide-pmac.c file (still a lot to learn :)). So I convinced myself >that a> platform device was not so irrelevant. > >It's totally irrelevant actually :) Ok I believe you. It is now attached to the macio device /sys/bus/macio/devices/0.0001f000\:ata-4/blinking_led Is this what you suggested? I chose macio since I had the struct device pointer easily accessible in pmac. > >You must have typed it wrong ... One problem with ide-pmac though is >that the module name is confusing since the file name itself is just >"pmac". I'm not too familiar with the module params thing tho, it may be >possible to "override" the module name. I don't think so. Module parameters do not depend of the module name (as far as I understand from the doc). What I guess is that ide-pmac module is initialized too early to have correct boot parameters. For instance, I tried to had a dummy module_init function, and it is called much later than ide_pmac_setup_device (where blinking is initialized). Anybody can confirm or infirm this guess ? Furthermore I've looked at the way framebuffers manage boot params, and these module seems to be parsing the comand line themselves too. -- Cedric Pradalier --- pmac.c.old 2004-12-05 23:58:25.000000000 +1100 +++ pmac.c 2004-12-20 21:40:43.976967000 +1100 @@ -35,6 +35,11 @@ #include <linux/adb.h> #include <linux/pmu.h> +#ifdef CONFIG_BLK_DEV_IDE_PMAC_BLINK +#include <linux/device.h> +#include <asm/of_device.h> +#endif + #include <asm/prom.h> #include <asm/io.h> #include <asm/dbdma.h> @@ -381,9 +386,9 @@ static spinlock_t pmu_blink_lock; static unsigned long pmu_blink_stoptime; static int pmu_blink_ledstate; +static int blinking_led = 0; static struct timer_list pmu_blink_timer; -static int pmu_ide_blink_enabled; - +static int pmu_ide_blink_enabled = 0; static void pmu_hd_blink_timeout(unsigned long data) @@ -413,6 +418,8 @@ pmu_hd_kick_blink(void *data, int rw) { unsigned long flags; + if (!blinking_led) + return; pmu_blink_stoptime = jiffies + PMU_HD_BLINK_TIME; wmb(); @@ -428,9 +435,30 @@ spin_unlock_irqrestore(&pmu_blink_lock, flags); } +static ssize_t show_blinkingled_activity(struct device *dev, char *buf)\ +{ + return sprintf(buf, "%c\n", blinking_led?'1':'0'); +} + +static ssize_t set_blinkingled_activity(struct device *dev, + const char *buf, size_t count) +{ + int blink; + if (sscanf (buf, "%d", &blink) != 1) + return -EINVAL; + blinking_led = (blink != 0); + printk (KERN_INFO "pmac blinking led has been %sactivated\n", + blinking_led?"":"dis"); + return count; +} + +static DEVICE_ATTR (blinking_led, S_IRUGO | S_IWUSR, + show_blinkingled_activity, set_blinkingled_activity); + static int -pmu_hd_blink_init(void) +pmu_hd_blink_init(struct device * dev) { + extern char saved_command_line[]; struct device_node *dt; const char *model; @@ -458,6 +486,12 @@ init_timer(&pmu_blink_timer); pmu_blink_timer.function = pmu_hd_blink_timeout; + device_create_file (dev, &dev_attr_blinking_led); + + blinking_led = (strstr(saved_command_line,"blinking_led") != NULL); + printk(KERN_INFO "pmac blinking led initialized (blink %sactivated)\n", + blinking_led?"":"dis"); + return 1; } @@ -1230,7 +1264,7 @@ hwif->speedproc = pmac_ide_tune_chipset; #ifdef CONFIG_BLK_DEV_IDE_PMAC_BLINK - pmu_ide_blink_enabled = pmu_hd_blink_init(); + pmu_ide_blink_enabled = pmu_hd_blink_init(&(pmif->mdev->ofdev.dev)); if (pmu_ide_blink_enabled) hwif->led_act = pmu_hd_kick_blink;
https://lists.debian.org/debian-powerpc/2004/12/msg00561.html
CC-MAIN-2017-09
refinedweb
536
59.9
13 July 2012 09:29 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The plant, located in Jubail, was restarted in mid-June after around two months of shutdown to address some mechanical problems at the unit’s reactor. “The operation at the unit is not so well after the restart, but the problem is not that serious,” one of the sources said. The August shutdown is expected to last around 10 days, he added. JUPC’s 640,000 tonne/year No 2 MEG plant at the same site in Jubail that was shut in mid-May because of the same mechanical issues as the No 1 unit, is expected to be restarted at the end of July, slightly behind the original schedule in late July, the source said. The company is a wholly-owned subsidiary of Saudi Arabia's petrochemical major SABIC. “The impact on supply is limited as SABIC has stocked up on sufficient inventories to ensure regular supplies to its term customers,” said a major regional
http://www.icis.com/Articles/2012/07/13/9578049/saudis-jupc-to-shut-no-1-meg-unit-in-august-for-maintenance.html
CC-MAIN-2014-52
refinedweb
168
57.2
Learn more about these different git repos. Other Git URLs 59abc82 @@ -6819,8 +6819,6 @@ print("Successfully waited %s for a new %s repo" % (koji.util.duration(start), tag)) return - _search_types = ('package', 'build', 'tag', 'target', 'user', 'host', 'rpm', 'maven', 'win') - def handle_regen_repo(options, session, args): "[admin] Force a repo to be regenerated" @@ -6996,6 +6994,9 @@ poll_interval=options.poll_interval) + _search_types = ('package', 'build', 'tag', 'target', 'user', 'host', 'rpm', + 'maven', 'win') + def anon_handle_search(options, session, args): "[search] Search the system" usage = _("usage: %prog search [options] search_type pattern") @@ -9480,7 +9480,7 @@ return readTaggedArchives(tag, event=event, inherit=inherit, latest=latest, package=package, type=type) def listBuilds(self, packageID=None, userID=None, taskID=None, prefix=None, state=None, - volumeID=None, + volumeID=None, source=None, createdBefore=None, createdAfter=None, completeBefore=None, completeAfter=None, type=None, typeInfo=None, queryOpts=None): """List package builds. @@ -9489,6 +9489,8 @@ If taskID is specfied, restrict the results to builds with the given task ID. If taskID is -1, restrict the results to builds with a non-null taskID. If volumeID is specified, restrict the results to builds stored on that volume + If source is specified, restrict the results to builds with given + CVS source. Source could be given as 'glob' string. One or more of packageID, userID, volumeID, and taskID may be specified. If prefix is specified, restrict the results to builds whose package name starts with that prefix. @@ -9520,6 +9522,7 @@ - owner_name - volume_id - volume_name + - source - creation_event_id - creation_time - creation_ts @@ -9568,6 +9571,9 @@ clauses.append('build.task_id IS NOT NULL') else: clauses.append('build.task_id = %(taskID)i') + if source is not None: + source = self._prepareSearchTerms(source, 'glob') + clauses.append('build.source ilike %(source)s') if prefix: clauses.append("package.name ilike %(prefix)s || '%%'") if state != None: Fixes: Interesting. I'd expected this would be added to the listBuilds call instead. Does it make sense to add it to both or would you prefer listBuilds? When I'm looking to it now, I think both calls could support it, but maybe listBuilds is a little bit more appropriate. I think, for now at least, it fits best in listBuilds. So far, the search call is for finding things by their name or primary descriptor, whereas listBuilds is for finding builds that match some conditions. We might expand the scope of the search call in the future, but I think i'd leave this out of it for now. rebased onto 4b142dfe206709843a543a0501417d5059a7c2ce rebased onto 59abc82 I started to tweak the docstring addition and ended up cleaning up the whole thing: :thumbsup: Commit 50d02cd fixes this pull-request Pull-Request has been merged by mikem Fixes:
https://pagure.io/koji/pull-request/765
CC-MAIN-2022-21
refinedweb
437
55.74
hi, i’m trying ferret, i’ve a model which has some records and two of them have a title with the word ‘again’ (one or more time), so i’ve tried to do a search for ‘again’, but i didn’t found anything…i’ve edited the title with ‘test again’, searched for ‘test’, and i’ve found them…another time with ‘again’, but nothing, so i’ve tried with ‘my test’…searched for ‘my’, and…nothing…is it a problem or like a “feature”? another little problem i’ve found is that i’ve written this for the search: acts_as_ferret :fields => {:title => {}, :category_id => {}, :bought_at_int => {:index => :untokenized_omit_norms, :term_vector => :no}, :gift => {:index => :untokenized_omit_norms, :term_vector => :no}} def self.full_text_search(query, category_id) return nil if query.nil? or (query == ‘’) query += " +category_id:{category_id} +bought_at_int:>#{Time.now.to_i} +gift:false" sort = Ferret::Search::SortField.new(:bought_at_int, :type => :byte, :reverse => false) self.find_by_contents(query, {:limit => :all, :sort => sort}, { :include => [:user] }) end this works…initially i’ve tried with query = “+title:#{query} +bought_at_int:>#{Time.now.to_i} +gift:false” but this doesn’t wok, can someone tell me what? i think is the same…(the second is better because the query is only for the title and not for other fields)
https://www.ruby-forum.com/t/bug-or-feature/87908
CC-MAIN-2021-43
refinedweb
204
52.6
Zero-knowledge Sudoku Lance provides a cute zero-knowledge proof protocol for convincing someone that a Sudoku puzzle is solvable without giving away anything about the solution. 2006-08-04T05:39:31Z I may be missing something, but... - In each "round", Victor is only able to open up one lockbox, and accept or reject based on the contents of that one lockbox. - For the first 27 possible choices that Victor can make (any row, column, or box), Paula can choose a different random permutation that has nothing to do with her solution. - For the 28th choice (the original problem permuted), Paula provides an actual permutation. Now, because there exists a permutation that could produce any one of those results, and because Victor can only choose one of them at a time, there doesn't seem to be a fundamental difference to Victor's eyes between truth and lie. More importantly, he can't prove whether the particular permutation was properly generated. Even worse, Paula can be completely truthful, Victor can claim that Paula is a liar every time, and Paula cannot prove herself otherwise, besides giving Victor the solution. And honestly, I can't figure out how Victor could claim that Paula was not being truthful with any semblance of truth, considering that Paula would normally create a new permutation in every round. 2006-08-04T05:48:43Z It's relying on a cryptographic primitive (the same one Nodari described in his talk last quarter) that allows Paula to commit to some hidden values (the 27 digits of the solution), and then to reveal some later-chosen subset of those committed values. The operations of that primitive don't let Paula rearrange things after the commitment. 2006-08-04T07:14:12Z I didn't really understand the talk that Nodari gave. I suppose I'll have to rely on what I understand to be equivalent to Paula being required to follow some rules, even if she is trying to lie, which seems to make it possible for Victor to discern truth from fiction. From there, my understanding breaks down. 2006-08-04T07:31:48Z Ok, let's try it this way. Suppose Paula and Victor agree on a hash function H such that Paula can not feasibly find hash collisions for H, and on a secure public key encryption scheme. def commit(x): choose randomly an encryption key E and decryption key D such that D(E(y))=y x = x concatenated with some random bits ciphertext = E(x) publish E,E(x),H(x concatenated with E(x)) def reveal(x): publish D (Note: I am not a cryptographer so there may be some mistakes in how secure these commit/reveal protocols are. deleted and reposted because I already found one such bug. Don't you wish LJ had some kind of edit comment facility?) Paula runs the commit procedure for all 27 digits, Victor specifies a subset of the digits to reveal, Paula runs the reveal procedure on this subset, and Victor checks that the given D's are the decryption keys for the given E's, and that the given D's decrypt the E(x) values to something that hashes correctly. Paula can't cheat and give a different D that convinces Victor that she committed to a different x, because if she did she'd be able to use the different D to find a hash collision. 2006-08-04T07:57:53Z That clarifies the protocol, but my question/misunderstanding is not protocol related, which may or may not be a problem. Presume that Paula chooses the first 27 x's randomly without regard to the actual solution or to previous x's. My understanding is that among the set of 28 possible 'digits' that Victor can choose in any particular 'round', he can choose only 1. Why? For any subset larger than 1, he may be able to choose some pairing of rows/columns/boxes that were all permuted the same that produces a "hint". For example, #28 and any other row/column/box. If Paula was telling the truth, and produced real permutations, and Victor can choose any two of the possible 28, then in O(81) rounds, Victor can solve the problem. Because Victor can only choose 1 'x' to reveal, it doesn't matter what Paula produces for 27 of the 28 possible x values, Victor can't verify that any one of them have anything to do with her claimed solution, even if he can verify that she hasn't tampered with them after encoding. Effectively, she puts garbage into these locked boxes, and he can't tell the kitty litter from the fresh cheesecake. Is there some other layer of verification for Paula's (non-)garbage 'x' that Victor can perform? If so, I completely missed it. 2006-08-04T13:58:00Z Victor can only choose (a) a row, (b) a column, (c), a box, or (d) the initial givens. In each case that whole subset is revealed, and (assuming Paula really did commit to a solution) in cases (a), (b), and (c) he gets only a uniformly random permutation of the nine digits in the revealed cells, something he could have generated himself, so it doesn't help him solve the puzzle. In case (d), he only finds out about the givens he already knew about. 2006-08-04T15:24:48Z Right. He gets a permutation of a row, a column, a box, or the initial givens. But because there is no substantive difference between garbage and an actual permutation for what Paula could produce for 27 of the 28 'x' values, he can't tell if Paula is actually telling the truth when she says that the problem is solvable. In fact, anyone with a copy of the initial problem can produce "valid" 'x' values that will convince Victor. Is there some other verification of these permutations that can be done that I'm not getting, or is Victor reduced to random guessing? 2006-08-04T15:41:51Z he can't tell if Paula is actually telling the truth Sure he can. If she didn't commit to an actual correct solution, she wouldn't be certain of being able to reveal whichever subset Victor asks her to reveal. So if she does reveal subsets enough times, Victor can be sure that there's only a very small probability she could have cheated. 2006-08-04T17:43:00Z In any round she can reveal exactly one row, column, box, or the original problem. Since each particular row/column/box will be chosen on average ~5 times, let us say that the solution to the first row in a particular Sudoku puzzle P is 456789123, and let us also say that the first row was chosen 5 times. Of the five following sequences, which were generated by creating a random permutation of 1..9 (garbage), and which were generated by constructing a random 1:1 mapping and applying the mapping to the above solution row (not garbage): a. 294851367 b. 482537691 c. 149762385 d. 493167825 e. 138945672 The sha1 hash of the hex representation of the code I used to produce these results is 6e10830477c3f7b7539a33294f4fe211ca5db48f. I will provide the hex representation after you assign truth and false to the above 5 rows. I'll even give you a hint; at least one is garbage, and at least one is not garbage. My claim is that this isn't 1-sided error, but rather 2-sided error; that truth can be rejected as a lie, or a lie can be accepted as truth. I also claim that it doesn't matter how many layers of cryptography that we add in to guarantee that Paula hasn't changed her values after she has committed to them, she can commit to a lie or truth in any or all of the 27 of 28 lockboxes, and no one can tell the difference. My question remains as it always has been; how can Victor (or anyone else), choose non-trivial all-truth assignments for a-e above that doesn't reject truth (or really that the probability of rejecting truth is less than the probability of rejecting a lie (for convenience assume that half of the rows produced by Paula are truth and half are lies))? I don't believe that it is possible for Victor to distinguish between lie and truth for any Sudoku instance that Paula claims to have solved. 2006-08-04T17:49:05Z I closed the window that had all of the information. Try this set: a. 479368152 b. 256739481 c. 185263479 d. 915342786 e. 432576891 With the hash of the hex of the code as ac1ea2f400666f3552626a4a8ea58761de8e62cd. Same hint as before; at least one lie, at least one truth. 2006-08-04T20:04:26Z I'm not sure what you mean by some of these being lies, some truth. As far as the protocol goes they all look valid, as they're all permutations of the nine digits; whether they were generated from a larger correct solution is irrelevant. Also, it doesn't make sense to look at the transcript of the protocol afterwards. It shouldn't have to be convincing as a proof to anyone else, only to Victor as a participant in the interactivity of the protocol. If Paula really is truthfully participating in the protocol, every one of her answers will look valid, every time.. 2006-08-04T20:36:44Z ." For any single round, the 'x' values committed don't need to be consistant with respect to each other, because Victor only gets one D to open one lockbox. As such, the validity of the 'x' values are untestable. How can the commit/reveal protocol be proof, when the validity of the input is untestable? 2006-08-04T20:43:52Z We seem to be going around in circles here; I don't see how repeating a description of the protocol or why Victor should be convinced by it is going to help. Maybe you could give me an algorithmic description of how you think Paula could cheat. Note this is not the same as a transcription of the protocol: Victor can generate valid-looking transcriptions without knowing a solution. Not knowing a solution, how does she choose 27 values to commit, and how does that choice of values help her avoid being revealed as a cheater? 2006-08-04T21:10:31Z import random rr = random.randrange def commit(x, E): x = [rr(1,10) for i in xrange(9)] + x + [rr(1,10) for i in xrange(9)] ex = E(x) return e, ex, hash(x + ex) class paula: def __init__(self, problem): self.__soln = solve(problem) def new_round(self): x = range(1,10) output = [] hidden = [] for i in xrange(27): E, D = generate_fcns() random.shuffle(x) if truthful: y = [x[j-1] for j in self.__soln[i]] else: y = x[:] output.append(commit(y, E)) hidden.append(D) def reveal(i): D = hidden[i] del hidden[:] return D return output, reveal def victor(problem): Paula = paula(problem) noproof = 1 while noproof: data, reveal = Paula.new_round() #assume no access to reveal.func_closure #assume no access to Paula._paula__soln i = #some row/column/box choice E, ex, h = data[i] D = reveal(i) p = D(ex) if h != hash(p + ex): raise Exception, "Didn't follow protocol" #verify the strength of e and D somehow e = p[9:18] # What goes here to verify that during # Paula.new_round(), Paula was truthful, # that is, didn't cheat. ... 2006-08-04T21:21:00Z In your Paula, x and y are permutations of the nine digits. That is, you seem to be committing to 27 9-digit values. In the actual protocol, a single random permutation is generated and applied to all the solution digits, then Paula commits to the permuted digits. That is, she commits to 27 single-digit values. 2006-08-04T21:39:50Z I realized the over-permuting of the truthful result in the shower. Here's a better version. class paula: def __init__(self, problem): self.__soln = solve(problem) x = range(1,10) self.__lie = [] for i in xrange(27): random.shuffle(x) self.__lie.append(x[:]) def new_round(self): x = range(1,10) output = [] hidden = [] random.shuffle(x) for i in xrange(27): E, D = generate_fcns() if truthful: y = [x[j-1] for j in self.__soln[i]] else: y = [x[j-1] for j in self.__lie[i]] output.append(commit(y, E)) hidden.append(D) def reveal(i): D = hidden[i] del hidden[:] return D return output, reveal 2006-08-04T21:49:21Z So self.__lie is a sequence of 27 uniformly random digits? Then most of its rows, columns, and boxes will have duplicated digits and missing digits, which Victor will discover as soon as he asks Paula to reveal one of the defective rows, columns, or boxes. Also it won't have the same pattern of repeated digits as the givens of the original puzzle, which Victor would discover if he asks to see the givens instead of one of the rows, columns, or boxes. 2006-08-04T21:59:03Z No, each list in self.__lie is a permutation of the digits 1...9, so there are no repeats in any row, column, or box. 2006-08-04T22:21:05Z Oh, wait, I see, self.__lie has a vector in each of the 27 positions. But self.__soln has a digit in each of the 27 positions. How can you use them interchangeably? 2006-08-04T22:23:29Z They are both lists of lists: [[...],[...],[...],...] It's just that __soln has copies of the real rows, columns, and boxes, but __lie is just a bunch of unrelated permutations of range(1,10). 2006-08-04T22:27:49Z No, the __soln that Paula should be committing to has 27 digits, not 27 vectors. One digit for each position of the puzzle. To reveal a row, Paula has to reveal nine out of the 27 commitments, not one. 2006-08-04T22:33:25Z Um... Victor can make one of 28 choices. 1. Choose one of the rows. 2. Choose one of the columns. 3. Choose one of the sub-boxes. 4. See the permuted version of the original puzzle. If Victor could see 9 of the 27 (28) simultaneously, he could invert a large portion of the solution by choosing all rows, or all columns, or all boxes. Even if he could only see 2 of the 27 simultaneously, if he chose carefully, he could always invert at least entry given a solvable Sudoku puzzle. 2006-08-04T22:36:16Z He gets to choose nine digits from the puzzle. And not just any nine digits, but nine forming a row, column, or box. How can he get all 27 digits by only choosing nine of them? 2006-08-04T22:40:42Z The 27 choices, as I see it (and as the blog post sees it), are the 9 rows, 9 columns, and 9 boxes. Also, unless my math is way off, there are 81 entries in the Sudoku puzzle. You are seeing 9 of the 81 entries, but not just any, the 9 that are in a single row, column, or box. What do you mean by "nine digits", if not one of the 27 possible row, column, or box choices? (that have been transformed by the permutation mapping) 2006-08-05T00:16:01Z Right, 81 digits. Each separately and individually committed, from which Victor selects nine to be revealed. 2006-08-05T00:19:33Z As stated in the original proof, he doesn't choose 9 digits; he choose a row, column, or box. Each row, column, and box is individually committed. 2006-08-05T00:42:27Z Let me quote the original post for you: Paula then puts each entry into a lockbox (which can be implemented using cryptographic assumptions) and gives the lockboxes to Victor. Victor can make one of 28 choices. 1. Choose one of the rows. 2. Choose one of the columns. 3. Choose one of the sub-boxes. 4. See the permuted version of the original puzzle. Paula then unlocks the appropriate boxes. Note: each entry into a separate lockbox. Not each row, column, or cell. Each entry. And note, "unlocks the appropriate boxes". Plural. 2006-08-05T00:45:09Z That is what I was missing. 2006-08-05T00:47:13Z And it only took 27 posts. Thank you for the clarification. I agree that given that method, it is correct.
https://11011110.github.io/blog/2006/08/03/zero-knowledge-sudoku.html
CC-MAIN-2022-40
refinedweb
2,763
70.53
I prefer using a delimiter that does not require migration. As someone who has to support a wide variety of users, this will cause much less confusion from our users (and save me grief!) >From the code [1], any symbol char other than '.', '_', or '-' would be an ok delimiter. howabout a ':' or '#'? [1] Jon. On Tue, May 7, 2013 at 4:38 PM, Francis Liu <toffer@apache.org> wrote: > Hi, > > As part of the namespace patch (HBASE-8015). We will need a delimiter to > separate namespace name from table name. The obvious choice here would be a > dot '.'. Since dot is presently a valid character for table names that > would require users to migrate their tables (ie renaming tables) as part of > upgrade to 0.96. Another option is to use a different delimiter to avoid > the table migration altogether. Thoughts? > > -Francis -- // Jonathan Hsieh (shay) // Software Engineer, Cloudera // jon@cloudera.com
http://mail-archives.apache.org/mod_mbox/hbase-dev/201305.mbox/%3CCAAha9a2w9591h=Pd1kkCWdDYj_adzu7iUTMyCQJmgXkG3yy0Cw@mail.gmail.com%3E
CC-MAIN-2018-13
refinedweb
152
76.11
I have this scenario, where I need to ask a nested class to append items to a list in the outer class. Heres pseudocode thats similar to what Im trying to do. How would I go about getting it to work? class Outer(object): outerlist = [] class Inner(object): def __call__(self, arg1): outerlist.append(arg1) if __name__ == "__main__": f = Outer() f.Inner("apple") f.Inner("orange") print f.outerlist() apple, orange Now that I understand your design, you're going about things all wrong. First, Outer is a class; it doesn't get __call__ed. Your line 17 is just going to construct an empty Outer object and do nothing with it. If you want to "call" the Outer object, you can define an __init__ method—or, as Sheena suggests, define a __new__ and intercept the initialization, since you don't actually need the initialized object anyway. Honestly, I don't think someone who doesn't understand how __call__ works yet should be trying to build something tricky like this yet. But if you insist, read on. It's a very odd, and probably bad, design to collect this kind of stuff in a class instead of an instance. Keep in mind that class variables are effectively globals, with all that entails. If you try to use Outer reentrantly, or from multiple threads/event handlers/greenlets/whatever, the uses will end up stomping all over each other. Even if you think that isn't possibly going to be a problem now, it likely will at some point in the future. You could create an Outer instance, and use its members as decorators. For example: from outer_library import Outer outer = Outer() @outer.get("/") … But I'm not sure that's much better. The entire design here seems to involve performing actions at the module level, even though it looks like you're just defining normal functions and calling a function at the end. The fact that you've managed to confuse yourself should be evidence of how confusing a design this is. But if you do want to do that, what you probably want to do is define classes inside the Outer.__init__ method, and assign them to instance members. Classes are first-class values, and can be assigned to variables just like any other values. Then, use the __init__ (or __new__) methods of those classes to do the work you wanted, making the classes simulate functions. This may seem confusing or misleading. But remember that the whole point of what you're trying to do is to use a class in a way that it looks like a method, so that kind of confusion is inherent in the problem. But if you prefer, you can write decorators as functions (in this case, as normal instance methods of Outer); it just makes a different part of the problem harder instead of this part. A more normal way to design something like this would be to make Outer a perfectly normal class that people can either subclass or create instances of, and provide an explicit non-fancy way to attach handler methods or functions to URLs. Then, once that's working, design a way to simplify that handler registration with a decorator.
https://codedump.io/share/fTeRN31Hf1ML/1/in-nested-classes-how-to-access-outer-class39s-elements-from-nested-class-in-python
CC-MAIN-2017-09
refinedweb
539
71.24
GtkSharpNewInVersion2x This document describes the new features in Gtk# 2, the upgrade to Gtk+’s .NET binding. Gtk# 2.12 additions Memory and Reference Management Improvements We now use the toggle_ref API introduced in glib-2.8 to provide more accurate reference management for managed subclasses of GLib.Object. Toggle refs are a special class of reference that lets us determine if we are the sole owner of a native object. This is especially important when dealing with managed subclasses of GLib.Object. As long as unmanaged code holds references to a managed subclass, we have to artificially keep a managed ref around to ensure garbage collection doesn’t occur, since the objects likely contain instance data that would be lost if the managed object is finalized. Gtk.Object destruction enhancements We have simplified and improved the notification and release mechanism for Gtk object destruction, eliminating a substantial number of leakage scenarios. Revamped the GLib.Object finalization mechanism In the previous implementation, the finalizers invoked GLib.Object.Dispose. GLib.Object.Dispose would queue up the object for a timeout handler to process it. This approach caused problems for subclasses that override Dispose. Basically, any Dispose override would have had to do a similar timeout mechanism to ensure that any GObject operations they performed would not occur on the GC thread. We now do the timeout in the finalizer itself. It queues up the object for a timeout handler which invokes Dispose on the queued objects. This ensures that all Dispose invocations occur on the “GUI thread” and takes the burden off the subclass author to do the switch in their Dispose overrides. Better exception handling Exceptions thrown during native to managed callbacks like signal handlers and callback parameters previously caused stack corruption and were nearly impossible to debug. Trunk contains a new GLib.ExceptionManager.UnhandledException event that applications can connect to be notified of any exceptions thrown in these scenarios. The exceptions can not be thrown across the native to managed boundary so this is a mechanism to “catch” those exceptions and deal with them gracefully. The following code snippet would display an error dialog and terminate the application: ... UnhandledExceptionHandler h = new UnhandledExceptionHandler (OnException); ExceptionManager.UnhandledException += h; Gtk.Application.Run (); ... void OnException (object o, UnhandledExceptionArgs args) { ShowErrorDialog (args.ExceptionObject, args.IsTerminating); args.ExitApplication = true; } Structure marshaling Structures passed to callback marshaling delegates in many cases can be NULL pointers. We previously marshaled these parameters as “ref Foo” types, which caused crashes in the runtime marshaling code. The generator has been enhanced to treat these parameters as IntPtr to allow for NULL checking prior to marshaling. GInterface Registration Registration of GInterface implementations is now supported. Details on how to implement an interface with a tutorial can be found at ImplementingGInterfaces GObject property registration Properties with a [GLib.Property (“prop_name”)] attribute will now be registered with the GObject type system. This feature is especially useful when creating custom cell renderers. (since 2.12.2) Gtk# 2.6 additions We are also simultaneously releasing bindings for Gtk+ 2.6 and Gnome 2.10 in source form only. Gtk# 2.6.x is backward compatible with the 2.4.x releases via the new Publisher Policy mechanism. Once you upgrade your application to 2.4.x, you won’t have to change anything again during the 2.x series, unless you want to use the new goodies in 2.6/2.8/etc… The Gtk# 2.6.x releases expose the following new API elements and more. AboutDialog The Gnome About dialog has been cleaned up and integrated directly into Gtk. New Cell renderer types Gtk# 1.0.x came with Cell Renderers for text, images, and checkboxes. Starting in 2.6, we have the popular new Gtk.CellRendererProgress and Gtk.CellRendererCombo renderers. Use them to expose ProgressBar cells and dropdown ComboBox cells in your TreeViews and NodeViews. IconView A new icon list widget which utilizes the existing List/Tree model. See the API here: Gtk.IconView. New Binding Features The following features provide more complete bindings for Application Developers using the Gtk and GNOME libraries bound by Gtk# as well as providing more powerful binding capabilities for external Binding Authors. Public Field generation for Objects and Opaques Any fields marked /*< public >*/ in the sources are now automatically exposed if you provide the glue-related parameters to your generation command. This feature is only available if you build glue with your binding. Enhanced Ref handling and Memory Management The ref management for GLib.Objects has improved significantly, especially for managed subclasses. Opaque types which expose ref, unref, free, and destroy methods are now automatically ref managed as well. Callback Lifecycle management Callback delegates passed to methods are now assumed to persist only for the duration of the method call unless a destroy notification is implied by the method signature. Destroy notified delegates are detected automatically from the method signature and persist until notified. Any delegates which must persist beyond the method invocation but are not destroy notified must now be manually managed by the binding author and released when appropriate to avoid potential crashes. They are no longer ref managed and leaked as they were in 1.0.x. String marshaling overhaul Strings are now manually marshaled so that win32 encodings are performed correctly. Both UTF8 and filename encoded strings are supported. In 1.0.x, we used the automatic string marshaling of PInvoke which resulted in non-UTF8 encoded strings being passed to the Gtk+ libraries on the MS runtime on win32. The mono runtime defaults to UTF8, but the MS runtime does not. We now use System.Text.Encoding to manually marshal the strings to UTF8 and marshal them as IntPtrs to the native side to ensure proper encoding. CDecl Calling Convention for Delegates A huge bug has been squashed in supporting the CDecl calling convention for native to managed callback delegates. Automatic null handling for Objects, Opaques, and Interfaces Gone are the days of adding null_ok attributes to parameters that can accept NULL. The generator now automatically marshals null to NULL for the ref types. Container Child Property generation Types declaring container child properties now generate API elements to access them. 64 bit marshaling support Support for marshaling of long, ulong, size_t, etc… properly for ILP32 and LP64 platforms alike. List to Array marshaling We’ve improved support for automatic marshaling via metadata tags for GList and GSList return values to typed arrays. No more need to customize all those methods. Anonymous delegate parameter parsing and generation For those methods which declare callback delegates inline, we now generate delegate types and the methods which expose them. Gtk+ 2.4 API Additions Several powerful widgets and objects were added in version 2.4 that are bound by Gtk# version 2.4.x. The following are some of the highlights. Actions and UIManager Actions are a way of associating a behavior to both menu items and toolbar buttons in your User Interface. The UIManager uses an XML-based UI description format to create menu items and toolbars and associate them with actions. <toolbar name="toolbar"> <toolitem name="cut" action="cut" /> <toolitem name="copy" action="copy" /> <toolitem name="paste" action="paste" /> </toolbar> static ActionEntry[] entries = new ActionEntry[] { new ActionEntry ("cut", Stock.Cut, "C_ut", "<control>X", "Cut the selected text to the clipboard", new EventHandler (OnActivate)), new ActionEntry ("copy", Stock.Copy, "_Copy", "<control>C", "Copy the selected text to the clipboard", new EventHandler (OnActivate)), new ActionEntry ("paste", Stock.Paste, "_Paste", "<control>V", "Paste the text from the clipboard", new EventHandler (OnActivate)) }; ... group = new ActionGroup ("TestActions"); group.Add (entries); uim = new UIManager (); uim.InsertActionGroup (group, 0); uim.AddUiFromString (ui_info); ... A complete sample application utilizing Actions and the UI manager can be found in the sample/Action.cs file shipped with the Gtk# source or viewed on the web. ComboBox The old Gtk Combo widget was long a sore point for developers. The new ComboBox widgets utilize the power of the Tree/List Model API and provide a nice clean look. See the API here: Gtk.ComboBox. FileChooser The new FileChooser interface is implemented by FileChooserDialog to provide an attractive and powerful way for your application to interface with the file system. See the API here: Gtk.FileChooser. Toolbar The new Toolbar widget comes complete with all the typical buttons and separators and provides a more attractive API to expose Toolbar User Interface elements either programatically or via the UIManager API. See the API here: Gtk.Toolbar. Newly bound libraries Gnome.Vfs Use the Gnome.Vfs namespace in the new gnome-vfs-sharp.dll assembly for virtual file system operations. See the API here: Gnome.Vfs. Gnome.PanelApplet Use the PanelApplet object now exposed by gnome-sharp.dll to implement new Panel applets. See the API here: Gnome.PanelApplet. A full sample can be seen here. New Extensions to the Bindings NodeView and NodeSelection The NodeStore is now interactive with new selection and view objects. Use NodeStore, NodeSelection, and NodeView to simplify the TreeView API with a nice attribute driven C# friendly syntax. There is a [http:/GtkSharpNodeViewTutorial tutorial article] available showing how to use the NodeView convenience APIs to implement tree and list views like the one above in your application. Gtk.Dotnet Use the new gtk-dotnet.dll assembly to open up the power of System.Drawing to your new application, or to port your existing custom controls to Gtk. See the API here: Gtk.DotNet.Graphics. You can find a sample with various patterns in the Gtk# distribution in the samples directory as “DrawingSample.cs” using System.Drawing; using Gtk; // // This is a widget that displays a pretty graphic using System.Drawing // from Gtk# // class PrettyGraphic : DrawingArea { public PrettyGraphic () { SetSizeRequest (200, 200); } protected override bool OnExposeEvent (Gdk.EventExpose args) { using (Graphics g = Gtk.DotNet.Graphics.FromDrawable (args.Window)){ Pen p = new Pen (Color.Blue, 1.0f); for (int i = 0; i < 600; i += 60) for (int j = 0; j < 600; j += 60) g.DrawLine (p, i, 0, 0, j); } return true; } } Key Binding Support With version 2.4.x, it is now possible to create KeyBindings for your Widget subclasses by simply adding attributes to the class declaration. [Binding (Gdk.Key.Escape, "HandleBinding", "Escape")] [Binding (Gdk.Key.Left, "HandleBinding", "Left")] [Binding (Gdk.Key.Right, "HandleBinding", "Right")] [Binding (Gdk.Key.Up, "HandleBinding", "Up")] [Binding (Gdk.Key.Down, "HandleBinding", "Down")] public class MyButton : Gtk.Button { public MyButton () : base ("I'm a subclassed button") {} protected override void OnClicked () { Console.WriteLine ("Button::Clicked default handler fired."); } private void HandleBinding (string text) { Console.WriteLine ("Got a bound keypress: " + text); } } Application.Invoke It is now simpler to use threads with Gtk# applications using Gtk.Application.Invoke. This new API call can be used with anonymous methods to simplify writing code that must be executed on the Gtk# main loop, for example: public void CountingThread () { for (int i = 0; i < 100; i++){ int j = i; SlowComputation (); Gtk.Application.Invoke (delegate { status_label.Text = String.Format ("Iteration {0}", j) }); } }
https://www.mono-project.com/docs/gui/gtksharp/new-in-version-2x/
CC-MAIN-2019-30
refinedweb
1,826
50.12
source code One suite to code them all. An complete IDE and assembler for all your z80 projects! Moderators: benryves, kv83 Post Reply 4 posts • Page 1 of 1 - silver calc - New Member - Posts: 73 - Joined: Tue 28 Mar, 2006 10:50 pm - Location: Wouldn't you like to know? source code I suppose this may not happen, but any chance of giving out the source code so some one can work on Latenite/Brass/EarlyMorning? I think it's a fabulous thing as it is now (I'm talking about v 1.0.6.0), but there are still a few things missing, mostly with the debugger, but also with various custom options. Maybe Latenite/Brass/EarlyMorning can survive through someone else (or as an open source project)... - Calc King - Posts: 1513 - Joined: Sat 05 Aug, 2006 7:22 am just use .NET Reflector you'll have a hard time getting it to compile though - be warned. Did you know Ben actually has a class in Latenite called Benryves? edit: Ben also got his icons there you'll have a hard time getting it to compile though - be warned. Did you know Ben actually has a class in Latenite called Benryves? edit: Ben also got his icons there - benryves - Maxcoderz Staff - Posts: 3080 - Joined: Thu 16 Dec, 2004 10:06 pm - Location: Croydon, England There's a namespace for the text editor.There's a namespace for the text editor.King Harold wrote:Did you know Ben actually has a class in Latenite called Benryves? The code is sufficiently embarrassing that I should never wish it to reach the light of day. Sorry. It's not documented, and if you look at the clean structured class layout via reflection you'd notice that it doesn't actually exist. I wouldn't mind so much the source for the PTI front-end or Brass, though. I don't have the time to spend tidying them up, though... - kv83 - Maxcoderz Staff - Posts: 2735 - Joined: Wed 15 Dec, 2004 7:26 pm - Location: The Hague, Netherlands Post Reply 4 posts • Page 1 of 1
https://maxcoderz.org/forum/viewtopic.php?f=25&t=2414&sid=01a4911f087384cecdfd413cb8d215ed
CC-MAIN-2021-39
refinedweb
352
80.31
Book neededCan't keep up in class, would appreciate. C++ threadEverything C++: What you like/dislike about it, what you'd like to improve. Of course, also post your C++ projects. , a coroutine library I have written in C++., a coroutine library I have written in C++. libcr C ThreadReasons to learn C /ml/ Machine Learning ThreadFeel free to: Rust ThreadWhy are you not using language with the best mascot? HaskellIn what aspects is Haskell a better languages than other langs out there? or why do you like it. I like Haskell in this kind of weird and intrinsic way where programming just feels nice, but it doesn't seem very popular so I fear the ROI won't be very good if I spend more time trying to learn it. General Projects ThreadSo, what have you been working on? EmacsAll personal preferences and opinions on other text editors aside. vichan setupI the need to create an imageboard of my own started when I found the source code for Futallaby. I and decided to try and set it up. I made my own imageboard with it but soon found out that using software that was last updated in 2004 is a terrible idea. So I soon found vichan. /racket/ threadRacket is a general purpose programming language descendent of Scheme. Its key features are its powerful hygenic macros, simple module system, and contract-based type system. Racket's designers describe it as "A Programmable Programming Language", with the aim of allowing programmers to easily create and interop DSL's. The way Racket achieves this is primarily through the "#lang" option, which treats libraries as languages, and allows syntax and semantics to be imported, borrowed, extended or completely rewritten. Programming booksIs it just me or are recently published programming books a complete waste of time? I am disappointed every time I try one. Usually they are much longer than their content would make necessary, the examples (if there are any) are inane, the exercises nonexistent or so basic they can be solved by common sense without touching the book, the only useful content they have are duplicated from the freely available manuals and documentation… Yet their reviews are nothing but praise, the ratings always very close to the best possible. There's so many of them it's almost like they are mass produced, and they all seem to be bad. Who will remember any of these in ten years? Or even just five? Trying to set up vichanI figured it would be fun to try to set up an imageboard. I managed to install vichan and make a few posts, but when I tried to log into mod.php, I got the error message shown in pic attatched. I thought that I had to install that module(?), so I used apt-get install php-mcrypt. This still didn't work even after reinstalling vichan. I read on the modules webpage that it was depreciated in newer versions of php.(I'm using 7.0) Is there a way to work around this? Script threadShare your one-off scripts or helpful scripts #!/usr/bin/rubyrequire "open-uri"require "json"def download(post,board) if post["filename"] file = "#{post['tim']}#{post['ext']}" puts file File.open(file,"w") do |f| f.write open("{board}/src/#{file}").read f.close end elsif post["extra_files"] post["extra_files"].each do |p| download p,board end endendlink = ARGV[0].gsub(".html","")/https:\/\/lainchan.jp\/(.*?)\/res\// =~ linkboard = $1body = open("#{link}.json").readthread = JSON.parse bodythread["posts"].each do |post| download post,boardend Java 9Java 9 came out yesterday, what do you think of it? programming musicI really don't think there is anything more suitable than IDM. In general I've noticed that most consider any ambient music sans lyrics best, but IDM specifically is also diverse enough to provide energetic tracks to listen to while executing something simple as well as calmer tracks for focused attention while working on something more complex. I'm curious what others think What does Alice listen to while programming? Project EulerI saw Project Euler mentioned somewhere in a thread, and after visiting the site, I decided to try to learn programming by going through it. Sadly, this newfound resolve was short-lived because I couldn't get past the first problem: Raspberry Pi: I am (not) RetardedBought an MHS 3.5" LCD screen for pi 3b+. Looking for help regarding ARGsWell I got to know about ARG thin and was really interested to try them out. Stumbled on gatetrail.com and people said it is good for beginners but I don't seem to be able to make out the password for any of gate. I did found this hexadecimal string which led me to a image link but I doubt it can help me with much, at least it won;t help me with Gate 1 Quantum Computer ProgrammingSo, who here already experimented in programming for (theoretical) Quantum Computers? ITT: We become a better communityLets share our projects, help and learn together while contributing eachother's projects. This is what a community should do, right? /fpg/ - Functional Programming GeneralWelcome all, to the /lambda/ FP general! This thread serves as both a discussion of more abstract concepts of Functional design as well as a place to discuss/collaborate/bitch about specific FP languages and projects. LAINCORPSeveral lains and I are interested in forming a collective of web designers, web developers, and sales representatives to either collaborate on freelance projects or form an flat hierarchy LLC. If you are interested, please contact me on Telegram. Serious inquiries only. (private) or(private) or (group)(group) programming language/topics directoryartificial intelligence JavaScript DiscussionRight now my favorite language is javascript. I know and have used several other languages in the past, especially python, but I've decided that I see no reason to use anything but javascript nowdays, unless I need a certain tool for a specific job. Why? It turns out it's really comfortable to use, it makes sense, can look good if you format it nicely, it evolves quickly and smartly every year, it's everywhere: Web Applications, Desktop Applications, Mobile Applications, even on Embedded Devices (something I'm interested to try one day). I still have to catch up periodically because it's actually a pretty rich language, which ironically evolved from what appears to have been a quick hack. Right now it's still seen as a meme language by some, I personally fear Node, NPM and the ecosystem in general might not be as mature as they could be, but it works now and hopefully it evolves in an intelligent and safe way. Which books do I need to work through to get to a CompSci bachelors level?I've got 3 and a half years (7 Semesters) to teach myself everything someome coming out of a CompSci Bachelors education should know (takes 6 Semesters in my country). When and why did you start programming?Saw this over at the big shot thread and I decided to make it. chatbotsIn case the subject… chatbots Windows dynamic linkerThis is a long shot, but I'll take it: any of you lot know anything about Windows' dynamic linker? Sometimes I run into intermittent crashes and the like where the intermittency seems attributable to nondeterminacy at load time. I'd like to find a way to control that nondeterminacy, so when I hit these kinds of problems I can actually turn them into a reliable reproducer. Music htmlI want to add music to html website but it doesn't work, can you check it pls? C64 and similar 8-bit CPU based MicrocomputersI've recently taken to refreshing myself on 6502 assembly in order to write software for the C64. Initially I was torn between choosing learning assembly for the Gameboy and the C64, but I figured development would be more satisfying on the C64 since I would be able to see results on the physical hardware without much hassle. There are also some features of the 6502's instruction set that I like over the Gameboy's CPU such as the index registers being very helpful with working on larger amounts of data and not being restricted to perform comparisons exclusively on the accumulator. I believe the zero page is larger on the C64 as well as not being forced to transfer and execute a subroutine in the zero page just in order to update sprite RAM. short x = 2;short y = 2;// short z = x + y; -- won't compileshort z = (short) x + y // correct My first websiteHi Alice, I made my first working website. It is a small imageboard, it actually has only 2 boards(General and nsfw). I'm, of course, open to any suggestion and advice, please help me! :) Is it possible to learn Java programming in a month if you're a beginner?I want to learn Java programming at least the basic stuff ( OOP, Polymorphism, control flow ect..)Is it possible to do so in a months time for someone who has done a bit of programming but not too much; if so how would I go about doing it? What types of pdfs do I need, exercise sites ect.. DebuggingI have to debug a lot, most often code that I didn't write. But the problem is, I'm not very good at it. Is it possible to specifically train for it? Or is there some common methodology to it? Maybe some tips and tricks? Open SourceDoes Lain contribute to open source projects? Introductory Resources (Computer Science)A lot of "beginner" threads in programming boards aren't very academic and aren't really directed towards actual beginners. They almost never share resources for someone who has literally never typed a single line of code in their entire life. The following two textbooks and courses may be especially challenging for the person I've just described, but they actually start at the beginning and introduce one to programming in a rigorous manner that endows one with a conceptual understanding of the science of computation and how to think computationally rather than only how to engage in programming itself. ReverseAnyone know of any good resources for learning reverse engineering. On linux mostly because y'know, winblows. Attached is Dennis Yucharev's beginner reverse engineering book I just started reading it and I remember there being a site called "reverse.me" or something but I can't find it anymore and I know that it was down for a while. Reverse engineering thread: Poll Site with IMAGESI wanna make poll site. Basicly like strawpoll.me but images + multiple questions. new programmeryeah i'm really new to programming, but i'd really like to get into it. Where do I start? I've been taking "programming" classes at my high school but we really only get into basic Javascript/C#. Could you guys give me any good resources for continuing this? C#/C/C++ especially. Ugh.I decided to learn Python. Idk why I haven't decided to use the official tutorial, I found some plain tutorial on Python online (I don't need theory on how stuff work, I know C already) and decided to go with that. It was okay until I noticed some flaws in site itself, then errors in code and finally this. FOSDEM 2018The recordings from this year's FOSDEM are slowly being uploaded. There were so many interesting talks I don't even know where to start. Learning ProgrammingHow do i get a complete understanding of computers and programming in general? Exploit DevelopmentIn binary exploitation, what level of knowledge should one have on the C programming language? In my case I am interested in windows exploitation, but on any level how much should one know? Spectre/MeltdownSo I was reading through the example code in the Spectre vulnerabilty paper and found this line here: /* Avoid jumps in case those tip off the branch predictor */x = ((j % 6) -1) & ~0xFFFF; /* Set x=FFF.FF0000 if j%6==0, else x=0 */ THE HARM OF FOSS ZEALOTRYWhen people install any piece of software, proprietary or otherwise, they are doing so because they expect some utility from it. It adds something of value to their life. When you tell people to uninstall that same software, you are asking them to voluntarily remove that value from their life, often without an adequate replacement, whether you think so or not. There is no open source Adobe Photoshop. There is no open source Discord. There is no open source World of Warcraft. OS programmingThis may sound like the classic newbie-wants-to-do-something-really-hard, but I've been trying to study OS programming, cuz I would like to create my own. This is mostly for hobby purposes and because I feel that, by learning OS programming, I will be tackling down a lot of Computer Sciences topics and applying that knowledge. Scala ThreadHave the best of both worlds. Construct elegant class hierarchies for maximum code reuse and extensibility, implement their behavior using higher-order functions. Or anything in-between. Wat do?Just finished first semester of CS, my country doesn't seem to get it's soykaf together so I'lll have like 3 months off. What project could I start? I wanted to know more about backend web developing, as I found out that frontend is tedious af, but I don't really know where to start. Besides that, what does Lain think I should do? I'm really not that great at having ideas. Software CrackingAnyone here written a software crack before? #/usr/bin/env python3import sysimport hashlibif len(sys.argv) != 2: exit("USAGE: {} path/to/sublime_text".format(sys.argv[0]))sf = open(sys.argv[1], "rb")sublime_bin = sf.read()sf.close()if hashlib.sha1(sublime_bin).hexdigest() != "536ca1f2ceee8746caeebad3af7acaad19cd42ea": exit("""\ERROR: hash mismatch.This crack is only intended for this version of sublime: you want to try anyway, patch out this check at your own risk.""")print("""\ _____ _ _ ____ _ _____ __ __ ______ / ____| | | | _ \| | |_ _| \/ | ____|| (___ | | | | |_) | | | | | \ / | |__ \___ \| | | | _ <| | | | | |\/| | __| ____) | |__| | |_) | |____ _| |_| | | | |____ |_____/ \____/|____/|______|_____|_| |_|______| CRACKED BY KYNAR""")# Note: The function at 0x419468 checks the key. 1=VALIDprint("[+] Patching binary.")sublime_bin = sublime_bin.replace(b"\x89\xe8\x74\x4c", b"\xff\xc0\xeb\x4c")print("[+] Writing patch to disk.")sf = open(sys.argv[1], "wb")sf.write(sublime_bin)sf.close()print("[+] Done!")print("NOTE: In order to complete activation, either create the file ~/.config/sublime-text-3/Local/License.sublime_license, or simply attempt to activate with an invalid license.") Python Growth elixir on the webso have somewhat fallen for the elixir hype. written my way through 50-or-so Syntax HighlightingWhat syntax highlighting theme does lain use and why? I personally enjoy the aesthetic of Monokai, but also its ubiquitous presence on programming websites even when there are very few options available. The one I am presently using is called dark-monokai and, as such, it is slightly darker than is typical. DeepSpec Test-Driven-Learning?I had this idea and I wonder what do you think about it. programming typographyWhile I enjoy using as a general purpose monospace typeface, while coding I much prefer to useas a general purpose monospace typeface, while coding I much prefer to use Roboto Mono . I don't use it for its added ligatures though; I turn those off. I use it because it has additional weights not present in Mozilla's official. I don't use it for its added ligatures though; I turn those off. I use it because it has additional weights not present in Mozilla's official Fira Code font. I personally use the 'light' weight in my editor.font. I personally use the 'light' weight in my editor. Fira Mono Parsing EnginsI'm currently working on like a silly digital assistant that i started on a long time ago on my C64. #include <iostream> #include <string> #include <fstream> #include <cstdlib> #include <stdlib.h> #include <time.h> #include <unistd.h> using namespace std;/*||||||Functions Prototype Start||||||*//*||||||Functions Prototype End||||||*/ int main(){/*||||||Variables Start||||||*/ string mainContVar; int menu_return;/*||||||Variables End||||||*/ /*||||||Main Control Loop Start||||||*/ while(mainContVar != "Close" || mainContVar != "close") { cout << "H H OOO PPP EEE\n"; cout << "H H O O P P E \n"; cout << "HHHHH O O P P EE \n"; cout << "H H O O P E \n"; cout << "H H * OOO * P * EEE *\n\n" <<endl; cout << "Hello World! I am H.O.P.E.\n"; cout << "What can I do for you? "; cin >> mainContVar; if (mainContVar == "about" || mainContVar == "About") { cout << endl << "Well I'm H.O.P.E. I'm a digital assitant. Anymore than that and R0gU3 might be mad at me.\n" << endl; sleep(5); } else if (mainContVar == "hello" || mainContVar == "Hello") { cout << endl << "I already said hello...I mean sure it was to the whole world. But come on, what else you got?\n" << endl; sleep(5); } else if (mainContVar == "poop" || mainContVar == "Poop") { cout << endl << "Really man. Like is there really a point to that?\n" << endl; sleep(5); } system("cls"); system("clear"); }/*|||||Main Control Loop End||||||*/ return(0);}
https://archive.arisuchan.jp/%CE%BB/catalog.html
CC-MAIN-2021-31
refinedweb
2,875
63.9
This action might not be possible to undo. Are you sure you want to continue? A Perfect Hash Function Generator Douglas C. Schmidt schmidt@cs.wustl.edu Department of Computer Science Washington University, St. Louis 63130 1 Introduction Perfect hash functions are a time and space efficient implementation of static search sets. A static search set is an abstract data type (ADT) with operations initialize, insert, and retrieve. Static search sets are common in system software applications. Typical static search sets include compiler and interpreter reserved words, assembler instruction mnemonics, shell interpreter built-in commands, and CORBA IDL compilers. Search set elements are called keywords. Keywords are inserted into the set once, usually off-line at compile-time. gperf is a freely available perfect hash function generator written in C++ that automatically constructs perfect hash functions from a user-supplied list of keywords. It was designed in the spirit of utilities like lex [1] and yacc [2] to remove the drudgery associated with constructing time and space efficient keyword recognizers manually. gperf translates an n element list of user-specified keywords, called the keyfile, into source code containing a k element lookup table and the following pair of functions: hash uniquely maps keywords in the keyfile onto the range 0..k , 1, where k n. If k = n hash is considered a minimal perfect hash function. in word set uses hash to determine whether a particular string of characters occurs in the keyfile, using at most one string comparison in the common case. gperf is designed to run quickly for keyfiles containing several thousand keywords. gperf generates efficient ANSI and K&R C and C++ source code as output. It has been used to generate reserved keyword recognizers in lexical analyzers for several production and research compilers and language processing tools, including GNU C/C++ [3] and the TAO CORBA IDL compiler [4]. This paper is organized as follows: Section 2 outlines alternative static search set implementations and compares them with gperf-generated hash tables; Section 3 presents 1 a sample input keyfile; Section 4 highlights design patterns and implementation strategies used to develop gperf; Section 5 shows the results from empirical benchmarks between gperf-generated recognizers and other popular techniques for reserved word lookup; Section 6 outlines the limitations with gperfand potential enhancements; and Section 7 presents concluding remarks. 2 Static Search Set Implementations There are numerous implementations of static search sets. Common examples include sorted and unsorted arrays and linked lists, AVL trees, optimal binary search trees, digital search tries, deterministic finite-state automata, and various hash table schemes, such as open addressing and bucket chaining [5]. Different static search structure implementations offer trade-offs between memory utilization and search time efficiency and predictability. For example, an n element sorted array is space efficient. However, the average- and worst-case time complexity for retrieval operations using binary search on a sorted array is proportional to Olog n [5]. In contrast, chained hash table implementations locate a table entry in constant, i.e., O1, time on the average. However, hashing typically incurs additional memory overhead for link pointers and/or unused hash table buckets. In addition, hashing exhibits On2 worst-case performance [5]. A minimal perfect hash function is a static search set implementation defined by the following two properties: The perfect property: Locating a table entry requires O1 time, i.e., at most one string comparison is required to perform keyword recognition within the static search set. The minimal property: The memory allocated to store the keywords is precisely large enough for the keyword set and no larger. Minimal perfect hash functions provide a theoretically optimal time and space efficient solution for static search sets [5]. However, they are hard to generate efficiently due to the extremely large search space of potential perfect hashing functions. Therefore, the following variations are often more appropriate for many practical hashing applications, especially those involving thousands of keywords: Non-minimal perfect hash functions: These functions do not possess the minimal property since they return a range of hash values larger than the total number of keywords in the table. However, they do possess the perfect property since at most one string comparison is required to determine if a string is in the table. There are two reasons for generating non-minimal hash functions: 1. Generation efficiency – It is usually much faster to generate non-minimal perfect functions than to generate minimal perfect hash functions [6, 7]. 2. Run-time efficiency – Non-minimal perfect hash functions may also execute faster than minimal ones when searching for elements that are not in the table because the “null” entry will be located more frequently. This situation often occurs when recognizing programming language reserved words in a compiler [8]. %{ #include <stdio.h> #include <string.h> /* Command-line options: -C -p -a -n -t -o -j 1 -k 2,3 -N is_month */ %} struct months { %% /* Auxiliary code goes here... */ #ifdef DEBUG int main () { char buf[BUFSIZ]; while (gets (buf)) { struct months *p = is_month (buf, strlen (buf)); printf ("%s is%s a month\n", p ? p->name : buf, p ? "" : " not"); } } #endif Near-perfect hash functions: Near-perfect hash functions do not possess the perfect property since they allow nonFigure 1: An Example Keyfile for Months of the Year unique keyword hash values [9] (they may or may not possess the minimal property, however). This technique is a compromise that trades increased generated-code-execution-time for month, as well as the months’ ordinal numbers, i.e., january = decreased function-generation-time. Near-perfect hash func- 1, february = 2, . . . , december = 12. gperf’s input format is similar to the UNIX utilities lex tions are useful when main memory is at a premium since they tend to produce much smaller lookup tables than non-minimal and yacc. It uses the following input format: perfect hash functions. declarations and text inclusions gperf can generate minimal perfect, non-minimal perfect, %% keywords and optional attributes and near-perfect hash functions, as described below. %% auxiliary code A pair of consecutive % symbols in the first column separate declarations from the list of keywords and their optional This section explains how end-users can interact with gperf. attributes. C or C++ source code and comments are included By default, gperf reads a keyword list and optional associ- verbatim into the generated output file by enclosing the text inated attributes from the standard input keyfile. Keywords side %{ %} delimiters, which are stripped off when the output are specified as arbitrary character strings delimited by a user- file is generated, e.g.: specified field separator that defaults to ’,’. Thus, keywords may contain spaces and any other ASCII characters. Associ- %{ #include <stdio.h> ated attributes can be any C literals. For example, keywords in #include <string.h> Figure 1 represent months of the year. Associated attributes in /* Command-line options: -C -p -a -n -t -o -j 1 -k 2,3 this figure correspond to fields in struct months. They in-N is_month */ clude the number of leap year and non-leap year days in each %} 2 3 Interacting with GPERF An optional user-supplied struct declaration may be placed at the end of the declaration section, just before the %% separator. This feature enables “typed attribute” initialization. For example, in Figure 1 struct months is defined to have four fields that correspond to the initializer values given for the month names and their respective associated values, e.g.: struct months { char *name; int number; int days; int leap_days; }; %% however, describe the design and implementation of a generalpurpose perfect hashing generator tool in detail. This section describes the data structures, algorithms, output format, and reusable components in gperf. gperf is written in 4,000 lines of C++ source code. C++ was chosen as the implementation language since it supports data abstraction better than C, while maintaining C’s efficiency and expressiveness [16]. gperf’s three main phases for generating a perfect or nearperfect hash function are shown in Figure 2: Figure 6 illustrates gperf’s overall program structure. and described be- Lines containing keywords and associated attributes appear KEYFILE GPERF C/C++ CODE in the keywords and optional attributes section of the keyfile. int hash january Key_List The first field of each line always contains the keyword itself, february (const char *str, unsigned int len) left-justified against the first column and without surround- ... { Asso_Values ing quotation marks. Additional attribute fields can follow december // ... the keyword. Attributes are separated from the keyword and from each other by field separators, and they continue up to the Figure 2: gperf’s Processing Phases “end-of-line marker,” which is the newline character (’\n’) by default. low: Attribute field values are used to initialize components of the user-supplied struct appearing at the end of the decla1. Process command-line options, read keywords and atration section, e.g.: tributes (the input format is described in Section 3), and initialize internal objects (described in Section 4.1). january, 1, 31, 31 february, march, ... 2, 3, 28, 31, 29 31 As with lex and yacc, it is legal to omit the initial declaration section entirely. In this case, the keyfile begins with the first non-comment line (lines beginning with a "#" character are treated as comments and ignored). This format style is useful for building keyword set recognizers that possess no associated attributes. For example, a perfect hash function for frequently occurring English words can efficiently filter out uninformative words, such as “the,” “as,” and “this,” from consideration in a key-word-in-context indexing application [5]. Again, as with lex and yacc, all text in the optional third auxiliary code section is included verbatim into the generated output file, starting immediately after the final %% and extending to the end of the keyfile. It is the user’s responsibility to ensure that the inserted code is valid C or C++. In the Figure 1 example, this auxiliary code provides a test driver that is conditionally included if the DEBUG symbol is enabled when compiling the generated C or C++ code. 2. Perform a non-backtracking, heuristically guided search for a perfect hash function (described in Section 4.2.1 and Section 4.2.2). 3. Generate formatted C or C++ code according to the command-line options (output format is described in Section 4.3). The following section outlines gperf’s perfect hash function generation algorithms and internal objects, examines its generated source code output, describes several reusable class components, and discusses the program’s current limitations and future enhancements. 4.1 Internal Objects gperf’s implementation centers around two internal objects: the keyword signatures list (Key List) and the associated values array (asso values), both of which are described below. 4.1.1 The Keyword Signatures List 4 Design and Implementation Strategies Every user-specified keyword and its attributes are read from the keyfile and stored in a node on a linked list, called Key List. gperf only considers a subset of each keyMany articles describe perfect hashing [10, 7, 11, 12] and min- words’ characters while it searches for a perfect hash function. imal perfect hashing algorithms [8, 13, 6, 14, 15]. Few articles, The subset is called the “keyword signature,” or keysig. 3 The keysig represents the particular subset of characters hash_value = asso_values[keyword[0]] used by the automatically generated recognition function to + asso_values[keyword[1]] compute a keyword’s hash value. Keysigs are created and + asso_values[keyword[length - 1]] + length; cached in each node in the Key List when the keyfile is initially processed by gperf. Developers can control the generated hash function’s contents using the "-k" option to explicitly specify the keyword 4.1.2 Associated Values Array index positions used as keysig elements by gperf. The deThe associated values array, asso values, is an object that fault is "-k 1,$", where the ’$’ represents the keyword’s is closely related to keysigs. In fact, it is indexed by keysig final character. Table 1 shows the keywords, keysigs, and hash value for characters. The array is constructed internally by gperf and each month shown in the Figure 1 keyfile. These keysigs were referenced frequently while gperf searches for a perfect hash function. Keyword Keysig Hash Value During the C/C++ code generation phase of gperf, an january an 3 ASCII representation of the associated array is output in the february be 9 generated hash function as a static local array. This array march ar 4 is declared as u int asso values[MAX ASCII SIZE]. april pr 2 When searching for a perfect hash function, gperf repeatedly may ay 8 reassigns different values to certain asso values elements june nu 1 specified by keysig entries. At every step during the search july lu 6 august gu 7 for the perfect hash function solution, the asso values arseptember ep 0 ray’s contents represent the current associated values’ configoctober ct 10 uration. november ov 11 When configured to produce minimal perfect hash functions december ce 5 (which is the default), gperf searches for an associated values configuration that maps all n keysigs onto non-duplicated hash values. A perfect hash function is produced when gperf Table 1: Keywords, Keysigs, and Hash Values for the Months finds a configuration that assigns each keysig to a unique loca- Example tion within the generated lookup table. The resulting perfect hash function returns an unsigned int value in the range produced using the -k2,3 option. 0::k , 1, where k = (maximum keyword hash value +1). Keysigs are multisets since they may contain multiple ocWhen k = n a minimal perfect hash function is produced. currences of certain characters. This approach differs from For k larger than n, the lookup table’s load factor is n other perfect hash function generation techniques [8] that only k of keywords ( number table size ). consider first/last characters + length when computing a keytotal A keyword’s hash value is typically computed by combin- word’s hash value. ing the associated values of its keysig with its length.1 By The hash function generated by gperf properly handles default, the hash function adds the associated value of a key- keywords shorter than a specified index position by skipping word’s first index position plus the associated value of its last characters that exceed the keyword’s length. In addition, users index position to its length, i.e.: can instruct gperf to include all of a keyword’s characters in its keysig via the "-k*" option. hash_value = asso_values[keyword[0]] + asso_values[keyword[length - 1]] + length; 4.2 Generating Perfect Hash Functions This subsection describes how gperf generates perfect hash Other combinations are often necessary in practice. For examfunctions. ple, using the default hash function for C++ reserved words causes a collision between delete and double. To resolve this collision and generate a perfect hash function for C++ re- 4.2.1 Main Algorithm served words, an additional character must be added to the gperf iterates sequentially through the list of i keywords, keysig, as follows: 1 i n, where n equals the total number of keywords. 1 The "-n" option instructs gperf not include the length of the keyword During each iteration gperf attempts to extend the set of when computing the hash function. uniquely hashed keywords by 1. It succeeds if the hash value 4 computed for keyword i does not collide with the previous i,1 collision between january and march by incrementing uniquely hashed keywords. Figure 3 outlines the algorithm. asso value[’n’] by 1. As shown in Table 2, this is its final value. for i 1 to n loop if hash (ith key) collides with any hash (1st key ... i 1st key) then modify disjoint union of associated values to resolve collisions based upon certain collision resolution heuristics end if end loop , Figure 3: Gperf’s Main Algorithm The algorithm terminates and generates a perfect hash function when i = n and no unresolved hash collisions remain. Thus, the best-case asymptotic time-complexity for this algorithm is linear in the number of keywords, i.e., n. 4.2.2 Collision Resolution Strategies Keysig Characters ’a’ ’b’ ’c’ ’e’ ’g’ ’l’ ’n’ ’o’ ’p’ ’r’ ’t’ ’u’ ’v’ ’y’ Associated Values 2 9 5 0 7 6 1 1 0 2 5 0 0 6 Frequency of Occurrence 3 1 2 3 1 1 2 1 2 2 1 3 1 1 As outlined in Figure 3, gperf attempts to resolve keyword Table 2: Associated Values and Occurrences for Keysig Charhash collisions by incrementing certain associated values. The acters following discusses the strategies gperf uses to speedup collision resolution. Search heuristics: gperf uses several search heuristics to reduce the time required to generate a perfect hash function. Disjoint union: To avoid performing unnecessary work, For instance, characters in the disjoint union are sorted by ingperf is selective when changing associated values. In par- creasing frequency of occurrence, so that less frequently used ticular, it only considers characters comprising the disjoint characters are incremented before more frequently used charunion of the colliding keywords’ keysigs. The disjoint union acters. This strategy is based on the assumption that increof two keysigs fAg and fB g is defined as fA B g,fA B g. menting infrequently used characters first decreases the negaTo illustrate the use of disjoint unions, consider the key- tive impact on keywords that are already uniquely hashed with words january and march from Figure 1. These key- respect to each other. Table 2 shows the associated values and words have the keysigs ‘‘an’’ and ‘‘ar’’, respectively, frequency of occurrences for all the keysig characters in the as shown in Table 1. Thus, when asso values[’a’], months example. asso values[’n’], and asso values[’r’] all equal 0, a collision will occur during gperf’s execution.2 To regperf generates a perfect hash function if increments to solve this collision, gperf only considers changing the as- the associated values configuration shown in Figure 3 and desociated values for ’n’ and/or ’r’. Changing ’a’ by any scribed above eliminate all keyword collisions when the end increment cannot possibly resolve the collision since ’a’ oc- of the Key List is reached. The worst-case asymptotic timecurs the same number of times in each keysig. complexity for this algorithm is On3 l, where l is the number By default, all asso values are initialized to 0. When a of characters in the largest disjoint union between colliding collision is detected gperf increases the corresponding asso- keyword keysigs. After experimenting with gperf on many ciated value by a “jump increment.” The command-line option keyfiles it appears that such worst-case behavior occurs rarely "-j" can be used to increase the jump increment by a fixed in practice. or random amount. In general, selecting a smaller jump increMany perfect hash function generation algorithms [6, 7] are ment, e.g., "-j 1" decreases the size of the generated hash sensitive to the order in which keywords are considered. To table, though it may increase gperf’s execution time. mitigate the effect of ordering, gperf will optionally reorder In the months example in Figure 1, the "-j 1" op- keywords in the Key List if the "-o" command-line option was used. Therefore, gperf quickly resolves the tion is enabled. This reordering is done in a two-stage pre2 Note that since the "-n" option is used in the months example, the different keyword lengths are not considered in the resulting hash function. pass [8] before gperf invokes the main algorithm shown in Figure 3. First, the Key List is sorted by decreasing fre5 quency of keysig characters occurrence. The second reordering pass then reorders the Key List so that keysigs whose values are “already determined” appear earlier in the list. These two heuristics help to prune the search space by handling inevitable collisions early in the generation process. gperf will run faster on many keyword sets, and often decrease the perfect hash function range, if it can resolve these collisions quickly by changing the appropriate associated values. However, if the number of keywords is large and the user wishes to generate a near-perfect hash function, this reordering sometimes increases gperf’s execution time. The reason for this apparent anomaly is that collisions begin earlier and frequently persist throughout the remainder of keyword processing [8, 9]. #include <stdio.h> #include <string.h> /* Command-line options: -C -p -a -n -t -o -j 1 -k 2,3 -N is_month */ struct months { char *name; int number; int days; int leap_days; }; enum { TOTAL_KEYWORDS = 12, MIN_WORD_LENGTH = 3, MAX_WORD_LENGTH = 9, MIN_HASH_VALUE = 0, MAX_HASH_VALUE = 11, HASH_VALUE_RANGE = 12, DUPLICATES = 0 }; static unsigned int hash (const char *str, unsigned int len) { static const unsigned char asso_values[] = {, 2, 9, 5, 12, 0, 12, 7, 12, 12, 12, 12, 6, 12, 1, 11, 0, 12, 2, 12, 5, 0, 0, 12, 12, 6, 12, 12, 12, 12, 12, 12, }; return asso_values[str[2]] + asso_values[str[1]]; } const struct months * is_month (const char *str, unsigned int len) { static const struct months wordlist[] = { {"september", 9, 30, 30}, {"june", 6, 30, 30}, {"april", 4, 30, 30}, {"january", 1, 31, 31}, {"march", 3, 31, 31}, {"december", 12, 31, 31}, {"july", 7, 31, 31}, {"august", 8, 31, 31}, {"may", 5, 31, 31}, {"february", 2, 28, 29}, {"october", 10, 31, 31}, {"november", 11, 30, 30}, }; if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) { int key = hash (str, len); if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE) { char *s = wordlist[key].name; if (*str == *s && !strcmp (str + 1, s + 1)) return &wordlist[key]; } } return 0; } 4.3 Generated Output Format Figure 4 depicts the C code produced from the gperfgenerated minimal perfect hash function corresponding to the keyfile depicted in Figure 1. Execution time was negligible on a Sun SPARC 20 workstation, i.e., 0.0 user and 0.0 system time. The following section uses portions of this code as a working example to illustrate various aspects of gperf’s generated output format. 4.3.1 Generated Symbolic Constants gperf’s output contains the following seven symbolic constants that summarize the results of applying the algorithm in Figure 3 to the keyfile in Figure 1: enum { TOTAL_KEYWORDS = 12, MIN_WORD_LENGTH = 3, MAX_WORD_LENGTH = 9, MIN_HASH_VALUE = 0, MAX_HASH_VALUE = 11, HASH_VALUE_RANGE = 12, DUPLICATES = 0 }; gperf produces a minimal perfect hash function when HASH VALUE RANGE TOTAL KEYWORDS and DUPLI CATES . A non-minimal perfect hash function occurs when DUPLICATES 0 and HASH VALUE RANGE TOTAL KEYWORDS. Finally, a near-perfect hash function occurs when DUPLICATES 0 and DUPLICATES TO TAL KEYWORDS. = 0 = = 4.3.2 The Generated Lookup Table By default, when gperf is given a keyfile as input it attempts to generate a perfect hash function that uses at most Figure 4: Minimal Perfect Hash Function Generated by one string comparison to recognize keywords in the lookup ta- gperf ble. gperf can implement the lookup table either an array or a switch statement, as described below. 6 asso values array lookup table: gperf generates an array by default, emphasizing run-time speed over minimal memory utilization. This array is called asso values, as shown in the hash function in Figure 4. The asso values array is used by the two generated functions that compute hash values and perform table lookup. gperf also provides command-line options that allow developers to select trade-offs between memory size and execution time. For example, expanding the range of hash values produces a sparser lookup table. This generally yields faster keyword searches but requires additional memory. The array-based asso values scheme works best when the HASH VALUE RANGE is not considerably larger than the TOTAL KEYWORDS. When there are a large number of keywords, and an even larger range of hash values, however, the wordlist array in is month function in Figure 4 may become extremely large. Several problems arise in this case: The time to compile the sparsely populated array is excessive; { const struct months *rw; switch (key) { case 0: rw = &wordlist[0]; break; case 1: rw = &wordlist[1]; break; case 2: rw = &wordlist[2]; break; case 3: rw = &wordlist[3]; break; case 4: rw = &wordlist[4]; break; case 5: rw = &wordlist[5]; break; case 6: rw = &wordlist[6]; break; case 7: rw = &wordlist[7]; break; case 8: rw = &wordlist[8]; break; case 9: rw = &wordlist[9]; break; case 10: rw = &wordlist[10]; break; case 11: rw = &wordlist[11]; break; default: return 0; } if (*str == *rw->name && !strcmp (str + 1, rw->name + 1)) return rw; return 0; } Figure 5: The switch-based Lookup Table The array size may be too large to store in main memory; 4.3.3 The Generated Functions A large array may lead to increased “thrashing” of virtual gperf generates a hash function and a lookup function. By default, they are called hash and in word set, although memory in the OS. a different name may be given for in word set using the "-N" command-line option. Both functions require two arguments, a pointer to a NUL-terminated (’\0’) array of Switch-based lookup table: To handle the problems decharacters, const char *str, and a length parameter, scribed above, gperf can also generate one or more switch unsigned int len. statements to implement the lookup table. Depending on the underlying compiler’s switch optimization capabilities, the The generated hash function (hash): Figure 4 shows the switch-based method may produce smaller and faster code, hash function generated from the input keyfile shown in Figcompared with the large, sparsely filled array. Figure 5 shows ure 1. The command-line option "-k 2,3" was enabled for how the switch statement code appears if the months exam- this test. This instructs hash to return an unsigned int ple is generated with gperf’s "-S 1" option. hash value that is computed by using the ASCII values of the 2nd and 3rd characters from its str argument into the local Since the months example is somewhat contrived, the tradeoff between the array and switch approach is not particularly static array asso values.3 The two resulting numbers obvious. However, good C++ compilers generate assembly are added to calculate str’s hash value. The asso values array is generated by gperf using the code implementing a “binary-search-of-labels” scheme if the algorithm in Section 4.1.2. This array maps the user-defined switch statement’s case labels are sparse compared to the range between the smallest and largest case labels [3]. This keywords onto unique hash values. All asso values array technique can save a great deal of space by not emitting un- entries with values greater than MAX HASH VALUE (i.e., all necessary empty array locations or jump-table slots. The exact the “12’s” in the asso values array in Figure 4) represent time and space savings of this approach varies according to the ASCII characters that do not occur as either the second or third characters in the months of the year. The is month function underlying compiler’s optimization strategy. in Figure 4 uses this information to quickly eliminate input gperf generates source code that constructs the array or switch statement lookup table at compile-time. Therefore, strings that cannot possibly be month names. initializing the keywords and any associated attributes requires Generated lookup function (in word set): The little additional execution-time overhead when the recognizer in word set function is the entry point into the perfect function is run. The “initialization” is automatically per- hash lookup function. In contrast, the hash function is formed as the program’s binary image is loaded from disk into 3 Note that C arrays start at 0, so str[1] is actually the second character. main memory. 7 declared static and cannot be invoked by application programs directly. If the function’s first parameter, char *str, is a valid user-define keyword, in word set returns a pointer to the corresponding record containing each keyword and its associated attributes; otherwise, a NULL pointer is returned. Figure 4 shows how the in word set function can be renamed to is month using the "-N" command-line option. Note how gperf checks the len parameter and resulting hash function return value against the symbolic constants for MAX WORD LENGTH, MIN WORD LENGTH, MAX HASH VALUE , and MIN HASH VALUE . This check quickly eliminates many non-month names from further consideration. If users know in advance that all input strings are valid keywords, gperf will suppress this addition checking with the "-O" option. If gperf is instructed to generate an array-based lookup table the generated code is quite concise, i.e., once it is determined that the hash value lies within the proper range the code is simply: { char *s = wordlist[key]; if (*s == *str && !strcmp (str + 1, s + 1)) return s; } ASSO VALUES KEY LIST GEN PERF GPERF COMPONENTS ACE COMPONENTS READ BUFFER HASH TABLE BOOL ARRAY SINGLETON Figure 6: gperf’s Software Architecture The *s == *str expression quickly detects when the computed hash value indexes into a “null” table slot since *s is the NUL character (’\0’) in this case. This check is useful when searching a sparse keyword lookup table, where there is a higher probability of locating a null entry. If a null entry is located, there is no need to perform a full string comparison. Since the months’ example generates a minimal perfect hash function null enties never appear. The check is still useful, however, since it avoids calling the string comparison function when the str’s first letter does not match any of the keywords in the lookup table. 4.4 Reusable Components and Patterns Figure 6 illustrates the key components used in gperf’s software architecture. gperf is constructed from reusable components from the ACE framework [17]. Each component evolved “bottom-up” from special-purpose utilities into reusable software components. Several noteworthy reusable classes include the following components: ACE Bool Array: Earlier versions of gperf were instrumented with a run-time code profiler on large input keyfiles that evoke many collisions. The results showed that gperf spent approximately 90 to 99 percent of its time in a single function when performing the algorithm in Figure 3. 8 This one function, Gen Perf::affects previous, determines how changes to associated values affect previously hashed keywords. In particular, it identifies duplicate hash values that occur during program execution. Since this function is called so frequently, it is important to minimize its execution overhead. Therefore, gperf employs a novel boolean array component called ACE Bool Array to expedite this process. The C++ interface for the ACE Bool Array class is depicted in Figure 7. Since only one copy is required, BOOL ARRAY is typedef’d to be a Singleton using the ACE Singleton adapter. This template automatically transforms a class into a Singleton using the Singleton and Adapter patterns [18]. The in set method efficiently detects duplicate keyword hash values for a given associated values configuration. It returns non-zero if a value is already in the set and zero otherwise. Whenever a duplicate is detected, the reset method is called to reset all the array elements back to “empty” for ensuing iterations of the search process. If many hash collisions occur, the reset method is executed frequently during the duplicate detection and elimination phase of gperf’s algorithm. Processing large keyfiles, e.g., containing more than 1,000 keywords, tends to require a maximum hash value k that is often much larger than n, the total number of keywords. Due to the large range, it becomes expensive to explicitly reset all elements in array back to empty, especially when the number of keywords actually checked for duplicate hash values is comparatively small. To address this issue, gperf uses a pattern called generation numbering, which optimizes the search process by not class ACE\_Bool_Array { public: // Constructor. ACE\_Bool_Array (void); // Returns dynamic memory to free store. ˜ACE_Bool_Array (void); // Allocate a k element dynamic array. init (u_int k); // Checks if <value> is a duplicate. int in_set (u_int value); // Reinitializes all set elements to FALSE. void reset (void); private: // Current generation count. u_short generation_number_; // Dynamically allocated storage buffer. u_short *array_; // Length of dynamically allocated array. u_int size_; }; // Create a Singleton. typedef ACE_Singleton <ACE_Bool_Array, ACE_Null_Mutex> BOOL_ARRAY; unsigned short integer, which occurs infrequently in practice. A design strategy employed throughout gperf’s implementation is “first determine a clean set of operations and interfaces, then successively tune the implementation.” In the case of generation numbering, this policy of optimizing performance, without compromising program clarity, decreased gperf’s execution-time by an average of 25 percent for large keyfiles, compared with the previous method that explicitly “zeroed out” the entire boolean array’s contents on every reset. ACE Read Buffer: Each line in gperf’s input contains a single keyword followed by any optional associated attributes, ending with a newline character (’\n’). The Read Buffer::read member function copies an arbitrarily long ’\n’-terminated string of characters from the input into a dynamically allocated buffer. A recursive auxiliary function, Read Buffer::rec read, ensures only one call is made to the new opeator for each input line read, i.e., there is no need to reallocate and resize buffers dynamically. This class has been incorporated into the GNU libg++ stream library [19] and the ACE network programming tookit [17]. ACE Hash Table: This class provides a search set implemented via double hashing [5]. During program initialization explicitly reinitializing the entire array. Generation number- gperf uses an instance of this class to detect keyfile entries that are guaranteed to produce duplicate hash values. These ing operates as follows: duplicates occur whenever keywords possess both identical 1: The Bool Array init method dynamically allocates keysigs and identical lengths, e.g., the double and delete space for k unsigned short integers and points array collision described in Section 4.1.2. Unless the user speciat the allocated memory. All k array elements in array fies that a near-perfect hash function is desired, attempting to are initially assigned 0 (representing “empty”) and the generate a perfect hash function for keywords with duplicate generation number counter is set to 1. keysigs and identical lengths is an exercise in futility! 2: gperf uses the in set method is used to detect duplicate keyword hash values. If the number stored at the hash(keyword) index position in array is not equal to the current generation number, then that hash value is not already in the set. In this case, the current generation number is immediately assigned to the hash(keyword) array location, thereby marking it as a duplicate if it is referenced subsequently during this particular iteration of the search process. 3: If array [hash(keyword)] is equal to the generation number, a duplicate exists and the algorithm must try modifying certain associated values to resolve the collision. 4: If a duplicate is detected, the array elements are reset to empty for subsequent iterations of the search process. The reset method simply increments generation number by 1. The entire k array locations are only reinitialized to 0 when the generation number exceeds the range of an 9 Figure 7: The ACE Boolean Array Component 5 Empirical Results Tool-generated recognizers are useful from a software engineering perspective since they reduce development time and decrease the likelyhood of development errors. However, they are not necessarily advantageous for production applications unless the resulting executable code speed is competitive with typical alternative implementations. In fact, it has been argued that there are no circumstances where perfect hashing proves worthwhile, compared with other common static search set methods [20]. To compare the efficacy of the gperf-generated perfect hash functions against other common static search set implementations, seven test programs were developed and executed on six large input files. Each test program implemented the same function: a recognizer for the reserved words in GNU Executable Program control.exe trie.exe flex.exe gperf.exe chash.exe patricia.exe binary.exe comp-flex.exe ET++.in 38.8 j 1.00 59.1 j 1.52 60.5 j 1.55 64.6 j 1.66 69.2 j 1.78 71.7 j 1.84 72.5 j 1.86 80.1 j 2.06 NIH.in 15.4 j 1.00 23.8 j 1.54 23.9 j 1.55 26.0 j 1.68 27.5 j 1.78 28.9 j 1.87 29.3 j 1.90 31.0 j 2.01 Input File g++.in idraw.in 15.2 j 1.00 8.9 j 1.00 23.8 j 1.56 13.7 j 1.53 23.9 j 1.57 13.8 j 1.55 25.1 j 1.65 14.6 j 1.64 27.1 j 1.78 15.8 j 1.77 27.8 j 1.82 16.3 j 1.83 28.5 j 1.87 16.4 j 1.84 32.6 j 2.14 18.2 j 2.04 cfront.in 5.7 j 1.00 8.6 j 1.50 8.9 j 1.56 9.7 j 1.70 10.1 j 1.77 10.8 j 1.89 10.8 j 1.89 11.6 j 2.03 libg++.in 4.5 j 1.00 7.0 j 1.55 7.1 j 1.57 7.7 j 1.71 8.2 j 1.82 8.7 j 1.93 8.8 j 1.95 9.2 j 2.04 Table 3: Raw and Normalized CPU Processing Time g++ . The function returns 1 if a given input string is identified as a reserved word and 0 otherwise. The seven test programs are described below. They are listed by increasing order of execution time, as shown in Table 3. The input files used for the test programs are described in Table 4. Table 5 shows the number of bytes for each test Input File ET++.in NIH.in g++.in idraw.in cfront.in libg++.in Identifiers 624,156 209,488 278,319 146,881 98,335 69,375 Keywords 350,466 181,919 88,169 74,744 51,235 50,656 Total 974,622 391,407 366,488 221,625 149,570 120,031 automata (DFA)-based recognizers. Not using compaction maximizes speed in the generated recognizer, at the expense of much larger tables. For example, the uncompacted flex.exe program is almost 5 times larger than the compacted comp-flex.exe program, i.e., 117,808 bytes versus 24,416 bytes. gperf.exe: a gperf-generated recognizer created with the "-a -D -S 1 -k 1,$" options. These options mean “generate ANSI C prototypes ("-a"), handle duplicate keywords ("-D"), via a single switch statement ("-S 1"), and make the keysig be the first and last character of each keyword.” chash.exe: a dynamic chained hash table lookup function similar to the one that recognizes reserved words for AT&T’s Table 4: Total Identifiers and Keywords for Each Input File cfront 3.0 C++ compiler. The table’s load factor is 0.39, the program’s compiled object file, listed by increasing size (both same as it is in cfront 3.0. patricia.o and chash.o use dynamic memory, so their patricia.exe: a PATRICIA trie recognizer, where PATRICIA overall memory usage depends upon the underlying free store stands for “Practical Algorithm to Retrieve Information Coded mechanism). in Alphanumeric.” A complete PATRICA trie implementation is available in the GNU libg++ class library distribution [19]. Object File control.o binary.o gperf.o chash.o patricia.o comp-flex.o trie.o flex.o text 88 1,008 2,672 1,608 3,936 7,920 79,472 3,264 data 0 288 0 304 0 56 0 98,104 Byte Count bss dynamic 0 0 0 0 0 0 8 1,704 0 2,272 16,440 0 0 0 16,440 0 total 88 1,296 2,672 3,624 6,208 24,416 79,472 117,808 binary.exe: a carefully coded binary search function that minimizes the number of complete string comparisons. comp-flex.exe: a flex-generated recognizer created with the default "-cem" options, providing the highest degree of table compression. Note the obvious time/space tradeoff between the uncompacted flex.exe (which is faster and larger) and the compacted comp-flex.exe (which is smaller and much slower). In addition to these seven test programs, a simple C++ program called control.exe measures and controls for I/O trie.exe: a program based upon an automatically generated overhead, i.e.: table-driven search trie created by the trie-gen utility included int main (void) { with the GNU libg++ distribution. char buf[BUFSIZ]; Table 5: Size of Object Files in Bytes flex.exe: a flex-generated recognizer created with the while (gets (buf)) "-f" (no table compaction) option. Note that both the printf ("%s", buf); flex.exe and trie.exe are uncompacted, deterministic finite } 10 All of the above reserved word recognizer programs were compiled by the GNU g++ 2.7.2 compiler with the "-O2 -finline-functions" options enabled. They were then tested on an otherwise idle SPARCstation 20 model 712 with 128 megabytes of RAM. All six input files used for the tests contained a large number of words, both user-defined identifiers and g++ reserved words, organized with one word per line. This formate was automatically created by running the UNIX command "tr -cs A-Za-z_ ’\012’" on the preprocessed source code for several large C++ systems, including the ET++ windowing toolkit (ET++.in), the NIH class library (NIH.in), the GNU g++ 2.7.2 C++ compiler (g++.in), the idraw figure drawing utility from the InterViews 2.6 distribution (idraw.in), the AT&T cfront 3.0 C++ compiler (cfront.in), and the GNU libg++ 2.8 C++ class library (libg++.in). Table 4 shows the relative number of identifiers and keywords for the test input files. Table 3 depicts the amount of time each search set implementation spent executing the test programs, listed by increasing execution time. The first number in each column represents the user-time CPU seconds for each recognizer. The second number is “normalized execution time,” i.e., the ratio of user-time CPU seconds divided by the control.exe program execution time. The normalized execution time for each technique is very consistent across the input test file suite, illustrating that the timing results are representative for different source code inputs. Several conclusions result from these empirical benchmarks: Time/space tradeoffs are common: The uncompacted, DFA-based trie (trie.exe) and flex (flex.exe) implementations are both the fastest and the largest implementations, illustrating the time/space trade-off dichotomy. Applications where saving time is more important than conserving space may benefit from these approaches. gperf can provide the best of both worlds: While the trie.exe and flex.exe recognizers allow programmers to trade-off space for time, the gperf-generated perfect hash function gperf.exe is comparatively time and space efficient. Empirical support for this claim can be calculated from the data for the programs that did not allocate dynamic memory, i.e., trie.exe, flex.exe, gperf.exe, binary.exe, and comp-flex.exe. The number of identifiers scanned per-second, per-byte of executable program overhead was 5.6 for gperf.exe, but less than 1.0 for trie.exe, flex.exe, and comp-flex.exe. Since gperf generates a stand-alone recognizer, it is easily incorporated into an otherwise hand-coded lexical analyzer, such as the ones found in the GNU C and GNU C++ com- piler. It is more difficult, on the other hand, to partially integrate flex or lex into a lexical analyzer since they are generally used in an “all or nothing” fashion. Furthermore, neither flex nor lex are capable of generating recognizers extremely large keyfiles because the size of the state machine is too big for their internal DFA state tables. 6 Current Limitations and Future Work gperf has been freely distributed for many years along with the GNU libg++ library and the ACE network programming toolkit at˜schmidt/ACE.html. Although gperf has proven to be quite useful in practice, there are several limitations. This section describes the tradeoffs and compromises with its current algorithms and outlines how it can be improved. Since gperf is open source software, however, it is straightforward to add enhancements and extensions. 6.1 Tradeoffs and Compromises Several other hash function generation algorithms utilize some form of backtracking when searching for a perfect or minimal perfect solution [6, 8, 9]. For example, Cichelli’s [8] algorithm recursively attempts to find an associated values configuration that uniquely maps all n keywords to distinct integers in the range 1::n. In his scheme, the algorithm “backs up” if computing the current keyword’s hash value exceeds the minimal perfect table size constraint at any point during program execution. Cichelli’s algorithm then proceeds by undoing selected hash table entries, reassigning different associated values, and continuing to search for a solution. Unfortunately, the exponential growth rate associated with the backtracking search process is simply too time consuming for large keyfiles. Even “intelligently-guided” exhaustive search quickly becomes impractical for more than several hundred keywords. To simplify the algorithm in Figure 3, and to improve average-case performance, gperf does not backtrack when keyword hash collisions occur. Thus, gperf may process the entire keyfile input, without finding a unique associated values configuration for every keyword, even if one exists. If a unique configuration is not found, users have two choices: 1. They can run gperf again, enabling different options in search of a perfect hash function; or 2. They can guarantee a solution by instructing gperf to generate an near-perfect hash function. 11 Near-perfect hash functions permit gperf to operate on keyword sets that it otherwise could not handle, e.g., if the keyfile contains duplicates or there are a very large number of keywords. Although the resulting hash function is no longer “perfect,” it handles keyword membership queries efficiently since only a small number of duplicates usually remain.4 Both duplicate keyword entries and unresolved keyword collisions are handled by generalizing the switch-based scheme described in Section 3. gperf treats duplicate keywords as members of an equivalence class and generates switch statement code containing cascading if-else comparisons within a case label to handle non-unique keyword hash values. For example, if gperf is run with the default keysig selection command-line option "-k 1,$" on a keyfile containing C++ reserved words, a hash collision occurs between the delete and double keywords, thereby preventing a perfect hash function. Using the "-D" option produces a near-perfect hash function, that allows at most one string comparison for all keywords except double, which is recognized after two comparisons. Figure 8 shows the relevant fragment of the generated near-perfect hash function code. { char *rw; ... switch (hash (str, len)) { ... case 46: rw = "delete"; if (*str == *rw && !strcmp (str + 1, rw + 1, len - 1)) return rw; rw = "double"; if (*str == *rw && !strcmp (str + 1, rw + 1, len - 1)) return rw; return 0; case 47: rw = "default"; break; case 49: rw = "void"; break; ... } if (*str == *rw && !strcmp (str + 1, rw + 1, len - 1)) return rw; return 0; } and secondary keys. In the latter case, if the primary keywords are distinguishable only via secondary key comparisons, the user may edit the generated code by hand or via an automated script to completely disambiguate the search key. 6.2 Enhancements and Extensions Fully automating the perfect hash function generation process is gperf’s most significant unfinished extension. One approach is to replace gperf’s current algorithm with more exhaustive approaches [9, 7]. Due to gperf’s object-oriented program design, such modifications will not disrupt the overall program structure. The perfect hash function generation module, class Gen Perf, is independent from other program components; it represents only about 10 percent of gperf’s overall lines of source code. A more comprehensive, albeit computationally expensive, approach could switch over to a backtracking strategy when the initial, computationally less expensive, non-backtracking first pass fails to generate a perfect hash function. For many common uses, where the search sets are relatively small, the program will run successfully without incurring backtracking overhead. In practice, the utility of these proposed modifications remains an open question. Another potentially worthwhile feature is enhancing gperf to automatically select the keyword index positions. This would assist users in generating time or space efficient hash functions quickly and easily. Currently, the user must use the default behavior or explicitly select these positions via command-line arguments. Finally, gperf’s output functions can be extended to generate code for other languages, e.g., Java, Ada, Smalltalk, Module 3, Eiffel, etc. 7 Concluding Remarks gperf was originally designed to automate the construction of keyword recognizers for compilers and interpreter reserved word sets. The various features described in this paper enable it to achieve its goal, as evidenced by its use in the GNU compilers. In addition, gperf has been used in the following applications: The TAO CORBA IDL compiler [4] uses gperf to generate the operation dispatching tables [21] used by serverside skeletons. A hash function for 15,400 “Medical Subject Headings” used to index journal article citations in MEDLINE, a large bibliographic database of the biomedical literature maintained by the National Library of Medicine. Generating this hash function takes approximately 10 minutes of CPU time on a SPARC 20 workstation. Figure 8: The Near-Perfect Lookup Table Fragment A simple linear search is performed on duplicate keywords that hash to the same location. Linear search is effective since most keywords still require only one string comparison. Support for duplicate hash values is useful in several circumstances, such as large input keyfiles (e.g., dictionaries), highly similar keyword sets (e.g., assembler instruction mnemonics), 4 The exact number depend on the keyword set and the command-line options. 12 The GNU indent C code reformatting program, where [12] M. Dietzfelbinger, A. Karlin, K. Mehlhorn, F. M. auf der Heid, H. Rohnert, and R. Tarjan, “Dynamic Perfect Hashing: Upthe inclusion of perfect hashing sped up the program by per and Lower Bounds,” SIAM Journal of Computing, vol. 23, an average of 10 percent. pp. 738–761, Aug. 1994. A public domain program converting double precision [13] G. Jaeschke, “Reciprocal Hashing: A Method for Generating FORTRAN source code to/from single precision uses Minimal Perfect Hashing Functions,” Communications of the gperf to modify function names that depend on the ACM, vol. 24, pp. 829–833, Dec. 1981. types of their arguments, e.g., replacing sgefa with [14] T. Sager, “A Polynomial Time Generator for Minimal Perdgefa in the LINPACK benchmark. Each name corfect Hash Functions,” Communications of the ACM, vol. 28, pp. 523–532, Dec. 1985. responding to a function is recognized via gperf and substituted with the version for the appropriate precision. [15] C. C. Chang, “A Scheme for Constructing Ordered Minimal A speech synthesizer system, where there is a cache bepp. 187–195, 1986. tween the synthesizer and a larger, disk-based dictionary. rd A word is hashed using gperf, and if the word is already [16] Bjarne Stroustrup, The C++ Programming Language, 3 Edition. Addison-Wesley, 1991. in the cache it is not looked up in the dictionary. Since automatic static search set generators perform well in practice and are widely and freely available, there seems little incentive to code keyword recognition functions manually for [18] E. Gamma, R. Helm, R. Johnson, and J. Vlissides, Design Patmost applications. terns: Elements of Reusable Object-Oriented Software. Reading, MA: Addison-Wesley, 1995. [17] D. C. Schmidt, “ACE: an Object-Oriented Framework for Developing Distributed Applications,” in Proceedings of the 6th USENIX C++ Technical Conference, (Cambridge, Massachusetts), USENIX Association, April 1994. Perfect Hashing Functions,” Information Sciences, vol. 39, References [1] M. Lesk and E. Schmidt, LEX - A Lexical Analyzer Generator. Bell Laboratories, Murray Hill, N.J., Unix Programmers Manual ed. [2] S. Johnson, YACC - Yet another Compiler Compiler. Bell Laboratories, Murray Hill, N.J., Unix Programmers Manual ed. [3] R. M. Stallman, Using and Porting GNU CC. Free Software Foundation, GCC 2.7.2 ed. [4] A. Gokhale, D. C. Schmidt, and S. Moyer, “Tools for Automating the Migration from DCE to CORBA,” in Proceedings of ISS 97: World Telecommunications Congress, (Toronto, Canada), IEEE Communications Society, September 1997. [5] D. E. Knuth, The Art of Computer Programming, vol. 1: Searching and Sorting. Reading, MA: Addison Wesley, 1973. [6] C. R. Cook and R. R. Oldehoeft, “A Letter Oriented Minimal Perfect Hashing Function,” SIGPLAN Notices, vol. 17, pp. 18– 27, Sept. 1982. [7] A. Tharp and M. Brain, “Using Tries to Eliminate Pattern Collisions in Perfect Hashing,” IEEE Transactions on Knowledge and Data Engineering, vol. 6, no. 2, pp. 329–347, 1994. [8] R. J. Cichelli, “Minimal Perfect Hash Functions Made Simple,” Communications of the ACM, vol. 21, no. 1, pp. 17–19, 1980. [9] M. Brain and A. Tharp, “Near-perfect Hashing of Large Word Sets,” Software – Practice and Experience, vol. 19, no. 10, pp. 967–978, 1989. [10] R. Sprugnoli, “Perfect hashing functions: A single probe retrieving method for static sets,” Communications of the ACM, pp. 841–850, Nov. 1977. [11] G. V. Cormack, R. Horspool, and M. Kaiserwerth, “Practical Perfect Hashing,” Computer Journal, vol. 28, pp. 54–58, Jan. 1985. [19] D. Lea, “libg++, the GNU C++ Library,” in Proceedings of the 1st C++ Conference, (Denver, CO), pp. 243–256, USENIX, Oct. 1988. [20] J. Kegler, “A Polynomial Time Generator for Minimal Perfect Hash Functions,” Communications of the ACM, vol. 29, no. 6, pp. 556–557, 1986. [21] A. Gokhale and D. C. Schmidt, “Evaluating the Performance of Demultiplexing Strategies for Real-time CORBA,” in Proceedings of GLOBECOM ’97, (Phoenix, AZ), IEEE, November 1997. 13 This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/3680/Schmidt-GPERF-Perfect-Hash-Gemerator-Function
CC-MAIN-2016-50
refinedweb
9,030
54.83
18588/configure-django-runserver-reload-static-python-files-changed By default, Django's runserver command auto reloads the server when python or template files are changed. Is it possible to configure Django to extend its file monitoring for this purpose to other directories or sets of files, such as JavaScript or CSS files being served statically (during development)? This would be useful in this scenario: the Django app reads a set of static text files on startup and I would like the server to re-read them when they change, without having to add this specific feature - simply restarting would be fine. Do I need to start meddling with (or extending) django/utils/autoreload.py ? There is no need to reload server, but sometimes there is need to copy static files to be visible for the server. Instead running collectstatic while developing, which copy recently edited static files (like javascript) from one directory to the directory, used by server. here is a trick: python manage.py collectstatic --noinput then your server will see all changes in files. The ActiveState solution that Pynt references makes instances of ...READ MORE Hi, good question. I have a solution ...READ MORE You need to set up the path ...READ MORE Context Manager: cd import os class cd: """Context manager for ...READ MORE To install Django, you can simply open ...READ MORE Try to install an older version i.e., ...READ MORE ALLOWED_HOSTS as in docs is quite self ...READ MORE Go to your project directory cd project cd project ALLOWED_HOSTS ...READ MORE down voteacceptedFor windows: you could use winsound.SND_ASYNC to play them ...READ MORE Here am talking about my example you ...READ MORE OR
https://www.edureka.co/community/18588/configure-django-runserver-reload-static-python-files-changed?show=18589
CC-MAIN-2019-26
refinedweb
281
67.15
/ Published in: JavaScript URL: One of those common tools that's easy to forget about is the Modulus operator (%), which returns the remainder of a division operation. If you divide some number by two, a remainder of 0 indicates an even number, while a remainder of 1 indicates an odd number. Expand | Embed | Plain Text - var isEven = function(someNumber){ - return (someNumber%2 == 0) ? true : false; - }; - - alert(isEven(64)); // Alerts "true". - - alert(isEven(97)); // Alerts "false". Report this snippet Tweet Nice, just what I needed. Thanks! I came across where there was a simple Javascript program to find whether the number is odd or even. I am pasting the same code with permission here. var n = prompt("Enter a number to find odd or even", "Type your number here"); n = parseInt(n); if (isNaN(n)) { alert("Please Enter a Number"); } else if (n == 0) { alert("The number is zero"); } else if (n%2) { alert("The number is odd"); } else { alert("The number is even"); }
http://snipplr.com/view/13487/
CC-MAIN-2015-06
refinedweb
163
71.75