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 |
|---|---|---|---|---|---|
(notes from Programming Clojure, 1st Edition)
TOC
- Chapter 1, Getting Started
- Chapter 2, Exploring Clojure
- Chapter 3, Working with Java
- Chapter 4, Unifying Data with Sequences
- Chapter 5, Functional Programming
- Chapter 6, Concurrency
- Chapter 7, Macros
- Chapter 8, Multimethods
- Chapter 9, Clojure in the Wild
Chapter 1, Getting Started
Why Lisp?
- Lisp is homoiconic. Lisp code is just Lisp data. This make it easy for programs to write other programs.
- The whole language is there, all the time. Read Paul Graham's Revenge of the Nerds.
Lisp, with Fewer Parentheses
- Clojure generalize Lisp's physical list into an abstraction called a sequence. This preserves the power of lists, while extending that power to a variety of other data structures.
- Clojure's reliance on the JVM provides a standard library and a deployment platform with great reach.
- Clojure's approach to symbol resolution and syntax quoting makes it easier to write many common macros.
- Clojure provides a convenient literal syntax for a wide variety of data structures besides just lists. (for example, vector
[]instead of list
())
- In Clojure, unlike most Lisps, commas are whitespace.
- Idiomatic Clojure does not nest parentheses more than necessary.
Clojure Is a Functional Language
Clojure is a functional language but not a pure functional language like Haskell. Functional languages have the following properties:
- Functions are first-class objects. That is, functions can be created at runtime, passed around, returned, and in general used like any other datatype.
- Data is immutable.
- Functions are pure; that is, they have no side effects.
Clojure Simplifies Concurrent Programming
Clojure's support for concurrency goes beyond just functional programming. It protects mutable data via software transactional memory (STM).
Clojure Embraces the Java Virtual Machine
You can call any Java API directly:
(System/getProperties)
Clojure Coding Quick Start
you need
- Java runtime
- Leiningen
enter repl
$ lein repl
hello world
(println "hello world") (defn hello [name] (str "Hello, " name)) (hello "Stu") ; `Ctrl+C` or `Ctrl+D` to exit repl
here
defndefines a function
hellois the function name
hellotakes one argument,
name
stris a function call that concatenates an arbitrary list of arguments into a string
defn,
hello,
name, and
strare all symbols, which are names that refer to things.
load file, you can use absolute path or a path relative to where you launched repl
(load-file "temp.clj")
Chapter 2, Exploring Clojure
Forms
When you run a Clojure program, a part of Clojure called the reader reads the text of the program in chunks called forms and translates them into Clojure data structures. Clojure then compiles and executes the data structures.
Numberic Types
Numberic literals are forms.
Clojure has a build-in Ratio type:
(class (/ 22 7)) => clojure.lang.Ratio ; if you actually want decimal division (/ 22.0 7) ; integer quotient and remainder (quot 22 7) => 3 (rem 22 7) => 1
Symbols
Symbols name all sorts of things in Clojure:
- Functions like
str
- "Operators" like
+, which are just functions
- Java classes like
Java.lang.Sring
- Namespaces like
clojure.coreand Java packages like
Java.lang
- Data structures and references
Symbols cannot start with a number.
Clojure treats
/ and
. specially in order to support namespaces.
Strings and Characters
Strings are delimited by
", and can span multiple lines:
"This is a multiline String"
you can call Java functions directly
(.toUpperCase "hello") => "HELLO"
the dot before
toUpperCase tells Clojure to treat it as the name of a Java method instead of a Clojure function.
Clojure characters are Java characters.
Boolean and Nil
rules
trueis true, and
falseis false
nilalso evaluates to false when used in a boolean context
- other than
falseand
nil, everything else evaluates to true in a boolean context
empty list is not false in Clojure.
zero is not false in Clojure.
A predicate is a function that returns either true of false.
(true? expr) (false? expr) (nil? expr) (zero? expr)
true? tests whether a value is actually
true, not whether that value evaluates to
true in a boolean context.
(true? "foo") => false
Maps, Keywords, and Structs
Map is a collection of key/value pairs. Literal form is surrounded by
{}
(def inventors {"Lisp" "McCarthy" "Clojure" "Hickey"}) ; same, comma is treated as whitespace (def inventors {"Lisp" "McCarthy", "Clojure" "Hickey"})
Maps are functions.
(inventors "Lisp") => "McCarthy"
get allows you to specify a different return value for missing keys:
(get inventors "Lisp" "I dunno!") => "McCarthy" (get inventors "Foo" "I dunno!") => "I dunno!"
Any Clojure data structure can be a key in a map. A very common key type is the Clojure keyword.
keywords begin with a colon
:, keywords resolve to themselves:
:foo => :foo
keywords are also functions:
(:Clojure inventors) => "Hicky"
Structs
(defstruct book :title :author) => #'user/book ; instantiate with struct (def b (struct book "Anathem" "Neal Stephenson")) (:title b)
you can omit values for some of the basic keys.
use
struct-map to add values
(struct-map book :copyright 2008 :title "Anathem") => {:title "Anathem", :author nil, :copyright 2008}
Reader Macros
Reader macros are special reader behaviors triggered by prefix macro characters.
(check book/online for list of reader macros)
Clojure does not allow programs to define new reader macros.
Functions
create function
(defn greeting "Returns a greeting" [username] (str "Hello, " username)) ; call (greeting "world") => "Hello, World" ; document (doc greeting)
exception will be thrown if argument is omitted. to use a default argument:
(defn greeting "Returns a greeting" ([] (greeting "world")) ([username] (str "Hello, " username))) (greeting) => "Hello, world"
you can create function with variable arity by including an ampersand
& in the parameter list, Clojure will bind the name after the
& to a sequence of all remaining parameters.
.
Anonymous Functions
you can create anonymous functions with
fn
reason to use anonymous functions
- function is so brief and self-explanatory
- function is being used only from inside another function and needs a local name
- function is created inside another function for the purpose of closing over some data
filter functions are often brief and self-explanatory.
(use '[clojure.contrib.str-utils :only (re-split)]) (filter (fn [w] (> (count w) 2)) (re-split #"\W+" "A fine day")) => ("fine" "day")
shorter syntax for anonymous functions:
(#body), parameters are named
%1,
%2 and so on.
(filter #(> (count %) 2) (re-split #"\W+" "A fine day it is")) => ("fine" "day)
use named function inside the scope of another function:
(defn indexable-words [text] (let [indexable-word? (fn [w] (> (count w) 2))] (filter indexable-word? (re-split #"\W+" text))))
the
let binds the name
indexable-word? to the anonymous function inside the (lexical) scope of
indexable-words
Vars, Bindings, and Namespaces
when you define an object with
def or
defn, that object is stored in a Clojure
var.
the
var special form returns a var itself, not the var's value
(var foo) => #'user/foo
vars are more than just storing a value:
- same var name can be aliased into more than one namespace
- vars can have metadata, includes documentation, type hints for optimization, and unit tests
- vars can be dynamically rebound on a per-thread basis
vars are bound to names. there're other kinds of bindings. in a function call, argument values bind to parameter names.
a function's parameter bindings hava a lexical scope: they are visible only inside the text of the function body. functions are not the only way to create a lexical binding, the special form
let does nothing other than create a set of lexical bindings.
(let [bindings*] exprs*)
bindings are then in effect for
exprs, and the value of the
let is the value of the last expression in
exprs.
Destructuring
(defn greeting-author-1 [author] (println "Hello, " (:first-name author)))
but you don't need the
author, all you need is the
first-name. Clojure solves this with destructuring: any place that you bind names, you can nest a vector or a map in the binding to reach into a collection and bind only the part you want.
(defn greeting-author-2 [{fname :first-name}] (println "Hello, " fname))
you can use a vector to destructure any sequential collection.
(let [[x y] [1 2 3]] [x y]) => [1 2] ; skip elements (let [[_ _ z] [1 2 3]] z) => 3 ; use :as to bind for the entire enclosing structure (let [[x y :as coords] [1 2 3 4 5 6]] (str "x: " x ", y: " y ", total dimensions " (count coords))) => "x: 1, y: 2, total dimensions 6"
Namespaces
use
resolve to explicitly resolve the symbol
(resolve 'foo) => #'user/foo
switch namespaces or creating a new one if needed, with
in-ns
(in-ns 'myapp) => #<Namespace myapp>
when you create new namespace with
in-ns,
java.lang package is automatically available to you.
making Clojure's core function available in new namspace as well:
(clojure.core/use 'clojure.core)
class names outside
java.lang must be fully qualified
; wrong File/separator ; correct java.io.File/separator
if you don't want to use a fully qualified name, you can use
import
(import '(java.io InputStream File)) File/separator => "/"
import is only for Java classes, if you want to use a Clojure var from another namespace, you must use fully qualified name or map the name into the current namespace.
(require 'clojure.contrib.math) (clojure.contrib.math/round 1.7) => 2 (round 1.7) => java.lang.Exception ; this maps all public vars to current namespace (use 'clojure.contrib.math) ; use :only to list only the vars you need (use '[clojure.contrib.math :only (round)]) ; now you can call (round 1.2) => 2 ; add :reload to make changes available to a running program (use :reload '[clojure.contrib.make :only (round)]) ; :reload-all reloads any namespaces that examples.exploring refers to (use :reload-all 'examples.exploring)
it's idiomatic to
import Java classes and
use namespaces at the top of a source file, using the
ns macro:
(ns examples.exploring (:use examples.utils clojure.contrib.str-utils) (:import (java.io File))
Flow Control
Clojure has very few flow control forms,
if,
do, and
loop/recur may be all you will ever need.
(defn is-small? [number] (if (< number 100) "yes")) ; if false it returns nil (is-small? 200) => nil ; add "else" part (defn is-small? [number] (if (< number 100) "yes" "no")) (is-small? 200) => "no"
if allows only one form for each branch.
do takes any number of forms, evaluates them all, and returns the last.
(defn is-small? [number] (if (< number 100) "yes" (do (println "Saw a big number" number) "no")))
and this is an example of side effect.
Recur with loop/recur
(loop [bindings *] exprs*]
loop just like
let, establishing
bindings and then evaluating
exprs, the difference is that
loop sets a recursion point, which can then be targeted by the
recur special form
(recur exprs*)
recur binds new values for
loop's bindings and return control to the top of the loop.
example
(loop [result [] x 5] (if (zero? x) result (recur (conj result x) (dec x)))) => [5 4 3 2 1]
instead of using a loop, you can use
recur back to the top of a function.
(defn countdown [result x] (if (zero? x) result (recur (conj result x) (dec x))) (countdown [] 5) => [5 4 3 2 1]
recur is a powerful building block, but you may not use it very often, because many common recursions are proviced by Clojure's sequence library.
; countdown could expressed as any of these (into [] (take 5 (iterate dec 5))) => [5 4 3 2 1] (into [] (drop-last (reverse (range 6)))) => [5 4 3 2 1] (vec (reverse (rest (range 6)))) => [5 4 3 2 1]
Where's My for Loop?
an implementation of Apache Commons
indexOfAny in Clojure (check online for the Java source)
; indexing a string (defn indexed [coll] (map vector (iterate inc 0) coll)) ; return indices (defn index-filter [pred coll] (when pred (for [[idx elt] (indexed coll) :when (pred elt)] idx)))
Clojure's
for is not a loop but a sequence comprehension.
(index-filter #{\a \b} "abcdbbb") => (0 1 4 5 6) (index-filter #{\a \b} "xyz") => nil ; return first result (defn index-of-any [pred coll] (first (index-filter [pred coll])))
Metadata
In Clojure, metadata is data that is orthogonal to the logical value of an object.
you can add metadata to a collection or a symbol using
with-meta
(with-meta object metadata)
example
(def stu {:name "Stu" :email "stu@example.com"}) (def serializable-stu (with-meta stu {:serializable true})) ; "=" tests for value equality, like Java's "equals" (= stu serializable-stu) => true ; "identical?" tests reference equality, like Java's "==" (identical? stu serializable-stu) => false ; assess metadata with "meta" macro (meta stu) => nil (meta serializable-stu) => {:serializable true} ; or use the reader macro "^" (^stu) => nil (^serializable-stu) => {:serializable true}
when you create a new object based on an existing object, the existing object's metadata flows to the new object.
Reader Macro
to add your own key/value pairs to a var, use the metadata reader macro
#^metadata form
example,
shout expects and returns a string, use
:tag key to enforce it
(defn #^{:tag String} shout [#^{:tag String} s] (.toUpperCase s)) ; inspect ^#'shout ; Exception, not a string (shout 1) ; ":tag" is so common, you can use short-form "#^Classname" (defn #^String shout [#^String s] (.toUpperCase s)) ; can also place the metadata last (defn shout ([s] (.toUpperCase s)) {:tag String})
common metadata keys
:arglists
:doc
:file
:line
:macro
:name
:ns
:tag
it is important to note that the metadata reader macro is not the same as
with-meta. reader macro addes metadata for the compiler,
with-meta adds for your own data
(def #^{:testdata true} foo (with-meta [1 2 3] {:order :ascending})) (meta #'foo) => {:ns .., :name foo, :file .., :testdata true} (meta foo) => {:order :ascending}
as a general rule, use metadata reader macro to add metadata to vars and parameters, use
with-meta to add metadata to data.
Chapter 3, Working with Java
Calling Java
create new object
(def rnd (new java.util.Random)) ; call with "." special form ; following calls no-argument version of "nextInt()" (. rnd nextInt) ; with argument (. rnd nextInt 10) ; "." also works with static fields (. Math PI)
Syntactic Sugar
instead of
new, you can use the
Classname. form
; following are equivalent (new Random) (Random.) ; for static fields, short form is "Classname/membername" (. Math PI) Math/PI ; for static methods, use "(Classname/membername)" (System/currentTimeMillis) ; another short form is".methodOrFieldName" (. rnd nextInt) (.nextInt rnd) ; chaining is ugly with prefix-dot notation (.getLocation (.getCodeSource (.getProtectionDomain (.getClass '(1 2))))) ; clean it up with ".." macro (.. '(1 2) getClass getProtectionDomain getCodeSource getLocation) ; to call methods several times, use "doto" macro (doto (System/getProperties) (.setProperty "name" "Stuart") (.setProperty "favoriteColor" "blue"))
Using Java Collections
make-array to create Java arrays
(make-array String 5) ; can wrap it as Clojure sequence (seq (make-array String 5))
(skipped, read later)
Chapter 4, Unifying Data with Sequences
Everything Is a Sequence
A Sequence has 3 core capabilities
; get first item (first aseq) ; get everything after first item (rest aseq) ; construct a new sequence by adding an item to the front of an existing sequence. (cons elem aseq) ; when apply to vector, "rest" and "cons" returns seq (rest [1 2 3]) => (2 3) (cons 0 [1 2 3]) => (0 1 2 3) ; works with maps and sets (first {:fname "Stu" :lname "Halloway"}) => [:fname "Stu"] (first #{:the :quick :brown :fox}) => :brown ; if you want a reliable order, sort it (sorted-set :the :quick :brown :fox) => #{:brown :fox :quick :the} (sorted-map :c 3 :b 2 :a 1) => {:a 1 :b 2 :c 3}
in addition to the core capabilities of seq, two other capabilities are worth meeting immediately:
conj and
into
; "conj" adds one or more elements to a collection (conj `(1 2 3) :a) => (:a 1 2 3) ; "into" adds all the items in one collection to another (into '(1 2 3) '(:a :b :c)) => (:c :b :a 1 2 3) ; for lists, they add to the front (above) ; for vectors, they add to the back (conj [1 2 3] :a) => [1 2 3 :a] (info [1 2 3] [:a :b :c]) => [1 2 3 :a :b :c]
most Clojure sequences are lazy: they can process sequences too large to fit in memory
Clojure sequences are immutable: they never change.
Using the Sequence Library
creating sequences
; (range start? end step?) ; ranges include their start, but not their end. (range 5) => (0 1 2 3 4) (range 1 5) => (1 2 3 4) (range 1 5 2) => (1 3) ; (repeat n x) (repeat 5 1) => (1 1 1 1 1) ; infinite version ; (iterate f x) ; combine with take ; (take n sequence) (take 5 (iterate inc 1)) => (1 2 3 4 5) ; cycle takes a collection and cycles it infinitely ; (cycle coll) (take 10 (cycle (range 3))) => (0 1 2 0 1 2 0 1 2 0) ; interleave takes multiple collections and produces a new collection what interleaves values from each collection until one of the collection is exhausted. ; (interleave & colls) (interleave (iterate inc 1) ["A" "B" "C"]) => (1 "A" 2 "B" 3 "C") ; interpose returns a sequence with each of the elements separated by a separator ; (interpose separator coll) (interpose "," ["apples" "bananas" "grapes"]) => ("apples" "," "bananas" "," "grapes) ; works with (apply str ...) to produce output strings (apply str (interpose \, ["apples" "bananas" "grapes"])) => "apples,bananas,grapes" ; clojure-contrib wraps it as "str-join" ; (str-join separator sequence)
filtering
; (filter pred coll) (take 10 (filter even? (iterate inc 1))) => (2 4 6 8 10 12 14 16 18 20) ; (take-while pred coll) (take-while (complement #{\a\e\i\o\u}) "the-quick-brown-fox") => (\t \h) ; complement reverses the behavior of another function. ; opposite of take-while is drop-while ; (drop-while pred coll) (drop-while (complement #{\a\e\i\o\u}) "the-quick-brown-fox") (\e \- \q \u .... ) ; (split-at index coll) ; (split-with pred coll) (split-at 5 (range 10)) => [(0 1 2 3 4) (5 6 7 8 9)] (split-with #(<= % 10) (range 0 20 2)) => [(0 2 4 6 8 10) (12 14 16 18)] ; all take-, split-, and drop- functions returns lazy sequences.
sequence predicates
; (every? pred coll) (every? odd? [1 3 5]) => true ; (some pred coll) ; some return first nonfalse value for its predicate or returns nil if no match (some even? [1 2 3]) => true (some identity [nil false 1 nil 2]) => 1 ; (not-every? pred coll) ; (not-any? pred coll)
transforming sequences
; (map f coll) (map #(format "<p>%s</p>" %) ["the" "quick" "brown" "fox"]) => ("<p>the</p>" "<p>quick</p>" ... ) ; map can take more than one collection argument, stopping whenever the smallest collection is exhausted ; (reduce f coll) (reduce + (range 1 11)) => 55 ; (sort comp? coll) ; (sort-by a-fn comp? coll) (sort [42 1 7 11]) => (1 7 11 42) (sort-by #(.toString %) [42 1 7 11]) => (1 11 42 7) (sort > [42 1 7 11]) => (42 11 7 1) (sort-by :grade > [{:grade 83} {:grade 90} {:grade 77}]) => ({:grade 90} {:grade 83} {:grade 77}
The granddaddy of all filters and transformations is the list comprehension. A list comprehension creates a list based on an existing list, using set notation. In general, list comprehension will consist of the following
- Input list(s)
- Placeholder variables for elements in the input lists
- Predicates on the elements
- An output form that produces output from the elements of the input lists that satisfy the predicates
; list comprehension using "for" macro ; (for [binding-form coll-expr filter-expr? ...] expr) ; rewrite the map example (for [word ["the" "quick" "brown" "fox"]] (format "<p>%s</p>" word)) ; emulate filter with ":when" (take 10 (for [n (iterate inc 1) :when (eval? n)])) ; the ":while" clause (for [n (iterate inc 1) :while (even? n)] n) => (0) ; the real power of "for" comes when you work with more than one binding expression. (for [file "ABCDEFGH" rank (range 1 9)] (format "%c%d" file rank)) => ("A1" "A2" ... "H7" "H8") ; Clojure iterates over the rightmost binding expression first and then works its way left. (for [rank (range 1 9) file "ABCDEFGH"] (format "%c%d" file rank)) => ("A1" "B1" ... "G8" "H8")
Lazy and Infinite Sequences
Most Clojure sequences are lazy, using lazy sequences has many benefits:
- you can postpone expensive computations that may not in fact be needed
- you can work with huge data sets that do not fit into memory
- you can delay I/O until it is absolutely needed
; force evaluation with "doall" ; (doall coll) (def x (for [i (range 1 3)] (do (println i) i))) (doall x) | 1 | 2 => (1 2) ; or "dorun", "dorun" walks the elements of sequence without keeping past elements in memory ; (dorun coll) (dorun x) | 1 | 2 => nil
Clojure Makes Java Seq-able
The seq abstraction of
first/
rest applies to following in Java world:
- The Collections API
- Regular expressions
- File system traversal
- XML processing
- Relational database results
Seq-ing Java Collections
(first (.getBytes "hello")) => 104 (rest (System/getProperties)) ; Clojure will automatically wrap collections in sequences, but will not automatically rewrap them back to their original type ; use (apply str seq) to convert a seq back to a string (apply str (reverse "hello")) ; also remember, seq wrappers are immutable
Seq-ing Regular Expressions
; (re-matcher regexp string) ; but you should use the higher-level "re-seq" ; (re-seq regexp string) (re-seq #"\w+" "the quick brown fox") => ("the" "quick" "brown" "fox")
Seq-ing the File System
(count (file-seq (File. "."))) ; check by last modified time (defn minutes-to-millis [mins] (* mins 1000 60)) (defn recently-modified? [file] (> (. lastModified file) (- (System/currentTimeMillis) (minutes-to-millis 30)))) (filter recently-modified? (file-seq (File. ".")))
Seq-ing a Stream
you can seq over the lines of any Java Reader using
line-seq. To get a Reader, you can use clojure-contrib's duck-streams library.
(use '[clojure.contrib.duck-streams :only (reader)) ; leaves reader open ... (take 2 (line-seq (reader "example/utils.clj"))) ; correctly close the reader (with-open [rdr (reader "book/utils.clj")] (count (filter #(re-find #"\S" %) (line-seq rdr)))) ; a function that counts the lines of Clojure code in a directory tree (use '[clojure.contrib.duck-streams :only (reader)) (def non-blank? [line] (if (re-find #"\S" line) true false)) (def non-svn? [file] (not (.contains (.toString file) ".svn"))) (def clojure-source? [file] (.endsWith (.toString file) ".clj")) (def clojure-loc [base-file] (reduce + (for [file (file-seq base-file) :when (and (clojure-source? file) (non-svn? file))] (with-open [rdr (reader file)] (count (filter non-blank? (line-seq rdr))))))) ; usage (clojure-loc (java.io.File. "/my/repos/clojure"))
Seq-ing XML
(use '[clojure.xml :only (parse)]) (parse (java.io.File. "examples/compositions.xml")) ; manipulate with xml-seq ; (xml-seq root) (for [x (xml-seq (parse (java.io.File. "examples.xml"))) :when (= :composition (:tag x))] (:composer (:attr x)))
Calling Structure-Specific Functions
Clojure includes functions that specifically target lists, vectors, maps, structs and sets.
Functions on lists
; peek is the same as first, but pop is not the same as rest. pop will throw an exception if the sequence is empty. (peek '(1 2 3)) => 1 (pop '(1 2 3)) => (2 3)
Functions on Vectors
; vectors also support peek and pop, but deal with element at the end (peek [1 2 3]) => [3] (pop [1 2 3]) => [1 2] ; get reutrns value at an index, nil if out of bound (get [:a :b :c] 1) => :b ; vectors are themselves functions, exception if out of bound ([:a :b :c] 1) => :b ; assoc associates a new value (assoc [0 1 2 3 4] 2 :two) => (0 1 :two 3 4) ; subvec return a subvector of a vector ; (subvec avec start end?) (subvec [1 2 3 4 5] 3) => [4 5] (subvec [1 2 3 4 5] 1 3) => [2 3]
Functions on Maps
; (keys map) ; (vals map) (keys {:sundance "spaniel", :darwin "beagle"}) => (:sundance :darwin) (vals {:sundance "spaniel", :darwin "beagle"}) ("spaniel" "beagle") ; (get map key value-if-not-found?) (get {:sundance "spaniel", :darwin "beagle"} :darwin) => "beagle" ; maps are functions too ({:sundance "spaniel", :darwin "beagle"} :darwin) => "beagle" ; keywords are functions too (:darwin {:sundance "spaniel", :darwin "beagle"}) => "beagle" ; (contains? map key) ; "assoc" returns a map with a key/value pair added ; "dissoc" returns a map with a key removed ; "select-keys" returns a map keeping only the keys passed in ; "merge" combines maps. if multiple maps contain a key, the right-most map wins ; "merge-with" is like "merge", but when two or more maps have the same key, you can specify a function for combining the values under the key ; (merge-with merge-fn & maps)
Functions on Sets
; Clojure provides a group of functions for sets ; (use 'clojure.set) ; "union" returns set of all elements present in either input set ; "intersection" returns the set of all elements present in both input sets ; "difference" returns the set of all elements present in the first input set, minus those in the second. ; "select" returns the set of all elements matching a predicate ; "union" and "difference" also part of relational algebra, which is the basis for query languages such as SQL. ; The relational algebra consists of 6 primitive operators: ; union, difference, rename, selection, projection, and cross product. ; (rename relation rename-map) (rename compositions {:name :title}) ; (select pred relation) (select #(= (:name %) "Requiem") compositions) ; (project relation keys) ; returns only the portions of the maps that match a set of keys (project compositions [:name]) ; (join relation-1 relation-2 keymap?) (join compositions composers)
Chapter 5, Functional Programming
The Sixe Rules
- Avoid direct recrusion. (JVM limitation)
- Use
recurwhen you are producing scalar values or small, fixed sequences. Clojure will optimize calls that use an explicit
recur.
- When producing large or variable-sized sequences, always be lazy. (Do not
recur)
- Be careful not to realize more of a lazy sequence than you need.
- Know the sequence library. You can often write code without using
recuror the lazy APIs at all.
- Subdivide. Divide even simple-seeming problems into smaller pieces, and you will often find solutions in the sequence library that lead to more general, reusable code.
How to Be Lazy
A recursion definition consists of two parts:
- A basis, which explicitly enumerates some members of the sequence
- A induction, which provides rules for combining members of the sequence to produce additional members
There are may ways to convert a recursion definition into working code:
- A simple recursion, using a function that call itself in some way to implement the induction step.
- a tail recrusion, using a function only calling itself at the tail of its execution. Tail recrusion enables an important optimization.
- A lazy sequence that eliminates actual recursion and calculates a values later, when it is needed.
example, Fibonacci numbers in simple recursion
; bad idea (defn stack-consuming-fibo [n] (cond (= n 0) 0 (= n 1) 1 :else (+ (stack-consuming-fibo (- n 1)) (stack-consuming-fibo(- n 2)))))
Tail Recursion
Recursion must come at the tail, that is, at an expression that is a return value of the function. Languages can then perform tail-call optimization (TCO), converting tail recursions into iterations that do not consume the stack.
fibo in tail recursion
(defn tail-fibo [n] (letfn [(fib [current next n] (if (zero? n) current (fib next (+ current next) (dec n))))] (fib 0 1 n))) ; the letfn macro ; (letfn fnspecs & body) ; fnspecs ==> (fname [params*] exprs)+
But JVM was not designed for functional languages. No language that runs directly on the JVM can perform automatic TCO.
One special case of recursion that can be optimized away on the JVM is a self-recursion. In Clojure, you can convert a function that tail calls itself into an explicit self-recursion with
recur.
; better but not great (defn recur-fibo [n] (letfn [(fib [current next n] (if (zero? n) current (recur next (+ current next) (dec n))))] (fib 0 1 n)))
Lazy Sequences
; (lazy-seq & body)
A
lazy-seq will invoke its body only when needed, that is, when seq is called directly or indirectly.
(defn lazy-seq-fibo ([] (concat [0 1] (lazy-seq-fibo 0 1))) ([a b] (let [n (+ a b)] (lazy-seq (cons n (lazy-seq-fibo b n ))))))
using existing sequence library functions
(defn fibo [] (map first (iterate (fn [[a b]] [b (+a b)]) [0 1])))
Losing Your Head
Unless you wnat to cache a sequence as you traverse it, you must be careful not to keep a reference to the head of the sequence. You should normally expose lazy sequences as a function that returns the sequence, not as a var that contains the sequence.
With lazy sequence, losing your head is often a good idea.
Currying and Partial Application
When you curry a function, you get a new function that takes one argument and returns the original function with that one argument fixed.
The absence of curry from Clojure is not a major problem, since
partial is available.
; (partical f & partial-args)
Recursion Revisited
(i have too many recursions in my mind, skipped for now)
Chapter 6, Concurrency
Clojure provides a powerful concurrency library, consisting of four APIs that enforce different concurrency models: refs, atoms, agents, and vars
- Refs manage coordinated, synchronous changes to shared state.
- Atoms manage uncoordinated, synchronous changes to shared state.
- Agents manage asynchronous changes to shared state.
- Vars manage thread-local state.
Refs and Software Transactional Memory (STM)
Most objects in Clojure are immutable. When you really want mutable data, you must be explicit about it, such as by creating a mutable reference (ref) to an immutable object.
; (ref initial-state) (def current-track (ref "Mars, the Bringer of War")) ; to read the contents of the reference, you can call "deref" ; (deref reference) (deref current-track) => "Mars, the Bringer of War" ; or shortened "@" reader macro @current-track => "Mars, the Bringer of War" ; you can change where a reference points to with "ref-set" ; (ref-set reference new-value) (ref-set current-track "Venus, the Bringer of Peace") => java.lang.IllegalStateException
because refs are mutable, you must protect their updates. In many languages, you would use a lock for this purpose. In Clojure, you can use a transaction. Transactions are wrapped in a
dosync
; (dosync & exprs) (dosync (ref-set current-track "Venus, the Bringer of Peace"))
Transactional Properties
Like database transactions, STM transactions guarantee some important properties:
- Updates are atomic. If you update more than one ref in a transaction, the cumulative effect of all the updates will appear as a single instantaneous event to anyone not inside your transaction.
- Updates are consistent. Refs can specify validation functions. If any of these functions fail, the entire transaction will fail.
- Updates are isolated. Running transactions cannot see partially completed results from other transactions.
Clojure does not guarantee that updates are durable (database ACID's D), because transactions are in-memory transactions. If you want a durable transaction in Clojure, you should use a database.
; you can make sure that updates are coordinated (def current-track (ref "Venus, the Bringer of Peace")) (def current-composer (ref "Holst")) (dosync (ref-set current-track "Credo") (ref-set current-composer "Byrd"))
alter will apply an update function to a referenced object within a transaction:
;(alter ref update-fn & args ...) (defn add-message [msg] (dosync (alter message conj msg)))
How STM Works: MVCC
Clojure's STM uses a technique called Multiversion Concurrency Control (MVCC). (read the book)
commute is a specialized variant of
alter allowing for more concurrency.
; (commute ref update-fn & args ...)
Commutes are so named because they must be commutative. That is, updates must be able to occur in any order.
Many updates are not commutative, consider a counter that returns an increasing sequence of numbers.
In general, you should prefer
alter over
commute.
Adding Validation to Refs
; (ref initial-state options*) ; options include: ; :validator validate-fn ; :meta metadata-map (def validate-message-list (partial every? #(and (:sender %) (:text %)))) (def messages (ref () :validator validate-message-list))
Refs are great for coordinated access to shared state, but not all tasks require such coordination. For updating a single piece of isolated data, prefer an atom.
Use Atoms for Uncoordinated, Synchronous Updates
Atoms are a lighter-weight mechanism than refs. Atoms allow updates of a single value, uncoordinated with anything else.
; (atom initial-state options?) ; options include: ; :validator validate-fn ; :meta metadata-map (def current-track (atom "Venus, the Bringer of Peace")) ; dereference with "deref" (deref current-track) => "Venus, the Bringer of Peace" ; or @current-track => "Venus, the Bringer of Peace" ; atoms do not participate in transactions, to update the value of an atom, simply call "reset!" (reset! current-track "Credo") ; (swap! an-atom f & args) ; swap! updates an-atom by calling function f on the current value of an-atom, plus any additional args. (swap! current-track assoc :title "Sancte Deus")
Both refs and atoms perform synchronous updates. When the update function returns, the value is already changed. If you do not need this level of control and can tolerate updates happening asynchronously at some later time, prefer an agent.
Use Agent for Asynchronous Updates
; (agent initial-state) (def counter (agent 0))
once you have an agent, you can
send the agent a function to update its state. send queues an update-fn to run later, on a thread in a thread pool
; (send agent update-fn & args) (send counter inc)
you can check the current value of an agent with
deref/
@
@counter => 1
if you want to be sure that the agent has completed the actions you sent to it, you can call
await or
await-for.
await has no timeout, so be careful:
await is willing to wait forever.
; (await & agents) ; (await-for timeout-millis & agents)
Validating Agents and Handling Errors
Agent can take a validation function also
; (agent initial-state options*) ; options include: ; :validator validate-fn ; :meta metadata-map (def counter (agent 0 :validator number?)) (send counter (fn [_] "boo")) ; no error, send still returns immediately. ; but when try to dereference @counter => java.lang.Exception: Agent has errors
to discover the specific error(s), call
agent-errors, which will return a sequence of errors thrown during agent actions
; (agent-errors counter)
once an agent has errors, all Subsequence attempts to query the agent will return an error. you make the agent usable again by calling
clear-agent-errors
; (clear-agent-errors agent) (clear-agent-errors counter) @counter => 0
Including Agents in Transactions
Transactions should not have side effects, because Clojure may retry a transaction an arbitrary number of times. However, sometimes you want a side effect when a transaction succeeds. Agents provide a solution. If you send an action to an agent from within a transaction, what action will be sent exactly once, if and only if the transaction succeeds.
(def backup-agent (agent "output/messages-backup.clj")) (use '[clojure.contrib.duck-steams :only (spit)]) (defn add-message-with-backup [msg] (dosync (let [snapshot (commute message conj msg)] (send-off backup-agent (fn [filename] (spit filename snapshot) filename)) snapshot)))
send-off is a variant of
send for actions that expect to block.
send-off actions get their own expandable thread pool. Never
send a blocking functions, or you may unnecessarily prevent other agents from making progress.
Managing Per-Thread State with Vars
When you call
def or
defn, you create a
dynamic var, you pass an initial value to
def, which becomes the root binding for the var.
(def foo 10)
the binding of
foo is shared by all threads
(.start (Thread. (fn [] (println foo)))) => nil | 10
you can create a thread-local binding for a var with the binding macro
; (binding [bindings] & body)
bindings have dynamic scope
Structurally, a
binding looks a lot like a `let
(binding [foo 42] foo) => 42 (defn print-foo [] (println foo)) ; now see the difference between binding and let (let [foo "let foo"] (print-foo)) | 10 (binding [foo "bound foo"] (print-foo)) | bound foo
the
let has no effect outside its own form, so the first
print-foo prints the root binding
10. the
binding, stays in effect down any chain of calls that begins in the biding form.
Acting at a Distance
Vars intended for dynamic binding are sometimes called special variables. It is good style to name them with leading and trailing asterisks
*. For example, Clojure uses dynamic binding for thread-wide options such as the standard I/O streams
*in*,
*out*, and
*err*.
Dynamic bindings enable action at a distance. When you change a dynamic binding, you can change the behavior of distant functions without changing any function arguments.
One kind of action at a distance is temporarily argumenting the behavior of a function. In some languages this would be classified as aspect-oriented programming; in Clojure it is simply a side effect of dynamic binding.
example
(defn slow-double [n] (Thread/sleep 100) (* n 2)) (defn calls-slow-double [] (map slow-double [1 2 1 2 1 2])) ; you have to run with "dorun", otherwise "map" will immediately returning a lazy sequence (time (dorun (calls-slow-double))) | "Elapsed time: 601.418 msecs"
slow-double is a good candidates for memoization. When you memoize a function, it keeps a cache mapping past inputs to past outputs.
(memoize function)
since the
slow-double function is already in use, you can create a binding to a memoized version and call
calls-slow-double from within the binding:
(defn demo-memoize [] (time (dorun (binding [slow-double (memoize slow-down)] (calls-slow-double))))) (demo-memoize) | "Elapsed time: 203.115 msecs"
dynamic binding has great power, but functions that use dynamic bindings are not pure functions and can quickly lose the benefits of Clojure's functional style.
A Clojure Snake
snake game written by Clojure
Chapter 7, Macros
**When to Use Macros
Macro Club has two rules, plus one exception.
The first rule is Don't Write Macros. Macros are complex, and they require you to think carefully about the interplay of macro expansion
create an implementation of
unless
begin by tring to write
unless as a function
; this is doomed to fail .. (defn unless [expr form] (if expr nil form)) (unless true (println "this should not print")) | this should not print
function arguments are always evaluated before passing them to
unless
macro solve his problem, because they do not evaluate their arguments immediately. Instead, you get to choose when (and if!) the arguments to a macro are evaluated.
when Clojure encounters a macro, it processes it in two steps. First, it expaneds (executes) the macro and substitutes the result back into the program. This is called macro expansion time. Then it continues with the normal compile time.
to write
unless, you need to write Clojure code to perform the translation at macro expansion time:
; (unless expr form) -> (if expr nil form)
then you need to tell Clojure that your code is a macro by using
defmacro
; (defmacro name doc-string? attr-map? [params*] body) (defmacro unless [expr form] (list 'if expr nil form)) (unless false (println "this should print"))
then Clojure will (invisibly to you) expand the
unless form into:
(if false nil (println "this should print"))
then Clojure compiles and executes the expanded
if form.
Special Forms, Design Patterns, and Macros
Clojure has no special syntax for code. Code is composed of data structures. This is true for normal functions but also for special forms and macros.
"design pattern is not a finished design that can be transformed directly into code" (Wikipedia)
that is what macros fit it. macros provide a layer of indirection so that you can automate the common parts of any recurring pattern. Macros and code-as-data work together, enabling you to reprogram your language on the fly to encapsulate patterns.
Expanding Macros
the
unless macro
(defmacro unless [expr form] (list 'if expr nil form))
only
if is quoted, because:
- you prevent Clojure from directly evaluating
ifat macro expansion time. Instead, evaluation strips off the quote, leaving
ifto be compiled.
- you do not want to quote
exprand
form, because they are macro arguments. Clojure will substitute them without evaluation at macro expansion time.
- you do not need to quote
nil, since
nilevaluates to itself.
you can test macro expansions at the REPL by using
macroexpand-1
; (macroexpand-1 form) (macroexpand-1 '(unless false (println "this should print"))) => (if false nil (println "this should print")) (defmacro bad-unless [expr form] (list 'if 'expr nil form)) (macroexpand-1 '(bad-unless false (println "this should print"))) => (if expr nil (println "this should print"))
for recursively expand, use
macroexpand
; (macroexpand form) (macroexpand '(.. arm getHand getFinger)) => (. (. arm getHand) getFinger)
it's not a problem
arm,
getHand, and
getFinger do not exist. you are only expanding them, not attempting to compile and execute them.
when and when-not
(unless false (println "this") (println "and also this")) => java.lang.IllegalArgumentException ; (when test & body) ; (when-not test & body) (when-not false (println "this) (println "and also this)) | this | and also this => nil ; source for when-not (defmacro when-not [test & body] (list 'if test nil (cons 'do body))) ; exam with macroexpand-1 (macroexpand-1 '(when-not false (print "1") (print "2"))) => (if false nil (do (print "1") (print "2")))
when differs from
if in two ways:
ifallows an
elseclause, and
whendoes not.
- since
whendoes not have
elseas its second argument, it can take a variable argument list and execute all the arguments inside a
do
Making Macros Simpler
build a replica of Clojure's
.. macro, call it
chain
(defmacro chain [x form] (list '. x form)) ; chain needs support any number of arguments (defmacro chain ([x form] (list '. x form)) ([x form & more] (concat (list 'chain (list '. x form)) more))) ; exam it (macroexpand '(chain arm getHead)) => (. arm getHead) (macroexpand '(chain arm getHead getFinger)) => (. (. arm getHead) getFinger)
it works fine but this part is difficult to read
(contact (list 'chain (list '. x form)) more))
one solution is a templating language
; hypothetical templating language (defmacro chain ([x form] (. ${x} ${form})) ([x form & more] (chain (. ${x} ${form}) ${more})))
Syntax Quote, Unquote, and Splicing Unquote
The syntax quote character ``
`` works almost like normal quoting, but inside a syntax quoted list, the *unquote character* ~` turns quoting off again.
(defmacro chain [x form] `(. ~x ~form)) (macroexpand '(chain arm getHead)) => (. arm getHead)
but it doesn't work for multiple arguments
; does not quite work (defmacro chain ([x form] `(. ~x ~form)) ([x form & more] `(chain (. ~x ~form) ~more))) (macroexpand '(chain arm getHead getFinger)) => (. (. arm getHead) (getFinger))
you want
more to be spliced into the list. splicing unquote
~@ is a reader macro for it
(defmacro chain ([x form] `(. ~x ~form)) ([x form & more] `(chain (. ~x ~form) ~@more))) (macroexpand '(chain arm getHead getFinger)) => (. (. arm getHead) getFinger)
many macros follow the pattern of
chain:
- begin the macro body with syntax quote `` ` `` to treat the entire thing as a template
- insert individual arguments with an unquote
~
- splice in
morearguments with splicing unquote
~@ | https://jchk.net/read/clojure | CC-MAIN-2022-33 | refinedweb | 7,048 | 59.53 |
Starting a New Django Projectdjangopythonweb development
Introduction #
Occasionally I get to start over with a new Django project. Usually this is just some side project: very occasionally I get to build a greenfield project for someone else (protip for new developers: 99.99% of your career you'll be inheriting someone else's project, for better or worse).
If it's just a quick throwaway, for a tutorial or proof-of-concept, I just type
django-admin.py startproject and go with all the defaults. I won't need anything more than Sqlite and I definitely won't need Docker. Maybe a virtualenv and that's that.
But say it's a serious project that is likely to have legs. What does a "good" project skeleton look like?
Cookiecutters #
At this point some people will recommend using a cookiecutter, and the best supported and maintained right now is Daniel Roy Greenfeld's Django cookiecutter. If you have never built a large Django project before you could do far worse than use this. It comes with some good defaults. Personally I find it a little too large, and it has a lot of artefacts I don't need, but I still use it as a reference for current thinking about best practices in Django.
I also do not maintain my own cookiecutter. I've tried a couple times, but they're a pain to maintain. You want to keep adding new things to the cookiecutter to reflect your learning in your Django projects, and you also want to keep up with latest changes in the ecosystem - for example, a best-of-breed library falls out of favour in place of the next hot thing. Over time the cookiecutter drifts away from your latest projects and thinking.
I would probably keep a cookiecutter if a) there were other maintainers who could help keep it up to date or b) I was running an agency where I make new projects every other week and a cookiecutter saves perhaps days of work each time, and there is a need to maintain a base level of quality and consistency. At present though I just start with a plain Django project and make the changes I need manually.
Project configuration #
Typically you'll find:
- .dockerignore
- .editorconfig
- .flake8 (because Flake doesn't support pyproject.toml)
- .gitignore
- .npmrc
- .pre-commit-config.yaml
- .prettierrc
- package.json
- pyproject.toml
- requirements.in
- requirements.txt
My pre-commit file typically includes (in addition to standard whitespace checking etc):
- Bandit
- Black
- Flake8
- absolufy-imports
- djhtml
- isort
- mypy
- prettier
I have tried mypy with
django-stubs, but found it a massive pain to work with due to need to run it inside the Docker container (among other problems), so I just use mypy with these settings:
[mypy]
python_version = 3.10
check_untyped_defs = false
ignore_missing_imports = true
show_error_codes = true
warn_unused_ignores = false
warn_redundant_casts = false
warn_unused_configs = false
warn_unreachable = true
Perhaps not as comprehensive as
django-stubs but good enough to provide some benefit to typing.
Settings #
My typical settings structure will look something like this:
myproject - settings base.py local.py production.py test.py urls.py wsgi.py
Some people like to have an extra level or use a
config package or something like that. Personally I dislike the extra typing that involves.
To keep settings maintainable I use django-environ to use environment variables as much as possible, and django-split-settings to keep inter-settings imports nice and tidy. For example in
local.py instead of this:
from .base import *
INSTALLED_APPS = INSTALLED_APPS + ["debug_toolbar"]
we have:
from split_settings.tools import include
from myproject.settings.base import INSTALLED_APPS
include("base.py")
INSTALLED_APPS = INSTALLED_APPS + ["debug_toolbar"]
Templates #
Generally I avoid per-app templates, but keep the templates all in one place under the top-level directory. Keeping them in one easily-accessible place is nice and consistent, particularly if non-Django developers (say frontend people) want to work on them and don't particularly want to have to hunt around in different apps trying to find the right file (the same goes, of course, for static files).
I've gone back-and-forth on naming individual templates and subdirectories, particularly regarding partials. For a while I used the underscore convention for example
_article.html as opposed to a non-partial
article.html. Nowadays I prefer to move partials under an
includes subdirectory and avoid the underscore naming. This is just a personal preference thing, but it avoids a directory becoming too large with similarly named files. The top level templates directory will have a "junk drawer"
includes directory (in addition to specific includes for things like pagination templates) and individual apps will have their own
includes:
myproject + myproject - templates base.html - django - forms default.html - includes sidebar.html - pagination pagination_links.html ... - articles article.html - includes - article.html
Rule of thumb: if I have to
{% include %} a template (or access it using an inclusion template tag) it goes in the relevant
includes subdirectory, unless the include has a specific function like pagination, forms etc.
Static files #
Static files also live under the top directory:
myproject + myproject - static + css + dist + img + js
The
dist directory contains any files generated by whatever frontend build system (django-compress, esbuild, webpack etc) such as minified/processed CSS and Javascript/sourcemap files. These days I tend to start with a more lightweight frontend but if I'm building a full SPA the static files will probably live in their own frontend directory at the top level of the project (or an entirely different repo).
I prefer Tailwind over Bootstrap, Bulma and other CSS frameworks, at least as a starter default, so I'll probably have a
tailwind.config.js in the top directory as well.
Local apps #
Django apps are a bone of contention for even experienced developers. First of all the word "app" screams "I was a framework designed pre-2007" as the very word has changed in meaning not only in the tech world but in mainstream culture. Perhaps if Django were invented today we'd use something else; the Elixir framework Phoenix has "contexts" for example, but maybe "domains" would be more accurate (although we would then go into the weeds of Domain-Driven Development). Nevertheless, the hardest part about apps is not so much what we call them but deciding on their granularity. Some developers like to make Django more like Rails or Laravel and have a giant single app with separate packages for models, views and so on. I personally like the concept of apps though and prefer to keep them relatively small, with a few models per app.
In any case your apps will change during the lifetime of the project. However I know I'm probably going to need users and I'll probably need somewhere to put any code that's not going to fit anywhere else (or is not particularly business domain-specific): a "junk drawer". You can call your junk drawer app whatever you want, I like "common".
myproject - myproject + common + settings + static + users urls.py wsgi.py
Some projects I've seen have an
apps directory but personally I find this redundant, especially if using absolute imports. I also have a personal aversion to calling packages and modules
utils: if I have a couple of functions that do networking stuff, for example, I'll make a
networking module rather than keep them in a
utils module.
Preferred libraries #
I've already mentioned
django-environ and
django-split-settings. Other favourites include:
- dj-database-url
- django-allauth
- django-cachalot
- django-extensions
- django-model-utils
- django-redis
- django-widget-tweaks
- psycopg2-binary
- redis
- whitenoise
For production I'll probably throw in:
And for local development:
I'm a big fan of pytest (I'm aware some developers are less so). But as I am, I also include these libraries:
- pytest
- coverage
- pytest-django
- factory-boy
- pytest-cov
- pytest-forked
- pytest-mock
- pytest-randomly
- pytest-xdist
If I'm using HTMX (and for new projects that's increasingly the case) I'll also add django-htmx.
For queuing, as mentioned, I go with
rq over Celery unless I have bigger requirements, and starter projects tend to have pretty small requirements.
Regarding requirements: some people recommend splitting these up into local, production, test and so on, but I've found that more micromanagement that I like and it's easy to add a requirement in the wrong place and end up with a broken build. It's not the worst thing if your production has to install pytest libraries, for example, but you can easily miss or delete an important library from your production requirements and have everything work in your CI/CD pipeline only to have a nasty surprise at the end.
In addition I tend to use Heroku or Dokku for early-stage projects, and these work out of the box with a plain
requirements.txt file.
That's not so say a more complex requirements setup is better for a larger and more complex project, but for a starter project (the subject of this article) I want to keep it simple as possible.
I've tried Poetry a few times, but in general I've found it slow and error-prone, particularly inside Docker environments. I see the appeal, and I hope to make it my go-to some day, but right now I find it more trouble than it's worth. Instead I use pip-tools to generate and update my
requirements.txt file from a
requirements.in file.
Docker #
One other library I enjoy for local development - particularly as I tend to start with Heroku/Dokku for early-stage deployments - is Honcho. It makes it easier to add a development Procfile and wrap all my local environment into a single Docker image:
services:
honcho:
build:
context: .
environment:
DATABASE_URL: postgres://postgres:password@postgres:5432/postgres
REDIS_URL: redis://redis:6379/0
SECRET_KEY: seekrit!
restart: on-failure
privileged: true
tty: true
stop_grace_period: '3s'
logging:
options:
max-size: '100k'
max-file: '3'
ports:
- '8000:8000'
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
volumes:
- ./:/app
- /app/node_modules
command: [
'honcho',
'start',
'-f',
'./Procfile.local'
]
The
Procfile.local file looks something like this:
web: python manage.py runserver 0.0.0.0:8000 worker: python manage.py rqworker mail default watcher: npm run watch
This also means I can keep my local image in a small, simple
Dockerfile. This one includes both Python and frontend (Node/npm):
FROM python:3.10.4-buster
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONFAULTHANDLER=1
ENV PYTHONHASHSEED=random
ENV NODE_VERSION 17.9.0
RUN curl "" -O \
&& tar -xf "node-v$NODE_VERSION-linux-x64.tar.xz" \
&& ln -s "/node-v$NODE_VERSION-linux-x64/bin/node" /usr/local/bin/node \
&& ln -s "/node-v$NODE_VERSION-linux-x64/bin/npm" /usr/local/bin/npm \
&& ln -s "/node-v$NODE_VERSION-linux-x64/bin/npx" /usr/local/bin/npx \
&& rm -f "/node-v$NODE_VERSION-linux-x64.tar.xz"
WORKDIR /app
COPY ./requirements.txt ./requirements.txt
RUN pip install -r ./requirements.txt
COPY ./package.json ./package.json
COPY ./package-lock.json ./package-lock.json
RUN npm cache clean --force && npm ci
A more complex project might require using multi-stage builds, or multiple Docker images/containers, but again KISS is the principle until I know I need that complexity.
Note that this is a Docker set up for local development. Nowadays there are so many approaches to production deployments that it's very difficult to come up with generalized advice, especially around containerized deployments. You could go with anything from a simple PAAS deployment like Heroku, Dokku or Render up through various AWS or Google Cloud environments or a more complex multi-cloud Kubernetes-based set up (or even your own on-prem hardware), and a lot depends on requirements, experience and budget.
Scripts #
I typically have a top-level
bin directory with simple Bash scripts to access some common things inside Docker containers:
- bin manage npm pytest
So for example
bin/manage will look like:
#!/usr/bin/env bash
set -euo pipefail
docker-compose exec honcho ./manage.py $@
This saves on a lot of tedious typing, so for example I can do
./bin/manage shell instead of
docker-compose exec honcho ./manage.py shell.
Makefile #
I'll usually make a simple
Makefile at some point with common things e.g.
make build: to build containers
make test: run unit tests
make upor
make start
make downor
make stop
make shell: start Django shell
Again, I like a smooth local development environment with minimal typing, especially for things I have to do over and over.
Source code for this article here.
- Previous: Notes on Learning Finnish | https://danjacob.net/posts/startingnewdjangoproject/ | CC-MAIN-2022-40 | refinedweb | 2,106 | 52.6 |
Web forms play an important role on many sites on the internet, and they're something you should know how to build as a web developer.
From good ol' login forms to signup forms and survey forms (or whatever they're called these days), their main purpose is to receive data and send them to a backend server where they're stored.
In this article, we're going to see how we can convert the data gotten from a form from one type to another with JavaScript. But, before you read this article any further, you should have an understanding of the following:
- The basics of React.js
- How to preserve form state in React.js
- How to create controlled input components
Also, in this article, we'll be covering:
- How to send the form data that you obtain to a backend server through an API
- How to get the exact value of a label in the
optionsarray of the react-dropdown-select package.
Now that you know what you need to get started with this article, let's dive in.
Getting Started
We'll be building a simple form with React in this article so we can understand how the process works. To do that we'll be using Next.js to bootstrap our application. If you're new to Next.js, you can take a look at their documentation here.
Now let's get all the dependencies that we'll be needing in this project. Since it is a Next.js project, let's start by setting up a next-app:
npx create-next-app name-of-your-app
The command above will install all important dependencies that we need in a Next.js app function. The next dependencies that we need in this project are:
- xios for data fetching, and
- styled-components to style the app.
The command below does that for us:
npm install styled-components react-dropdown-select axios --save-dev
A typical Next.js project structure is different from that of create-react-app. To keep this article concise, we won't be going over the full application structure – we'll only be focusing on what applies to us.
That being said, let's take a look at the app structure below:
|__pages | |-- _app.js | |-- index.js |__src | |__components | | |__role | | | |__style | | | |-- role.styled.js | | |__index.js | | | |__containers | | |__dropdown-select | | |-- index.js | |__
Overview of the app structure
In the last section, we got the required dependencies for this project. In this section, we'll be looking at the project structure and the function that each file performs.
The pages directory is where all the routing of the app takes place. This is an out-of-the-box feature of Nextjs. It saves you the stress of hard-coding your independent routes.
pages/api: this API directory enables you to have a backend for your Next.js app. inside the same codebase. This means you don't have to go through.
pages/_app.js is where all our components get attached to the DOM. If you take a look at the component structure, you’ll see that all the components are passed as pageProps to the Component props too.
It is like the index.js file when using Create-React-App. The only difference here is that you are not hooking your app to the DOM node called “root”
React.render(document.getElementById("root"), <App />)
index.js is the default route in the pages folder. That is where we'll be doing most of the work in this project. When you run the command below, it starts up a development server and the contents of index.js are rendered on the web page.
components/role is the component file that houses the dropdown select component and its style
And lastly,
containers/dropdown-select is where we're building the form component.
How to Build the Form and Manage State
Now that we have seen some of the basic functions of the folders/files in the app, let's start building the form component. We won't be focusing on writing the styles in this article.
The code snippet below shows the basic structure of the form component without the state variables. We'll take a step-by-step approach to understanding what is going on in the snippet.
import React from "react"; import styled from "styled-components"; import { InputGroup } from "../../components/role/style/role.styled"; import Role from "../../components/role"; import axios from "axios"; const AuthForm = styled.form` ... `; const DropDownSelect = () => { return ( <AuthForm onSubmit=""> <h2>Register an Account...</h2> <InputGroup> <label htmlFor="email">Email address</label> <input name="email" id="email" type="email" placeholder="Enter email address" className="inputs" /> </InputGroup> <InputGroup> <label htmlFor="password">Create password</label> <input name="password" id="password" type="password" placeholder="Create password" className="inputs" /> </InputGroup> <Role /> </AuthForm> ); }; export default DropDownSelect;
The component above doesn't have any means of tracking the input that the user types into the form fields, and we do not want that. To get that sorted out, we'll make use of React's
useState() hook to monitor the state
Let's start by creating the state variables. You'll notice that we have three input fields in the component, so that means we'll have to create three state variables.
const [email, setEmail] = React.useState(""); const [password, setPassword] = React.useState(""); const [role, setRole] = React.useState();
But we need a way to track the state of the data we're sending to the backend server, so we need another state variable to monitor the status of our asynchronous data fetching (POST) request.
A very popular pattern in the React ecosystem is to create a loading component that'll indicate this process.
const [loading, setLoading] = React.useState(false);
Now that we have this in place we can set up our input fields to be controlled using the
onChange() prop.
<input name="email" id="email" type="email" placeholder="Enter email address" className="inputs" value={email} onChange={(e) => setEmail(e.target.value)} />
The process is then repeated for the remaining input fields. But, there's a catch. You'll notice that we already imported the
<Role /> component and we already passed some pre-defined props to the component. Let's take a look at the component itself before we go too deep.
The Role Component
This component utilizes the
react-dropdown-select package for its functionality, it takes in an array of values into its properties.
The least required prop is the
options prop which receives an array of objects with
label and
value keys
const options = [ { label: "Manager", value: "Manager" }, { label: "Worker", value: "Worker" } ]
Let's have a look at the component below:
import React from "react"; import { InputGroup } from "./style/role.styled"; import Select from "react-dropdown-select"; import propTypes from "prop-types"; const Role = ({ userRole, roleChange }) => { const options = [ { label: "Worker", value: "Worker" }, { label: "Manager", value: "Manager" }, ]; return ( <React.Fragment> <InputGroup> <label htmlFor="fullname">Role</label> <Select value={userRole} options={options} placeholder="Please select your role" required={true} dropdownPosition="top" className="select" color="#ff5c5c" onChange={roleChange} /> </InputGroup> </React.Fragment> ); }; export default Role; Role.propTypes = { ... };
I mentioned before that the
<Role /> component has its own custom props, and you can see that above.
The component takes in two props:
userRole that tracks the input based on the option that user selects, and the
roleChange prop that gets passed as a value to the
onChange() property of the
<Select /> component.
The
<Select /> component has various props that you can pass to it. From the
dropdownPosition prop that specifies where the options menu is positioned on the page, to the
color prop that affects the style of the items in the options menu, and so on. You can take a look at some of them here.
We made an import statement that brings in the React
"prop-types" module at the top of this component's file. We'll be using this module to validate the type of data that is passed into this component.
Role.propTypes = { userRole: propTypes.array.isRequired, roleChange: propTypes.func.isRequired, };
From snippet above, we stated that the type of data that will be passed into
userRole as a value must be of a JavaScript array data-type and
roleChange is required to be a function. Anything other than these will result in an error.
How to Use the Role Component
Now that we have gone through the
<Role /> component and learned how it works, let's take a look at how we can use it in the app below:
import React from "react"; import styled from "styled-components"; import { InputGroup } from "../../components/role/style/role.styled"; import Role from "../../components/role"; const AuthForm = styled.form` ... `; const DropDownSelect = () => { const [role, setRole] = React.useState(); return ( <AuthForm onSubmit={handleSignUp}> <h2>Register an Account...</h2> // previous details <Role userRole={role} roleChange={(role) => setRole(role.map((role) => role.value))} /> </AuthForm> ); }; export default DropDownSelect;
The snippet above shows how the
<Role /> component is being used. You can see the custom props in use too.
userRole is assigned the
role state value.
You may have been wondering why we did not assign any value to the
role state value we declared it. Well, that's because the
<Select /> component from react-dropdown-select has a default data-type value of an array, so there's no need to set an array in the
useState() hook.
The
roleChange prop looks totally different from the previous way we have been using the onChange prop in the input fields. Here, we had to place the items we needed into a separate array, so that we're able to get the exact data when the user selects an option.
roleChange={(role) => setRole(role.map((role) => role.value))}
If you can recall, we had an array called
options which had key value pairs of
label and
value. The snippet above helps us place the
value key into an entirely new array since that is what we need, and this is possible with the inbuilt
map() method of JavaScript.
When the user clicks on any option, we'll be getting an array containing just one item that was selected. Say, for example, the user clicks on the "Worker" option, the value that is stored in form state is:
['Worker'].
But we do not want this data type to be sent to the server – we want a string instead. How then do we fix this, you might ask? We'll see how we can do that in the next section.
How to Send the Form Data to the Server
In the previous sections, learned about the structure of a Next.js app and how to build and manage state in a React form.
In this section, we'll be sending the data that we obtained from the form to the backend server via an API.
import React from "react"; import styled from "styled-components"; import { InputGroup } from "../../components/role/style/role.styled"; import Role from "../../components/role"; import axios from "axios"; const AuthForm = styled.form` ... `; const DropDownSelect = () => { ... const [loading, setLoading] = React.useState(false); const handleSignUp = async (e) => { e.preventDefault(); try { setLoading(true); const response = await axios({ method: "POST", url: "", data: { email, password, role: role.toString(), }, headers: { "Content-Type": "application/json", }, }); } catch (error) { console.log(error); } }; return ( <AuthForm onSubmit={handleSignUp}> <h2>Register an Account...</h2> // form feilds <button className="btn">{loading ? "Registering" : "Register"}</button> </AuthForm> ); }; export default DropDownSelect;
We'll be focusing on the asynchronous data call function,
handleSignup, which we'll be using to send the data to the server through the API endpoint.
const handleSignUp = async (e) => { e.preventDefault(); try { setLoading(true); const response = await axios({ method: "POST", url: "", data: { email, password, role: role.toString(), }, headers: { "Content-Type": "application/json", }, }); } catch (error) { console.log(error); } };
The initial value of the
false, but in the
try block, it is
true. This means that, if the asynchronous data call is going on, the loading value should be
true. If not, it should be
false.
We mentioned before that we do not want to send an array data type as an input value to the server. Instead we want a string. We do this by using the native string method [
toString()] of JavaScript to transform this data type.
data: { role: role.toString() }
The
loading state value can be seen in action below. We're using a ternary operator to check if the loadin state variable is true. If Yes, the text in button will be "Registering". If No, the text remains unchanged.
<button className="btn">{loading ? "Registering" : "Register"}</button>
You can play with the snippet below to confirm if the result is accurate or not.
const options = [ { label: "Worker", value: "Worker" }, { label: "Manager", value: "Manager" } ] // create a new array with the key value that you want const mappedOptions = options.map(option => option.value) console.log(mappedOptions) // ['Worker', 'Manager'] // convert the mapped option array to a string value const mappedOptionsToString = mappedOptions.toString() console.log(mappedOptionsToString)
Conclusion
If your backend API lets you send an array data-type as a value from an input field, you can use what you have learnt here, because the react-dropdown-select package allows you to do that.
But in scenarios where the value that is required from your input field is a string, then you can consider using the native
toString() method of JavaScript as you wish.
Here's the link to the deployed demo app and a GIF that shows you what it looks like with all the styles applied:
Thank you for reading this article. If you've found it helpful, kindly share it with your peers. | https://www.freecodecamp.org/news/how-to-send-the-right-data-type-from-a-form-to-the-backend-server/ | CC-MAIN-2022-33 | refinedweb | 2,262 | 56.25 |
MooseX::Declare - Declarative syntax for Moose::clean is injected to clean up Moose for you.
Because of the way the options are parsed, you cannot have a class named "is", "with" or "extends".
It's possible to specify options for classes:
class Foo extends Bar { ... }
Sets a superclass for the class being declared.
class Foo with Role { ... }
Applies a role::clean is injected to clean up Moose::Role and.
When creating a class with MooseX::Declare like:
use MooseX::Declare; class Foo { ... }
What actually happens is something like this:
{ package Foo; use Moose; use namespace::clean -except => 'meta'; ... __PACKAGE__->meta->mate_immutable(); 1; } }
Furthermore, any imports will not be cleaned up by namespace::clean after compilation since the class knows nothing about them! The temptation to do this may stem from wanting to keep all your import declarations in the same place.
The solution is two-fold. First, only import MooseX::Declare outside the class definition (because you have to). Make all other imports inside the class definition and clean up with the
clean keyword:
use MooseX::Declare; class Foo { use Data::Dump qw/dump/; clean;.
MooseX::Method::Signatures
vim syntax:
Florian Ragwitz <rafl@debian.org>
With contributions from:
Licensed under the same terms as perl itself. | http://search.cpan.org/~flora/MooseX-Declare-0.20/lib/MooseX/Declare.pm | CC-MAIN-2017-09 | refinedweb | 206 | 67.35 |
hey yunhee,
like chris said i would use the java properties he defined and modify the following class
to set port to it by default to it:
your change would probably look something like:
public class JschSftpProtocolFactory implements ProtocolFactory {
public static final String PORT_PROPERTY = "org.apache.oodt.cas.protocol.s";
private int port;
public JschSftpProtocolFactory() {
port = System.getProperty(PORT_PROPERTY, -1);
}
....
}
up can then add the property (commented out) to:
-brian
On Aug 06, 2012, at 08:13 AM, "Mattmann, Chris A (388J)" <chris.a.mattmann@jpl.nasa.gov>
wrote:
Hi YunHee,
On Aug 6, 2012, at 5:20 AM, YunHee Kang wrote:
> Hi Chris,
>
> I am writing to you to ask you about how to apply a port number in a
> property file of the pushpull framework.
> Until now I didn't find how to do that in the push-pull user manual
> written by Brian.
>
> I think that we usually use a well-know port number assigned to a
> specific protocol. For instance the number 22 belongs to scp.
> But sometimes we use a different port number, instead of common port
> number, cause of a security reason.
> On the other hand, we also need to consider how to describe a port
> number that is assigned to a new protocol if we develop the protocol.
I think the best way to do this would be to:
1. Suggest a system property inside of the push_pull_framework.properties
file, e.g., org.apache.oodt.cas.protocol.s
2. To flow that system property down into the protocol API layer (e.g., expect
it to be read and set by the Push Pull framework, and then passed down
into the SFTP protocol; or more generally just change it to a protocol only
property and set there).
>
> Let me know how to add a new property for the port number.
Let me know what you think? We can file a JIRA issue and
when we have decided on an approach, create a patch and go from there.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ | http://mail-archives.apache.org/mod_mbox/oodt-user/201208.mbox/%3Ced9f2b47-9c29-cf43-89c7-a8e25f43c433@me.com%3E | CC-MAIN-2015-11 | refinedweb | 333 | 61.56 |
This question already has an answer here:
What is the reason behind “non-static method cannot be referenced from a static context”? [duplicate]
13 answers
You need to add "static" to all your methods, as well as to the variables you defined at the beginning (the arrays "rain" and "values").
You should always consider setting your methods as static whenever you're not using properties defined in the class you're working with (e.g. a method to calculate the average, usually depends only on the values you get as argument).
Instance variables cannot be accessed in static methods such as
main. You must make all of the fields and methods static.
static String[] rain = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; static double[] values; public static String mostRain(... public static String leastRain(...
Your problem is that your main method is
static but the other methods and variables are not.
You either need to create an instance of
rainfall and call the methods in that instance or make all the methods and variables static too.
You are calling a method in a static context:
System.out.println(Average(...));
That means that you are using the method without using it within an object context, i.e.
object.Average(...).
You must either
Declare the method to be static:
public static double Average(...) {
Or use the method on an object:
YourObject obj = new YourObject(); obj.Average(...);
PS: Methods should start with a lowercase character.
Change this
String[] rain = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; double[] values = { 0.40,0.94,3.21,3.74,1.73,1.03,1.27,2.58,6.98,6.90,2.80,2.53};
to this
static String[] rain = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; static double[] values = { 0.40,0.94,3.21,3.74,1.73,1.03,1.27,2.58,6.98,6.90,2.80,2.53};
or
put the (non-static) variables into the main function itself, and then pass them into the functions as needed. Such as
public static final void main(String[] ignored) { String[] rain = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; double[] values = { 0.40,0.94,3.21,3.74,1.73,1.03,1.27,2.58,6.98,6.90,2.80,2.53}; Total(values);
All functions called by main, as stated by others, either need to be static as well, or alternatively called via a new instance.
(And please, change function names to lowercase.)
Since those methods are non static, they can only be accessed through an object of that class. When you run static methods, they are not run through an instantiated object so they don't have access to the non static methods.
So what you would do is create a Rainfall object in main and call the methods on that object. This is how is is usually done. Generally, the main() method doesn't do much work itself but creates an object and calls the methods on that object to do the actual work.
So you would do something like:
public class Rainfall { //your methods from above public static void main(String[]Args) { String highest = "" ; String least = ""; double total = 0 ; double average = 0 ; double high = 0; double low = 0; Rainfall rain = new Rainfall(); System.out.println(" AUSTIN Tx RAINFALL 2009 " ); for( int i = 0 ; i < rain.length ; i ++ ) { System.out.println(rain[i]+"\t"+values[i]); } System.out.println(rain.Total(total)); System.out.println(rain.Average(average)); System.out.println(rain.mostRain(highest,high)); System.out.println(rain.leastRain(least,low)); } } | http://m.dlxedu.com/m/askdetail/3/c2c5c60abd2899a9bbb3a66b482f5a52.html | CC-MAIN-2019-13 | refinedweb | 614 | 55.64 |
Logging¶
Note
TODO(shade) This document is written from a shade POV. It needs to be combined with the existing logging guide, but also the logging systems need to be rationalized.
openstacksdk uses Python Logging. As openstacksdk is a library, it does not configure logging handlers automatically, expecting instead for that to be the purview of the consuming application.
Simple Usage¶
For consumers who just want to get a basic logging setup without thinking about it too deeply, there is a helper method. If used, it should be called before any other openstacksdk functionality.
openstack.
enable_logging(debug=False, http_debug=False, path=None, stream=None, format_stream=False, format_template='%(asctime)s %(levelname)s: %(name)s %(message)s')¶
Enable logging output.
Helper function to enable logging. This function is available for debugging purposes and for folks doing simple applications who want an easy ‘just make it work for me’. For more complex applications or for those who want more flexibility, the standard library
loggingpackage will receive these messages in any handlers you create.
- Parameters
debug (bool) – Set this to
Trueto receive debug messages.
http_debug (bool) – Set this to
Trueto receive debug messages including HTTP requests and responses. This implies
debug=True.
path (str) – If a path is specified, logging output will written to that file in addition to sys.stderr. The path is passed to logging.FileHandler, which will append messages the file (and create it if needed).
stream – One of
None `` or ``sys.stdoutor
sys.stderr. If it is
None, nothing is logged to a stream. If it isn’t
None, console output is logged to this stream.
format_stream (bool) – If format_stream is False, the default, apply
format_templateto
pathbut not to
streamoutputs. If True, apply
format_templateto
streamoutputs as well.
format_template (str) – Template to pass to
logging.Formatter.
- Return type
None
import openstack openstack.enable_logging()
The
stream parameter controls the stream where log message are written to.
It defaults to sys.stdout which will result in log messages being written
to STDOUT. It can be set to another output stream, or to
None to disable
logging to the console.
The
path parameter sets up logging to log to a file. By default, if
path is given and
stream is not, logging will only go to
path.
You can combine the
path and
stream parameters to log to both places
simultaneously.
To log messages to a file called
openstack.log and the console on
stdout:
import sys import openstack openstack.enable_logging( debug=True, path='openstack.log', stream=sys.stdout)
openstack.enable_logging also sets up a few other loggers and squelches some warnings or log messages that are otherwise uninteresting or unactionable by an openstacksdk user.
Advanced Usage¶
openstacksdk logs to a set of different named loggers.
Most of the logging is set up to log to the root
openstack logger.
There are additional sub-loggers that are used at times, primarily so that a
user can decide to turn on or off a specific type of logging. They are listed
below.
- openstack.config
Issues pertaining to configuration are logged to the
openstack.configlogger.
- openstack.iterate_timeout
When openstacksdk needs to poll a resource, it does so in a loop that waits between iterations and ultimately times out. The
openstack.iterate_timeoutlogger emits messages for each iteration indicating it is waiting and for how long. These can be useful to see for long running tasks so that one can know things are not stuck, but can also be noisy.
- openstack.fnmatch
openstacksdk will try to use fnmatch on given name_or_id arguments. It’s a best effort attempt, so pattern misses are logged to
openstack.fnmatch. A user may not be intending to use an fnmatch pattern - such as if they are trying to find an image named
Fedora 24 [official], so these messages are logged separately.
HTTP Tracing¶
HTTP Interactions are handled by keystoneauth. If you want to enable HTTP
tracing while using openstacksdk and are not using openstack.enable_logging,
set the log level of the
keystoneauth logger to
DEBUG.
For more information see
Python Logging¶
Python logging is a standard feature of Python and is documented fully in the Python Documentation, which varies by version of Python.
For more information on Python Logging for Python v2, see.
For more information on Python Logging for Python v3, see. | https://docs.openstack.org/openstacksdk/ussuri/user/guides/logging.html | CC-MAIN-2022-27 | refinedweb | 711 | 58.08 |
ColdFusion 10 - XmlSearch() And XmlTransform() Now Support XPath 2.0
In today's world, we don't often work with XML; the majority of data exchange is done using JavaScript Object Notation (JSON). Even APIs that support both XML and JSON seem to be dropping XML support in their roadmap (I know this from personal experience). That said, XML is still a data type that will inevitably be a part of our lives for some time. That's why it's actually kind of exciting that ColdFusion 10 now supports XPath 2.0 in the xmlSearch() and xmlTransform() functions.
NOTE: At the time of this writing, ColdFusion 10 was in public beta.
I don't pretend to be an expert on XPath or XSLT (Extensible Stylesheet Language Transformations); so, rather than try to explain the differences between the versions of XPath, I figured I would just demonstrate some of the functionality that is now available in ColdFusion 10. In the following code, I'm creating a simple XML document and then using xmlSearch() to gather various nodes. I try to explain what's going on in the comments.
- <!---
- Create an XML document on which to test new XPath 2.0
- functionality support.
- --->
- <cfxml variable="bookData">
- <books>
- <book id="101" rating="4.5">
- <title>Muscle: Confessions of an Unlikely Bodybuilder</title>
- <author>Samuel W. Fussell</author>
- <published>August 1, 1992</published>
- <isbn>0380717638</isbn>
- </book>
- <book id="201" rating="4">
- <title>The Fountainhead</title>
- <author>Ayn Rand</author>
- <published>November 1, 1994</published>
- <isbn>0452273331</isbn>
- </book>
- <book id="301" rating="4.5">
- <title>It Was On Fire When I Lay Down On It</title>
- <author>Robert Fulghum</author>
- <isbn>0804105820</isbn>
- </book>
- </books>
- </cfxml>
- <!--- Groovy - now let's execute some XML Path queries. --->
- <cfscript>
- // Get all of the ratings that are greater than or equal to 4.5.
- results = xmlSearch(
- bookData,
- "//book/@rating[ number( . ) > 4.0 ]"
- );
- // Get the average rating of the reviews.
- results = xmlSearch(
- bookData,
- "avg( //book/@rating )"
- );
- // Get a compoud result of the Title and Author notdes. Notice
- // that we can now create divergent results in the SAME path.
- // We don't need to create two completely different paths.
- results = xmlSearch(
- bookData,
- "//book/( title, author )"
- );
- // Get all of the book's children EXCEPT for the ISBN number.
- // XPath 2.0 introduces some intesting operators like "except",
- // "every", "some", etc.
- results = xmlSearch(
- bookData,
- "//book/( * except isbn )"
- );
- // XPath 2.0 now uses sequences instead of node-sets which allow
- // for more interesting data combinations. This only gets the
- // nodes from one collection that are NOT in the other collection.
- // We're using inline branching and merging!
- results = xmlSearch(
- bookData,
- "//book/( (title, published) except (isbn, published) )"
- );
- // Get all of the ISBN numbers that use a 10-digit ISBN. XPath
- // 2.0 now supports regular exprdssion functions like matches(),
- // replace(), and tokenize() -- thought it is quicky and a
- // bit limited in patterns.
- results = xmlSearch(
- bookData,
- "//book/isbn[ matches( text(), '^\d{10}$' ) ]"
- );
- // Iterate over one collection and map it onto the resultant
- // collection. We can now iterate inline within a path.
- results = xmlSearch(
- bookData,
- "for $b in (//book) return ( $b/published )"
- );
- // We can now pass in params into our xmlSeach() calls. Notice
- // that the key, "title" is quoted - that is because XPATH is
- // case-sensitive.
- results = xmlSearch(
- bookData,
- "//book/title[ . = $title ]",
- {
- "title": "The Fountainhead"
- }
- );
- // Get the given book, no matter what the casing. FINALLY, we
- // can case-insensitive searching in XML :)
- results = xmlSearch(
- bookData,
- "//book[ upper-case( title ) = 'THE FOUNTAINHEAD' ]"
- );
- // Debug the results.
- writeDump( results );
- </cfscript>
From what I've read about the functionality in XPath 2.0, the biggest upgrades seem to be the use of sequences over node-sets and the use of inline path branching and logic. At a very practical level, XPath 2.0 simply supports more functions like lower-case() and upper-case() for case-insensitive matching - something many people have asked for in previous versions of ColdFusion.
Oh, and XPath 2.0 now supports Regular Expression matching as well - yeah boyyyyyy!
Well, that's probably about as much excitement as I can squeeze out of searching XML documents in ColdFusion 10. That is, of course, until you realize that ColdFusion 10 can now parse HTML... but more to come on that shortly.
Reader Comments
@All,
And here's part of why XML is getting more exciting in ColdFusion 10 - we can now "easily" convert dirty HTML into valid XML documents:
Due to the JAR files that now ship with ColdFusion 10 (ie. TagSoup), we have now have built-in Java classes that facilitate this kind of parsing.
It all looked good until you added the part about regular expression support. That really put it over the edge to greatness!
@Steve,
Heck yeah! Regular expressions are always groovy :) Unfortunately, it looks like the "\b" word-boundary construct is not supported, which I only realized because it was the first thing I tried. They have a slightly different notation for some things, which I haven't gone through yet.
But, good to know that it's there.
That is disappointing omission. Still, I guess some regular expression support is a major improvement over no regular expression support at all.
Please provide the explanation of xml transfom in Cold Fusion | https://www.bennadel.com/blog/2340-coldfusion-10---xmlsearch-and-xmltransform-now-support-xpath-2-0.htm | CC-MAIN-2018-22 | refinedweb | 870 | 57.57 |
Archives
GhostDoc is RTM (or is that RTRAC?)
(RTRAC = Released to Roy's Addin Contest ;-)
23:49 the mail with my contest entry GhostDoc left my outbox.
I'm exhausted. Several nights of only 4 hours sleep are taking their toll. Mostly addin related problems, stuff not working that worked perfectly for weeks. COM registration issues, you name it.
I had to cut features, there are things that could have been better, but that sucker is out the door.
I feel satisfied.
Crunch Mode
I'm busy putting the final touches on GhostDoc for entering it here:
Testing, cutting features, testing, writing release notes, testing, fixing last minute bugs, testing, ...
Hmm. Some parts of developing software a more fun than others... ;-)
Cool Google Search Macro for Visual Studio
Marty Garins wrote a really cool macro for performing a Google search from Visual Studio.
See the feedback section of that blog entry for a minor addition I proposed (urlencoding of the search text). By the time you are reading this, it may already be included in the macro code.
Tip: If you want to limit your search to the MSDN site, add the red text to line building the URL string:
Dim url As String = String.Format("{0}", selectedText)
Strange: GetProcessesByName and Floppy Drive Access
Here's something strange: Each time I call the method Process.GetProcessesByName my floppy drive is accessed, which is rather annoying especially if no disk is inserted.
If you want to try it yourself, here's the code for a minimal command line app:
using System;
using System.Diagnostics;
class GetProcessesByNameDemo
{
static void Main(string[] args)
{
Process[] arrProcesses=Process.GetProcessesByName("notepad");
}
}
A search on Google Groups for "getprocessesbyname floppy" shows (at least at the moment of writing these lines) that I'm not the only one with this problem; unfortunately I could find neither an explanation nor a solution.
So.... anybody out there knowing more about this strange behavior? | https://weblogs.asp.net/rweigelt/archive/2004/6 | CC-MAIN-2020-29 | refinedweb | 323 | 63.49 |
check my code please?
Rene Rad
Greenhorn
Joined: Feb 10, 2010
Posts: 15
posted
Mar 29, 2010 21:22:02
0
Hey everyone,
I'm writing a method to shuffle a deck and am unsure if it's executing properly. I'm not sure how to check if it is shuffling 1000 times. (using constant public static final int TIMES_TO_SHUFFLE = 1000) My instructions are in the javadoc before the code. I tried using the debugger but I kept looping in the block and am unsure how to properly use it. Here is my code...
import java.util.Random; import java.util.ArrayList; public class Deck { /** The number of times to shuffle */ public static final int TIMES_TO_SHUFFLE = 1000; private ArrayList<Card> deck; // a deck of cards /** * Constructor for objects of class Deck */ public Deck() { deck = new ArrayList<Card>(); loadDeck(); } /** * Load a deck with all the cards */ public void loadDeck() { deck.add(new Card("Ace","Spades",11)); deck.add(new Card("Ace","Hearts",11)); deck.add(new Card("Ace","Clubs",11)); deck.add(new Card("Ace","Diamonds",11)); deck.add(new Card("King","Spades",10)); deck.add(new Card("King","Hearts",10)); deck.add(new Card("King","Clubs",10)); deck.add(new Card("King","Diamonds",10)); deck.add(new Card("Queen","Spades",10)); deck.add(new Card("Queen","Hearts",10)); deck.add(new Card("Queen","Clubs",10)); deck.add(new Card("Queen","Diamonds",10)); deck.add(new Card("Jack","Spades",10)); deck.add(new Card("Jack","Hearts",10)); deck.add(new Card("Jack","Clubs",10)); deck.add(new Card("Jack","Diamonds",10)); deck.add(new Card("10","Spades",10)); deck.add(new Card("10","Hearts",10)); deck.add(new Card("10","Clubs",10)); deck.add(new Card("10","Diamonds",10)); deck.add(new Card("9","Spades",9)); deck.add(new Card("9","Hearts",9)); deck.add(new Card("9","Clubs",9)); deck.add(new Card("9","Diamonds",9)); deck.add(new Card("8","Spades",8)); deck.add(new Card("8","Hearts",8)); deck.add(new Card("8","Clubs",8)); deck.add(new Card("8","Diamonds",8)); deck.add(new Card("7","Spades",7)); deck.add(new Card("7","Hearts",7)); deck.add(new Card("7","Clubs",7)); deck.add(new Card("7","Diamonds",7)); deck.add(new Card("6","Spades",6)); deck.add(new Card("6","Hearts",6)); deck.add(new Card("6","Clubs",6)); deck.add(new Card("6","Diamonds",6)); deck.add(new Card("5","Spades",5)); deck.add(new Card("5","Hearts",5)); deck.add(new Card("5","Clubs",5)); deck.add(new Card("5","Diamonds",5)); deck.add(new Card("4","Spades",4)); deck.add(new Card("4","Hearts",4)); deck.add(new Card("4","Clubs",4)); deck.add(new Card("4","Diamonds",4)); deck.add(new Card("3","Spades",3)); deck.add(new Card("3","Hearts",3)); deck.add(new Card("3","Clubs",3)); deck.add(new Card("3","Diamonds",3)); deck.add(new Card("2","Spades",2)); deck.add(new Card("2","Hearts",2)); deck.add(new Card("2","Clubs",2)); deck.add(new Card("2","Diamonds",2)); } /** * Add a single card to the deck. * @param a Card object */ public void addCard(Card cardToAdd) { deck.add(cardToAdd); } /** * Shuffle the deck. This involves selecting random pairs of * cards and swapping them, the number of times to swap determined * by the constant TIMES_TO_SHUFFLE. Java provides a shuffle method * as part of the Collections interface, however for this assignment * you must write your own. */ //public void shuffle() public void shuffle(){ int i = 0; while(i <= TIMES_TO_SHUFFLE) { ArrayList copy = new ArrayList(); for (Object object : deck) copy.add(object); Random generator = new Random(); ArrayList result = new ArrayList(); do{ int index = (int) (generator.nextDouble() * (double) copy.size()); result.add(copy.remove(index)); } while (copy.size() > 0); deck = result; i++; } } /** * Display the entire contents of the deck. Not used in the * game but useful for debugging. */ public void showDeck() { for (Card x : deck) { System.out.println("Type: "+ x.getDescription() + " Suit: " + x.getSuit()+ " Value: " + x.getValue() ); } } /** * Remove the top card (the first card) from the deck. * @return the Card object removed or null if there is nothing in the deck. */ public Card takeCard() { // return card or return null; } }
here is the card class.
public class Card { // instance variables private int value; private String suit; private String description; public Card(String description, String suit, int value){ this.description = description; this.suit = suit; this.value = value; } public String getDescription(){ return description; } public String getSuit(){ return suit; } public int getValue(){ return value; } }
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14686
16
I like...
posted
Mar 29, 2010 22:21:49
0
What I can understand from the javadoc is :
1. Take two cards (you need two random indexes)
2. Swap them (no need to use another array)
3. Repeat TIMES_TO_SHUFFLE times
If you follow these simple steps, the method should be easier to write.
[My Blog]
All roads lead to JavaRanch
Bert Wilkinson
Ranch Hand
Joined: Oct 28, 2009
Posts: 33
posted
Mar 29, 2010 23:04:25
0
It looks like your instructions for the assignment are in the javadoc....
So, with that in mind, your shuffle method looks like it will do some shuffling, but it is not doing what the javadoc says it should. You are looping through the entire deck TIMES_TO_SHUFFLE times vice doing that many "swaps" within the deck. Hopefully that's clear and gives you some direction on where you need to tweak your code.
After you think you are close, you can put a println statement in there to compare the deck before and after a "shuffle" is called to convince yourself something is happening.
David Newton
Author
Rancher
Joined: Sep 29, 2008
Posts: 12617
I like...
posted
Mar 30, 2010 05:20:10
0
(Consider using loop(s) in loadDeck rather than specifying each card manually, which is rather error-prone.)
Note also that "shuffling" in code is a different operation than shuffling a physical deck of cards--shuffling 1000 times is not likely to give you a deck that's (substantially?) more random than shuffling once.
I agree. Here's the link:
subject: check my code please?
Similar Threads
Compilation Err - Collection Interface Program
How to test my code for proper function?
adding objects to an arraylist.
Accessor methods on enum
Urgent help PLEASE
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/489396/java/java/check-code | CC-MAIN-2014-10 | refinedweb | 1,064 | 63.56 |
I have an assignment where I need to make a utility where if ran, it would perform the same action as a tee command in linux.
So the tee command takes the command line:
ls *.txt | tee txtfiles.txt
But for my assignment if I named the utility to be "test" then the command line would run:
ls *.txt | test txtfiles.txt
I am making this utility in C++ and need to use GNU Tools (so autoconf, automake, ./configure, etc) to compile the utility. I have no clue how to code the tee command in c++ as my background is VERY MINIMAL. One friend suggested I try this code:
#include <fstream> int main( int argc, const char** argv ) { std::ofstream file(argv[1]); teestream teeout(std::cout, file); teeout << std::cin.rdbuf(); }
I tried running ./configure and then make but a number of errors pop up when I run make:
gcc -DPACKAGE=\"test\" -DVERSION=\"1.0\" -I. -I. -g -O2 -c test.c test.c:1:19: error: fstream: No such file or directory test.c: In function ‘main’: test.c:5: error: expected expression before ‘:’ token test.c:6: error: ‘teestream’ undeclared (first use in this function) test.c:6: error: (Each undeclared identifier is reported only once test.c:6: error: for each function it appears in.) test.c:6: error: expected ‘;’ before ‘teeout’ test.c:7: error: ‘teeout’ undeclared (first use in this function) test.c:7: error: ‘std’ undeclared (first use in this function) test.c:7: error: expected ‘;’ before ‘:’ token make: *** [test.o] Error 1 | https://www.daniweb.com/programming/software-development/threads/327133/tee-command | CC-MAIN-2017-26 | refinedweb | 260 | 78.45 |
Den 11.01.2019 11.25, skrev Daniel Vetter:> On Fri, Jan 11, 2019 at 05:49:15PM +0800, CK Hu wrote:>> Hi, Daniel:>>>> On Fri, 2019-01-11 at 10:20 +0100, Daniel Vetter wrote:>>> On Fri, Jan 11, 2019 at 11:20:09AM +0800, CK Hu wrote:>>>> Hi, Daniel:>>>>>>>> On Thu, 2019-01-10 at 21:02 +0100, Daniel Vetter wrote:>>>>> On Thu, Jan 10, 2019 at 08:01:37PM +0100, Frank Wunderlich wrote:>>>>>> Hi Daniel,>>>>>>>>>>>>>> Would be good to use the new generic fbdev emulation code here, for even>>>>>>>> less code. Or at least know why this isn't possible to use for mtk (and>>>>>>>> maybe address that in the core code). Hand-rolling fbdev code shouldn't be>>>>>>>> needed anymore.>>>>>>>>>>>>>> Back on the mailing list, no private replies please:>>>>>>>>>>>> i don't wanted to spam all people with dumb questions ;)>>>>>>>>>> There's no dumb questions, only insufficient documentation :-)>>>>>>>>>>>> For examples please grep for drm_fbdev_generic_setup(). There's also a>>>>>>> still in-flight series from Gerd Hoffmann to convert over bochs. That,>>>>>>> plus all the kerneldoc linked from there should get you started.>>>>>>> -Daniel>>>>>>>>>>>> this is one of google best founds if i search for drm_fbdev_generic_setup:>>>>>>>>>>>>>>>>>>>>>>>> not very helpful...>>>>>>>>>>>> so i tried kernel-doc>>>>>>>>>>>>>>>>>>>>>>>> which is nice function-reference but i've found no generic workflow>>>>>>>>>>>> as the posted driver is "only" a driver ported from kernel 4.4 by Alexander, i don't know if this new framework can be used and which parts need to be changed. I only try to bring his code Mainline....>>>>>> Maybe CK Hu can help here because driver is originally from him and he knows internals. Or maybe you can help here?>>>>>>>>>>>> i personally make my first steps as spare-time kernel-developer :)>>>>>>>>>> There's a ton of in-kernel users of that function already, I meant you can>>>>> use those to serve as examples ... If those + the kerneldoc aren't>>>>> good enough, then we need to improve them.>>>>> -Daniel>>>>>>>> I've tried with drm_fbdev_generic_setup() and it works fine with simple>>>> modification. The patch is>>>>>>>> --- a/drivers/gpu/drm/mediatek/mtk_drm_drv.c>>>> +++ b/drivers/gpu/drm/mediatek/mtk_drm_drv.c>>>> @@ -16,6 +16,7 @@>>>> #include <drm/drm_atomic.h>>>>> #include <drm/drm_atomic_helper.h>>>>> #include <drm/drm_crtc_helper.h>>>>> +#include <drm/drm_fb_helper.h>>>>> #include <drm/drm_gem.h>>>>> #include <drm/drm_gem_cma_helper.h>>>>> #include <drm/drm_of.h>>>>> @@ -379,6 +380,7 @@ static void mtk_drm_kms_deinit(struct drm_device>>>> *drm)>>>> .gem_prime_get_sg_table = mtk_gem_prime_get_sg_table,>>>> .gem_prime_import_sg_table = mtk_gem_prime_import_sg_table,>>>> .gem_prime_mmap = mtk_drm_gem_mmap_buf,>>>> + .gem_prime_vmap = mtk_drm_gem_prime_vmap,>>>> .ioctls = mtk_ioctls,>>>> .num_ioctls = ARRAY_SIZE(mtk_ioctls),>>>> .fops = &mtk_drm_fops,>>>> @@ -416,6 +418,8 @@ static int mtk_drm_bind(struct device *dev)>>>> if (ret < 0)>>>> goto err_deinit;>>>>>>>> + drm_fbdev_generic_setup(drm, 32);>>>> +>>>> return 0;>>>>>>>>>>>> But I implement .gem_prime_vmap with a workaround,>>>>>>>>>>>> --- a/drivers/gpu/drm/mediatek/mtk_drm_gem.c>>>> +++ b/drivers/gpu/drm/mediatek/mtk_drm_gem.c>>>> @@ -280,3 +280,8 @@ int mtk_gem_create_ioctl(struct drm_device *dev,>>>> void *data,>>>> mtk_drm_gem_free_object(&mtk_gem->base);>>>> return ret;>>>> }>>>> +>>>> +void *mtk_drm_gem_prime_vmap(struct drm_gem_object *obj)>>>> +{>>>> + return (void *)1;>>>> +}>>>>>>>> Current drm_fb_helper depends on drm_client to create fbdev. When>>>> drm_client create drm_client_buffer, it need to vmap to get kernel>>>> vaddr. But I think for fbdev, the vaddr is useless. Do you agree that I>>>> temporarily implement .gem_prime_vmap in such way?>>>>>> The vmap is used by fbcon, without that fbdev won't really work I think.>>> So I'm rather confused on what you tested ...>>>>>> Adding Noralf, he's the expert here.>>> -Daniel>>>> I test with fb_test [1], it is a user space program just open /dev/fb0>> and mmap it to user space. I does not turn on fbcon so everything looks>> well. If support fbcon is essential, I would implement vmap correctly.>> If it's not essential, I think I could return 0 when>> CONFIG_FRAMBUFFER_CONSOLE is defined.> > I think fbdev emulation without working fbcon is fairly useless. And it> shouldn't be that much work to make it work, we have quite a few more> helers for gem bo nowadays.If the virtual address is not set, fbcon can't be used and that means ithas to be disabled using something like this in the driver Kconfig: depends on !FRAMEBUFFER_CONSOLEOtherwise it will crash if someone tries to use it.The problem here is that this driver doesn't map a virtual address forits buffers: mtk_gem->dma_attrs |= DMA_ATTR_NO_KERNEL_MAPPING;Probably because of limited virtual address space.rockchip is in the same situation.I'm aware of this shortcoming of the generic emulation, but I don't seehow it can be solved without using somekind of flag attached to the dumbbuffer creation request.Noralf. | https://lkml.org/lkml/2019/1/11/1065 | CC-MAIN-2019-04 | refinedweb | 742 | 57.06 |
5887/how-to-get-the-already-existing-channels-in-hyperledger-v1-0
I am using the Node SDK with Hyperledger 1.0 and want to check if a channel with a specific name exists. Is there a way to query all existing channels? Can I get a channel by its name?
You cannot see all available channels, but you can leverage CSCC (Configuration System Chaincode) GetChannels API to get a list of channels client eligible to. All you need to do is invoke chaincode named CSCC.
The CSCC is the system chaincode, meaning it inherently built in into peer binary and loaded and "instantiate" during peer startup. Considering NodeJS the request will look as following:
const request = {
chaincodeId : "cscc",
txId: 213213123123, // Some random transaction id
fcn: "GetChannels",
args: ['']
}
it can also be done by the peer cli
peer channel list
I think you have found a partial ...READ MORE
First, get the list of all existing ...READ MORE
There are two features that I know ...READ MORE
This information can easily be calculated by ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
To read and add data you can ...READ MORE
Give the proposal responses you are receiving ...READ MORE
Smart contracts can be definitive if they ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/5887/how-to-get-the-already-existing-channels-in-hyperledger-v1-0 | CC-MAIN-2020-34 | refinedweb | 235 | 67.65 |
Synchronized Considered Harmful
News flash: concurrency is hard. Any time you have mutable data and multiple threads, you are just asking for abuse, and synchronized is simply not going to cut it.
I was recently contacted by a client who was load testing their Tapestry 5.3.3.
Fortunately, these people approached me not with a vague performance complaint, but with a detailed listing of thread contention hotspots.
The goal with Tapestry has always been to build the code right initially, and optimize the code later if needed. I've gone through several cycles of this over the past couple of years, optimizing page construction time, or memory usage, or throughput performance (as here). In general, I follow Brian Goetz's advice: write simple, clean, code and let the compiler and Hotspot figure out the rest.
Another piece of advice from Brian is that "uncontested synchronized calls are very cheap". Many of the hotspots located by my client were, in fact, simple synchronized methods that did some lazy initialization. Here's an example:
public class InternalComponentResourcesImpl ... private Messages messages; public synchronized Messages getMessages() { if (messages == null) messages = elementResources.getMessages(componentModel); return messages; } }
In this example, getting the messages can be relatively time consuming and expensive, and is often not necessary at all. That is, in most instances of the class, the getMessages() method is never invoked. There were a bunch of similar examples of optional things that are often not needed ... but can be heavily used in the cases where they are used.
It turns out that "uncontested" really means virtually no thread contention whatsoever. I chatted with Brian at the Hacker Bed & Breakfast about this, and he explained that you can quickly go from "extremely cheap" to "asymptotically expensive" when there's any potential for contention. The synchronized keyword is very limited in one area: when exiting a synchronized block, all very, very, expensive.
Enter ReentrantReadWriteLock: this is an alternative that allows any number of readers to share a lock, but only a single writer. When a thread attempts to acquire the write lock, the thread blocks until all reader threads have released the read lock. The cost of managing the ReentrantReadWriteLock's state is somewhat higher than synchronized, but has the huge advantage of letting multiple reader threads operate simultaneously. That means much, much higher throughput.
In practice, this means you must acquire the shared read lock to look at a field, and acquire the write lock in order to change the field.
ReentrantReadWriteLock is smart about only waking the right thread or threads when either the read lock or the write lock is released. You don't see the same thrash you would with synchronized: if a thread is waiting for the write lock, and another thread releases it, ReentrantReadWriteLock will (likely) just unblock the one waiting thread.
Using synchronized is easy; with an explicit ReentrantReadWriteLock there's a lot more code to manage:
public class InternalComponentResourcesImpl ... private final ReadWriteLock lazyCreationLock = new ReentrantReadWriteLock(); private Messages messages; public Messages getMessages() { try { lazyCreationLock.readLock().lock(); if (messages == null) { obtainComponentMessages(); } return messages; } finally { lazyCreationLock.readLock().unlock(); } } private void obtainComponentMessages() { try { lazyCreationLock.readLock().unlock(); lazyCreationLock.writeLock().lock(); if (messages == null) { messages = elementResources.getMessages(componentModel); } } finally { lazyCreationLock.readLock().lock(); lazyCreationLock.writeLock().unlock(); } } }
I like to avoid nested try ... finally blocks, so I broke it out into seperate methods..
Is the conversion effort worth it? Well, so far, simply by converting synchronized to ReentrantReadWriteLock, and adding a couple of additional caches (also using ReentrantReadWriteLock), we've seen some significant improvements; from 450 req/sec to 2000 req/sec ... and there's still a few minor hotspots to address. I think that's been worth a few hours of work!
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
Francesco Illuminati replied on Sun, 2012/06/17 - 3:58am
Being a simple lazy initialization and not a variable you have to update, I would go for the double checking initiazialization idiom as suggested by Bloch :
But I would also seriously consider doing a proper initialization at constrution time (if the getter is used often enough the time spent constructing it is statistically irrilevant).
Stig Christensen replied on Sun, 2012/06/17 - 9:40am
Going from synchronized to the read/writer pattern would it this case almost be negligible. After all the only thing that was synchronized was the null instance check, and on your hardware this doesn't cost anything. The cache that your mentioned must be the real reason for the better performance.
The JRE 5+ (use of volatile and double locking) code posted by Francesco would also be my choice!
Philip Herbst replied on Sun, 2012/06/17 - 8:28am
in response to:
Francesco Illuminati
dieter von holten replied on Sun, 2012/06/17 - 9:27am
i think, the code as written has a problem: the messages field should be volatile. the semantics of synchronized make sure that fields accessed in a synchronized block are flushed when the block is left. i am not aware that the locks have the same behaviour.
as you said : concurrency is hard ...
Darryl Miles replied on Sun, 2012/06/17 - 11:49am
in response to:
Francesco Illuminati
I agree with comment 1 for the scenario presented in the main article. Due to lockless reads. One thing about synchronized is that every Object has one by default with no additional object count / memory overhead. Use of ReadWriteLock is better when there is likely to be frequent changes made to the data being protected in the lifetime of the app; in my experience messages would not a realistic example of that. Other than that a well written article to explain a way to do something differently.
With comment 1 I question the use of 'volatile' it can only make sense to ensure the Java VM does not optimize away the local variable 'FieldType result' setup in line 4. i.e. instead of ensuring a local reference is taken of whatever non-null object may exist in the field 'field' the compiler decides to convert all use of 'result' variable into direct load/store of the field itself. But I have not found any VM that would do this in a method coded the way comment 1 indicates. The characteristics of this method are that the value (and field value) is either null or non-null by way of having been initialized and once it is assigned a non-null value it is never changed again, a common Java idiom.
So maybe someone can explain by pointing at the Java specs the theoretical scenario by which volatile is a requirement for the code example function correctly across all VMs (and memory models used by CPUs).
Since there is exactly one load before (and outside) the synchronized block and one compare. Then the synchronized lock is aquired. Up until this point volatile seems irrelevant. Then this load is done again overwriting the old value (or in static single assignment terms, setting up a new version of variable 'result') that is then used for the compare performed inside the synchronized block.
As another commentor points out the writes to memory made inside the synchronized block can not be moved down to an execution point after the close of the synchronized block. So we are assured of a flush of changes to real memory will be made before control leaves the synchronized block.
What is unclear is if the reads from memory made before (and outside) the synchronized block from locations visible to changes from elsewhere need to be reloaded again when such a load expression is evaluated inside the synchronized block. If this is the case and volatile was not used anywhere and the Java VM optimized the code to completely remove the local variable 'result' the code would still be safe as a reload would happen again because the old value would be considered stale (even if known by the optimizer).
So I am asking does entering a synchronized block automatically make stale any aliases the optimizer knows for values that could have been modified in the meantime.
Re my choice of terminology new variables on the stack are considered private to the owning thread those references can't be modified from elsewhere. That is not to say the object(s) the variable reference point to can't have their state changed; but the concrete reference to the object can not be changed. Which is why the loading into a local variable is an important aspect in the comment 1 example.
Howard Lewis Ship replied on Mon, 2012/06/18 - 12:17pm
To reiterate comments I've made on the original blog post, the example I chose was the simplest case, for ease of discussion.
One of the main faults of synchronized is that is a lock per-object; imagine 500 threads all rendering the same Tapestry page simultaneously; those threads will be invoking synchronized methods of the same component objects with some frequency (even if they aren't invoking the exact same methods on those objects); in fact, the synchronized keyword will trend towards enforcingg that the threads are operating in lock-step. Replaced with the ReadWriteLock, the threads will be more free to operate at their own pace, passing though locked methods without respect to what other threads are currently doing, as they walk the page's component tree.
In any case, in an example this simple it is OK to not do any locking, as long as only a single field is updated, and that the value is idempotent; i.e., if multiple threads write to the field (due to a race condition), it doesn't matter which thread's value "wins". This works in the example, because the ElementResources object caches the result of the getComponentMessages() method anyway, so whichever threads invoke the method, the value assigned to the field will always be the same instance.
Other examples in the code are more complicated, involving updates to more than one field, or providing the possibility of memory leaks. See the source for those examples.
Howard Lewis Ship replied on Mon, 2012/06/18 - 12:23pm
in response to:
Philip Herbst
Howard Lewis Ship replied on Mon, 2012/06/18 - 12:36pm
in response to:
dieter von holten
John Russell replied on Tue, 2012/06/26 - 1:16pm
in response to:
Stig Christensen
Double Checked Locking isn't all its cracked up to be. In fact, since we're quoting the amazingly great Brian Goetz, its "broken".
Stig Christensen replied on Thu, 2012/06/28 - 12:25pm | http://java.dzone.com/articles/synchronized-considered | CC-MAIN-2014-10 | refinedweb | 1,773 | 58.42 |
You should create an alias.
Set-Alias alias command
example
Set-Alias "folder" "cd C:/Path/to/desktop/folder"
Edit: if you want to use argument you should make a script (using or not an
alias to call it)'
Turn on the wordpress debugging in wp-config.php file and run again to
check is there any fatal error or not:
define('WP_DEBUG', true);
And be sure that error reporting is On
Maybe you are not in right path. I found this theme on your host refer to
modular theme:.
You are adding a blank space " " too many
.overview li.active { border:1px solid rgba(51,204,204,0.9); } /* change
color on active */
.overview li.active:hover { border:1px solid rgba(51,204,204,0.9); } /*
trying to force border */
Basically, you were looking for any class active in the
children/grandchildren nodes of li and not on the li itself.
The problem you had was that currentItem didn't get updated when you
clicked on a breadcrumb.
I made a lot of changes, mostly "streamlining" things. I removed your
global variables and based the current item on the active class instead.
Check:
$("#next-button").on('click', function () {
var nextItem = $('.active').removeClass('active').next();
if (!nextItem.length) {
nextItem = $('.item').first();
}
nextItem.addClass('active');
});
$(".breadcrumb-cell .breadcrumb").on('click', function () {
$('.active').removeClass('active');
var theID = $(this).data("id");
$("#" + theID).addClass('active');
});
Note that I also modified your DOM a bit to make it easier to select an
item when a user clicks a breadcrumb. That change is
You use jQuery and you have a unique toggler id. So, you can do this inside
your existing function:
$('.post-[id]').addClass('active');
Some suggestions though:
Since your toggler classes have unique ids, you may want to have them use
ids instead of classes.
Instead of doing e.style.display, you can use jQuery's toggleClass which
keeps track of adding and removing a class for you. You start by hiding all
classes whenever you trigger the function, so you could just turn display
on for that div.
Since you use jQuery, you can use that to trigger the click as well.
A simple example based on your code:
<div class="trigger" id="[id]">Toggle</div>
$('.trigger').click(function(){
$('.episodemirrors').hide();
var id = $(this).attr('id');
$('#post-'+id).css('display'
Mouse events happen within the context of the Java application (not your
desktop). I don't think this is possible.
The best you can do is check if the cursor has left your Java application.
As user BackSlash mentioned,
you can use PointerInfo to get the pointer coordinates, but you cannot
know if it has entered something that isn't part of your java
application.
An alternative option is:
Add an AWTEventListener for focus events. As long as your app has
focus before the button is clicked you'll receive a focus lost event.
Then query for the pointer position.
The limitation is that, of course, your app loses focus. So depending
on what you are ultimately trying to achieve this might not be useful
No, the problem is not how you add the conditions. It is the condition
itself, because where needs one parameter. where.not does not work at all.
Try where('store_id <> 0')
Javascript
$('ul li a').on('click', function(e) {
// to keep your link from actually clicking through
e.preventDefault();
$(this).addClass('active');
$( '#' + $(this).attr('href') ).slideToggle();
});
HTML
<ul>
<li><a href="projekte">Projekte</a></li>
<li><a href="mo">Mo</a></li>
</ul>
So if you want to detect a desktop trying to view the mobile version put
this in your .htaccess file:
Options +FollowSymlinks
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^m.domain.com$
RewriteCond %{HTTP_USER_AGENT}
!C]|
You can check for the first item in the loop:
<div id="testimonials" class="carousel slide">
<div class="carousel-inner">
@{
var i = 0;
foreach (var item in Model.Testimonials)
{
var itemClass = i++ == 0 ? "item active" : "item";
<div class="@itemClass" style="max-height:70px;
overflow:hidden">
<h4>@item.Title</h4>
@item.Quote
</div>
}
}
</div>
</div>
or replace foreach with for loop if your Model.Testimonials property is a
type of IList<T> or any collection, which items can be individually
accessed by index:
<div id="testimonials" class="carousel slide">
1. use document ready to fire your jquery
(jQuery(document).ready(function($) {
// Code using $ as usual goes here.
});) see also:
2. you put the li tags of your subnav in a div instead of an ul tag
3. use a css selector to make your submenu active item visible:
.nav-list li.active li.active > a{
background-color: #0088CC;
color: #FFFFFF;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2);
}
Working example code:
<!DOCTYPE html>
<html>
<head>
<title>Responsive nesting</title>
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<!-- Bootstrap -->
<style type="text/css">
body {
padding-top: 40px;
padding-bottom: 40px;
}
.nav-list li.active li.active >.
I think that you want something like this:
<ul id="navigation">
<li <?php if (strpos($_SERVER['PHP_SELF'], 'index.php')) echo
'class="current"';?>><a href="index.php">Home
Page</a></li>
<li <?php if (strpos($_SERVER['PHP_SELF'], 'about.php')) echo
'class="current"';?>><a href="about.php">About
Me</a></li>
<li <?php if (strpos($_SERVER['PHP_SELF'], 'contact.php')) echo
'class="current"';?>><a href="contact.php">Contact
Me</a></li>
<li <?php if (strpos($_SERVER['PHP_SELF'], 'portfolio.php')) echo
'class="current"';?>><a href="portfolio.php">My
Work</a></li>
</ul>
I hope this will help you!
PS: index.php, about.php, contact.php and portofoli
Hope this helps!
As per this post, you can use a line like the following in the action of
choice:
@page_title="My Custom Title"
For example, to implement this in a pre-existing action like 'new', you
would do something like this:
controller do
def new do
@page_title="My Custom Title"
new! do |format|
format.html{render "my_new"}
end
end
end
Remove color: white; from your .dropdown ul li.on rule and instead add it
to this new css rule:
.dropdown ul li:hover > a {
color: white;
}
There are many ways to do this. There are some easy and some ugly hacky
ones:
Solution 1:
Use a Menu Control. The standard .NET Menu Control has an easy solution to
do this. This is the cleanest and fastest solution in my opinion. Have a
look at this post. Maby it'll help you if you choose this solution.
Solution 2:
You coud use some sort of javascript to highlight the current item. jQuery
would make that easier if you dont want to write everything by yourself.
For this solution have a look at this page. It's outdated but still
effective.
Solution 3:
This is kinda ugly solution and you can do that in many different ways: You
could change the <a> elements to HyperLink controls and set some sort
of session or cookie when you click on them. When set you could change the
style based o
You should do it like this:
<li <?php echo ($current_url == "globaluser.php") ? $active : ''?>
><a href="globaluser.php?Agent=<?php echo
$Agent;?>">Overview</a></li>
because right now you're conditioning the presence of the opening
<li> tag
var myIndex = $(this).parent('li').index();
$('.containers').eq(myIndex).find('.container_box').slideToggle().slideToggle();
The problem with your code is you are trying to retrieve it onclick. That's
the wrong logic. The correct logic is: when the page loads, retrieve it.
When the li is clicked, store it. You also have a problem when using
find("active"), you need to use the class character . otherwise it will
search for elements with the tag name active not the class.
$(document).ready(function () {
$("li").click(function () {
var id = $(this).attr("id");
$('#' + id).siblings().find(".active").removeClass("active");
// ^ you forgot this
$('#' + id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem != null) {
$('#' + s
This is a simple logic as follows
<li class="<?php echo (!empty($this->params['action']) &&
($this->params['action']=='controlpanel') )?'active' :'inactive'
?>">
<?php echo $this->Html->link('Dashboard',
array('controller'=>'users','action' => 'controlpanel'),
array('title' => 'Dashboard','class' => 'shortcut-dashboard'));?>
</li>
<li class="<?php echo (!empty($this->params['action']) &&
($this->params['action']=='index') )?'active' :'inactive' ?>">
<?php echo $this->Html->link('Contacts',
array('controller'=>'contacts','action' => 'index'), array('title'
=> 'Contacts','class' => 'shortcut-contacts'));?></li>
I found the answer to my question in one of "Related questions" on this
page. The answer was in this topic: Why does DirectoryServicesCOMException
occur querying Active Directory from a machine other than the web server?
I found, that it was exactly my case. After reading the suggested Microsoft
article, I learned, that impersonating works only for local resources on
the IIS server. To access network resources (SQL, Active Directory), I have
to set "Trust this computer for delegation" in the computer object in
Active Directory.
Try this: your modified example
$(document).ready(function(){
$('section').waypoint(function(direction) {
var me = $(this); //added
thisId = $(this).attr('id');
$('ul li').each(function(){
var secondaryID = $(this).attr('class');
if ( secondaryID == thisId )
{
$('ul li').removeClass('active');
//added
if(direction==='up'){
me = $(this).prev();
}
//added
if(!me.length){
me = $(this);
}
$(this).addClass('active');
}
});
},{offset: '0'});
});
UPD
ok, how about this exam
Background scripts are isolated from the current page because they're
designed to be persistant regardless of the content of the page. You need
to use the chrome.tabs API, specifically chrome.tabs.getCurrent. Once you
have the current tab, you can inject code into the window. That's where
your snippet above comes in.
You will need to add "tab" to your permissions in the manifest file.
I ended up with doing two requests and merging the results together. It is
not as hard as it sounds:
# per_page is 20
limit = "#{(page.to_i - 1) * 20}, #{(page.to_i * 20)}"
query = Users.where('items.title LIKE "%whatever%"').where('addresses.lat
< 50')
return query.includes([{items: [:images, :category]}, :profile,
:addresses]).
joins(:items).
limit(limit).all |
query.select('DISTINCT users.*').joins(:items, :addresses).
limit(200).all
Remark 1:
This eager loads only the 20 elements of the current page, and adds all the
elements on the other pages without eager loading. For example, say you are
on page 3, the first request would eager loads with limit 60, 80 and
elements #0 to #199 are added. The way array union (operator |) works in
ruby is that if the s
With the introduction of Windows 8, Metro, and Windows Store, API
documentations now specify which framework(s) they are supported on. Not
all desktop APIs are available to metro/mobile apps, and vice versa.
Yes, check your session_id(). If it returns an empty string, session is not
set. If you want to be able to tell from the client-side, you'll need to
use AJAX.
you can set javascript variable as bellow and use it for your script.
sample code with php ,
<?php
$active_tab_from_php = 2 // you should change this, for testing you can
hard code
echo '<script> var active_tab = "'. $active_tab_from_php .
'";</script>';
?>
now you can use this active_tab variable with your script as below,
var current = active_tab;
jQuery's .load() will allow you to fetch just a portion of a document. See:
For example:
$('#summary').load('somepage.html #summary > *');
Loads the content of the element #summary from the page somepage.html into
the current element #summary
You mean scrollspy? Check here
// Cache selectors
var lastId,
topMenu = $("#top-menu"),
topMenuHeight = topMenu.outerHeight()+15,
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
$(window).scroll(function(){
// Get container scroll
That's a PHP config issue. If you don´t have any access to the php.ini
file or don´t wanna mess with it, what you can do is that every time you
enter a page you save the current page in a table on the database (it
should have a relation with the user table), and when the user log outs
after the 30min limit, you just retrieve that value from the database.
You can get the current URL with $_SERVER['PHP_SELF']. To check if the user
logout just save a session variable and everytime the page is load do:
if(!isset($_SESSION['userid'])){
// redirect to the page in the database table
header("Location: ".$field_from_db);
}
Hope it helps!
Here is how I add page classes to all of my pages:
In the beginning of my index.php file, I add the following php:
if (is_object($menu))
$pageclass = $menu->params->get('pageclass_sfx');
Then, I use the following for the new opening body tag:
<body class="<?php echo $pageclass ? htmlspecialchars($pageclass) :
'default'; ?>">
This sets the body class to "default" by default if a Page Class is not set
(see below).
Once the above is done, changing the body class is easy. In the Joomla
admin, open the menu item you want to set the page class on, click on
Advanced Options and scroll down/expand Page Display Options. Enter the
class name in Page Class and that's it!
Just use an if-statement to add "active-page" as class to the current
active page:
<li><a href="index.html" title="Home" class="<?php if
(ACTIVE_PAGE == "About") echo "active-page"; ?>"><span
aria-hidden="true" class="li_display
nav_icon"></span>About</a>
You then need to define a constant ACTIVE_PAGE before including your
navigation.
<?php
define ('ACTIVE_PAGE', "About");
include ('yournav.php');
?>
This should work and is okay if you do not have too many pages.
An alternative could be in getting the currently visited page via
$_SERVER['PHP_SELF']
and then add to navigation.php which html-file shall be called for which
entry in php_self. The advantage would be that you have all your
navigation-based code in one place. Personally, I wo");
}
Sure, you can do it in CSS, using @media rules to set different fonts based
on the screen size. Here's a good source of information:.
I'd set the desktop font first, then override it with @media queries with
your phone font. | http://www.w3hello.com/questions/-Adding-ASP-NET-page-to-active-desktop- | CC-MAIN-2018-17 | refinedweb | 2,376 | 60.21 |
Recent mobile application models impose some surprising straightjackets that defeat the ability to compose applications from constituent parts.
On the desktop, composition support is de rigeur. On Windows it’s possible because there simply aren’t many rules. Want to use a DLL that uses another DLL that loads some external resources? There’s an API for that. Well, APIs, anyway. You can string them together by solving for units, which by the way also works wonders in high school physics.
On Mac OS composition is by design. Which is fortunate, since otherwise it probably wouldn’t be allowed. Depend on a framework? There’s a place to put it. Framework depends on another framework? Yes, there’s a place for that, too. All places rationally named, everything is a bundle, layout standardized.
iOS? Not so much. Mostly because dynamic code loading isn’t allowed, at least not outside of OS frameworks. We have to revert to linking everything together into one big blob. And then all linker symbols appear in a common namespace, so we’re denied the pleasure of embedding multiple copies of the PNG library into the same application without modifying any of them to use unique prefixes.
The real surprise for me, though, was Android. Surely an open platform would support composition? But alas, resources on Android get compiled into one big block of unique IDs. No way to use this mechanism to create a library beforehand with its own set, because there’s only one R.java file to rule them all.
No doubt there’s a method to the madness that I just can’t see. Maybe they can break it down into pieces for me. | http://blogs.adobe.com/simplicity/2011/07/application-structure-and-composition.html | CC-MAIN-2015-11 | refinedweb | 282 | 68.97 |
- PMC suddenly refused to lock.
- Investigated what's wrong
- Finally, I touched RF Output Adjust (C1:PSL-PMC_RFADJ). Then it started locking.
- C1:PSL-PMC_RFADJ was set to 2.0 by rana when we looked at the PMC LO issue.
Now PMC does not lock with this value. I set it to 6.0 so that the lock is robust.
- Right before I lost PMC locking, I had some difficulty in locking IMC. Of course, the robustness of the PMC is related to the robustness of the IMC.
We definitely need to investigate this. (RF powers, open loop TF, etc)
FSS Slow set point to be zero
op340m:FSS>cat FSSSlowServo
#!/usr/bin/perl -w
# PID Servo for PSL-FSS (Slow)
# Tobin Fricke 2007-01-09
use strict;
#use Scalar::Util qw(looks_like_number);
sub looks_like_number {
return ($_[0] =~ /^-?\d+\.?\d*$/); #FIXME
}
use EpicsTools;
# Parameters
my $process = 'C1:PSL-FSS_FAST';
my $actuator = 'C1:PSL-FSS_SLOWDC';
#my $setpoint = 5.5;
my $setpoint = 0;
my $blinkystatus = 0;
op340m:scripts>/opt/rtcds/caltech/c1/scripts/PSL/FSS/FSSSlowServo > /cvs/cds/caltech/logs/scripts/FSSslow.cronlog &
The main IFO modulation frequency was adjusted to match with the FSR of the IMC.
The new frequency is 11.066128 MHz. This corresponds to the IMC round-trip length of 27.0910 m
This has been done by looking at the peak at 25.845MHz (5* fmod - 29.5MHz) in the MC REFL PD mon.
Did this break "netgpibdata"?
I couldn't download data from SR785. Downloading from AG4395A was OK.
The cause seemed the module for SR785
-rw-rw-r-- 1 controls controls 24225 2014-07-30 18:36 SR785.py
I had a local copy of this file and replaced it with mine. Now netgpibdata start working.
The old one is named SR785.py_bak
-rwxr-xr-x 1 controls staff 12944 Jul 31 23:08 SR785.py
The file size is significantly different from the one we had.
Oh, this is cool! Thanks!
I could not figure out how to place robot.txt as it was not so obvious how elogd handles the files in the "logfile" directory..
Purpose.
Methods.
Moving Forward
The.
These telescopes will be used to mode match//couple the dumped SHG light from both PSL and AUX (Y-Arm) lasers into PM fibers for use in FOL...
Plan for the week:
Inside the Lab:
Yesterday,.
From old 40m elog 5-29-2007 address as I find them, to make them robust against future local movement of the svn files.
Peoples' user files should be fine, this looks like it'll only really affect things such as scripts and medm screens, etc.
That was super fast! Great job, Andres and Nic!
Nick and I did the upgrade for the green steering mirror today. We locked in the TEM00 mode.
We placed the shutter and everything. We move the OL, but we placed it back. Tonight, I'll be doing a more complete elog with more details..
ETMX sus damping restored
[Akhil, Harry]
Work Completed :
Frequency Counter:
- Transfer Function
- Quantization Noise Estimation
Temperature Actuator:
EPICS and Channel Readout:
Frequency Offset Locking(FOL) Box Design and Plan:
Work Plan for Upcoming Weeks:.
The PRM sus gains checked OK
All other suspension oplev gains setting were checked out OK
arrrrggggh
I've restored the gains to their old values, and measured the loop TFs.
. | https://nodus.ligo.caltech.edu:8081/40m/?id=10296 | CC-MAIN-2022-21 | refinedweb | 558 | 77.74 |
Reverse Fast Fourier Transform. More...
#include <vtkImageRFFT.h>
Reverse Fast Fourier Transform.
vtkImageRFFT implements the reverse butterfly filters for each prime factor of the dimension. This makes images with prime number dimensions (i.e. 17x17) much slower to compute. Multi dimensional (i.e volumes) FFT's are decomposed so that each axis executes in series. In most cases the RFFT will produce an image whose imaginary values are all zero's. In this case vtkImageExtractComponents can be used to remove this imaginary components leaving only the real image.
Definition at line 41 of file vtkImageRFFT.h.
Definition at line 45 of file vtkImageRFFT.h.
Definition at line 48 of file vtkImageRFFT.h.
Definition at line 49 of file vtkImageRFFT.h.
Return 1 if this class is the same type of (or a subclass of) the named class.
Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h.
Reimplemented from vtkImageFourierFilter.
Reimplemented from vtkImageFourierFilter. | https://vtk.org/doc/nightly/html/classvtkImageRFFT.html | CC-MAIN-2020-16 | refinedweb | 157 | 54.69 |
Hello World!
This should prove to be an interesting series of posts coming up, as I am working on a new project that is very unique and interesting. The idea is to use incoming data from Arduinos, Raspberry Pis, Gallileos, Edisons and other assortments of IoT type devices connected to oil and gas pipelines to determine if a leak is currently in progress and also predict if a leak is likely to occur in the future based on current and trending conditions.
My part in the project is all back end analytics, and I have very little to do with the actual telemetry and hardware. The telemetry will be posted using Azure Event Hubs, and thus my portion of the project begins with mocking that real time data at a large enough geo dispersed scale that I can develop a system that can handle it, and then switch my configurations to consume from the production event hubs. Since I am no longer a consultant working on projects with trade secrets and everything these days is about the elevation of skills in the community, I have posted everything on github that you can download and peruse at your leisure. Please note that this is in progress and well the github source may not necessarily work when you look. I’ll try to enforce a standard to comment “working – comment” on pushes to the repository. The git repository is located here:
So 30,000 foot view
of the components of the project are: C# to deal with Azure components, F# to do the real heavy lifting. We are using Azure Event Hubs, because Event Hubs kicks ass. The final component that hosts the worker role is currently Cloud Services, but because WebSite’s Web Job has the capability to scale vertically without a redeployment, I recommend to go that route, however I have implemented a cloud service, just realize, vertical scaling requires a redeployment and is not instantaneous.
So to generate the mock data, there are a few project files that you will want to focus on in the solution. Those projects are: OilGas.DataGeneration, OilGas.DataGenerator, Oil.Gas.DataGenerator.CloudService, OilGas.EventHubProvider and OilGas.TelemetryCore.
Lets talk high level about what each project is for and what it does.
OilGas.TelemetryCore is nothing more than a definition of all telemetry data that may be posted out to event hubs. This is shared across almost all projects in the solution. This is a C# project.
OilGas.DataGenerator.CloudService is the hosting project. This is the project that contains the definition for how many of what size machines will be used in the deployment. This is the Azure specific project that you can right click publish out to Azure.
OilGas.DataGenerator is a C# worker role. It simply wraps my F# implementations of posting data. It is C# purely for the reason of the F# worker role just doesn’t work. I have submitted a bug to the Azure team, and a fix is due to be included in the next release.
OilGas.DataGeneration is poorly named, it should be OilGas.DataGenerator.Core. This is the bread and butter of how posting data works. It is an F# application that leverages the parallel Sequence libraries to take advantage of all cores and make sure I can peg my current box both in horizontal and vertically scaled scenarios.
OilGas.EventHubProvider was my attempt to have a re-useable event hub library. This could probably have just been shoved in with OilGas.DataGeneration, but whatever, its here. It simply provides a simpler interface for dealing with Event Hubs.
So I’m going to focus on what I believe to be the most interesting components of the solution for this article, and let you check out github for the rest.
The Cloud Service, go read the documentation on MSDN, its straightforward, its simple, I’m not going to talk about that; same with the worker role. The core to this is the EventHub Provider and the DataGeneration (or Generator.Core if I get around to renaming it). Lets start with the DataGeneration project, as that will allow me to break the problem down in the way that I think.
DataGeneration
The first part and file of this project is Core.fs. If you are unfamiliar with railway oriented programming, I have an article written on that located here: personal plug, in Core.fs, you will find a function “pipeWithAdditionals”, if you can figure that out, comment here, contribute, I ran out of time, but something on the backlog to figure out. Core.fs is nothing more than ensuring I have ROP available to my code base.
The real complexity lies in this section of code. The rest should be self explanatory (I hope, leave comments if its not).
let Run () = let s = seq { for i in 1 .. 5 -> CreateTelemetryDevice i } |> Seq.filter(fun d -> match d with | Success s -> true | Failure f -> false) |> Seq.map(fun d -> d.SuccessValue) while(true) do Thread.Sleep(4000) s |> PSeq.iter(fun d -> Thread.Sleep(1000) d |> GenerateSensorData |> ignore )
Everything before the while(true) statement simply creates new telemetry devices and transforms from wrapped success results into devices. I use ROP, but not the way its intended here. After the while true, I use the PSeq, which is a nuget package called: “FSharp.Collections.ParallelSeq”. This takes a sequence and dynamically determines the number of cores you have available and kicks off that many processes scheduled specifically on those cores. Notice I have sleep, just ditch those sleep statements if you want to generate data faster.
Next steps on this for me is to change device id’s to being generated based on machine name+core number and to maybe rebuild devices every 10 minutes to deal with possibly random vertical scaling that is possible due to the way clouds work. This particular instance is built for a machine instance with 4 cores. (notice that I have 4 devices, and I am uses parallel seq on a seq with 4 items in it, each device. This will work on as small as 1 core, but as large as 4.
So where is the tie in to OilGas.EventHubProvider?
That is located in the actual generation function:
let createProvider() = let config = CreateEHConfiguration <!> succeed @"" <*> succeed @"Endpoint=sb://rtoieventhub-ns.servicebus.windows.net/;SharedAccessKeyName=master;SharedAccessKey=iAZa4YpxH4IeEatOC1MpImgVLby45NGZq+6TRcqrRAU=" <*> succeed @"oilgasmockinput" match config with | Failure f -> Failure f | Success s -> new EventHubProvider(s.ns, s.description, s.connstring) |> succeed let generateFlowEvent(provider:EventHubProvider, device:TelemetryDevice) = let eventData = new PipeFlowTelemetryEvent( device.id.ToString() + "F" + DateTime.UtcNow.ToString(), device.id, 3.0f, DateTime.UtcNow, device.longitude, device.latitude) provider.SendEvent(eventData).Wait() device let GenerateSensorData (device : TelemetryDevice) = let p = createProvider() match p with | Success s -> generateFlowEvent(s, device) |> succeed | Failure f -> Failure f
p = createProvider() makes a call that is into the EventHubProvider to create the provider, and then the provider.SendEvent manages the actual sending of an event asynchronously, which is of course important to keep scalability high and make sure we peg all our cores in the most optimal way.
So lets check out Event Hub Provider’s Create Provider and SendEvent functions (or methods).
/// <summary> /// Instantiate an Event Hub along with a Client. /// </summary> /// <param name="hubNameSpace">uri namespace</param> /// <param name="description">description</param> /// <param name="connectionString">connection string from app.config</param> public EventHubProvider(string hubNameSpace, string description, string connectionString, bool createClient = true) { ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(connectionString); builder.TransportType = TransportType.Amqp; NamespaceManager manager = NamespaceManager.CreateFromConnectionString(builder.ToString()); this.EHDescription = manager.CreateEventHubIfNotExists(description); this.EHClient = EventHubClient.CreateFromConnectionString(connectionString, EHDescription.Path); }
This is easy, it just simply wraps the standard creation of an EventHub Client per the msdn documentation. Piece of cake!
/// <summary> /// Sends a message. Note that if this fails, it will throw an exception. For performance reasons, it is not try/catched here. /// </summary> /// <param name="eventHubName"></param> /// <param name="message"></param> /// <returns></returns> public Task SendEvent(ITelemetryMessage message) { var serializedString = JsonConvert.SerializeObject(message); EventData data = new EventData(Encoding.UTF8.GetBytes(serializedString)) { PartitionKey = message.ID }; // Set user properties if needed data.Properties.Add("Type", "PipeFlow" + DateTime.UtcNow.ToLongTimeString()); return this.EHClient.SendAsync(data); }
Sending an event is exactly the same deal. Simply wraps an event hub send event.
So where is the magic here? Well, it has to do with the F# PSeq operation, and a few things on the backlog to do. The largest to do item is to take advantage of Event Hub partitions. When you start sending insane quantities of data, you should start taking advantage of the 16 default partitions up to the maximum 32 partitions that you have available to you. When you do it this way, analyzing data from each partition is a bit easier to plan for, as 1 compute box per posting partition to analyze with, maximum 32 box cluster, which is pretty damn sizeable.
Summary
So here you have it, a basic solution for mocking telemetry input from IoT devices to Azure Event Hubs in which you can scale to god knows how high, we can take advantage of all cores, so G series boxes and scale horizontally. The biggest changes to do would be the following items:
- Remove thread sleeps.
- Number device Ids by machineId + thread Id.
- Randomize data based on realistic data trends and errors.
- Take advantage of Event Hub Partitions.
Pingback: Pipe Dreams: Fun with Azure and IoT - Jennifer Marsman - Site Home - MSDN Blogs
Pingback: F# Weekly #11, 2015 | Sergey Tihon's Blog
Thanks for sharing for your ‘so where is the tie in to Oil Gas.Event Hub Provider. | http://dacrook.com/mocking-iot-telemetry-data-with-azure/ | CC-MAIN-2017-30 | refinedweb | 1,603 | 55.84 |
This is a
playground to test code. It runs a full
Node.js environment and already has all of
npm’s 400,000 packages pre-installed, including
pryjs with all
npm packages installed. Try it out:
require()any package directly from npm
awaitany promise instead of using callbacks (example)
This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.
A interactive repl for node, inspired by pry.
npm install --save pryjs
Throw this beautiful snippet in the middle of your code:
import pry from 'pryjs' eval(pry.it)
pry = require('pryjs') eval(pry.it)
You MUST name the variable
pry. You are executing an anonymous function, and
this assumes the variable is named
pry in your scope. This is so it can keep
prompting you.
While you are in the prompt there are a few things you might want to do:
helpdisplay all the available commands.
killcompletely stop the script.
modeswitch between javascript and coffeescript mode. Defaults to javascript.
playplay lines of code as if you had entered them. Accepts two integers: start and end. End defaults to start.
stopwill exit the pryjs prompt and continue through the app.
versiondisplay the current version.
whereamiwill show you exactly where you are in the code. Accepts two integers to replace the default 5 before and 5 after.
wtfdisplay the last caught exception.
Examples can be found in the examples directory. | https://npm.runkit.com/pryjs | CC-MAIN-2019-18 | refinedweb | 235 | 69.99 |
One of Java's greatest advantages is that its design allows for cross-platform capability. This feature, however, is also a bug with regard to other aspects of programming. It is constrained in its interaction with the local machine, and thus the local machine instructions cannot be utilized to achieve the full performance potential of the machine. To ameliorate this weakness, there is the Java Native Interface, a Java platform that interacts with the machine on the local level. It can be employed to allow the use of legacy code and more interaction with the hardware for efficient performance. This article explores the JNI workflow, provides code examples of how Java calls in both C and C++, and introduces the Android Native Development Kit (NDK), which compiles the C/C++ code into applications that can run on an Android device.
JNI and NDK
This article focuses on the capabilities of the Java Native Interface, which overcomes the limitations of Java by allowing Java code and native code software collaborate and share resources. We introduce the basic workflow of JNI, and then provide instructions and code examples for the general framework of a C/C++ function call via a JNI and Java program, noting the slight variations that exist between C and C++. The Android NDK is also introduced and explained. By the end of the article, a developer should understand how to utilize both JNI and NDK on Android devices.
JNI Introduction
We know that Java applications do not run directly on the hardware, but actually run in a virtual machine. The source code of an application is not compiled to get the hardware instructions, but is instead compiled to get the interpretation of a virtual machine to execute code. For example, Android applications run in the Dalvik virtual machine; its compiled code is executable code for the Dalvik virtual machine in DEX format. This feature means that Java runs on the virtual machine and actually ensures its cross-platform capability: that is, its "compile once, run anywhere" feature. This cross-platform capability of Java causes it to be less connected to and limits its interaction with the local machine's various internal components, making it difficult to use the local machine instructions to utilize the performance potential of the machine. It is difficult to take advantage of locally based instructions to run a huge existing software library, and thus functionality and performance are limited.
Is there a way to make Java code and native code software collaborate and share resources? The answer is yes: the Java Native Interface (JNI), which is an implementation method of a Java local operation. JNI is a Java platform defined as the Java standard to interact with the code on the local platform (It is generally known as the host platform. But this article is about the mobile platform, and in order to distinguish it from the mobile cross-development host, we have renamed it the local platform). The so-called "interface" includes two directions, one is Java code to call native functions (methods), and the other is local application calls to the Java code. Relatively speaking, the former method is used more in Android application development. So we will put our emphasis on the approach in which Java code calls native functions.
The way Java calls native functions through JNI is to have the local method stored in the form of library files. For example, on a Windows platform the files are in .dll file format, in the Unix/Linux machine the files are in .so file format. By an internal method of calling the local library file, it enables Java to establish close contact with the local machine and is called the system-level approach for various interfaces.
JNI usually has two usage scenarios: first, to be able to use legacy code (for example C/C++, Delphi, and other development tools); second, to more directly interact with the hardware for better performance. We will see some of this as we go through the article.
JNI general workflow is as follows: Java initiates calls so that the local function's side code (such as a function written in C/C++) runs. This time the object is passed over from the Java side, and run at a local function completion. After finishing running a local function, the value of the result is returned to the Java code. Here JNI is an adapter, completing mapping between the variables and functions (Java methods) between the Java language and native compiled languages (such as C/C++). We know that Java and C/C++ are very different in function prototype definitions and variable types. In order to make the two match, JNI provides a jni.h file to complete the mapping between the two. This process is shown in Figure 1.
Figure 1: JNI general workflow.
The general framework of a C/C++ function call via a JNI and Java program (especially Android application) is as follows:
- The way of compiling native is declared in the Java class (C/C++ function).
- The .java source code file containing the native method is compiled (Build project in Android).
- The
javahcommand generates an .h file, which corresponds to the native method according to the .class files.
- C/C++ methods are used to achieve the local method.
- The recommended method for this step is first to copy the function prototypes into the .h file and then modify the function prototypes and add the function body. In this process, the following points should be noted:
- The JNI function call must use the C function. If it is the C++ function, do not forget to add the extern "C" keyword;
- The format of the method name should follow the following template:
Java_pacakege_class_method, namely the
Java_packagename class name and function method name.
Use the
System.loadLibrary() or
System.load() method in the Java class to load the dynamic library generated.
These two functions are slightly different:
System.loadLibrary(): Loads the default directory (for Windows, for example, this is
\System32,
jre\bin, and so on) under the local link library;
System.load(): Depending on the local directory to add the cross-link library, you must use an absolute path.
In the first step, Java calls the native C/C++ function; the format is not the same for both C and C++. For example, for Java methods such as non-passing parameters and returning a
String class, C and C++ code for the function differ in the following ways:
C code:
Call function:(*env) -> <jni function> (env, <parameters>) Return jstring:return (*env)->NewStringUTF(env, "XXX");
C++ code:
Call function:env -> <jni function> (<parameters>) Return jstring:return env->NewStringUTF("XXX");
in which
NewStringUTF are the Java
String object's functions generated in C/C++ provided by the JNI.
Java Methods and their Corresponding Relationship with the C Function Prototype Java
Earlier we said that in the code framework for Java programs to call a C/C++ function, you can use the
javah command, and this will generate the corresponding .h file for native methods according to the .class files. The .h file is generated in accordance with certain rules, so as to make the correct Java code find the corresponding C function to execute.
For example, for the following Java code for Android:
public class HelloJni extends Activity { public void onCreate(Bundle savedInstanceState) { TextView tv.setText(stringFromJNI() ); // Use C function Code } public native String stringFromJNI(); }
For the C function
stringFromJNI() used in the fifth row, the function prototype in the .h file generated by
javah is:
JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI (JNIEnv *, jobject);
In this regard, C source code files for the definition of the function code are roughly:
/* …… Signature: ()Ljava/lang/String; */ jstring Java_com_example_hellojni_HelloJni_stringFromJNI (JNIEnv* env, jobject this ) { …… return (*env)->NewStringUTF(env, “……”); }
From the above code, we can see that the function name is quite long, but still very regular, in full accordance with the naming convention:
java_package_class_method. That is: the
stringFromJNI() method in
Hello.java corresponds to the
Java_com_example_hellojni_HelloJni_stringFromJNI() method in C/C++.
Notice the comment for
Signature: ()Ljava/lang/String;. Here the "
()" of "
()Ljava/lang/String;" indicates the function parameter is empty, which means that besides the two parameters
JNIEnv * and
jobject, there are no other parameters.
JNIEnv * and
jobject are two parameters that all JNI functions must have, respectively, for the JNI environment and corresponding Java class (or object) itself. "
Ljava/lang/String;" indicates the function's return value is a Java
String object. | http://www.drdobbs.com/architecture-and-design/android-on-x86-java-native-interface-and/240166271?cid=SBX_ddj_related_mostpopular_default_architecture_and_design&itc=SBX_ddj_related_mostpopular_default_architecture_and_design | CC-MAIN-2014-52 | refinedweb | 1,409 | 51.28 |
Geostatistical expansion in the scipy style
Project description
Info: scikit-gstat needs Python >= 3.5!
How to cite
In case you use SciKit-GStat in other software or scientific publications, please reference this module. It is published and has a DOI. It can be cited as:
Mirko Mälicke, & Helge David Schneider. (2019, November 25). Scikit-GStat 0.2.7: A scipy flavored geostatistical analysis toolbox written in Python. (Version v.0.2.7). Zenodo.
Full Documentation
The full documentation can be found at:
Description
SciKit-Gstat is a scipy-styled analysis module for geostatistics. It includes two base classes Variogram and OrdinaryKriging. Additionally, various variogram classes inheriting from Variogram are available for solving directional or space-time related tasks. The module makes use of a rich selection of semi-variance estimators and variogram model functions, while being extensible at the same time. The estimators include:
- matheron
- cressie
- dowd
- genton
- entropy
- two experimental ones: quantiles, minmax
The models include:
- sperical
- exponential
- gaussian
- cubic
- stable
- matérn
with all of them in a nugget and no-nugget variation. All the estimator are implemented using numba’s jit decorator. The usage of numba might be subject to change in future versions.
Installation
PyPI:
pip install scikit-gstat
GIT:
git clone cd scikit-gstat pip install -r requirements.txt pip install -e .
Note: It can happen that the installation of shapely, numba or numpy is failing using pip. Especially on Windows systems. Usually, a missing Dll (see eg. #31) or visual c++ redistributable is the reason. These errors are not caused by pip, scikit-gstat or the respective packages and there are a lot of issues in the shapely and numpy repo concerning these problems. Usually, the best workaround is to install especially shapely independent from scikit-gstat. As far as I know, these problems do not apply if anaconda is used like:
conda install shapely numpy
Usage
The Variogram class needs at least a list of coordiantes and values. All other attributes are set by default. You can easily set up an example by generating some random data:
import numpy as np import skgstat as skg coordinates = np.random.gamma(0.7, 2, (30,2)) values = np.random.gamma(2, 2, 30) V = skg.Variogram(coordinates=coordinates, values=values) print(V)
spherical Variogram ------------------- Estimator: matheron Range: 1.64 Sill: 5.35 Nugget: 0.00
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/scikit-gstat/ | CC-MAIN-2021-10 | refinedweb | 419 | 50.53 |
30 December 2011 03:29 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
“Both plants will be shut as we need to change their catalysts,” said the source.
Aekyung operates five fully owned PA plants at it
The PA lines that will be shut are its 20,000 tonne/year and 50,000 tonne/year lines. The 20,000 tonne/year line is internally known as “P-2”, while the 50,000 tonne/year line is internally classified as “P-5”.
The company’s three other PA lines, “P-3” with a nameplate capacity of 20,000 tonne/year, “P-7” with a nameplate capacity of 50,000 tonne/year and “P-10” with a nameplate capacity of 50,000 tonne/year will operate at 100% of capacity in Apr | http://www.icis.com/Articles/2011/12/30/9519506/s-koreaa-aekyung-to-shut-two-pa-lines-for-catalyst-change-in-april.html | CC-MAIN-2014-10 | refinedweb | 129 | 66.88 |
Hello --- I am trying to create a Flash website where the background is an FLV movie like ( or). I would also like the site to resize depending on the size of the viewers browser window (I assume there is a javascript command for this). I am using Flash CS3 with AS3.
I am a bit of newbie and have only incorporated videos into sites using the Flash prefab components. Does anyone have any idea how I might do this? Any help would be greatly appreciated. My client needs this website finished by Wednesday (oh boy!).
If you don't care about audio sync, then the solution is simple. Just import the flv into your Flash movie, size the movie to fill the stage area. The flv will just play with no on screen controls. Playing an flv with sound in the timeline will usually result in a loss of sync. It may be slight or severe.
To resize the browser window, look at the Javascript functions resize() and resizeTo().
Hi Rob -- thank you so much for your response! Will the java code that you gave me allow the website to automatically fill whatever browser window that it is viewed on? And if so (I am very unsophisticated with java) where do I type in the code? Within the HTML file or the action script?
If you import the flv into its own movieclip and place that movieclip on the main timeline, you don't need to do anything to have it loop. Movieclips loop unless you tell them not to.
You want to write a javascript function for the head section of your HTML doc. Something like this:
<SCRIPT LANGUAGE="JavaScript">
function bigMe() {
self.moveTo(0,0);
self.resizeTo(self.screen.availWidth,self.screen.availHeight);
}
</script>
and then call that function from the body tag of the HTML:
<body onLoad="bigMe()">
I have a example of what I think you want
the code:
// com is the instance name of my FLVPlayBack component.
// it is the only thing placed on stage at author time
//btnHolder is a movieclip in the library that holds the
//buttons which are also MovieClips
//initial size of the video 320 X 213 which also the
//initial size of the stage
package
{
import flash.display.*;
import flash.display.BitmapData;
import flash.display.IBitmapDrawable;
import flash.media.*;
import flash.events.*;
import jim.interactive.*;
import btnHolder;
public class WebSite extends MovieClip
{
var mesolve:Dissolve2; // Dissolve2 lives in jim.interactive
var holder:btnHolder;
public function WebSite()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
holder = new btnHolder();
addChild(holder);
var onStage:*;
onStage = com;
var ratio:Number;
var rRatio:Number;
ratio = onStage.height/onStage.width;
rRatio = onStage.width/onStage.height;
var newRatio:Number;
function fillBG(evt:Event = null):void
{
newRatio = stage.stageHeight/stage.stageWidth;
holder.x = stage.stageWidth - (holder.width +25);
holder.y = 50;
if (newRatio > ratio)
{
onStage.height = stage.stageHeight;
onStage.width = stage.stageHeight * rRatio;
}
else
{
onStage.width = stage.stageWidth;
onStage.height = stage.stageWidth * ratio;
}
}
fillBG();
stage.addEventListener(Event.RESIZE, fillBG);
// ************************* buttons ***************
this.holder.mcContact.buttonMode = true;
this.holder.mcContact.addEventListener(MouseEvent.CLICK, gotoContact);
function gotoContact(e:MouseEvent){
var canvas:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight, false, 0xffffffff);
canvas.draw(stage);
var bmp:Bitmap = new Bitmap(canvas);
addChild(bmp);
removeChild(com);
mesolve = new Dissolve2(canvas);
mesolve.addEventListener(Event.COMPLETE, nextPage);
SoundMixer.stopAll();
var contact:contactUs = new contactUs();
function nextPage(e:Event):void {
trace("nextPage");
addChildAt(contact, 0);
onStage = contact;
removeChild(bmp);
}
}
}
}
}
// ************************ buttons end ************
In the publish settings under html tab set the dimensions to percent 100 100
In the html make these css rules
body {margin: 0; padding:0; overflow: auto;}
Hi Jim --- thank you so much for your suggestion. my only question is can i still use the code for the video background if I have created buttons and text boxes on the stage? i have done a considerable amount of work already and i wouldn't really know how to code everything on the site as animated movie clips. rob -- the problem with doing it the way you suggested is that it stretches everything out to fit the browser. i am trying to keep the buttons and text a stationary size.
the buttons and text in my example don't change size but they're not stationary. The var holder in my example is what holds the buttons as you can see it is set to change position as the stage width and height change. If you gave holder a fixed x and y then it would remain stationary.
hi jim -- the way i have my site set up is that i have a container file with 6 key frames along a timeline. i have set up stationary buttons along the bottom of the stage with EventListeners attached them so that when i click on a new button it jumps to a corresponding keyframe. upon reaching the new keyframe a UILoader Component loads an external SWF file with the background video and lot of other information. to see the site in action you can go to flatbushpictures.com.
on top of the sizing issues we have already discussed, i have just realized that when a new swf file is loaded the other swf file continues playing in the background, making the site move incredibly slowly.
do you have any idea about how to deal with this, while still maintaining the previous specifications i was attempting to accomplish?
thank you so much for all of your help!
That's going to be a awsome site when you get the kinks out. The people in it seem very indecisive. Getting all the processes to die when you load a new swf is a pain AS2 seemed much better at that. You should probably start a new discussion on that.
yeah, you're telling me. i just opening another thread on this issue, but given the specifications that i have explained do you think your method would allow me to stretch the site to full screen? still having trouble with that as well...
If you mean maximized browser no problem but as for full screen that's a different animal that I have no experience with.
no, sorry. i mean maximize the browser. basically have my site interact with the web browser in the same way your site does.
About garbage collection you might find this interesting
also is useful.
yeah, that stuff is interesting. i think some of it might help me. any new ideas about the browser stuff?
If by "browser stuff" you mean issues you're having with the liquid full browser stuff then I should mention that when I was looking at your site I noticed that when I changed the width or height seperately it would take a while for your swf to react and fill in the space so you might take a good look at how I use the width to height ratios to keep everything smooth. Your site isn't online now so I cant recall if the page has a 5pixel default margin around it or if in IE theres a scrollbar on the right thest css rules fill fix those issues.
body {margin: 0; padding:0; overflow:auto} I'll upload that site so you can play with it.
I was looking for the same thing , and I found this.
There is a complete solution for video background behind the html site ( content )
It can also be integrated in a wordpress blog.
Check it out here: rsion/85688 | http://forums.adobe.com/message/2247193 | CC-MAIN-2013-48 | refinedweb | 1,248 | 72.97 |
I am trying to overload various operators for a class I am creating. In this instance, I am trying the assignment operator. I get the same error for all of them, so I will post just the assignment operator:
// header
and the implementationand the implementationCode:#include <cstdio> #include <iostream> namespace mine { template<class type> class vector { public: ... vector& operator=(const vector& other); ... }; }
I've tried various combinations of scoping on the implementation to see if it would do anything but I keep getting the:I've tried various combinations of scoping on the implementation to see if it would do anything but I keep getting the:Code:#include "vector.h" #include <cstdio> #include <iostream> template<class type> vector& vector::vector<type>::operator=(const vector& other) { if(&other != this) { ptr = new type [other.n]; for (int i = 0; i < other.n; i++) { ptr[i] = other.ptr[i]; } } }
"Expected constructor, destructor, or type conversion before '&' token" error.
I am running this on a Mac OSX Snow Leopard 10.6.2 with Xcode Version 3.2.1. Please Help! | http://cboard.cprogramming.com/cplusplus-programming/121882-overloading-operators-template-class.html | CC-MAIN-2015-18 | refinedweb | 176 | 50.12 |
Opened 6 years ago
Closed 4 years ago
#16110 closed Bug (fixed)
GeometryField does not allow setting blank=True and null=False
Description
Sometimes you want to populate a required field's missing value with a value generated eg. from other form fields.
One common idiom for doing this is to have SomeField(blank=True, null=False) and provide the missing value in eg. the Form's clean() method.
For example, I've done variations on this a lot:
class Foo(Model): geom = PointField(blank=True, null=False) address = CharField(max_length=100) class Meta: app_label = 'myblock' # or whatever, class FooForm(ModelForm): class Meta: model = Foo def clean(self): geom = self.cleaned_data.get('geom') if not geom: self.cleaned_data['geom'] = geocode(self.cleaned_data['address']) return super(FooForm, self).clean()
But with a GeometryField, that doesn't work, because of these lines in
GeometryField.clean() in django/contrib/gis/forms/fields.py :
if not value: if self.null and not self.required: # The geometry column allows NULL and is not required. return None else: raise forms.ValidationError(self.error_messages['no_geom'])
Effectively, this makes blank=True meaningless.
As far as I know, GeometryField is the only FormField shipped with django that behaves this way.
This is surprising and inconsistent, and leads to odd workarounds to convince forms.GeometryField to leave you alone. Eg. hacking a ModelAdmin's formfield_for_dbfield() like so:
def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'geom': kwargs['required'] = False kwargs['null'] = True return super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
Fixing this is trivial. Patch attached.
Attachments (2)
Change History (7)
Changed 6 years ago by
comment:1 Changed 6 years ago by
comment:2 Changed 6 years ago by
Yep, raising that on the dev list now...
comment:3 Changed 5 years ago by
Change UI/UX from NULL to False.
Changed 4 years ago by
Updated patch
comment:4 Changed 4 years ago by
Just attached an updated patch, with some other choices, but basically the same effect (hopefully). I choose a quick deprecation timeline for the null argument, because this is mostly undocumented stuff.
second attempt patch to fix 16610, with test. a typo fixed | https://code.djangoproject.com/ticket/16110 | CC-MAIN-2017-13 | refinedweb | 357 | 51.14 |
How can I delete my account here.. Thanks
How can I delete my account here.. Thanks
Hi Everyone.. How can I deselect a single radio button??
This is my code please help.. Thanks :)
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class test2...
Thanks @jsp and @syedbhai.. :)
We are required to use Awt and not Swing..
Can you tell me the particular keyword to arrange my checkbox?
Thanks :)
Can you tell me the particular keyword?
Does setBorder() is available in Checkbox class??
Hi I'm having a problem in GridBagLayout.. I want my code to be same in the image below..
2277
But my code output looks like this..
2278
And How can I set the color of box in checkbox to...
Hi everyone... Do you know any real world problem that can solve using algorithms (Brute Force to be exact).
Thanks :) | http://www.javaprogrammingforums.com/search.php?s=db2970609243516486bc47db9679e9ba&searchid=837607 | CC-MAIN-2014-15 | refinedweb | 145 | 88.53 |
Dashboards and jam-jars Helping consumers with small Defined Contribution pension pots make decisions about retirement income
- Crystal Bell
- 1 years ago
- Views:
Transcription
1 Dashboards and jam-jars Helping consumers with small Defined Contribution pension pots make decisions about retirement income Age UK discussion paper, written by Dominic Lindley, independent consultant (December 2014)
2 Dashboards and jam-jars Helping consumers with small Defined Contribution pension pots make decisions about retirement income Age UK discussion paper, written by Dominic Lindley, independent consultant, December 2014
3 Dashboards and Jam-Jars Helping consumers with small DC pension pots make decisions about retirement income Executive Summary The retirement income reforms announced in the 2014 Budget are the most significant changes to the taxation of pensions for a generation. The reforms increase the complexity of retirement income decisions for individuals. Simply will mean that most consumers will struggle to make these decisions and there may be a strong trend towards the default option, with consumers either taking what they are offered or choosing the middle of multiple options. Despite more than 10 years of effort and rewriting products. Current alternatives to annuities are not suitable for the mass market due to cost and investment risk. The. Small DC pension pots Consumers with small DC pension pots face a series of complex decisions about how to access their DC pension pots to generate a retirement income. They should: Maximise State Pensions and means-tested benefits: Maximising State Pensions is a good value way for those with small DC pension pots to gain much higher levels of secure income than through a standard annuity. Those on means-tested benefits should limit withdrawals to remain below capital limits and be aware of the impact of how they access their pension on their benefits. Gain a full picture of all pension and other assets: Before taking any decisions, consumers should gain a full picture of all of their pensions and other assets and track down any lost pension pots. Consider merging small pots: Consumers should merge small pots before buying an annuity or entering income drawdown unless they would lose valuable Guaranteed Annuity Rates or be subject to exit charges. Be aware of taxation: Cashing in their entire pension in one year could result in consumers sleepwalking into a higher rate tax charge. Spreading withdrawals over a number of years could dramatically reduce the tax they pay.
4 Consider using DC pensions to repay expensive debt: Consumers with expensive unsecured debt could use their pensions or other assets to repay it. Whether consumers should access their pension to repay mortgage debt will depend on the interest rate charged, their attitude to risk and financial circumstances. Maximise income from other financial assets: In addition to being wary of taxation on withdrawals from their DC pension, consumers should maximise use of ISA allowances and shop around for better savings account. Retirement income products: Consumers will need to decide (with or without the help of a financial adviser) whether they prefer the lower secure lifetime income from an annuity or take the risk that entering an income drawdown plan could see them having to reduce their income or run out of money. For some they may want to choose a mixture of these two options or enter income drawdown with a view to buying an annuity at a later date. Take difficult decisions about income drawdown: Consumers should try and avoid high charging income drawdown products and understand how their pension should be invested and how much they want to withdraw each year to avoid running out of money. They should think about what income they would live on if their DC pension ran out. These decisions will be difficult for them to undertake on their own. Shop around for an annuity and declare medical details to qualify for a higher rate: Consumers should always shop around for an annuity, declare any medical details so they qualify for an enhanced rate and consider the position of their partner and whether they want a level income or one which increases over time. Recommendations To help those with small DC pension pots take decisions and maximise their retirement income, the Government, pensions industry and regulators should introduce the following changes: Pensions Dashboard: Consumers should be provided with a Pensions Dashboard which should be able to gather data electronically from all their schemes. The Dashboard should display details of all of the consumer s DB and DC schemes in one place alongside their State Pension entitlement. Pensions Jam-Jars: Pension providers should develop new tools. Once consumers have made a plan, specific alerts can be used if consumers are departing from it or at risk of running out of money or triggering a higher rate tax charge. Integrate decisions about small DC pots with decisions about State Pensions: It is essential that decisions about how to access small DC pension pots are aligned and integrated with decisions about when to access State Pensions and whether to use some or all of their DC pot to buy Additional State Pension. Introduce a Second-line of defence requiring pension providers to ask specific questions at the time the pension is used to generate a retirement income: To help consumers make the best
5 decisions pension providers should be required to introduce a second line of defence, consisting of a further set of questions when consumers access their pensions. The questions would include issues around their medical circumstances, whether they had a partner, what they would live on if they exhausted their DC pension, how to avoid scams and the need to minimise taxation. Introduce strong governance requirements around retirement income processes: It is important that those responsible for specifying retirement income processes within pension schemes have strong duties to act in the best interests of pension scheme members. This should include requirements to ensure that all annuities, income drawdown and other retirement income products available through the scheme offer value for money. Review default investment options in DC pension schemes: The new flexibilities mean that many previous default investment options could be inappropriate and should be reviewed. Reasonable returns for those holding cash within their pension: The industry and Government should do more to make better cash products available within pensions. One option might be to make the new Pensioner Bonds available within pensions. Charge cap for income drawdown pensions: Understanding and comparing the total charges for an income drawdown pension is very complicated. It will be very difficult for consumers to compare the cost of different schemes, shop around and switch to better value arrangements. The extension of the charge cap to income drawdown will help prevent consumers from paying excessive charges. Clearing house for annuity purchases and mandatory medical questions: Annuities will remain an important source of retirement income for many consumers. An annuity clearing house could help maximise value and prevent consumers being defaulted into a poor product. Pension providers would need to check their own internal rates against those which were available through the clearing house. Pension providers and intermediaries should also be required to ask specific medical questions when selling an annuity and to provide enhanced annuities to those consumers eligible for higher rates due to medical or lifestyle issues. Pensions industry to work with regulators, the Government and the police to prevent scams: Pension providers employees need to be trained to spot consumers who may be vulnerable to investment scams and to provide specific warnings. Lenders to clarify how they will treat small DC pension pots when attempting to collect debts: There should be clarity about how mortgage and other lenders should treat small DC pension pots when collecting debts or starting repossession procedures.
6 Contents Dashboards and Jam-Jars Helping consumers with small DC pension pots make decisions about retirement income... 3 Executive Summary... 3 Small DC pension pots... 3 Recommendations... 4 Contents... 6 Section 1: Introduction... 8 The Budget reforms... 8 Why are those with small pots important?... 8 Behavioural factors affecting retirement income decision-making Section 2: Choices and decisions faced by consumers taking a retirement income from their small DC pension pot Types of consumers with small DC pensions pots used in the report A: Maximising State Pensions Deferring State Pensions Topping up the Basic State Pension by buying additional qualifying years Buying Additional State Pension Conclusions B: Understanding the impact on Means-tested benefits C: Gaining a full picture of multiple pension pots Tracking down lost pension pots D: Understanding whether to merge multiple small DC pension pots Using multiple small pots to buy annuities Using multiple small pots for income drawdown Conclusions E: Issues for those with Defined Benefit schemes alongside small DC pension pots Section 3: Accessing Small DC pension pots A: Taxation: Understanding the options for making withdrawals from their pension and how this would impact on the amount of tax paid The rate of taxation applied to withdrawals from DC pots Notification requirements PAYE... 32
7 Conclusions B: Accessing the DC pension fund to repay debt and using non-pension financial assets to generate income 33 Using the DC pension fund to repay debt Unsecured debt Mortgage debt Using holdings of other financial assets to generate retirement income Cash - Taking the fund as cash Peer-2-Peer lending Bonds and Bond funds / Stock market linked funds Structured products Property Alternative investments Conclusions C: Retirement income products Income drawdown Charges Investment strategy / Asset allocation Level of withdrawal The total income received by the different types of consumer and the impact on their total income when they run out of money in their DC pension Lifetime annuities Enhanced annuities Single life / Joint life annuities Hybrid products Section 4: Recommendations About the author Notes:... 55
8 Section 1: Introduction The Budget reforms The enhanced flexibilities which will be introduced in April 2015 are the most significant reforms to the pension taxation framework since the 1986 Social Security Act. The two key changes for consumers are: Flexibility in how they access their pension: From April 2015 consumers over the age of 55 will be able to access their Defined Contribution pension however they want. All limits on how consumers can access their pension will be removed. They will be able to take the entire fund as cash, buy an annuity, leave the fund invested and draw an income from it (known as income drawdown) or any combination of these approaches. Up to 25% of the pension fund will be available as a tax-free lump sum, with the remainder withdrawn incurring a tax charge payable at the consumer s marginal rate. Pensions Guidance: To support this increased flexibility the Government has announced a Guidance Guarantee which will enable all consumers with a DC pension fund to access free, impartial guidance. This service will give the consumer guidance to help them make decisions about what to do with the benefits available from their pension scheme. The guidance will be delivered to standards set by the FCA. Why are those with small pots important? While on some measures consumers are reaching retirement with higher levels of wealth the economic environment and financial markets have meant that the rate at which that wealth can be used to generate secure income has declined. Returns on savings accounts are at record lows, and falling interest rates and increased longevity have pushed down annuity rates. This makes it more important than ever that those approaching retirement are able to access suitable and efficient products and take decisions which mean that they get the best value from their retirement income. This research focuses on the implications of the reforms for those with average-sized pension pots. It examines their information needs and the decisions and conflicts they will face. The reforms increase the complexity of retirement income decisions for consumers. The changes will also transform the management of retirement income from a one-shot and irreversible decision into a situation where consumers (or their advisers) will need to review on a regular basis. On its own, identified below will mean that most consumers will struggle to make retirement income decisions and there may be a strong trend towards the default option, with consumers either taking what they are offered or choosing the middle of multiple options. Despite more than 10 years of effort and the rewriting retirement income products. The
9. There are several reasons why policymakers should carefully consider the needs of those with small pots. These include: The majority of those approaching retirement will have small pots: The Pensions Regulator found that the average pot size in a DC trust-based scheme at retirement is 25,000. i ABI figures indicate that the mean annuity purchase in 2013 was 35,600, but the median was 20,000 meaning half of all consumers bought an annuity worth less than this. ii DC pensions wealth is a larger proportion of total assets for those with low wealth: For the poorest 20%, DC pensions wealth makes up just under a fifth of their total wealth. iii For the next quintile, DC pensions wealth represents 12.9% of their total wealth. The fact that for many with low wealth, the DC pension pot is a very important part of their overall assets makes it vital for them to get the best value when taking a retirement income. Automatic enrolment: The introduction of automatic enrolment harnesses inertia to help consumers save for their retirement. When they are about to retire, the existing system relies on consumers becoming informed, engaged and taking active decisions which are difficult to make. Many older workers savings for a pension for the first time under automatic enrolment will reach retirement with small pots. People don t know that they will have to make a retirement income decision and so don t prepare for it: Research published by the ABI showed low levels of knowledge and engagement amongst those approaching retirement with a general assumption that money will somehow simply be paid back to me by my provider. iv This means that even a few years out from retirement many will not have made a decision. Research by the Pensions Policy Institute found that just 26% of those aged 55 to 64 knew how they would use their pension pot. 40% of all individuals over 40 thought that they would be best placed to make a decision about what to do with their pension a year or less before their retirement. Tailored Independent Financial Advice is likely to be less accessible and less affordable for those with small pots: High quality independent financial advice will be available from both IFAs and some specialist brokers. Those with significant pensions or other financial wealth may have an existing IFA to provide advice about retirement income. But it may be difficult to access for those with small pots. Consumers may not know how to find an IFA or how to judge the quality and value of their advice. Others may not be able to afford it or may be put off by the level of fees.
10 Lack of appropriate regulation for non-advised / execution-only services: Instead of taking advice, those consumers with small pots may rely on non-advised services. Those providing these services can still receive commission from pension product providers for selling products. Decisions are now more complex, include more options for consumers to consider and will need to be reviewed regularly: The reforms expand the number of different options available to consumers and will require more of them to make ongoing decisions postretirement about where their pension is invested and how much to withdraw each year. Relying on written information doesn t work: Improving the quality of the written information provided to consumers at the point of retirement has had little impact in making the retirement income market work better for consumers. Those with small pension pots have less choice of annuity provider and are offered worse rates: There is less competition in the market for small pots, with the result that annuity rates are particularly poor. Current alternative retirement income products to annuities do not meet the needs of the mass market: Research conducted by the Pensions Institute and published by Which? found that the alternative products to annuities do not meet the needs of the mass market due to costs and investment risk. v Vulnerability to scams: Those with small pension pots will have the ability to take all of their money out at once which could make them a target for scam artists and fraudsters. Behavioural factors affecting retirement income decision-making Retirement income decisions involve a number of factors that many would describe as difficult: longterm planning, complex and unfamiliar decision making, weighing up risk and making decision around what to do with a large pot of money. When considering how consumers might make these decisions it is important to take into account the behavioural factors affecting their decision. The following factors mean that consumers find it difficult to find the best value approach to their retirement incomevi: Inertia and procrastination Taking a retirement income requires an active decision which is often complex and requires a sequence of choices. There will be a strong preference to put off such a complex decision, which could mean that they might not be prepared for it and may need to make a quick decision. Shopping around and switching retirement income products could be perceived (and actually is) complicated and difficult, putting consumers off. This could lead to consumers taking the default option. Poor financial literacy and difficulty understanding the saliency of information consumers do not understand what is required for effective retirement planning and the complexities of annuities and income drawdown.
11 Poor grasp of life expectancies People underestimate their life expectancy (on average by about five years for men and three years for women) and also do not understand variability in life expectancy. This means people underestimate longevity risk and overestimate the risk of dying young. This could make them reluctant to purchase an annuity or more likely to take out more money in the early years of their retirement. Choice overload This applies when considered which type of annuity or retirement income product to take out, but also when looking for advice. They may not know how to access advice or how to assess its quality and value. Lack of trust Consumers may not trust their pension provider or the pension industry in general and may ignore or place low weight on information they are sent. Lack of engagement and knowledge of pensions Pensions schemes may use complex terms or jargon which can put people off engaging. Consumers may have few positive assumptions about their pension and they may be cynical that it will be worth anything. They may not understand the key terms of their pension schemes or be able to estimate how much in total they hold in their different multiple pension pots. Fear of the unknown Consumers might think that if they try to switch their pension pot to another provider then something might go wrong or the provider might collapse. They may feel that their current provider is the safer option. Illusion of control People like to feel in control of their money. Pensions may be seen as risky and subject to fluctuations due to changes in the stock market. Withdrawing all of their money from the pension and placing it in a normal cash savings account may give them a feeling of increased control. Investing in something tangible such as property that they can see may also increase their feeling of control. Buying an annuity could feel like totalling losing control of all of their money. Overconfidence People do not have realistic expectations of how much they will need to live on in retirement and over-estimate the amount of income which could be provided from a DC pension. Unwillingness to contemplate unpleasant things Issues around death are often things that people do not like thinking about or acting on. People might not want to contemplate how their partner will cope after they die. Hyperbolic discounting People value today over tomorrow, and value tomorrow over next week. This leads to a poor understanding of the distant future and a poor understanding of things like inflation. Options which lead to a higher retirement income in the first few years of retirement could be preferred such as higher level annuities, rather than those which increase with inflation. Even though consumers may say they want an income which increases with inflation, they take a different choice when actually presented with the numbers. It could also lead to people preferring single life annuities over joint-life annuities. Mental accounting People tend to see different pots of money as different and a more/less inclined to spend from them. Theory suggests that annuities help people with this, as people have an over propensity to spend lump sum payments as they are seen as available for immediate spending while annuities are seen as retirement income. Mental accounting can also cause a bias against people depleting their capital.
12 Difficulty with self-control Consumers self-control could be weaker if they are upset, stressed or don t have a specific plan. This could encourage people to take impulsive decisions about taking money out of their pension. Framing effects Consumers can be influenced by how the information is presented to them. Giving them three options could result in them choosing the middle one as this might be perceived as the safest option which most people would go for (safety in numbers). Describing things in different ways could affect the option they choose for example, saying You have a 20% chance of running out of money would lead to a different choice than saying You have an 80% chance of meeting your retirement income target. Stressing retirement income rather than depletion of a large sum is positive for people. Conversely the conversion of a seemingly large pension pot into an apparently small annuity has the opposite effect. In experiments, listing the annuity income in a table leads to more consumers choosing level annuities over index-linked than if the data is shown on a graph. Loss aversion People may be more reluctant to lose their pension savings through early death than they are to benefit from potential gains through living longer than expected. Probabilities and other rational ways of evaluating risks have little effect on this. Regret aversion People avoid potential feelings of regret, so may feel as though they got a good deal even when they didn t. Consumers may claim that they shopped around, even when they didn t do so effectively.
13 Section 2: Choices and decisions faced by consumers taking a retirement income from their small DC pension pot Consumers with small DC pension pots face a number of complex and inter-linked questions when deciding how to use their pension to generate a retirement income. These include: How do they gather information about their pension schemes and other assets to understand the total resources they have available to provide an income in retirement How do they maximise their State Pension and should they use some of their DC pension pot to help them do this? What implications do their DC pension choices for any means-tested benefits they receive? What should they do with their DB pension and how might this affect decisions about what to do with their DC pension? Do any of their DC pension schemes have valuable guarantees which they should take into account? Should they merge their multiple small DC pension pots into one place, or access them separately? How should they access their DC pension to minimise their tax bill and avoid paying tax at the higher rate? Should they use a withdrawal from their DC pension fund to pay off debt? How should they use their other non-pension assets to generate a retirement income? If they make a withdrawal from their DC pension, where should they save or invest it? What retirement income product should they buy? Do they want a secure income from an annuity of take extra risk through income drawdown in the hope of gaining a higher overall income or leaving an inheritance? Should they buy a single life or joint life annuity? Should they buy a level annuity or one which increases each year? How much should I take out of my DC pension each year and how often should I review it? How long will my pension last? How much will be left for their partner when they die? How will they and/or their partner cope if it runs out? What implication do their medical circumstances have for their choices? How can they ensure that their partner has enough income to live on after they die? In this section of the report we examine some of the options and trade-offs associated with these decisions and how different types of consumers can maximise their retirement income. Types of consumers with small DC pensions pots used in the report Throughout this report we analyse and model the decisions consumers have to make by using 5 different types of consumer with average DC pensions wealth ( 15,000-45,000). Consumer type 1 - Multiple small pots: 4 small DC pension pots of varying sizes - 3,000; 4,000; 8,000 & 14,000 totalling 29,000. Other financial assets of 15,000 cash and 15,000 investments.
14 Consumer type 2 - DC pension alongside DB pension: DC pensions wealth of 15,000 alongside DB pension of 7,000 a year. They have a minor health condition. Consumer type 3 - Renter: DC pension pot of 15,000 and 5,000 cash. Entitled to Housing Benefit / Council tax benefit. Consumer type 4 - Debt: DC pension pot of 45,000, homeowner with interest-only mortgage of 60,000 and other financial assets of 30,000. Consumer type 5 Serious Health condition: DC pension pot of 30,000, Types of consumer used in the modelling in this report: Consumer type Multiple small pots DC and DB Pensions wealth 4 DC pots - 29,000 DB - 7,000 a year DC - 15,000 Renter DC - 15,000 Debt DC - 45,000 Health condition DC - 30,000 State pension Homeowne r Financial wealth / Debt Full Yes 15,000 Cash 15,000 Investmen t funds Full Yes 12,000 - Cash Health conditions Benefits Marital status None None Married Minor health condition None Married Partial No 5,000 None Housing / Council tax benefit & Pension Credit Married Full Yes 30,000 None None Single Cash 60,000 Interestonly mortgage Full No Potentially None Married serious health condition
15 2A: Maximising State Pensions State Pensions consist of the Basic State Pension and the Additional State Pension (previously known as the SERPs or the S2P). The Basic State Pension for 2014/15 is per week for those with a full National Insurance record. Additional State Pension has undergone a variety of changes over the years but entitlement depends on earnings, the number of years in the labour market with some allowances for those out of the labour market such as people with caring responsibilities and whether the individual was contracted out through an occupational or personal pension. The current Government has committed that the Basic State Pension will be increased each year by the triple lock (the higher of prices, earnings or 2.5% a year). The Additional State Pension is increased each year in line with prices measured by the Consumer Price Index (CPI). State Pensions represent an important source of secure income for many pensioners although women continue to have lower levels of pension entitlement than men. There are 3 options for those with small pots to use State Pensions to gain additional secure income. Defer their State Pension and use some alternative form of income until they receive it For those with partial entitlement to the Basic State Pension, buy additional qualifying years by paying extra Class 3 National Insurance contributions For those who reach State Pension Age before 6 th April 2016, buy Additional State Pension by making a new form of Class 3A National Insurance contributions Deferring State Pensions Once they reach State Pension Age (currently 65 for men and 62 for women), consumers can choose when to start claiming their State Pension. If they defer then they will receive extra State Pension or a taxable lump-sum when they begin to claim it. The current rules vii surrounding the deferral of State Pensions are: A consumer can defer their State Pension at any point even if they have already started claiming it. The whole of the State Pension and any additional payments (such as the Additional State Pension) on top must be deferred consumers cannot defer only part of their State Pension. By deferring their State Pension the consumer will receive extra money when they start to receive their pension. They can claim this in one of two ways: o Taking a higher weekly State Pension for life: Under the current rules the consumer would receive an extra 1% in weekly State Pension for each 5 weeks of deferral, which amounts to 10.4% for each year (this will reduce to 5.8% for each year for those who reach State Pension age after April 2016). o Receiving a lump sum: If the consumer defers their State Pension for at least a year then they can receive a one-off, taxable lump-sum. This is based upon the amount of State Pension they would have received if it had not been deferred and interest at about 2% above the Bank of England Base Rate. This option will only be available to those who retire before April The amount of extra State Pension is applied to all of the consumer s State Pension payments which have been deferred, including Basic State Pension, S2P and some other additions
16 When the consumer dies part of the extra weekly State Pension or the entire lump-sum payment can be inherited by their spouse or civil partner Table 1: Extra amounts which could be gained by deferring a full Basic State Pension assuming current rate of 10.4% increase for each year of deferral Weekly State Pension Number of Years Total amount deferred Lump-sum Payment Extra Weekly State Extra Yearly State Pension Deferred Pension ,896 5, ,793 12, , ,690 18, , ,587 24, , ,484 31, ,066 One option for those with small pension pots is to defer their State Pension and rely on other sources of income before claiming it at a later date. By doing this they could benefit from a higher rate of secure income or a lump-sum payment once they begin to draw their State Pension. Other sources of income could include continuing to work where once they reach State Pension age they will no longer pay National Insurance contributions and would therefore see a small increase in take-home pay. However, continuing to work is likely to only be an option for a minority of individuals and, despite recent improvements, just 10.1% of those aged over 65 are employed. viii Therefore many with small pots would have to either rely on other financial assets during this time or use the new flexibilities to make regular withdrawals from their pension fund. Consumers using their DC pension to replace the income from the State Pension during this deferral period would have to erode the capital in their fund an annuity would pay far too little. To replace the income received from a Basic State Pension a consumer would need to withdraw a total of 5,897 annually from their pension. For a consumer with a 29,000 pension pot this would erode their pension pot within 5 years. When they began to draw their State Pension they would then benefit from an extra 3,066 a year, which would increase in line with CPI. By comparison if they had used their pension fund immediately to buy an annuity then this would have produced an annual income of around 1,600 a year from a level annuity or 900 from an RPI index-linked annuity. This means that compared with the cost of buying an annuity they have gained around 2-3 times as much secure income. Alternatively they could opt for a lump sum payment of 31,400. They may want to take a lump sum if they had become seriously ill since deferring their State Pension. Topping up the Basic State Pension by buying additional qualifying years Eligibility for the Basic State Pension depends on the number of years in which a consumer has paid National Insurance contributions. A consumer retiring between 2010 and 5th April 2016 needs 30 years of National Insurance contributions or eligible credits for the basic State Pension. After 5th April 2016 a consumer will need 35 qualifying years to qualify for the new single tier State Pension. Consumers with fewer than the required number of qualifying years will receive a partial State Pension. To boost their number of qualifying years some consumers will be able to make voluntary National Insurance contributions. Normally consumers can only pay for gaps in their National Insurance records
17 in the current year and the previous six years. However, those who reach State Pension age between April 2010 and April 2015 and already have 20 qualifying years are eligible to pay up to six years covering years going back to In 2014/15 the cost of buying extra years is for each year purchased. For each year purchased, their Basic State Pension will increase by 3.77 a week or 196 a year.ix This means that it will take just over 3.5 years for a consumer to receive their capital back and continue to benefit from a higher rate of secure income through the Basic State Pension. Even if the consumer has to pay tax to withdraw money from their pension fund to buy the extra years then the return available is more than 7 times that available from an index-linked annuity. However, those on Pension Credit or other means-tested benefits might see the increase to the State Pension offset, either totally or partly, by reductions in these other benefits. Buying Additional State Pension The Government will also be introducing a further scheme for those who reach State Pension Age before 6 th April This will be known as Class 3A voluntary contributions. This will enable consumers to top-up their State Pension by between 1 and 25 a week, with the cost depending on how much extra pension they want and how old they are when they make the contribution. As currently proposed the scheme will only operate between October 2015 and April The Government expects most people who want to take up the additional entitlements under the scheme to do so in the first few months of its operation. Pricing of the scheme will be on an actuarially fair basis based on estimates of life expectancy provided by the ONS. The Government has indicated that the following types of people will gain from the schemex: Couples where only one pays tax, with women who have an average state pension of 109 a year highlighted as potential beneficiaries Self-employed people who generally have lower levels of State Pension but are approaching retirement with higher levels of assets People approaching retirement with Defined Contribution pensions who may want to supplement their income from annuities or income drawdown Older pensioners who may welcome a simple offer from the State to increase their income The Additional State Pension will increase in line with prices as measured through the Consumer Price Index (CPI), rather than by the triple lock. On death, at least 50% of the additional state pension is inheritable by the consumer s spouse. Additional State Pension can be deferred using the process described in the previous section.
18 Table 2: Cost of Paying Additional Class 3A NI Contributions by Age Compared to Cost of Buying Index-Linked Annuity Age Cost of buying 1 a week additional income Cost of buying the maximum 25 a week Cost of buying equivalent single life RPIlinked Annuity Cost of buying equivalent joint-life RPIlinked Annuity ,250 38,000 42, ,675 33,000 36, ,475 29,500 34, ,850 22,500 26,000 RPI-Linked Annuity, Living in SE13, Joint-life both aged 65 or single life aged 65, annuity increasing by RPI, Rate available on Money Advice Service Comparison Table - Accessed 24th November The table shows that the current cost of paying additional Class 3A NI contributions to gain additional State Pension income is considerably cheaper than buying either a single-life or joint-life index-linked annuity. This is true even when adjusting for the fact that the additional state pension is uprated with CPI instead of RPI. There is one additional complication which is that Class 3A NI contributions can only be paid in cash a consumer cannot use their tax advantaged pension saving to purchase additional state pension. This means that to use their pension saving in this way consumers can use the new flexibilities to make a withdrawal from their pension and incur a tax charge on at least 75% of this amount. So, if consumer type 1 decides that they want to secure an index-linked income from 12,500 of their pension fund then they can either purchase an index-linked annuity within their pension or withdraw the money from their pension fund incurring a tax charge of 1,875 and purchase additional state pension with the balance of 10,625. The first chart below shows that the amount of an index-linked annuity, compared to the amount which could be purchased through the additional state pension. However, the vast majority of annuities purchased are level annuities which do not increase over time. The second chart shows that the amount which can be purchased through the additional state pension will, after 3 years, surpass the return available from a level annuity.
19 Chart 1: Annual income from withdrawing a 12,500 pension fund and using it to purchase Additional State Pension versus using it to buy RPI index-linked annuity Annual Income: Additional State Pension vs RPI- Linked Annuity - 12,500 pension fund Additional State Pension Company 1 Company 2 Company 3 Company 4 Company 5 Company 6 Index-Linked Annuity, Living in SE13, Joint-life annuity increasing by RPI, Both aged 65 Rate availables on Money Advice Service Comparison Table - Accessed 24th November Chart 2: Comparison between purchasing Additional State Pension and an Annuity Joint-life annuity, Living in SE13, RPI linked annuity is assumed to increase at 2.75% per year and Additional State Pension is assumed to increase at 2% a year, Both aged 65 Best rate available on Money Advice Service Comparison Table - Accessed 24th November Conclusions Under the current framework, deferring their State Pension or buying Additional State Pension or extra qualifying years to enhance their Basic State Pension are good value ways for those with small pension pots to secure higher levels of secure lifetime inflation-linked income for themselves and their spouses. Maximising State Pension benefits in these ways may be particularly helpful for consumers: In good health
20 With spouses/partners, as long as the inheritable Additional State Pension would not take their partner above the maximum amount With small pension pots where annuity rates are particularly poor Women who retire earlier and therefore would be offered poorer annuity rates It is likely to be less beneficial or not beneficial at all for consumers: In poor health Receiving means-tested benefits such as Pension Credit However the following caveats should be considered: Communications challenges: There are currently no requirements for the option to defer the State Pension or purchase Additional State Pension to be highlighted in wake-up packs and communication documents sent by occupational or personal pensions. Promoting it as 1 a week for an additional payment of 890 may suffer from the same problem as an annuity in that it sounds a very low payment in return for the lump sum. Unexpected expenses: Eroding all of their DC pension fund and other assets might leave those consumers less able to cope with an unexpected expense in retirement. However, if a consumer who had deferred their State Pension was faced with an unexpected bill then they could take a lump-sum instead of an increase in their weekly State Pension. Future changes will reduce the attractiveness of these options or eliminate them: The reduction in the benefit from deferring the State Pension from 10.4% to 5.8% a year and removing the ability to take a lump sum will reduce though not remove the attractiveness of this option. The Government s intention is that the ability to make Class 3A NI contributions will only be available to those reaching State Pension age before 6 th April 2016 and that they will have to done so by April Political risk: Whilst at the moment the major political parties are committed to increasing the State Pension each year this may change in the future as it did when the uprating of the Additional State Pension was changed from RPI to CPI.
21 2B: Understanding the impact on means-tested benefits The three main types of means-tested benefits available for those older than State Pension age are: Pension Credit: The Guarantee Credit tops up a consumer s income to a week for individuals and the Savings Credit which can provide a further payment for those with an income of between and 190 a week. Housing Benefit: Renters can receive Housing Benefit with the eligibility and amount received depending on their weekly income and rent. Council Tax Reduction: Those on a low income or claiming benefits can get a reduction on their Council Tax bill. What a consumer receives can depend on their circumstances and where they live as each council runs its own scheme. Income received from the DC pensions will reduce eligibility for means-tested benefits. The Government has announced that this will be the greater of the actual income taken or 100% of the income which could be bought by a conventional annuity. xi The consumer type 3 renter - currently has 15,000 in a DC pension. This means that in calculating their entitlement to means-tested benefits this would be assumed to generate an income of around a week ( 774 a year). They would be assumed to receive this income even if they did not make any withdrawals from their pension scheme. If they were to withdraw more than this amount then the additional income would further reduce their entitlement to means-tested benefits. Also relevant for those with small pension pots receiving these benefits will be the capital limits which apply. Capital which counts towards the limits include savings in bank accounts, investments, and property. However, it excludes holdings in occupational and personal pensions. Claimants with capital above the minimum limit will start to see a reduction in their benefits. Those which exceed the maximum limit will no longer be entitled to any of that particular type benefit. The amount of tariff income is the amount of income which it is assumed that capital above the minimum limit delivers and it is used when estimating entitlement to benefits. These are shown in the table below:
22 Table 3: Capital limits for means-tested benefits Benefit Minimum Capital Maximum Capital Tariff income Limit Limit Pension Credit 10,000 No maximum 1 a week for every 500 of eligible capital Housing Benefit 6,000 for those below Pension Credit age 10,000 for those above Pension Credit age 16,000 unless eligible for the Pension Credit Guarantee Credit in which case no maximum is applied 1 a week for every 500 of eligible capital for those above Pension Credit age 1 a week for every 250 of eligible capital for those below Pension Council Tax Reduction Depends on the Council but can be between 6,000 and 10,000 and vary between those below and above Pension Credit age Depends on the Council and age but can be between 6,000 and 16,000. Credit age 1 a week for every 500 of eligible capital for those above certain ages 1 a week for every 250 of eligible capital for those below certain ages The consumer type 3 renter currently has 5,000 held in cash savings accounts. This amount is below the minimum capital limit for all 3 types of means-tested benefits and therefore does not affect their entitlements. If they were to withdraw their entire 15,000 DC pension fund then after tax they would receive 13,850 in cash. Adding this to their existing savings would give them a total of 18,850. This means they would lose entitlement to Housing Benefit and Council Tax reduction. They would also lose some entitlement to Pension Credit as the 8,850 in capital would be assumed to generate them 930 a year in income. Those consumers who receive means-tested benefits will need to consider how the way in which they flexibly access their pension will affect their entitlement to these benefits. There will be a greater impact on those who access their pension before State Pension Age as the capital limits are lower.
23 2C: Gaining a full picture of multiple pension pots The first stage for any consumer approaching retirement will be to gain a comprehensive picture of their pension entitlements. This would need to include their State Pension and any public and private sector Defined Benefit and Defined Contribution schemes. As a starting point, when they reach their retirement, they would need to know the following information for each of their pension schemes. State Pension: The amount of income they would receive from the State after their State Pension age. Defined Benefit / Hybrid schemes: The amount of income payable from the scheme and the retirement age from which it becomes payable. They would also need to know whether the pension would increase post retirement and if it would provide an income for their spouse/partner. Defined Contribution schemes: The value of the accumulated savings in the scheme, what assets it is invested in and the amount of income this might generate when they retire. This information will be more complicated to obtain for those with multiple pension pots. At present there is no easy way for an individual to view their total aggregate amount of their DB and DC pensions in one place or to see this alongside their State Pension entitlement. State Pension forecasts and statements can be requested from the Pension Service and are now available online although the statement cannot be saved, only printed out. To gather information for their DC and DB pensions they would need to consult their annual statements or terms and conditions of the pension. If they were within 6 months of their scheduled retirement date then they should have received a wake up pack which would contain this information. They would then need to add these numbers together to determine their total retirement savings. It was estimated that between a quarter and two-fifths of DC pension holders have multiple pension pots. xii These numbers are likely to have increased following the introduction of automatic enrolment, which will result in more consumers possessing a separate pension for each of their jobs. Whilst the Government is scheduled to introduce a mechanism for automatic transfers of small pension pots in the next Parliament, this will only apply to new small pots and exclude those with a value of more than 10,000. Tracking down lost pension pots Consumers may have lost touch with their pension savings or not kept address details up to date. Both occupational and personal pensions are supposed to make some effort to trace individuals for whom they no longer hold up to date contact details. The Pension tracing service is free and enables consumers to track down their pension schemes by entering any information they have about their employer or pension provider. Following a successful trace, the consumer would need to contact the scheme provider to find out what the scheme is worth.
24 Communications between pension providers and customers regarding retirement options Between two and five years prior to their selected retirement date, a pension provider must communicate with a customer on an individual basis at least once to: Encourage the customer to start considering their retirement options Introduce the customer to the decisions they will need to make This can be done through the annual pension statement, or alternatively through a separate customer communication. If a provider has not already been approached by a customer about their retirement options, the provider must also: send out a wake-up pack at least 6 months pre-selected Retirement Date for trust-based occupational schemes and at least 4 months pre-selected Retirement Date for contractbased schemes send out a follow-up pack at least 10 weeks pre-selected Retirement Date for trust-based occupational schemes and at least 6 weeks pre-selected Retirement Date for contractbased schemes
25 2D: Understanding whether to merge multiple small DC pension pots Once they have received details of their pensions, then those consumers with multiple small DC pots will need to make a decision as to whether they convert each of the individual pots into a retirement income or whether they merge them together in one place. To take this decision consumers will need the following information: Exit charges and Market Value Reductions: The application of these charges could reduce the benefits from the scheme if the consumer transfers out, makes a withdrawal or cashes-in their pension. Explicit exit charges may be levied in the form of an explicit charge for leaving the scheme before a certain number of years have elapsed or before the stated maturity date. These exit charges are not normally present in schemes set up after 2001 and are prohibited for Stakeholder schemes. In 2013, the FSA said that it did not hold data on the prevalence or level of exit penalties within pension schemes. xiii A Market Value Reduction is a deduction which can be applied to pensions held in withprofits funds when the consumer transfers out of their pension, makes a withdrawal or cashes it in. These are expressed in percentage terms for example a 10% MVR would mean a reduction in 10% in the value of the consumer s pension policy. The amount of an MVR is not fixed the insurance company can change it and will levy the MVR which applies when the consumer cashes-in their pension or transfers out. Exit charges / MVR-free windows: There may be certain times when exit charges or MVRs will not apply. For example, an exit charge/mvr might not apply if the consumer holds the pension until their stated retirement date when they joined the scheme. However, some with-profits funds only offer MVR-free windows for a period before and after the selected retirement date. If the consumer does not transfer out during that window then they can be subject to MVRs in the future when they transfer, cash-in or take a withdrawal from their pension. Guaranteed Annuity Rates, Guaranteed Annuity Option and any other Guarantees: A Guaranteed Annuity Rate (GAR) provides a guarantee that the pension provider will use a particular minimum rate at which the consumer can use their pension saving to purchase an annuity with that provider. For example a GAR of 10% would mean that if the final value of the pension at retirement was 100,000 then the consumer could use it to purchase an annuity paying 10,000 a year. Guaranteed Annuity Rates can be very valuable as they are normally far above that which can currently be achieved by a healthy individual in the current market. Information about charges and asset allocation: Consumers would need to understand whether they would incur any extra administration charges by merging pots. To decide which scheme to use they would have to have some way of understanding and comparing the different charges and where the schemes were invested. Using multiple small pots to buy annuities Buying individual annuities across a number of small pots could also increase complexity and reduce the amount of income received by the consumer. Smaller pots receive lower annuity rates due to increased administration costs and lower levels of competition for small pots as few companies will compete on the open market for annuities below 10,000. The chart below shows the annuity rate offered by one major provider by pot size annuity rates are lower for those consumers with pension
26 pots of less than 20,000 and take a further significant lurch downwards for those with less than 10,000. If the consumer type 1 with multiple pots fails to combine their different pension pots before buying an annuity then they could lose out on valuable secure income. Buying separate single life annuities with their small pots of 3,000, 4,000, 8,000 and 14,000 would pay them an income of just over 1,500 a year. Combining these into one big 29,000 pension pot could give them around 1,700 a year. Chart 3: Annuity rate by pot size Single Life Annuity, Purchased at age 65 in good health, lives in SE13 Using multiple small pots for income drawdown To manage and review a drawdown programme across multiple small pots increases complexity as the consumer will have to know the amounts remaining and investment allocation across the multiple pension pots. Managing multiple small pots could also incur greater charges if there are initial or annual fees for entering income drawdown or administration fees for changing the amounts of regular withdrawals or taking ad-hoc withdrawals. It could also increase the cost of receiving advice. Conclusions Consumers with exit charges should try and avoid accessing their scheme before retirement but should consider taking advantage of any penalty free window. Schemes with GARs are likely to be a good option for those consumers who want to use their pension to gain a secure income. However, some of the GARs may come with restrictions such as not providing an income for a consumer s partner. If there are no schemes with GARs then consumers should always aggregate their schemes when buying an annuity. Consumers should also consider merging schemes before entering income drawdown, but whether to do this and which pension scheme to use is a complicated decision for which most consumers will require financial advice.
27 2E: Issues for those with DB schemes alongside small DC pension pots Defined Benefit (DB) schemes can provide consumers with a good source of secure income in retirement. 43% of individuals aged and 30% of individuals aged have some form of DB pension which they have not yet received a payment from. xiv In addition to offering a greater level of certainty to consumers regarding the amount of their final pension, 97% of DB schemes also provide an income for the surviving spouse and 74% increase benefits in line with inflation. Issues arising for those with DB schemes include: Lump sum or secure income: DB schemes typically offer the ability for consumers to transform or commute part of their annual income into a tax-free lump sum. Ability to transfer out: The Government decided to continue to allow transfers from private sector and funded public sector DB schemes into DC schemes. Two new safeguards will be introduced requiring consumers to take independent financial advice and new guidance for trustees to delay transfer payments and take account of funding levels when deciding on the transfer value. In a thematic review of advice concerning whether to transfer out of DB schemes the FCA found that even when advice was provided by the employer this was process driven, creating a risk that not all the consumers circumstances were considered in all cases. If consumers want to transfer out then they need to do so before they reach the retirement age for the scheme. Those receiving a pension from a DB scheme are normally banned from transferring out. Consumer type 2 - Defined Benefit - has a DB pension of 7,000 a year alongside a DC pension of 15,000. He is a smoker with raised cholesterol and would therefore qualify for an enhanced annuity paying 10% more than the standard rate. Their DB scheme has a commutation factor of 18:1 and a transfer value of 140,000. They would face the following decisions: Whether to give up DB pension to generate a lump-sum: By giving up 1,000 of annual income the consumer would receive a lump-sum of 18,000. However, even accounting for the fact that he would qualify for a higher annuity rate due to his health it would cost at least 30,000 to replace the 1,000 of index-linked income. Those with DB schemes and with needs for lump-sums may be better off using the new flexibilities to withdraw it from their DC scheme. Whether to transfer out: The transfer value of 140,000 is equivalent to an annual income from an index-linked annuity of 4,600 a year so would be a significant decrease to the annual income available in the DB scheme. Moving into drawdown would result in a significant increase in investment risk and the risk of running out of money. Transferring out of DB schemes is only likely to be suitable for a small minority of consumers such as those with a serious health condition. Under the new framework if the consumer died before the age of 75 any payment from a drawdown pension or jointlife annuity to their partner would be tax-free. However, this example illustrates that even for those with relatively modest DB pensions, the transfer value is likely to vastly exceed the amount in their DC scheme. This may prove tempting to some consumers even with the requirement to take Independent Financial Advice. It is notable that in the FCA s recent thematic review xv, 59% of transfers were undertaken at the insistence of the member after the adviser had given them a recommendation to stay in the DB scheme. Employers seeking to reduce their deficits in final salary schemes may also encourage consumers to transfer out of DB schemes by offering some enhancement to transfer values.
28 Section 3: Accessing Small DC pension pots 3A: Taxation: Understanding the options for making withdrawals from their pension and how this would impact on the amount of tax paid Under the new framework consumers with small pots will have four main ways of accessing their pension with different implications for taxation. These options are: Small Lump Sum (SLS): This is available for small pots of less than 10,000 with 25% of the fund being paid tax-free and 75% being taxed at the marginal rate. In a SLS the entire pension fund is paid to the individual in one go. Taking a SLS does not trigger a reduction in the consumer s Annual Allowance for money purchase pensions to 10,000. Uncrystallised Funds Pension Lump Sum (UFPLUS): This is available for any size of fund and is a withdrawal in the form of a lump sum with 25% being paid tax-free and 75% being taxed at the marginal rate. A consumer can take multiple UFPLUSs from their fund and spread them over months or years. Taking an UFPLUS reduces the consumer s Annual Allowance for money purchase pensions to 10,000 Flexi Access Drawdown (FAD): This is available for any size of fund. The consumer takes 25% of the fund immediately as a tax-free lump sum. The remainder is placed into Flexi Access Drawdown with any withdrawals through FAD being taxed at the marginal rate. Entering FAD reduces the consumer s Annual Allowance for money purchase pensions to 10,000. Tax-free lump sum and annuity: This is available for any size of fund. The consumer can take up to 25% of the fund immediately as a tax-free lump sum and use the remainder to buy an annuity or other retirement income product. Taking a Pension Commencement Lump-Sum (PCLS) and buying an annuity reduces the consumer s Annual Allowance for money purchase pensions to 10,000. The income from the annuity will be taxed at the consumer s marginal rate. Many of the consumers with small pots who use the new rules to access their pension post retirement might be unlikely to be negatively affected by the reduced Annual Allowance. Those continuing to work will still be entitled to employer contributions into their workplace pensions and be allowed to make their own contributions to workplace or personal pensions. These would be unlikely to exceed 10,000 a year. However, those below State Pension age or those who know that they might want to make a lump-sum contribution into a pension perhaps from an inheritance will need to be aware of the potential impact before they decide how to access their pension. If they have multiple pension pots then the best option for them would be to take one or more of those as Small Lump Sums. For those consumers who need to withdraw larger amounts there are some differences between the two ways they can access their pots flexibly, the UFPLUS and the FAD. Whether those with small pots are better off using the UFPLUS or FAD will depend on the following factors: FAD is more suitable for those consumers who have an immediate need for larger amounts of cash in the first year of their retirement and/or those who may have unused portions of their
29 personal allowance to use in the latter years of their retirement. In particular, using FAD allows those on moderate incomes to maximise the withdrawals from their pension and avoid paying higher rate tax. UFPLUSs are more suitable for those who have no immediate need for large amounts of cash in the first year of their retirement and/or those who know that their income will exceed the annual allowance in each year of their retirement. By delaying the utilisation of the tax-free element of the withdrawal consumers could gain if the size of their pension fund continues to grow post-retirement. The rate of taxation applied to withdrawals from DC pots With the exception of the tax-free element, the money withdrawn from pensions will be taxed at a consumer s marginal income tax rate. To determine the marginal rate it is necessary to add up all of the consumer s income from other sources including employment, profits from self-employment, State Pensions, savings, property and investments. Adding the amount of taxable withdrawal from their DC pension to this amount and applying the marginal rate from the table below will give the total tax paid by the consumer. Table 4: Marginal Rates of Income Tax Amount of income Tax-rate 0-10,500 0% 10,500-42,385 20% 42, ,000 40% Above 150,000 45% The key objective for those consumers with small pots who want to drawdown their pensions as quickly as possible will be to minimise the amount of the withdrawals which are taxed at the 40% marginal rate. Making some assumptions about the income from employment and savings the table below shows the maximum amount the consumer type 1 with multiple small pots totalling 29,000 could withdraw from their pension in the year they retire before they move into the higher rate tax band. To minimise their tax liability it is important that the consumer does not withdrawal more than these amounts. If the entire 29,000 was withdrawn immediately then given the amount of other taxable income the consumer has in the 2015/16 tax year 6,800 of the withdrawal would be taxed at the higher marginal rate of 40%. This is because the consumer has taxable income of 27,402 in 2015/16 and so can only withdraw 14,983 ( 42,385-27,402) in a taxable withdrawal from their pension before they begin to pay tax at the higher marginal rate of 40%. This would lead to a total tax payment on the withdrawal of the pension of 5,700 (40%* 6, %* 14,983).
30 Table 5: Taxable income and amounts consumer with multiple small pots can withdraw from their pension in the first tax year of their retirement before paying higher rate tax Consumer type 1 Year 1 (2015/16) Total taxable income 27,402 Total taxable withdrawal before being 14,983 taxed at the higher rate ( 42,385-27,402) Maximum UFPLUS which can be made before the consumer would begin to pay higher rate tax Maximum tax-free lump sum + withdrawal under FAD which could be made before the consumer would begin to pay higher rate tax 19,978 (75% - 14,983 would be taxed) 22,233 (Consisting of tax-free lump-sum of 7,250 and taxable withdrawal of 14,983) Assumptions: Consumer retires at end of December 2015 having worked up until their retirement and then immediately claims the State Pension. Makes the withdrawal through the UFPLUS or FAD in the 2015/16 tax year Table 6: Taxable income and total tax paid on pension withdrawal by multiple small pots consumer if withdrawals are spread over 5 years Consumer type 1 Year 1 (2015/16) Year 2 (2016/17) Year 3 (2017/18) Year 4 (2018/19) Year 5 (2019/20) Total taxable income 27,402 7,798 7,723 7,955 8,194 from savings/investments & State Pension Total tax-free 0 3,227 3,853 4,200 4,569 regular withdrawal Tax-free lump sum 7,250 Total withdrawal 7,250 5,438 5,438 5,438 5,438 Total taxable pension withdrawal 0 2,211 ( 5,438-1,585 ( 5,438-1,238 ( 5, ( 5,438 - Total amount of tax paid After tax income from pension 3,227) (20% * 2,211) 3,853) 317 (20% * 1,585) 4,200) 247 (20% * 1,238) 4,569) 173 (20% * 869) 7,250 4,996 5,121 5,190 5,264 Assumptions: Consumer retires at end of December 2015 having worked up until their retirement and then immediately claims the State Pension and gradually moved their cash savings and investments into ISAs. Annual Allowance is 10,500 in 2015/16 and then increases at 5% per year. Consumer takes tax-free lump sum in 2015/16 and places the rest in Flexi-Access Drawdown and makes 4 further withdrawals of 5,438 each tax year.
31 Chart 4: Amount of tax paid by multiple small pots consumer if pension withdrawn over 1 year, 2 years or 5 years Notification requirements When a consumer has flexibly accessed their pension saving the administrator of the pension scheme must send them a flexible access notification. This must include the following information: That the member has flexibly accessed their pension savings and the date of the relevant event If the member's total pension inputs into money purchase arrangements and certain hybrid arrangements is more than 10,000 for a tax year, o they will be liable to an annual allowance charge on the excess over 10,000, and o their annual allowance for pension inputs under other types of arrangements will be reduced by 10,000. Following the receipt of the notification: the member must within 91 days, beginning with the day of receipt of the notice from the scheme administrator tell the scheme administrator of any other scheme that they are an active member of (or for any new scheme they join when they join the scheme) that they have flexiblyaccessed their pension rights and the date of that they did so; If a consumer fails to notify other schemes within 91 days of receiving the notice then they can be liable for a penalty of 300. xvi These notification requirements will affect those consumers with small pots who continue to work into retirement after having accessed their pension flexibly through an UFPLUS or FAD. It is likely that many who continue to work will be paying into their current workplace pension as they will have been automatically enrolled before reaching State Pension Age. There will need to be clear information provided to those with small pots as to how they should find the details of their current scheme. Given that many with small pots are unlikely to exceed the 10,000 Annual Allowance placing the notification requirement on the consumer and penalising them if they fail to comply seems unnecessarily harsh.
32 PAYE Pay-As-You-Earn (PAYE) is the HMRC system through which those making pension payments to individuals, both employers making occupational pension payments and registered pension providers, should deduct income tax and send it to HMRC. Those accessing a pension fund will need to supply a tax-code to their pension scheme. If they do not then on the initial withdrawal they may be taxed under an emergency code. An emergency code will normally mean that the consumer does not receive any benefit from their annual allowance, meaning that at least basic rate tax will be deducted, and the payment will be taxed as though it is a monthly payment. This could result in them paying tax at the 40% rate. To prevent this occurring consumers will need to supply their pension scheme with their P45 or their tax code. xvii If only one payment is made from a scheme during a tax year then as part of the end of tax year reconciliation under PAYE, HMRC will determine whether the consumer has paid too much tax and if so, refund them. Where more than one payment is made then provided that the member has given their tax code to their pension scheme an adjustment can be made during the year. Given that some with small pension pots may have unused personal allowances due to being on a low income it will be particularly important for them to supply their pension provider with their tax code to avoid excessive tax deductions being made. Conclusions There is a risk of consumers with small pots paying excessive amounts of tax when they make a withdrawal from their DC pension. By not minimising their tax liability they are reducing their potential retirement income. Consumers should be encouraged to spread their withdrawals over a number of years and to take the maximum tax-free lump sum. To ensure right amount of tax is deducted it is important that consumers are provided with accurate tax codes and are able to communicate these to their pension schemes.
33 3B: Accessing the DC pension fund to repay debt and using non-pension financial assets to generate income Consumers ability to generate a retirement income will be influenced by the amount of debt and other financial assets they possess. 9 out of 10 retired people have other sources of income in addition to their annuity and State Pension, including savings, investments, earnings from employment or rental income from a property. xviii Decisions about what to do with their DC small pot should factor in consideration of the amount and investment strategy of their other assets. Consumers will also need to make decisions about which product and which provider to save or invest any tax-free lump sum they withdraw from their pension. Others may use the new flexibilities to withdraw more money than they need from their pension pot for their day-to-day spending. They will then need to decide where to save or invest this surplus income. Using the DC pension fund to repay debt Research from Prudential found that 1 in 6 of those planning to retire in 2014 will have debts. The main sources of debts are credit cards (56% of those with debt) and mortgages (44%), followed by overdrafts (19%) and bank loans (14%). xix Age UK has found that whilst the proportion of older people with debt had fallen between 2002 and 2010, the average size of the debt had increased. xx There are also concerns that lenders may be unwilling to lend to older people and in particular to extend mortgage terms so that they are repayable after retirement. xxi This could mean that more consumers have to repay debt when they reach State Pension age. Those consumers with unsustainable levels of debt will need to be referred to independent debt advice agencies. The pension flexibilities raise interesting questions about how lenders will treat an uncrystallised DC pension pot when negotiating with consumers. For example, under the old regime there would be no way for most consumers to use more than 25% of their DC fund to repay their mortgage. This might have made the lender more likely to compromise by agreeing an extension to the mortgage term and/or a lower monthly payment. Under the new flexibilities, the lender could demand that the consumer withdraws money from their pension to repay the mortgage or sell the house. Similar issues might arise if a consumer falls into mortgage arrears after the age of 55. There are questions about whether the lender would insist that the consumer accesses their pension to avoid repossession. Factors which will determine whether consumers should make withdrawals from their pension fund to repay debt will be: Overall level and type of debt Interest rates charged and whether they can be reduced by refinancing debt When the debt is due for repayment and whether there are any Early Repayment Charges Whether there are any alternative repayment strategies/vehicles in place Attitude to risk Access to emergency fund Whether the consumer might have to incur significant expenditure during their retirement in the near future
34 Unsecured debt Unsecured debt includes overdrafts, credit cards and personal loans. Interest on these types of loans range from 5% for large personal loans to 19.67% for overdrafts. The returns from the pension are not likely to exceed that which could be gained from paying off the higher cost unsecured debt such as credit cards, overdrafts and personal loans. This means that consumers overall could benefit from accessing their pension flexibly to repay this debt. However, they should only consider doing this if they do not have any alternative means of repaying the debt such as sufficient cash in savings accounts or other income. If the debts are manageable and could be cleared in a relatively short timescale then the consumer could consider refinancing them by using a special offer such as a 0% balance transfer deal and clearing them over the life of the deal. If consumers do need to access their pension to clear unsecured debts then they should do it in the most tax efficient way possible, utilising their tax-free personal allowance wherever possible and ensuring that they never pay tax at a marginal rate of 40%. Table 7: Average interest rates on unsecured debt Type of debt Average Interest Rate Credit Card 17.47% Overdraft 19.67% Personal Loan ( 5,000) 8.57% Personal Loan ( 10,000) 5.00% Mortgage debt Whilst fewer consumers will have mortgage debt at retirement, the absolute size of these debts is likely to be much greater. Many of those with a need to repay a mortgage post retirement will have an interest-only mortgage. FCA modelling predicts that just under half of interest-only mortgage holders whose loans mature before 2020 will have a shortfall between their mortgage and their expected repayment vehicle. In the near-term there is a peak of mortgages maturing in 2017/18 many of which will be those who were sold an endowment mortgage in the early 1990s. Some of these shortfalls could be significant the FCA estimates that a third of those with a shortfall whose loan matures in 2020 will have a shortfall greater than 50,000. xxii Whether a consumer would be better off using their DC pension pot to repay their mortgage will depend on their financial circumstances and attitude to risk. If they are paying a high interest rate on their mortgage which could exceed the return they could gain on their pension and they are risk averse then they using the DC pension to repay the mortgage would be more suitable. On the other hand, the consumer could have a long-term deal on their mortgage rate and be paying interest at close to the Bank of England base rate and have a high attitude to risk. In these circumstances the return from investing the DC pension could exceed the return from repaying the mortgage. Consumers should also consider whether they have any expenses in the future which can only be met by taking on additional debt. For example if a consumer knows that they are going to need to spend money on essential house maintenance that they would only be able to get by taking on expensive credit card debt then it may make more sense not to use the DC pension or their other financial assets to repay the mortgage.
35 Table 8: Consumer characteristics which make using their DC pension for repaying the mortgage more or less suitable Using DC pension for mortgage repayment more suitable Higher interest rate on mortgage Can repay debt penalty free Will remain in house during retirement No need to take on additional debt Has emergency fund Low attitude to investment risk and capacity for loss Can clear mortgage using tax-free lump sum Using DC pension for mortgage repayment less suitable. Lower interest rate on mortgage Early Repayment Charge applies Considering downsizing in the near future Knows that will have an expense in the future which they will only be able to meet by taking on additional debt Has no other way of meeting an unexpected expense other than borrowing High attitude to investment risk and capacity for loss Will incur high marginal tax rate If a consumer (or their adviser) decides that they would be better off repaying their mortgage debt, then the duration over which they should do so has important consequences for the amount of tax they will pay to access the pension. Consumer type 4 - Debt - has an outstanding interest-only mortgage of 60,000, a DC pension pot of 45,000 and cash of 30,000. If they were to withdraw all of their DC pension immediately post-retirement to repay their mortgage then they would pay tax at the higher rate and would only have 6,000 of their cash savings remaining. Spreading the withdrawals over 2 tax years and reducing their tax bill would mean that even after paying for the additional mortgage interest they would have an extra 2,000 of savings. However, they would gain an even better outcome by using their entire cash savings of 30,000 to repay part of the mortgage and using the tax-free lump sum from their DC pot and then gradually repaying it by keeping withdrawals within their annual allowance. This would clear the mortgage after 7 years and they would still have around 16,500 in their DC pension pot. Even accounting for extra mortgage interest payments they would be over 5,000 better off. Using holdings of other financial assets to generate retirement income Holdings of other non-pension financial assets can be used to generate additional retirement income. The same factors which have led to falling annuity rates have also reduced the returns available from other income producing assets. In particular the rate of return on safer assets such as cash and government bonds has fallen to the lowest levels in a generation meaning that if consumers want to generate significant amounts of extra income then they will need to take extra risk. Consumers holdings of financial assets could also influence how they use their small DC pension fund. If they have sufficient holdings of other financial assets to fall back on then they may be able to take greater risk with their DC pension. In this paper it is not possible to review the pros and cons of each asset type as regards their use to generate an income. They clearly involve a range of risks, from cash which offers security of capital,
36 but minimal returns through to high risk stockmarket investments which can be volatile and place capital at risk but might generate higher long-term returns. Some of these assets would also not be available within a DC pension or if they are might be in a different form if held within a DC pension. This is relevant because a consumer who accesses all of their pension fund or takes a tax-free lump sum which exceeds their need for immediate income will need to decide where to save or invest it. Once the capital has been withdrawn from the pension, consumers will also need to decide whether they are going to erode the capital over time to fund their spending or whether they are going to only spend the income produced by the savings or investments. Cash - Taking the fund as cash The returns available on cash are the lowest for a generation. In January 2008 the average Cash ISA interest rate was over 5%, now it is just over 1%. xxiii These falls have been driven by the record low Bank of England base rate and the Government s Funding for Lending scheme, which has reduced the need for banks to attract cash deposits. There has also been criticism of the way the cash savings market operates, with banks offering excessively complex ranges of savings accounts. Consumers who don t switch account regularly can find themselves in superseded zombie accounts paying low rates of interest. In January 2015, the Government (through National Savings & Investments) will be launching a new range of fixed rate savings accounts, dubbed Pensioner Bonds, which will be exclusively available to those aged over 65. Interest rates on these products have not yet been announced, but they have been promised to be market leading. The maximum investment held by an individual will be 10,000 in each issue for each term. They cannot be held within a pension. Holding their assets in cash funds within the pension or in a cash deposit account or ISA would lead to security of capital/income but would not maintain the real, inflation-adjusted, value of the consumer s savings. Taking a withdrawal from a pension and placing it in cash could also mean potentially taking two tax hits, one on the initial withdrawal from the pension and a further tax deduction on the income from the savings account. The Tax impact can be partially mitigated by savings through an ISA. With the higher allowance now in effect it would take those with a 45,000 pension pot a maximum of 3 years to move the money into an ISA. However, one factor in favour of making a withdrawal from the pension is that interest rates could be higher outside the pension. The average pension fund in the Deposit and Treasury Sector has returned zero over the last 5 years and the average pension fund in the Money Market sector has returned 1.4% over 5 years or less than 0.3% a year. The performance of some cash funds, combined with high levels of charges would actually see the fund eroded over time. A Money market fund held in a stakeholder pension has actually declined by 2% over the previous five years. xxiv
37 Chart 5: Money Market and Deposit & Treasury pension fund annual performance Peer-2-Peer lending Peer-2-Peer lending (P2P) is a relatively new form of investing. It involves using a P2P platform to lend directly to other consumers and businesses. It is possible that some consumers could be tempted by the high headline rates on offer to withdraw some of the money from their pension and use it for P2P lending. However, P2P lending is not covered by the Financial Services Compensation Scheme and so consumers could lose their capital if the borrower defaults. Some P2P sites have established provision funds to cover the cost of defaults, but there is no regulation concerning the size these funds. P2P lending is currently not available within a pension, although it will become available within an ISA. Bonds and Bond funds / Stock market linked funds Funds invested in bonds and shares will offer varying levels of risk and return for the consumer, depending on the assets within the fund. These funds will be available both within the pension and within an ISA. Taking a tax-free lump sum from a pension and using it to invest in funds (preferably held within an ISA) might make financial sense for some consumers depending on their financial circumstances and attitude to risk. Taking a taxed withdrawal from a pension to invest in similar funds outside a pension will not make financial sense for most with DC small pots. It would immediately reduce the capital available for investment by 20% or 40%, depending on the amount taken out and the tax rate applied. If the funds are held outside an ISA then the income produced from them would be taxable. Leaving the money invested the funds inside the pension will also result in them passing tax-free to the consumer s spouse or partner should the consumer die before the age of 75. Structured products Structured products are a type of investment which offer a return linked to the performance of an underlying investment such as a stock-market index. The formula used to calculate the return can be complex and difficult to understand. Whilst high headline rates may be on marketing material, the
38 average performance could be substantially worse. Capital is at risk and consumers with structured products may lose money if the underlying investment performs poorly. If the bank or other financial institution backing the structured product collapses as happened with Lehman Brothers in 2008 consumers can suffer significant losses. Property Funds which invest in commercial and residential property are available within pensions, inside and outside ISAs. Direct investment in residential property is not allowed within a pension. Although some SIPPs can hold direct investments in commercial property, these will not be appropriate for those with small DC pension pots. Some consumers might be tempted to make withdrawals from their pension and use it to invest in a Buy-to-Let (BTL) property. Given the amount in a small DC pension pot, using it for a BTL property would also require the consumer to borrow through a BTL mortgage. Investing in a sole asset or asset class in this way to fund retirement income is an extremely risky investment strategy. This could particularly be the case if consumers are borrowing to invest in an overvalued asset class at a time when interest rates could potentially rise. Alternative investments Perhaps the biggest risk in this area is for consumers to be tempted to place money into risky alternative investments on the promise that they are safe and will offer higher levels of income. In some cases these could be outright scams, with consumers losing all of their money to fraud. As the FCA website notes Investment scams can look and sound believable, with smooth-talking salespeople, slick websites or sophisticated brochures and prospectuses. This can make it hard to tell them apart from genuine investment opportunities. The FCA has issues warnings about share fraud and boiler room schemes, land-banking, overseas property and crop investment schemes, carbon credit trading, rare-earth metals and graphene. xxv There is always a risk that consumers typing their details into marketing websites could have their details sold on to scammers. Trading standards officers and some police forces have been working with banks to help their staff can be alert if someone who is elderly comes in to withdraw a large amount of money in suspicious circumstances. This is part of drives to prevent older people falling victim to scams and rogue traders. It is unlikely that pension companies have similar training schemes in place. Conclusions Financial assets can be a useful supplement to the retirement income available from a DC pension pot. Depending on the asset, these will provide differing levels of income. Some will offer security, but low levels of income and others the potential for growth but place the consumer s capital at risk. Levels of non-pension financial assets can be taken into account by consumers and their advisers in how they manage their DC pension. The system of Pensions Guidance introduced by the Pensions Schemes Bill is classified as guidance given for the purpose of helping a member of a pension scheme make decisions about what to do with the pension benefits provided to the member. It will not automatically include guidance helping them maximise income and make decisions about their non-pension financial assets. Guidance could encourage consumers with small DC pension pots to: Be wary of taxation: Consumers withdrawing money from their pension to hold in cash or invest in other financial assets should be wary of the impact of taxation and try to limit the tax paid on withdrawals from their pension.
39 Maximise the use of ISA allowances: Financial assets and investments held outside a pension should be held in ISAs wherever possible to minimise the payment of tax on the income they generate. Holding money in a cash fund within a pension could give poor returns: Given how existing pension products are structured, excessive charges and poor interest rates could lead to some consumers invested in cash funds within pensions losing money. Shop around for the best deal in savings accounts: Consumers who move their pension savings or their tax-free lump sum into cash savings account should shop around and switch regularly to obtain the best deal. Avoid scams: Consumers should be wary of being targeted by scammers and fraudsters promoting alternative investments. The pensions industry may be able to do more to prevent those withdrawing money from DC pensions being subject to scams. 3C: Retirement income products There are three main types of retirement income products which consumers with small pension pots could access from within their pension. These are: Conventional annuities: An annuity provides a secure income for the rest of the consumer s life in return for the accumulated pension fund. Income Drawdown: This involves leaving the pension fund invested and taking income by making regular or ad-hoc withdrawals. Hybrid products: These include investment-linked, fixed-term and variable annuities. These are effectively packages of investment products, combined with some guarantees of the amount of income they will deliver or how much of a consumer s fund they will return after a set number of years. Annuities have dominated the retirement income products market for many years accounting for 94% of the retirement income products sold in 2012, with the remaining 6% of consumers opting for income drawdown. The overwhelming number of annuities sold were standard or conventional rather than the hybrid or investment linked products. The products sold were the result of three main influences on the market: 1) To access their pension many consumers had to buy a retirement income product as the limits which applied at the time did not enable many to take their fund in a cash lump-sum. 2) Annuities were the default retirement income product offered to consumers, with most pension schemes and insurance companies funnelling consumers towards these products. 3) Income drawdown was seen as risky and potentially unsuitable for those consumers with small pension pots. The FSA was clear that it was normally unsuitable for those with pension funds of less than 100,000. The introduction of additional flexibilities will inevitably see a decline in the sales of conventional annuities. Sales are already down by 56% in Q3 of 2014 xxvi, with some predicting that they could fall up to 75%. However, even with these declines between 100, ,000 annuities will be sold each year. Questions remain about what types of products will replace conventional annuities and whether they will be suitable for those with small to average sized pension pots.
40 A report from Which? and the Pensions Institute xxvii believed that income drawdown will become the norm rather than the exception. However the research found that none of the alternative products to conventional annuities (including income drawdown and hybrid products) are currently suitable for the mass market due to the costs and investment risks. The report concluded that a suitable retirement income product that can be integrated into an auto-enrolment pension for the mass market would meet the following characteristics: a. Benefits from institutional design, governance, and pricing b. Delivers a reasonably reliable income stream (i.e., with minimal fluctuations) c. Maintains the purchasing power of the fund d. Offers the flexibility to purchase the Lifetime annuity at any time (or at regular predetermined intervals to hedge interest rate and mortality risk) e. Is simple to understand, transparent and low-cost f. Requires minimal consumer engagement, e.g., by offering a high-quality default option g. Benefits from a low-cost delivery system. Which type of product is suitable for which consumers will depend on their financial circumstances, attitudes to risk, total size of their DC pension pot and their number of dependents. Annuities will be more suitable for those consumers who want to have a secure income for the rest of their life, are not willing to take investment risk and have no dependents. Income drawdown will be more suitable for consumers who have other sources of secure income they can rely on, are willing to take investment risk and the risk of running out of money in return for the possibility of higher income. It will also be more suitable for those who want to leave an inheritance or bequest. Income drawdown will need to be transformed from an expensive and potentially risky product so that it meets the criteria set out above. At the moment, its significant cost could mean that consumers fail to benefit from higher long-term growth due to excessive charges. Many consumers will also find it very difficult to take decisions about where to invest their pension and how much to withdraw without independent financial advice, which might be too expensive or difficult for them to access. Even with reform, income drawdown products will still expose consumers to investment and longevity risks. Poor performance of the investments will mean that some consumers will face having to cut their income or running out of money altogether. The differing risks from annuities compared with income drawdown and hybrid products and the flexibilities available are shown in the table below: Table 9: Risks and flexibility of different retirement income products xxviii Method Risks exposed to Risks protected against Annuities Risk of missing out Longevity risk on investment Investment risk (of growth though some capital loss) annuities are Risk of forgoing investment linked consumption Time-of-purchase risk Flexibility Level of withdrawal: low flexibility there will be a range of options at time of annuity purchase Growth: No ability to benefit from
41 Income Drawdown Hybrid products Irrevocable decision risk Inflation risk unless annuity is index linked Longevity risk Investment risk (of capital loss) leading to Income risk (the need to reduce the annual income taken from the plan) Risk of forgoing consumption Cost risk: That costs of running the drawdown plan or the investments are higher than anticipated Annuity rate risk: the risk that when it comes time to secure an income annuity rates have declined Investment risk (within the limits set by the product) Some products could involve: Counterparty risk: that those providing the guarantees can t meet their obligations Annuity rate risk: the risk that when it comes time to Partial protection from the following risks: Risk of missing out on investment growth Time-of-purchase risk Irrevocable decision risk Inflation risk Partial protection from the following risks (depending on the product): Longevity risk Risk of missing out on some investment growth (although consumers will always have given up some investment growth in return for guarantees) potential growth Bequest: low flexibility - guaranteed annuities provide some by paying out for up to 15 years from the date of purchase. Joint life annuities can provide income to a dependent which will now be tax-free if the consumer dies before the age of 75 Level of withdrawal: high flexibility up to maximum withdrawal cap Growth: high flexibility - to potentially grow fund but will depend on asset allocation Bequest: high flexibility if consumers have money remaining in their drawdown pension and they die before age 75 then it is passed on tax-free. If they die after age 75 then there will be a tax charge Level of withdrawal: The rate at which the income can vary by depending the performance of the investments can be determined by the consumer Growth: Medium flexibility to benefit from investment growth over time depending on the
42 secure an income annuity rates have declined Interest-rate risk: the risk that when the product matures and requires reinvestment, interest rates and hence the income which can be generated from the product have declined Inflation risk product Bequest: Low to medium flexibility but some products will offer the return of a proportion of a consumer s fund if they live for a set time period Income drawdown Under Income Drawdown, the consumer leaves their pension fund invested and over time can withdraw up to 25% of it tax-free, with withdrawals in excess of this amount being taxed at the marginal income tax rate. Until the introduction of the new flexibilities there was a cap which applied to the amount consumers could withdraw from their pension each year through income drawdown unless the consumer could demonstrate that they had a secure source of retirement income exceeding 20,000 a year. With the introduction of the new flexibilities consumers will be able to withdraw as much or as little as they like of their pension fund each year. Most income drawdown plans are sold with regulated financial advice and some pension companies will insist that the consumer takes advice before offering them income drawdown. In 2007, the FSA was generally of the view that income drawdown was unsuitable for those clients with funds of less than 100,000 xxix although they accepted that there may be circumstances where this may not be the case. Insurance companies also apply limits to the size of funds they would accept for income drawdown and in some cases these have now been reduced to 30,000 and are likely to be reduced further when the full Budget flexibilities are introduced. Schemes do not have to and will not have to offer income drawdown and if consumers in these schemes want access to it then they will have to switch to a different scheme. Charges Consumers using income drawdown will incur initial and ongoing charges. The level of charges for income drawdown is currently outside of the scope of the Government s charge cap for qualifying automatic enrolment pension schemes. There are five main types of charges which consumers could pay: Administration charges specific to drawdown: These could include (a) Set-up fees for entering income drawdown (b) Annual fees for being in income drawdown (c) Charges for altering the level of drawdown payments (d) Charges for altering the frequency of payments or making one-off withdrawals (e) Charges for depleting the fund or reducing it below a certain size. Investment charges: The costs and charges paid in return for managing the funds and investments. These include (a) Direct Fund Management costs and charges paid to the fund manager, which could
43 include initial charges, annual charges and performance fees (b) Legal and audit fees which would be included in the Total Expense Ratio (c) costs incurred by any stock lending undertaken by the fund (d) commission payments made to the financial adviser who sold the consumer the investment (these have been banned for new business from 1 st January 2013, but existing legacy arrangements can continue). Platform charges: The costs of holding the pension funds and investments through a platform such as a SIPP. These could include (a) Initial/set up fees (b) Annual fees which could be charged as a fixed fee, a percentage of the investment held on the platform or both (c) Administration charges for transferring in/out or on death (d) Net interest margin on cash held in the bank account on the platform. Transaction costs within and between funds: These include (a) The costs incurred both by the investor when switching between different pension funds (b) The transaction costs incurred within individual funds as a result of the fund manager buying and selling the assets. Advice costs: If the consumer receives advice about whether to enter income drawdown, how their investments should be managed and how much they should withdraw each year then they would need to pay initial and/or ongoing charges to a financial adviser. A low-cost portfolio might have ongoing investment and platform charges of around 1% a year. A more expensive portfolio might cost between 1.5% and 2% a year. Additional administration charges could be levied by the platform or pension provider for entering income drawdown and for taking withdrawals. Research from the found significant variability in one-off event charges, such as set up fees which range from zero to 240, additional crystallisation charges that could go up to 100, and withdrawal charges that could be as high as 60. xxx However, several providers have recently announced the removal of set-up fees. Advice costs might be in the region of 2% initial adviser charge and a 0.5% ongoing annual adviser charge for regular reviews. However, some advisers may have specified minimum charges for advice on income drawdown and advice may be difficult for those with small DC pots to access unless they are willing to pay these charges. The implication of these different charging structures are that it will be difficult for consumers to understand and compare the total cost of income drawdown. Shopping around for income drawdown is likely to be even more difficult and complex than shopping around for an annuity. Inertia and complexity could mean that those consumers are at risk of paying higher charges. The long-term impact of costs and charges for income drawdown for those with small pots could be significant and result in consumers having to take less income out of their pension or running out money quicker. The chart below shows that a high-charging income drawdown plan could see consumer type 1 with a DC pot of 29,000 withdrawing 2,000 a year run out of money almost six years earlier and receive 11,000 less in income payments than one with a total cost of 0.75% a year.
44 Chart 6: Income drawdown comparison between high-charging and low-charging fund Notes: High-charging scheme has charges of 2% initial, and 2% annual charges. Low-charging scheme has an annual charge of 0.75% Investment strategy / Asset allocation Consumers entering income drawdown will also have to choose an investment strategy. At present most drawdown policies are sold with regulated financial advice and so the adviser is likely to make a personal recommendation regarding the investment strategy. Those consumers who do not take advice will either have to choose a new investment strategy themselves or remain in the strategy they chose when they last made a decision or the default investment strategy offered by their pension scheme. Some pension schemes will have a default strategy which includes lifestyling which means that as the consumer approaches retirement their investments are gradually moved into safer assets. The default investment strategy for many pension schemes is currently designed for those buying an annuity at retirement. This could mean that at retirement age the consumer s pension fund is invested in 75% bonds and 25% cash. However, in a survey of default funds used in stakeholder pension schemes some used 100% bonds and some used 100% cash as the asset allocation at retirement. xxxi Stakeholder pensions are required to use a lifestyling strategy but in other types of pension scheme there may be no such approach in place. Lifestyling as a concept was only introduced around 10 years ago so it is less likely to apply in older schemes. This means that the investment strategy at retirement might no longer be suitable as it could either be the one selected by the consumer when they joined the scheme or the one set by the scheme provider when it was established. The investment strategy of the scheme after retirement has significant implications for the amount of risk the individuals pension will be subject to, the level of income they can withdraw and how likely they are to run out of money. Broadly, a low-risk investment strategy will reduce the level of income that can be taken from the scheme, but reduce the risk of having to make cuts to the level of income and the
45 probability of the consumer running out of money. A higher risk investment strategy, with exposure to riskier assets is more likely to provide growth over the longer-term, but with the trade-off of increased risk and volatility for the consumer s investment. A higher risk strategy could mean that consumers could face a greater prospect of having to reduce their income because of poor investment performance or running out of money. Policymakers and the pensions industry should also recognise that the removal of the prompt to purchase an annuity could result in consumers simply leaving their funds invested. By removing the prompt for action that comes from being offered and having little choice about whether to purchase an annuity, more consumers may simply leave their fund where it is. This may be a conscious decision they may not need to use the pension fund to supplement their income or it may be the result of inertia. This means that funds will continue to accumulate, but if it is invested in low-return assets then it may not keep pace with inflation. Level of withdrawal Consumers entering income drawdown will need to take (with or without advice/guidance) complicated decisions about how much income to withdraw each year and how often the level should be reviewed. The general advice for those entering income drawdown is to only take the natural income from their fund to avoid eroding their capital. But those with small pots are unlikely to be able to attain their desired level of income without eroding capital the key question will be over what time period the capital should be eroded. If consumers withdraw too much of their money each year then they could run out of money. On the other hand if they restrict withdrawals because they are worried about running out of money they might under-consume in the first few years of their retirement and still be left with a significant funds on death. The rate at which consumers want to drawdown their pension will also help determine the asset allocation. Consumers are known to under-estimate their life expectancy and over-estimate how much income their pension will deliver. A consumer with a spouse/partner would also have to take into account how long their partner might live when deciding how much to drawdown each year. Consumers who die before the age of 75 will be able to pass on their accumulated fund without paying tax. If they are above the Inheritance Tax threshold then it may be worth them using other assets first before starting to use their DC pension. The tables below show the age when the small DC pension pots will run out under various scenarios, assuming they are claimed at age 65.They show how long the DC pension will last given a fixed withdrawal each year, or a withdrawal which starts at a certain level and increases with inflation assumed to be 2.75% a year. Table 10: Age when DC pension pot runs out (Consumer type 1: Multiple small pots Total DC fund 29,000) Portfolio return (pre charges) 1,000 Fixed 1,000 Index- Linked Yearly income 2,000 2,000 Fixed Index- 3,000 Fixed 3,000 Index- Linked Linked 1% % > % >
46 7% >100 > Table 11: Age when DC pension pot runs out (Consumer type 2: DC and DB Total DC fund 15,000) Portfolio return (pre charges) 750 Fixed 750 Index- Linked Yearly income 1,500 1,500 Fixed Index- 2,000 Fixed 2,000 Index- Linked Linked 1% % % % > Table 12: Age when DC pension pot runs out (Consumer type 4: Debt Total DC fund 45,000) Portfolio return (pre charges) 2,000 Fixed 2,000 Index- Linked Yearly income 3,000 3,000 Fixed Index- 5,000 Fixed 5,000 Index- Linked Linked 1% % % > % > Assumptions: Consumer retires at 65, enters income drawdown with their entire DC pension pot and withdraws either a fixed or inflation-linked amount from their pension each year. Investment growth occurs equally over the time period. Charges are 1.5% a year. During the income drawdown phase protection from downside risks is important particularly in the first few years after retirement. Poor performance in the early years can lead to a far earlier erosion of a consumer s pension pot. As research by NEST has demonstrated Strong returns in the early years can provide a significant buffer against poor performance in later years. Conversely, poor performance in early years is very difficult to make up when the capital is being depleted through drawdown. xxxii A consumer who entered income drawdown in 1999 aged 65 and took the amount of a standard annuity, would be due to run out of money next year, aged just 81 5 years below average longevity for males and 7 years for females. xxxiii The total income received by the different types of consumer and the impact on their total income when they run out of money in their DC pension Whether consumers (and their partners) can afford to take the risk of running out of money will partly depend on what other forms of secure income they can access. The Charts below show the impact on the 3 example individuals of running out of money at around the same age. These assume a fixed annual withdrawal from the DC pension. The different colour bars represent the income from different sources, with the blue bars representing the income taken out of the DC pension pot. All 3 will experience a drop in income the year after they run out of money. However, for the consumer type 2 with a DB pension the drop will be relatively modest. The multiple small pots consumer experiences a larger drop in annual income, from over 14,000 to under 12,000, but may be able to
47 better manage this due to their other financial assets which they could use to supplement their income. At this point they could consider spending some of their other financial assets to cushion the drop in income. The drop will be largest for the consumer who entered retirement with debt and had to use all of their financial assets to repay debt consumer type 4. They would experience a drop in annual income from 13,600 to 9,000. From the age of 78 they would be entirely reliant on the State Pension for their retirement income. If that consumer is going to decide to drawdown at that rate then they should consider whether they can cope with the potential drop in income. Chart 7: Yearly income for consumer type 1 Multiple small pots withdrawing 3,000 3,000 a year. Other income is taken from Cash and an Investment ISA.
48 Chart 8: Yearly income for consumer type 2 DB and DC withdrawing 1,500 1,500 a year. Income from DB pension scheme is index-linked and increases at 2.75% a year. Chart 9: Yearly income for consumer type 4 Debt withdrawing 5,000 a year from their DC pension Yearly income - 45,000 pension pot, 5,000 a year withdrawn 16,000 14,000 12,000 10,000 8,000 6,000 4,000 2, DC Pens ion Income State Pensi on income Assumptions: Consumer retires at 65, enters income drawdown with their entire DC pension pot and withdraws a fixed amount each year. Yearly investment growth within the pension of 7% and charges of 1.5% a year. Fixed annual withdrawals from the pension of 5,000 a year.
A relief for some: how to stop lump sum tax relief favouring the wealthy
Summary The tax relief permitted on pension lump sums disproportionately benefits the wealthy at taxpayers expense. The result is a regressive system where those with the most generous entitlements also
Universal Credit: welfare that works.
Universal Credit: welfare that works. Presented to Parliament by the Secretary of State for Work and Pensions by Command of Her Majesty November 2010 Cm 7 9 5 7 19.75 Universal Credit: welfare that works.
Making the most of your money
Making the most of your money The Money Advice Service is here to help you manage your money better. We provide clear, unbiased advice to help you make informed choices. We try to ensure that the information
Investing between the flags. A practical guide to investing
Investing between the flags A practical guide to investing About ASIC The Australian Securities and Investments Commission (ASIC) regulates financial advice and financial products (including credit). ASIC,
Table of Contents. The Thrift Savings Plan... 1 Establishing Your TSP Account... 2. Employee Contributions... 3
Table of Contents The Thrift Savings Plan... 1 Establishing Your Account... 2 The Contribution Election... 2 Employee Contributions... 3 Regular Employee Contributions... 3 Catch-Up Contributions...
Using Credit to Your Advantage.
Using Credit to Your Advantage. Topic Overview. The Using Credit To Your Advantage topic will provide participants with all the basic information they need to understand credit what it is and how to make
Regulating will-writing
Regulating will-writing July 2011 Will-writing I 2 CONTENTS Foreword 1 1 Executive Summary 2 2 Introduction 8 3 Market Picture 12 4 Quality 19 5 Sales practices 34 6 Storage 45 7 Mental capacity 49 8 Fraud
A guide to receiving direct payments from your local council
A guide to receiving direct payments from your local council A route to independent living September 2009 This guide contains information on direct payments updated in 2009, under the provisions contained
Pension schemes Pension schemes under the new employer duties
Workplace pensions reform detailed guidance Pension schemes Pension schemes under the new employer duties 4 April 2013 v4.1 1 Employer duties and defining the workforce An introduction to the new employer
BOARD DEVELOPMENT. Financial Responsibilities of Not-for-Profit Boards
BOARD DEVELOPMENT Financial Responsibilities of Not-for-Profit Boards Board Development Financial Responsibilities of Not-for-Profit Boards A Self-Guided Workbook The Right to Copy this Workbook Permission
American Retirement Savings Could Be Much Better
AP Photo/Jae C. Hong American Retirement Savings Could Be Much Better By Rowland Davis and David Madland August 2013 American Retirement Savings Could Be Much Better By Rowland
Has Labour made work pay?
Has Labour made work pay? Has Labour made work pay? Mike Brewer and Andrew Shephard The Joseph Rowntree Foundation has supported this project as part of its programme of research and innovative development | http://docplayer.net/9565-Dashboards-and-jam-jars-helping-consumers-with-small-defined-contribution-pension-pots-make-decisions-about-retirement-income.html | CC-MAIN-2017-09 | refinedweb | 19,332 | 51.92 |
LEEP(3) OpenBSD Programmer's Manual USLEEP(3)
NAME
usleep - suspend execution for interval of microseconds
SYNOPSIS
#include <unistd.h>
int
usleep(useconds_t microseconds);
DESCRIPTION).
RETURN VALUES
If the usleep() function returns because the requested time has elapsed,
the value returned will be zero.
If the usleep() function returns due to the delivery of a signal, the
value returned will be the -1, and the global variable errno will be set
to indicate the interruption.
ERRORS
If any of the following conditions occur, the usleep() function shall re-
turn -1 and set errno to the corresponding value.
[EINTR] usleep() was interrupted by the delivery of a signal.
[EINVAL] useconds specified a value of 1,000,000 or more microsec-
onds.
NOTES
A microsecond is 0.000001 seconds.
SEE ALSO
getitimer(2), nanosleep(2), setitimer(2), alarm(3), sigpause(3),
sleep(3), ualarm(3)
STANDARDS
The usleep() function conforms to X/Open Portability Guide Issue 4.2
(``XPG4.2'').
HISTORY
The usleep() function appeared in 4.3BSD.
OpenBSD 2.6 November 4, 1997 1 | http://www.rocketaware.com/man/man3/usleep.3.htm | crawl-002 | refinedweb | 173 | 57.37 |
In this article we learn about routing, or URL-based filtering as it is sometimes referred to. We'll use it to provide a unique URL for each of the three todo views — "All", "Active", and "Completed".
URL-based filtering
Ember comes with a routing system that has a tight integration with the browser URL. Typically, when writing web applications, you want the page to be represented by the URL so that if (for any reason), the page needs to refresh, the user isn't surprised by the state of the web app — they can link directly to significant views of the app.
At the moment, we already have the "All" page, as we are currently not doing any filtering in the page that we've been working with, but we will need to reorganize it a bit to handle a different view for the "Active" and "Completed" todos.
An Ember application has a default "application" route, which is tied to the
app/templates/application.hbs template. Because that application template is the entry point to our todo app, we'll need to make some changes to allow for routing.
Creating the routes
Let's start by creating three new routes: "Index", "Active" and "Completed". To do this you’ll need to enter the following commands into your terminal, inside the root directory of your app:
ember generate route index ember generate route completed ember generate route active
The second and third commands should have not only generated new files, but also updated an existing file,
app/router.js. It contains the following contents:
import EmberRouter from '@ember/routing/router'; import config from './config/environment'; export default class Router extends EmberRouter { location = config.locationType; rootURL = config.rootURL; } Router.map(function() { this.route('completed'); this.route('active'); });
The highlighted lines were added when the 2nd and 3rd commands above were run.
router.js behaves as a "sitemap" for developers to be able to quickly see how the entire app is structured. It also tells Ember how to interact with your route, such as when loading arbitrary data, handling errors while loading that data, or interpreting dynamic segments of the URL. Since our data is static, we won't get to any of those fancy features, but we'll still make sure that the route provides the minimally required data to view a page.
Creating the "Index" route did not add a route definition line to
router.js, because like with URL navigation and JavaScript module loading, "Index" is a special word that indicates the default route to render, load, etc.
To adjust our old way of rendering the TodoList app, we'll first need to replace the TodoList component invocation from the application template with an
{{outlet}} call, which means "any sub-route will be rendered in place here".
Go to the
todomvc/app/templates/application.hbs file and replace
<TodoList />
With
{{outlet}}
Next, in our
index.hbs,
completed.hbs, and
active.hbs templates (also found in the templates directory) we can for now just enter the TodoList component invocation.
In each case, replace
{{outlet}}
with
<TodoList />
So at this point, if you try the app again and visit any of the three routes
localhost:4200
localhost:4200/active
localhost:4200/completed
you'll see exactly the same thing. At each URL, the template that corresponds to the specific path ("Active", "Completed", or "Index"), will render the
<TodoList /> component. The location in the page where
<TodoList /> is rendered is determined by the
{{ outlet }} inside the parent route, which in this case is
application.hbs. So we have our routes in place. Great!
But now we need a way to differentiate between each of these routes, so that they show what they are supposed to show.
First of all, return once more to our
todo-data.js file. It already contains a getter that returns all todos, and a getter that returns incomplete todos. The getter we are missing is one to return just the completed todos. Add the following below the existing getters:
get completed() { return this.todos.filter(todo => todo.isCompleted); }
Models
Now we need to add models to our route JavaScript files to allow us to easily return specific data sets to display in those models.
model is a data loading lifecycle hook. For TodoMVC, the capabilities of model aren't that important to us; you can find more information in the Ember model guide if you want to dig deeper. We also provide access to the service, like we did for the components.
The index route model
First of all, update
todomvc/app/routes/index.js so it looks as follows:
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class IndexRoute extends Route { @service('todo-data') todos; model() { let todos = this.todos; return { get allTodos() { return todos.all; } } } }
We can now update the
todomvc/app/templates/index.hbs file so that when it includes the
<TodoList /> component, it does so explicitly with the available model, calling its
allTodos() getter to make sure all of the todos are shown.
In this file, change
<TodoList />
To
<TodoList @todos={{ @model.allTodos }}/>
The completed route model
Now update
todomvc/app/routes/completed.js so it looks as follows:
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class CompletedRoute extends Route { @service('todo-data') todos; model() { let todos = this.todos; return { get completedTodos() { return todos.completed; } } } }
We can now update the
todomvc/app/templates/completed.hbs file so that when it includes the
<TodoList /> component, it does so explicitly with the available model, calling its
completedTodos() getter to make sure only the completed todos are shown.
In this file, change
<TodoList />
To
<TodoList @todos={{ @model.completedTodos }}/>
The active route model
Finally for the routes, let's sort out our active route. Start by updating
todomvc/app/routes/active.js so it looks as follows:
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class ActiveRoute extends Route { @service('todo-data') todos; model() { let todos = this.todos; return { get activeTodos() { return todos.incomplete; } } } }
We can now update the
todomvc/app/templates/active.hbs file so that when it includes the
<TodoList /> component, it does so explicitly with the available model, calling its
activeTodos() getter to make sure only the active (incomplete) todos are shown.
In this file, change
<TodoList />
To
<TodoList @todos={{ @model.activeTodos }}/>
Note that, in each of the route model hooks, we are returning an object with a getter instead of a static object, or more simply just the static list of todos (for example,
this.todos.completed). The reason for this is that we want the template to have a dynamic reference to the todo list, and if we returned the list directly, the data would never re-compute, which would result in the navigations appearing to fail / not actually filter. By having a getter defined in the return object from the model data, the todos are re-looked-up so that our changes to the todo list are represented in the rendered list.
Getting the footer links working
So our route functionality is now all in place, but we can't access them from our app. Let's get the footer links active so that clicking on them goes to the desired routes.
Go back to
todomvc/app/components/footer.hbs, and find the following bit of markup:
<a href="#">All</a> <a href="#">Active</a> <a href="#">Completed</a>
Update it to
<LinkTo @All</LinkTo> <LinkTo @Active</LinkTo> <LinkTo @Completed</LinkTo>
<LinkTo> is a built-in Ember component that handles all the state changes when navigating routes, as well as setting an "active" class on any link that matches the URL, in case there is a desire to style it differently from inactive links.
Updating the todos display inside TodoList
One small final thing that we need to fix is that previously, inside
todomvc/app/components/todo-list.hbs, we were accessing the todo-data service directly and looping over all todos, as shown here:
{{#each this.todos.all as |todo| }}
Since we now want to have our TodoList component show a filtered list, we'll want to pass an argument to the TodoList component representing the "current list of todos", as shown here:
{{#each @todos as |todo| }}
And that's it for this tutorial! Your app should now have fully working links in the footer that display the "Index"/default, "Active", and "Completed" routes.
Summary
Congratulations! You've finished this tutorial!
There is a lot more to be implemented before what we've covered here has parity with the original TodoMVC app, such as editing, deleting, and persisting todos across page reloads.
To see our finished Ember implementation, checkout the finished app folder in the repository for the code of this tutorial or see the live deployed version here. Study the code to learn more about Ember, and also check out the next article, which provides links to more resources and some troubleshooting advice. | https://developer.mozilla.org/pl/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing | CC-MAIN-2020-45 | refinedweb | 1,506 | 51.58 |
In this problem, we are given an array of points. This represents a list of x-coordinates and y-coordinates of some points that lie on an X-Y 2-D plane. We need to check if these points form a straight line. Note that there will be at least 2 points in the input and their absolute values will not exceed 10^4.
Example
Co-ordinates = {{1 , 2} , {2 , 3} , {3 , 4} , {4 , 5} , {5 , 6}}
true
Explanation The following diagram confirms that all points are collinear.
Co-ordinates = {{1 , 2} , {3 , 4}}
true
Explanation: Two connected points always form a straight line.
Approach
It is easy to observe that if there are only two points in the given list then they will always form a straight line and the result will be true. However, if there are three points, all of them may or may not be collinear. So, we can fix any two points, form a line passing through them, and check if all the other points lie on the same line. Mathematically, this can be done by checking the slope of the line formed between any two points. For example, let us consider we have three points: P1 = (x1 , y1) , P2 = (x2 , y2) and P3 = (x3 , y3).
Now, let’s form a line passing through P1 and P2. The slope of this line will be:
Slope = (y2 – y1) / (x2 – x1)
In order to ensure that P3 is collinear with P1 and P2, let us find the slope of the line formed by points P2 and P3 first. That is,
Slope(P2 and P3) = (y3 – y2) / (x3 – x2)
Now, the points are collinear only and only if: Slope of line formed by P1 and P2 = Slope of line formed by P2 and P3.
Therefore, if P1, P2 and P3 are collinear, we have
(y2 – y1) : (x2 – x1) :: (y3 – y2) : (x3 – x2) , or
(y2 – y1) * (x3 – x2) = (x2 – x1) * (y3 – y2)
Therefore, we can fix two points, say P1 and P2, and for every i > 2 in the input list, we can check if slope(1 , 2) is equal to Slope(1 , i) by cross-product check as we saw above.
Algorithm
- We use a boolean function checkStraightLine() to return whether an array of points passed to it forms a straight line
- If the array has only 2 points:
- return true
- Initialize x0 as x-coordinate of first point and y0 as y-coordinate of second point. Similarly, (x1 , y1) for coordinates of second point
- Since we need their difference for cross-product check, store their differences as:
- dx = x1 – x0
- dy = y1 – y0
- Now for every point in the array after the second point:
- Store x and y coordinates of this point in variables x and y
- Now, we check whether the slopes of the first two points and the slope of this and the first point are the same:
- If dy * (x – x0) is not equal to dx * (y – y0)
- return false
- Return true
- Print the result
Implementation of Check If It Is a Straight Line Leetcode Solution
C++ Program
#include <bits/stdc++.h> using namespace std; bool checkStraightLine(vector <vector <int> > &coordinates) { if(coordinates.size() == 2) return true; int x0 = coordinates[0][0] , x1 = coordinates[1][0]; int y0 = coordinates[0][1] , y1 = coordinates[1][1]; int dx = x1 - x0 , dy = y1 - y0; for(int i = 2 ; i < coordinates.size() ; i++) { int x = coordinates[i][0] , y = coordinates[i][1]; if(dy * (x - x0) != dx * (y - y0)) return false; } return true; } int main() { vector <vector <int> > coordinates = {{1 , 2} , {2 , 3} , {3 , 4} , {4 , 5} , {5 , 6}}; cout << (checkStraightLine(coordinates) ? "true\n" : "false\n"); }
Java Program
class check_straight_line { public static void main(String args[]) { int[][] coordinates = {{1 , 2} , {2 , 3} , {3 , 4} , {4 , 5} , {5 , 6}}; System.out.println(checkStraightLine(coordinates) ? "true" : "false"); } static boolean checkStraightLine(int[][] coordinates) { if(coordinates.length == 2) return true; int x0 = coordinates[0][0] , x1 = coordinates[1][0]; int y0 = coordinates[0][1] , y1 = coordinates[1][1]; int dx = x1 - x0 , dy = y1 - y0; for(int i = 2 ; i < coordinates.length ; i++) { int x = coordinates[i][0] , y = coordinates[i][1]; if(dy * (x - x0) != dx * (y - y0)) return false; } return true; } }
true
Complexity Analysis of Check If It Is a Straight Line Leetcode Solution
Time Complexity
O(N) where N = number of points in the array. We do a single pass of the array and all the operations performed in it take constant time.
Space Complexity
O(1) as we only use constant memory space. | https://www.tutorialcup.com/leetcode-solutions/check-if-it-is-a-straight-line-leetcode-solution.htm | CC-MAIN-2021-49 | refinedweb | 756 | 63.22 |
BBC micro:bit
MicroPython Matrix
Introduction
There are two things that we want to use when dealing with the LED matrix. The display object allows us to interact with the matrix, show images, text or turn pixels on or off. The Image class has lots of useful functionality for defining the images you want to display on the matrix.
Display Object
display.set_pixel(x, y, val)
You can set the brightness of individual pixels from 0 (off) to 9 (full brightness). The following example varies the brightness of the central pixel of the matrix.
from microbit import * while True: for i in range(0,10): display.set_pixel(2,2,i) sleep(100) for i in range(9,-1,-1): display.set_pixel(2,2,i) sleep(100)
You can use the display.get_pixel(x, y) method to find out the brightness of a pixel. You might need to do this if you are doing something where the brightness of pixels on the matrix varies with user or sensor input.
display.scroll(string, delay=400)
This method allows you to scroll text across the matrix at the speed of your choice. The delay argument is optional. The following example scrolls text slowwwwly.
from microbit import * while True: display.scroll("A message", delay=1000)
display.show(image, delay=0, wait=True, loop=False, clear=False)
We use this method to display an image on the matrix. A built-in image is used in this program.
from microbit import * display.show(Image.HAPPY)
display.clear()
It does what you expect.
from microbit import * while True: display.show(Image.HAPPY) sleep(1000) display.show(Image.SAD) sleep(1000) display.clear() sleep(1000)
The Image Class
The Image class is a way of working with patterns that you want to display on the screen. With the other code editors, you work directly with the screen and don't have an abstract model of a 5x5 pattern that you can work with.
Built-In ImagesMicroPython has a shedload of built-in images.
from microbit import *] display.show(built_in_images, delay=1000,loop=True)
The above example uses an overloaded version of the display.show() method that allows you to pass a list of images as an argument. This creates a repeating animation/slideshow of all of the built-in image constants. Alternatively, you can use them just like this,
from microbit import * display.show(Image.HAPPY)
Make Your Own
You can define your own image quite easily with a string like this,
from microbit import * im = Image('99999:90009:90009:90009:99999:') display.show(im)
Remember that you can vary the brightness by choosing digits from 0 - 9.
from microbit import * im = Image('99999:97779:97379:97779:99999:') display.show(im)
Animation
Here a list of images is used to make a simple line animation.
from microbit import * imgs = [ Image('90000:00000:00000:00000:00000:'), Image('90000:09000:00000:00000:00000:'), Image('90000:09000:00900:00000:00000:'), Image('90000:09000:00900:00090:00000:'), Image('90000:09000:00900:00090:00009:') ] display.show(imgs, delay=500,loop=True)
Moving
You can set a pixel in an image and move it around quite nicely too. The advantage of being able to work with the image class is that you don't have the matrix updating until you want it to. In this example, we'll create a blank image. Then we'll set the central pixel to full brightness. Then we'll move the image around a little.
from microbit import * im = Image('00000:00000:00900:00000:00000:') display.show(im) sleep(500) while True: im = im.shift_up(1) display.show(im) sleep(500) im = im.shift_right(1) display.show(im) sleep(500) im = im.shift_down(1) display.show(im) sleep(500) im = im.shift_left(1) display.show(im) sleep(500)
You can make some variation to what happens to the dot in this program quite easily. Replace the sleep number with a variable. Find a way to vary that variable to alter the speed at which the dot moves.
You can also use the same technique that was used to display the built-in images to make some sort of animation without having to go through the clunkiness of clicking out your frames in the code editors.
Challenge
Hopefully you have some ideas starting to form. There's going to be a lot more you can do with the matrix once you get a little bit more into the functionality of the micro:bit module. Make sure that you have had a go at all of the samples on this page. Mess around a little with the values and change the overall effect a little. | http://www.multiwingspan.co.uk/micro.php?page=pyled | CC-MAIN-2019-47 | refinedweb | 775 | 67.96 |
>> if a given graph is tree or not
In this problem, one undirected graph is given, we have to check the graph is tree or not. We can simply find it by checking the criteria of a tree. A tree will not contain a cycle, so if there is any cycle in the graph, it is not a tree.
We can check it using another approach, if the graph is connected and it has V-1 edges, it could be a tree. Here V is the number of vertices in the graph.
Input and Output
Input: The adjacency matrix. 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 Output: The Graph is a tree
Algorithm
isCycle(u, visited, parent)
Input: The start vertex u, the visited list to mark visited or not, the parent vertex.
Output: True if there is a cycle in the graph.
Begin mark u as visited for all vertex v which are adjacent with u, do if v is visited, then if isCycle(v, visited, u) = true, then return true else if v ≠ parent, then return true done return false End
isTree(graph)
Input: The undirected graph.
Output: True when the graph is a tree.
Begin define a visited array to mark which node is visited or not initially mark all node as unvisited if isCycle(0, visited, φ) is true, then //the parent of starting vertex is null return false if the graph is not connected, then return false return true otherwise End
Example
#include<iostream> #define NODE 5 using namespace std; int graph[NODE][NODE] = { {0, 1, 1, 1, 0}, {1, 0, 1, 0, 0}, {1, 1, 0, 0, 0}, {1, 0, 0, 0, 1}, {0, 0, 0, 1, 0} }; bool isCycle(int u, bool visited[], int parent) { visited[u] = true; //mark v as visited for(int v = 0; v<NODE; v++) { if(graph[u][v]) { if(!visited[v]) { //when the adjacent node v is not visited if(isCycle(v, visited, u)) { return true; } } else if(v != parent) { //when adjacent vertex is visited but not parent return true; //there is a cycle } } } return false; } bool isTree() { bool *vis = new bool[NODE]; for(int i = 0; i<NODE; i++) vis[i] = false; //initialize as no node is visited if(isCycle(0, vis, -1)) //check if there is a cycle or not return false; for(int i = 0; i<NODE; i++) { if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected return false; } return true; } int main() { if(isTree()) cout << "The Graph is a Tree."; else cout << "The Graph is not a Tree."; }
Output
The Graph is a Tree.
- Related Questions & Answers
- Check if a given tree graph is linear or not in C++
- C++ Program to Check if a Directed Graph is a Tree or Not Using DFS
- C++ program to Check if a Given Binary Tree is an AVL Tree or Not
- C++ Program to Check if an UnDirected Graph is a Tree or Not Using DFS
- Check if a Tree is Isomorphic or not in C++
- Check if a directed graph is connected or not in C++
- C++ Program to Check if a Given Graph must Contain Hamiltonian Cycle or Not
- Check if a binary tree is sorted levelwise or not in C++
- Program to check whether given tree is symmetric tree or not in Python
- Check if a given matrix is Hankel or not in C++
- Check if a given matrix is sparse or not in C++
- Check if a given number is sparse or not in C++
- Python - Check if a given string is binary string or not
- C++ Program to Check Whether a given Binary Tree is a Full Binary Tree or not
- Program to check whether given graph is bipartite or not in Python
Advertisements | https://www.tutorialspoint.com/Check-if-a-given-graph-is-tree-or-not | CC-MAIN-2022-27 | refinedweb | 648 | 51.55 |
Question: Seqan read compressed stream
0
Hi,
I want read a sequence file (fasta fastq bam, etc), so I read Seqan tutorial. But If I want know my position in file I need use std::ifstream (for generate a progress bar) , it's not a problem, I write this test code:
#include <iostream> #include <fstream> #include <seqan/seq_io.h> int main (int argc, char ** argv) { std::streampos begin,end; std::ifstream myfile (argv[1], std::ios::in | std::ios::binary); begin = myfile.tellg(); seqan::SeqFileIn seq_file(myfile); seqan::CharString id; seqan::Dna5String seq; seqan::CharString qual; while(!seqan::atEnd(seq_file)) { seqan::readRecord(id, seq, qual, seq_file); std::cout<<"pos: "<<myfile.tellg()<<" id "<<id<<std::endl; } end = myfile.tellg(); myfile.close(); std::cout << "begin: "<< begin << " end: "<< end << std::endl; std::cout << "size is: " << (end-begin) << " bytes.\n"<<std::endl; return 0; }
But when I try this code on compressed fastq read, Seqan throw an exception
terminate called after throwing an instance of 'seqan::ParseError'
My question :
- Use std::ifstream is the only solution to get the current position in file ?
- How I can say to Seqan this stream are a compressed stream ?
- Can I generate an uncompressed stream from my compressed stream (with SeqAn or zlib)
Thanks.
why would you want to know the position of a fastq record in a compressed file ? unless you're using bgzf, there is no way to 'fseek ' a bgzip file...
I want generate a progress bar, the post required an edit. For compress file we can have a good approximation with size of compressed file and the position in compressed file.
then I would create a custom std::streambuf to count the number of bytes... e.g:
I use a std::ifstream to get current position in file during seqan parsing, it's easy. But when I try my code on compressed file, seqan parsing failed. So seqan didn't detect my stream contain compressed data or seqan can't work on compressed stream, but isn't documented.
Usually it is the other way round: Things don't work on compressed data, unless documented.
Is documented
Source :
Well, there is compressed
.bamand compressed
.gz.
And bz2 according to | https://www.biostars.org/p/289979/ | CC-MAIN-2018-13 | refinedweb | 364 | 64.71 |
The.
Note: in this document the terms "Java AWT Native Interface", "AWT Native Interface" and "JAWT" are interchangeable and refer to this same specification.
The fundamental obstacle to native rendering without JAWT is that is that the rendering code cannot identify where to draw. The native code needs access to information about a Java drawing surface (such as a handle to the underlying native ID of a Canvas), but cannot get.
Reasons for using the AWT Native Interface include
Drawbacks include
An example illustrating how easy it is to use the AWT Native Interface is presented and discussed later in this document.
JAWT usage depends on JNI.
So JNI is general enough to be used to access almost any sort of native library. The rest of this document assumes a familiarity with how to use JNI.
How to use JAWT
In this section we. Canvas is a good candidate for the rendering surface as it does not have any content as a Button would.
The new paint method, to be implemented in the native rendering library, must be declared as public native void , and the native library itself is loaded at runtime by including a call to System.loadLibrary( "myRenderingLib")in the static block of the class. The myRenderingLib name is used for the native shared library; for Linux or the Solaris operating environment, the actual name for the library file on disk is libmyRenderingLib.so .
Here to run JDK. NB: javac -h outputdir may also be used.
The final step and the most interesting one is to write the native rendering method, with an interface that conforms to the header file that javah generated, and build it as a standard shared library (called myRenderingLib in the above example) by linking it, against the appropriate JDK provided $JDK_HOME/lib/$JAWT_LIB library for the target platform. Where JAWT_LIB has the base name "jawt" and follows platform shared object naming rules. i.e.: X11-based drawing environment (Linux or Solaris) and a Java VM where the AWT Native Interface is present:
_9; GDI API. The same also for MacOS.. This book was published in June 1999 by Addison-Wesley. The ISBN is 0-201-32577-2.
Appendix
Header Files for jawt.h and jawt_md.h
jawt.h
. * */ /* * all platforms support the existing structures in jawt_md.h. * ******************* * EXAMPLE OF USAGE: ******************* * * On Microsoft Windows, <assert.h> * *. Request version 9 to access features in that release. * awt.version = JAWT_VERSION_9; * Microsoft Windows or a * JAWT_X11DrawingSurfaceInfo on Linux and Solaris. On MacOS this is a * pointer to a NSObject that conforms to the JAWT_SurfaceLayers protocol. *. * If Lock(), Unlock(), GetDrawingSurfaceInfo() or * FreeDrawingSurfaceInfo() are called from a different thread, * this data member should be set before calling those functions. */().. */ _JNI_IMPORT_OR_EXPORT_ jboolean JNICALL JAWT_GetAWT(JNIEnv* env, JAWT* awt); /* * Specify one of these constants as the JAWT.version * Specifying an earlier version will limit the available functions to * those provided in that earlier version of JAWT. * See the "Since" note on each API. Methods with no "Since" * may be presumed to be present in JAWT_VERSION_1_3. */ #define JAWT_VERSION_1_3 0x00010003 #define JAWT_VERSION_1_4 0x00010004 #define JAWT_VERSION_1_7 0x00010007 #define JAWT_VERSION_9 0x00090000 #ifdef __cplusplus } /* extern "C" */ #endif #endif /* !_JAVASOFT_JAWT_H_ */
jawt_md.h (Linux/Solaris/X11 operating environment version)
#ifndef _JAVASOFT_JAWT_MD_H_ #define _JAVASOFT_JAWT_MD_H_ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Intrinsic.h> (Microsoft Windows version)
#ifndef _JAVASOFT_JAWT_MD_H_ #define _JAVASOFT_JAWT_MD_H_ #include <windows.h> #include "jawt.h" #ifdef __cplusplus extern "C" { #endif /* * Microsoft Windows_ */
jawt_md.h (MacOS version)
_ */ | https://docs.oracle.com/en/java/javase/12/docs/specs/AWT_Native_Interface.html | CC-MAIN-2019-30 | refinedweb | 572 | 57.77 |
measure of risk for given probability distribution of return
Swift Manufacturing must choose between two asset purchases. The annual rate of return and the related probabilities given in the table.
Project 257 Project 432
Rate of return Probability Rate of return Probability
value of return
3. the standard deviation of the returns
4. the coefficient of variation of the returns
b. Construct the bar chart of each distribution of rates of return
c. Which project would you consider less risky? why?
Solution Preview
See the attached Excel file. Go to the cell to see the specific formulas used for calculations. The text pasted here may not print correctly as some symbols and tables may not print correctly.
Project 257 Project 432
Rate of return (X) Probability (P) (X-mu)^2*P Rate of return (X) Probability ...
Solution Summary
Answers several questions related to the measures of risk and return for a given probability distribution of return. The answer is explained in simple terms for easy understanding. | https://brainmass.com/business/beta-and-required-return-of-a-project/191910 | CC-MAIN-2017-39 | refinedweb | 166 | 50.33 |
Hi, I'm new in java. Can someone help me with this problem. I've attempted it and the code is as shown after the questions:
Question:
1. Create a new Movie class which has two properties, title and rating.
2. Create a new Cinema class, add method addMovieGoers which takes a collection of Humans and another-(Done)- method showMovie which does not take any arguments.(---DONE---) Your Cinema class should also have a setMovie method which takes a Movie as an argument.
3. When the addMovieGoers is called on a cinema instance the movie goers should be added to a private collection.
4. Add a new method to your family class that returns all family members.
5. In the main method of the Cinema class call a new static method that creates a family and a cinema then use the addMovieGoers method of the cinema to add the family members. Next create a new movie and use it to set the movie property of the cinema. Finally call cinema.showMovie.
Now, if you were careful your code may have executed without exception but there are quite a few loopholes in your code, to close them do the following.
1. In the showMovie method test whether or not the movie property has been set, if not throw an exception,<Pending> also add code to empty the Cinema whether the movie was shown or not.
2. In the setMovie method check that the movie title and rating have been set, if not throw an exception.
3. In the addMovieGoers method, check that the movie property has been set and if not throw an exception.
4. Also in the addMovieGoers method check that every member of the collection is a human and that they are old enough to watch the movie, if not throw an exception. Note that although the family has getMovieGoers method, you can't be sure it was used to build the collection.
5. Static main )Finally add another static method to the cinema class that demonstrates the usage of the cinema class. Include multiple scenarios to show how the exceptions work.
6. Remember about creating your own exceptions and passing them to the controlling module (here method with scenarios). After an exception occurs your code should stop execution of current scenario and go to another one.
MY CODE:
My code is as below and it's not working properly, so I need your help please.
//Movie class public class Movie { String movieRating; public Movie(String rated, String mtitle) { this.mrating=rated; this.title=mtitle; } public void setRating(String Rating) { movieRating = Rating; } // Get the rating public String getRating() { return movieRating; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } @Override public String toString() { return "Movie" +" title="+getTitle() + " rating="+getRating(); } public static void main(String args []) { Movie mv= new Movie("",""); mv.toString(); } private String title; private String mrating; } //Cinema class import java.util.*; import java.io.*; public class Cinema { public static final int maxRate = 3; public static final int minRate = 1; float cost; String Title,humans; ArrayList mGoers; public Cinema (String mtitle, float pounds) { this.Title=mtitle; this.cost = pounds; mGoers = new ArrayList(); } public float getcost (int people) { return cost * people; } //methods for adding movie goers which takes a collection of Humans public void addMovieGoers() { int minAge=18; Family fam = new Family("",0); fam.listAll(); // for (int cnt=0; cnt<mGoers.size(); cnt++) // { // Adult stud = (Adult) mGoers.get(cnt); // System.out.println(stud); // } } /** * Method check that the movie title and rating have been set, * if not throw an exception. */ public void setMovie(Movie movieNew) throws IOException { try { if (!isObjectEmpty(movieNew.getTitle()) && !isObjectEmpty(movieNew.getRating())) { System.out.println("The movie is called " +movieNew.getTitle()+ " and is rated " +movieNew.getRating()+ "."); } else { System.out.println("Movie title and rating not set"); } } catch(Exception e) { System.out.println("Title and Rating not Set"); } } public void showMovie() { try { Movie mv = new Movie("",""); String mRating = mv.getRating(); String mTitle = mv.getTitle(); if((mRating!=null)&& (mTitle!=null)) { System.out.println("Title is "+mTitle+" and is Rated " +mRating+""); } else { System.out.println("Either Title or Rating is missing"); } } catch(Exception e) { System.out.println("The Movie properties not set"); } finally { System.out.println("The movie is over."); } } /** * Checks is indiacated Object is empty. * restrictions for raiting type (rating must be >=1 and <=3) */ public boolean isObjectEmpty(Object obj) { int rating=1; boolean result = obj==null; if((rating<1)||(rating>3)) { System.out.println("The rating is out of bounds"); } else { System.out.println("Movie properly rated"); } return result; } public static void main(String args[]) { String temp; int rate; System.out.println("What's the Movie rating:"); BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); try { temp= stdin.readLine(); rate=Integer.parseInt(temp); if((rate<1)||(rate>3)) { System.out.println("Rate out of bounds!"); } else { System.out.println("The following can go for a movie:"); Cinema cin = new Cinema("PG",maxRate); cin.addMovieGoers(); } } catch(Exception e) { System.out.println("Movie not properly rated."); } finally { System.out.println("Cinema closed now."); } } } //Family class import java.util.*; import java.io.*; //import java.util.Iterator; public class Family extends Human { // String me,myPatner,famMembers; int myAge; // private Child ourChild; String rating; ArrayList familia; public Family(String name, int Age) { this.name=name; this.age=Age; // ourChild=new Child("",0); familia = new ArrayList(); } // protected String getPName(String pName) // { // return famMembers = pName; // // } public String getMovieGoers() { return rating; } //return all family members public void listAll() { for (int cnt=0; cnt<familia.size(); cnt++) { System.out.println(familia.get(cnt)); } } public void addHumans(Adult newAdult) { try { familia.add(newAdult); } catch (NullPointerException npe) { System.err.println("Error: " + npe); } } public static void main(String args[]) { Family familia = new Family("",0); Adult father = new Adult("Russel" , 32); Adult mother = new Adult("Lisa",28); // Populate the list using the .addHumans() methods familia.addHumans(father); familia.addHumans(mother); //calls listAll() method to display the family members familia.listAll(); } } //MovieRating class import java.util.HashMap; import java.util.Map; public class MovieRating { private Map ageMap = new HashMap(); public MovieRating() { ageMap.put("G", new Integer(18)); ageMap.put("PG", new Integer(16)); } public boolean getStatus(String rating, int age) { Integer rateAge = (Integer)ageMap.get(rating); if(rateAge != null) { int minAge = rateAge.intValue(); if (age < minAge ) { return false; } else { return true; } } return false; } }
I'll really appreciate your help/corrections. | https://www.daniweb.com/programming/software-development/threads/151504/movie-and-cinema-class | CC-MAIN-2017-51 | refinedweb | 1,051 | 50.12 |
This chapter includes the following sections:
About Creating an ADF Skin
Creating an ADF Skin File
Importing One or More ADF Skins Into the Current ADF Skin
Adding ADF Skins from an ADF Library JAR
An ADF skin defines the properties for the selectors that ADF Faces and ADF Data Visualization components expose.
Using the editor in JDeveloper, you can create a source file for an ADF skin. As a source file for an ADF skin is a type of CSS file, you could create it without using an editor. However, when you use the editor, associated configuration files get created (the first time that you create an ADF skin) or modified (when you create subsequent ADF skins). For information about these configuration files, see Configuration Files for an ADF Skin.
Create an ADF skin file in JDeveloper that defines how ADF Faces and ADF Data Visualization components render at runtime.
The ADF skin that you create must extend either one of the ADF skins that Oracle ADF provides or from an existing ADF skin that you created. The ADF skins that Oracle ADF provides vary in the level of customization that they define for ADF Faces and ADF Data Visualization components. For information about the inheritance relationship between the ADF skins that Oracle ADF provides, see Inheritance Relationship of the ADF Skins Provided by Oracle ADF . For information about the levels of customization in the ADF skins provided by Oracle ADF and for a recommendation about the ADF skin to extend, see ADF Skins Provided by Oracle ADF.
By default, the editors in JDeveloper create ADF skins for the
org.apache.myfaces.trinidad.desktop render kit. A render kit defines how ADF Faces components map to component tags that are appropriate for a particular client.
After you create an ADF skin, you can use the design editor and the other provided editors to modify the values for the selectors that the ADF Faces and ADF Data Visualization components expose. Otherwise, the ADF skin that you create defines the same appearance as the ADF skin from which it extends. See Working with Component-Specific Selectors .
If you create an ADF skin that extends from the Skyros ADF skin, you enable the design editor. This tab provides an overview pane where you can use controls to set properties for many frequently-used selectors. For information about using the design editor, see Working with the ADF Skin Design Editor.
You can create an ADF skin in JDeveloper.
To create an ADF skin in JDeveloper:
File Name: Enter a file name for the new ADF skin.
Directory: Enter the path to the directory where you store the CSS source file for the ADF skin or accept the default directory proposed by the editor.
Family: Enter a value for the family name of your skin.
You can enter a new name or specify an existing family name. If you specify an existing value, you may need to version ADF skins, as described in Versioning ADF Skins, to distinguish between ADF skins that have the same value for family.
The value you enter is set as the value for the
<family> element in the
trinidad-skins.xml where you register the ADF skin that you create. At runtime, the
<skin-family> element in an application's
trinidad-config.xml file uses this value to identify the ADF skin that an application uses. See Applying an ADF Skin to Your Web Application.
Use as the default skin family for this project: Deselect this checkbox if you do not want to make the ADF skin the default for your project immediately. If you select the checkbox, the
trinidad-config.xml file is updated, as described in What Happens When You Create an ADF Skin.
Show Latest Versions Only: Clear this checkbox to show all available versions of ADF skins.
Available Skins: Select the ADF skin that you want to extend. ADF Faces provides a number of ADF skins that you can extend. The list also includes any ADF skins that you created previously in this project. For a recommendation on the ADF skin to extend, see ADF Skins Provided by Oracle ADF.
Skin Id: A read-only field that displays a concatenation of the value you enter in File Name and the ID of the render kit (
desktop) for which you create your ADF skin. You select this value from the Extends list if you want to create another ADF skin that extends from this one.
JDeveloper writes the value to the
<id> element in the
trinidad-skins.xml file.
If you accepted the default value proposed for the Directory field, a file with the extension
.css is generated in a subdirectory of the
skins directory in your project.
An ADF skin that extends the Alta skin opens in the selectors editor, as illustrated in Figure 5-1. This selectors editor is also available if you create an ADF skin that extends from the Skyros ADF skin.
Figure 5-1 Newly-Created ADF Skin that Extends from Alta in the Selectors Editor
An ADF skin that extends the Skyros ADF skin opens in the design editor, as illustrated in Figure 5-2.
Figure 5-2 Newly-Created ADF Skin that Extends from Skryos in the Design Tab
The
trinidad-skins.xml file is modified to include metadata for the ADF skin that you create, as illustrated in Example 5-1, which shows entries for an ADF skin that extends from the Skyros family of ADF skins. Example 5-1 also contains values that specify the render kit and the resource bundle associated with this ADF skin. For information about resource bundles, see Working With Text in an ADF Skin.
If you select the Use as the default skin family for this project check box in the Create ADF Skin dialog, the
trinidad-config.xml file is modified to make the new ADF skin the default skin for your application. This means that if you run the application from JDeveloper, the application uses the newly-created ADF skin. See Applying an ADF Skin to Your Web Application. The following example shows a
trinidad-config.xml file that makes the ADF skin in Example 5-1 the default for an application.
<?xml version="1.0" encoding="windows-1252"?> <trinidad-config <skin-family>skin2</skin-family> </trinidad-config>
The source file for the ADF skin contains a comment and namespace references, as illustrated in the following example. These entries in the source file for the ADF skin distinguish the file from non-ADF skin files with the
.css file extension. A source file for an ADF skin requires these entries in order to open in the design or selectors editors for the ADF skin.
/**ADFFaces_Skin_File / DO NOT REMOVE**/ @namespace af ""; @namespace dvt "";
The first time that you create an ADF skin in your project, a resource bundle file (
skinBundle.properties) is generated, as illustrated in Figure 5-1. For information about using resource bundles, see Working With Text in an ADF Skin.
Example 5-1 trinidad-skins.xml File
<?xml version="1.0" encoding="windows-1252"?> <skins xmlns=""> .... <skin> <id>skin2.desktop</id> <family>skin2</family> <extends>skyros-v1.desktop</extends> <render-kit-id>org.apache.myfaces.trinidad.desktop</render-kit-id> <style-sheet-name>skins/skin2/skin2.css</style-sheet-name> <bundle-name>resources.skinBundle</bundle-name> </skin> </skins>
Import another ADF skin that is in your JDeveloper project into your ADF skin using the
@import rule.
This makes the style properties defined in the latter ADF skin available to your ADF skin. The following examples demonstrate the valid syntax to import an ADF skin (
skinA) into the current ADF skin:
/** Use the following syntax if skinA.css is in the same directory **/ @import "skinA.css"; @import url("skinA.css"); /** Use the following syntax if skinA.css is in another directory **/ @import "../skinA/skinA.css"; @import url("../skinA/skinA.css");
The
@import rule(s) must follow all
@charset rules and precede all other at-rules and rule sets in an ADF skin, as shown in the following example that imports two ADF skins into the current ADF skin:
@charset "UTF-8"; @import url("../skinA/skinA.css"); @import url("../skinB/skinB.css"); /**ADFFaces_Skin_File / DO NOT REMOVE**/ @namespace af ""; @namespace dvt ""; af|inputText{ background-color: Green; } ...
Add ADF skins that have been packaged in a JAR file into your JDeveloper project. When you add an ADF skin into your project, it is available to extend from when you create a new ADF skin.
The recommended type of JAR file to use to package an ADF skin is an ADF Library JAR file. For information about how to package an ADF skin into this type of JAR file, see Packaging an ADF Skin into an ADF Library JAR.
You can add ADF skins into your project that have been packaged in a JAR file.
To add an ADF skin from an ADF Library JAR:
The JAR file appears in the Classpath Entries list.
The ADF skin(s) that you add from the JAR file appear in the Extends list when you create a new ADF skin, as described in Creating an ADF Skin File. After you create a new ADF skin by extending an ADF skin that you added from a JAR file, the Extended Skins list in the selectors editor's Preview Pane displays the name of the ADF skin that you added. For example, in Figure 5-3 the
skin2.css ADF skin has been created by extending the ADF skin,
jarredskin.css, that was added into the project from a JAR file.
Figure 5-3 Imported ADF Skin in the Extended Skins List
Properties that have been defined in the ADF skin that you added appear with a blue upward pointing arrow in the Properties window. An information tip about the inheritance relationship displays when you hover the mouse over the property, as illustrated in Figure 5-4.
Figure 5-4 Property Inherited from an Imported ADF Skin | https://docs.oracle.com/middleware/12213/adf/develop-skin-editor/creating-source-files-adf-skin.htm | CC-MAIN-2020-10 | refinedweb | 1,669 | 62.38 |
09 January 2008 15:32 [Source: ICIS news]
MUMBAI (ICIS news)--The Indo-Russian titanium joint venture plans to commission its 40,000 tonne/year titanium dioxide (TiO2) plant at in Gopalpur in Orissa state in the fourth quarter of 2009, an official from the Indian company said on Wednesday.
The joint venture of India’s Saraf Agencies, Russia's state-run Vnesheconombank and Russian chemical trader Technochim Holding would source ilmenite feedstock from Indian Rare Earths Limited (IREL), the official told ICIS news.
"The final contract for raw material would be signed by the beginning of February," he added.
Saraf Agencies holds a 45% stake in the joint venture, with the remaining 55% being owned by Russian government, represented by three ministries, and Technochim Holding, the official said.
In the first phase, the companies would invest about Indian rupees (Rs) 12bn ($306.7m) to set up the TiO2 plant, he said.
“In the second phase, we would set up a 10,000 tonne/year titanium sponge plant, which would be commissioned by the fourth quarter of 2010,” he added.
According to the terms of contract, 75% of the TiO2 produced would be exported to ?xml:namespace>
Russia's Ti02 demand is estimated at about 55,000 tonne/year, of which around 80% is imported, mainly from
According to media reports, the Indo-Russian titanium project had hit a roadblock due to IREL’s refusal to enter a long-term supply contract with the promoters of the project.
IREL had said that it would supply the feedstock at market price and on the terms that it extends to other customers.
The company official, however, declined to comment on this issue.($1 = Rs39 | http://www.icis.com/Articles/2008/01/09/9091558/india-russia-jv-to-commission-tio2-plant-in-q4-09.html | CC-MAIN-2015-06 | refinedweb | 282 | 55.68 |
#include <iostream> #include <iomanip> using namespace std; int main() { const int PRICE = 5; int cost[PRICE], choice, ROW, COLUMN, ticket, seat, sum; const int row = 5, column = 10; const char full = '*'; const char empty = '#'; char seats[row][column]; cout << "Guadalupe Sanchez\n"; for(int count = 0; count < PRICE; count++) { cout << "Enter the price of Row " << (count + 1) << ":" << endl; cin >> cost[count]; } cout << "\t\tSeats\n"; cout << "\t 1 2 3 4 5 6 7 8 9 10\n"; for(int x = 1; x <= row; x++) { cout << "Row " << x; cout << "\t"; for (int y = 1; y <= column; y++) { seats[row][column] = empty; cout << " " << seats[row][column]; } cout << endl; } do { cout << "1. Purchase a ticket or tickets.\n"; cout << "2. View open seats.\n"; cout << "3. View total of ticket sales.\n"; cout << "4. Exit.\n"; cout << "Please enter an option: "; cin >> choice; switch (choice) { case 1: do { cout << "How many tickets would you like to purchase?:\n"; cin >> ticket; cout << "Which row would you like to sit?\n"; cin >> ROW; if(ticket > 1) cout << "What seats would you like?\n"; else cout << "What seat would you like?\n"; for(int count = 0; count < ticket; count++) { cout << "Enter seat in row:\n"; cin >> seat; } if (seats[ROW][seat] == '*') { cout << "Seat is sold out. Please enter a new seat.\n"; } else { sum =
This post has been edited by Atli: 12 May 2013 - 11:25 AM
Reason for edit:: Fixed the [code] ... [/code] tags. | http://www.dreamincode.net/forums/topic/320884-theater-seating-question/ | CC-MAIN-2016-22 | refinedweb | 240 | 89.99 |
Originaly published on. Republished with author’s permission.
If you’re reading this, dear Devop, you can probably remember a time before you were a Devop, or a Site Reliability Engineer, or whatever. Back to a time when you were a Systems Administrator, or a Unix Technician, or an Infrastructure Engineer; when your job involved switch blades and RAID cards, and you had to worry about LUN alignment and BIOS configurations.
Of course nobody is suggesting those tasks have disappeared but, with the advent of cloud computing, much of the yuckiness has been abstracted away from us. Instead of ‘remote hands’ we are presented with a nice clean API, gifting us the ability to build complex infrastructure…provided we have the skills to utilize it.
A corollary to this has been rise of OSS. Instead of black-box COTS products with expensive support contracts we are encouraged to use free software, with the source code hung out like fresh linen, inviting us to fix our own bugs and craft our own features. Inevitably then, our roles have transmuted. Increasingly we have to live up to the Dev part of our job title. Where once we wrote scripts we now write code; we can find ourselves unexpectedly in coding interviews, and writing tooling has become an essential skill.
But this is good news! It should be embraced. What it means in practicality is that we’ve had to imbibe knowledge from our developer cousins, to catch up with them in a relatively short period of time. We have quickly adopted their coding practices: pull requests, code reviews, coding standards…and testing.
Testing. Until recently, I’ll admit, tests were things that were bolted on once everything else was done. TDD was something that happened in text books. I’d embark on a test suite with a heavy heart and a dramatic sigh, and the afternoon would drag.
Of course I was wrong. I’m now a convert, a born again testafarian. The moment of epiphany came when I realised that, far from being a hindrance, a good test suite is absolutely indispensable. Its a small investment up-front, a down-payment for months or years of smooth maintenance and easy extendability.
This is particularly true when writing code that interacts with vendor APIs, such as AWS. As long as the API is well designed and well documented, we are easily able to mock the expected responses, and write whole applications without a single credit card detail being passed.
To illustrate this point let’s write a very small Ruby class to perform the simplest of tasks — listing DynamoDB tables. We’ll use RSpec and the frankly awesome response-stubbing powers of the AWS Ruby SDK to test two common scenarios: listing only tables with a given prefix, and handling paginated responses.
In true TDD fashion, lets write some tests first:
require_relative "../dynamo_lister.rb" require_relative "factories/dynamo_factory.rb" include DynamoFactory describe DynamoLister do context "list tables" do before :context do Aws.config[:dynamodb] = { stub_responses: { list_tables: list_tables_response(prefix: "test") } } end it "lists all tables" do expect(DynamoLister.list_all.length) .to eq(10) end it "lists all tables in given environment" do expect(DynamoLister.list_all(environment: "dev") .length) .to eq(0) end end end
Nothing too radical here. We are describing tests for the eminently useful
DynamoLister class. We wish to test listing all tables and then listing only those with a given prefix. (In the absence of any sort of namespacing, it is recommended practice to prefix DynamoDB tables with the environment in which they run.)
One thing that does beg explanation is the setting of
Aws.config[:dynamodb]. Here we are telling the AWS SDK to stub responses for — and only for — calls made to the
:list_tables method of any instance of the
Aws::DynamoDb::Client. Furthermore, we are telling it exactly what should be returned when this call is made, a
list_tables_response(prefix: test).
Of what provenance is this mythical
list_tables_response? Well, let me draw your attention, dear Devop, to the inclusion of the DynamoFactory module and its forebear, the
require_relative "factories/dynamo_factory.rb".
module DynamoFactory def list_tables_response(count: 10, prefix: "test") Aws::DynamoDB::Types::ListTablesOutput.new( table_names: Array.new(count) do |i| "#{prefix}_table_#{i}" end ) end end
This function returns a handcrafted
Aws::DynamoDB::Types::ListTablesOutput, populated with a list of names of DynamoDB tables. This is exactly the response that the AWS SDK returns when a
list_tables call is made. How do we know this? Because the AWS SDK docs are blessedly complete. We can easily identify the types and nested types that are expected to be returned from any API call. This happens to be a very simple example, we can see here that the
ListTablesOutput consists simply of a
table_names array of strings, and potentially a
last_evaluated_table_name, which we’ll come to in a moment.
The factory function takes 2 values:
:count, which is the number of tables to be included in the response, and
:prefix, a string which all of the tables will be prefixed with (i.e. the environment).
So, we now know that any call to
list_tables made against any instance of
Aws::DynamoDB::Client will result in a list of 10 tables (the default
:count value), all prefixed with “test” (the value we pass for
:prefix in the initial
stub_responses config). With this knowledge, the 2 test cases we have written should start to make sense. The first expects that our
DynamoLister will return 10 tables, the second that it will return 0 tables when we ask only for those prefixed with “dev”.
With the tests in place, we can go ahead and write a simple DynamoLister class:
require "aws-sdk-core" class DynamoLister class << self def list_all(environment: "*") Aws::DynamoDB::Client.new .list_tables .table_names .select { |t| /^#{environment}_/.match(t) } end end end
This very simply invokes the
list_tables call, and processes the returned list of
table_names, weeding out those which do not match the given prefix. The prefix defaults to all (*) so by default all tables are returned.
A quick run of
rspec will confirm that our tests pass.
However we can’t in all good conscience leave our test suite here.
The AWS docs tell us explicitly that:
The output from
ListTablesis paginated, with each page returning a maximum of 100 table names.
This means that, if we ever create more than 100 DynamoDB tables (which, across all environments, is wholly feasible) then our
DynamoLister will cease to work. We need to ensure it can handle paginated responses. Fortunately, we can easily figure out what a paginated response might look like, and cause our test suite to return one.
Recall from above that the
list_tables response may also include a
last_evaluated_table_name. Also note that the call to the
list_tables may include an
exclusive_start_table_name and you can probably start to figure out how to deal with paginated responses: if a response includes a
last_evaluated_table_name then we must make the call again, passing that value as an
exclusive_start_table_name.
Again, let’s write the test first:
context "paginated response" do it "lists all tables with paginated response" do @client = Aws::DynamoDB::Client.new( stub_responses: { list_tables: list_tables_paginated_response(count: 100) } ) expect(Aws::DynamoDB::Client) .to receive(:new) .and_return(@client) expect(@client).to receive(:list_tables) .with(no_args) .and_call_original expect(@client).to receive(:list_tables) .with(exclusive_start_table_name: "test_table_100") .and_return(list_tables_response(count: 10)) expect(DynamoLister.list_all.length) .to eq(110) end end
The assignment of a stubbed
Aws::DynamoDB::Client instance to
@client shows that you don’t have to stub responses globally, you can do so on a per-instance basis. The next thing we do here is to cause our doctored
@client object to be returned when we instantiate an
Aws::DynamoDB::Client object (i.e. the call to
:new).
Next we tell RSpec we expect that
@client to receive a call to
:list_tables with no arguments, and when it does we are to ‘call_original’. In this case calling original will result in our stubbed
list_tables_paginated_response(count: 100) being returned. Lets take a look at this response (which has been added to
dynamo_factory.rb):
def list_tables_paginated_response(count: 10, prefix: "test") Aws::DynamoDB::Types::ListTablesOutput.new( last_evaluated_table_name: "#{prefix}_table_#{count}", table_names: Array.new(count) do |i| "#{prefix}_table_#{i}" end ) end
It is almost identical to the non-paginated response function apart from the addition of a
last_evaluated_table_name, which in our case will be set to
test_table_100.
Back in the test above, the next expectation we state is that the
@client object will receive a second call to
:list_tables, with an
exclusive_start_table_name parameter. This time it is to return a standard, non-paginated response of 10 tables. Finally we state that we expect the total number of tables to be returned by the
DynamoLister.list_all call will be 110.
The last thing we need to do is amend the
DynamoLister itself to be aware of paginated responses by telling it to loop until
last_evaluated_table_name is nil:
class DynamoLister class << self def list_all(environment: "*") client = Aws::DynamoDB::Client.new resp = client.list_tables tables = resp.table_names while resp.last_evaluated_table_name resp = client.list_tables( exclusive_start_table_name: resp.last_evaluated_table_name ) tables.concat(resp.table_names) end tables.select { |t| /^#{environment}_/.match(t) } end end end
The last last thing we need to do is to run RSpec and check that all of our tests pass. Success!
The clear benefit to having written this test suite is that we were able to develop the DynamoLister and ensure it worked with over 100 tables without using any AWS resources. But a less obvious benefit is that we were able to completely refactor the code, and still ensure backwards functionality.
P.S. Would you like to learn how to build sustainable Rails apps and ship more often? We’ve recently published an ebook covering just that — “Rails Testing Handbook”. Learn more and download a free copy. | https://semaphoreci.com/community/tutorials/stubbing-the-aws-sdk | CC-MAIN-2019-13 | refinedweb | 1,639 | 55.13 |
Serial API: NOACK when sending with ACK failed
I assume, sending messages with ack are re-sent multiple times. Anyways I don't see how long this is being retried (which IS built in nicely in the RF24NETWORK library, if known).
But something I really think is important is the fact that we only know whether the radio message worked is, when we receive the answer. And the answer unfortunately is exactly what we have sent.
Wouldn't it be nice if we could have the sending node would print the message that was not acknowledged back to the serial console, but with a "2" in the ACK field? This way we could react to problems asynchronously, instead of waiting a couple of seconds for receiving what we have sent. Also it would make it easier for repeating nodes to tell the GW what happened.
Any thoughts about this?
I assume, sending messages with ack are re-sent multiple times
Currently, no.
You have to resend them yourself if you get no ack back in due time. We've been reluctant implementing resend-functionality in the library just because it would require buffering of outgoing non acked messages in a queue taking up lots of precious space.
Might be easier to implement as a per-sketch selectable feature now... But not top on my prio list.
From my perspective it is an absolute must to have this handled by the library, because it is a core feature of nRF24L01+'s and would be relatively easy to implement.
My home automation system should not need to care about the transport layer stuff, but just make use of a reliable transport layer and be notified if sending and retransmission fail consecutively. Even TCP/IP Stack connections just notify the application layer if the timed out.
Can you put this higher on the list and help if possible?
Edit: This is the library where i got this from and it automagically just works
Other libraries like the common RadioHead are doing this as well.
MySensors has a build in network ack feature similar to RF24Network's.
I can't find any automatic network resend functionality in RF24Network. Both MySensors and RF24Network utilises the automatic hardware ack functionality in the NRF24L01 radio though. But this only works between two nodes, not when messages needs several hops to reach their destination.
Implementing what you say is not hard but it has unwanted drawbacks. Here is a few I've considered.
We would either need to have a ...
Blocking send which waits and resends until ack arrives...
- What should we do with other incoming messages while blocking/resending? Throw away? If we start processing these in-the-middle we could get some interesting scenarios.
- Howto handle battery operated devices when radio link fails. They would stay awake/resending until battery is flat.
- Should we have a timeout? If so, the send could still fail.
...or queue outgoing messages with resending in the background:
- Takes space which we don't have.
- Increases complexity; Especially when you start thinking of message signing etc.
- How long should they be queued? We will have to drop them eventually.. Then we're back at square 1. Message never was sent. How do we notify sender/programmer about this?
- How do we handle timestamping of message (which we don't have to care about today)
I've also considered a blocking version of the request().. but it has the same drawbacks as the blocking send.
I could not find it in the code either, but I assume it is described as a feature on
New (2014): Network ACKs: Efficient acknowledgement of network-wide transmissions, via dynamic radio acks and network protocol acks.
The thoughts about the resend drawbacks are interesting. Especially while hopping over multiple nodes we seem to have no easy way to determine if the send was OK or FAILED. At least with hardware, because the neighbor node was okay and this is all the nrf provides.
Regarding the "lost or queued" messages while resending (and thus blocking completely and not running
loop(): Messages will be kept in serial buffer. But with 64 bytes we don't have space for many messages anyway. So we should time out after max 500ms of retries (which is a lot in radio world, as you know).
I saw that there acually is a arduino-driven solution for at leat retrying it a couple of times:
Do you think it would make sense to provide a new
bool send(MyMessage &msg, bool ack, uint8_t retries)for this case? ( I hope I am not overloading any existing function).
At least I will try this this tonight and give feedback about the increased reliability of my PCB-antenna nRF24L01+ modules.
Here is a patch of what I have done to the original
GatewayUtil.h:
SiLeX@SiLeX-PC /c/c/U/S/D/Arduino> diff libraries/MySensors/examples/SerialGateway/GatewayUtil.h SerialGateway/GatewayUtil.h -pbBc4 1 *** libraries/MySensors/examples/SerialGateway/GatewayUtil.h 2015-09-04 16:19:18.000000000 +0200 --- SerialGateway/GatewayUtil.h 2015-10-25 00:37:06.482032200 +0200 *************** void parseAndSend(MySensor &gw, char *co *** 114,129 **** --- 114,135 ---- } else { #ifdef WITH_LEDS_BLINKING gw.txBlink(1); #endif + + uint8_t resends = 0; + while (!ok && resends < 10) { ok = gw.sendRoute(msg); + resends++; + delay(random(5, 50)); if (!ok) { #ifdef WITH_LEDS_BLINKING gw.errBlink(1); #endif } } } + } } void setInclusionMode(boolean newMode) { if (newMode != inclusionMode) {
It is very aggressive for now and may be considered as a proof-of-conept only. This is running on the Gateway. The sensors would need another change. For me this fit's better as I am remote-controlling way more than I receive data from sensors.
Improvements are very welcome.
Nice start.. But this mod only resend if the first hop fails. You have to take the whole radio network into the picture with relay and final ack from destination node.
@hek If I understand correctly: This is what you try to achive by sending back a requested ACK. So this means, to take the whole network into picture, I would have to remember the message I sent (including the request for an ACK from the reciepient) and see if I receive the same message back from the node.
Unfortunately I don't have the recources to build a bigger network with relays. But I think this would be the same like I did here. But with checking the String and much more time. And much less buffering...
Hope someone want's to try this or something similar
In the BACnet protocol, the messages are not sent directly, but pushed into an internal state machine that remembers (some) of the previously messages sent (i.e.
memorize(_msg); send(_msg);).
The state machine also peeks incoming messages and can trigger a message re-send in case of a missed ACK.
the difference with MySensors is that all the messages are numbered, otherwise you would not know which message of the last N sent previously was ACKed,
but well.. ACKing the last similar message might be good enough.
Anyway @SiLeX : if you want to try, this is not that complicated, (if you don't take into account the STREAMs) it will just costs about (1 status byte + 1 timestamp + 1 frame size) x N ; for N frames memorized.
Suggested Topics
💬 MultiRF MultiVoltage ProtoBox
Capacitive sensor w/ transceiver
[SOLVED] No communication between node and gateway - NRF24
Ethernet gateway troubleshooting advice
Need volunteer: MyController 1.2.0-SNAPSHOT version with major provider changes and supports for ack
💬 EASY NRF24+PA+LNA for RFM69HCW footprint
nRF frequency and channels | https://forum.mysensors.org/topic/2189/serial-api-noack-when-sending-with-ack-failed | CC-MAIN-2018-30 | refinedweb | 1,267 | 65.52 |
Contents
Important Changes ............................................ 1 1 2 2 4 5 5 6 6 6 6 11 12 12 13 14 14 15 16 18 Introduction ........................................................ Education Tax Credits ....................................... Rules That Apply to Both Credits .................... Income Phaseout ............................................. Hope Credit ...................................................... Lifetime Learning Credit .................................. Choosing Which Credit To Claim .................... How To Claim the Credits ............................... Individual Retirement Arrangement (IRA) Provisions .................................................... Education IRA .................................................. Withdrawals From Traditional or Roth IRAs .... Student Loans .................................................... Interest Deduction ............................................ Cancellation of Loan ........................................ State Tuition Programs ..................................... Education Savings Bonds ................................. Employer-Provided Educational Assistance ... How To Get More Information .......................... Index ....................................................................
Publication 970
Cat. No. 25221V
Tax Benefits for Higher Education
For use in preparing
1999
Returns
Important Changes
Tax from recapture of education credits. You may owe this tax if you claimed an education credit on your 1998 tax return and, in 1999, you, your spouse if filing jointly, or your dependent received a refund of qualified tuition and related expenses, or tax-free educational assistance. See Recapture of credit under No double benefit.
Get forms and other information faster and easier by: COMPUTER • World Wide Web ➤ • FTP ➤ • IRIS at FedWorld ➤ (703) 321-8020 FAX • From your FAX machine, dial ➤ (703) 368-9694
See How To Get More Information in this publication.
Introduction
This publication explains the tax benefits for persons who are saving for or paying higher education costs for themselves and members of their families. It covers the following topics.
• The Hope credit and the lifetime learning credit. • Education individual retirement accounts (education
IRAs).
• Withdrawals from traditional or Roth IRAs for the
costs of higher education.
Education Tax Credits
The following two tax credits are available to persons who pay higher education costs.
• Interest paid on certain student loans. • The cancellation of certain student loans. • Qualified state tuition programs. • Savings bond interest used to pay the costs of
higher education.
• The Hope credit. • The lifetime learning credit.
Rules that apply to both credits are explained first, followed by explanations of rules that apply to each credit, choosing which credit to claim, and how to claim your credits. The last section includes an illustrated Form 8863. If a student receives a tax-free withdrawal from an education IRA in a particular tax year, none CAUTION of that student's expenses can be used as the basis of a higher education credit for that tax year. However, the student can waive the tax-free treatment. See Education IRA, later.
• Employer-provided educational assistance benefits.
Table 1 gives you a general comparison of some features of the different benefits. You may find it helpful in determining the benefits for which you are eligible. This publication does not cover the itemized deduction you may be able to claim for work-related educational expenses. Information on that deduction can be found in Publication 508, Tax Benefits for WorkRelated Education. This publication also does not cover scholarships that you may be able to exclude from your income. Information on scholarships can be found in Publication 520, Scholarships and Fellowships. You may be able to reduce the amount of your
!
TIP federal income tax withholding throughout the
year based on your estimated tax benefits for higher education. After you figure the amount of your estimated 2000 income, exclusions, deductions, and credit(s), see Publication 919, How Do I Adjust My Tax Withholding? Caution. You should check your withholding again during the year if there are changes to your personal or financial situation that would affect your expected 2000 tax liability, including your allowable higher education tax benefits.
Rules That Apply to Both Credits
The amount of each credit is determined by the amount you pay for qualified tuition and related expenses for students and the amount of your modified adjusted gross income. Education credits are subtracted from your tax but they are nonrefundable. This means if the credits are more than your tax, the excess is not refunded to you.
CAUTION
!
If you are married filing separately, you cannot claim the higher education credits.
Useful Items
You may want to see: Publication 508 520 525 550 590 Tax Benefits for Work-Related Education Scholarships and Fellowships Taxable and Nontaxable Income Investment Income and Expenses Individual Retirement Arrangements (IRAs) (Including Roth IRAs and Education IRAs)
Form (and Instructions) 8815 Exclusion of Interest From Series EE and I U.S. Savings Bonds Issued After 1989 8863 Education Credits (Hope and Lifetime Learning Credits) See How To Get More Information, near the end of this publication, for information about getting these publications and forms. Page 2
What expenses qualify. The credits are based on qualified tuition and related expenses you pay for yourself, your spouse, or a dependent for whom you claim an exemption on your tax return. The credits are allowed for qualified tuition and related expenses paid for an academic period beginning in the same year as the year the payment is made (but see Prepaid expenses, later).. Prepaid expenses. If you pay qualified tuition and related expenses for an academic period that begins in the first three months of the following year, you can use the prepaid amount in figuring your credit. For example, if you paid $2,000 in December 1999 for qualified tuition for the winter 2000 semester beginning in January 2000, you can use that $2,000 in figuring your 1999 credit. Payments with borrowed funds. You claim an education credit for the qualified tuition and related expenses paid with the proceeds of a loan. The credit is claimed in the year in which the expenses are paid, not in the year in which the loan is repaid.
Table 1. Highlights of Tax Benefits for Higher Education
Do not rely on this chart alone. It provides only general highlights of some of the differences among the benefits covered in this publication. See the text for definitions of ter ms and for more complete explanations. Caution: No double benefits are allowed. See the footnotes.
Hope credit (Education credit) Lifetime learning credit (Education credit) Education IRA1 Traditional and Roth IRAs1 Interest Paid on Student Loans Qualified State Tuition Programs Qualified U.S. Savings Bonds1 Employer’s Educational Assistance Program1
What is your benefit?2 What is the annual limit? What expenses qualify besides tuition and required enrollment fees?2
Tax credit (nonrefundable)
Withdrawals No 10% Deduction are tax additional to arrive at free tax on early adjusted withdrawal gross income $500 contribution per child under 18 Books, supplies, & equipment; Room and board if at least halftime attendance; Payments to qualified state tuition program Amount of qualifying expenses Books, supplies, & equipment; Room & board if at least half-time attendance 1999: $1,500 2000: $2,000 2001: $2,500 Books, supplies, & equipment; Room & board; Transportation; Other necessary expenses
Prepay future tuition expenses None
Interest is excludable from income Amount of qualifying expenses Payments to qualified state tuition programs; Payments to education IRAs
Employer benefits are excludable from income $5,250
Up to $1,500 per student N/A
Up to $1,000 per family
Books, supplies, & equipment; Room & board if at least half-time attendance
Books, supplies, & equipment
What education qualifies? What other conditions apply?
1st 2 years of undergraduate Can be claimed only for 2 years; Must be enrolled at least halftime in a degree program Applies to expenses paid and for school attendance after June 30, 1998
All undergraduate and graduate levels
Undergraduate level Taxdeferred earnings are taxed to beneficiary when withdrawn Applies only to qualified series EE bonds issued after 1989 or series I bonds Cannot also claim an education credit; Expires for courses beginning after December 31, 2001
Contributions not deductible; Cannot also contribute to qualified state tuition program or claim an education credit; Must withdraw assets at age 30 $95,000– $110,000; $150,000– $160,000 for joint returns
Must receive entire balance or begin receiving withdrawals by April 1 of year following year in which age 701⁄2 is reached N/A
Applies to the 1st 60 months’ interest; Must be enrolled at least halftime in a degree program
At what income range do benefits phase out?
1 2
$40,000–$50,000 $80,000–$100,000 for joint returns
$40,000– $55,000; $60,000– $75,000 for joint returns
N/A
1999: $53,100– $68,100; $79,650– $109,650 for joint returns
N/A
Any nontaxable withdrawal is limited to the amount that does not exceed qualifying educational expenses. You must generally reduce qualifying educational expenses by any tax-free income. You generally cannot use the same educational expense for figuring more than one benefit.
Page 3
What expenses do not qualify.. Dependent for whom you claim an exemption. You claim an exemption for a dependent if you list that person in the Exemptions section of your tax return. Eligible educational institution. An eligible educational institution is any college, university, vocational school, or other postsecondary educational institution eligible to participate in a student aid program administered by the Department of Education. It includes virtually all accredited, public, nonprofit, and proprietary (privately owned profit-making) postsecondary institutions. The educational institution should be able to tell you if it is an eligible educational institution. Academic period. An academic period includes a semester, trimester, quarter, or other period of study (such as a summer school session) as reasonably determined by an educational institution. No double benefit allowed. If you take a deduction for higher education expenses on your tax return, you cannot claim a credit for those same expenses. Adjustments to qualified expenses. If you pay higher education expenses with certain tax-free funds, you cannot claim a credit for those amounts. You must reduce the qualified expenses by the amount of any tax-free educational assistance. Tax-free educational assistance could include scholarships, Pell grants, employer-provided educational assistance, veterans' educational assistance, and any other nontaxable payments (other than gifts, bequests, or inheritances) received for educational expenses. Do not reduce the qualified expenses by amounts paid with the student's earnings, loans, gifts, inheritances, and personal savings. Also, do not reduce the qualified expenses by any scholarship reported as income on the student's return or any scholarship which, by its terms, cannot be applied to qualified tuition and related expenses. Refunds. Qualified tuition and related expenses do not include expenses that are refunded. If you receive a refund in the same year in which you paid the expenses, or in the following year, but before you file your tax return for the year you paid them, simply reduce the amount of the expenses by the amount of the refund received. If you receive the refund after you file your tax return, see Recapture of credit, next. Recapture of credit. If, after you file your tax return, you receive tax-free educational assistance for, or a refund of, an expense you used to figure a higher edPage 4
ucation credit on that return, you may have to recapture all or part of the credit. You must refigure your education credits as if the assistance or refund was received in the year the expenses were paid. Include the difference, if any, on your return for the year in which the assistance or refund was received. Include it on line 40 of your Form 1040 (line 25 of Form 1040A). Next to the line, enter the amount and “ECR.” Who can claim the credit. If there are higher education costs for your dependent child, either you or your child, but not both of you, can claim a credit for a particular year. If you claim an exemption for your child on your tax return, only you can claim a credit. If you do not claim an exemption for your child on your tax return, only your child can claim a credit. Expenses paid by others. If someone other than you, your spouse, or your dependent (such as a relative or former spouse) makes a payment directly to an eligible educational institution to pay for a student's qualified tuition and related expenses, the student is treated as receiving the payment from the other person. The student is treated as paying the qualified tuition and related expenses to the institution. Example. Ms. Allen makes a payment directly to an eligible educational institution in 1999 for her grandson's qualified tuition and related expenses. For purposes of claiming an education credit, the grandson is treated as receiving the money from Ms. Allen and, in turn, paying his qualified tuition and related expenses. Expenses paid by dependent. If you claim an exemption for your child on your tax return, treat any expenses paid by your child as if you had paid them. Include these expenses when figuring the amount of your Hope or lifetime learning credit. Qualified tuition and related expenses paid di-
TIP rectly to an eligible educational institution for
your dependent under a court-approved divorce decree are treated as paid by your dependent.
Income Phaseout
Your education credits are phased out (gradually reduced) if your modified adjusted gross income is between $40,000 and $50,000 ($80,000 and $100,000 in the case of a joint return). You cannot claim any higher education credits if your modified adjusted gross income is CAUTION $50,000 or more ($100,000 or more in the case of a joint return).
!
Modified adjusted gross income. For most taxpayers, modified adjusted gross income will be their adjusted gross income (AGI) as figured on their federal income tax return. However, you must make adjustments to your AGI if you excluded income earned abroad or from certain U.S. territories or possessions. If this applies to you, increase your AGI by the following amounts you excluded from your income.
1) Foreign earned income of U.S. citizens or residents living abroad. 2) Housing costs of U.S. citizens or residents living abroad. 3) Income from sources within Puerto Rico, Guam, American Samoa, or the Northern Mariana Islands. How the phaseout works. The phaseout (reduction) works on a sliding scale. The higher your modified adjusted gross income, the more your credits are reduced. You figure the reduction, if any, in Part III of Form 8863.
each eligible student for whom you pay at least $2,000 for qualified expenses. However, the credit may be reduced based on your modified adjusted gross income. See Income Phaseout, earlier. Example. Jon and Karen are married and file a joint tax return. For 1999, they claim an exemption for their dependent daughter on their tax return and their modified adjusted gross income is $70,000. Their daughter is in her sophomore (second) year of studies at the local university and Jon and Karen pay $4,300 in 1999 for her tuition costs. Jon and Karen, their daughter, and the local university meet all of the requirements for the Hope credit. Jon and Karen can claim a $1,500 Hope credit in 1999. This is the maximum amount allowed for 1999. How to figure the Hope credit. The Hope credit is figured in Parts I and III of Form 8863. An illustrated example using Form 8863 appears later.
Hope Credit
You may be able to claim a Hope credit of up to $1,500 for qualified tuition and related expenses paid for each eligible student. You can take into account expenses paid in 1999 for academic periods beginning after December 31, 1998, and before April 1, 2000. The credit can be claimed for only 2 years for each eligible student. Eligible student for the Hope credit. For purposes of the Hope credit, an eligible student is a student who meets all of the following requirements. 1) Has not completed the first 2 years of postsecondary education (generally, the freshman and sophomore years of college) as of the beginning of the year. 2) Is enrolled in a program that leads to a degree, certificate, or other recognized educational credential for at least one academic period beginning during the year. 3) Is taking at least half of the normal full-time work load for his or her course of study for at least one academic period beginning during the calendar year. 4) Is free of any federal or state felony conviction for possessing or distributing a controlled substance as of the end of the year. Completion of first 2 years. A student awarded 2 years of academic credit for postsecondary work completed prior to the beginning of the year has completed the first 2 years of postsecondary education. Any academic credit awarded solely on the basis of the student's performance on proficiency examinations is disregarded in determining whether the student has completed 2 years of postsecondary education. Half of normal full-time workload. The standard for what is half of the normal full-time work load is determined by each eligible educational institution. However, the standard may not be lower than standards for half-time established by the Department of Education under the Higher Education Act of 1965. Amount of credit. The amount of the Hope credit is 100% of the first $1,000 plus 50% of the next $1,000 of qualified tuition and related expenses you pay for each eligible student. The maximum amount of Hope credit you can claim in 1999 is $1,500 times the number of eligible students. You can claim the full $1,500 for
Lifetime Learning Credit
You may be able to claim a lifetime learning credit of up to $1,000 for qualified tuition and related expenses paid for all students enrolled in eligible educational institutions. You can take into account expenses paid in 1999 for academic periods beginning after December 31, 1998, and before April 1, 2000. The lifetime learning credit is different than the Hope credit in the following ways. 1) The lifetime learning credit is not based on the student's work load. It is allowed for one or more courses. 2) The lifetime learning credit is not limited to students in the first 2 years of postsecondary education. 3) Expenses for graduate-level degree work are eligible. 4) Expenses related to a course of instruction or other education that involves sports, games, hobbies, or other noncredit courses are eligible if they are part of a course of instruction to acquire or improve job skills. 5) There is no limit on the number of years for which the lifetime learning credit can be claimed for each student. 6) The amount you can claim as a lifetime learning credit does not vary (increase) based on the number of students for whom you pay qualified expenses. Amount of credit. The amount of the lifetime learning credit is 20% of the first $5,000 of qualified tuition and related expenses you pay for all students in the family. The maximum amount of lifetime learning credit you can claim for 1999 is $1,000 (20% × $5,000). However, that amount may be reduced based on your modified adjusted gross income. See Income Phaseout, earlier. Example. Bruce and Toni are married and file a joint tax return. For 1999, their modified adjusted gross income is $50,000. Toni is attending the community Page 5
college (an eligible educational institution) to earn credits towards an associate's degree in nursing; she already has a bachelor's degree in history and wants to become a nurse. In August 1999, Toni paid $2,000 for her fall 1999 semester. Bruce and Toni can claim a $400 (20% × $2,000) lifetime learning credit on their 1999 joint tax return. How to figure the lifetime learning credit. The lifetime learning credit is figured in Parts II and III of Form 8863. An illustrated example using Form 8863 appears later.
The eligible educational institution may ask for a completed Form W–9S, Request for Student's or Borrower's Social Security Number and Certification, or similar statement, to obtain the information needed to complete (2) above.
Illustrated Example
Dave and Valerie are married and file a joint tax return. For 1999, they claim exemptions for their two dependent children on their tax return, and their modified adjusted gross income is $72,000. Their son, Sean, will receive his bachelor's degree in psychology from the state college in May 2000. Their daughter, Corey, enrolled full-time at that same college in August 1998 to begin working on her bachelor's degree in physical education. In December 1998, Dave and Valerie paid $2,000 for each child's tuition for the winter 1999 semester. In July 1999, they paid $2,200 in tuition costs for each of them for the fall 1999 semester. Dave and Valerie, their children, and the college meet all of the requirements for the higher education credits. Because Sean is beyond the second (sophomore) year of his postsecondary education, his expenses do not qualify for the Hope credit. But, amounts paid for Sean's expenses in 1999 for academic periods beginning after 1998 and before April 1, 2000, qualify for the lifetime learning credit. Corey is in her first two (freshman and sophomore) years of postsecondary education and expenses paid for her in 1999 for academic periods beginning after 1998 and before April 1, 2000, qualify for the Hope credit. Dave and Valerie figure their total higher education credits for 1999, $1,940, as shown in the completed Form 8863. They can claim the full amount because their modified adjusted gross income is not more than $80,000. They carry the amount from line 18 of Form 8863 to line 44 of Form 1040, and they attach the Form 8863 to their return.
Choosing Which Credit To Claim
For each student, you can elect for any tax year only one of the credits or a tax-free withdrawal from an education IRA. (See Education IRA, later, for more information.) For example, if you elect to take the Hope credit for a child on your 1999 tax return, you cannot, for that same child, also claim the lifetime learning credit for 1999 or take a tax-free withdrawal from an education IRA for 1999. Lifetime learning credit after Hope credit. You can claim the Hope credit for the first 2 years of a student's postsecondary education and claim the lifetime learning credit for that same student in later tax years. More than one student. If you pay qualified expenses for more than one student in the same year, you can choose to take credits on a per-student, per-year basis. This means that, for example, you can claim the Hope credit for one student and the lifetime learning credit for another student in the same tax year.
How To Claim the Credits
You elect to claim education credits and you figure their amount by completing Form 8863. Use Part I for the Hope credit and Part II for the lifetime learning credit. In both parts, you enter the student's name and taxpayer identification number (usually a social security number) and the amount of qualified expenses paid in 1999. You then complete Part III to compute the amount to enter on line 44 of Form 1040 or line 29 of Form 1040A. Attach the completed Form 8863 to your return. An eligible educational institution (such as a college or university) that receives payment of qualified tuition and related expenses generally must issue Form 1098–T, Tuition Payments Statement, to each student by February 1, 2000. The information on Form 1098–T will help you determine whether you can claim an education tax credit for 1999. The following information should be included on the 1999 form. 1) The name, address, and taxpayer identification number of the educational institution. 2) The name, address, and taxpayer identification number of the student. 3) Whether the student was enrolled for at least half of the full-time academic workload. 4) Whether the student was enrolled exclusively in a graduate-level program. Page 6
Individual Retirement Arrangement (IRA) Provisions
You may be able to establish an education individual retirement account (education IRA or Ed IRA) to finance a child's qualified higher education expenses. In addition, you may be able to take withdrawals from other IRAs without paying the 10% additional tax on early withdrawals if you pay for qualified higher education expenses. Publication 590 has detailed information on all IRA accounts.
Education IRA
You may be able to contribute up to $500 cash each year to an education IRA for a child under age 18. Contributions to an education IRA are not deductible, but amounts deposited in the account grow tax free until withdrawn. Any individual (including the child) can contribute to a child's education IRA if his or her income is below a certain amount. There is no limit on the number of education IRAs that can be established designating a child
Form
8863
Dave and Valerie Jones Hope Credit
Education Credits (Hope and Lifetime Learning Credits)
See instructions on pages 3 and 4. Attach to Form 1040 or Form 1040A.
OMB No. 1545-1618
Department of the Treasury Internal Revenue Service
Attachment Sequence No.
1999
51 00 6543
Name(s) shown on return
Your social security number
987
Part I 1
(a) Student’s name First, Last
(b) Student’s social security number
(c) Qualified expenses (but do not enter more than $2,000 for each student). See instructions
(d) Enter the smaller of the amount in column (c) or $1,000
(e) Subtract column (d) from column (c)
(f) Enter one-half of the amount in column (e)
Corey, Jones 137 00 9642 2,000 1,000 1,000 500
2 3
Add the amounts in columns (d) and (f)
Add the amounts on line 2, columns (d) and (f) Lifetime Learning Credit
Part II 4
Caution: You cannot take the Hope credit and the lifetime lear ning credit for the same student. 5 6 7
Add the amounts on line 4, column (c), and enter the total Enter the smaller of line 5 or $5,000 Multiply line 6 by 20% (.20)
Part III 8 9 10 11 12 13
N
Allowable Education Credits
of 999 as , 1 ) of 29 nge ro er ha P b oc m ct t ve ubje o
(a) Student’s name Last First
2
1,000
500 3 1,500
(b) Student’s social security number
(c) Qualified expenses. See instructions
Sean
Jones
246
00
9731
2,200
5 6 7
2,200 2,200 440
(s
Add lines 3 and 7 Enter: $100,000 if married filing jointly; $50,000 if single, head of 100,000 9 household, or qualifying widow(er) 72,000 Enter the amount from Form 1040, line 34 (or Form 1040A, line 19)* 10 Subtract line 10 from line 9. If line 10 is greater than or equal to 28,000 11 line 9, stop; you cannot take any education credits Enter: $20,000 if married filing jointly; $10,000 if single, head of 20,000 12 household, or qualifying widow(er) If line 11 is greater than or equal to line 12, enter the amount from line 8 on line 14 and go to line 15. If line 11 is less than line 12, divide line 11 by line 12. Enter the result as a decimal (rounded to at least three places) Multiply line 8 by line 13 Enter your tax from Form 1040, line 40 (or Form 1040A, line 25) Enter the total, if any, of your credits from Form 1040, lines 41 and 42 (or from Form 1040A, lines 26 and 27) Subtract line 16 from line 15. If line 16 is greater than or equal to line 15, stop; you cannot take any education credits Education credits. Enter the smaller of line 14 or line 17 here and on Form 1040, line 44 (or Form 1040A, line 29)
Cat. No. 25379M
8
1,940
13 14 15 16 17 18
. 1,940 9,475 0 9,475 1,940
Form
14 15 16 17 18
*See Pub. 970 for the amount to enter if you are filing Form 2555, 2555-EZ, or 4563, or you are excluding income from Puerto Rico. For Paperwork Reduction Act Notice, see page 4.
8863
(1999)
Page 7
as the beneficiary. However, total contributions for the child during any tax year cannot be more than $500. See Contributions, later. If, for a year, withdrawals from an account are not more than a child's qualified higher education expenses at an eligible educational institution, the child will not owe tax on the withdrawals. See Withdrawals, later.
b) c)
Is made before the beneficiary reaches age 18. Would not result in total contributions for the tax year (not including rollover contributions) being more than $500.
4) Money in the account cannot be invested in life insurance contracts. 5) Money in the account cannot be combined with other property except in a common trust fund or common investment fund. 6) The balance in the account generally must be withdrawn within 30 days after the earlier of the following events. a) b) The beneficiary reaches age 30. The beneficiary's death. See When assets must be withdrawn, later. Designated beneficiary. The individual named in the document creating the trust or custodial account to receive the benefit of the funds in the account is the designated beneficiary. Qualified higher education expenses. These are expenses required for the enrollment or attendance of the designated beneficiary at an eligible educational institution. They include the following items. 1) Tuition and fees.
Education IRAs At a Glance
Do not rely on this chart alone. It provides only general highlights. See the text for definitions of terms in bold type and for more complete explanations. Question What is an education IRA? Answer An IRA that is set up to pay the qualified higher education expenses of a designated beneficiary. It can be opened in the United States at any bank or other IRS-approved entity that offers education IRAs. Any child who is under age 18. Generally, any individual (including the beneficiary) whose modified adjusted gross income for the year is less than $110,000 ($160,000 in the case of a joint return).
Where can it be established?
Who can an education IRA be set up for? Who can contribute to an education IRA?
2) The cost of books, supplies, and equipment. 3) Amounts contributed to a qualified state tuition program. (See State Tuition Programs, later.) 4) The cost of room and board if the designated beneficiary is at least a half-time student at an eligible educational institution. The term eligible educational institution was defined earlier under Rules That Apply to Both Credits for the education credits. A student is enrolled “at least halftime” if he or she is enrolled for at least half the full-time academic work load for the course of study the student is pursuing as determined under the standards of the school where the student is enrolled. For purposes of item (4) above, the expense for room and board is limited to one of the following two amounts. 1) The school's posted room and board charge for students living on campus. 2) $2,500 each year for students living off campus and not at home.
What Is an Education IRA?
An education IRA is a trust or custodial account created only for the purpose of paying the qualified higher education expenses (defined later) of the designated beneficiary of the account. When the account is established, the designated beneficiary must be a child under age 18. To be treated as an education IRA, the account must be designated as an education IRA when it is created. Account requirements. The document creating and governing the account must be in writing and must satisfy the following requirements. 1) The account must be created or organized in the United States. 2) The trustee or custodian must be a bank or an entity approved by the IRS. 3) The document must provide that the trustee or custodian can only accept a contribution that meets all of the following conditions. a) Page 8 Is in cash.
Contributions
Any individual (including the child for whose benefit the account is established) can contribute to a child's education IRA if the individual's modified adjusted gross income (defined earlier under Income Phaseout for the education credits) for the tax year is less than $110,000 ($160,000 in the case of a joint return). Contributions must be in cash, and you cannot contribute to an education IRA after the beneficiary reaches age 18.
Contributions can be made to one or several education IRAs for the same child provided that the total contributions are not more than the contribution limit (defined later) for a tax year.
Education IRA Contributions At a Glance
Do not rely on this chart alone. It provides only general highlights. See the text for definitions of terms in bold type and for more complete explanations. Question Are contributions deductible? Why should someone contribute to an education IRA? No. Earnings on the account grow tax free until withdrawn. Answer
What is the contribution $500 each year for each limit per child? child. What if more than one education IRA has been opened for the same child? What if more than one individual makes contributions for the same child? The annual contribution limit is $500 for each child, no matter how many education IRAs are set up for that child. The contribution limit is $500 per child, no matter how many individuals contribute.
Limit for each contributor. You can contribute up to $500 for each child for any year. This is the most you can contribute for the benefit of any one child for any year, regardless of the number of education IRAs set up for the child. However, this limit may be reduced as explained next. If your modified adjusted gross income (defined earlier) is between $95,000 and $110,000 (between $150,000 and $160,000 if filing a joint return), the $500 limit for each child is gradually reduced (see Figuring the limit, next). If your modified adjusted gross income is $110,000 or more ($160,000 or more if filing a joint return), you cannot contribute to anyone's education IRA. Figuring the limit. To figure the limit on the amount you can contribute for each child, multiply $500 by a fraction. The numerator (top number) is your modified adjusted gross income minus $95,000 ($150,000 if filing a joint return). The denominator (bottom number) is $15,000 ($10,000 if filing a joint return). Subtract the result from $500. This is the amount you can contribute for each child. Example. Paul, a single individual, had modified adjusted gross income of $96,500 for the year. For Paul, the maximum contribution for each child is reduced to $450, figured as follows. 1) $96,500 – $95,000 = $1,500 2) $1,500 ÷ $15,000 = 10% 3) 10% × $500 = $50 4) $500 – $50 = $450 Additional tax on excess contributions. A 6% excise tax applies each year to excess contributions that are in an education IRA at the end of the year. Excess contributions are the total of the following three amounts. 1) Contributions to any child's education IRA for the year that are more than $500 (or, if less, the total of each contributor's limit for the year, as discussed earlier). 2) All contributions to a child's education IRA for the year if any amount is also contributed during the year to a qualified state tuition program on behalf of the same child. However, amounts withdrawn from the education IRA to be contributed to the qualified state tuition program are not excess contributions. 3) Excess contributions for the preceding year, reduced by the total of the following two amounts: a) b) Withdrawals (other than those rolled over as discussed later) made during the year, and The contribution limit for the current year minus the amount contributed for the current year.
Can contributions other No. than cash be made to an education IRA? When must contributions No contributions can be stop? made to a child’s education IRA after he or she reaches age 18.
No contributions can be made to an education IRA on behalf of a child if any amount is conCAUTION tributed during the tax year to a qualified state tuition program on behalf of the same child.
!
Contribution limits. There are two yearly limits, one on the total amount that can be contributed for each designated beneficiary (child) and one on the amount that any individual can contribute for any one child for a year. Limit for each child. The total of all contributions to all education IRAs set up for the benefit of any one designated beneficiary (child) cannot be more than $500 for a year. This includes contributions (other than rollovers) to all the child's education IRAs from all sources. Rollovers are discussed under Rollovers and Other Tranfers, later.
Exceptions. The excise tax does not apply if the excess contributions (and any earnings on them) are withdrawn before the due date of the beneficiary's tax return (including extensions). If the beneficiary does not have to file a return, the tax does not apply if the Page 9
excess contributions (and the earnings) are withdrawn by April 15 of the year following the year the contributions are made. The withdrawn earnings must be included in the beneficiary's income for the year in which the excess contribution is made. The excise tax also does not apply to any rollover contribution.
education expenses (defined earlier) that the beneficiary has in the tax year.
Education IRA Withdrawals At a Glance
Do not rely on this chart alone. It provides only general highlights. See the text for definitions of terms in bold type and for more complete explanations. Question Answer Generally, yes, to the extent the amount of the withdrawal is not more than the designated beneficiary’s qualified higher education expenses. Yes. Amounts must be withdrawn when the designated beneficiary reaches age 30. Also, certain transfers to members of the designated beneficiary’s family are permitted. No.
Rollovers and Other Transfers
Assets can be rolled over from one education IRA to another. The designated beneficiary can be changed and the beneficiary's interest can be transferred to a spouse or former spouse because of divorce. Rollovers. Any amount withdrawn from an education IRA and rolled over to another education IRA for the benefit of the same beneficiary or a member of the beneficiary's family is not taxable. A rollover to an education IRA of a family member is not taxable only if that family member is under age 30. An amount is rolled over if it is paid to another education IRA within 60 days after the date of the withdrawal. Members of the beneficiary's family. The beneficiary's spouse and the following individuals (and their spouses) are members of the beneficiary's family.
Is a withdrawal from an education IRA to pay for a designated beneficiary’s qualified higher education expenses tax free? After the designated beneficiary completes his or her education at an eligible educational institution, may amounts remaining in the education IRA be withdrawn? Does the designated beneficiary need to be enrolled for a minimum number of courses to take a tax-free withdrawal?
• The beneficiary's child, grandchild, or stepchild. • A brother, sister, half brother, half sister,
stepbrother, or stepsister of the beneficiary.
• The father, mother, grandfather, grandmother,
stepfather, or stepmother of the beneficiary.
• A brother or sister of the beneficiary's father or
mother.
• A son or daughter of the beneficiary's brother or
sister.
• The beneficiary's son-in-law, daughter-in-law,
father-in-law, mother-in-law, brother-in-law, or sister-in-law.
Withdrawals not more than expenses. Generally, withdrawals are tax free if they are not more than the beneficiary's qualified higher education expenses for the tax year. Withdrawals more than expenses. Generally, a portion of the withdrawals is taxable to the beneficiary if the withdrawals are more than the beneficiary's qualified higher education expenses for the tax year. The taxable portion is the amount of the withdrawal that represents earnings that have accumulated tax free in the account. Figure the taxable portion as shown in the following steps. 1) Multiply the amount withdrawn by a fraction. The numerator is the total contributions in the account and the denominator is the total balance in the account before the withdrawal(s). 2) Subtract the amount figured in (1) from the total amount withdrawn during the year. This is the amount of earnings included in the withdrawal(s). 3) Multiply the amount of earnings figured in (2) by a fraction. The numerator is the qualified higher education expenses paid during the year and the denominator is the total amount withdrawn during the year.
CAUTION
!
Only one rollover per education IRA is allowed during the 12-month period ending on the date of the payment or withdrawal.
Changing the designated beneficiary. The designated beneficiary can be changed to a member of the beneficiary's family (defined earlier). There are no tax consequences if, at the time of the change, the new beneficiary is under age 30. Transfer because of divorce. If a spouse or former spouse receives an education IRA under a divorce or separation instrument, it is not a taxable transfer. After the transfer, the spouse or former spouse treats the education IRA as his or her own.
Withdrawals
The designated beneficiary of an education IRA can take withdrawals at any time. Whether the withdrawals are tax free depends, in part, on whether the withdrawals are more than the amount of qualified higher Page 10
4) Subtract the amount figured in (3) from the amount figured in (2). This is the amount the beneficiary must include in income. Example. You receive a $600 withdrawal from an education IRA to which $1,000 has been contributed. The balance in the IRA before the withdrawal was $1,200. You had $450 of qualified higher education expenses for the year. Using the steps above, you figure the taxable portion of your withdrawal as follows. 1) $600 × ($1,000 ÷ $1,200) = $500 2) $600 − $500 = $100 3) $100 × ($450 ÷ $600) = $75 4) $100 − $75 = $25 You must include $25 in income as withdrawn earnings not used for the expenses of higher education. You cannot take a deduction or credit for any educational expenses that you use as the basis CAUTION for a tax-free withdrawal from an education IRA. But see Waiver of tax-free treatment, next.
4) Included in income only because the beneficiary waived the tax-free treatment of the withdrawal (as explained earlier). 5) A return of an excess contribution (and any earnings on it) made before the due date of the beneficiary's tax return (including extensions). If the beneficiary does not have to file a return, the excess (and any earnings) must be withdrawn by April 15 of the year following the year of the contribution. The beneficiary must include in gross income for the year the contribution is made any income earned on the excess contribution. When assets must be withdrawn. Any assets remaining in an education IRA must be withdrawn when either one of the following two events occurs. 1) The designated beneficiary reaches age 30. In this case, the designated beneficiary must withdraw the remaining assets within 30 days after he or she reaches age 30. 2) The designated beneficiary dies before reaching age 30. In this case, the remaining assets must generally be withdrawn within 30 days after the date of death. The earnings that accumulated tax free in the account must be included in taxable income. You determine these earnings as shown in the following two steps. 1) Multiply the amount withdrawn by a fraction. The numerator is the total contributions in the account and the denominator is the total balance in the account before the withdrawal(s). 2) Subtract the amount figured in (1) from the total amount withdrawn during the year. The result is the amount of earnings included in the withdrawal. The beneficiary must include this amount in income. Exception for transfer to surviving spouse or family member. If an education IRA is transferred to a surviving spouse or other family member as the result of the death of the designated beneficiary, the education IRA retains its status. (For this purpose, family member was defined earlier under Rollovers.) This means the spouse or other family member can treat the education IRA as his or her own. There are no tax consequences as a result of the transfer.
!
Waiver of tax-free treatment. The designated beneficiary can waive the tax-free treatment of the withdrawal and elect to pay any tax that would otherwise be owed on the withdrawal. The beneficiary or the beneficiary's parents may then be eligible to claim a Hope credit or lifetime learning credit for qualified higher education expenses paid in that tax year. (See Education Tax Credits, earlier, to determine if all of the requirements for those credits are met.) Additional tax. Generally, if the beneficiary receives a taxable withdrawal, he or she also must pay a 10% additional tax on the amount included in income. Exceptions. The 10% additional tax does not apply to withdrawals described in the following list. 1) Paid to a beneficiary (or to the estate of the designated beneficiary) on or after the death of the designated beneficiary. 2). 3) Made because the designated beneficiary received: a) b) c) A qualified scholarship excludable from gross income, An educational assistance allowance, or Payment for the designated beneficiary's educational expenses that is excludable from gross income under any law of the United States.
Withdrawals From Traditional or Roth IRAs
You can make withdrawals from your traditional or Roth IRA for qualified higher education expenses. A traditional IRA is an IRA that is not a Roth IRA, SIMPLE IRA, or education IRA. You will owe income tax on at least part of the amount withdrawn, but you will not have to pay the 10% additional tax on early withdrawals. (Generally, if you make withdrawals from your traditional or Roth IRA before you reach age 591/2, you must pay a 10% additional tax on the early withdrawal.) Page 11
The exception applies only to the extent the withdrawal is not more than the scholarship, allowance, or payment.
Withdrawals for higher education expenses. Part (or all) of any withdrawal may not be subject to the 10% additional tax on early withdrawals. The part not subject to the tax is generally the amount that is not more than the qualified higher education expenses (defined later) for the year for education furnished at an eligible educational institution (defined earlier under Rules That Apply to Both Credits for the education credits). The education must be for you, your spouse, or the children or grandchildren of you or your spouse. When determining the amount of the withdrawal that is not subject to the 10% additional tax, include qualified higher education expenses paid with any of the following funds. 1) An individual's earnings. 2) A loan. 3) A gift. 4) An inheritance given to either the student or the individual making the withdrawal. 5) Personal savings (including savings from a qualified state tuition program). Do not include expenses paid with any of the following funds. 1) Tax-free withdrawals from an education IRA. 2) Tax-free scholarships, such as a Pell grant. 3) Tax-free employer-provided educational assistance. 4) Any tax-free payment (other than a gift, bequest, or devise) due to enrollment at an eligible educational institution. Qualified higher education expenses. Qualified higher education expenses are tuition, fees, books, supplies, and equipment required for the enrollment or attendance of a student at an eligible educational institution. In addition, if the individual is at least a half-time student, room and board are qualified higher education expenses.
You cannot deduct the interest on any later payments because they are after the 60-month period (October 1, 1994 – September 30, 1999). Your interest deduction for 1999 cannot be more than $1,500 and is subject to the limit described later. Include as interest. Loan origination fees (other than fees for services) and capitalized interest are deductible as student loan interest if all other requirements are met. Capitalized interest is accrued and unpaid interest on a qualified student loan that is capitalized by the lender and added to the outstanding principal balance of the loan. Claiming the deduction. This deduction is an adjustment to income, so you can claim it even if you do not itemize deductions on Schedule A (Form 1040). Complete the worksheet in your form instructions and enter the allowable amount on line 24 of Form 1040 or line 16 of Form 1040A. If you pay more than $600 in interest during the
TIP year to a single lender, you should receive a
statement at the end of the year from the lender showing the amount of interest. That information will help you complete your tax forms. Persons not eligible. You cannot claim the deduction in any tax year in which: 1) Your filing status is married filing a separate return, or 2) You are a dependent for whom an exemption is claimed on the tax return of another taxpayer. Qualified student loan. This is a loan you took out solely to pay qualified higher education expenses. The expenses must have been: 1) For you, your spouse, or a person who was your dependent when you took out the loan, 2) Paid or incurred within a reasonable time before or after you took out the loan, and 3) For education furnished during a period when the recipient of the education was an eligible student. Qualified higher education expenses. These expenses are the costs of attending an eligible educational institution, including graduate school. Generally, these costs include tuition, fees, room and board, books, equipment, and other necessary expenses, such as transportation. But you must reduce these costs by the following items. 1) Nontaxable employer-provided educational assistance benefits. 2) Nontaxable withdrawals from an education IRA. 3) U.S. savings bond interest that is nontaxable because you paid qualified higher education expenses. 4) Qualified scholarships that are nontaxable.
Student Loans
You may be able to deduct interest you pay on a qualified student loan. This applies to loan interest payments due and paid after 1997. And, if a student loan is canceled, you may not have to include any amount in income.
Interest Deduction
You may be able to deduct interest you pay on a qualified student loan even if you took out the loan before 1999. Regardless of when you took out the loan, you can deduct only interest paid during the first 60 months that interest payments are required. Example. You took out a qualified student loan in 1992. You made a payment on the loan every month, as required, beginning October 1, 1994. You can deduct the interest on your first nine payments for 1999. Page 12
5) Veterans' educational assistance benefits. 6) Any other nontaxable payments (other than gifts, bequests, or inheritances) received for educational expenses. Eligible educational institution. The term eligible educational institution generally has the same meaning as defined earlier under Rules That Apply to Both Credits for the education credits. For purposes of the student loan interest deduction, the term also includes an institution conducting an internship or residency program leading to a degree or certificate from an institution of higher education, a hospital, or a health care facility that offers postgraduate training. Eligible student. An eligible student is one who: 1) Is enrolled in a degree, certificate, or other program (including a program of study abroad that is approved for credit by the institution at which the student is enrolled) leading to a recognized educational credential at an eligible educational institution, and 2) Is carrying at least one-half the normal full-time work load for the course of study the student is pursuing. Loan from related person. You cannot deduct interest on a loan you get from a related person. Related persons include your brothers and sisters, half brothers and half sisters, spouse, ancestors (parents, grandparents, etc.), and lineal descendants (children, grandchildren, etc.). Related persons also include certain corporations, partnerships, trusts, and exempt organizations. Loan from employer plan. You cannot deduct interest on a loan made under a qualified employer plan or under a contract purchased under such a plan. Refinanced loan. If you refinance a qualified student loan, the new loan can also be a qualified student loan. But refinancing a loan does not extend the 60-month period described earlier. The 60-month period is based on the original loan. Maximum deduction. Your deduction for 1999 cannot be more than $1,500. This limit increases to $2,000 for 2000, and $2,500 for 2001 and later years. Limit on deduction. Your deduction may be limited, depending on the amount of your modified adjusted gross income. This limit applies if your modified adjusted gross income is more than $40,000 ($60,000 in the case of a joint return). If your modified adjusted gross income is $55,000 or more ($75,000 or more in the case of a joint return), you cannot claim a deduction. Modified adjusted gross income. For purposes of this deduction, modified adjusted gross income means AGI figured on your income tax return before this deduction for student loan interest and modified by adding back any of the following items you excluded or deducted from your income. 1) Foreign earned income of U.S. citizens or residents living abroad.
2) Housing costs of U.S. citizens or residents living abroad. 3) Income from sources within Puerto Rico, American Samoa, Guam, or the Northern Mariana Islands. Figuring the limit. To figure the limit, multiply your deduction (before the limit) by a fraction. The numerator is your modified adjusted gross income minus $40,000 ($60,000 in the case of a joint return). The denominator is $15,000. Subtract the result from your deduction (before the limit). This result is the amount you can deduct. Example 1. During 1999 you paid $900 interest on a qualified student loan. Your 1999 modified adjusted gross income is $70,000 and you are filing a joint return. You must reduce your deduction (before the limit) by $600, figured as follows. $70,000 - $60,000 = $600 $900 × $15,000 You can deduct $300 ($900 − $600). Example 2. The facts are the same as in Example 1 except that you paid $1,600 interest. Your maximum deduction for 1999 is $1,500. You must reduce your maximum deduction by $1,000, figured as follows. $70,000 - $60,000 = $1000 $1,500 × $15,000 You can deduct $500 ($1,500 − $1,000). You cannot deduct as interest on a student loan any amount you can deduct under any other CAUTION provision of the tax law (for example, as home mortgage interest).
!
Cancellation of Loan
Forgiveness of a student loan in return for certain community service is tax free. Qualifying loans. To qualify for tax-free treatment, your student loan must contain a provision that all or part of the debt will be canceled if you work for a certain period of time in certain professions for any of a broad class of employers. You do not have income if your student loan is later canceled because you agreed to this provision and performed the services required. The loan must have been made by one of the following. 1) The government — federal, state, or local, or an instrumentality, agency, or subdivision thereof. 2) A tax-exempt public benefit corporation that has assumed control of a state, county, or municipal hospital, and whose employees are considered public employees under state law. 3) An educational institution if the loan is made: a) Under an agreement with an entity described in (1) or (2) that provided the funds to the educational institution to make the loan, or Page 13
b)
Under a program of the educational institution that is designed to encourage students to serve in occupations or areas with unmet needs, and where the services required of the students are for or under the direction of a governmental unit or a tax-exempt section 501(c)(3) organization. In satisfying the community service requirement in (3)(b), the student must not provide services for the lender organization.
a waiver or payment of qualified higher educational expenses, or b) Make contributions to an account that is set up to meet the qualified higher educational expenses of a designated beneficiary of the account,
CAUTION
!
2) Requires all purchases or contributions to be made only in cash, 3) Prohibits the contributor and the beneficiary from directing the amount invested, 4) Allows a rollover or a change of beneficiary to be made only between members of the same family (defined earlier under Rollovers for the education IRA), and 5) Imposes a penalty on any refund of earnings that does not meet at least one of the following conditions. a) b) c) The amount is used for qualified higher educational expenses of the beneficiary. The refund is made because of the death or disability of the beneficiary. The refund is made because the beneficiary received (and the refund is not more than) a scholarship, a veterans educational assistance allowance, or another nontaxable payment (other than a gift, bequest, or inheritance) received for educational expenses..
• • • • • • •
Charitable. Religious. Educational. Scientific. Literary. Testing for public safety. Fostering national or international amateur sports competition (but only if none of its activities involve providing athletic facilities or equipment).
• The prevention of cruelty to children or animals.
Refinanced loan. If you refinanced a student loan with another loan from an educational institution or certain tax-exempt organizations, that loan can also qualify for tax-free treatment of canceled debt. This is true if the new loan was made: 1) To assist you in attending the educational institution, and 2) Under a program of the new lender that meets the conditions under (3)(b).
For more information on a specific state tuition program, contact the state or agency that established and maintains it.
Education Savings Bonds
You may be able to exclude from your gross income all or part of the interest you receive during the year on the redemption of qualified U.S. savings bonds if you pay qualified higher educational expenses during the same year.
CAUTION
!
If you are married, you can qualify for this exclusion only if you file a joint return with your spouse.
State Tuition Programs
Certain states and agencies maintain programs that allow people to purchase credits or certificates or make contributions to an account to pay for future education. Contributions to a qualified state tuition program are not deductible, and withdrawals are taxable only to the extent they are more than the amount contributed to the program. (See Withdrawals more than expenses for the education IRA.) A qualified state tuition program is one that is established and maintained by a state or agency and that: 1) Allows a person to: a) Buy tuition credits or certificates for a designated beneficiary who would then be entitled to
Qualified U.S. savings bonds. A qualified U.S. savings bond is a series EE bond issued after 1989 or a series I bond. The bond must be issued either in your name (as the sole owner) or in your and your spouse's names (as co-owners). You must be at least 24 years old before the bond's issue date. Qualified expenses. Qualified higher education expenses include the following items you pay for either yourself, your spouse, or a dependent for whom you claim an exemption. 1) Tuition and fees required to enroll at or attend an eligible educational institution (defined earlier under Rules That Apply to Both Credits for the education credits). Qualified expenses do not include ex-
Page 14
penses for room and board or for courses involving sports, games, or hobbies that are not part of a degree program. 2) Contributions to a qualified state tuition program. 3) Contributions to an education IRA. Expenses reduced by certain benefits. You must reduce your qualified higher educational expenses by the amount of any of the following benefits received by the student. 1) Tax-free scholarships (see Publication 520). 2) Tax-free withdrawals from an education IRA. 3) Any nontaxable payments (other than gifts, bequests, or inheritances) received for educational expenses or for attending an eligible educational institution, such as: a) b) c) Veterans' educational assistance benefits, Benefits under a qualified state tuition program, or Tax-free employer-provided educational assistance.
Use the worksheet in the instructions for line 9, Form 8815, to figure your modified AGI. If you claim any of the exclusion or deduction items (1) – (6) listed above, add the amount of the exclusion or deduction to the amount on line 5 of the worksheet, and enter the total on Form 8815, line 9, as your modified AGI. Because the deduction for interest expenses attributable to royalties and other investments CAUTION is limited to your net investment income, you cannot figure the deduction until you have figured this interest exclusion. Therefore, if you had interest expenses attributable to royalties and deductible on Schedule E (Form 1040), you must make a special computation of your deductible interest without regard to this exclusion to figure the net royalty income included in your modified AGI. See Royalties included in modified AGI under Education Savings Bond Program in chapter 1 of Publication 550.
!
Claiming the exclusion. Use Form 8815 to figure your exclusion. Attach the form to your Form 1040 or 1040A.
4) Any expenses used in figuring the Hope and lifetime learning credits. Amount excludable. If the total proceeds (interest and principal) from the qualified U.S. savings bonds you redeem during the year are not more than the qualified higher educational expenses for the year, you can exclude all of the interest. If the proceeds are more than the expenses, you. Modified adjusted gross income limit. The interest exclusion is phased out if your modified adjusted gross income is between $53,100 and $68,100 (between $79,650 and $109,650 for joint returns). You do not qualify for the interest exclusion if your modified adjusted gross income is equal to or more than the upper limit. Modified adjusted gross income, for purposes of this exclusion, is adjusted gross income (AGI) (line 18 of Form 1040A or line 33 of Form 1040) figured before the interest exclusion, and modified by adding back any: 1) Foreign earned income exclusion, 2) Foreign housing exclusion or deduction, 3) Exclusion of income for bona fide residents of American Samoa, 4) Exclusion for income from Puerto Rico, 5) Exclusion for adoption benefits received under an employer's adoption assistance program, and 6) Deduction for student loan interest.
Employer-Provided Educational Assistance
Educational assistance benefits you receive from your employer under an educational assistance program are tax free, up to $5,250 each year. This means your employer should not include the benefits with your wages, tips, and other compensation shown in box 1 of your Form W–2. You must reduce your deductible educational expenses by the amount of any tax-free eduCAUTION cational assistance benefits you received for those expenses.
!
Educational assistance program. To qualify as an educational assistance program, the plan must be written and meet certain other requirements. Your employer can tell you whether there is a qualified program where you work. Educational assistance. Tax-free educational assistance benefits include payments by your employer for tuition, fees and similar expenses, books, supplies, and equipment. The payments must be for undergraduatelevel courses that begin before January 1, 2002.. Page 15
3) Graduate-level courses normally taken under a program leading to a law, business, medical, or other advanced academic or professional degree.
• Tax Regs in English to search regulations and the
Internal Revenue Code (under United States Code (USC)).
about the site or with tax questions. Benefit over $5,250. If your employer gives you more than $5,250 of educational assistance benefits during the year, the amount over $5,250 is generally taxable. Your employer should include the taxable amount in your wages (box 1 of your Form W–2). However, if the payments also qualify as a working condition fringe benefit, your employer can exclude all of the payments from your wages. A working condition fringe benefit is a benefit which, had you paid for it, you could deduct as an employee business expense. For more information on fringe benefits, see chapter 4 of Publication 535, Business Expenses. Expenses paid with benefits. If you received tax-free benefits under your employer's qualified educational assistance program, you cannot take a deduction for qualified educational expenses. If you had educational expenses that you excluded from gross income under your employCAUTION er's educational assistance program, you cannot take the Hope credit or the lifetime learning credit for these same expenses.
• Digital Dispatch and IRS Local News Net (both located under Tax Info For Business) to receive our electronic newsletters on hot tax issues and news.
• Small Business Corner (located under Tax Info For
Business) to.
Phone. Many services are available by phone.
How To Get More Information
You can order free publications and forms, ask tax questions, and get more information from the IRS in several ways. By selecting the method that is best for you, you will have quick and easy access to tax help. select:
• Ordering forms, instructions, and publications. Call
1–800–829–3676 to order current and prior year forms, instructions, and publications.
• Asking tax questions. Call the IRS with your tax
questions at 1–800–829–1040. Frequently Asked Tax Questions (located under
Taxpayer Help & Ed) to find answers to questions you may have.
• A second IRS representative sometimes monitors
live telephone calls. That person only evaluates the IRS assistor and does not keep a record of any taxpayer's name or tax identification number.
• Forms & Pubs to download forms and publications
or search for forms and publications by topic or keyword.
• We sometimes record telephone calls to evaluate
IRS assistors objectively. We hold these recordings no longer than one week and use them only to measure the quality of assistance.
• Fill-in Forms (located under Forms & Pubs) to enter
information while the form is displayed and then print the completed form.
• We value our customers' opinions. Throughout this
year, we will be surveying our customers for their opinions on our service.
• Tax Info For You to view Internal Revenue Bulletins
published in the last few years. Page 16
Walk-in. You can walk in to many post offices, libraries, and IRS offices to pick up certain forms, instructions, and publications. Also, some libraries and IRS offices have:
• Eastern part of U.S. and foreign addresses:
Eastern Area Distribution Center P.O. Box 85074 Richmond, VA 23261–5074
• An extensive collection of products available to print
from a CD-ROM or photocopy from reproducible proofs. CD-ROM. You can order IRS Publication 1796, Federal Tax Products on CD-ROM, and obtain:
• The Internal Revenue Code, regulations, Internal
Revenue Bulletins, and Cumulative Bulletins available for research purposes.
• Current tax forms, instructions, and publications. • Prior-year tax forms, instructions, and publications. • Popular tax forms which may be filled in electronically, printed out for submission, and saved for recordkeeping.
Mail. You can send your order for forms, instructions, and publications to the Distribution Center nearest to you and receive a response within 10 workdays after your request is received. Find the address that applies to your part of the country..
• Western part of U.S.:
Western Area Distribution Center Rancho Cordova, CA 95743–0001
• Central part of U.S.:
Central Area Distribution Center P.O. Box 8903 Bloomington, IL 61702–8903
Page 17
Index
A
Assistance (See More information) Form 8863 ............................... 6 Form W–9S ............................. 6 Free tax services ................... 16 More information ................... 16
P
Publications (See More information)
C
Cancellation of student loan .. 13 Credits for higher education expenses ................................. 2
H
Help (See More information) Hope credit .............................. 5
S
Savings bonds ....................... State tuition programs ........... Student loans: Cancellation of ................... Interest on .......................... 14 14 13 12
D
Dependent ............................... 4
I
Individual retirement arrangement (IRA) provisions (See also Education IRA and IRA withdrawals) ........................... 6 Interest on savings bonds ..... 14 Interest on student loans ....... 12 IRA withdrawals ............... 10, 11
E
Education IRA: Contributions ........................ 8 Rollovers ............................ 10 Transfers ............................ 10 Withdrawals ....................... 10 Education savings bonds ...... 14 Educational assistance benefits .............................. 15 Eligible educational institution . 4 Employer-provided educational assistance .......................... 15
T
Tax credits for higher education ............................. 2 Tax help (See More information) TTY/TDD information ............ 16
L
Lifetime learning credit ............ 5 Loans for students ................. 12
U M
Members of the family ........... 10 Modified adjusted gross income for education credits ............ 4 Modified adjusted gross income for savings bond interest ... 15 Modified adjusted gross income for student loans ................ 13 U.S. savings bonds ............... 14
F
Family members .................... 10 Forgiveness of student loan .. 13 Form 1098–T ........................... 6 Form 8815 ............................. 15
W
Waiver of tax-free withdrawal from education IRA ............ 11 Withdrawals from IRAs .... 10, 11
Page 18
Tax Publications for Individual Taxpayers
General Guides 1 Your Rights as a Taxpayer 17 Your Federal Income Tax (For Individuals) 225 Farmer’s Tax Guide 334 Tax Guide for Small Business 509 Tax Calendars for 2000 553 Highlights of 1999 Tax Changes 595 Tax Highlights for Commercial Fishermen 910 Guide to Free Tax Services Specialized Publications 3 Armed Forces’ U.S. Government Civilian Employees Stationed Abroad 517 Social Security and Other Information for Members of the Clergy and Religious Workers 519 U.S. Tax Guide for Aliens 520 Scholarships and Fellowships 521 Moving Expenses 523 Selling Your Home 524 Credit for the Elderly or the Disabled 525 Taxable and Nontaxable Income 526 Charitable Contributions 527 Residential Rental Property 529 Miscellaneous Deductions
See How To Get More Information for a variety of ways to get publications, including by computer, phone, and mail.
530 Tax Information for First-Time Homeowners 531 Reporting Tip Income 533 Self-Employment Tax 534 Depreciating Property Placed in Service Before 1987 537 Installment Sales 541 Partnerships 544 Sales and Other Dispositions of Assets 547 Casualties, Disasters, and Thefts (Business and Nonbusiness)75 Pension and Annuity Income 584 Understanding the Collection Process IRS Will Figure Your Tax 968 Tax Benefits for Adoption 970 Tax Benefits for Higher Education 971 Innocent Spouse Relief 972 Child Tax Credit 1542 Per Diem Rates 1544 Reporting Cash Payments of Over $10,000
Form Number and Title
See How To Get More Information for a variety of ways to get forms, including by computer, fax, phone, and mail. For fax orders only, use the catalog numbers when ordering.
Catalog Number 11320 11330 11334 14374 11338 10424 11344 13339 11346 12187 25513 11359 11358 11327 12075 10749 12064 11329 11340 11360
Form Number and Title 2106 Employee Business Expenses 2106-EZ Unreimbursed Employee Business Expenses 2210 Underpayment of Estimated Tax by Individuals, Estates, and Trusts 2441 Child and Dependent Care Expenses 2848 Power of Attorney and Declaration of Representative 3903 Moving Expenses 4562 Depreciation and Amortization 4868 Application for Automatic Extension of Time To File U.S. Individual Income Tax Return 4952 Investment Interest Expense Deduction 5329 Additional Taxes Attributable to IRAs, Other Qualified Retirement Plans, Annuities, Modified Endowment Contracts, and MSAs 6251 Alternative Minimum Tax–Individuals 8283 Noncash Charitable Contributions 8582 Passive Activity Loss Limitations 8606 Nondeductible IRAs 8812 Additional Child Tax Credit 8822 Change of Address 8829 Expenses for Business Use of Your Home 8863 Education Credits
Catalog Number 11700 20604 11744 11862 11980 12490 12906 13141 13177 13329 13600 62299 63704 63966 10644 12081 13232 25379
1040 U.S. Individual Income Tax Return Sch A & B Itemized Deductions & Interest and Ordinary Dividends Sch C Profit or Loss From Business Sch C-EZ Net Profit From Business Sch D Capital Gains and Losses Sch D-1 Continuation Sheet for Schedule D Sch E Supplemental Income and Loss Sch EIC Earned Income Credit Sch F Profit or Loss From Farming Sch H Household Employment Taxes Sch J Farm Income Averaging Sch R Credit for the Elderly or the Disabled Sch SE Self-Employment Tax 1040A U.S. Individual Income Tax Return Sch 1 Interest and Ordinary Dividends for Form 1040A Filers Sch 2 Child and Dependent Care Expenses for Form 1040A Filers Sch 3 Credit for the Elderly or the Disabled for Form 1040A Filers 1040EZ Income Tax Return for Single and Joint Filers With No Dependents 1040-ES Estimated Tax for Individuals 1040X Amended U.S. Individual Income Tax Return
Page 19 | https://www.scribd.com/document/546069/US-Internal-Revenue-Service-p970-1999 | CC-MAIN-2018-47 | refinedweb | 12,118 | 53.61 |
08 October 2008 06:50 [Source: ICIS news]
SINGAPORE (ICIS news)--Yankuang Cathay Coal Chemicals' new 100,000 tonne/year ethyl acetate (EA) plant in Tengzhou City is on track to come on stream at the end of October, in line with the start-up of its new 300,000 tonne/year acetic acid line at the same site, a company official said on Wednesday.
?xml:namespace>
The start-up was in line with the progress of project works, the official said in Mandarin. The plants are located in ?xml:namespace>
Chinese domestic ethyl acetate prices fell further after the country’s Golden Week holidays due to poor demand, a supply glut and bearish sentiment in the wake of declining crude oil values, other producers said.
Ex-tank deals in eastern
($1 = CNY6.81)
For more | http://www.icis.com/Articles/2008/10/08/9162002/yankuang-cathays-new-ea-plant-start-up-on-track.html | CC-MAIN-2015-22 | refinedweb | 136 | 67.59 |
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.
Microcontroller Programming » scanf_P doesn't work
trying to get a simple printf scanf program to work and i am completely stumped. i searched the forum and its seems this has been a problem for others as well. i never found a solution. here is my code, if someone could please give me some insight. all it does is read a number from the terminal(putty) and blink an led at the entered frequency. ignore the lcd stuff. seems simple. also i loaded the printf scanf.c code from the tutorial and it works fine. connected the green and yellow wires on the ttl cable and it echos. the output of the code below is that it prints "please enter the frequency: thanks,the frequency is: 500" on a single terminal line and then repeats every 500ms (1/2s). it never pauses and reads like the tutorial does and the code is identical. please help.
gil's blinking led with keyboad input
#define F_CPU 14745600
#include <inttypes.h>
#include <avr/io.h>
#include <math.h>
#include <stdio.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
#include "../libnerdkits/uart.h"
int main() {
//pin definitions
//pb1=led anode
// led as output
DDRB |= (1<<PB1);
//set up lcd
lcd_init();
FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0,_FDEV_SETUP_WRITE);
lcd_write_string(PSTR("frequency from keyboard"));
// start up the serial port
uart_init();
FILE uart_stream = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
stdin = stdout = &uart_stream;
int16_t t = 500;
while(1){
// write message to serial port
printf_P(PSTR("\r\nplease enter the frequency: "));
scanf_P(PSTR("%d"), &t);
printf_P(PSTR("thanks, the frequency is: %d\n\r"), t);
lcd_clear_and_home();
lcd_write_string(PSTR("frequency is: "));
lcd_write_int16(t);
lcd_write_string(PSTR(" Hz "));
lcd_line_two();
lcd_write_string(PSTR("thanks"));
//turn on led
PORTB |= (1<<PB1);
//delay
delay_ms(t);
//turn off led
PORTB &= ~(1<<PB1);
//delay
delay_ms(t);
}
return 0;
}
forgot to say the led blinks as expected. thanks again gil
Hi Gil,
Your code looks like it should do what you expect, so I'm thinking there is something more subtle going on here. Could you post up your makefile for me, there are some compiler flags that need to be there for scan_f to work correctly. You can read all about it in the vscanf documentation
Humberto
thanks for the quick response. i'm pulling my hair out on this and will soon be bumping up agaist the write limit on my chip for loading programs. its like 1 million right, i'm close. here is the make file. its the same file that i compiled the tutorial with which worked. thanks for the help. g: keyboard-upload
keyboard
one more piece of information. i am using the usb cable to power my board. can't imagine that it matters, because again the tutorial runs fine.
I'm just following up on this thread, because its got me fairly confused. Have you figured out a solution yet?
Just as a precaution, delete all .o and .hex files both in libnerdkits and your project folder and recompile.
Another thing you could try is changing the optimization settings from -Os to -O0 or -O1, perhaps its your compiler that is optimizing away from part of the code.
Humberto - thanks for keeping this in mind. no solution yet. i will try and recompile tonight with your delete suggestions. i'm really new at this and don't know where the optimization settings are located. can you guide me? am i right in thinking that the program should pause at the scanf and wait for and read input until an enter is pressed. i did read the vscanf document but have to admit that all i really understood was the format string stuff.
Gil said:
i'm really new at this and don't know where the optimization settings are located.
i'm really new at this and don't know where the optimization settings are located.
They are in your MakeFile!!
GCCFLAGS=-g -Os -Wall -mmcu=atmega328p
Ralph
You are correct that scanf should block and wait for the input. Is that the way the sample program from the scanf tutorial behaves?
yes, the sample scanf program works fine. thats the confusing part, they are compiled with the exact same make file, with a "find and replace" on the filename obviously. i didn't have a chance to recompile yet but will soon. i feel that there is not much hope for this solution beacause of the sample scanf running as it should. you guys are awesome and the circutlab looks very cool, i can't wait to use it. gil
looking back at my posts i noticed something. see how my program editor (programers notepad) highlights some instructions in red. in the make file vfprintf is highlighted but vfscanf is not. is this a clue holmes?
i deleted the .o .h files in the project dir and i changed the optimization settings and got the same results. how do you recompile the libnerdkits dir?, i couldn't get new .o and .h files for delay, uart, and lcd. i think they were there when i got my kit.
Just use a generic MakeFile recompile the .c file!!
This is where using ProjectName (or Target or Whatever) comes in handy.
Just change the ProjectName to delay, uart, lcd etc. and type make!
GCCFLAGS=-g -Os -Wall -mmcu=atmega328p328p -F -b 115200 -P /dev/cu.PL2303-0000101D
LINKOBJECTS=../libnerdkits/delay.o ../libnerdkits/lcd.o ../libnerdkits/uart.o
ProjectName=delay
should i recompile these with the -Os changed to -O0 or -O1 as suggested by humberto?
also why does your make file have a $(projectname) and mine has just projectname? is this a problem for me?
I would certainly try it at least once with -00 (thats dash the letter O then the number 0). I too am not too hopeful of this solution working (because the sample program works for you) however compilers can be finicky things, especially when they are trying to optimize things. Id say its worth a shot.
i know this is an old post but i found the solution to my problem and want to share and know why. to recap - my simple printf scanf program above never puased at the scanf it just ran a loop printing "please enter the frequency: thanks,the frequency is: 500" and blinked the led. the sample nerdkits printf scanf program compiled in the same way ran fine " what is your age what is your favorite number". like i mentioned i used the usb to power my board. i got so sick of pluging and unplugging the usb under my desk to reset the board/mc that i installed in the nerdkits push button switch to cut only the usb power to reset the mc. guess what...the scanf in my program worked as expected. so...why??? the tutorial runs fine without the switch. it was print,scan,print,scan,print and mine was print,scan,print. i understand now that there maybe some intial signals sent over the usb once plugged in that could confuse my program but why the endless loop with scanf never pausing and why did the tutorial work. thanks gil
Please log in to post a reply. | http://www.nerdkits.com/forum/thread/2139/ | CC-MAIN-2019-04 | refinedweb | 1,221 | 74.69 |
libpfm_intel_nhm — support for Intel Nehalem core PMU
Synopsis
#include <perfmon/pfmlib.h> PMU name: nhm PMU desc: Intel Nehalem PMU name: nhm_ex PMU desc: Intel Nehalem EX
Description
The library supports the Intel Nehalem core PMU. It should be noted that this PMU model only covers the each core's PMU and not the socket level PMU. It is provided separately. Support is provided for the Intel Core i7 and Core i5 processors.
Modifiers
The following modifiers are supported on Intel Nehalem_INST_RETIRED:LATENCY_ABOVE_THRESHOLD event. This is an integer attribute that must be in the range [3:65535]. It is required for this event. Note that the event must be used with precise sampling (PEBS).
OFFCORE_RESPONSE event
The library is able to encode the OFFCORE_RESPONSE_0 event. This is a special event because it needs a second MSR (0x1a6) to be programmed for the event to count properly. Thus two values are necessary. The first value can be programmed on any of the generic counters. The second value goes into the dedicated MSR (0x1a6).
The OFFCORE_RESPONSE event is exposed as a normal event dedicated MSR (0x1a6).
When using an OS-specific encoding routine, the way the event is encoded is OS specific. Refer to the corresponding man page for more information.
Referenced By
libpfm(3). | https://dashdash.io/3/libpfm_intel_nhm | CC-MAIN-2022-33 | refinedweb | 213 | 59.9 |
.biz is a generic top-level domain (TLD) intended for domains to be used by businesses; the name is a phonetic spelling of the first syllable of "business." It was created to relieve some of the demand for the good domain names available in the .com top-level domain, and to provide an alternative to businesses whose preferred .com domain name had already been registered by another party. There are no specific legal or geographic qualifications to register a .biz domain name, except that it must be for "bona fide business or commercial use" (i.e. no personal or soap-box sites), and no cybersquatting, and the usual legal remedies for trademark infringement are applicable. It was created in 2001 along with several others as the first batch of new gTLDs approved by ICANN following the boom in interest in the internet in the 1990s. It is administered by NeuStar.
In contrast to the sunrise period of .info, .biz did not grant trademark owners first chance at registration, but instead used a procedure whereby they could file intellectual property claims in advance and then challenge any eventual registrant through a policy named "STOP" (Startup Trademark Opposition Policy). A number of domains were successfully obtained by trademark owners from other registrants through this policy; some of the more controversial cases, where generic words were taken over based on trademark claims in a process deemed "reverse hijacking" by critics[who?], included that of paint.biz and canadian.biz, the latter of which was reversed by a court decision.
It was announced on June 23, 2008 at the Paris, France ICANN 32nd International Public Meeting [1] that .biz had officially surpassed two million registrations worldwide. Consequently, the .biz TLD is now ranked as the tenth most registered TLD in the world.
The APWG 2008 Global Phishing Survey [2] identified the top twenty TLDs most subject to abuses, including phishing. The study concluded that .biz, along with .com and .info, were comparatively superior to many other leading TLDs in safety, and less subject to phishing attacks as demonstrated in statistical analysis. Per the study "Two gTLDs had notably better performance than the others: .INFO and .BIZ. Both the .INFO and .BIZ registries are known in the anti-abuse community to have proactive stances for dealing with phishing abuse within their namespaces."
Registrations are processed via accredited registrars.
Before ICANN approved of .biz as a top-level domain it was already in use by one or more alternative DNS root(s). This created the possibility of a .biz domain pointing to different IP addresses depending on the domain name server used. For this reason, NeuStar, which currently has control of the .biz root, requires that a DNS server be officially registered with them on their list of approved DNS servers before a domain registrar may register it in WHOIS as the DNS server for a particular domain.
stock | retire | vm
Why are we here?
All text is available under the terms of the GNU Free Documentation License
This page is cache of Wikipedia. History | http://wiki.xiaoyaozi.com/en/.biz.htm | crawl-002 | refinedweb | 509 | 56.15 |
I current computer or on another computer on their network.
Read All Processes
To read all processes running on a computer, use the .NET Process class located in the System.Diagnostics namespace. The GetProcesses method returns a string array of Process objects from the current (or a remote) computer. From this Process object, you can retrieve information about the process (Figure 1) such as its unique ID, its name, whether or not it is running, and how much memory that process is consuming.
Create a process class in order to add additional information about processes such as memory displayed in KB and MB.
You can pass a computer name to the GetProcesses method to have it attempt to read the processes running on that remote computer. You must have the appropriate network/computer permissions to read the processes on the other computer or this call will fail. Certain properties for the remote process cannot be filled in because they cannot be retrieved remotely.
The code in Listing 1 is what fills in the process information on the XAML screen shown in Figure 1. A Process array is initialized as a variable named List. Another variable, machineName, is used to hold the computer’s name that is entered into the text box on the form. A call to the GetProcesses method, with or without the computer name, returns the array of Process objects into the List variable. This string array is placed into the DataContext property of the ListView control to display all the properties from each Process object.
Create a Custom Process Class
There are a couple of things missing from the .NET Process class that you will probably want to add. First, the MachineName property is filled in with a period (.) when you are running on the current computer. You probably want this to be filled in with the current computer’s name. Another important property is whether or not this Process object was retrieved from a remote computer. A useful set of properties is the amount of memory used, expressed in both kilobytes and megabytes. All of these properties are easy to add by creating your own process class.
In order to work more effectively with a collection of processes, create a couple of new classes for your process listing service that can add additional properties and functionality. I have called mine PDSAProcess and PDSAProcessBase, but feel free to name them what you want. The PDSAProcess class inherits from the PDSAProcessBase class. The Base class implements the INotifyPropertyChanged event and adds two properties called LastMessage and LastException. These two properties can be used to keep track of the last display or error message and the last exception object when you are loading your process objects. You can look at the sample source code that comes with this article to see the implementation of the PDSAProcessBase class.
NOTE: Using INotifyPropertyChanged in XAML applications is a well-known design pattern and there are many articles on the subject, so I won’t cover it here.
Listing 2 shows the PDSAProcess class but with some of the normal property get/set methods not fully documented because they are all the same. You will see the full code for those properties that have special code in Listing 2. Notice the MachineName “property set” procedure calls the SetMachineName method. Also note the calculations for the MemoryInKb and MemoryInMb properties. The end result of creating the PDSAProcess class is shown in Figure 2. As you can see, there is better information displayed in the ListView control and the data displayed is sorted by the process name.
The PDSAProcess class also has many of the same properties as the .NET Process class, but the properties in this class raise the property changed event for use with XAML applications. Notice that the MachineName property shown in Figure 2 displays the current computer name rather than the period (.) that is reported by the .NET Process class. In the Set procedure of the MachineName property, a private method called SetMachineName is called to set the current computer name and to set the IsRemote property at the same time.
To load the custom process collection shown in Figure 2, click on the Load All Processes button shown on the form. The button’s Click event procedure fires and runs the code shown in the following code snippet:
private void btnLoad_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(txtMachineName.Text)) lstProcesses.DataContext = LoadAllProcesses(string.Empty); else lstProcesses.DataContext = LoadAllProcesses(txtMachineName.Text.Trim()); }
Check the text box to see if the user entered a computer name or not. If they have entered one, pass in the computer name to a method called LoadAllProcesses. If there is no computer name in the text box, pass in an empty string to the LoadAllProcesses method. Listing 3 shows the code to load the processes from the .NET Process object into a PDSAProcess object and then into an ObservableCollection of those PDSAProcess objects.
The code in the LoadAllProcesses method is fairly straight-forward. You are primarily moving the properties from the .NET Process class into the corresponding properties in the PDSAProcess class. The PDSAProcess class takes care of filling in the real computer name, and setting whether or not the computer is remote Be careful accessing the IsResponding property on the .NET Process class because it is not available on remote Process objects. In fact, if you try to access this property, an exception is thrown. That is why you see an “if” statement surrounding the code that attempts to access the IsResponding property.
The .NET GetProcesses method does not return the processes in any sort of order. Most users like to see sorted data, so it is probably a good idea to sort your process collection by the process name. Toward the bottom of Listing 3, you can see the following code snippet:
ProcessList = new ObservableCollection<PDSAProcess> (ProcessList.OrderBy(p => p.ProcessName));
This line of code uses the OrderBy method of the ObservableCollection class to create a new ObservableCollection of PDSAProcess objects. You pass a lambda expression (p => p.ProcessName) that informs the OrderBy method the name of the property by which to sort the collection.
The use of lambda expressions for ordering a collection turns what would otherwise be multiple lines of code into one.
A Process Manager Class
Instead of writing the code to load a ListView or other list-type of control, you might want to move the code you just wrote in the XAML window to a method in a class. Create a “Manager” class with the appropriate method to manage the process of creating a collection of process objects.
In preparation for creating a Manager class, move the IsRemote and MachineName properties from the PDSAProcess class into the PDSAProcessBase class. Move the SetMachineName method into the PDSAProcessBase class as well, because the set property of the MachineName property relies on this method. The Manager class you are going to write needs these two properties IsRemote and MachineName, so you might as well take advantage of inheritance by placing them into the Base class. The following code snippet shows the declaration for your new process manager class.
public class PDSAProcessManager : PDSAProcessBase { }
In this new process Manager class, you are going to add a method to retrieve memory instead of merely accessing the WorkingSet64 property of the .NET Process class. The WorkingSet64 property does not report the same amount of memory as the Task Manager utility and it can sometimes be confusing if you are looking at Task Manager, and then at your program, and you see different memory values. The method you are going to write will use a PerformanceCounter object in .NET to get the same value reported by Task Manager. The basics of how to retrieve memory using a performance counter is coded like this:
PerformanceCounter pc = null; long ret = -1; pc = new PerformanceCounter("Process", "Working Set - Private", prc.ProcessName); if(pc != null) ret = pc.RawValue;
Although the above code works, you may also need to pass in a computer name to the constructor of the PerformanceCounter if you are accessing a remote computer. Be aware that in order to access a performance counter on another computer, you need to either be a member of the Performance Monitor Users group or have administrative privileges on that computer.
Within the new PDSAProcessManager class, add a constant called PERF_COUNTER_MEMORY that holds the name of the performance counter you use. Add an ObservableCollection of PDSAProcess classes to hold the list of PDSAProcess objects as well. These two items are shown in the following code snippet:
private const string PERF_COUNTER_MEMORY = "Working Set - Private"; private ObservableCollection<PDSAProcess> _ProcessList = new ObservableCollection<PDSAProcess>(); public ObservableCollection<PDSAProcess> ProcessList { get { return _ProcessList; } set { _ProcessList = value; RaisePropertyChanged("ProcessList"); } }
You are now ready to write the LoadAllProcesses method in your process Manager class. Listing 4 shows the complete LoadAllProcesses method. As you will notice when you read the code, there are a few differences from the method you wrote earlier in this article.
The first difference is that you are using LINQ to create a collection of PDSAProcess objects. LINQ simplifies the process of creating a collection and is more concise than looping through the string array of .NET Process objects. However, if you like using a loop, you can modify this code to use the loop like you did in Listing 3. The second difference is the call to set the Memory property on the PDSAProcess object by calling a method named GetMemory.
Use LINQ to iterate to build your collection of process objects makes your code more readable and succinct.
The GetMemory method is where you attempt to get the PerformanceCounter object from either the local or the remote computer. You need to wrap up the creation of the PerformanceCounter object into a try…catch block in case you can’t access the performance counter for one of the reasons stated above. Also notice that you need a finally block when accessing a performance counter, in order to close and dispose of the performance counter object properly. You can wrap this call into a using block if you prefer. If, for some reason, you can’t access the performance counter to get the memory and you still want to have a valid memory value, and if the memory value is not set, get the WorkingSet64 property on the .NET Process object to set the return value from this method.
Now that you have this process Manager class written, you can use it as a view model on your WPF Window. (Some of the XAML has been removed in the code snippet below because it was not important to show it.) You create an XML namespace to reference the .NET namespace that the PDSAProcessManager is contained within. In the Window.Resources section of the XAML, create an instance of the PDSAProcessManager class and assign it a key of “viewModel”. Bind the ItemsSource property of the ListView to the ProcessList property in the PDSAProcessManager class. This is the collection of process objects retrieved when you call the LoadAllProcesses method. Finally, you bind each of the GridViewColumn objects in the ListView to each property of the PDSAProcess class that you wish to display.
<Window x: <Window.Resources> <vm:PDSAProcessManager x: </Window.Resources> <ListView ItemsSource="{Binding Path=ProcessList}"> <GridViewColumn DisplayMemberBinding="{Binding Path=Id}" /> <GridViewColumn DisplayMemberBinding="{Binding Path=ProcessName}" /> // MORE XAML HERE
To load the process collection into the ProcessList property, call the LoadAllProcesses method when the user clicks on the Load All Processes button shown in Figure 2. The MachineName property of the PDSAProcessManager class is bound to the TextBox shown on Figure 2. In the constructor of this main window, you bind the instance of the view model class created in the XAML to a variable called _ViewModel. Call the LoadAllProcesses method, as shown in the following code snippet:
public partial class MainWindow : Window { PDSAProcessManager _ViewModel = null; public MainWindow() { InitializeComponent(); _ViewModel = (PDSAProcessManager)this.Resources["viewModel"]; } private void btnLoad_Click(object sender, RoutedEventArgs e) { _ViewModel.LoadAllProcesses(); } }
The LoadAllProcesses method retrieves all the processes on the specified computer, builds the collection class, sorts the collection class, and sets the ProcessList property. As the ProcessList property is an ObservableCollection, any bindings to it are automatically updated when the collection changes. Thus, the ListView control is refreshed once it is set in the LoadAllProcesses method.
Summary
In this article, you learned how to read the list of processes running on the current computer or a remote computer using the .NET Process class. Create your own process class so that you can add additional properties and functionality that is not available with the .NET Process class. One feature you might want to add includes returning the amount of memory in both kilobytes and megabytes. Also, whether or not the process was read from a remote computer is very useful. Setting the computer name is more readable than displaying a period (.) as the .NET Process class does. Sorting the data using an ObservableCollection makes the display of the data easier for the user. Finally, wrapping the loading of process classes into a Manager class makes creating a list of processes quick and easy. | https://www.codemag.com/Article/1309031/Listing-Processes-Running-on-a-Computer | CC-MAIN-2020-10 | refinedweb | 2,196 | 53.92 |
it.
This demonstrates the flexibility and reusability of components, and how they can be used as powerful building blocks in your React apps.
OK, let's create a component! To start with, we'll keep things fairly simple and refactor the header HTML into its own component.
Modern React best practices recommend separating out each component in your app into a separate file. We'll be following this principle so, in your projects
/src/components/ folder, create a new file called
Header.js and open it in a text editor.
At the top of component files we always start by importing required libraries, other components (as we can nest components), and extra assets we need (e.g. styles). The
import statement is part of ES6 and allows us to keep our projects highly modular.
For our
<Header /> component, we only need to import the React library, which we can do with this statement:
import React, { Component } from 'react';
This imports the entire React library and makes it available via the
React variable. It also imports the
Component object directly so we can use it without having to specifically qualify it with a preceding
React. object reference.
In other words, if we didn't explicitly import the
Component object then we'd have to access it as follows:
React.Component
But because we imported
Component directly, we can just use it on its own without any reference to the
React variable. It doesn't matter which one you use, and is just down to preference.
Next, to actually create the component, we extend the
Component object to create a new class that defines our
<Header /> component. After the
import statement, type:
class Header extends Component { } export default App;
Here, we use an ES6 class as our component container. Classes are a great way to encapsulate all the code needed to describe your component.
You might have also noticed that the component file ends with an export statement. This, as you might expect, exports our component and makes it available to other files in our project.
At the very minimum, all React components are required to have a render method, which returns some markup. This could be HTML, other React components, or a mixture of both.
Add this inside your component class:
render() { return React.createElement( 'div', null, 'Hello there, this is a React component!' ); }
The
React.createElement() method creates an HTML element (a
<div> in this case) and adds some content to it. Save changes to
Header.js and open up
App.js.
To use a React component inside another component, we first need to import it, so add this to the list of import statements at the top of
App.js:
import Header from './Header';
Note how you don't need to add the
.js file extension as this is assumed. Also, because the
<Header /> component is in the same folder as our
<App /> component, we don't need to specify the full path.
In fact, if you try to use
import Header from './components/Header'; from inside
App.js, you'll get a compilation error.
We can now add the
<Header /> component inside the return statement just like any HTML element. However, there is a caveat. You can only return one top-level element inside a components return method.
So this is not allowed:
render() { return ( <div className="apples"></div> <div className="oranges"></div> ); }
If you want to return multiple elements then you have to wrap them all up inside a single wrapper element:
render() { return ( <div className="fruit"> <div className="apples"></div> <div className="oranges"></div> </div> ); }
So make sure that you add the
<Header /> component inside the
<div className="App"> element to avoid errors.
class App extends Component { render() { return ( <div className="App"> <Header /> <div className="App-header"> <h2>Discover Your Movie Mojo!</h2> </div> <p className="App-intro"> Welcome to the 'Movie Mojo' React app! </p> </div> ); } }
This will result in our
<Header /> component being rendered.
To complete the
<Header /> component, we'll remove the following block of HTML from
App.js and add it to
Header.js.
<div className="App-header"> <h2>Discover Your Movie Mojo!</h2> </div>
However, you might have noticed there is an issue. In
App.js the
<App /> component render method returns what looks like HTML. Yet in
Header.js there's just a single call to
React.createElement(). What's going on?
The answer is JSX. In
App.js we use JSX to write HTML-like syntax to define our component output. Compare this with our component definition for
Header.js.
React.createElement( 'div', null, 'Hello there, this is a React component!' );
This is how we have to write React components without JSX. In fact, under the hood, this is what JSX is compiled into before it can be rendered to the browser.
You're not required to use JSX at all for your React components; it is entirely up to you. But almost all components you'll come across will be written in JSX because it's just so much easier to write.
It's also highly readable for others new to your code. Imagine having to study a React project containing dozens of different components written in plain JavaScript!
So it should come as no surprise that we'll be using JSX for component definitions throughout the remainder of this tutorial series.
Go ahead and replace the
React.createElement() call with the JSX equivalent we copied from
App.js. Your
Header.js file should now look like this:
import React, { Component } from 'react'; class Header extends Component { render() { return ( <div className="App-header"> <h2>Discover Your Movie Mojo!</h2> </div> ); } } export default Header;
While JSX allows us much more flexibility in writing our components, bear in mind that it isn't actual HTML we're writing but an abstraction of it.
You can see this in the code snippet above. Notice in the
<div> tag we used
className rather than
class to indicate where we want to declare a CSS class? This is because all JSX is compiled down to pure JavaScript, and
class is a reserved word in ES6 JavaScript.
Let's also tweak the header styles. Open
App.css and edit the
.App-header CSS class to be:
.App-header { background-color: steelblue; height: 70px; padding: 20px; color: white; }
This updates the background color of the header and reduces the height.
So far, our
<Header /> component is static. That is, it displays fixed content that never changes. But components can be made to be dynamic and display content passed into them, via component props. This makes components suddenly much more useful as they become generic and reusable.
Think of component props as similar to HTML tags. For example, a
<div> tag may have attributes for
id,
class,
style and so on that enable us to assign unique values for that specific
<div> element.
We can do the same for React components. Say we didn't want our header to output the fixed text 'Discover Your Movie Mojo!' all the time. Wouldn't it be better if our header could display any text?
Unlike HTML attributes, we can name our component props whatever we like. Inside
App.js, update the
<Header /> tag to be:
<Header text="David's Movie Mojo App!" />
Then, update the
<Header /> component to use the
text prop.
<div className="App-header"> <h2>{this.props.text}</h2> </div>
This results in our header displaying whatever text is added to the
text prop in
App.js.
Let's take a closer look at how we referenced the
text prop inside
Header.js using:
{this.props.text}
The curly braces simply tell JSX that we have some JavaScript we want to evaluate. This distinguishes it from text. If we didn't use any curly braces, the string literal
this.props.text would be outputted, which isn't what we want.
The
this keyword refers to the
Header component class, and
props is an object that contains all the values passed in from
<Header text="David's Movie Mojo App!" />. In our case, the
props object contains just the one entry, but you can add as many as you like in practice.
Our
<Header /> component is now much more generic and doesn't contain a hard-coded string. This is a good practice when writing React components. The more generic you make them, the more reusable they are.
This is good news when developing future React apps as you can reuse components from previous projects so you don't have to write everything from scratch.
We used props above to pass a fixed string into the
<Header /> component, but props can also pass variables, function references, and state to components.
To send a variable via props, we could do something like this, where
headerText is a variable:
<Header text={headerText} />
There's a very useful tool available for the Chrome browser that lets you inspect information about your React app.
The default developer tools only allow you to view normal HTML elements, but with the React Developer Tools extension installed, you can navigate through all the React components in your app.
Once it's installed, open your browser inspector tools, and click on the newly available React tab. Notice that instead of HTML elements, you see the hierarchy of React components in your app. Click on the
<App /> component to select it.
Once selected, information about a component is displayed in the window to the right. The
<App /> component doesn't have any props and so the window is empty. But if you select the
<Header /> component inside
<App /> then you'll see the 'text' prop we passed in.
The React developer tools are very useful for debugging, especially when you get onto developing more complex React apps, so it's well worth getting used to using them on simpler apps.
You can also use the React developer tools to inspect your application state, which we'll get into in the next tutorial.
In this tutorial you learned how to split your app into separate components to make it more modular. Component props enable you to pass in values to individual components, similar to how you add attributes to HTML elements.
We also saw how to leverage new browser inspector tools to examine components and props data.
In part 3, we'll add state to our app to help us manage our data more effectively.… | https://www.4elements.com/blog/read/react_crash_course_for_beginners_part_2 | CC-MAIN-2019-18 | refinedweb | 1,738 | 65.12 |
Hi,
I want to subtract 1 year from my current year.
This is how i am getting the year
Qyearfull = "20" + fdmContext["PERIODNAME"][4:]
I want to get previous year.
I thought i could convert Qyearfull into integer and subtract 1 from it.
This is how i tried int(Qyearfull) but getting error.
Any idea how can i convert string into integer.
Regards
What error are you getting? Are you sure the string you are trying to convert only contains numeric characters? The method you are trying will work so long as the string is just a representation of a number
The value is 100 percent integer (2017). I have confirmed it by logging.
I even tried using this x = int('19') but getting an error.
Unfortunately i don't have python compiler at the moment. Getting just script fail error in log.
These are the classes i have added:
import string
import java.sql as sql
import java.lang as lang
Regards
This works for me, no need to import java classes
fdmAPI.logDebug("Period Name=:%s" % fdmContext["PERIODNAME"]) fullYear = int("20" + fdmContext["PERIODNAME"][4:]) fdmAPI.logDebug("Full Year Name=:%s" % fullYear)
or
YearMinus1 = int("20" + fdmContext["PERIODNAME"][4:])-1 fdmAPI.logDebug("Year -1=:%s" % YearMinus1)
Cheers
John
Thanks for help.
Regards | https://community.oracle.com/thread/4038803 | CC-MAIN-2018-17 | refinedweb | 213 | 69.28 |
DEBSOURCES
Skip Quicknav
sources / fragroute / 1.2-7.1 / bget592
/*
B G E T
Buffer allocator
Designed and implemented in April of 1972 by John Walker, based on the
Case Algol OPRO$ algorithm implemented in 1966.
Reimplemented in 1975 by John Walker for the Interdata 70.
Reimplemented in 1977 by John Walker for the Marinchip 9900.
Reimplemented in 1982 by Duff Kurland for the Intel 8080.
Portable C version implemented in September of 1990 by an older, wiser
instance of the original implementor.
Souped up and/or weighed down slightly shortly thereafter by Greg
Lutz.
AMIX edition, including the new compaction call-back option, prepared
by John Walker in July of 1992.
Bug in built-in test program fixed, ANSI compiler warnings eradicated,
buffer pool validator implemented, and guaranteed repeatable test
added by John Walker in October of 1995.
This program is in the public domain..
And buffers begat buffers, and links begat links, and buffer pools
begat links to chains of buffer pools containing buffers, and lo the
buffers and links and pools of buffers and pools of links to chains of
pools of buffers were fruitful and they multiplied and the Operating
System looked down upon them and said that it was Good.
INTRODUCTION
============
BGET is a comprehensive memory allocation package which is easily
configured to the needs of an application. BGET is efficient in
both the time needed to allocate and release buffers and in the
memory overhead required for buffer pool management. It
automatically consolidates contiguous space to minimise
fragmentation. BGET is configured by compile-time definitions,
Major options include:
* the <assert.h> mechanism; all these checks can be
turned off by compiling with NDEBUG defined, yielding a version of
BGET with minimal size and maximum speed.
The basic algorithm underlying BGET has withstood the test of
time; more than 25 years have passed since the first
implementation of this code. And yet, it is substantially more
efficient than the native allocation schemes of many operating
systems: the Macintosh and Microsoft Windows to name two, on which
programs have obtained substantial speed-ups by layering BGET as
an application level memory manager atop the underlying system's.
BGET has been implemented on the largest mainframes and the lowest
of microprocessors. It has served as the core for multitasking
operating systems, multi-thread applications, embedded software in
data network switching processors, and a host of C programs. And
while it has accreted flexibility and additional options over the
years, it remains fast, memory efficient, portable, and easy to
integrate into your program.
BGET IMPLEMENTATION ASSUMPTIONS
===============================
BGET is written in as portable a dialect of C as possible. The
only fundamental assumption about the underlying hardware
architecture is that memory is allocated is a linear array which
can be addressed as a vector of C "char" objects. On segmented
address space architectures, this generally means that BGET should
be used to allocate storage within a single segment (although some
compilers simulate linear address spaces on segmented
architectures). On segmented architectures, then, BGET buffer
pools may not be larger than a segment, but since BGET allows any
number of separate buffer pools, there is no limit on the total
storage which can be managed, only on the largest individual
object which can be allocated. Machines with a linear address
architecture, such as the VAX, 680x0, Sparc, MIPS, or the Intel
80386 and above in native mode, may use BGET without restriction.
GETTING STARTED WITH BGET
=========================
Although BGET can be configured in a multitude of fashions, there
are three basic ways of working with BGET. The functions
mentioned below are documented in the following section. Please
excuse the forward references which are made in the interest of
providing a roadmap to guide you to the BGET functions you're
likely to need.
Embedded Applications
---------------------
Embedded applications typically have a fixed area of memory
dedicated to buffer allocation (often in a separate RAM address
space distinct from the ROM that contains the executable code).
To use BGET in such an environment, simply call bpool() with the
start address and length of the buffer pool area in RAM, then
allocate buffers with bget() and release them with brel().
Embedded applications with very limited RAM but abundant CPU speed
may benefit by configuring BGET for BestFit allocation (which is
usually not worth it in other environments).
Malloc() Emulation
------------------
If the C library malloc() function is too slow, not present in
your development environment (for example, an a native Windows or
Macintosh program), or otherwise unsuitable, you can replace it
with BGET. Initially define a buffer pool of an appropriate size
with bpool()--usually obtained by making a call to the operating
system's low-level memory allocator. Then allocate buffers with
bget(), bgetz(), and bgetr() (the last two permit the allocation
of buffers initialised to zero and [inefficient] re-allocation of
existing buffers for compatibility with C library functions).
Release buffers by calling brel(). If a buffer allocation request
fails, obtain more storage from the underlying operating system,
add it to the buffer pool by another call to bpool(), and continue
execution.
Automatic Storage Management
----------------------------
You can use BGET as your application's native memory manager and
implement automatic storage pool expansion, contraction, and
optionally application-specific memory compaction by compiling
BGET with the BECtl variable defined, then calling bectl() and
supplying functions for storage compaction, acquisition, and
release, as well as a standard pool expansion increment. All of
these functions are optional (although it doesn't make much sense
to provide a release function without an acquisition function,
does it?). Once the call-back functions have been defined with
bectl(), you simply use bget() and brel() to allocate and release
storage as before. You can supply an initial buffer pool with
bpool() or rely on automatic allocation to acquire the entire
pool. When a call on bget() cannot be satisfied, BGET first
checks if a compaction function has been supplied. If so, it is
called (with the space required to satisfy the allocation request
and a sequence number to allow the compaction routine to be called
successively without looping). If the compaction function is able
to free any storage (it needn't know whether the storage it freed
was adequate) it should return a nonzero value, whereupon BGET
will retry the allocation request and, if it fails again, call the
compaction function again with the next-higher sequence number.
If the compaction function returns zero, indicating failure to
free space, or no compaction function is defined, BGET next tests
whether a non-NULL allocation function was supplied to bectl().
If so, that function is called with an argument indicating how
many bytes of additional space are required. This will be the
standard pool expansion increment supplied in the call to bectl()
unless the original bget() call requested a buffer larger than
this; buffers larger than the standard pool block can be managed
"off the books" by BGET in this mode. If the allocation function
succeeds in obtaining the storage, it returns a pointer to the new
block and BGET expands the buffer pool; if it fails, the
allocation request fails and returns NULL to the caller. If a
non-NULL release function is supplied, expansion blocks which
become totally empty are released to the global free pool by
passing their addresses to the release function.
Equipped with appropriate allocation, release, and compaction
functions, BGET can be used as part of very sophisticated memory
management strategies, including garbage collection. (Note,
however, that BGET is *not* a garbage collector by itself, and
that developing such a system requires much additional logic and
careful design of the application's memory allocation strategy.)
BGET FUNCTION DESCRIPTIONS
==========================
Functions implemented in this file (some are enabled by certain of
the optional settings below):
void bpool(void *buffer, bufsize len);
Create a buffer pool of <len> bytes, using the storage starting at
<buffer>. You can call bpool() subsequently to contribute
additional storage to the overall buffer pool.
void *bget(bufsize size);
Allocate a buffer of <size> bytes. The address of the buffer is
returned, or NULL if insufficient memory was available to allocate
the buffer.
void *bgetz(bufsize size);
Allocate a buffer of <size> <newsize> and preserving all existing data. NULL is
returned if insufficient memory is available to reallocate the
buffer, in which case the original buffer remains intact.
void brel(void *buf);
Return the buffer <buf>, <compact> is non-NULL, whenever
a buffer allocation request fails, the <compact> function will be
called with arguments specifying the number of bytes (total buffer
size, including header overhead) required to satisfy the
allocation request, and a sequence number indicating the number of
consecutive calls on <compact> attempting to satisfy this
allocation request. The sequence number is 1 for the first call
on <compact> for a given allocation request, and increments on
subsequent calls, permitting the <compact> function to take
increasingly dire measures in an attempt to free up storage. If
the <compact> function returns a nonzero value, the allocation
attempt is re-tried. If <compact> returns 0 (as it must if it
isn't able to release any space or add storage to the buffer
pool), the allocation request fails, which can trigger automatic
pool expansion if the <acquire> argument is non-NULL. At the time
the <compact> function is called, the state of the buffer
allocator is identical to that at the moment the allocation
request was made; consequently, the <compact> function may call
brel(), bpool(), bstats(), and/or directly manipulate the buffer
pool in any manner which would be valid were the application in
control. This does not, however, relieve the <compact> function
of the need to ensure that whatever actions it takes do not change
things underneath the application that made the allocation
request. For example, a <compact> function that released a buffer
in the process of being reallocated with bgetr() would lead to
disaster. Implementing a safe and effective <compact> mechanism
requires careful design of an application's memory architecture,
and cannot generally be easily retrofitted into existing code.
If <acquire> is non-NULL, that function will be called whenever an
allocation request fails. If the <acquire> function succeeds in
allocating the requested space and returns a pointer to the new
area, allocation will proceed using the expanded buffer pool. If
<acquire> cannot obtain the requested space, it should return NULL
and the entire allocation process will fail. <pool_incr>
specifies the normal expansion block size. Providing an <acquire>
function will cause subsequent bget() requests for buffers too
large to be managed in the linked-block scheme (in other words,
larger than <pool_incr> minus the buffer overhead) to be satisfied
directly by calls to the <acquire> function. Automatic release of
empty pool blocks will occur only if all pool blocks in the system
are the size given by <pool_incr>.
void bstats(bufsize *curalloc, bufsize *totfree,
bufsize *maxfree, long *nget, long *nrel);
The amount of space currently allocated is stored into the
variable pointed to by <curalloc>. The total free space (sum of
all free blocks in the pool) is stored into the variable pointed
to by <totfree>, and the size of the largest single block in the
free space pool is stored into the variable pointed to by
<maxfree>. The variables pointed to by <nget> and <nrel> <pool_incr>, or the negative thereof if
automatic expansion block releases are disabled. The number of
currently active pool blocks will be stored into the variable
pointed to by <npool>. The variables pointed to by <npget> and
<nprel> will be filled with, respectively, the number of expansion
block acquisitions and releases which have occurred. The
variables pointed to by <ndget> and <ndrel> will be filled with
the number of bget() and brel() calls, respectively, managed
through blocks directly allocated by the acquisition and release
functions.
void bufdump(void *buf);
The buffer pointed to by <buf> is dumped on standard output.
void bpoold(void *pool, int dumpalloc, int dumpfree);
All buffers in the buffer pool <pool>, previously initialised by a
call on bpool(), are listed in ascending memory address order. If
<dumpalloc> is nonzero, the contents of allocated buffers are
dumped; if <dumpfree>
==================
*/
#if 0
#define TestProg 20000 /* Generate built-in test program
if defined. The value specifies
how many buffer allocation attempts
the test program should make. */
#endif
#define SizeQuant 4 /* Buffer allocation size quantum:
all buffers allocated are a
multiple of this size. This
MUST be a power of two. */
#if 0
#define BufDump 1 /* Define this symbol to enable the
bpoold() function which dumps the
buffers in a buffer pool. */
#define BufValid 1 /* Define this symbol to enable the
bpoolv() function for validating
a buffer pool. */
#define DumpData 1 /* Define this symbol to enable the
bufdump() function which allows
dumping the contents of an allocated
or free buffer. */
#define BufStats 1 /* Define this symbol to enable the
bstats() function which calculates
the total free space in the buffer
pool, the largest available
buffer, and the total space
currently allocated. */
#define FreeWipe 1 /* Wipe free buffers to a guaranteed
pattern of garbage to trip up
miscreants who attempt to use
pointers into released buffers. */
#define BestFit 1 /* Use a best fit algorithm when
searching for space for an
allocation request. This uses
memory more efficiently, but
allocation will be much slower. */
#endif
#define BECtl 1 /* Define this symbol to enable the
bectl() function for automatic
pool space control. */
#include <stdio.h>
#ifdef lint
#define NDEBUG /* Exits in asserts confuse lint */
/* LINTLIBRARY */ /* Don't complain about def, no ref */
extern char *sprintf(); /* Sun includes don't define sprintf */
#endif
#include <assert.h>
#include <memory.h>
#ifdef BufDump /* BufDump implies DumpData */
#ifndef DumpData
#define DumpData 1
#endif
#endif
#ifdef DumpData
#include <ctype.h>
#endif
/* Declare the interface, including the requested buffer size type,
bufsize. */
#include "bget.h"
#define MemSize int /* Type for size arguments to memxxx()
functions such as memcmp(). */
/* Queue links */
struct qlinks {
struct bfhead *flink; /* Forward link */
struct bfhead *blink; /* Backward link */
};
/* Header in allocated and free buffers */
struct bhead {
bufsize prevfree; /* Relative link back to previous
free buffer in memory or 0 if
previous buffer is allocated. */
bufsize bsize; /* Buffer size: positive if free,
negative if allocated. */
};
#define BH(p) ((struct bhead *) (p))
/* Header in directly allocated buffers (by acqfcn) */
struct bdhead {
bufsize tsize; /* Total size, including overhead */
struct bhead bh; /* Common header */
};
#define BDH(p) ((struct bdhead *) (p))
/* Header in free buffers */
struct bfhead {
struct bhead bh; /* Common allocated/free header */
struct qlinks ql; /* Links on free list */
};
#define BFH(p) ((struct bfhead *) (p))
static struct bfhead freelist = { /* List of free buffers */
{0, 0},
{&freelist, &freelist}
};
#ifdef BufStats
static bufsize totalloc = 0; /* Total space currently allocated */
static long numget = 0, numrel = 0; /* Number of bget() and brel() calls */
#ifdef BECtl
static long numpblk = 0; /* Number of pool blocks */
static long numpget = 0, numprel = 0; /* Number of block gets and rels */
static long numdget = 0, numdrel = 0; /* Number of direct gets and rels */
#endif /* BECtl */
#endif /* BufStats */
#ifdef BECtl
/* Automatic expansion block management functions */
static int (*compfcn) _((bufsize sizereq, int sequence)) = NULL;
static void *(*acqfcn) _((bufsize size)) = NULL;
static void (*relfcn) _((void *buf)) = NULL;
static bufsize exp_incr = 0; /* Expansion block size */
static bufsize pool_len = 0; /* 0: no bpool calls have been made
-1: not all pool blocks are
the same size
>0: (common) block size for all
bpool calls made so far
*/
#endif
/* Minimum allocation quantum: */
#define QLSize (sizeof(struct qlinks))
#define SizeQ ((SizeQuant > QLSize) ? SizeQuant : QLSize)
#define V (void) /* To denote unwanted returned values */
/* End sentinel: value placed in bsize field of dummy block delimiting
end of pool block. The most negative number which will fit in a
bufsize, defined in a way that the compiler will accept. */
#define ESent ((bufsize) (-(((1L << (sizeof(bufsize) * 8 - 2)) - 1) * 2) - 2))
/* BGET -- Allocate a buffer. */
void *bget(requested_size)
bufsize requested_size;
{
bufsize size = requested_size;
struct bfhead *b;
#ifdef BestFit
struct bfhead *best;
#endif
void *buf;
#ifdef BECtl
int compactseq = 0;
#endif
assert(size > 0);
if (size < SizeQ) { /* Need at least room for the */
size = SizeQ; /* queue links. */
}
#ifdef SizeQuant
#if SizeQuant > 1
size = (size + (SizeQuant - 1)) & (~(SizeQuant - 1));
#endif
#endif
size += sizeof(struct bhead); /* Add overhead in allocated buffer
to size required. */
#ifdef BECtl
/* If a compact function was provided in the call to bectl(), wrap
a loop around the allocation process to allow compaction to
intervene in case we don't find a suitable buffer in the chain. */
while (1) {
#endif
b = freelist.ql.flink;
#ifdef BestFit
best = &freelist;
#endif
/* Scan the free list searching for the first buffer big enough
to hold the requested size buffer. */
#ifdef BestFit
while (b != &freelist) {
if (b->bh.bsize >= size) {
if ((best == &freelist) || (b->bh.bsize < best->bh.bsize)) {
best = b;
}
}
b = b->ql.flink; /* Link to next buffer */
}
b = best;
#endif /* BestFit */
while (b != &freelist) {
if ((bufsize) b->bh.bsize >= size) {
/* Buffer is big enough to satisfy the request. Allocate it
to the caller. We must decide whether the buffer is large
enough to split into the part given to the caller and a
free buffer that remains on the free list, or whether the
entire buffer should be removed from the free list and
given to the caller in its entirety. We only split the
buffer if enough room remains for a header plus the minimum
quantum of allocation. */
if ((b->bh.bsize - size) > (SizeQ + (sizeof(struct bhead)))) {
struct bhead *ba, *bn;
ba = BH(((char *) b) + (b->bh.bsize - size));
bn = BH(((char *) ba) + size);
assert(bn->prevfree == b->bh.bsize);
/* Subtract size from length of free block. */
b->bh.bsize -= size;
/* Link allocated buffer to the previous free buffer. */
ba->prevfree = b->bh.bsize;
/* Plug negative size into user buffer. */
ba->bsize = -(bufsize) size;
/* Mark buffer after this one not preceded by free block. */
bn->prevfree = 0;
#ifdef BufStats
totalloc += size;
numget++; /* Increment number of bget() calls */
#endif
buf = (void *) ((((char *) ba) + sizeof(struct bhead)));
return buf;
} else {
struct bhead *ba;
ba = BH(((char *) b) + b->bh.bsize);
assert(ba->prevfree == b->bh.bsize);
/* The buffer isn't big enough to split. Give the whole
shebang to the caller and remove it from the free list. */
assert(b->ql.blink->ql.flink == b);
assert(b->ql.flink->ql.blink == b);
b->ql.blink->ql.flink = b->ql.flink;
b->ql.flink->ql.blink = b->ql.blink;
#ifdef BufStats
totalloc += b->bh.bsize;
numget++; /* Increment number of bget() calls */
#endif
/* Negate size to mark buffer allocated. */
b->bh.bsize = -(b->bh.bsize);
/* Zero the back pointer in the next buffer in memory
to indicate that this buffer is allocated. */
ba->prevfree = 0;
/* Give user buffer starting at queue links. */
buf = (void *) &(b->ql);
return buf;
}
}
b = b->ql.flink; /* Link to next buffer */
}
#ifdef BECtl
/* We failed to find a buffer. If there's a compact function
defined, notify it of the size requested. If it returns
TRUE, try the allocation again. */
if ((compfcn == NULL) || (!(*compfcn)(size, ++compactseq))) {
break;
}
}
/* No buffer available with requested size free. */
/* Don't give up yet -- look in the reserve supply. */
if (acqfcn != NULL) {
if (size > exp_incr - sizeof(struct bhead)) {
/* Request is too large to fit in a single expansion
block. Try to satisy it by a direct buffer acquisition. */
struct bdhead *bdh;
size += sizeof(struct bdhead) - sizeof(struct bhead);
if ((bdh = BDH((*acqfcn)((bufsize) size))) != NULL) {
/* Mark the buffer special by setting the size field
of its header to zero. */
bdh->bh.bsize = 0;
bdh->bh.prevfree = 0;
bdh->tsize = size;
#ifdef BufStats
totalloc += size;
numget++; /* Increment number of bget() calls */
numdget++; /* Direct bget() call count */
#endif
buf = (void *) (bdh + 1);
return buf;
}
} else {
/* Try to obtain a new expansion block */
void *newpool;
if ((newpool = (*acqfcn)((bufsize) exp_incr)) != NULL) {
bpool(newpool, exp_incr);
buf = bget(requested_size); /* This can't, I say, can't
get into a loop. */
return buf;
}
}
}
/* Still no buffer available */
#endif /* BECtl */
return NULL;
}
/* BGETZ -- Allocate a buffer and clear its contents to zero. We clear
the entire contents of the buffer to zero, not just the
region requested by the caller. */
void *bgetz(size)
bufsize size;
{
char *buf = (char *) bget(size);
if (buf != NULL) {
struct bhead *b;
bufsize rsize;
b = BH(buf - sizeof(struct bhead));
rsize = -(b->bsize);
if (rsize == 0) {
struct bdhead *bd;
bd = BDH(buf - sizeof(struct bdhead));
rsize = bd->tsize - sizeof(struct bdhead);
} else {
rsize -= sizeof(struct bhead);
}
assert(rsize >= size);
V memset(buf, 0, (MemSize) rsize);
}
return ((void *) buf);
}
/* BGETR -- Reallocate a buffer. This is a minimal implementation,
simply in terms of brel() and bget(). It could be
enhanced to allow the buffer to grow into adjacent free
blocks and to avoid moving data unnecessarily. */
void *bgetr(buf, size)
void *buf;
bufsize size;
{
void *nbuf;
bufsize osize; /* Old size of buffer */
struct bhead *b;
if ((nbuf = bget(size)) == NULL) { /* Acquire new buffer */
return NULL;
}
if (buf == NULL) {
return nbuf;
}
b = BH(((char *) buf) - sizeof(struct bhead));
osize = -b->bsize;
#ifdef BECtl
if (osize == 0) {
/* Buffer acquired directly through acqfcn. */
struct bdhead *bd;
bd = BDH(((char *) buf) - sizeof(struct bdhead));
osize = bd->tsize - sizeof(struct bdhead);
} else
#endif
osize -= sizeof(struct bhead);
assert(osize > 0);
V memcpy((char *) nbuf, (char *) buf, /* Copy the data */
(MemSize) ((size < osize) ? size : osize));
brel(buf);
return nbuf;
}
/* BREL -- Release a buffer. */
void brel(buf)
void *buf;
{
struct bfhead *b, *bn;
b = BFH(((char *) buf) - sizeof(struct bhead));
#ifdef BufStats
numrel++; /* Increment number of brel() calls */
#endif
assert(buf != NULL);
#ifdef BECtl
if (b->bh.bsize == 0) { /* Directly-acquired buffer? */
struct bdhead *bdh;
bdh = BDH(((char *) buf) - sizeof(struct bdhead));
assert(b->bh.prevfree == 0);
#ifdef BufStats
totalloc -= bdh->tsize;
assert(totalloc >= 0);
numdrel++; /* Number of direct releases */
#endif /* BufStats */
#ifdef FreeWipe
V memset((char *) buf, 0x55,
(MemSize) (bdh->tsize - sizeof(struct bdhead)));
#endif /* FreeWipe */
assert(relfcn != NULL);
(*relfcn)((void *) bdh); /* Release it directly. */
return;
}
#endif /* BECtl */
/* Buffer size must be negative, indicating that the buffer is
allocated. */
if (b->bh.bsize >= 0) {
bn = NULL;
}
assert(b->bh.bsize < 0);
/* Back pointer in next buffer must be zero, indicating the
same thing: */
assert(BH((char *) b - b->bh.bsize)->prevfree == 0);
#ifdef BufStats
totalloc += b->bh.bsize;
assert(totalloc >= 0);
#endif
/* If the back link is nonzero, the previous buffer is free. */
if (b->bh.prevfree != 0) {
/* The previous buffer is free. Consolidate this buffer with it
by adding the length of this buffer to the previous free
buffer. Note that we subtract the size in the buffer being
released, since it's negative to indicate that the buffer is
allocated. */
register bufsize size = b->bh.bsize;
/* Make the previous buffer the one we're working on. */
assert(BH((char *) b - b->bh.prevfree)->bsize == b->bh.prevfree);
b = BFH(((char *) b) - b->bh.prevfree);
b->bh.bsize -= size;
} else {
/* The previous buffer isn't allocated. Insert this buffer
on the free list as an isolated free block. */;
b->bh.bsize = -b->bh.bsize;
}
/* Now we look at the next buffer in memory, located by advancing from
the start of this buffer by its size, to see if that buffer is
free. If it is, we combine this buffer with the next one in
memory, dechaining the second buffer from the free list. */
bn = BFH(((char *) b) + b->bh.bsize);
if (bn->bh.bsize > 0) {
/* The buffer is free. Remove it from the free list and add
its size to that of our buffer. */
assert(BH((char *) bn + bn->bh.bsize)->prevfree == bn->bh.bsize);
assert(bn->ql.blink->ql.flink == bn);
assert(bn->ql.flink->ql.blink == bn);
bn->ql.blink->ql.flink = bn->ql.flink;
bn->ql.flink->ql.blink = bn->ql.blink;
b->bh.bsize += bn->bh.bsize;
/* Finally, advance to the buffer that follows the newly
consolidated free block. We must set its backpointer to the
head of the consolidated free block. We know the next block
must be an allocated block because the process of recombination
guarantees that two free blocks will never be contiguous in
memory. */
bn = BFH(((char *) b) + b->bh.bsize);
}
#ifdef FreeWipe
V memset(((char *) b) + sizeof(struct bfhead), 0x55,
(MemSize) (b->bh.bsize - sizeof(struct bfhead)));
#endif
assert(bn->bh.bsize < 0);
/* The next buffer is allocated. Set the backpointer in it to point
to this buffer; the previous free buffer in memory. */
bn->bh.prevfree = b->bh.bsize;
#ifdef BECtl
/* If a block-release function is defined, and this free buffer
constitutes the entire block, release it. Note that pool_len
is defined in such a way that the test will fail unless all
pool blocks are the same size. */
if (relfcn != NULL &&
((bufsize) b->bh.bsize) == (pool_len - sizeof(struct bhead))) {
assert(b->bh.prevfree == 0);
assert(BH((char *) b + b->bh.bsize)->bsize == ESent);
assert(BH((char *) b + b->bh.bsize)->prevfree == b->bh.bsize);
/* Unlink the buffer from the free list */
b->ql.blink->ql.flink = b->ql.flink;
b->ql.flink->ql.blink = b->ql.blink;
(*relfcn)(b);
#ifdef BufStats
numprel++; /* Nr of expansion block releases */
numpblk--; /* Total number of blocks */
assert(numpblk == numpget - numprel);
#endif /* BufStats */
}
#endif /* BECtl */
}
#ifdef BECtl
/* BECTL -- Establish automatic pool expansion control */
void bectl(compact, acquire, release, pool_incr)
int (*compact) _((bufsize sizereq, int sequence));
void *(*acquire) _((bufsize size));
void (*release) _((void *buf));
bufsize pool_incr;
{
compfcn = compact;
acqfcn = acquire;
relfcn = release;
exp_incr = pool_incr;
}
#endif
/* BPOOL -- Add a region of memory to the buffer pool. */
void bpool(buf, len)
void *buf;
bufsize len;
{
struct bfhead *b = BFH(buf);
struct bhead *bn;
#ifdef SizeQuant
len &= ~(SizeQuant - 1);
#endif
#ifdef BECtl
if (pool_len == 0) {
pool_len = len;
} else if (len != pool_len) {
pool_len = -1;
}
#ifdef BufStats
numpget++; /* Number of block acquisitions */
numpblk++; /* Number of blocks total */
assert(numpblk == numpget - numprel);
#endif /* BufStats */
#endif /* BECtl */
/* Since the block is initially occupied by a single free buffer,
it had better not be (much) larger than the largest buffer
whose size we can store in bhead.bsize. */
assert(len - sizeof(struct bhead) <= -((bufsize) ESent + 1));
/* Clear the backpointer at the start of the block to indicate that
there is no free block prior to this one. That blocks
recombination when the first block in memory is released. */
b->bh.prevfree = 0;
/* Chain the new block to the free list. */;
/* Create a dummy allocated buffer at the end of the pool. This dummy
buffer is seen when a buffer at the end of the pool is released and
blocks recombination of the last buffer with the dummy buffer at
the end. The length in the dummy buffer is set to the largest
negative number to denote the end of the pool for diagnostic
routines (this specific value is not counted on by the actual
allocation and release functions). */
len -= sizeof(struct bhead);
b->bh.bsize = (bufsize) len;
#ifdef FreeWipe
V memset(((char *) b) + sizeof(struct bfhead), 0x55,
(MemSize) (len - sizeof(struct bfhead)));
#endif
bn = BH(((char *) b) + len);
bn->prevfree = (bufsize) len;
/* Definition of ESent assumes two's complement! */
assert((~0) == -1);
bn->bsize = ESent;
}
#ifdef BufStats
/* BSTATS -- Return buffer allocation free space statistics. */
void bstats(curalloc, totfree, maxfree, nget, nrel)
bufsize *curalloc, *totfree, *maxfree;
long *nget, *nrel;
{
struct bfhead *b = freelist.ql.flink;
*nget = numget;
*nrel = numrel;
*curalloc = totalloc;
*totfree = 0;
*maxfree = -1;
while (b != &freelist) {
assert(b->bh.bsize > 0);
*totfree += b->bh.bsize;
if (b->bh.bsize > *maxfree) {
*maxfree = b->bh.bsize;
}
b = b->ql.flink; /* Link to next buffer */
}
}
#ifdef BECtl
/* BSTATSE -- Return extended statistics */
void bstatse(pool_incr, npool, npget, nprel, ndget, ndrel)
bufsize *pool_incr;
long *npool, *npget, *nprel, *ndget, *ndrel;
{
*pool_incr = (pool_len < 0) ? -exp_incr : exp_incr;
*npool = numpblk;
*npget = numpget;
*nprel = numprel;
*ndget = numdget;
*ndrel = numdrel;
}
#endif /* BECtl */
#endif /* BufStats */
#ifdef DumpData
/* BUFDUMP -- Dump the data in a buffer. This is called with the user
data pointer, and backs up to the buffer header. It will
dump either a free block or an allocated one. */
void bufdump(buf)
void *buf;
{
struct bfhead *b;
unsigned char *bdump;
bufsize bdlen;
b = BFH(((char *) buf) - sizeof(struct bhead));
assert(b->bh.bsize != 0);
if (b->bh.bsize < 0) {
bdump = (unsigned char *) buf;
bdlen = (-b->bh.bsize) - sizeof(struct bhead);
} else {
bdump = (unsigned char *) (((char *) b) + sizeof(struct bfhead));
bdlen = b->bh.bsize - sizeof(struct bfhead);
}
while (bdlen > 0) {
int i, dupes = 0;
bufsize l = bdlen;
char bhex[50], bascii[20];
if (l > 16) {
l = 16;
}
for (i = 0; i < l; i++) {
V sprintf(bhex + i * 3, "%02X ", bdump[i]);
bascii[i] = isprint(bdump[i]) ? bdump[i] : ' ';
}
bascii[i] = 0;
V printf("%-48s %s\n", bhex, bascii);
bdump += l;
bdlen -= l;
while ((bdlen > 16) && (memcmp((char *) (bdump - 16),
(char *) bdump, 16) == 0)) {
dupes++;
bdump += 16;
bdlen -= 16;
}
if (dupes > 1) {
V printf(
" (%d lines [%d bytes] identical to above line skipped)\n",
dupes, dupes * 16);
} else if (dupes == 1) {
bdump -= 16;
bdlen += 16;
}
}
}
#endif
#ifdef BufDump
/* BPOOLD -- Dump a buffer pool. The buffer headers are always listed.
If DUMPALLOC is nonzero, the contents of allocated buffers
are dumped. If DUMPFREE is nonzero, free blocks are
dumped as well. If FreeWipe checking is enabled, free
blocks which have been clobbered will always be dumped. */
void bpoold(buf, dumpalloc, dumpfree)
void *buf;
int dumpalloc, dumpfree;
{
struct bfhead *b = BFH(buf);
while (b->bh.bsize != ESent) {
bufsize bs = b->bh.bsize;
if (bs < 0) {
bs = -bs;
V printf("Allocated buffer: size %6ld bytes.\n", (long) bs);
if (dumpalloc) {
bufdump((void *) (((char *) b) + sizeof(struct bhead)));
}
} else {
char *lerr = "";
assert(bs > 0);
if ((b->ql.blink->ql.flink != b) ||
(b->ql.flink->ql.blink != b)) {
lerr = " (Bad free list links)";
}
V printf("Free block: size %6ld bytes.%s\n",
(long) bs, lerr);
)));
} else
#endif
if (dumpfree) {
bufdump((void *) (((char *) b) + sizeof(struct bhead)));
}
}
b = BFH(((char *) b) + bs);
}
}
#endif /* BufDump */
#ifdef BufValid
/* BPOOLV -- Validate a buffer pool. If NDEBUG isn't defined,
any error generates an assertion failure. */
int bpoolv(buf)
void *buf;
{
struct bfhead *b = BFH(buf);
while (b->bh.bsize != ESent) {
bufsize bs = b->bh.bsize;
if (bs < 0) {
bs = -bs;
} else {
char *lerr = "";
assert(bs > 0);
if (bs <= 0) {
return 0;
}
if ((b->ql.blink->ql.flink != b) ||
(b->ql.flink->ql.blink != b)) {
V printf("Free block: size %6ld bytes. (Bad free list links)\n",
(long) bs);
assert(0);
return 0;
}
)));
assert(0);
return 0;
}
#endif
}
b = BFH(((char *) b) + bs);
}
return 1;
}
#endif /* BufValid */
/***********************\
* *
* Built-in test program *
* *
\***********************/
#ifdef TestProg
#define Repeatable 1 /* Repeatable pseudorandom sequence */
/* If Repeatable is not defined, a
time-seeded pseudorandom sequence
is generated, exercising BGET with
a different pattern of calls on each
run. */
#define OUR_RAND /* Use our own built-in version of
rand() to guarantee the test is
100% repeatable. */
#ifdef BECtl
#define PoolSize 300000 /* Test buffer pool size */
#else
#define PoolSize 50000 /* Test buffer pool size */
#endif
#define ExpIncr 32768 /* Test expansion block size */
#define CompactTries 10 /* Maximum tries at compacting */
#define dumpAlloc 0 /* Dump allocated buffers ? */
#define dumpFree 0 /* Dump free buffers ? */
#ifndef Repeatable
extern long time();
#endif
extern char *malloc();
extern int free _((char *));
static char *bchain = NULL; /* Our private buffer chain */
static char *bp = NULL; /* Our initial buffer pool */
#include <math.h>
#ifdef OUR_RAND
static unsigned long int next = 1;
/* Return next random integer */
int rand()
{
next = next * 1103515245L + 12345;
return (unsigned int) (next / 65536L) % 32768L;
}
/* Set seed for random generator */
void srand(seed)
unsigned int seed;
{
next = seed;
}
#endif
/* STATS -- Edit statistics returned by bstats() or bstatse(). */
static void stats(when)
char *when;
{
bufsize cural, totfree, maxfree;
long nget, nfree;
#ifdef BECtl
bufsize pincr;
long totblocks, npget, nprel, ndget, ndrel;
#endif
bstats(&cural, &totfree, &maxfree, &nget, &nfree);
V printf(
"%s: %ld gets, %ld releases. %ld in use, %ld free, largest = %ld\n",
when, nget, nfree, (long) cural, (long) totfree, (long) maxfree);
#ifdef BECtl
bstatse(&pincr, &totblocks, &npget, &nprel, &ndget, &ndrel);
V printf(
" Blocks: size = %ld, %ld (%ld bytes) in use, %ld gets, %ld frees\n",
(long)pincr, totblocks, pincr * totblocks, npget, nprel);
V printf(" %ld direct gets, %ld direct frees\n", ndget, ndrel);
#endif /* BECtl */
}
#ifdef BECtl
static int protect = 0; /* Disable compaction during bgetr() */
/* BCOMPACT -- Compaction call-back function. */
static int bcompact(bsize, seq)
bufsize bsize;
int seq;
{
#ifdef CompactTries
char *bc = bchain;
int i = rand() & 0x3;
#ifdef COMPACTRACE
V printf("Compaction requested. %ld bytes needed, sequence %d.\n",
(long) bsize, seq);
#endif
if (protect || (seq > CompactTries)) {
#ifdef COMPACTRACE
V printf("Compaction gave up.\n");
#endif
return 0;
}
/* Based on a random cast, release a random buffer in the list
of allocated buffers. */
while (i > 0 && bc != NULL) {
bc = *((char **) bc);
i--;
}
if (bc != NULL) {
char *fb;
fb = *((char **) bc);
if (fb != NULL) {
*((char **) bc) = *((char **) fb);
brel((void *) fb);
return 1;
}
}
#ifdef COMPACTRACE
V printf("Compaction bailed out.\n");
#endif
#endif /* CompactTries */
return 0;
}
/* BEXPAND -- Expand pool call-back function. */
static void *bexpand(size)
bufsize size;
{
void *np = NULL;
bufsize cural, totfree, maxfree;
long nget, nfree;
/* Don't expand beyond the total allocated size given by PoolSize. */
bstats(&cural, &totfree, &maxfree, &nget, &nfree);
if (cural < PoolSize) {
np = (void *) malloc((unsigned) size);
}
#ifdef EXPTRACE
V printf("Expand pool by %ld -- %s.\n", (long) size,
np == NULL ? "failed" : "succeeded");
#endif
return np;
}
/* BSHRINK -- Shrink buffer pool call-back function. */
static void bshrink(buf)
void *buf;
{
if (((char *) buf) == bp) {
#ifdef EXPTRACE
V printf("Initial pool released.\n");
#endif
bp = NULL;
}
#ifdef EXPTRACE
V printf("Shrink pool.\n");
#endif
free((char *) buf);
}
#endif /* BECtl */
/* Restrict buffer requests to those large enough to contain our pointer and
small enough for the CPU architecture. */
static bufsize blimit(bs)
bufsize bs;
{
if (bs < sizeof(char *)) {
bs = sizeof(char *);
}
/* This is written out in this ugly fashion because the
cool expression in sizeof(int) that auto-configured
to any length int befuddled some compilers. */
if (sizeof(int) == 2) {
if (bs > 32767) {
bs = 32767;
}
} else {
if (bs > 200000) {
bs = 200000;
}
}
return bs;
}
int main()
{
int i;
double x;
/* Seed the random number generator. If Repeatable is defined, we
always use the same seed. Otherwise, we seed from the clock to
shake things up from run to run. */
#ifdef Repeatable
V srand(1234);
#else
V srand((int) time((long *) NULL));
#endif
/* Compute x such that pow(x, p) ranges between 1 and 4*ExpIncr as
p ranges from 0 to ExpIncr-1, with a concentration in the lower
numbers. */
x = 4.0 * ExpIncr;
x = log(x);
x = exp(log(4.0 * ExpIncr) / (ExpIncr - 1.0));
#ifdef BECtl
bectl(bcompact, bexpand, bshrink, (bufsize) ExpIncr);
bp = malloc(ExpIncr);
assert(bp != NULL);
bpool((void *) bp, (bufsize) ExpIncr);
#else
bp = malloc(PoolSize);
assert(bp != NULL);
bpool((void *) bp, (bufsize) PoolSize);
#endif
stats("Create pool");
V bpoolv((void *) bp);
bpoold((void *) bp, dumpAlloc, dumpFree);
for (i = 0; i < TestProg; i++) {
char *cb;
bufsize bs = pow(x, (double) (rand() & (ExpIncr - 1)));
assert(bs <= (((bufsize) 4) * ExpIncr));
bs = blimit(bs);
if (rand() & 0x400) {
cb = (char *) bgetz(bs);
} else {
cb = (char *) bget(bs);
}
if (cb == NULL) {
#ifdef EasyOut
break;
#else
char *bc = bchain;
if (bc != NULL) {
char *fb;
fb = *((char **) bc);
if (fb != NULL) {
*((char **) bc) = *((char **) fb);
brel((void *) fb);
}
continue;
}
#endif
}
*((char **) cb) = (char *) bchain;
bchain = cb;
/* Based on a random cast, release a random buffer in the list
of allocated buffers. */
if ((rand() & 0x10) == 0) {
char *bc = bchain;
int i = rand() & 0x3;
while (i > 0 && bc != NULL) {
bc = *((char **) bc);
i--;
}
if (bc != NULL) {
char *fb;
fb = *((char **) bc);
if (fb != NULL) {
*((char **) bc) = *((char **) fb);
brel((void *) fb);
}
}
}
/* Based on a random cast, reallocate a random buffer in the list
to a random size */
if ((rand() & 0x20) == 0) {
char *bc = bchain;
int i = rand() & 0x3;
while (i > 0 && bc != NULL) {
bc = *((char **) bc);
i--;
}
if (bc != NULL) {
char *fb;
fb = *((char **) bc);
if (fb != NULL) {
char *newb;
bs = pow(x, (double) (rand() & (ExpIncr - 1)));
bs = blimit(bs);
#ifdef BECtl
protect = 1; /* Protect against compaction */
#endif
newb = (char *) bgetr((void *) fb, bs);
#ifdef BECtl
protect = 0;
#endif
if (newb != NULL) {
*((char **) bc) = newb;
}
}
}
}
}
stats("\nAfter allocation");
if (bp != NULL) {
V bpoolv((void *) bp);
bpoold((void *) bp, dumpAlloc, dumpFree);
}
while (bchain != NULL) {
char *buf = bchain;
bchain = *((char **) buf);
brel((void *) buf);
}
stats("\nAfter release");
#ifndef BECtl
if (bp != NULL) {
V bpoolv((void *) bp);
bpoold((void *) bp, dumpAlloc, dumpFree);
}
#endif
return 0;
}
#endif | https://sources.debian.org/src/fragroute/1.2-7.1/bget.c/ | CC-MAIN-2019-22 | refinedweb | 5,992 | 52.29 |
Red Hat Bugzilla – Bug 7351
Up2date batch requires X
Last modified: 2008-05-01 11:37:53 EDT
I use Redhat for a few remote firewall and standalone servers where I do
not bother to install X on the system. Also I am many times supporting
these machines remotely over ssh regardless of X being installed or not.
Up2date, even in batch mode, requires the existance of X. This makes it
impossible to use on several of the systems I administer. Unfortunately the
change to gpg signatures, while a GoodThing(tm), breaks freshrpms, the
other such tool that came out a while back.
This leaves me with -no- way to remotely upgrade packages on a Redhat 6.1
system.
I don't know if the following patch fixes *all* the dependencies on X, but it
fixes at least one that I discovered while attempting to use up2date in batch
mode last night -- it prevents up2date from trying to update the GUI progres bar
when that progress bar doesn't exist.
--- /usr/share/up2date/client.py Wed Nov 3 15:21:48 1999
+++ /tmp/up2date/client.py Thu Dec 16 06:30:26 1999
@@ -134,23 +134,22 @@
return cid
def setProgress(self, amount, total):
+ if not self.gui:
+ return
threads_enter()
self.gui.progressBar.set_activity_mode(FALSE)
threads_leave()
- if not self.gui:
- return
- else:
- if total != 0:
- i = (amount + 1.0) / total
- if i > 1:
- i = 1.0
- elif i < 0:
- i = 0
- else:
+ if total != 0:
+ i = (amount + 1.0) / total
+ if i > 1:
+ i = 1.0
+ elif i < 0:
i = 0
- threads_enter()
- self.gui.progressBar.update(i)
- threads_leave()
+ else:
+ i = 0
+ threads_enter()
+ self.gui.progressBar.update(i)
+ threads_leave()
def setActivity(self):
threads_enter()
fixed for 6.2. | https://bugzilla.redhat.com/show_bug.cgi?id=7351 | CC-MAIN-2018-30 | refinedweb | 286 | 67.55 |
While I can't change the API for Minecraft: Pi edition I can change RaspberryJuice - so I decided to add functions to allow you to find out where the player is looking. You can download the RaspberryJuice plugin Canarymod and Bukkit.
I have also created a new Adventures in Minecraft starterkit which includes the new version of RapsberryJuice and everything you need to use the new api functions.
The 3 new functions in the api are:
- player.getRotation() - return the angle of rotation between 0 and 360
- player.getPitch() - returns the angle of pitch between -90 and 90
- player.getDirection() - returns a unit-vector of x,y,z pointing in the direction the player is facing
The functions also work with the entities as well so you can use entity.getRotation(), entity.getPitch() and entity.getDirection()
Here are the couple of code examples I demo in the video.
Get the players rotation and pitch angles:
#import the minecraft module import mcpi.minecraft as minecraft #create a connection to minecraft mc = minecraft.Minecraft.create() while True: #get the players rotational angle angle = mc.player.getRotation() #get the player up and down angle pitch = mc.player.getPitch() mc.postToChat(str(angle) + " : " + str(pitch))
Create a block in front of the player using getDirection():
import mcpi.minecraft as minecraft import mcpi.block as block import time #how far in front of the player the block will be BLOCKDISTANCE = 5 mc = minecraft.Minecraft.create() while True: #get the position pos = mc.player.getPos() #get the direction direction = mc.player.getDirection() #calc the position of the block in front of the player x = round(pos.x + (direction.x * BLOCKDISTANCE)) y = round(pos.y + (direction.y * BLOCKDISTANCE) + 1) z = round(pos.z + (direction.z * BLOCKDISTANCE)) mc.setBlock(x,y,z,block.DIAMOND_BLOCK) time.sleep(0.1) mc.setBlock(x,y,z,block.AIR)I hope you find the new api functions useful.
I've posted some code on the Adventures in Minecraft forum, showing how you can approximate direction in Minecraft Pi Edition. It's very rough, its only an approximation based on monitoring changes in the player position, but it's good enough for some purposes.
David Whale
@whaleygeek
And here is a link to David's post -
I have installed the latest version of RasperryJuice on my server but where can I download the updated Python module with the new functions from?
I got mine from
Thanks.
You can get it from the raspberry juice git hub repo - | http://www.stuffaboutcode.com/2015/01/minecraft-api-players-direction.html | CC-MAIN-2017-17 | refinedweb | 414 | 58.58 |
/* * <sys/sysctl.h> #include <errno.h> #include <kvm.h> #include <string.h> int getvfsbyname(const char *, struct vfsconf *); /* * Given a filesystem name, determine if it is resident in the kernel, * and if it is resident, return its vfsconf structure. */ int getvfsbyname(fsname, vfcp) const char *fsname; struct vfsconf *vfcp; { int name[4], maxtypenum, cnt; size_t buflen; name[0] = CTL_VFS; name[1] = VFS_GENERIC; name[2] = VFS_MAXTYPENUM; buflen = 4; if (sysctl(name, 3, &maxtypenum, &buflen, (void *)0, (size_t)0) < 0) return (-1); name[2] = VFS_CONF; buflen = sizeof *vfcp; for (cnt = 0; cnt < maxtypenum; cnt++) { name[3] = cnt; if (sysctl(name, 4, vfcp, &buflen, (void *)0, (size_t)0) < 0) { if (errno != ENOTSUP) return (-1); continue; } if (!strcmp(fsname, vfcp->vfc_name)) return (0); } errno = ENOENT; return (-1); } | http://opensource.apple.com//source/Libc/Libc-825.40.1/gen/getvfsbyname.c | CC-MAIN-2016-36 | refinedweb | 123 | 56.35 |
Skip navigation links
java.lang.Object
oracle.webcenter.search.Predicate
oracle.webcenter.search.TextPredicate
public class TextPredicate
This class models a text criterion for data querying. Note: Sometimes one may wish to turn a keyword search into both a data and a metadata search - e.g. List Search UI has a keyword search box that pits the search against list data but also at the same time against the list name, list description, list column name, and list column data. This is a decision made from the caller, i.e. the UI code, and is not to be modeled at this level.
public TextPredicate(java.lang.String textQueryString)
textQueryString- the text query String to use as a criterion
public java.lang.String getTextQueryString()
public void setTextQueryString(java.lang.String textQueryString)
textQueryString- a String that will be used for text-based queries
public Predicate clonePredicate()
clonePredicatein class
Predicate
public java.lang.String toString()
toStringin class
java.lang.Object
Skip navigation links | http://docs.oracle.com/cd/E23943_01/apirefs.1111/e15995/oracle/webcenter/search/TextPredicate.html | CC-MAIN-2017-30 | refinedweb | 160 | 50.33 |
The current code runs the balance_rt_tasks() on every _schedule()once the system enters an overload state. Now that we have betterdistribution on the push side, we can reduce the conditions thatrequire us to pull tasks. They are as follows:At the time of a _schedule(), if our priority is staying the same orgoing logically higher between _prev_ and _next_ we can skip tryingto balance tasks because any tasks that were runnable by our queuehave already been pushed to us. However, if our priority istransitioning lower AND some CPUs out there are in overload, weshould check to see if we can pull some over.Note: DO NOT RUN TEST WITH THIS PATCH APPLIED !This patch is a concept only (for now) and is here fordemonstration/comment purposes only. The current series is stillracy with respect to acquiring the lowest RQ in the system. Theconcept in this patch is predicated on raceless distribution to ourcurrent priority level. So the current balancer is a nice bigsafety net to cleanup any issues related to that. This patcheffectively takes that net away, so we need to be sure we have allour ducks lined up before turning this one on. But once we do we caneliminate the (fairly expensive) checks (e.g. rq double-locks, etc)in a subset (hopefully significant #) of the calls to schedule(),which sounds like a good optimization to me ;) We shall see if thatpans out.Signed-off-by: Gregory Haskins <ghaskins@novell.com>--- kernel/sched.c | 16 ++++++++++++++-- 1 files changed, 14 insertions(+), 2 deletions(-)diff --git a/kernel/sched.c b/kernel/sched.cindex b79b968..9e1f3ec 100644--- a/kernel/sched.c+++ b/kernel/sched.c@@ -4118,8 +4118,20 @@ asmlinkage void __sched __schedule(void) sub_preempt_count(PREEMPT_ACTIVE); #if defined(CONFIG_PREEMPT_RT) && defined(CONFIG_SMP)- if (unlikely(atomic_read(&rt_overload)))- balance_rt_tasks(rq, cpu);+ /*+ * If we are switching away from an RT task while the system is in+ * overload, we need to see if there is a way we can help a different+ * cpu. If the next task to run is not RT, or if it *is* RT but+ * is a logically lower priority, try to balance the system. Otherwise+ * we can skip it, because anyone that could have pushed their tasks+ * to us already did.+ */+ if (unlikely(rt_task(prev) && atomic_read(&rt_overload))) {+ struct task_struct *preview = pick_rt_task(rq, cpu);++ if (!preview || (preview->prio > prev->prio))+ balance_rt_tasks(rq, cpu);+ } #endif if (unlikely(!rq->nr_running))-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2007/10/12/520 | CC-MAIN-2016-18 | refinedweb | 423 | 54.32 |
Hi,
i was trying to use a python script but it always returns an 500 internal server error.
The script is very simple. I have tried to use the example of the the dreamhost wiki but it doesnt work either.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
def main():print "Content-type: text/html"printprint ""print "Hello World from Python"print ""print "Standard Hello World from a Python CGI Script"print ""
if name == "main":main()"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@uguu-web."
Heeeeelp! >_<
Do you have the access to error.log file? Please check the log and see what it says.
Most of the time, Internal Server Error is caused by syntax error. Please have [color=#CC0000];[/color] at the end of each line of your code. And you may want to try
print "Content-type: text/html[color=#CC0000]\n\n[/color]"
You have to have two empty lines after the header.
$50 off and 3 free domains with code: [color=#CC0000]DH3[/color] [url=]Sign Up NOW[/url] or More Codes Here
Programming partner here. Error log says:
[Wed May 07 00:20:34 2008] [error] [client 84.127.104.121] Premature end of script headers: webtest.py
...and then some 404s about the personalized 500 error page. I added the \n's and the result is the same. I also simplified the code to this:
print "Content-type: text/html\n\n"print "Hello World from PythonStandard Hello World from a Python CGI Script"
It's not a syntax problem, methinks. And the script works locally. You can see for yourself, the script is located on
What is the file permission on the py file? You'll need execute permission on the file.
It's 755. I tried with 777 too.
...but, somehow, it started working just now. Odd.
Strange... Now let's shake legs
Try this one:
#!/usr/bin/python
# for linux
import sys
import os
def printHeader():
print "Content-type: text/html\n"
def printArgs():
for arg in sys.argv:
print arg + "<br/>"
def printEnv():
for key in os.environ.keys():
print "<b>" + key + "</b>=" + os.environ[key] + "<br/>"
def printVersion():
print "Python %s" % sys.version
def main():
printHeader()
print "<TITLE>Hello World from Python</TITLE>"
print "Standard Hello World from a Python CGI Script"
print "<p />Python Info...<br />"
print "<code>"
printVersion()
print "</code>"
print "<p />Command Line...<br />"
print "<code>"
printArgs()
print "</code>"
print "<p />Environment...<br />"
print "<code>"
printEnv()
print "</code>"
if( __name__ == "__main__"):
main()
Note that you need to use a *nix editor, or in some other way make sure you have proper *nix style line endings. Failure to do so will often result in the kinds of errors you are seeing.
--rlparker
The 500itis is back again. Unix style lines and everything. I named the script from rlparker "tests.py". It returns a 500, and error.log says:
[Fri May 09 11:12:38 2008] [error] [client 130.206.30.217] Premature end of script headers: tests.py[Fri May 09 11:12:38 2008] [error] [client 130.206.30.217] File does not exist: /home/uguues/uguu-web.com/internal_error.html
My own webtest.py:
...does the same. Everything is 777 and unix style. You can check on
Or your webtest.py (chmod 755)
rewritten as
#!/usr/bin/python
print "Content-type: text/html\n\n"
print """
<html><head><title>Hello World from Python</title></head><body>Standard Hello World from a Python CGI
Script</body></html>
"""
should work.
-- Norm
Opinions are my own views, not DreamHosts'.I am NOT a DreamHost employee OK! :@
Act on my advice at your own risk!
I think you meant triple single quotes, not double. I tried with both options just in case, and it does the same thing. I don't think it's a problem of the script itself, it works with my local apache >_<
No I used triple double quotes and in the editor added a blank line at the end of the script.
Well, that doesn't work either.
777 will not work under suExec on DreamHost,iles to be executed as CGI need to be 755 or more restrictive. Period. Pythin is picky about editors, blank lines, extra characters. Etcetera.
The code I posted works fine, on a DH server, when properly prepared, upload, chmodded, etc.
The same code for both above links, prepared with different *nix editors in the shell. | https://discussion.dreamhost.com/t/error500-with-a-python-script/47632 | CC-MAIN-2017-47 | refinedweb | 747 | 76.62 |
18 January 2019 1 comment Javascript, ReactJS
When Immer first came out I was confused. I kinda understood what I was reading but I couldn't really see what was so great about it. As always, nothing beats actual code you type yourself to experience how something works.
Here is, I believe, a great example:
If you're reading this on your mobile it might be hard to see what it does. Basically, it's a very simple React app that displays a "todo list like" thing. The state (aka.
this.state.tasks) is a pure JavaScript array. The React components that display the data (e.g.
<List tasks={this.state.tasks}/> and
<ShowItem item={item} />) are pure (i.e.
extends React.PureComponent) meaning React natively protects from re-rendering a component when the props haven't changed. So no wasted render-cycles.
What Immer does is that it helps mutate an object in a smart way. I'm sure you've heard that you're never supposed to mutate state objects (arrays are a form of mutable objects too!) and instead do things like
const stuff = Object.assign({}, this.state.stuff); or
const things = this.state.things.slice(0);. However, those things are shallow copies meaning any mutable objects within (i.e. nested objects) don't get the clone treatment and can thus cause problems with not re-rendering when they should.
Here's the core gist:
import React from "react"; import produce from "immer"; class App extends React.Component { state = { tasks: [[false, { text: "Do something", date: new Date() }]] }; onToggleDone = (i, done) => { // Immer // This is what the blog post is all about... const tasks = produce(this.state.tasks, draft => { draft[i][0] = done; draft[i][1].date = new Date(); }); // Pure JS // Don't do this! // const tasks = this.state.tasks.slice(0); // tasks[i][0] = done; // tasks[i][1].date = new Date(); this.setState({ tasks }); }; render() { // appreviated, but... return <List tasks={this.state.tasks}/> } } class List extends React.PureComponent { ...
It just works. Neat!
By the way, here's a code sandbox that accomplishes the same thing but with ImmutableJS which I think is uglier. I think it's uglier because now the rendering components need to be aware that it's rendering
immutable.Map objects instead.
The cost of doing what
immer.produce isn't free. It's some smart work that needs to be done. But the alternative is to deep clone the object which is going to be much slower. Immer isn't the fastest kid on the block but unlike MobX and ImmutableJS once you've done this smart stuff you're back to plain JavaScript objects.
Careful with doing something like
console.log(draft) since it will raise a
TypeError in your web console. Just be aware of that or use
console.log(JSON.stringify(draft)) instead.
If you know with confidence that your mutable object does not, and will not, have nested mutable objects you can use object spread,
Object.assign(), or
.slice(0) and save yourself the trouble of another dependency.
Follow @peterbe on Twitter
I suggest to migrate to hooks and use tiny libraries to manage nested and complex state, for example the one specifically dedicated to complex state management and 2 hooks: useMap and useList from react-use package. Disclaimer: I am an author of the first lib. | https://api.minimalcss.app/plog/using-immer-to-handle-nested-objects-in-react-state | CC-MAIN-2020-16 | refinedweb | 557 | 68.77 |
General purpose Testing Utilities and also special testing tools for for Web Applications
Project description
General purpose Testing Utilities and also special testing tools for Web Applications
Better API for accessing Selenium
With smoothtest you can write nicer tests for web sites.
class SearchEnginesDemo(unittest.TestCase): def setUp(self): # We need to enter "single test level" of life for each test # It will initialize the webdriver if no webdriver is present from upper levels self._level_mngr = WebdriverManager().enter_level(level=SINGLE_TEST_LIFE) # Get Xpath browser self.browser = self._level_mngr.get_xpathbrowser(name=__name__) def tearDown(self): # Make sure we quit those webdrivers created in this specific level of life self._level_mngr.exit_level() def test_duckduckgo(self): # Load a local page for the demo self.browser.get_url('') # Type smoothtest and press enter self.browser.fill(".//*[@id='search_form_input_homepage']", 'smoothtest\n') result_link = './/a[@title="smoothtest "]' # Wait for the result to be available self.browser.wait_condition(lambda brw: brw.select_xpath(result_link)) # Click on result self.browser.click(result_link) # First result should point to github expected_url = '' wait_url = lambda brw: brw.current_url() == expected_url # Make sure we end up in the right url self.assertTrue(self.browser.wait_condition(wait_url))
The API is very XPath oriented, so you can test your XPath with Firefox’s extensions like FirePath.
How to use smoothtest
The main utility is the smoothtest command. This command monitors your project’s files and your unittest files for changes, it will trigger reloading and rerunning tests when a file changes. This means you can work in your code and see how tests are affected automatically. You can select a group of tests files to be monitored - that trigger partial reloads of those same modules - and an group of files or directories to trigger full reloads of the project.
It also provides a ipython UI interface to modify certain values and re-test.
Do
smoothtest
To enter the Ipython UI without specifying any initial test.
If you want to start with a specific test, run this to get possible arguments.
smoothtest --help
Inside Ipython you have commands:
%smoothtest %test %reset %test_config %get %chrome %firefox %phantonjs %steal_xpathbrowser
Where %smoothtest has same parameters as the smoothtest command but adds -u for updating test parameters and -f for forcing a reloading.
smoothtest command is still in beta stage, so some functionality won’t be as reliable as expected. (but still useful for developing tests) You may need to restart the smoothtest command from time to time.
Configuration
You will need a smoothtest_settings.py in your PYTHONPATH that looks like this:
from smoothtest.settings.default import DefaultSettings import logging class Settings(DefaultSettings): web_server_url = '' webdriver_browser = 'Firefox' #'Chrome' 'PhantomJS' ...
Installing
You can use pip to install it:
pip install smoothtest
Or uninstall it:
pip uninstall smoothtest
Installing virtual screen dependencies
In ubuntu you may need to install
sudo apt-get install xserver-xephyr xvfb
Windows and Mac OSX
Windows
On windows, the smoothtest shell does not work (due to partial support of unix’s fork()) , although running test cases directly will work.
Mac OSX
Inside Mac OS fork() should work, although I haven’t had the chance to test it there. Let me know if you do.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/smoothtest/ | CC-MAIN-2021-21 | refinedweb | 550 | 55.13 |
On Feb 8 16:13, Ismail Donmez wrote: > On Mon, Feb 8, 2016 at 4:10 PM, Corinna Vinschen > <corinna-cygwin@cygwin.com> wrote: > > On Feb 8 15:31, Ismail Donmez wrote: > >> On Mon, Feb 8, 2016 at 3:18 PM, Corinna Vinschen > >> <corinna-cygwin@cygwin.com> wrote: > >> > On Feb 8 12:01, Ismail Donmez wrote: > >> >> Hi, > >> >> > >> >> cdrtools has some code to detect Solaris style ACLs: > >> >> > >> >> #if defined(HAVE_ACL) && defined(HAVE_FACL) && \ > >> >> defined(HAVE_ACLFROMTEXT) && defined(HAVE_ACLTOTEXT) > >> >> # define HAVE_SUN_ACL 1 /* Sun UFS ACL's present */ > >> >> #endif > >> >> > >> >> Since cygwin still seems to be defining aclfromtext() and acltotext() > >> >> functions (which are not defined in POSIX) cdrtools thinks this a > >> >> Solaris-style system and get up getting a compile error later on. > >> > > >> > Probably due to including sys/acl.h. Does swtiching to cygwin/acl.h > >> > help? Or changing the above check to prefer POSIX ACLs over Solaris > >> > ACLs? > >> > >> This is a generic code so I don't want to add a cygwin specific > >> dependency there. Is there a preprocessor definition for cygwin > >> version? I could use that to disable HAVE_SUN_ACL for cygwin 2.5+ > > > > If you include cygwin/version.h you could use the version definitions. > > > > Alternatively we could allow to use the Solaris ACL functions even if > > only including sys/acl.h, given some macro: > > > > sys/acl.h: > > > > #ifdef __USE_OLD_SOLARIS_ACL_FUNCTIONS > > # include <cygwin/acl.h> > > #else > > [...POSIX definitions...] > > #endif > > > > Would that help? > > That should help, I cook a patch and send to cdrecord maintainer. Wait, that's a bit premature. I'm not even sure yet if the macro name is ok.: <> | https://sourceware.org/pipermail/cygwin/2016-February/226022.html | CC-MAIN-2020-29 | refinedweb | 257 | 58.89 |
How many JavaScript files does your web applications contain? As web applications grow more complex, we typically split our codebase into multiple files. We then include each file individually in the HTML document which is sent to the browser. The browser then makes multiple requests to the server to get each file separately, which can slow down the load time of our web applications. Moreover, since browsers typically limit the number of concurrent requests they make to the same hostname, some of the requests for script files may end up being serialized, which slows things even further.
.NET 4.5 offers a powerful optimization that allows us to bundle multiple files into a single file, which is then downloaded by a browser in a single request. Let's dive right in and see how it works.
Using Bundles
Let's create a new MVC web application. By default, the template project contains a file named BundleConfig.cs in the App_Start folder. The
BundleConfig class contains a single method,
RegisterBundles, which defines multiple bundles. Let's examine one of the bundle definitions:
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*"));
This code creates a new instance of
ScriptBundle and assigns it the virtual path
~/bundles/jqueryval. It then invokes the
Include method to specify which files should be included in the bundle.
Now that the bundle is registered, it can be referenced in the views. We could just add a
script element to the view and specify the bundle's virtual path, but it's best to use the
@Script.Render directive instead. This provides additional features (such as caching support), as we discuss later in this tutorial. If you open the Login.cshtml file for example, you'll see the following line:
@Scripts.Render("~/bundles/jqueryval")
This tells MVC to render a single
script element for the bundle. Let's make sure that it works.
Let's run the application and click the Login link at the top right. Once the login page loads, we can view the page source to verify that only one script element was generated per this bundle, and that it refers to its virtual path. However, it seems that the source actually contains multiple
script elements, one per each file in the bundle:
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script> <script src="/Scripts/jquery.validate.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.js"></script>
Hmm... Why didn't it work?
By default, bundling and minification is disabled when executing in debug mode. Instead, each file is included separately, to make debugging more convenient. When we run the web application in release mode and examine the source of the login page, we see the following single
script element:
<script src="/bundles/jqueryval?v=mRjM0qa6T8GTCa8lhmXMI_-t5fsTCmHSxo4BqkY9x4A1"></script>
As you can see, it refers to the virtual path of the bundle, as defined in the
RegisterBundles method. Don't worry about the strange looking query string for now, I'll explain why it's there later in this tutorial, when we discuss caching.
By the way, you can enable bundling and minification even in debug mode, by including the following line of code in the
RegisterBundles method:
BundleTable.EnableOptimizations = true;
More on Bundle Registration
After creating a bundle object, we typically call the
Include method to specify the files that are part of the bundle (note that
Include accepts multiple file paths, so we don't have to invoke it multiple times).
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.unobtrusive*", "~/Scripts/jquery.validate*"));
As you can see, the
Include method also supports wildcards (though only one wildcard may exist in each pattern and it must be used either as a prefix or a suffix). This way you can include multiple files based on a pattern.
You might want to avoid using the * wildcard if the order of script inclusion is significant. By explicitly specifying each included file, you have full control of the order they appear in the bundle. Note that it is also possible to include all scripts in a given directory, by calling the
IncludeDirectory method instead of
Include, but again the order is arbitrary.
Another, special wildcard is
{version}. Consider the following bundle definition:
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js"));
This allows defining a bundles without specifying the version. Currently, when we create a new MVC application, the jQuery scripts the template contains are of version 1.8.2 (e.g. jquery-1.8.2.js). By using
{version}, if we later upgrade to a newer version of jQuery, we don't need to update the bundle definition.
An interesting point to note is that if both a debug version and a minified version of a script exist, the bundle will automatically use the debug version (e.g. jquery-1.8.2.js) when running in debug, and the minified version (e.g. jquery-1.8.2.min.js) in release.
But what if we don't have a minified version of a script? Wouldn't it be great if MVC could generate a minified version for us automatically?
Actually it can!
Minification
Minification is the process of removing comments, whitespaces and shortening the length of identifiers in the script. This yields a "compressed" script that provides identical functionality. Third party libraries are typically available in the original form, for ease of debugging / code browsing, and in a minified form, for a smaller file size. But what about the thousands of lines of script code that wrote? How does our own code get minified?
As part of the bundling process, ASP .NET also minifies the scripts. We don't need to do anything - it works automatically. Just remember that in debug mode, bundling and minification are disabled, for ease of debugging.
CSS Bundling
Out of the box, ASP .NET also supports bundling and minification of Cascading Style Sheets (CSS) files. Instead of creating a
ScriptBundle, we create a
StyleBundle when registering the bundles. Here is a sample, from the default
RegisterBundles method (truncated for brevity):", ...));
The view then refers to the bundle using
@Styles.Render (rather than
Scripts.Render):
@Styles.Render("~/Content/themes/base/css")
A word of advice: don't include CSS files from multiple directories in the same bundle. Also, make sure that the virtual path to the bundle is in the same directory as the source CSS files. A CSS file may contain relative references to other resources, so the location can be significant. In the style bundle above, all CSS files, as well as the virtual path to the bundle are in the
~/Content/themes/base/ directory.
Caching Support
When ASP .NET serves a bundle file, it also includes a header, which indicates that the file can be cached by the browser (or any proxy along the way) for one year. This is great, because the next time the user loads our web application, the file may be loaded from cache, which can significantly expedite load time and reduce bandwidth utilization.
But what happens if we change the content of one of the files in the bundle, or add another file for example? If the browser caches the bundle file for a whole year, how will it get the new version once it becomes available?
This is one of the reasons why it's best to use
@Scripts.Render and
@Styles.Render instead of explicitly using the corresponding HTML elements. Recall that the emitted
script element for a bundle looks like the following:
<script src="/bundles/jqueryval?v=mRjM0qa6T8GTCa8lhmXMI_-t5fsTCmHSxo4BqkY9x4A1"></script>
The path to the bundle file includes a query string, with a token which is guaranteed to remain the same until the bundle changes in any way. Since browsers cache resources based on an exact URL, including the query string, then once anything in the URL changes (which only happens when the bundle content changes), the browser will not find a match in the cache and will download the new bundle. This is how freshness is guaranteed.
Actually, this feature alone is a great reason to use bundles, even if you have just one file in each bundle. Browsers sometimes take a rather aggressive approach to caching, and automatically cache scripts and CSS files even if there is no header indicating that they should do so. By using a bundle it is guaranteed that the browser will always have the latest version of your files, and also benefit from optimum caching.
CDN support
Libraries such as jQuery are so commonly used, that they are hosted on CDNs (content delivery networks). Specifying a URL to the file on a CDN, which is basically an external server, offer multiple benefits:
- CDNs can be very fast and are often distributed into multiple geographic zones.
- Unrelated web applications may also use the same common libraries that your application requires, and may load them from the same CDN. Since resources are cached based on URL, then the library your application needs may already exist in the browser's cache, even if the user never loaded your application before.
- Browsers limit concurrent resource downloading based on the hostname, and since a CDN has a different hostname than your application, your resources can be downloaded in parallel.
OK, sounds great, now how do we do it? There are two steps.
First, per each bundle that can be downloaded from a CDN, we need to specify the CDN URL. For example:
bundles.Add(new ScriptBundle("~/bundles/jquery", "") .Include("~/Scripts/jquery-{version}.js"));
The second parameter to the
ScriptBundle constructor above denotes the CDN path for this resource.
The second step is to enable CDN usage in the
RegisterBundles method:
bundles.UseCdn = true;
Once we do that, the CDN version will be used in release builds, or if
BundleTable.EnableOptimizations is set to
true, but the local version will be used for debugging, so as developers we don't have to be connected to the internet to work on our web application.
Note that if the CDN is unavailable, the bundle won't be automatically downloaded from our server instead. Therefore, it is advised that you provide such fallback yourself. Here is an example of how to provide a fallback for jQuery:
@Scripts.Render("~/bundles/jquery") <script type="text/javascript"> if (typeof jQuery == 'undefined') { var e = document.createElement('script'); e.src = '@Url.Content("~/Scripts/jquery-1.8.2.js")'; e.type = 'text/javascript'; document.getElementsByTagName("head")[0].appendChild(e); } </script>
If the script element that results from the
@Script.Render directive fails to load jQuery, then the jQuery object remains undefined. In such case, the script above dynamically adds a new script element, which explicitly refers to the jQuery file hosted on our server, instead of the CDN.
Extensibility
ASP .NET is a highly extensible framework, and bundling is no exception. We can create our own bundle types, and specify how to transform them before they're being sent to the client.
A classic example is adding support for LESS. LESS is an extension to CSS that allows for dynamic behavior, such as variables, operations and functions. But while a LESS file offers some great advantages over CSS, it cannot be processed by browsers, and must be converted to CSS on the server side. Let's see how we can add bundle support for LESS, which will automatically transform LESS files to CSS.
First, we need to install the LESS parser in our web application. Probably the easiest way to do so is to install the dotless package using NuGet. Then we need to create a transform class that is capable of handling LESS input:
public class LessTransform : IBundleTransform { public void Process(BundleContext context, BundleResponse response) { response.Content = dotless.Core.Less.Parse(response.Content); response.ContentType = "text/css"; } }
We create a class that implements the
IBundleTransform interface. In the
Process method we invoke the LESS parser to transform the LESS file to CSS, and we set the content type accordingly.
Here is how we define a less bundle:
Bundle lessBundle = new Bundle("~/Content/themes/base/less") .Include("~/Content/themes/base/site.less"); lessBundle.Transforms.Add(new LessTransform()); lessBundle.Transforms.Add(new CssMinify()); bundles.Add(lessBundle);
Here we create a
Bundle object (which is the base class of
ScriptBundle and
StyleBundle), and we specify the virtual path and the file to include in the bundle. We then add two transforms. First we add our custom transform to covert the LESS file to a CSS. We then add the
CssMinify transform, so once the LESS file is transformed to a CSS file it can be minified (note that the order is significant). Alternatively, we could create a custom bundle class, such as
LessBundle that derives from
Bundle and adds the transforms in its constructor. This is useful if we have to define multiple LESS bundles.
And that's it! We just added support for LESS... You can use bundles to transform into any file type before sending it to the client.
Summary
Bundling is a powerful new optimization option, which is available in .NET 4.5. Even if you have just one file, the minification and caching features may make it worthwhile to define a bundle.
Note that even though this tutorial is focused on ASP .NET MVC applications, bundling and minification are also available in Web Forms application. | http://tech.pro/tutorial/1411/bundling-and-minification-in-asp-net-mvc | CC-MAIN-2015-18 | refinedweb | 2,223 | 55.84 |
.bzl Style Guide
Starlark is a language that defines how software is built, and as such it is both a programming and a configuration language.
You will use Starlark to write BUILD files, macros, and build rules. Macros and rules are essentially meta-languages - they define how BUILD files are written. BUILD files are intended to be simple and repetitive.
All software is read more often than it is written. This is especially true for Starlark, as engineers read BUILD files to understand dependencies of their targets and details of their builds.This reading will often happen in passing, in a hurry, or in parallel to accomplishing some other task. Consequently, simplicity and readability are very important so that users can parse and comprehend BUILD files quickly.
When a user opens a BUILD file, they quickly want to know the list of targets in the file; or review the list of sources of that C++ library; or remove a dependency from that Java binary. Each time you add a layer of abstraction, you make it harder for a user to do these tasks.
BUILD files are also analyzed and updated by many different tools. Tools may not be able to edit your BUILD file if it uses abstractions. Keeping your BUILD files simple will allow you to get better tooling. As a code base grows, it becomes more and more frequent to do changes across many BUILD files in order to update a library or do a cleanup.
Do not create a macro just to avoid some amount of repetition in BUILD files. The DRY principle doesn’t really apply here. The goal is not to make the file shorter; the goal is to make your files easy to process, both by humans and tools.
General advice
- Use skylint.
- Follow testing guidelines.
Style
When in doubt, follow the Python style guide. In particular, use 4 spaces for indentation (we previously recommended 2, but we now follow the Python convention).
Document files and functions using docstrings. Use a docstring at the top of each
.bzlfile, and a docstring for each public function.
Rules and aspects, along with their attributes, as well as providers and their fields, should be documented using the
docargument.
Variables and function names use lowercase with words separated by underscores (
[a-z][a-z0-9_]*), e.g.
cc_library. Top-level private values start with one underscore. Bazel enforces that private values cannot be used from other files. Local variables should not use the underscore prefix.
As in BUILD files, there is no strict line length limit as labels can be long. When possible, try to use at most 79 characters per line.
In keyword arguments, spaces around the equal sign are optional, but be consistent within any given call. In general, we follow the BUILD file convention when calling macros and native rules, and the Python convention for other functions, e.g.
def fct(name, srcs): filtered_srcs = my_filter(source = srcs) native.cc_library( name = name, srcs = filtered_srcs, testonly = True, )
Prefer values
Trueand
Falseinstead of
0and
1for boolean values (e.g. when using a boolean attribute in a rule).
Do not use the
print()function in production code; it is only intended for debugging, and will spam all direct and indirect users of your
.bzlfile. The only exception is that you may submit code that uses
print()if it is disabled by default and can only be enabled by editing the source – for example, if all uses of
print()are guarded by
if DEBUG:where
DEBUGis hardcoded to false. Be mindful of whether these statements are useful enough to justify their impact on readability.
Macros
A macro is a function which instantiates one or more rules during the loading phase. In general, use rules whenever possible instead of macros. The build graph seen by the user is not the same as the one used by Bazel during the build - macros are expanded before Bazel does any build graph analysis.
Because of this, when something goes wrong, the user will need to understand
your macro’s implementation to troubleshoot build problems. Additionally,
bazel
query results can be hard to interpret because targets shown in the results
come from macro expansion. Finally, aspects are not aware of macros, so tooling
depending on aspects (IDEs and others) might fail.
A safe use for macros is leaf nodes, such as macros defining test permutations: in that case, only the “end users” of those targets need to know about those additional nodes, and any build problems introduced by macros are never far from their usage.
For macros that define non-leaf nodes, follow these best practices:
- A macro should take a
nameargument and define a target with that name. That target becomes that macro’s main target.
- All other targets defined by a macro should have their names preceded with a
_, include the
nameattribute as a prefix, and have restricted visibility.
- All the targets created in the macro should be coupled in some way to the main target.
- Keep the parameter names in the macro consistent. If a parameter is passed as an attribute value to the main target, keep its name the same. If a macro parameter serves the same purpose as a common rule attribute, such as
deps, name as you would the attribute (see below).
- When calling a macro, use only keyword arguments. This is consistent with rules, and greatly improves readability.
Engineers often write macros when the Starlark API of relevant rules is insufficient for their specific use case, regardless of whether the rule is defined within Bazel in native code, or in Starlark. If you’re facing this problem, ask the rule author if they can extend the API to accomplish your goals.
As a rule of thumb, the more macros resemble the rules, the better.
Rules
- Rules, aspects, and their attributes should use lower_case names (“snake case”).
- Rule names are nouns that describe the main kind of artifact produced by the rule, from the point of view of its dependencies (or for leaf rules, the user). This is not necessarily a file suffix. For instance, a rule that produces C++ artifacts meant to be used as Python extensions might be called
py_extension. For most languages, typical rules include:
*_library- a compilation unit or “module”.
*_binary- a target producing an executable or a deployment unit.
*_test- a test target. This can include multiple tests. Expect all tests in a
*_testtarget to be variations on the same theme, for example, testing a single library.
*_import: a target encapsulating a pre-compiled artifact, such as a
.jar, or a
.dllthat is used during compilation.
- Use consistent names and types for attributes. Some generally applicable attributes include:
srcs:
label_list, allowing files: source files, typically human-authored.
deps:
label_list, typically not allowing files: compilation dependencies.
data:
label_list, allowing files: data files, such as test data etc.
runtime_deps:
label_list: runtime dependencies that are not needed for compilation.
- For any attributes with non-obvious behavior (for example, string templates with special substitutions, or tools that are invoked with specific requirements), provide documentation using the
dockeyword argument to the attribute’s declaration (
attr.label_list()or similar).
- Rule implementation functions should almost always be private functions (named with a leading underscore). A common style is to give the implementation function for
myrulethe name
_myrule_impl.
- Pass information between your rules using a well-defined provider interface. Declare and document provider fields.
- Design your rule with extensibility in mind. Consider that other rules might want to interact with your rule, access your providers, and reuse the actions you create.
- Follow performance guidelines in your rules. | https://docs.bazel.build/versions/0.19.1/skylark/bzl-style.html | CC-MAIN-2020-34 | refinedweb | 1,266 | 64.81 |
(This article was first published on The Pith of Performance, and kindly contributed to R-bloggers)PDQ is a library of functions that helps you to express and solve performance questions about computer systems using the abstraction of queues. The queueing paradigm is a natural choice because, whether big (a web site) or small (a laptop), all computer systems can be represented as a network or circuit of buffers and a buffer is a type of queue.
As a performance analyst, there are several things I really like about using PDQ in R; as opposed to the other programming languages: C, Perl, Python, etc. It enables you to:
- easily import (large) data with a variety formats
- perform sophisticated statistical analysis
- extract input parameters for a PDQ model
- construct and execute the PDQ model within R
- plot the PDQ output and compare it with the original data
- test your ideas in the R console and save the best into a script
R syntax for naming function dependency is the same as Perl. The :: operator is used for explicitly exported names. It also avoids conflict between packages the export different functions with the same name. The ::: operator is used for access to functions that are not exported in the package namespace.
Let's look at the above steps in the context of an example based on load testing data. A key point to observe here is how the performance data and the performance model play together to provide validation of the measurements.
Performance dataWe begin by importing the load test data from measurements of an application intended for a three-tier architecture.
Even though the ineq package is part of base R functionality, I've loaded it explicitly so as to name its functions explicitly. This will also provide a contrast with explicitly named functions from the PDQ package.Even though the ineq package is part of base R functionality, I've loaded it explicitly so as to name its functions explicitly. This will also provide a contrast with explicitly named functions from the PDQ package.
library(ineq)
library(pdq)
# Read in the performance measurements
gdat <- read.csv("/Users/njg/.../gcap.dat",header=TRUE)
The columns are respectively the client load, measured throughput, response time (in milliseconds), and system utilization on each of the three tiers.The columns are respectively the client load, measured throughput, response time (in milliseconds), and system utilization on each of the three tiers.
> gdat
Vusr Xgps Rms Uweb Uapp Udbm
1 1 24 26.0 0.21 0.08 0.04
2 2 48 26.0 0.41 0.13 0.05
3 4 85 29.3 0.74 0.20 0.05
4 7 100 44.7 0.95 0.23 0.05
5 10 115 66.0 0.96 0.22 0.06
6 20 112 140.0 0.97 0.22 0.06
Statistical analysisWe can now perform various kinds of statistical analysis on these data.
More significantly, we can use R statistical functions to derive appropriate parameters for a PDQ model.More significantly, we can use R statistical functions to derive appropriate parameters for a PDQ model.
> summary(gdat)
Vusr Xgps Rms Uweb Uapp
Min. : 1.000 Min. : 24.00 Min. : 26.00 Min. :0.2100 Min. :0.0800
1st Qu.: 2.500 1st Qu.: 57.25 1st Qu.: 26.82 1st Qu.:0.4925 1st Qu.:0.1475
Median : 5.500 Median : 92.50 Median : 37.00 Median :0.8450 Median :0.2100
Mean : 7.333 Mean : 80.67 Mean : 55.33 Mean :0.7067 Mean :0.1800
3rd Qu.: 9.250 3rd Qu.:109.00 3rd Qu.: 60.67 3rd Qu.:0.9575 3rd Qu.:0.2200
Max. :20.000 Max. :115.00 Max. :140.00 Max. :0.9700 Max. :0.2300
Udbm
Min. :0.04000
1st Qu.:0.05000
Median :0.05000
Mean :0.05167
3rd Qu.:0.05750
Max. :0.06000
In particular, we calculate the average service times on each tier (second row) by applying Little's law.In particular, we calculate the average service times on each tier (second row) by applying Little's law.
# Apply Little's law to get mean service times + CoVs
Sweb <- mean(gdat$Uweb/gdat$Xgps)
Sapp <- mean(gdat$Uapp/gdat$Xgps)
Sdbm <- mean(gdat$Udbm/gdat$Xgps)
Csw <- ineq::var.coeff(gdat$Uweb/gdat$Xgps)
Csa <- ineq::var.coeff(gdat$Uapp/gdat$Xgps)
Csd <- ineq::var.coeff(gdat$Udbm/gdat$Xgps)
s1 <- sprintf("System: %6s %6s %6s\n", "Web","App","DBMS")
s2 <- sprintf("Mean S: %6.4f %6.4f %6.4f\n", Sweb, Sapp, Sdbm)
s3 <- sprintf("CoV S: %6.4f %6.4f %6.4f\n", Csw, Csa, Csd)
cat("\n",s1,s2,s3)
System: Web App DBMS
Mean S: 0.0088 0.0024 0.0008
CoV S: 0.0411 0.1989 0.5271
PDQ modelAs shown in Figure 1, the service times for each of the three tiers in the load-test platform can be represented as queueing resources in PDQ.
In the above PDQ model, we've selected the predicted throughput and the predicted response times to compare with the original load-test data.In the above PDQ model, we've selected the predicted throughput and the predicted response times to compare with the original load-test data.
# Plotting variables
xc <- 0 # Vuser loads
yc <- 0 # PDQ throughputs
rc <- 0 # PDQ response times
# Define and solve the PDQ model
for(n in 1:max(gdat$Vusr)) {
pdq::Init("Three-Tier Model")
pdq::CreateClosed("httpGETs", TERM, as.numeric(n), 0.028)
pdq::CreateNode("WebServer", CEN, FCFS)
pdq::CreateNode("AppServer", CEN, FCFS)
pdq::CreateNode("DBMServer", CEN, FCFS)
pdq::SetDemand("WebServer", "httpGETs", Sweb)
pdq::SetDemand("AppServer", "httpGETs", Sapp)
pdq::SetDemand("DBMServer", "httpGETs", Sdbm)
pdq::Solve(EXACT)
xc[n] <- n
yc[n] <- pdq::GetThruput(TERM, "httpGETs")
rc[n] <- pdq::GetResponse(TERM, "httpGETs") * 10^3
}
Plot PDQ results
The above R code produces the following plot array:The above R code produces the following plot array:
# Plot throughput and response time models
par(mfrow=c(2,1))
plot(xc, yc, type="l", lwd=1, col="blue", ylim=c(0,120), main="PDQ Throughput Model", xlab="Vusers (N)", ylab="Gets/s X(N)")
points(gdat$Vusr, gdat$Xgps)
plot(xc, rc, type="l", lwd=1, col="blue", ylim=c(0,220), main="PDQ Response Time Model", xlab="Vusers (N)", ylab="ms R(N)")
points(gdat$Vusr, gdat$Rms)
PDQ reportOptionally, we can produce a formal PDQ report to examine the performance of each of the three tiers, even if we don't have any corresponding performance measurements from the load-test platform. This is one way by which bottlenecks can be predicted and checked before deploying into production.
> pdq::Report()
***************************************
****** Pretty Damn Quick REPORT *******
***************************************
*** of : Sun May 15 18:26:21 2011 ***
*** for: Three-Tier Model ***
*** Ver: PDQ Analyzer v5.0 030211 ***
***************************************
***************************************
=======================================
****** PDQ Model INPUTS *******
=======================================
Node Sched Resource Workload Class Demand
---- ----- -------- -------- ----- ------
CEN FCFS WebServer httpGETs TERML 0.0088
CEN FCFS AppServer httpGETs TERML 0.0024
CEN FCFS DBMServer httpGETs TERML 0.0008
Queueing Circuit Totals:
Streams: 1
Nodes: 3
WORKLOAD Parameters:
httpGETs 20.00 0.0120 0.03
=======================================
****** PDQ Model OUTPUTS *******
=======================================
Solution Method: EXACT
****** SYSTEM Performance *******
Metric Value Unit
------ ----- ----
Workload: "httpGETs"
Mean concurrency 16.8004 Users
Mean throughput 114.2725 Users/Sec
Response time 0.1470 Sec
Round trip time 0.1750 Sec
Stretch factor 12.2633
Bounds Analysis:
Max throughput 114.2725 Users/Sec
Min response 0.0120 Sec
Max Demand 0.0088 Sec
Tot demand 0.0120 Sec
Think time 0.0280 Sec
Optimal clients 4.5696 Clients
****** RESOURCE Performance *******
Metric Resource Work Value Unit
------ -------- ---- ----- ----
Throughput WebServer httpGETs 114.2725 Users/Sec
Utilization WebServer httpGETs 100.0000 Percent
Queue length WebServer httpGETs 16.3144 Users
Waiting line WebServer httpGETs 15.3144 Users
Waiting time WebServer httpGETs 0.1340 Sec
Residence time WebServer httpGETs 0.1428 Sec
Throughput AppServer httpGETs 114.2725 Users/Sec
Utilization AppServer httpGETs 27.7529 Percent
Queue length AppServer httpGETs 0.3841 Users
Waiting line AppServer httpGETs 0.1066 Users
Waiting time AppServer httpGETs 0.0009 Sec
Residence time AppServer httpGETs 0.0034 Sec
Throughput DBMServer httpGETs 114.2725 Users/Sec
Utilization DBMServer httpGETs 9.2447 Percent
Queue length DBMServer httpGETs 0.1019 Users
Waiting line DBMServer httpGETs 0.0094 Users
Waiting time DBMServer httpGETs 0.0001 Sec
Residence time DBMServer httpGETs 0.0009 Sec... | http://www.r-bloggers.com/applying-pdq-in-r-to-load-testing/ | CC-MAIN-2015-11 | refinedweb | 1,385 | 60.21 |
In this article, I will discuss how to write custom patterns for your snowflake decoration. This is a rather advanced topic, and there are a number of prerequisites that are required and listed below. Nevertheless, it is rewarding to you see your very own pattern displayed on the decoration.
- You must solder a 5-pin programming header to all snowflake boards you wish to reprogram, which is not included in the kit from Pimoroni.
- An SWD programmer is required to write the firmware to the microcontroller.
- Established C++ language knowledge.
If you are still with me at this point 😆, please read “Programming the Snowflake Decoration” if you have not already done so. The article describes the basic setup of the toolchain required for reprogramming.
First, Some Basics
Blinking a single LED is easy — displaying a smooth animation is not.
In the firmware, I use a number of techniques to optimize the display:
- Double-buffering
- Frame-synchronization
- Non-linear PWM
- Frame-based animation system
- Fixed point math
Double-Buffering
You want to implement double-buffering to prevent incomplete data from being displayed. This is a very simple technique, and is most effective with frame synchronization.
Check the
Display.hpp and
Display.cpp files from the snowflake firmware. This code implements software PWM using an interrupt to control the brightness of all 19 LEDs. The code reads a value from a buffer with 19 bytes. Each byte represents the brightness-level for a single LED.
Without double-buffering, you will experience many undesired side effects.
Imagine this situation: All LEDs are off and you are about to turn them all on to full brightness. You start to write the full brightness values to the buffer, but your code is interrupted by the display interrupt. Only the first ten values were written to the full brightness, and the nine remaining are still zero.
The first ten LEDs are turned on by the display interrupt handler code. After the interrupt, the processor returns to your code and writes the remaining nine values. For a short period, there was an incomplete frame visible on the decoration.
If this happens once every minute, it is likely that nobody will notice it – but if this happens 20-30 times per second, the displayed animation will look rather strange. In certain situations, if the animation code has even a slightly different frequency than the display code, you will see noticeable side effects on the display.
Double-buffering solves this problem.
Double-buffering helps solve this problem. You can simply use two buffers. One buffer is displayed and one is prepared for display. If all writing for one buffer is complete, the display will then switch to the new buffer.
Frame-Synchronization
We implement frame-synchronization to switch between the two buffers at a defined point in time.
This illustration displays a program that switches an LED between 50% and 90% brightness. If the switching is not synchronized, you get a mix between the two PWM values.
At first glance, you may think this is rather useful. It will add intermediate values to the animation, which smoothes quick changes. If you just slowly blend between brightness levels, this can be the case. Yet, if you try to create sparkling effects, these intermediate values will kill the effect.
Non-linear PWM
Thanks to rhodopsin in the rods of the retina in your eyes, your brain can detect very small amounts of light. To optimize night vision, the perception of brightness levels is not linear, but somewhat logarithmic.
If you drive an LED using PWM and measure the emitted light in lumens, you will obtain linear results. An LED emitting 500lm when fully powered will emit 250lm with a 50% PWM ratio.
However, your perception of this brightness is very different. You will observe a large difference between 1% and 2%, but it will be difficult to differentiate between 90% and 91%.
If you look at this problem superficially, the solution is simple. You can simply create a conversion table to adapt to the logarithmic perception.
Let’s do some 8-bit math: You would like to have 64 brightness levels, from zero as black to 64 as fully on. To prevent any visible flickering, you run the software PWM at a high frequency, which supports 64 PWM levels.
0: 0.0000 0 1: 0.0002 0 2: 0.0020 0 3: 0.0066 0 4: 0.0156 0 5: 0.0305 0 6: 0.0527 0 7: 0.0837 0 8: 0.1250 0 9: 0.1780 0 10: 0.2441 0 11: 0.3250 0 12: 0.4219 0 13: 0.5364 1 ... 60: 52.7344 53 61: 55.4153 55 62: 58.1855 58 63: 61.0466 61 64: 64.0000 64
This table was generated using the following Python script:
import math level_count = 64 for level in range(level_count + 1): pwm = math.pow(level / level_count, 3) * level_count print(f'{level:4d}: {pwm:8.3f} {round(pwm):3d}')
Adjusting the brightness perception requires a formula such as:
As you can see, this leads to a long series of zero values at the beginning of the table. You would need at least a 16bit resolution for your LED PWM implementation to get the required precision.
0: 0x00000 1: 0x00001 2: 0x00002 3: 0x00007 4: 0x00010 ... 60: 0x0d2f0 61: 0x0dda9 62: 0x0e8be 63: 0x0f430 64: 0x10000
The Performance Problem of Linear PWM
For linear PWM, you set a timer to a regular interval. An interrupt is triggered in the defined interval which controls the LED outputs.
This illustration shows a very simplified system with only 9 different brightness levels. The red bars at the top of the timeline represents the executed interrupt code.
This is the more straightforward way to implement PWM on a microcontroller if there is no dedicated PWM peripheral for all outputs. In the case of DMA support, the interrupt code is replaced by a large bit-table — but the core principle remains the same.
To avoid perceptible flickering, the PWM frequency should be greater than 400Hz. If you want to provide 256 brightness levels at this frequency, the interrupt must be called 102’400 times per second, at 102.4kHz.
Now, consider a microcontroller executing ten instructions per microsecond (e.g. running at 10MHz). At 102.4kHz, it could only execute approximate 90 instructions in the interrupt – and this would use the full capacity of the processor without any room for other code.
To solve the performance problem, you can either lower the overall frequency of 400Hz, and risk perceptible flickering, or lower the number of levels with poor stepping in the dim brightness levels.
Pros
- Simple implementation.
- Not very time-sensitive.
Cons
- Brightness adaptation required.
- More brightness levels required due to the adaptation.
- Many brightness levels are not used because of the adaptation.
- Uses a large amount of CPU time for the interrupt if not implemented via DMA.
Non-Linear PWM
With non-linear PWM, you utilize a precise timer for the interrupt dynamically.
At the start of each interrupt, a new dynamic timing to the next interrupt is set, which creates a logarithmic timing behaviour.
As you can see, at very low levels, the timing between the interrupts would be too short without overlapping. This is solved by merging the first levels into one initial interrupt block.
Pros
- Dim brightness levels are possible.
- No adaptation of levels required.
- Fewer brightness levels required.
- Less interrupt code executed.
Cons
- Complex implementation.
- Time-sensitive interrupt.
Frame-Based Animation System
Many different patterns (called
Scene in the code) are integrated in the firmware. In Random Mode, one pattern will blend smoothly to another. This is possible using a highly abstract, frame-based animation system.
Code generating only an effect (scene, pattern) must provide a sequence of frames with the new states for all 19 LEDs. Each call has to provide the next frame in the sequence, just like a video stream.
This makes the scene code completely independent from the rest of the system, meaning it is free from any dependencies. Effects can then be implemented in a very simple, abstract way.
The animation system in the snowflake decoration runs at ~32 frames per second, allowing for very smooth effects.
Fixed Point Math
Cortex-M0+ chips have no hardware support for floating-point numbers. For best performance, you must stick with integer calculations. However, there is a good compromise between these two worlds, called fixed-point math.
The class
Fixed16 is located in my HAL layer, and is also contained in the snowflake firmware. It implements a 32-bit fixed-point value with a 16-bit fraction part. You can use it like any floating-point value, but calculations are completed nearly as fast as integer math.
Using this class, we can represent brightness levels as values between
0.0 and
1.0, where
0.0 is off and
1.0 is full-on. This has many benefits:
- It is an abstract system in which you do not need to know the actual number of brightness levels of the system.
- Because of this abstraction, any effect can easily be ported to another implementation with more or fewer brightness levels.
- Calculations to mix and blend frames are simple and precise.
- Interpolation between values, used for any smooth transition, is straightforward.
Where to Start
Be sure to download the latest version of the firmware, 1.2.2. It contains a template scene for a quick start.
The files
src/scene/User.hpp and
src/scene/User.cpp contain the
User scene, which is already integrated into the firmware. Go ahead and modify the code in these files for your first experiments.
The Structure of a Scene
An effect or pattern is called a scene in the firmware. A scene is no class, but rather a well-defined interface in a namespace.
namespace scene { namespace User { /// The number of frames for this scene /// const FrameIndex cFrameCount = 1216; /// The function to initialize this scene. /// void initialize(SceneData *data, uint8_t entropy); /// The function to get a frame from this scene. /// Frame getFrame(SceneData *data, FrameIndex frameIndex); } }
Each scene is found in the namespace
scene and defines its own namespace with the name of the scene. In this case, the second namespace is called
User.
The interface is defined in the header file
User.hpp and must consist of the following three elements:
- A const variable
cFrameCountwith the number of frames in the scene.
- The
initializefunction, which is called once before a scene is displayed.
- The
getFramefunction, which is called ~32 times per second to obtain the next frame of the scene.
namespace scene { namespace User { void initialize(SceneData*, uint8_t) { // empty } Frame getFrame(SceneData*, FrameIndex frameIndex) { Frame frame; for (uint8_t i = 0; i < Display::cLedCount; ++i) { const auto shiftedValue = static_cast<uint8_t>((frameIndex + i) % Display::cLedCount); frame.pixelValue[i] = PixelValue::normalFromRange<uint8_t>(0, Display::cLedCount-1, shiftedValue); } return frame; } } }
Here, you see a minimal example implementation in
User.cpp. In this example, the
initialize function is not used and remains empty.
In the
getFrame function, a black frame is created with the line
Frame frame;. Next, the
for loop assigns new values to this frame which is returned in the last line.
The parameter
frameIndex of the
getFrame function is incremented for each call. In the current example code, from zero to
1215, then the counter will start over at zero. The number of counted frame indexes is modified using the
cFrameCount constant in the header file.
Enable Testing Mode
Open the file
Configuration.hpp. You will see that it contains various configuration variables for the firmware. Now, search for the following line:
const bool cStartWithUserScene = false;
Set the value to
true:
const bool cStartWithUserScene = true;
If you compile the firmware and run it on the snowflake board, it will start directly with the
User scene.
The Frame
Remove the example code from the
getFrame function and replace it with this code:
Frame getFrame(SceneData*, FrameIndex frameIndex) { Frame frame; frame.pixelValue[0] = PixelValue(0.1f); frame.pixelValue[5] = PixelValue(0.5f); frame.pixelValue[9] = PixelValue(1.0f); return frame; }
The LED indexes in each frame are arranged as shown in the following figure:
By assigning a
PixelValue to individual frame indices, you set the brightness of these LEDs. A pixel value lies within the range of
0.0f and
1.0f. Here,
0.0f is black and
1.0f is maximum brightness.
fsuffix to define
floatliterals.
PixelValue(…). This will convert the floating point number into a fixed point number at the compile time.
Add an Index-Based Animation
The simplest way to create an animation is by using the frame index, on which you will base the animation:
Frame getFrame(SceneData*, FrameIndex frameIndex) { Frame frame; frame.pixelValue[frameIndex % Display::cLedCount] = PixelValue(0.75f); return frame; }
Conclusion
Implementing custom animations is relatively straightforward thanks to the extensive animation framework that already exists in the firmware. You can create numerous interesting effects, even with just a few lines of code.
Go ahead and start experimenting with simple animations and take a look at the existing scenes, which use slightly different animation techniques. In the next part of this series, I will explain some of these in more detail.
If you have any questions, missed any information, or simply want to provide feedback, feel free to comment below or reach out to us on Twitter!
More Posts
Recreating the Human Perception of the Snowflake Sparkling Effect
Snowflake Component Side
Snowflake Project Documentation
Snowflake Decoration Available on the Pimoroni Store
Snowflake Project Videos
1 thought on “How to Write Custom Snowflake Patterns”
Thanks for this, lots of very useful information. | https://luckyresistor.me/2019/12/07/how-to-write-custom-snowflake-patterns-1/ | CC-MAIN-2022-05 | refinedweb | 2,271 | 66.54 |
#include <sql_string.h>
A wrapper class for null-terminated constant strings. Constructors make sure that the position of the '\0' terminating byte in m_str is always in sync with m_length.
This class must stay as small as possible as we often pass it and its descendants (such as Name_string) into functions using call-by-value evaluation.
Don't add new members or virual methods into this class!
Compare to another Simple_cstring.
Check if m_ptr is set.
Return name length.
Return string buffer.
Initialize from a C string whose length is already known.
Set to a null-terminated string.
Copy to the given buffer | http://mingxinglai.com/mysql56-annotation/classSimple__cstring.html | CC-MAIN-2019-22 | refinedweb | 103 | 71 |
Welcome! Today we’re going to start building a Flask app that calculates word-frequency pairs based on the text from a given URL. This is a full-stack tutorial.
Free Bonus: Click here to get access to a free Flask + Python video tutorial that shows you how to build Flask web app, step-by-step.
Updates:
- 03/22/2016: Upgraded to Python version 3.5.1, and added autoenv version 1.0.0.
- 02/22/2015: Added Python 3 support.
- Part One: Set up a local development environment and then deploy both a staging and a production environment on Heroku. (current)
- Part Two: Set up a PostgreSQL database along with SQLAlchemy and Alembic to handle migrations.
-.
Project Setup
We’ll start with a basic “Hello World” app on Heroku with staging (or pre-production) and production environments.
For the initial setup, you should have some familiarity with the following tools:
- Virtualenv -
- Flask -
- git/Github -
- Heroku (basics) -
First things first, let’s get a working directory set up:
$ mkdir flask-by-example && cd flask-by-example
Initialize a new git repo within your working directory:
$ git init
Set up a virtual environment to use for our application:
$ pyvenv-3.5 env $ source env/bin/activate
You should now see you
(env) to the left of the prompt in the terminal, indicating that you are now working in a virtual environment.
In order to leave your virtual environment, just run
deactivate, and then run
source env/bin/activatewhen you are ready to work on your project again.
Next we’re going to get our basic structure for our app set up. Add the following files to your “flask-by-example” folder:
$ touch app.py .gitignore README.md requirements.txt
This will give you the following structure:
├── .gitignore ├── app.py ├── README.md └── requirements.txt
Be sure to update the .gitignore file from the repo.
Next install Flask:
$ pip install Flask==0.10.1
Add the installed libraries to our requirements.txt file:
$ pip freeze > requirements.txt
Open up app.py in your favorite editor and add the following code:
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello World!" if __name__ == '__main__': app.run()
Run the app:
$ python app.py
And you should see your basic “Hello world” app in action on. Kill the server when done.
Next we’re going to set up our Heroku environments for both our production and staging app.
Heroku Setup
If you haven’t already, create a Heroku account, download and install the Heroku Toolbelt, and then in your terminal run
heroku login to log in to Heroku.
Once done, create a Procfile in your project’s root directory:
$ touch Procfile
Add the following line to your newly created file
web: gunicorn app:app
Make sure to add gunicorn to your requirments.txt file
$ pip install gunicorn==19.4.5 $ pip freeze > requirements.txt
We also need to specify a Python version so that Heroku uses the right Python Runtime to run our app with. Simply create a file called runtime.txt with the following code:
python-3.5.1
Commit your changes in git (and optionally push to Github), then create two new Heroku apps.
One for production:
$ heroku create wordcount-pro
And one for staging:
$ heroku create wordcount-stage
These names are now taken, so you will have to make your Heroku app name unique.
Add your new apps to your git remotes. Make sure to name one remote pro (for “production”) and the other stage (for “staging”):
$ git remote add pro git@heroku.com:YOUR_APP_NAME.git $ git remote add stage git@heroku.com:YOUR_APP_NAME.git
Now we can push both of our apps live to Heroku.
- For staging:
git push stage master
- For production:
git push pro master
Once both of those have been pushed, open the URLs up in your web browser and if all went well you should see your app live in both environments.
Staging/Production Workflow
Let’s make a change to our app and push only to staging:
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "Hello World!" @app.route('/<name>') def hello_name(name): return "Hello {}!".format(name) if __name__ == '__main__': app.run()
Run your app locally to make sure everything works -
python app.py
Test it out by adding a name after the URL - i.e.,.
Now let’s try out our changes on staging before we push them live to production. Make sure your changes are committed in git and then push your work up to the staging environment -
git push stage master.
Now if you navigate to your staging environment, you’ll be able to use the new URL - i.e., “/mike” and get “Hello NAME” based on what you put into the URL as the output in the browser. However, if you try the same thing on the production site you will get an error. So we can build things and test them out in the staging environment and then when we’re happy with the changes, we can push them live to production.
Let’s push our site to production now that we’re happy with it -
git push pro master
Now we have the same functionality live on our production site.
This staging/production workflow allows us to make changes, show things to clients, experiment, etc. - all within a sandboxed server without causing any changes to the live production site that users are, well, using.
Config Settings
The last thing that we’re going to do is set up different config environments for our app. Often there are things that are going to be different between your local, staging, and production setups. You’ll want to connect to different databases, have different AWS keys, etc. Let’s set up a config file to deal with the different environments.
Add a config.py file to your project root:
$ touch config.py
With our config file we’re going to borrow a bit from how Django’s config is set up. We’ll have a base config class that the other config classes inherit from. Then we’ll import the appropriate config class as needed.
Add the following to your newly created config.py file:
import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SECRET_KEY = 'this-really-needs-to-be-changed' class ProductionConfig(Config): DEBUG = False class StagingConfig(Config): DEVELOPMENT = True DEBUG = True class DevelopmentConfig(Config): DEVELOPMENT = True DEBUG = True class TestingConfig(Config): TESTING = True
We imported
os and then set the
basedir variable as a relative path from any place we call it to this file. We then set up a base
Config() class with some basic setup that our other config classes inherit from. Now we’ll be able to import the appropriate config class based on the current environment. Thus, we can use environment variables to choose which settings we’re going to use based on the environment - e.g., local, staging, production.
Local Settings
To set up our application with environment variables, we’re going to use autoenv. This program allows us to set commands that will run every time we cd into our directory. In order to use it, we will need to install it globally. First, exit out of your virtual environment in the terminal, install autoenv, then and add a .env file:
$ deactivate $ pip install autoenv==1.0.0 $ touch .env
Next, in your .env file, add the following:
source env/bin/activate export APP_SETTINGS="config.DevelopmentConfig"
Run the following to update then refresh your .bashrc:
$ echo "source `which activate.sh`" >> ~/.bashrc $ source ~/.bashrc
Now, if you move up a directory and then cd back into it, the virtual environment will automatically be started and the
APP_SETTINGS variable is declared.
Heroku Settings
Similarly we’re going to set environment variables on Heroku.
For staging run the following command:
$ heroku config:set APP_SETTINGS=config.StagingConfig --remote stage
For production:
$ heroku config:set APP_SETTINGS=config.ProductionConfig --remote pro
To make sure that we use the right environment change app.py:
import os from flask import Flask app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) @app.route('/') def hello(): return "Hello World!" @app.route('/<name>') def hello_name(name): return "Hello {}!".format(name) if __name__ == '__main__': app.run()
We imported
os and used the
os.environ method to import the appropriate
APP_SETTINGS variables, depending on our environment. We then set up the config in our app with the
app.config.from_object method.
Commit and push your changes to both staging and production (and Github if you have it setup).
Want to test the environment variables out to make sure it’s detecting the right environment (sanity check!)? Add a print statement to app.py:
print(os.environ['APP_SETTINGS'])
Now when you run the app, it will show which config settings it’s importing:
Local:
$ python app.py config.DevelopmentConfig
Commit and push again to staging and production. Now let’s test it out…
Staging:
$ heroku run python app.py --app wordcount-stage Running python app.py on wordcount-stage... up, run.7699 config.StagingConfig
Production:
$ heroku run python app.py --app wordcount-pro Running python app.py on wordcount-pro... up, run.8934 config.ProductionConfig
Be sure to remove
print(os.environ['APP_SETTINGS']) when done, commit, and push back up to your various environments.
Conclusion
With the setup out of the way, we’re going to start to build out the word counting functionality of this app. Along the way, we’ll add a task queue to set up background processing for the word count portion, as well dig further into our Heroku setup by setting up the configuration and migrations for our database (part2) which we’ll use to store our word count results. Best!
Free Bonus: Click here to get access to a free Flask + Python video tutorial that shows you how to build Flask web app, step-by-step.
Grab the code from the repo.
This is a collaboration piece between Cam Linke, co-founder of Startup Edmonton, and the folks at Real Python. | https://realpython.com/flask-by-example-part-1-project-setup/ | CC-MAIN-2019-04 | refinedweb | 1,685 | 66.23 |
Ruminations on technology, software and philosophy.
I just finished tracking down a Visual C++ compiler bug. This bug exists in the optimizer in VC 2003 and 2005. It does not exist in VC 2008. It only happens with optimization turned on (ie, Release build).
Finding this bug was interesting in that we had a defect reported from a customer that caused an exception to be raised when trying to load a particular image. This image had an error in it and was causing a throw deep within the codec. This looked like an easy bug to find. Unfortunately for me, unit tests would pass on my machine, but not on the build server. This turned a routine bug into a nightmare bug - the debugger was not likely to help me. What I ended up doing was taking the library that (most likely) contained the bug and built it release, and used that in the debug build on my machine. This allowed me to reproduce the bug (and proving that it was a release bug). Using divide and conquer, I found where the exception was being thrown and to my great surprise, where the catch was being totally missed.
The bug is this:
if you have a try/catch block in C++ that only calls "pure" C code, the optimizer sees an opportunity to remove the catch block as C can't throw. If however, the C code calls back into C++ and that code throws, the exception will blow past the handler.
It is arguable that C++ code called from C should never throw without catching before returning to the caller. If the catch block is outside the C, it could cause memory or resource leaks. In this particular case, the function being called was a function pointer acting as an event handler. Basically, it was signaling to the caller, "something bad has happened - I've cleaned up, now it's your turn".
To illustrate how this happens, I've created a minimal code example to reproduce it. This code is a simple C++ app that calls a C function, PerformOperation with a C++ callback. PerformOperation prints a message than calls the callback if it's non-null. The C++ implementation of the callback throws an empty class to signal a failure. The calling code should catch this error and report failure. In debug, you get correct behavior. In release, you get an unhandled exception.
File - Perf.h - a header describing an external operation in C:
#ifndef _H_Perf#define _H_Perf#ifdef __cplusplusextern "C" {#endiftypedef void (*fPerformer)();extern void PerformOperation(fPerformer pf);#ifdef __cplusplus}; // _cplusplus#endif#endif
File - Perf.c - an implementation of the function PerformOperation
#include "Perf.h"#include "stdio.h"#ifdef __cplusplusextern "C" {#endifvoid PerformOperation(fPerformer pf){ printf("Performing operation..."); if (pf) pf();}#ifdef __cplusplus};#endif
File - OptimizerBug.cpp - calls the performer from C++ with a C++ callback that throws
what happens - in a debug build, you will see "Performing operation...fail." - this is correct output. In a release build, the code will crash with an unhandled exception. I need to also stress that the function PerformOperation needs to live in its own file. If it lives in OptimizerBug.cpp, the optimizer goes even further and notices that PerformOperation can be inlined, and since it's only being used once, the callback can be inlined too and that it will always throw. It's a nice chunk for call->call optimization, but it makes the bug go away. If the implementation is in a different file, the optimizer doesn't inline.
the assembly output for the release build in VC 2005:
; 20 : bool fail = false;; 21 : try {; 22 : PerformOperation(CPPPerform);;; Here's the call to PerformOperation; push OFFSET ?CPPPerform@@YAXXZ ; CPPPerform call _PerformOperation; 23 : }; 24 : catch (PerfError) {; 25 : fail = true;; 26 : }; 27 : ; 28 : cout << (fail ? "fail." : "pass.");
;; and here's the call to cout, operator << - you'll notice; that the fail = true is not here.;
push OFFSET ??_C@_05MFHHNNDH@pass?4?$AA@ push OFFSET ?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::cout call ??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator<<<std::char_traits<char> > add esp, 12 ; 0000000cH; 29 : ; 30 : return 0; xor eax, eax
There is a workaround - the most basic is to refactor to never throw in a C++ callback called from C. Where this is not possible, the routine with the catch block needs to be surrounded by:
#if NDEBUG#pragma optimize("", off)#endif
#if NDEBUG
#pragma optimize("", on)
#endif
This bug is NOT fixed by changing the catch to catch(...) - the optimizer will take out the handler no matter what.
On a more meta level, I want to talk more about bugs that happen only in release and not in debug. These are among the most frustrating bugs as it looks like you have to shed your main tool for tracking them down - your debugger. In my case, I was able to isolate the behavior and build that particular component with release. You can still use the debugger in release, but it's not as useful as you might think since the optimizer may shift the order of operations of things and you will see some truly bizarre behavior. For example, I watched the execution of an if (condition) statement where condition was false - and the debugger stepped into the block (!!). This was because a lot of the method had been optimizer rearranged to reduce size and increase speed. I find it easier to use the Disassembly window in VisualStudio so I can better see what the compiled code is. While doing this, I spotted the missing catch block - quite the WTF.
PingBack from
You've been kicked (a good thing) - Trackback from DotNetKicks.com
Cheap xanax xanax online xanax bar al bawaba blogs. My blog order xanax mg xanax cheap xanax online. Cheap xanax online buy cheap xanax buy cheap xanax. | http://www.atalasoft.com/cs/blogs/stevehawley/archive/2008/06/13/woo-hoo-compiler-bug.aspx | crawl-002 | refinedweb | 990 | 63.9 |
local variables rewrote primitives2c.el in Forth (prims2x.el) various small changes Added Files: from-cut-here gforth.el gforth.texi glocals.fs gray.fs locals-test.fs prims2x.fs: \ the locals stack grows downwards (see primitives) 68: \ of the local variables of a group (in braces) the leftmost is on top, 69: \ i.e. by going onto the locals stack the order is reversed. 70: \ there are alignment gaps if necessary. 71: \ lp must have the strictest alignment (usually float) across calls; 72: \ for simplicity we align it strictly for every group. 73: 74: vocabulary locals \ this contains the local variables 75: ' locals >body Constant locals-list \ acts like a variable that contains 76: \ a linear list of locals names 77: 78: create locals-buffer 1000 allot \ !! limited and unsafe 79: \ here the names of the local variables are stored 80: \ we would have problems storing them at the normal dp 81: 82: variable locals-dp \ so here's the special dp for locals. 83: 84: : alignlp-w ( n1 -- n2 ) 85: \ cell-align size and generate the corresponding code for aligning lp 86: dup aligned tuck - compile-lp+!# ; 87: 88: : alignlp-f ( n1 -- n2 ) 89: dup faligned tuck - compile-lp+!# ; 90: 91: \ a local declaration group (the braces stuff) is compiled by calling 92: \ the appropriate compile-pushlocal for the locals, starting with the 93: \ righmost local; the names are already created earlier, the 94: \ compile-pushlocal just inserts the offsets from the frame base. 95: 96: : compile-pushlocal-w ( a-addr -- ) ( run-time: w -- ) 97: \ compiles a push of a local variable, and adjusts locals-size 98: \ stores the offset of the local variable to a-addr 99: locals-size @ alignlp-w cell+ dup locals-size ! 100: swap ! 101: postpone >l ; 102: 103: : compile-pushlocal-f ( a-addr -- ) ( run-time: f -- ) 104: locals-size @ alignlp-f float+ dup locals-size ! 105: swap ! 106: postpone f>l ; 107: 108: : compile-pushlocal-d ( a-addr -- ) ( run-time: w1 w2 -- ) 109: locals-size @ alignlp-w cell+ cell+ dup locals-size ! 110: swap ! 111: postpone swap postpone >l postpone >l ; 112: 113: : compile-pushlocal-c ( a-addr -- ) ( run-time: w -- ) 114: -1 chars compile-lp+!# 115: locals-size @ swap ! 116: postpone lp@ postpone c! ; 117: 118: : create-local ( " name" -- a-addr ) 119: \ defines the local "name"; the offset of the local shall be stored in a-addr 120: create 121: immediate 122: here 0 , ( place for the offset ) ; 123: 124: : lp-offset, ( n -- ) 125: \ converts the offset from the frame start to an offset from lp and 126: \ adds it as inline argument to a preceding locals primitive 127: \ i.e., the address of the local is lp+locals_size-offset 128: locals-size @ swap - , ; 129: 130: vocabulary locals-types \ this contains all the type specifyers, -- and } 131: locals-types definitions 132: 133: : W: 134: create-local ( "name" -- a-addr xt ) 135: \ xt produces the appropriate locals pushing code when executed 136: ['] compile-pushlocal-w 137: does> ( Compilation: -- ) ( Run-time: -- w ) 138: \ compiles a local variable access 139: postpone @local# @ lp-offset, ; 140: 141: : W^ 142: create-local ( "name" -- a-addr xt ) 143: ['] compile-pushlocal-w 144: does> ( Compilation: -- ) ( Run-time: -- w ) 145: postpone laddr# @ lp-offset, ; 146: 147: : F: 148: create-local ( "name" -- a-addr xt ) 149: ['] compile-pushlocal-f 150: does> ( Compilation: -- ) ( Run-time: -- w ) 151: postpone f@local# @ lp-offset, ; 152: 153: : F^ 154: create-local ( "name" -- a-addr xt ) 155: ['] compile-pushlocal-f 156: does> ( Compilation: -- ) ( Run-time: -- w ) 157: postpone laddr# @ lp-offset, ; 158: 159: : D: 160: create-local ( "name" -- a-addr xt ) 161: ['] compile-pushlocal-d 162: does> ( Compilation: -- ) ( Run-time: -- w ) 163: postpone laddr# @ lp-offset, postpone 2@ ; 164: 165: : D^ 166: create-local ( "name" -- a-addr xt ) 167: ['] compile-pushlocal-d 168: does> ( Compilation: -- ) ( Run-time: -- w ) 169: postpone laddr# @ lp-offset, ; 170: 171: : C: 172: create-local ( "name" -- a-addr xt ) 173: ['] compile-pushlocal-c 174: does> ( Compilation: -- ) ( Run-time: -- w ) 175: postpone laddr# @ lp-offset, postpone c@ ; 176: 177: : C^ 178: create-local ( "name" -- a-addr xt ) 179: ['] compile-pushlocal-c 180: does> ( Compilation: -- ) ( Run-time: -- w ) 181: postpone laddr# @ lp-offset, ; 182: 183: \ you may want to make comments in a locals definitions group: 184: ' \ alias \ immediate 185: ' ( alias ( immediate 186: 187: forth definitions 188: 189: \ the following gymnastics are for declaring locals without type specifier. 190: \ we exploit a feature of our dictionary: every wordlist 191: \ has it's own methods for finding words etc. 192: \ So we create a vocabulary new-locals, that creates a 'w:' local named x 193: \ when it is asked if it contains x. 194: 195: 0. 2constant last-local \ !! actually a 2value 196: 197: also locals-types 198: 199: : new-locals-find ( caddr u w -- nfa ) 200: \ this is the find method of the new-locals vocabulary 201: \ make a new local with name caddr u; w is ignored 202: \ the returned nfa denotes a word that produces what W: produces 203: \ !! do the whole thing without nextname 204: drop nextname W: \ we don't want the thing that W: produces, 205: ['] last-local >body 2! \ but the nfa of a word that produces that value: last-local 206: [ ' last-local >name ] Aliteral ; 207: 208: previous 209: 210: : new-locals-reveal ( -- ) 211: true abort" this should not happen: new-locals-reveal" ; 212: 213: create new-locals-map ' new-locals-find A, ' new-locals-reveal A, 214: 215: vocabulary new-locals 216: new-locals-map ' new-locals >body cell+ A! \ !! use special access words 217: 218: variable old-dpp 219: 220: \ and now, finally, the user interface words 221: : { ( -- addr wid 0 ) 222: dp old-dpp ! 223: locals-dp dpp ! 224: also new-locals 225: also get-current locals definitions locals-types 226: 0 TO locals-wordlist 227: 0 postpone [ ; immediate 228: 229: locals-types definitions 230: 231: : } ( addr wid 0 a-addr1 xt1 ... -- ) 232: \ ends locals definitions 233: ] old-dpp @ dpp ! 234: begin 235: dup 236: while 237: execute 238: repeat 239: drop 240: locals-size @ alignlp-f locals-size ! \ the strictest alignment 241: set-current 242: previous previous 243: locals-list TO locals-wordlist ; 244: 245: : -- ( addr wid 0 ... -- ) 246: } 247: [char] } word drop ; 248: 249: forth definitions 250: 251: \ A few thoughts on automatic scopes for locals and how they can be 252: \ implemented: 253: 254: \ We have to combine locals with the control structures. My basic idea 255: \ was to start the life of a local at the declaration point. The life 256: \ would end at any control flow join (THEN, BEGIN etc.) where the local 257: \ is lot live on both input flows (note that the local can still live in 258: \ other, later parts of the control flow). This would make a local live 259: \ as long as you expected and sometimes longer (e.g. a local declared in 260: \ a BEGIN..UNTIL loop would still live after the UNTIL). 261: 262: \ The following example illustrates the problems of this approach: 263: 264: \ { z } 265: \ if 266: \ { x } 267: \ begin 268: \ { y } 269: \ [ 1 cs-roll ] then 270: \ ... 271: \ until 272: 273: \ x lives only until the BEGIN, but the compiler does not know this 274: \ until it compiles the UNTIL (it can deduce it at the THEN, because at 275: \ that point x lives in no thread, but that does not help much). This is 276: \ solved by optimistically assuming at the BEGIN that x lives, but 277: \ warning at the UNTIL that it does not. The user is then responsible 278: \ for checking that x is only used where it lives. 279: 280: \ The produced code might look like this (leaving out alignment code): 281: 282: \ >l ( z ) 283: \ ?branch <then> 284: \ >l ( x ) 285: \ <begin>: 286: \ >l ( y ) 287: \ lp+!# 8 ( RIP: x,y ) 288: \ <then>: 289: \ ... 290: \ lp+!# -4 ( adjust lp to <begin> state ) 291: \ ?branch <begin> 292: \ lp+!# 4 ( undo adjust ) 293: 294: \ The BEGIN problem also has another incarnation: 295: 296: \ AHEAD 297: \ BEGIN 298: \ x 299: \ [ 1 CS-ROLL ] THEN 300: \ { x } 301: \ ... 302: \ UNTIL 303: 304: \ should be legal: The BEGIN is not a control flow join in this case, 305: \ since it cannot be entered from the top; therefore the definition of x 306: \ dominates the use. But the compiler processes the use first, and since 307: \ it does not look ahead to notice the definition, it will complain 308: \ about it. Here's another variation of this problem: 309: 310: \ IF 311: \ { x } 312: \ ELSE 313: \ ... 314: \ AHEAD 315: \ BEGIN 316: \ x 317: \ [ 2 CS-ROLL ] THEN 318: \ ... 319: \ UNTIL 320: 321: \ In this case x is defined before the use, and the definition dominates 322: \ the use, but the compiler does not know this until it processes the 323: \ UNTIL. So what should the compiler assume does live at the BEGIN, if 324: \ the BEGIN is not a control flow join? The safest assumption would be 325: \ the intersection of all locals lists on the control flow 326: \ stack. However, our compiler assumes that the same variables are live 327: \ as on the top of the control flow stack. This covers the following case: 328: 329: \ { x } 330: \ AHEAD 331: \ BEGIN 332: \ x 333: \ [ 1 CS-ROLL ] THEN 334: \ ... 335: \ UNTIL 336: 337: \ If this assumption is too optimistic, the compiler will warn the user. 338: 339: \ Implementation: 340: 341: \ orig, dest and do-sys have the following structure: 342: \ address (of the branch or the instruction to be branched to) (TOS) 343: \ locals-list (valid at address) (second) 344: \ locals-size (at address; this could be computed from locals-list, but so what) (third) 345: 346: 3 constant cs-item-size 347: 348: : CS-PICK ( ... u -- ... destu ) 349: 1+ cs-item-size * 1- >r 350: r@ pick r@ pick r@ pick 351: rdrop ; 352: 353: : CS-ROLL ( destu/origu .. dest0/orig0 u -- .. dest0/orig0 destu/origu ) 354: 1+ cs-item-size * 1- >r 355: r@ roll r@ roll r@ roll 356: rdrop ; 357: 358: : CS-PUSH ( -- dest/orig ) 359: locals-size @ 360: locals-list @ 361: here ; 362: 363: : BUT sys? 1 cs-roll ; immediate restrict 364: : YET sys? 0 cs-pick ; immediate restrict 365: 366: : common-list ( list1 list2 -- list3 ) 367: \ list1 and list2 are lists, where the heads are at higher addresses than 368: \ the tail. list3 is the largest sublist of both lists. 369: begin 370: 2dup u<> 371: while 372: 2dup u> 373: if 374: swap 375: endif 376: @ 377: repeat 378: drop ; 379: 380: : sub-list? ( list1 list2 -- f ) 381: \ true iff list1 is a sublist of list2 382: begin 383: 2dup u< 384: while 385: @ 386: repeat 387: = ; 388: 389: : list-size ( list -- u ) 390: \ size of the locals frame represented by list 391: 0 ( list n ) 392: begin 393: over 0<> 394: while 395: over 396: cell+ name> >body @ max 397: swap @ swap ( get next ) 398: repeat 399: faligned nip ; 400: 401: : x>mark ( -- orig ) 402: cs-push 0 , ; 403: 404: variable dead-code \ true if normal code at "here" would be dead 405: 406: : unreachable ( -- ) 407: \ declares the current point of execution as unreachable and 408: \ prepares the assumptions for a possible upcoming BEGIN 409: dead-code on 410: dup 0<> if 411: 2 pick 2 pick 412: else 413: 0 0 414: endif 415: locals-list ! 416: locals-size ! ; 417: 418: : check-begin ( list -- ) 419: \ warn if list is not a sublist of locals-list 420: locals-list @ sub-list? 0= if 421: \ !! print current position 422: ." compiler was overly optimistic about locals at a BEGIN" cr 423: \ !! print assumption and reality 424: endif ; 425: 426: : xahead ( -- orig ) 427: POSTPONE branch x>mark unreachable ; immediate 428: 429: : xif ( -- orig ) 430: POSTPONE ?branch x>mark ; immediate 431: 432: \ THEN (another control flow from before joins the current one): 433: \ The new locals-list is the intersection of the current locals-list and 434: \ the orig-local-list. The new locals-size is the (alignment-adjusted) 435: \ size of the new locals-list. The following code is generated: 436: \ lp+!# (current-locals-size - orig-locals-size) 437: \ <then>: 438: \ lp+!# (orig-locals-size - new-locals-size) 439: 440: \ Of course "lp+!# 0" is not generated. Still this is admittedly a bit 441: \ inefficient, e.g. if there is a locals declaration between IF and 442: \ ELSE. However, if ELSE generates an appropriate "lp+!#" before the 443: \ branch, there will be none after the target <then>. 444: : xthen ( orig -- ) 445: sys? dup @ ?struc 446: dead-code @ 447: if 448: >resolve 449: locals-list ! 450: locals-size ! 451: else 452: locals-size @ 3 roll - compile-lp+!# 453: >resolve 454: locals-list @ common-list locals-list ! 455: locals-size @ locals-list @ list-size - compile-lp+!# 456: endif 457: dead-code off ; immediate 458: 459: : scope ( -- dest ) 460: cs-push ; immediate 461: 462: : endscope ( dest -- ) 463: drop 464: locals-list @ common-list locals-list ! 465: locals-size @ locals-list @ list-size - compile-lp+!# 466: drop ; immediate 467: 468: : xexit ( -- ) 469: locals-size @ compile-lp+!# POSTPONE exit unreachable ; immediate 470: 471: : x?exit ( -- ) 472: POSTPONE xif POSTPONE xexit POSTPONE xthen ; immediate 473: 474: : xelse ( orig1 -- orig2 ) 475: sys? 476: POSTPONE xahead 477: 1 cs-roll 478: POSTPONE xthen ; immediate 479: 480: : xbegin ( -- dest ) 481: cs-push dead-code off ; immediate 482: 483: : xwhile ( dest -- orig dest ) 484: sys? 485: POSTPONE xif 486: 1 cs-roll ; immediate 487: 488: \ AGAIN (the current control flow joins another, earlier one): 489: \ If the dest-locals-list is not a subset of the current locals-list, 490: \ issue a warning (see below). The following code is generated: 491: \ lp+!# (current-local-size - dest-locals-size) 492: \ branch <begin> 493: : xagain ( dest -- ) 494: sys? 495: locals-size @ 3 roll - compile-lp+!# 496: POSTPONE branch 497: <resolve 498: check-begin 499: unreachable ; immediate 500: 501: \ UNTIL (the current control flow may join an earlier one or continue): 502: \ Similar to AGAIN. The new locals-list and locals-size are the current 503: \ ones. The following code is generated: 504: \ lp+!# (current-local-size - dest-locals-size) 505: \ ?branch <begin> 506: \ lp+!# (dest-local-size - current-locals-size) 507: \ (Another inefficiency. Maybe we should introduce a ?branch-lp+!# 508: \ primitive. This would also solve the interrupt problem) 509: : until-like ( dest xt -- ) 510: >r 511: sys? 512: locals-size @ dup 4 roll - compile-lp+!# ( list dest-addr old-locals-size ) 513: r> compile, 514: >r <resolve 515: check-begin 516: locals-size @ r> - compile-lp+!# ; 517: 518: : xuntil ( dest -- ) 519: ['] ?branch until-like ; immediate 520: 521: : xrepeat ( orig dest -- ) 522: 3 pick 0= ?struc 523: postpone xagain 524: postpone xthen ; immediate 525: 526: \ counted loops 527: 528: \ leave poses a little problem here 529: \ we have to store more than just the address of the branch, so the 530: \ traditional linked list approach is no longer viable. 531: \ This is solved by storing the information about the leavings in a 532: \ special stack. The leavings of different DO-LOOPs are separated 533: \ by a 0 entry 534: 535: \ !! remove the fixed size limit. 'Tis easy. 536: 20 constant leave-stack-size 537: create leave-stack leave-stack-size cs-item-size * cells allot 538: variable leave-sp leave-stack leave-sp ! 539: 540: : clear-leave-stack ( -- ) 541: leave-stack leave-sp ! ; 542: 543: \ : leave-empty? ( -- f ) 544: \ leave-sp @ leave-stack = ; 545: 546: : >leave ( orig -- ) 547: \ push on leave-stack 548: leave-sp @ 549: dup [ leave-stack leave-stack-size cs-item-size * cells + ] Aliteral >= 550: if 551: abort" leave-stack full" 552: endif 553: tuck ! cell+ 554: tuck ! cell+ 555: tuck ! cell+ 556: leave-sp ! ; 557: 558: : leave> ( -- orig ) 559: \ pop from leave-stack 560: leave-sp @ 561: dup leave-stack <= if 562: abort" leave-stack empty" 563: endif 564: cell - dup @ swap 565: cell - dup @ swap 566: cell - dup @ swap 567: leave-sp ! ; 568: 569: : done ( -- ) 570: \ !! the original done had ( addr -- ) 571: begin 572: leave> 573: dup 574: while 575: POSTPONE xthen 576: repeat 577: 2drop drop ; immediate 578: 579: : xleave ( -- ) 580: POSTPONE xahead 581: >leave ; immediate 582: 583: : x?leave ( -- ) 584: POSTPONE 0= POSTPONE xif 585: >leave ; immediate 586: 587: : xdo ( -- do-sys ) 588: POSTPONE (do) 589: POSTPONE xbegin 590: 0 0 0 >leave ; immediate 591: 592: : x?do ( -- do-sys ) 593: 0 0 0 >leave 594: POSTPONE (?do) 595: x>mark >leave 596: POSTPONE xbegin ; immediate 597: 598: : xfor ( -- do-sys ) 599: POSTPONE (for) 600: POSTPONE xbegin 601: 0 0 0 >leave ; immediate 602: 603: \ LOOP etc. are just like UNTIL 604: \ the generated code for ?DO ... LOOP with locals is inefficient, this 605: \ could be changed by introducing (loop)-lp+!# etc. 606: 607: : loop-like ( do-sys xt -- ) 608: until-like POSTPONE done POSTPONE unloop ; 609: 610: : xloop ( do-sys -- ) 611: ['] (loop) loop-like ; immediate 612: 613: : x+loop ( do-sys -- ) 614: ['] (+loop) loop-like ; immediate 615: 616: : xs+loop ( do-sys -- ) 617: ['] (s+loop) loop-like ; immediate 618: 619: : locals-:-hook ( sys -- sys addr xt ) 620: DEFERS :-hook 621: last @ lastcfa @ 622: clear-leave-stack 623: 0 locals-size ! 624: locals-buffer locals-dp ! 625: 0 locals-list ! ; ( clear locals vocabulary ) 626: 627: : locals-;-hook ( sys addr xt -- sys ) 628: 0 TO locals-wordlist 629: locals-size @ compile-lp+!# 630: lastcfa ! last ! 631: DEFERS ;-hook ; 632: 633: ' locals-:-hook IS :-hook 634: ' locals-;-hook IS ;-hook: \ !! The lp gymnastics for UNTIL are also a real problem: locals cannot be 647: \ used in signal handlers (or anything else that may be called while 648: \ locals live beyond the lp) without changing the locals stack. 649: 650: \ About warning against uses of dead locals. There are several options: 651: 652: \ 1) Do not complain (After all, this is Forth;-) 653: 654: \ 2) Additional restrictions can be imposed so that the situation cannot 655: \ arise; the programmer would have to introduce explicit scoping 656: \ declarations in cases like the above one. I.e., complain if there are 657: \ locals that are live before the BEGIN but not before the corresponding 658: \ AGAIN (replace DO etc. for BEGIN and UNTIL etc. for AGAIN). 659: 660: \ 3) The real thing: i.e. complain, iff a local lives at a BEGIN, is 661: \ used on a path starting at the BEGIN, and does not live at the 662: \ corresponding AGAIN. This is somewhat hard to implement. a) How does 663: \ the compiler know when it is working on a path starting at a BEGIN 664: \ (consider "{ x } if begin [ 1 cs-roll ] else x endif again")? b) How 665: \ is the usage info stored? 666: 667: \ For now I'll resort to alternative 2. When it produces warnings they 668: \ will often be spurious, but warnings should be rare. And better 669: \ spurious warnings now and then than days of bug-searching. 670: 671: \ Explicit scoping of locals is implemented by cs-pushing the current 672: \ locals-list and -size (and an unused cell, to make the size equal to 673: \ the other entries) at the start of the scope, and restoring them at 674: \ the end of the scope to the intersection, like THEN does. 675: 676: 677: \ And here's finally the ANS standard stuff 678: 679: : (local) ( addr u -- ) 680: \ a little space-inefficient, but well deserved ;-) 681: \ In exchange, there are no restrictions whatsoever on using (local) 682: dup 683: if 684: nextname POSTPONE { [ also locals-types ] W: } [ previous ] 685: else 686: 2drop 687: endif ; 688: 689: \ \ !! untested 690: \ : TO ( c|w|d|r "name" -- ) 691: \ \ !! state smart 692: \ 0 0 0. 0.0e0 { c: clocal w: wlocal d: dlocal f: flocal } 693: \ ' dup >definer 694: \ state @ 695: \ if 696: \ case 697: \ [ ' locals-wordlist >definer ] literal \ value 698: \ OF >body POSTPONE Aliteral POSTPONE ! ENDOF 699: \ [ ' clocal >definer ] literal 700: \ OF POSTPONE laddr# >body @ lp-offset, POSTPONE c! ENDOF 701: \ [ ' wlocal >definer ] literal 702: \ OF POSTPONE laddr# >body @ lp-offset, POSTPONE ! ENDOF 703: \ [ ' dlocal >definer ] literal 704: \ OF POSTPONE laddr# >body @ lp-offset, POSTPONE d! ENDOF 705: \ [ ' flocal >definer ] literal 706: \ OF POSTPONE laddr# >body @ lp-offset, POSTPONE f! ENDOF 707: \ abort" can only store TO value or local value" 708: \ endcase 709: \ else 710: \ [ ' locals-wordlist >definer ] literal = 711: \ if 712: \ >body ! 713: \ else 714: \ abort" can only store TO value" 715: \ endif 716: \ endif ; 717: 718: \ : locals| 719: \ !! should lie around somewhere | https://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/glocals.fs?f=h;only_with_tag=MAIN;ln=1;content-type=text%2Fx-cvsweb-markup;rev=1.1 | CC-MAIN-2022-21 | refinedweb | 3,384 | 60.45 |
Part I - Concurrent Programming - A Primer
My purpose to writing the previous article, Concurrent Programming - A Primer, was to investigate Microsoft's Parallel FX library (PFX). As was made clear by various experts, PFX does not address the issue of application state and shared memory synchronization. One of the features of Erlang that enamored me was the concept of message passing between tasks. Specifically, the thread receiving the message gets a local copy of the message being sent by the sender thread. This completely eliminates synchronization issues. The purpose of this article is to investigate a simple TaskMessageManager (TMM) implementation that works with PFX to add serialized messaging between tasks.
If you download the code, you will also need to install the Parallel FX library. Also, and very important, if you compile the code in Debug mode, uncheck the "Define DEBUG constant" in the properties--the debug messages that the TMM outputs will kill the performance of the application when testing the TMM mode. Visual Studio 2008 is required.
Tasks register themselves with the TMM, specifying the message queue on which they are listening. The task blocks until a message is placed into the message queue. Tasks can share the same message queue so that work can be distributed among tasks. Rather than use the SelfReplicating flag option (see PFX Problems below), the application must set up tasks to run concurrently against a specific message queue. Messages are retrieved from the queue as the task requests them, meaning that it has completed its current work. A couple built-in message (cancel and done) are used, respectively, to tell the task to terminate and to indicate to the task that all its work is complete. In both cases, that task terminates. If the queue is shared by several tasks, they all terminate (a sort of broadcast to all tasks listening to the message queue).
The TMM sets up message queues in which the main application and its tasks can communicate between each other, initiating work based on the message type and contents. Furthermore, messages are copied, so that the receiver thread does not directly reference the sender thread's message. The TMM is a thin API which the developer can use to reduce the setup work necessary to achieve the same functionality.
The TMM is an experiment, one that I plan to continue further. It is not intended to be used in production code. There are clearly performance issues that will probably never be solvable in C#. There are also core architectural issues that I imagine can only be solved with a VM, like Erlang's, that facilitates moving of data between tasks as values and doesn't even include constructs for synchronization. On the other hand, the careful use of the TMM may result in an application benefiting from synchronization-less task communication.
And of course, the TMM doesn't eliminate synchronization issues between tasks, it merely moves the problem from one the developer has to deal with to one the TMM deals with for the developer. There are lots of lock statements in the TMM to control access to the message queues, and of course, there's the serialization process as well, which is ripe with performance and usability issues. This is true as well with PFX--it makes it easier for the developer to add concurrency into an application by taking the thread management problem off of the developer's hands and putting into PFX.
There are two key interfaces,
IMessage and
IClonableMessage. All messages sent to the tasks must implement
IMessage. If the message implements
IClonableMessage:
public interface IClonableMessage { IMessage DeepClone(); }
then the
DeepClone method is called rather than using the brute force .NET serialization. If you don't implement
IClonableMessage, then your message class must be serializable. The
IMessage interface is simply a stub at the moment.
In this simple example, two tasks are created, and the application waits for the tasks to register (see PFX Problems below):
task1 = Task.Create(ATask, null, TaskManager.Default, TaskCreationOptions.None, "Task1"); task2 = Task.Create(ATask, null, TaskManager.Default, TaskCreationOptions.None, "Task2"); while (!tmm.IsRegistered(task1)) {Thread.Sleep(10);} while (!tmm.IsRegistered(task2)) { Thread.Sleep(10); }
The task registers itself, and starts listening to the same message queue, specifying a 100ms timeout.
static void ATask(object obj) { tmm.RegisterTask(Task.Current, "TaskQueue"); bool stopped = false; while (!stopped) { TaskMessage tm = tmm.GetMessage(100); ...
If a task specifies a timeout, the
GetMessage call will return the built-in
NoMessage. If the task specifies no timeout (-1), the TMM internally still monitors the task to see if a cancel request has been issued by the application or the PFX TaskManager, in which case, the TMM throws the
TaskCanceledException1. Because the task might be informed by the application that it is no longer needed, via the
StopMessage, a typical task should also check for this message. In our simple example, once the task receives one of our two messages, it terminates itself:
while (!stopped) { TaskMessage tm = tmm.GetMessage(100); Debug.WriteLine("!tmm: " + Task.Current.Name + ": "+tm.Message.ToString()); if (tm.Message is SayHelloMessage) { // executes in either task 1 or task 2. Console.WriteLine("Hello!"); stopped = true; } else if (tm.Message is RequestHelloMessage) { // executes in task 1. // Post the message queue rather than a specific task. tmm.PostMessage("TaskQueue", new SayHelloMessage()); stopped = true; } else if (tm.Message is StopMessage) { stopped = true; } else if (tm.Message is NoMessage) { } }
The application posts
RequestHelloMessage to this queue. One of the tasks will be released, and it posts a
SayHelloMessage to the same queue, which usually is processed by the second task before the first one gets around to checking for more messages. In our simple test, the application does this:
tmm.PostMessage("TaskQueue", new RequestHelloMessage()); tmm.Wait();
The message queue monitors the
Task.Completed event, and removes tasks from its internal maps, so we can wait until all tasks have completed.
By looking at the trace of this application when it is run, you will see the two tasks working:
A different run shows that Task1 received the message first:
At this point, it's useful to start identifying concurrent programming patterns.
One kind of concurrent application pattern is a "Process Work Then Terminate" pattern, which is basically just a task that waits for a message, acts on that message, then terminates itself. The above example illustrates this pattern.
A slightly more complex version processes all the messages in its queue, then terminates. This assumes that the queue has been fully loaded before the task begins, otherwise the task is racing against the loader. This pattern is currently not possible (see PFX Problems below).
A more advanced pattern than the previous requires that the last message added to the queue is
StopMessage. The task only terminates when it sees this message. Obviously, this assumes that messages are dequeued in sequentially by all the tasks listening to that queue. Furthermore, it requires that the TMM automatically place messages into the queue for each of the tasks listening to the queue, so that all listening tasks terminate. This pattern, as implemented by the TMM, currently fails when tasks dynamically add themselves to a message queue after the
StopMessage has been posted.
Going back to the Mandelbrot example5 I used in the first article, I'm going to show how the code is changed yet again, illustrating tasks and task messaging this time. What you will immediately notice about this architecture is that the original code has been broken up into small, autonomous units. In this version though, there is still a global set of variables that is referenced by the tasks:
readonly double xstep; readonly double ystep; readonly double escapeRadius; readonly double logEscapeRadius; readonly int width; readonly int height; readonly byte[] argb; readonly Color[] colors; readonly ComplexNumber p1; readonly ComplexNumber p2; readonly int maxIteration; readonly ProgressBar progress;
On my todo list is moving these variables into their respective tasks and using the task parameter to initialize them when the task is created. For the moment, they are designated
readonly to emphasize that they are immutable.
There are three messages.
/// <summary> /// The initial task is primed with width messages, each an x coordinate. /// </summary> public class XCoordMessage : IMessage, IClonableMessage { public int x; public XCoordMessage(int x) { this.x = x; } public IMessage DeepClone() { return new XCoordMessage(x); } } /// <summary> /// The coordinate message is sent to the task that computes /// the iterations. /// </summary> public class CoordMessage : IMessage, IClonableMessage { public int x; public int y; public CoordMessage(int x, int y) { this.x = x; this.y = y; } public IMessage DeepClone() { return new CoordMessage(x, y); } } /// <summary> /// This message is sent to the task responsible for updating /// the bitmap. /// </summary> public class CoordColorMessage : IMessage, IClonableMessage { public int x; public int y; public int colorIndex; public CoordColorMessage(int x, int y, int colorIndex) { this.x = x; this.y = y; this.colorIndex = colorIndex; } public IMessage DeepClone() { return new CoordColorMessage(x, y, colorIndex); } }
The first message sets up the task to generate the full (x,y) coordinate that is then passed to the iteration task. The iteration task, when the iteration is determined, sends a message to the task that is responsible for updating the bitmap.
There are three tasks. Each task checks for a
StopMessage and terminates itself if that message is returned by the TMM. If not, it checks that the message is the expected message type, and performs the task based on that message.
This task posts the (x, y) coordinates of the pixel to compute to the
ComputeIterations task.
public void PostCoordinates(object obj) { // When we get the the x coord // and vertical height, post the complete coordinate. tmm.RegisterTask(Task.Current, "CoordQueue"); bool stopped = false; while (!stopped) { TaskMessage tm = tmm.GetMessage(); if (tm.Message is StopMessage) { stopped = true; } else if (tm.Message is XCoordMessage) { XCoordMessage xch = (XCoordMessage)tm.Message; for (int y = 0; y < height; y++) { tmm.PostMessage("IterationQueue", new CoordMessage(xch.x, y)); } } } }
This task computes the number of iterations before z escapes. It operates on the (x, y) coordinate received in the message for its queue.
public void ComputeIterations(object obj) { // When we get the coordinate, // compute the # of iterations before escape and // post the result. tmm.RegisterTask(Task.Current, "IterationQueue"); bool stopped = false; while (!stopped) { TaskMessage tm = tmm.GetMessage(); if (tm.Message is StopMessage) { stopped = true; } else if (tm.Message is CoordMessage) { CoordMessage cm = (CoordMessage)tm.Message; ComplexNumber z = p2; z.Re = p2.Re + (cm.x * xstep); z.Im = p1.Im-cm.y*ystep;); } tmm.PostMessage("BitmapQueue", new CoordColorMessage(cm.x, cm.y, colorIndex)); } } }
This task receives the (x, y) coordinate of the pixel as well as the color index computed by the task above. It is responsible for posting the color to the bitmap.
public void UpdateBitmap(object obj) { // When we get the computed iterations // for the coordinate, put it in the bitmap. tmm.RegisterTask(Task.Current, "BitmapQueue"); bool stopped = false; while (!stopped) { TaskMessage tm = tmm.GetMessage(); if (tm.Message is StopMessage) { stopped = true; } else if (tm.Message is CoordColorMessage) { CoordColorMessage cm = (CoordColorMessage)tm.Message; int colorIndex=cm.colorIndex; if ((colorIndex < 0) || (colorIndex >= 768)) { colorIndex = 0; } int index = (cm.y * width + cm.x) * 4; argb[index] = colors[colorIndex].B; argb[index + 1] = colors[colorIndex].G; argb[index + 2] = colors[colorIndex].R; argb[index + 3] = 255; // See comments in UpdateProgress for why we do this rather than // another task that updates the progress bar. Interlocked.Increment(ref Tasks.progressValue); // tmm.PostMessage("UpdateQueue", UpdateProgressMessage.msg); } } }
The progress bar is updated in the main application thread. Because more than one
UpdateBitmap task may be running, the task
progressValue must be incremented atomically, hence the
Interlocked.Increment statement. Attempts to post the count and use
BeginInvoke on the progress bar's container form was a disaster--updating the UI with task instances is Not A Good Idea, it would seem. In the main application thread, there is a callback that the TMM is provided when it waits for task completion. This effectively marshals the progress bar update onto the main application thread where it can be safely updated:
protected void UpdateUI() { // on 32 bit systems, this is atomic. int val = Tasks.progressValue; progress.Value = val; Application.DoEvents(); Thread.Sleep(100); }
The upshot though is that this violates the model of keeping data local to the task. I am leaving this issue for a future enhancement.
Tasks are initialized via a compiler option, as either one
Task instance per task, or n
Task instances, where n is the number of processors available. You can play with the performance difference by defining this compiler option in the code. This mode simulates task self-replication. Ideally, we would want the
TaskManager to manage self-replication.
public void Initialize() { Task task; #if DualTask for (int i = 0; i < System.Environment.ProcessorCount; i++) #endif { #if DualTask #else int i = 0; #endif task = Task.Create(PostCoordinates, null, TaskManager.Default, TaskCreationOptions.None, "Coordinates"+i); while (!tmm.IsRegistered(task)) { Thread.Sleep(10); } task = Task.Create(ComputeIterations, null, TaskManager.Default, TaskCreationOptions.None, "Iterations"+i); while (!tmm.IsRegistered(task)) { Thread.Sleep(10); } task = Task.Create(UpdateBitmap, null, TaskManager.Default, TaskCreationOptions.None, "Bitmap" + i); while (!tmm.IsRegistered(task)) { Thread.Sleep(10); } } }
Rather than the two loops for calculating the iterations of each fractal, the main application primes the first task with x coordinate messages and then waits for all the tasks to complete:
Tasks tasks = new Tasks(xStep, yStep, escapeRadius, logEscapeRadius, p.Width, p.Height, maxIteration, P1, P2, argb, Colors, progress); tasks.Initialize(); tasks.SendX(); // Wait for the coord queue to flush. TaskMessageManager.Default.Wait("CoordQueue", UpdateUI); TaskMessageManager.Default.PostMessage("CoordQueue", StopMessage.Default); // Wait next for the iteration queue to flush. TaskMessageManager.Default.Wait("IterationQueue", UpdateUI); TaskMessageManager.Default.PostMessage("IterationQueue", StopMessage.Default); // Then wait for the bitmap queue to flush. TaskMessageManager.Default.Wait("BitmapQueue", UpdateUI); TaskMessageManager.Default.PostMessage("BitmapQueue", StopMessage.Default); // Then wait for the bitmap queue to flush. //TaskMessageManager.Default.Wait("UpdateQueue", UpdateUI); //TaskMessageManager.Default.PostMessage("UpdateQueue", StopMessage.Default); TaskMessageManager.Default.Wait(UpdateUI);
The salient point here is that the application posts a
StopMessage to the queue when the queue is empty, and finally calls
Wait to wait for the last tasks to complete. This really does work, even if it's incredibly inelegant, because the queue of task 1 cannot be emptied without having at least posted messages into the queue of task 2.
The resulting performance is illustrated quite dramatically by this chart4:
You will note, to one's amazement, that parallelizing the outer loop (using
Parallel.For on the inner loop instead--not together with the outer loop--is considerably worse, as predicted in my first article), as described in my previous article, results in worse performance than the single threaded application, even though I can clearly see that the dual cores, in single threaded execution, are executing at only 50% utilization, and the cores in the PFX version are executing at 100% utilization. As expected, the TMM version is considerably slower, but here at least, setting up multiple tasks results in a performance improvement. Incidentally, in all cases, removing the code that updates the progress bar results in 10%-20% improvement, which just goes to show that updating the UI is an expensive operation.
Now, the interesting thing is that, depending on what area of the fractal one is rendering, the performance is sometimes better with PFX. Perhaps, by luck, I found an area of the fractal where PFX performs worse. This is definitely something that deserves a lot more investigation.
The most important result of this experiment was the problems I discovered with PFX. Hopefully, they will be addressed in future releases, but if not, replacing the PFX task manager and
Task classes is straightforward enough, though it would result in decoupling PLINQ. However, there are alternatives for that as well. In the meantime though, I'm bucking my modus operandi of always re-inventing the wheel and trying to work with PFX as much as possible.
The first problem is that tasks, once created, immediately start. This means that I cannot register the
Task instance after creating it because the task will immediately start asking for messages from the TMM, and it may not have been registered yet by the task creator. Conversely, if the task registers itself (which is how I implemented it), the creator has to wait until the task is registered before posting messages. The first scenario could be accommodated with some sort of auto-register process of the task. The second scenario can be accommodated (and this is my preference, but is not implemented) by first creating the queue. This would allow the task creator to prime the queue with messages, then create the task.
Ideally though, I would think that the
Task.Create method would allow you to create the task in a suspended state, and start (or resume) it at a time of your choosing. For completeness, the application should be able to suspend a task. The PFX
TaskManager ought to be smart enough to assign a task to the core that was previously dedicated to the now suspended task.
When self-replicating, the
Task.Completed event fires even though the task was never started. For this example, I removed the creation of task2. From this trace:
you can see that Task1 is registered twice (the PFX
TaskManager sees that there are two cores, so it duplicates this task with the same name, which is fine). However, you can also see that there are four "Task Completed" event calls! I do not think that
Task.Completed should be called for threads that were never even started.
With self replication enabled, I have seen this exception occur:
if (taskQueueMap.ContainsKey(task)) { throw new TaskMessageManagerException("The task " + task.Name + " is already registered."); }
I cannot reliably replicate this problem, but it indicates that a
Task instance is possibly re-used by the PFX
TaskManager. As to why the
taskQueueMap still contained this task, I am not clear on, and the exception may have been thrown due to a bug in my code. None-the-less, knowing whether
Task instances are re-used or not is important, and bears further investigation of the
System.Threading assembly. If
Task instances are re-used, the task better make darn sure it is initialized to a known state (and not its last state) when the task starts.
Because a task may be waiting a long time for a message, this "known correctness bug" (I guess, saying simply "bug" isn't in vogue anymore): "Tasks blocked for significant periods of time may cause runaway thread injection and out of memory conditions when the default policy is used."2 is of concern. Hopefully, this will be fixed.
Tasks are assigned to cores, and in self-replication, tasks are replicated when a core becomes available.3 To me, this is not ideal. It assumes that a task will consume 100% of its core, which is not always the case. What if the task is waiting for an I/O completion event? With regards to the TMM, what if a task is waiting for a message? Can no other
Task instance, with actual work to do, utilize this core in the meantime? So far, I haven't found any information regarding whether PFX handles cases where tasks do not consume 100% of the core.
I fully expected that the Mandelbrot rendering with PFX would be better than the single threaded operation, and I'm actually dismayed that it's worse! It would be great if someone from the PFX team could explain this result.
Only one TMM is permitted. The task always interacts with the default TMM. The whole concept of task queues might be better managed by allowing for multiple TMM's, each managing a single queue.
PostMessage has overloads for posting to the queue or to a task. However, posting to a task is a misnomer, because it posts to that task's queue, which is like posting to a queue, in that any available task listening on that queue gets that message. This is not obvious, and the method signature is misleading, as the developer might incorrectly think that the message is being posted to that specific task.
The TMM does not work with self-replicating tasks. A whole section of the code has been commented out regarding this issue and "smart" removal of tasks no longer needed because there's nothing in the queue to process. This may be mixing apples and oranges regarding task management, and it probably conflicts with PFX's
TaskManager as well. Another reason self-replicating tasks don't work is the PFX problem with
Task.Completed events greater than the number of
Task instances started. And finally is the TMM problem of stopping tasks, described next.
In the "Process Work Until Stopped" pattern, the TMM sends a
StopMessage to each task listening on the designated queue. For this to successfully stop all tasks, the task itself must behave correctly--it cannot request another message after the
StopMessage is received. Also, since this message is enqueued when it is issued (rather than when it is encountered, which doesn't really solve anything since a task can be added while the other tasks stop), any tasks that add themselves after the message in enqueued will not receive the stop message. This is a serious problem which must be resolved in order for self-replication to work.
Using structs for messages is essentially pointless, I would think, because they are boxed when referenced via the interface (though I need to really check on this). This is another reason that the .NET environment is unsuitable in certain scenarios for inter-task messaging. Those scenarios can be identified as having tasks that are so short-lived that serialization of the message is a measurable percentage of the task itself.
As eluded to above, multiple queues per TMM causes unnecessary locking when adding and removing messages to a particular queue, as the entire queue collection is being locked, rather than just the queue itself. This will block other tasks that are trying to retrieve a message from a different queue altogether. A future performance improvement is to utilize only one queue per TMM, which will necessitate creating TMM instances.
Debug messages in the TMM really slow it down.
If a core is task switching between numerous active threads, the task switching itself starts to bog down the core. This requires further investigation.
Working with the TMM, it's clear that a careful understanding of the parallel tasks is required in order to take advantage of concurrent programming.
It also is clear that, in addition to understanding your application requirements, one needs to clearly understand the workings of any library that is facilitating the management of tasks and coordination (such as messaging) between tasks. I would hope that the PFX team produces high quality documentation so that the developer can clearly understand how to best take advantage of PFX and concurrent programming. The pitfall would be to believe that PFX makes concurrent programming easy. It does not--the CTP is little more than syntactical sugar regarding the process of managing threads yourself. The performance test above shows that parallelizing the outer loop does not improve performance--in fact, it degrades it. If anyone on the PFX team can explain this behavior and make post on this article about it, I would greatly appreciate it.
TaskMessageManagerinstances.
What I have attempted to do here is put together a use case for PFX that probably is outside of the scope of what the designer of PFX had planned for. Also, I wanted to experiment with synchronization free inter-task communication to study the advantages and disadvantages of such an approach. It may turn out that PFX is not suitable for this kind of work, regardless of other more fundamental issues such as serialization performance (which may make .NET languages, in general, unsuitable for this approach). However, I do hope that the creators of PFX will look at this work and consider some of my suggestions. I plan on continuing this investigation in future articles. Performance measurement and optimization is one such topic that intrigues me--how to measure performance changes with PFX, or TMM, and so forth, as well as performance optimization within a core, since quite frankly, I expect to be working in .NET languages for quite a while.
1 - Canceling a task
2 - Known Correctness Bugs with PFX
3 - First Look at Parallel FX and self-replicating tasks
4 - These tests were done on a Sony Viao VGN-FE890 laptop, running 32 bit Vista Business with 2GB RAM, T5500 processor at 1.66Ghz. The Mandelbrot configuration was:
maxIteration = 300; P1 = new ComplexNumber(-0.669912107426552, 0.451398357629374); P2 = new ComplexNumber(-0.672973630864052, 0.449948162316874);
and the drawing area was 1254w x 594h.
5 - livibetter's Mandelbrot set with smooth drawing
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/recipes/tmm1.aspx | crawl-002 | refinedweb | 4,144 | 55.95 |
Python for Fortran programmers III: Learning Python
Learning Python is easier than learning Fortran. First, because the language has a simpler syntax and its interactive behaviour makes errors easier to catch and more understandable. Second, because there are lots of resources, many of them free: tutorials, books, etc.
These two interactive web-pages are a good example of the type of help you cannot find with Fortran:
That said, at some point you might feel dismayed by the size of the language. Python is much larger than Fortran. Both the core language and the available extensions. You’ll have to assume that, unless you become too hooked on it, there’ll be many areas of the language that you will – and can – ignore. With the risk of blasphemy, I dare say you can write hundreds of useful scripts completely ignoring Object Oriented Programming.
The number of available packages is also overwhelming. Take, for example, the calculation of the square root. In most tutorials you are told to import the
math module which contains a
sqrt function.
math.sqrt will give an error for negative arguments.
math.sqrt only returns floats. If you want deal with complex numbers, you need to
import cmath. But
cmath.sqrt always returns a complex number, even if its imaginary part is zero. All this is similar to the Fortran
sqrt function (which implicitly calls two different functions for real and complex arguments). But with python you can both have your cake and eat it. There is a third
sqrt function which returns a complex number only when the argument is negative. It can be found in the
numpy.lib.scimath module. This third function can be useful to you, but you can also live without it. Getting used to ignoring all these potentially useful features is part of the learning process. Eventually you will remember and look for the ones you really need.
One last confusing issue is which Python version to learn. As with Fortran, the newest versions are better, but the problem with Python is that versions 3.x are not backward compatible with the wide-spread versions 2.x. My recommendation is that you learn python 3.x. Mainly because it is the future. Most packages have already been translated into Python 3. I think installing python3, numpy, scipy, sympy, and ipython is enough to start using python in scientific problems. Make sure you install these packages for python3. Each python version can host its own modules completely independently. If you are using an older distribution, you can also install them quite easily with
pip. Of course, things can get more complex, as Konrad Hinsen reports in his interesting blog.
Despite their incompatibility, Python3 and Python2 are not that different. Probably, they are less different than FORTRAN77 and Fortran 2000. The most significant differences that you will find are that
print() is a function in Python3 (it uses parenthesis) and that
input() works differently.
And if you start programming, please do it in a nice way.
Recent Comments | https://ramoncrehuet.wordpress.com/2014/01/08/python-for-fortran-programmers-iii-learning-python/ | CC-MAIN-2018-26 | refinedweb | 506 | 66.33 |
#include <iq.h>
An abstraction of an IQ stanza.
Definition at line 33 of file iq.h.
Describes the different valid IQ types.
The stanza is a request for information or requirements.
The stanza provides required data, sets new values, or replaces existing values.
The stanza is a response to a successful get or set request.
An error has occurred regarding processing or delivery of a previously-sent get or set (see Stanza Errors (Section 9.3)).
The stanza is invalid
Definition at line 43 of file iq.h.
EmptyString
Creates an IQ Query.
Definition at line 38 of file iq.cpp.
Virtual destructor.
Definition at line 44 of file iq.cpp.
Returns the IQ's type.
Definition at line 74 of file iq.h.
Creates a Tag representation of the Stanza. The Tag is completely independent of the Stanza and will not be updated when the Stanza is modified.
Implements Stanza.
Definition at line 48 of file iq.cpp. | https://camaya.net/api/gloox-1.0.23/classgloox_1_1IQ.html | CC-MAIN-2020-34 | refinedweb | 160 | 61.93 |
SIGACTION(2) Linux Programmer's Manual SIGACTION(2)
sigaction, rt_sigaction - examine and change a signal action
#include <signal.h> int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): sigaction(): _POSIX_C_SOURCE siginfo_t: _POSIX_C_SOURCE >= 199309L
The field is not intended for application use. (POSIX does not specify a sa_restorer field.) Some further details of the purpose of this field can be found in sigreturn(2). three arguments, as described below. fol‐ lowing: mean‐ ingful only when establishing a handler for SIGCHLD. SA_NOCLDWAIT (since Linux 2.6) If signum is SIGCHLD, do not transform children into zom‐ bies when they terminate. See also waitpid(2). This flag is meaningful only when establishing a handler for SIGCHLD, or when setting that signal's disposition to SIG_DFL. If the SA_NOCLDWAIT flag is set when establishing a han‐ dler for SIGCHLD, POSIX.1 leaves it unspecified whether a SIGCHLD signal is generated when a child process termi‐ nates. On Linux, a SIGCHLD signal is generated in this case; on some other implementations, it is not. pro‐ vided estab‐ lishing a signal handler. SA_ONESHOT is an obsolete, non‐ standard_han‐ dler. This flag is meaningful only when establishing a signal handler. The siginfo_t argument to a SA_SIGINFO handler When the SA_SIGINFO flag is specified in act.sa_flags, the signal handler address is passed via the act.sa_sigaction field. This han‐ dler takes three arguments, as follows: void handler(int sig, siginfo_t *info, void *ucontext) { ... } These three arguments are as follows sig The number of the signal that caused invocation of the han‐ dler. info A pointer to a siginfo_t, which is a structure containing fur‐ ther information about the signal, as described below. ucontext This is a pointer to a ucontext_t structure, cast to void *. The structure pointed to by this field contains signal context information that was saved on the user-space stack by the ker‐ nel; for details, see sigreturn(2). Further information about the ucontext_t structure can be found in getcontext(3). Com‐ monly, the handler function doesn't make any use of the third argument. The siginfo_t data type is a structure with the following fields:) */ void *si meaning‐ ful_over‐ run sys‐ tem CPU time used by the child process; these fields do not include the times used by waited-for children (unlike getrusage(2) and times)). * cor‐ rupted, responsi‐ ble con‐ sumed;.
sigaction() returns 0 on success; on error, -1 is returned, and errno is set to indicate the error..
POSIX.1-2001, POSIX.1-2008, SVr4.
A and later allow, namely by using a sa_handler with), pause)
This page is part of release 4.16 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. Linux 2017-09-15 SIGACTION(2)
Pages that refer to this page: kill(1),), syscalls), seccomp_init(7), signal-safety(7), socket(7), user_namespaces(7) | http://man7.org/linux/man-pages/man2/sigaction.2.html | CC-MAIN-2018-26 | refinedweb | 494 | 56.96 |
I am using Micropython on ESP32 board that has few sensors connected. The task for ESP32 is to read sensors and send data to MQTT server.
I got it all working, however process used to stop unexpectedly. Sometimes it happened once a week, sometimes it kept for few weeks. I was only guessing that this could be due to drop of wifi connection or missing connection to MQTT server (or possibly something else). My workaround was just to press Reset button on ESP32 and all was working again (this particular ESP32 was monitoring temp in the greenhouse).
I have then read code example in the your book with following code:
def restart_and_reconnect():
print(‘Failed to connect to MQTT broker. Reconnecting…’)
time.sleep(10)
machine.reset()
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
while True:
try:
client.check_msg()
if (time.time() – last_message) > message_interval:
msg = b’Hello #%d’ % counter
client.publish(topic_pub, msg)
last_message = time.time()
counter += 1
except OSError as e:
restart_and_reconnect()
So I thought ESP32 will reset if it does not reach MQTT server. But my process is possibly “not right” for this to work.
In order to read sensor data, I used Node-Red to generate mqtt message every 30 min. ESP32 has subscription to this particular message and does reading of sensor data and sends it back to MQTT server.
What I would like to add to code is attempt to connect to MQTT let say every 30 min and if it does not succeed for whatever reason (being drop of wifi or mqtt connection) it would reset ESP32 with machine.reset() command.
Can this be done?
Do you have the exact error message that it’s printed in the Terminal when that crash happens?
That exact error message would be crucial to understand what happened and prepare the code to restart the ESP every time that happens.
Unfortunately I do not have message. ESP32 is running on power supply, not connected to PC. As such I do not get message back. Is there any way to get error message without having PC connected to ESP32 for weeks?
I have therefore thought that ESP32 could try to connect to mqtt server per defined intervals and if connection is missing, then do command machine.reset() . Resetting ESP32 would run initial script to connect to WiFi and mqtt. Isn’t that good work around?
Unfortunately I don’t think there’s an easy way to find that error… It would require to have the computer with the serial monitor open.
To me it doesn’t look like it’s a problem with the MQTT connection or Wi-Fi connection getting lost.
It looks like your code is experiencing a different error (it might be a memory error for example). The best way to fix this project is to know the exact error message and creating an exception to restart your board when that happens.
With my MQTT example, the ESP32 is always connected to the MQTT broker, in case the connection is lost it keeps trying to restart the board and reconnect to the MQTT broker ( with restart_and_reconnect() function).
You can try shutting down your MQTT broker, and you’ll see your board restarting over and over again until it can connect to the MQTT broker.
So, the ESP32 already does that, it looks like you get a different error that crashes your board…
Thanks, will have to make some test environment with separate esp connected to PC. Current module in use is running without errors for two weeks now…
Is there a way to save log of error messages to some text file on ESP32? I could then capture errors easier. | https://rntlab.com/question/keeping-esp32-connected-to-mqtt-server/ | CC-MAIN-2021-25 | refinedweb | 613 | 71.24 |
Introduction
Hello! Hello! Hello, I'm mumuzi. Today's update is coming~
Recently, the National Day is too long, which leads to a lot of guys playing crazy, and then they don't come to work. What's wrong with it? I met a colleague who asked for leave!!
Boss: OK (clever).
Now, in addition to meeting a lot of friends asking for leave, have you met a lot of people who want to resign?
When water flows to the bottom and people go to the top, resignation is inevitable. So let's talk about how to write the resignation letter?
When we choose to leave one company to another, it may be because of low wages or being far away from home. So, when we resign, how do we write our resignation?
Today, Xiaobian will give you a small class of resignation! Ha ha ha, you can leave directly after you send it. The following code is for entertainment only!
text
The reasons in the resignation report should be sufficient and credible. Because only when the reasons are sufficient and credible can it be approved. The language should be accurate, the words should be simple, the wording should be euphemistic and sincere, and euphemistic and sincere words should be used to show the sincerity of resignation.
Humorous snippet——
Boss, leave me, you will live better!
Sorry, I'm a man with a dream. I'm going back to raise pigs ↓↓
Sorry, my wings are hard ↓↓
Be justified, not ashamed of your parents ↓↓
It is my responsibility to maintain world peace and protect the earth. Farewell ↓↓
My ideal is not to go to work ↓↓
Ha ha ha! Write code every day, but also relax! Well, after the entertainment, Xiaobian began to get down to business~
Text start——
(1) Environmental installation.
This article is an interface applet based on tkinter, including Python installation, pychar installation, pilot module and some built-in modules.
Unified module installation:
pip install -i. Doublan. COM / simple / + module name
(2) Thinking framework.
The boss can't close the window whether he closes it or doesn't agree. Finally, he can only agree
The main functions of resignation letter include: agree, disagree and close the window.
Agree: click agree to pop up a prompt box. Click the button on the prompt box to close the whole window.
Disagree: click disagree, disagree to move, click move once.
Close window: Click X No. close the window and pop up the humiliation prompt box.
Effects of clicking different buttons:
(3) The code implements four steps.
01.Tkinter interface setting window size, selected interface pictures, buttons, etc.
if __name__ == '__main__': window = tk.Tk() window.title('letter of resignation') width = 600 height = 650 screenwidth = window.winfo_screenwidth() screenheight = window.winfo_screenheight() alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) window.geometry(alignstr) # Set whether the window can be variable in length and width window.resizable(width=False, height=True) window.geometry('600x600') window.protocol("WM_DELETE_WINDOW", closeWindow) load = Image.open('02.jpeg').resize((300, 310)) render = ImageTk.PhotoImage(load) L2 = tk.Label(window, image=render) L2.place(x=150, y=100) B1 = tk.Button(window, text='agree', command=agree) B1.place(x=155, y=420) B2 = tk.Button(window, text='disagree', command=disagree) B2.place(x=400, y=420) window.mainloop()
02. Consent code.
def agree(): win = tk.Toplevel(window) win.geometry("500x150+{}+{}". format(int((screenwidth - width) / 2), int((screenheight - height) / 2))) win.title("resignation") label = tk.Label(win, text="Your mouse tail juice", font=("Chinese block letters", 20)) label.pack() btn = tk.Button(win, text="Get out of here", width=6, height=1, command=window.destroy) btn.pack()
03. Disagree code.
def disagree(): B2.place_forget() B2.place(x=random.randint(100, 500), y=random.randint(100, 500))
04. Close window code.
def closeWindow(): messagebox.showinfo(title="If you don't agree, you can't close it", message="Can't close it, hehe") return
The effect is as follows——
Figure I
Figure II
summary
As the saying goes, a life without resignation is incomplete (as the saying goes: I didn't say it). Then write here!
Your support is my biggest motivation!! Remember the third company ~mua Welcome to read previous articles~
| https://programmer.help/blogs/61808ebedc146.html | CC-MAIN-2021-49 | refinedweb | 701 | 61.93 |
zope.httpform 1.0.1
HTTP Form Data Parser
zope.httpform is a library that, given a WSGI or CGI environment dictionary, will return a dictionary back containing converted form/query string elements. The form and query string elements contained in the environment are converted into simple Python types when the form element names are decorated with special suffixes. For example, in an HTML form that you’d like this library to process, you might say:
<form action="."> Age : <input type="hidden" name="age:int" value="20"/> <input type="submit" name="Submit"/> </form>
Likewise, in the query string of the URL, you could put:
In both of these cases, when provided the WSGI or CGI environment, and asked to return a value, this library will return a dictionary like so:
{'age':20}
This functionality has lived for a long time inside Zope’s publisher, but now it has been factored into this small library, making it easier to explain, test, and use.
Contents
Form/Query String Element Parsing
zope.httpform provides a way for you to specify form input types in the form, rather than in your application code. Instead of converting the age variable to an integer in a controller or view, you can indicate that it is an integer in the form itself:
Age <input type="text" name="age:int" />
The :int appended to the form input name tells this library to convert the form input to an integer when it is invoked. If the user of your form types something that cannot be converted to an integer in the above case (such as “22 going on 23”) then this library will raise a ValueError.
Here is a list of the standard parameter converters.
:boolean
Converts a variable to true or false. Empty strings are evaluated as false and non-empty strings are evaluated as true.
:int
Converts a variable to an integer.
:long
Converts a variable to a long integer.
:float
Converts a variable to a floating point number.
:string
Converts a variable to a string. Most variables are strings already, so this converter is not often used except to simplify file uploads.
.
:tokens
Converts a string to a list by breaking it on white spaces.
:lines
Converts a string to a list by breaking it on new lines.
:required
Raises an exception if the variable is not present.
:ignore_empty
Excludes the variable from the form data if the variable is an empty string.
These converters all work in more or less the same way to coerce a form variable, which is a string, into another specific type.
The :list and :tuple converters can be used in combination with other converters. This allows you to apply additional converters to each element of the list or tuple. Consider this form:
<form action="."> <p>I like the following numbers</p> <input type="checkbox" name="favorite_numbers:list:int" value="1" /> One<br /> <input type="checkbox" name="favorite_numbers:list:int" value="2" />Two<br /> <input type="checkbox" name="favorite_numbers:list:int" value="3" />Three<br /> <input type="checkbox" name="favorite_numbers:list:int" value="4" />Four<br /> <input type="checkbox" name="favorite_numbers:list:int" value="5" />5<br /> <input type="submit" /> </form>
By using the :list and :int converters together, this library will convert each selected item to an integer and then combine all selected integers into a list named favorite_numbers.="."> First Name <input type="text" name="person.fname:record" /><br /> Last Name <input type="text" name="person.lname:record" /><br /> Age <input type="text" name="person.age:record:int" /><br /> <input type="submit" /> </form>
If the information represented by this form post is passed to zope.httpform, the resulting dictionary will container one parameter, person. The person variable will have the attributes fname, lname and age. Here’s an example of how you might use zope.httpform to process the form post (assuming you have a WSGI or CGI environment in hand):
from zope.httpform import parse info = parse(environ, environ['wsgi.input']) person = info['person']>
If you call zope.httpform’s parse method with the information from this form post, a dictionary will be returned from it.
Gotchas
The file pointer passed to zope.httpform.parse() will be consumed. For all intents and purposes this means you should make a tempfile copy of the wsgi.input file pointer before calling parse() if you intend to use the POST file input data in your application.
Acknowledgements
This documentation was graciously donated by the team at Agendaless Consulting. The zope.httpform package is expected to replace the repoze.monty package.
Version 1.0.1 (2009-02-07)
- Fixed some misleading documentation.
- Relaxed the requirement for REQUEST_METHOD because the zope.publisher tests do not set it.
- Used documentation and design ideas from repoze.monty. Thanks, Chris and Agendaless.
Version 1.0.0 (2009-02-06)
- First release of zope.httpform. Extracted from zope.publisher 3.5.5.
- Downloads (All Versions):
- 0 downloads in the last day
- 28 downloads in the last week
- 199 downloads in the last month
- Author: Zope Corporation and Contributors
- License: ZPL 2.1
- Categories
- Package Index Owner: davisagli, menesis, agroszer, baijum, hannosch, faassen, tlotze, gary, srichter, hathawsh
- DOAP record: zope.httpform-1.0.1.xml | https://pypi.python.org/pypi/zope.httpform/1.0.1 | CC-MAIN-2015-35 | refinedweb | 866 | 56.55 |
The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable is constant, which means it cannot be modified. For example:
const int x = 0;
public const double gravitationalConstant = 6.673e-11;
private const string productName = "Visual C#";.; run-time constants, as in this line: public static readonly uint l1 = (uint)DateTime.Now.Ticks;
// );
}
}
x = 11, y = 22
c1 = 5, c2 = 10
This example demonstrates using constants as local variables.
// const_keyword_2.cs
using System;
public class MainClass
{
static void Main()
{
const int c = 707;
Console.WriteLine("My local constant = {0}", c);
}
}
My local constant = 707
For more information, see the following sections in the C# Language Specification:
6.1.6 Implicit constant expression conversions
8.5.2 Local constant declarations
// const_keyword.cs
using
public
{
x = p1;
y = p2;
} | http://msdn.microsoft.com/en-us/library/e6w8fe1b(VS.80).aspx | crawl-002 | refinedweb | 144 | 51.04 |
I was talking to someone the other day and he asked me whether Visual Studio has a tool to count the lines of code in an application. It occurred to me that others might be interested in the answer so I decided to blog about it.
There is a tool called Code Metrics in Visual Studio 2008 and 2010 that among other things, counts the lines of code in a project. Using Code Metrics is very simple. In Solution Explorer, select the project that you want to know the LOC for, right-click and select "Calculate Code Metrics".
The screenshot below shows the Code Metrics window. One of the nice things about the Code Metrics window is that it shows you the lines of code per project, namespace, class or method.
Habib Heydarian. | http://blogs.msdn.com/b/habibh/archive/2009/10/27/how-to-count-the-lines-of-code-loc-in-your-application-using-visual-studio.aspx | CC-MAIN-2015-32 | refinedweb | 133 | 77.67 |
Introduction: Data Generated Surfboards
This is taken from my senior thesis in Industrial Design from about a year ago so sorry if theres some holes in it my memory might be a little off. It is an experimental project and there are so many things that could have been done differently, don't hesitate to let me know.
This project is on a system which gathers data to run a surfboard-building program. A device which logs readings from force sensors as you surf and applying that data in a way which optimizes the shape of your surfboard through generative modeling.
What makes this project work is that the surfboard is an interesting object where the force applying to the top of the object has an equal and opposite reaction to the bottom. Meaning if you press more or less with your toes or heel when you turn your surfboard should dictate where your surfboard needs to be shaped differently.
SURFBOARD DESIGN
I am going to assume that not everyone is an expert in contemporary surfboard design and I can't call myself one either, though here is my condensed explanation. Surfboards are vehicles for moving water through the fins, it does this through channeling water through the bottom concave and overall board outline. The surfboard can be exaggerated through asymmetrical shapes where you are creating a surfboard which identifies toe / heel weight distribution and attempts to capitalize on that. Through identifying where the surfer is applying the most pressure to turn their surfboard we can optimize an asymmetrical shape for the individual surfer.
WHO IS THIS FOR
This is a project which caterers to an intermediate to advanced surfer, someone who might be getting their second or third surfboard. At this stage you will have started to develop a style which dictates how your surfboard should function under your feet.
RESOURCES & SKILLS
The data is logged using an Arduino mini and parsed with excel. For the modeling of the surfboard you will need to have a copy of Rhinocerous 3D with Grasshopper installed on it. To actually produce the surfboard you will need to have access to a CNC large enough to mill a surfboard.
Step 1: The Sensor Pad
THE PAD
The pad is essentially a waterproof bag that protects the network of sensors while allowing you to access the arduino and sd card after you surf.
The bag is constructed of pond liner which is adhered using PVC glue.
// Materials //
+ pond liner...
+ pvc glue...
+ FPT Cap...
+ Male Adaptor...
+ VHB Tape...
+ 3mm styrene
+ Double Sided film tape...
// Tools //
+Vinyl Cutter... or X-Acto knife
+ Soldering Iron
+ Ruler
THE SENSOR
+ Force Sensor Resistor (11)
+ 10k ohm Resistor (11)
+ Stranded wire
+ Arduino mini...
+ Arduino Datalogging Shield...
+ Battery?...
Step 2: The Test Board
// Intro //
To properly generate a new surfboard you have to start with a demo model. This demo is re-created in the grasshopper definition and is the base for where the shape is generated from. For this reason your going to have to make a test model which you can either hand shape if your good enough or get CNCd. I included the AKU shaper file. The other option is to use a 5'8 Hayden Shapes hypto-krypto which is pretty similar to the base model.
// Details //
+ Blank - EPS ( It floats slightly better than Polyurethane, and is a little lighter. The pad is pretty heavy)
+ Resin - Epoxy ( Its a little less likely to ding and also its springiness gives the sensors a better reading you also have to use Epoxy when fiberglassing a EPS blank)
+ Fiberglass - 4x6 ( This is a heavier glass job than a standard surfboard, its important for the board not to get too many dings, its already pretty heavy with the pad and since the board is a little hefty it can still float you pretty well with all this glass)
Step 3: Cutting the Pad
// Intro //
The pad is constructed from pond liner. I used A vinyl cutter with a cutting board under it to cut out all the pieces but I would think that printing out the pattern then cutting it out with an X-Acto knife would work.
// Steps //
1. Each of these cuts are going to need to be done for both sides like in the illustration
2. Cut 1, 2 & 3 are going to be used for the inside of the sensor pad. These pieces primary function are to keep the sensors in the right place and organize the wires.
3. piece 4 & 5 make up the bag that all the sensors will go into
4. I also cut out styrene pieces that go over the enclosures, the theory behind this is to broaden the through of the sensors by increasing the surface.
Step 4: Wiring the Pad
// Intro //
The network which makes up this project is wired to an arduino mini with an data logging shield. It can be made more or less complicated depending on how exact you want your data set to be. I settled for 11 pins taking two measurements from the center front and one from the edges. This allows you to identify where the pressure is being applied, though broad, is enough to give the program a good idea of how the surfboard should be generated.
// Resources //...
// Steps //
1. Follow the schematic and wire each of the sensors, I used stackable headers to solder each of the sensors, I'm not the best at soldering and this is a safe way to prevent melting your sensors.
2. I also used a bread board to organize my board, resistors and battery Its not totally necessary but it was nice to have it in a nice package
3. I used double sided tape to adhere all of the pad parts...
its not totally necessary to use PVC glue though you could
Step 5: Glueing the Pad
// Intro //
I love pond liner, it is some really cool stuff, I had never even heard about it before doing this project but through some research settled on this as being a great material for building the pad. Pond liner is a PVC coated nylon which means you can use PVC pipe glue to weld it together creating a fully waterproof enclosure. Its also great because then you can use it to weld PVC pipes to it adding access points to the Arduino.
// Steps //
1. To make the composite lay all the pieces on the pad bottom piece
2. You can adhere all the sensor pieces using either double sided tape or PVC glue
3. Use the PVC fittings to create the access point to the Arduino on the top pad piece.
+ Theres a fine line when applying the pvc glue too much makes it bubble up and brittle though too little makes the bond weak. You kinda just have to experiment with some pieces and get a understanding of how it works
3. Once all of the pieces are dry adhere the top and bottom of the pad, you pretty much have one chance to do this so be patient, I did it in sections and made two glue lines to make sure that it would not leak.
+ The pad I built lasted two sessions before it started to break down, salt water is pretty brutal.
4. To adhere the pad to the surfboard use VHB tape
+ Be sure to wipe down the deck with paint thinner and be sure its super clean before laying down the pad
+ VHB tape is really strong, I didn't have any problems with the pad falling off
Step 6: Arduino Data Logging Program
// Intro //
The Arduino program logs data from the sensor network to an SD card. Included are some resources on formatting and trouble shooting SD cards. They Can be a bit finicky. The code is taken from and modified to include all the sensor readings.
// Resources //...
// Code //
/ (for MKRZero SD: SDCARD_SS_PIN)
created 24 Nov 2010
modified 9 Apr 2012
by Tom Igoe
This example code is in the public domain.
*/
#include <SPI.h>
#include <SD.h>
const int chipSelect = 4;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600); = 1; analogPin = 2;analogPin = 3; analogPin = 4; analogPin = 5; analogPin = 6; analogPin =");
}
}
Step 7: Collecting the Data
// Intro //
Now its time to try out the pad. Plug in the battery and insert the SD card. Its a good idea to test the program to make sure its logging the data properly before going out. Be careful when tightening the PVC cap so that you don't rip the pad, the threads are pretty hefty though its also a good idea to dust off the threading so that its super water tight
Its kind of a crazy thing surfing with this pad, the ocean is not always the nicest and the pad is a pretty clunky object. I gathered data using the pad two times and after that I was afraid that the pad would not last another. You should be pretty confident in the water and take it out on pretty tame days so that it doesn't get ripped off by big waves or you get yourself in a situation with a heavier than normal surfboard.
Step 8: Parcing the Data
// Intro //
When you finish collecting the data insert your SD card into you computer and you should have a folder containing a very long log of numbers. Since logging works by continuously running a string of contentious readings your going to have to copy the log into excel or google sheets to organize each of the sensor sets. Your going to want to take the average reading of each sensor to get it ready to insert into the grasshopper definition.
Its pretty easy to identify when you were applying pressure because you get drastically different readings than when you were sitting on your board. It becomes pretty spastic for a while then goes back to being consistent. The times of chaos is what you want... just delete the rest.
Step 9: Generating the Custom Surfboard
// Intro //
For this step your going to need to be somewhat proficient in Rhinocerous and grasshopper its not too advanced by any means though. In the grasshopper definition your going to notice that there are a bunch of nodes attached to various points, what your going to have to do is replace each of the nodes with the appropriate sensor readings. After gathering the data and parsing it in excel you should be be sure to keep track of where each of the readings came from so that you can adjust the grasshopper model to appropriately generate the optimal shape.
// Steps //
1. Open grasshopper and load the generative surfboard def
2. Insert the readings from the data log, I used the mediums from each readings.
3. Bake the model in grasshopper
+ your going to have a framework of the surfboard with just vectors
4. SWEEP2 using rails along the center and outside curves
+ This takes a bit of time and patience you may also need to blend surfaces to get it all watertight
Step 10: Milling the Surfboard
The final step is Milling the Surfboard. I used a two styrofoam blocks that I bought from home depot-... and spray adhesived them together so that it was thick enough to accommodate the rocker and board thickness. I used a Multicam 3000 using RhinoCAM. I am no CNC expert and had a lot of help in this step so I really can't offer any advice other than get someone to do this step for you ;)
Step 11: Final Thoughts
This project took me about a year and I finished it almost a year ago. I showed it at both the CCA industrial design senior show and Maker Faire. I am put it on here now because it took me that much time to actually look at it again... I was so sick of looking at this stuff. I hope you appreciate it, I think this type of research and work might be useful in other projects, if anyone actually attempts to do this Instructable please let me know its kind of a crazy thing and it would be great to see other peoples take on it. I think that there is a wealth of data that can be captured and used in creating products in a new way. I think were coming into a new age of customization and things that can be bespoke this type of rapid prototyping might be coming into rapid personal manufacturing.
I am happy to answer any questions regarding the process, theories, any of the programs or surfboard design in general.
Recommendations
We have a be nice policy.
Please be positive and constructive. | http://www.instructables.com/id/GENERATE-YOUR-PERFECT-SURFBOARD-FROM-DATA/ | CC-MAIN-2018-09 | refinedweb | 2,129 | 65.15 |
examples
HOW TO BECOME A GOOD PROGRAMMER
HOW TO BECOME A GOOD PROGRAMMER I want to know how to become good programmer
Hi Friend,
Please go through the following link:
CoreJava Tutorials
Here you will get lot of examples with illustration where you can
PHP Examples
In this section of PHP examples, the new bees will learn the basic examples of most common used functions. These examples will help to the experts too as assesing our codes, the programmers can develop simple to very complex programs
jQuery - jQuery Tutorials and examples
piece of code that provides very good support for ajax. jQuery can be used...
jQuery - jQuery Tutorials and examples
The largest collection of jQuery examples... getElementById with select by using a very
simple example.
JavaScript get
Java Tutorial with examples
Java Tutorial with examples What is the good urls of java tutorial with examples on your website?
Thanks
Hi,
We have many java tutorial with examples codes. You can view all these at Java Example Codes
Struts Layout Examples - Struts
be clicked on.
Im not able to find simple examples/explanation on it.
Any help on this would be very helpful.
Thanks,
Priya Hi priya,
I am
PHP Tutorials Guide with Examples
PHP Tutorials Guide with Examples Hi,
I am a beginners in PHP. I have searching for php tutorial guides with examples. Can any one provide me... fundamentals. This PHP beginner guide will be very essential for beginner?s
About Examples
, and these examples do that from the very beginning.
Simple, useful...
Java NotesAbout Examples
This series of progressive examples shows a typical pattern for building
simple applications with a window.
Example - First
Struts 2 Tags Examples
Struts 2 Tags Examples
In this section we are discussing the Struts 2 tags with examples. Struts 2
tags provides easy..., Control Tags and Data Tags.
We will show you all the tags with good
Ajax Examples
Ajax Examples
Displaying
Time:
This example is simple one to understand Ajax with JSP. The objective of the
example is to display the current date
JSP Simple Examples
JSP Simple Examples
Index 1.
Creating... page.
Html tags in jsp
In this example... will be included in the jsp page at
the translation time. In this example we have
Hi good afternoon
Hi good afternoon write a java program that Implement an array ADT with following operations: - a. Insert b. Delete c. Number of elements d. Display all elements e. Is Empty
Apache MyFaces Examples
;
Examples provided by the myfaces-example... to webapps\myfaces
directory of Tomcat server and open JSP file for the examples... through some
examples :
Data Scroller Example:(dataScroller.jsp
JSP Simple Examples
Struts 2 Date Format Examples
Struts 2 Date Format Examples
...
have provided fully tested example code to illustrate the concepts. You can...
The nice format is very interesting. The following table shows,
how
very urgent
very urgent **
how to integrate struts1.3
,ejb3,mysql5.0 in jboss server with
myeclipse IDE
Java ArrayList, Java Array List examples
list.add("Java ");
list.add("is ");
list.add("very ");
list.add("good... as shown below:
Java is very good programming language
Download... the ArrayList in Java with the example code.
SampleInterfaceImp.java
import
Arrays -- Examples
Java NotesArrays -- Examples
This applet shows a number of methods...
There are many kinds of sort programs. These are
examples showing some....
NOTE: You should rarely, if ever, write your own sort.
Good sorts are available
connection with mysql with jstl - JSP-Servlet
dsn-
for with Dsn-
Hi,
We have very good examples
Examples of iText
gives the file good look and feel. After going through
this example you...
Examples of iText
...
application.
pdf system
In this example we
RetDAO.java (part get
jsp - JSP-Servlet
JSP directives with example JSP Directive with examples
{
response.sendRedirect("/examples/jsp/login.jsp");
}
}
catch...JSP entered name and password is valid HII Im developing a login page using jsp and eclipse,there are two fields username and password,I want
jsp
as for usercategory......how can i do it...plz hwlp me...its very urgent
simple examples
Web Services Examples in NetBeans
and test the webservices very easily in the NetBeans IDE.
NetBeans Webservices examples
Let's start developing the webservices example...
Web Services Examples in NetBeans
JSP Standard Actions
& their elements
with some examples.
JSP Standard action are predefined... an applet with
the Java Plug-in software
Examples
<jsp... the browser and the
server). Following is an example of jsp:include usage
Nested classes: Examples and tutorials
Nested classes: Examples and tutorials
Nested classes
Here is another advantage of the Java...)
of Java. Very rarely local class is defined within a method.
The lacal
Downloading MyFaces example integrated with tomahawk
its necessary to
follow the examples provided by any source. Here apache itself has provided
examples in a zipped format. These examples are good...Downloading MyFaces example integrated with tomahawk
JSP Actions
JSP Actions
In this section we will explain you about JSP Action
tags and in the next section we will explain the uses of these tags with
examples. We will also show how to use
HTML
examples. We have created many easy to
understand HTML examples. These examples will help you in understanding HTML
very quickly
HTML is used to create web... will have to learn HTML.
HTML Examples:
HTML Tutorials
HTML5
Multilingual - JSP-Servlet
Multilingual Hello Sir,
good afternoon
I have developing jsp... conversion in jsp..
so, sir please give me the solution.. with example...
i... in it one column name as "language" which i use in my jsp code to translate data
Java Util Examples List
package of JDK. All the examples are with free source
code. It includes many examples that demonstrate the syntax and example code of
java util package... Java Util Examples List - Util Tutorials
JSF Tutorial and examples
EXAMPLES EXPLORED
(Part-2) (published in July-05)
In this second part... as a menu bar (graph specified via JSP):<br>
<d:graph_menubar id="... as a tree control (graph specified via JSP):<br>
<d:graph_menutree id
need ENUM examples
need ENUM examples i need enum sample examples
Ask Questions?
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions. | http://roseindia.net/tutorialhelp/comment/9788 | CC-MAIN-2013-20 | refinedweb | 1,052 | 57.77 |
Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering how to build a simple grader in under 15 lines of Python!
We don’t need to import any libraries for this function. For this episode we’re going to simply be building some functions out and using them like we did in the Unit Convertor, and the Calculator.
Grader Function in Python
Let’s pretend like we’re lucky and we go somewhere with a 10 point scale. If you’re in the UK I’m looking at you. When I went to school (in America) we had a 7 point system. I was a straight A student anyway, but it’s still bullshit to me lol.
Anyway, let’s get started by creating a
grader function that takes one parameter. We expect our
score parameter to be a float. In our function, we can just go down the list and return
A, when the score is above
90,
B when the score is about
80, and so on until we get to
F. Note that we don’t have to build an upper bound on any of these grades because we go down in order and return when we find what we need.
def grader(score: float): if score > 90.0: return 'A' if score > 80.0: return 'B' if score > 70.0: return 'C' if score > 60.0: return 'D' else: return 'F'
Testing the Grader Function Out
Now that we’ve built the grader, let’s test it out. All we are going to do to test it is print out the return value from different numbers. Notice how I included some integers in the test. This is just to illustrate a point. Even though our function expects floats, we can pass integers and Python will interpret it correctly!
print(grader(91.0)) print(grader(88.5)) print(grader(71)) print(grader(89.9)) print(grader(64))
We should expect to see the output: A, B, C, B, D from above. When we run our program we get an output like the image below.
As expected, we got A, B, C, B, | https://pythonalgos.com/super-simple-python-grader/ | CC-MAIN-2022-27 | refinedweb | 369 | 83.05 |
SelInside
selInside selects all atoms of a certain type that are located within the bounding box defined by some selection. See examples.
Usage
# find all atoms inside the box spanned by (0,0,0) and (10,10,10) # for the example PDB, 1hpv fetch 1hpv pseudoatom b1, pos=[0,0,0] pseudoatom b2, pos=[10,10,10] selInside b1 or b2
The Code
import pymol from pymol import cmd, stored from random import randint def selInside(bounding_object, target="*", radius=None): """ Selects all atoms of a given target type inside some selection that acts like a bounding box. PARAMS: bounding_object -- [PyMOL object/selection] the object/selection inside of which we want to choose atoms target -- [PyMOL selection] that defines the atoms to select. Use "solvent" to select only solvent atoms inside the selection radius -- [float] expand the box by this many angstroms on all sides RETURNS: (string) name of the selection created NOTES: assumes a single-state setup; for multi-state you must modify this script """ # get the extents of the bounding object into two arrays (bMin, bMax) = cmd.get_extent(bounding_object) # if the user supplied a size by which we need to expand the box, we do that here if radius!=None: try: # try to convert a string to a float radius = float(str(radius)) except ValueError: print "ERROR: Invalid radius declared. Please make sure the radius is a number or left blank" return # add/subtract the radius to the bounds bMin = map( lambda f: f-radius, bMin) bMax = map( lambda f: f+radius, bMax) # initialize a selection; selections starting with underscores are hidden by PyMOL cmd.select("__toRemove", "None") # for each atom in the target selection, if it's inside the box, add it to the selection for at in cmd.get_model(target).atom: if at.coord[0] > bMin[0] and at.coord[0] < bMax[0] and at.coord[1] > bMin[1] and at.coord[1] < bMax[1] and at.coord[2] > bMin[2] and at.coord[2] < bMax[2] : cmd.select("__toRemove", "__toRemove or index %d" % at.index) # prepare the return values rName = "insideBoundingObj" cmd.set_name("__toRemove", rName) return rName cmd.extend("selInside", selInside) | https://pymolwiki.org/index.php/SelInside | CC-MAIN-2021-43 | refinedweb | 355 | 54.52 |
This class implements a mutex interface.
The actual work is done via TMutex which is available as soon as the thread library is loaded.
and
This class provides mutex resource management in a guaranteed and exception safe way. Use like this:
when guard goes out of scope the mutex is unlocked in the TLockGuard destructor. The exception mechanism takes care of calling the dtors of local objects so it is exception safe.
Definition at line 32 of file TVirtualMutex.h.
#include <TVirtualMutex.h>
Definition at line 35 of file TVirtualMutex.h.
Definition at line 36 of file TVirtualMutex.h.
Definition at line 42 of file TVirtualMutex.h.
Implemented in ROOT::TVirtualRWMutex, ROOT::TRWMutexImp< MutexT, RecurseCountsT >, and TMutex.
Definition at line 43 of file TVirtualMutex.h. | https://root.cern.ch/doc/master/classTVirtualMutex.html | CC-MAIN-2021-17 | refinedweb | 125 | 52.26 |
Provided by: libncarg-dev_6.3.0-6build1_amd64
NAME
HLSRGB - Converts a color specification given as Hue, Lightness, and Saturation (HLS) values to Red, Green, and Blue (RGB) intensity values.
SYNOPSIS
CALL HLSRGB ( H, L, S, R, G, B )
C-BINDING SYNOPSIS
#include <ncarg/ncargC.h> void c_hlsrgb (float h, float l, float s, float *r, float *g, float *b)
DESCRIPTION
H (REAL, input, range [0.,360.) ) represents the hue of the input color in HLS color space. H=0. corresponds to blue. L (REAL, input, range [0.,100.]) represents the lightness value of the input color in HLS color space. Lightness is a measure of the quantity of light - a lightness of 0. is black, and a lightness of 100. gives white. The pure hues occur at lightness value 50. S (REAL, input, range [0.,100.]) represents the saturation value of the input color in HLS color space.. R (REAL, output, range [0.,1.]) represents the red intensity component of the output color in RGB color space. G (REAL, output, range [0.,1.]) represents the green intensity component of the output color in RGB color space. B (REAL, output, range [0.,1.]) represents the blue intensity component of the output color in RGB color space.
C-BINDING DESCRIPTION
The C-binding argument descriptions are the same as the FORTRAN argument descriptions.
EXAMPLES
Use the ncargex command to see the following relevant examples: ccpcldm, ccplbam, ccpllb, ccplll, ccpllw, colcon, fcce02.
ACCESS
To use HLSRGB or c_hlsrgb, load the NCAR Graphics libraries ncarg, ncarg_gks, and ncarg_c, preferably in that order.
MESSAGES
See the colconv man page for a description of all Colconv error messages and/or informational messages.
SEE ALSO
Online: colconv, hlsrgb, hsvrgb, rgbhls, rgbhsv, rgbyiq, yiqrgb, ncarg_cbind. Hardcopy: NCAR Graphics Fundamentals, UNIX Version
Copyright (C) 1987-2009 University Corporation for Atmospheric Research The use of this Software is governed by a License Agreement. | http://manpages.ubuntu.com/manpages/xenial/man3/hlsrgb.3NCARG.html | CC-MAIN-2019-30 | refinedweb | 313 | 59.5 |
Created on 2012-06-07 03:37 by eric.snow, last changed 2013-02-17 01:25 by python-dev. This issue is now closed.
In issue 15003 Raymond recommended that types.SimpleNamespace be picklable. I'll get a patch up as soon as I can to add this capability.
I've attached a patch that gives types.SimpleNamespace pickle support. To do it I had to change the name of the type from "namespace" to "types.SimpleNamespace". That's fine.
I also added __eq__/__ne__ support so I could use it during tests.
New changeset 3b93ab8c9c20 by Eric Snow in branch 'default':
Issue #15022: Add pickle and comparison support to types.SimpleNamespace.
New changeset e4c065b2db49 by Eric Snow in branch 'default':
Issue #15022: Ensure all pickle protocols are supported. | https://bugs.python.org/issue15022 | CC-MAIN-2021-49 | refinedweb | 130 | 61.83 |
Available items
The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:
boltons should be builtins.
Boltons is a set of over 230 BSD-licensed, pure-Python utilities in the same spirit as — and yet conspicuously missing from — the standard library, including:
Full and extensive docs are available on Read The Docs. See what's new by checking the CHANGELOG.
Boltons is tested against Python 2.6, 2.7, 3.4, 3.5, 3.6, and 3.7, as well as CPython nightly and PyPy/PyPy3.
Boltons can be added to a project in a few ways. There's the obvious one:
pip install boltons
On macOS, it can also be installed via MacPorts:
sudo port install py-boltons
Then, thanks to PyPI, dozens of boltons are just an import away:
from boltons.cacheutils import LRU my_cache = LRU()
However, due to the nature of utilities, application developers might want to consider other options, including vendorization of individual modules into a project. Boltons is pure-Python and has no dependencies. If the whole project is too big, each module is independent, and can be copied directly into a project. See the Integration section of the docs for more details.
The majority of boltons strive to be "good enough" for a wide range of basic uses, leaving advanced use cases to Python's myriad specialized 3rd-party libraries. In many cases the respective
boltonsmodule will describe 3rd-party alternatives worth investigating when use cases outgrow
boltons. If you've found a natural "next-step" library worth mentioning, see the next section!
Found something missing in the standard library that should be in
boltons? Found something missing in
boltons? First, take a moment to read the very brief architecture statement to make sure the functionality would be a good fit.
Then, if you are very motivated, submit a Pull Request. Otherwise, submit a short feature request on the Issues page, and we will figure something out. | https://xscode.com/mahmoud/boltons | CC-MAIN-2020-40 | refinedweb | 340 | 66.33 |
Product: Chrome
Stack Signature: base::debug::BreakDebugger()-18B549E
New Signature Label: base::debug::BreakDebugger()
New Signature Hash: 709aa75d_83ac9070_8d0c0e87_4744031f_4f3a1fe3
Report link:
Meta information:
Product Name: Chrome
Product Version: 21.0.1155.2
Report ID: 6f0fc2047867de29
Report Time: 2012/05/31 00:45:37, Thu
Uptime: 18 sec
Cumulative Uptime: 0 sec
OS Name: Windows NT
OS Version: 5.1.2600 Service Pack 3
CPU Architecture: x86
CPU Info: GenuineIntel family 6 model 23 stepping 10
The following are couple of URLs that were pointed out by net::URLRequestContext::AssertNoURLRequests.
""
""
This seems to have started in 1144:, but not in (these crashes are in ProfileIOData shutdown, so it's a different URLRequestContext, not the PAC context). is the culprit CL.
If we leak Profiles, then the PAC fetcher context may have ongoing URLRequests on behalf of those Profiles. We need to not leak Profiles.
In Beta (M20), it is one of top 50 crashes.
net::URLRequestContext::AssertNoURLRequests
In Dev (M21), it is among the top 10 crashes
net::URLRequestContext::AssertNoURLRequests
mad - should the change mentioned in comment #2 be reverted?
This is not a profile leak it's a render process host leak... if the
profile goes away before the render process host, we can get crashes... we
need to fix the render process host leak...
BYE
MAD...
sent from Mobile Answering Device!
Le 6 juin 2012 18:01, <willchan@chromium.org> a
As an experiment, I will change the destruction delay to a DCHECK, so that we can catch to render process leak / late delays, and then see if the number of crashes we get from render process hosts holding on to a dead profile or not quite as bad as this one...
Yes, the root cause is the RenderProcessHost leak. We need to fix that. But r138038 causes a RenderProcessHost leak to *also* cause a profile leak. IIUC, r138038 should get reverted, since we're just shuffling around where the crash happens, not actually fixing a crash.
There are still cases where the fix actually resolve crashes where the render process host didn't leak, it just got released later than the Profile because all this is independently asynchronous... But I guess these should be fixed in some other ways too... :-(
Getting released later than the Profile is a leak in this case, because RenderProcessHost is a UI thread object. The Profile gets deleted after the MessageLoop on the UI thread has stopped pumping events. That means that by the time the ProfileManager starts deleting Profiles, if the RenderProcessHost isn't gone, then it will be leaked, since the MessageLoop will not run any more tasks, so it won't just get deleted later, but it will be completely leaked.
I don't think this is the case for incognito profile... Which is why this initially only took care of incognito profiles... Which eventually caused problems when incognito profile outlived parent profile...
Yes, sorry for being imprecise. My statement is only true for normal profiles. But as you point out, due to the dependency between incognito profiles and normal profiles, we need to either make profiles live longer (and everything that depends on those profiles live longer), or we need to make sure that everything that uses profiles gets destroyed promptly.
There are a few points to keep in mind here. Even if we decide to let Profiles live longer, it's not acceptable to ever leak them, since then we aren't persisting lots of their data on shutdown, which is clearly a bug. So, we we want to keep Profiles alive longer, and not leak them, then we need to keep pumping the UI MessageLoop. Of course, during shutdown, we've never done this, so re-pumping the UI MessageLoop would probably lead to a lot of bugs. Also, allowing things to keep objects alive longer is an inversion of ownership. Profiles own all these profile-related objects like RenderProcessHost, so those objects should not keep Profiles alive.
As I think we've agreed on, the real solution is to track down this RenderProcessHost delayed shutdown issue and figure out how to make it get destroyed promptly.
The following revision refers to this bug:
------------------------------------------------------------------------
r144251 | mad@chromium.org | Tue Jun 26 13:09:16 PDT 2012
Changed paths:
M
M
M:
------------------------------------------------------------------------
let me know once this has made to canary and has been verified. pls. :)
OK, will do... :-)
Seems like the crash is still happening with the fix... :-(
There are a few occurrences in 1188 which was cut after the fix got it (but none yet in 1189, not sure why though, too soon?)...
So either the fix isn't correct, or the problem wasn't caused by the profile destroyer... :-/
We need to go deeper...
ok so removing merge request for now :)
Actually, I take that back, the issues we are seeing after the fix I made were not related, they were in the destructor of the ProfileIOData, so not related as mentioned by willchan in comment 1 above...
There were no occurrence of the non-ProfileIOData destructor crash after this fix, so I guess we are good to go with the merge...
Unless I'm missing something again...
hmm. we have a bit more time for beta2, would u like to stew this a bit? u can merge all the way to july 10 and still be in beta2 at this moment.
I personally don't mind as lo g as the other stake holders are OK with it...
BYE
MAD...
sent from Mobile Answering Device!
Le 29 juin 2012 13:27, <kareng@google.com> a
there are no builds between now and then anyway so it's not possible to get it out sooner, might as well wait and make sure there are no side effects.
The following revision refers to this bug:
------------------------------------------------------------------------
r145740 | mad@chromium.org | Mon Jul 09 14:14:22 PDT 2012
Changed paths:
M
M
M
Merge 144251 -:
TBR=mad@chromium.org
Review URL:
------------------------------------------------------------------------
We had 4 crashes in 22.0.1200.0 in net::URLRequestContext::AssertNoURLRequests.
The following are couple of URLs.
crash id: 6c802a8f5d028365 crashing while deleting SystemURLRequestContext (or non-ProfileIOData).
The following is one call stack:
Thread 13 *CRASHED* ( EXCEPTION_BREAKPOINT @ 0x62d68a75 )
0x62d68a75 [chrome.dll] - debugger_win.cc:107
base::debug::BreakDebugger()
0x62d31f82 [chrome.dll] - url_request_context.cc:92
net::URLRequestContext::AssertNoURLRequests()
0x62d31fce [chrome.dll] - url_request_context.cc:39
net::URLRequestContext::~URLRequestContext()
0x62d3850c [chrome.dll] + 0x0050850c]
`anonymous namespace'::SystemURLRequestContext::`scalar deleting destructor'(unsigned int)
0x62d38459 [chrome.dll] - io_thread.cc:309
IOThread::Globals::~Globals()
0x62d382ef [chrome.dll] - io_thread.cc:505
IOThread::CleanUp()
0x629ab5a6 [chrome.dll] - browser_process_sub_thread.cc:54
content::BrowserProcessSubThread::CleanUp()
The following is another call stack (crash during ProfileIOData).
Thread 12 *CRASHED* ( EXCEPTION_BREAKPOINT @ 0x6bf17e81 )
0x6bf17e81 [chrome.dll] - debugger_win.cc:107
base::debug::BreakDebugger()
0x6bee3a0d [chrome.dll] - url_request_context.cc:92
net::URLRequestContext::AssertNoURLRequests()
0x6bee815c [chrome.dll] - profile_io_data.cc:283
ProfileIOData::~ProfileIOData()
0x6bee5928 [chrome.dll] + 0x00505928]
ProfileImplIOData::`vector deleting destructor'(unsigned int)
Crash ids in 22.0.1200.0 are:
0c56dc8ee88df0b8
6c802a8f5d028365
1bccfcaf931b802d
e75b79e2c3487273
Oh! Yeah, right, this bug is the more generic one... I was taking this one as just failing because the ProfileDestroyer was holding on Profile objects for too long...
But now that we have fixed the most frequent cause of this symptom, maybe we can remove the ReleaseBlock-Stable label?
And I also remove myself as a owner and make the bug available since I don't know this code that much, I was just owner to fix the ProfileDestroyer issue (which I also don't own, but I had volunteered to introduce to fix another problem many months ago).
OK? looks like u added the CHECK will and i still see this crash on 23.0.1235.0
Karen, how many crashes are we seeing? Raman, can update the bug with the latest URLs we see? I want to know if we're seeing new, different kinds of URLs due to regressions, or if it's still the same slow trickle due to profile destruction being all messed up.
42ddcbfdb1219436 url -> ""
The following 2 crashes are from googleusercontent.com
4cfaf4fa5531d6b2
9b3c795dc47b8430
There were only 3 crashes in 23.0.1235.0 until 8/14 5:04pm PST.
Looks like the profile is getting leaked. This should be a different bug,
it's not the PAC script fetcher. But yeah, until we fix the profile leakage
(which has some other implications), we will continue to have issues.
i see 13 in today's canary. is this not fixable at this point?
Issue 144260 has been merged into this issue.
recently this is showing up on the top. Is there a recent regression causing the spike?
I'm seeing something that looks similar to this in R25 on Chrome OS. Is this the same bug?
0x73f44109 [chrome] - base/debug/debugger_posix.cc:245] base::debug::BreakDebugger()
0x73fb3ad9 [chrome] - net/url_request/url_request_context.cc:122] net::URLRequestContext::AssertNoURLRequests() const
0x73cad9f1 [chrome] - chrome/browser/profiles/profile_io_data.cc:311] ProfileIOData::~ProfileIOData()
0x73e2dd19 [chrome] - chrome/browser/profiles/off_the_record_profile_io_data.cc:154] OffTheRecordProfileIOData::~OffTheRecordProfileIOData()
0x73e2dd2b [chrome] - chrome/browser/profiles/off_the_record_profile_io_data.cc:154] OffTheRecordProfileIOData::~OffTheRecordProfileIOData()
0x73cacd69 [chrome] - ./base/sequenced_task_runner_helpers.h:39] base::DeleteHelper<ProfileIOData>::DoDelete(void const*)
0x75a36f87 [chrome] - ./base/bind_internal.h:171] base::internal::Invoker<1, base::internal::BindState<base::internal::RunnableAdapter<void (*)(void const*)>, void (void const*), void (void const*)>, void (void const*)>::Run(base::internal::BindStateBase*)
0x7585c4ff [chrome] - ./base/callback.h:391] MessageLoop::RunTask(base::PendingTask const&)
0x7585c465 [chrome] - base/message_loop.cc:485] MessageLoop::DeferOrRunPendingTask(base::PendingTask const&)
0x75846fdb [chrome] - base/message_loop.cc:668] MessageLoop::DoWork()
0x75856da1 [chrome] - base/message_pump_libevent.cc:239] base::MessagePumpLibevent::Run(base::MessagePump::Delegate*)
0x75846dbb [chrome] - base/message_loop.cc:430] MessageLoop::RunInternal()
0x75846d4d [chrome] - base/run_loop.cc:45] base::RunLoop::Run()
0x75846cab [chrome] - base/message_loop.cc:310] MessageLoop::Run()
0x758a7033 [chrome] - content/browser/browser_thread_impl.cc:149] content::BrowserThreadImpl::IOThreadRun(MessageLoop*)
0x7589dac5 [chrome] - content/browser/browser_thread_impl.cc:177] content::BrowserThreadImpl::Run(MessageLoop*)
0x75846901 [chrome] - base/threading/thread.cc:195] base::Thread::ThreadMain()
0x758468a3 [chrome] - base/threading/platform_thread_posix.cc:65] base::::ThreadFunc
0x73601089 [libpthread-2.15.so] - pthread_create.c:307] start_thread
This is an incognito request leak. Can you repro in a debugger? Or somehow get the stack data from a crash dump? In URLRequestContext::AssertNoURLRequests(), we'll record the URL requested and the allocation stack trace, so we can debug the leak. More likely than not, it's a regression. All types of regressions will fall into this same stack trace, and we have to analyze the stack to determine the root cause. So I recommend you file a separate bug and cc me on it.
Howdy folks, we are still seeing this crash in Chrome 28 (28.0.1500.20) and it represents about 1% of the browser crashes.
Would greatly appreciate some help putting this monkey to bed, since it looks like it's been poking us since the early 20s.'Chrome'%20AND%20product.version%3D'28.0.1500.20'%20AND%20custom_data.ChromeCrashProto.ptype%3D'browser'%20AND%20custom_data.ChromeCrashProto.magic_signature_1.name%3D'net%3A%3AURLRequestContext%3A%3AAssertNoURLRequests'
Seeing something similar on shutdown in CrOS R29:
Issue 252538 has been merged into this issue. | https://bugs.chromium.org/p/chromium/issues/detail?id=130772 | CC-MAIN-2018-51 | refinedweb | 1,841 | 58.79 |
Visual Studio Code Settings and Extensions for Faster JavaScript Development
I have been using Visual Studio Code for more than two years, when I jumped on it from Sublime Text.
I spend about 5–6 hours every day inside VS Code so it’s imperative that it is tailored to my needs to make me as productive as possible. Over the years, I have tried many extensions and settings but now I feel settled with what I have so it’s worth talking about them.
I use Prettier for code formatting across all of my projects and I’ve set up this extension so that it automatically formats my HTML/CSS/JS when I hit ⌘ + S. This has allowed me to get rid of language-specific code formatters.
I use this extension along with npm intellisense (below) to ensure that my
package.json is up to date and not bloated with modules that I am not using.
This extension indexes my package.json and allows me to autocomplete my
import statements when requiring modules.
This extension color codes all of my brackets, allowing me to quickly see where each code block starts and ends.
This is the newest extension that I have added to my arsenal and I really like it. It lets you select some JSX and refactor it out into a custom React Class, function, or hook.
Another simple extension that does one thing well: auto-closes my JSX tags.
I recently moved from the native Source Control setting that VSCode has to Gitlens. I like this extension because it lets me:
I write so much React code that I needed an extension to help me save some time. I now use this extension to fill in some of the boilerplate that comes along with writing React components.
This extension helps me a lot when writing READMEs, or other Markdown documents. I specifically enjoy how it deals with lists, tables, and table of contents.
Apart from the extensions, the other aspect of customizing your VS Code experience are your User Settings. I have shared my complete Settings file below, but here are some of the important bits:
I really like fonts with ligatures. If you are unfamiliar with ligatures, they are special characters that parses and joins multiple characters. I primarily use Fira Code as my programming font. Here’s how it renders JavaScript:
My complete font stack is:
"editor.fontFamily": "'Fira Code', 'Operator Mono', 'iA Writer Duospace', 'Source Code Pro', Menlo, Monaco, monospace", "editor.fontLigatures": true,
To detect indentation, I also prefer these settings:
"editor.detectIndentation": true, "editor.renderIndentGuides": false,
To help manage my imports, I prefer these:
// Enable auto-updating of import paths when you rename a file. "javascript.updateImportsOnFileMove.enabled": "always",
Emmet now comes included with VS Code now, but to make it work well with React, I had to update some of the settings.
"emmet.includeLanguages": { "javascript": "javascriptreact", "jsx-sublime-babel-tags": "javascriptreact" }, "emmet.triggerExpansionOnTab": true, "emmet.showExpandedAbbreviation": "never",
Here’s my complete
user-settings.json
{ "editor.formatOnSave": true, // Enable per-language "[javascript]": { "editor.formatOnSave": true }, "[json]": { "editor.formatOnSave": true }, "emmet.syntaxProfiles": { "javascript": "jsx", "xml": { "attr_quotes": "single" } }, "editor.lineHeight": 22, "javascript.validate.enable": false, "workbench.editor.enablePreview": false, "javascript.updateImportsOnFileMove.enabled": "always", "prettier.trailingComma": "all", "bracketPairColorizer.forceIterationColorCycle": true, "editor.fontWeight": "500", "editor.fontLigatures": true, "editor.letterSpacing": 0.5, "editor.cursorWidth": 5, "editor.renderWhitespace": "all", "editor.snippetSuggestions": "top", "editor.glyphMargin": true, "editor.minimap.enabled": false, "terminal.integrated.fontWeight": "400", "editor.fontFamily": "Fira Code, iA Writer Duospace, Menlo, Monaco, 'Courier New', monospace", "editor.fontSize": 14, "window.zoomLevel": -1, "files.trimTrailingWhitespace": true, "files.trimFinalNewlines": true, "workbench.fontAliasing": "auto", "terminal.integrated.macOptionIsMeta": true, "prettier.bracketSpacing": true, "terminal.integrated.fontSize": 14, "terminal.integrated.fontWeightBold": "700", "terminal.integrated.lineHeight": 1.6, "workbench.colorTheme": "Shades of Purple", // SOP's Import Cost Extension Settings. "importCost.largePackageColor": "#EC3A37F5", "importCost.mediumPackageColor": "#B362FF", "importCost.smallPackageColor": "#B362FF" }
For more tips and tricks about Visual Studio Code, I recommend checking out VSCode Can Do That.
*Originally published by Tilo at *tilomitra.com
======================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | TwitterLearn More
☞ Learn Visual Studio Code
☞ Visual Studio Code Crash Course 2019
☞ The Complete JavaScript Course 2019: Build Real Projects!
☞ The Complete 2019 Web Development Bootcamp
☞ Svelte.js - The Complete Guide
Best Visual Studio Code Extensions for Web Development. One of the most impressive parts of Visual Studio Code is customizability, especially via extensions. If you’re a web developer, you won’t be able to live without installing these extensions!
Best Visual Studio Code Extensions for Web Development. One of the most impressive parts of Visual Studio Code is customizability, especially via extensions. If you’re a web developer, you won’t be able to live without installing these extensions!
Want to improve your Web Development workflow? You won't be able to live without installing these extensions for Visual Studio Code!
Want to install all of the extensions listed below at once?! Check out The Web Development Essentials Extension
Check out Learn Visual Studio Code to learn everything you need to know about about the hottest editor in Web Development for just Check out Learn Visual Studio Code to learn everything you need to know about about the hottest editor in Web Development for just $10!0!## 1. Debugger for chrome
Believe it or not, debugging JavaScript means more than just writing console.log() statements (although that’s a lot of it). Chrome has features built in that make debugging a much better experience. This extension gives you all (or close to all) of those debugging features right inside of VS Code!2. Javascript (ES6) Code Snippets
I loooove snippet extensions. I’m a firm believer that there’s no need to retype the same piece of code over and over again. This extensions provides you with snippets for popular pieces of modern (ES6) JavaScript code.
Side note…if you’re not using ES6 JavaScript features, you should be!3. ESLint
Want to write better code? Want consistent formatting across your team? Install ESLint. This extension can be configured to auto format your code as well as “yell” with linting errors/warnings. VS Code specifically is also perfectly configured to show you these errors/warnings.
Make changes in code editor, switch to browser, and refresh to see changes. That’s the endless cycle of a developer, but what if your browser would automatically refresh anytime you make changes? That’s where Live Server comes in!
It also runs your app on a localhost server. There are some things you can only test when running your app from a server, so this is a nice benefit.5. Bracket Pair Colorizor
Brackets are the bane of a developer’s existence. With tons of nested code, it gets almost impossible to determine which brackets match up with each other. Bracket Pair Colorizer (as you might expect) colors matching brackets to make your code much more readable. Trust me, you want this!6. Auto Rename Tag
Need to rename an element in HTML? Well, with Auto Rename Tag, you just need to rename either the opening or closing tag, and the other will be renamed automatically. Simple, but effective!7. Quokka
Need a quick place to test out some JavaScript? I used to open up the console in Chrome and type some code right there, but there were many downsides. Quokka gives you a JavaScript (and TypeScript) scratchpad in VS Code. This means you can test out a piece of code right there in your favorite editor!8. Path Intellisense
In large projects, remembering :)9. Project Manager
One thing I hate is switching between projects in VS Code. Every time I have to open the file explorer and find the project on my computer. But that changes with Project Manager. With this extension, you get an extra menu in your side menu for your projects. You can quickly switch between projects, save favorites, or auto-detect projects Git projects from your file system.
If you work on multiple different projects, this is a great way to stay organized and be more efficient.10. Editor Config
Editor Config is a standard of a handlful of coding styles that are respected across major text editors/IDEs. Here’s how it works. You save a config file in your repository which your editor respects. In this case, you have to add an extension to VS Code for it to respect these config files. Super easy to setup and works great on team projects.
Read more on the Editor Config Docs.11. Sublime Text Keymap
Are you an avid Sublime user, nervous to switch over to VS Code? This extension will make you feel right at home, by changing all of the shortcuts to match those of Sublime. Now, what excuse do you have for not switching over?12. Browser Preview
I love the Live Server extension (mentioned above), but his extension goes another step further in terms of convenience. It gives you a live-reloading preview right inside of VS Code. No more having to tab over to your browser to see a small change!13. Git Lens
There a bunch of git extensions out there, but one is the most powerful with tons of features. You get blame information, line and file history, commit searching, and so much more. If you need help with your Git workflow, start with this extension!14. Polacode
You know those fancy code screenshots you see in articles and tweets? Well, most likely they came from Polacode. It’s super simple to use. Copy a piece of code to your clipboard, open up the extension, paste the code, and click to save your image!15. Prettier
DONT spend time formatting your code…just DONT. There’s no need to. Ealier, I mentioned ESLint which provides formatting and linting. If you don’t need the linting part, then go with Prettier. It’s super easy to setup and can be configured to formatted your code automatically on save.
Never worry about formatting again!16. Better Comments
This extension color codes various types of comments to give them different significance and stand out from the rest of your code. I use this ALL THE TIME for todo comments. It’s hard to ignore a big orange comment telling me I’ve got some unfinished work to do.
There are also color codes for questions, alerts, and highlights. You can also add your own!17. Git Link
If you’ve ever wanted to view a file that you’re working on in Github, this extension is for you. After installing, just right-click in your file and you’ll see the option to open it in Github. This is great for checking history, branch versions, etc. if you’re not using the Git Lens extension.18. VS Code Icons
Did you know you can customize the icons in VS Code? If you look in settings, you’ll seen an option for “File Icon Theme”. From there you can choose from the pre-installed icons or install an icon pack. This extension gives you a pretty sweet icon pack that is used by over 11 million people!19. Material Icon Theme
Fan of Google’s Material design? Then, check out this Material themed icon pack. There’s hundreds of different icons and they are pretty awesome looking!20. Settings Sync
Developers,!21. Better Align
If you’re the kind of person who loves perfect alignment in your code, you need to get Better Align. You can align multiple variable declarations, trailing comments, sections of code, etc. There’s no better way to get a feel for how amazing this extension is than installing it and giving it a try!22. VIM
Are you a VIM power user? Bless you if you are, but you can take all of that VIM power user knowledge and use it right inside VS Code. Not the path I personally want to go, but I know how insane productivity can be when using VIM to its potential, so more power to you. | https://morioh.com/p/1968cd5edbb2 | CC-MAIN-2020-05 | refinedweb | 2,020 | 67.96 |
Why is my array globally manipulated, when I run the below ruby code? And how can I get arrays to be manipulated only within the function's scope?
a = [[1,0],[1,1]]
def hasRowsWithOnlyOnes(array)
array.map { |row|
return true if row.keep_if{|i| i != 1 } == []
}
false;
end
puts a.to_s
puts hasRowsWithOnlyOnes(a)
puts a.to_s
$ ruby test.rb
[[1, 0], [1, 1]]
true
[[0], []]
.select{true}
$ ruby -v
ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]
All variables in Ruby are references to objects.
When you pass an object to a method, a copy of that object's reference is made and passed to the object.
That means that the variable
array in your method and the top-level variable
a refer to the exact same Array. Any changes made to
array will be also visible as changes to
a, since both variables refer to the same object.
Your method does modify the array by calling Array#keep_if. The
keep_if method modifies the array in-place.
The best fix for this is to make it so that your method does not modify the array that was passed in. This can be done pretty neatly using the Enumerable#any? and Enumerable#all? methods:
def has_a_row_with_only_ones(array) array.any? do |row| row.all? { |e| e == 1 } end end
This code says that the method returns true if, for any row, every element in that row is 1. These methods do not modify the array. More important, they communicate the method's intent clearly.
If you want the method to act as through a copy of the array were passed to it, so that the array can be modified without that modification being visible outside the method, then you can make a deep copy of the array. As shown in this answer, you can define this method to make a deep copy:
def deep_copy(o) Marshal.load(Marshal.dump(o)) end
Then, at the top of the method, make the deep copy:
def has_a_row_with_only_ones(array) array = deep_copy(array) # code that modifies array end
This should be avoided because it's slow. | https://codedump.io/share/0gmcElI2Xku2/1/how-can-i-get-my-array-to-only-be-manipulated-locally-within-a-function-in-ruby | CC-MAIN-2017-13 | refinedweb | 354 | 67.04 |
Andrew Morton <akpm@linux-foundation.org> writes:> I was thinking more along the lines of some repeated operation which> generates reclaimable storage, only nothing reclaims that storage> sufficiently promptly (the 500 second delay, perhaps).>> Like the problem we had with SLAB_DESTROY_BY_RCU and, umm, I think it> was route cache entries increasing like mad and not getting reaped.Well what happens is I run reclaim that chain whenever a processexits or every 500s. The 500s is really the backup in casewe don't have any processes exiting, which is a reallystrange workload.Now maybe there is an extremely perverse case out there thatcan trigger some bad behavior. But I can't think of anythinglike that at the moment. It would require accessing a lotof /proc/<pid>/net directories and holding them open even aftertheir files were gone, pinning a lot of mounts, and thenuse a lot of memory elsewhere. Where the problem wouldbe that the code is not well tied in with memory reclaim.A mount is not a big or expensive structure and it requiresa fd somewhere to keep it alive past exit. Thinking backto my analysis on /proc a few years ago where I introducedstruct pid to prevent lowmem exhaustion. I can't think ofa case where it would be a problem or user triggerable.Basically you have to have a fd open for every proc inodethat lives past process exit. And we have hard limits onthe number of fds a process can open and limits on thenumber of processes we can have.One of the things on my todo list to look at sometime is the issuethat mounts can deny you the permission to delete a file or directorywhen the mount is in another mount namespace. It is a pretty nastyDOS from my opinion. Especially when the last process holding openthe mount namespace oopses and there is no way to remove the mount.However that DOS is only available to root today so it doesn't feellike a huge danger. To fix that we would need to introduce somebetter mount reaping logic. Which I expect would remove the need forthe proc_automounts. That is tricky subtle vfs logic and I don'tplan to rush into it.Eric | https://lkml.org/lkml/2008/11/7/272 | CC-MAIN-2015-40 | refinedweb | 368 | 62.98 |
Principales respuestas
How to retrieve token for service bus from ACS?
Hi!
I want to use ACS as a STS for the service bus. I've managed to use ACS for authentication for a web service. However, the service bus requires a token and I don't know how to retrieve such from the ACS?
In short, I want my client services to be able to use the service bus by authenticating with certificates that matches certificates stored as service identities in the acs (the one corresponding to the service bus -sb).
Also, I'm using NetTcpRelayBinding for the Service Bus.
Pregunta
Respuestas
Todas las respuestas
Hi Jimmy,
The tokens you mentioned can be created using the SBAzTool available on code.msdn.microsoft.com: With this tool you can add extra 'accounts' with token next to the default 'owner'. Now this will work if you use tokens, but I doubt this will help you in using the certificates for authentication.
You might also want to take a look at Clemens' talk a few months ago, he explains in detail how you can start securing your SB with ACS:
Sandrino
Sandrino Di Mattia | Twitter: | Azure Blog: | Blog:
Thanks Sandrino for your quick response. However, I've succeeded adding service identities that uses symmetric keys. The problem is certificates. I can create new service identities in acs that uses certificate credentials and use those to authenticate client before using a web service. But I've been unable to authenticate before using the service bus.
What am I missing here...
Hi,
As far as i know, if you want to add ACS with ServiceBus sample, please add certificate to ACS management portal, refer to the following article for more details:
Then you can check the sample that provided by Azure Team Blog:
Hope it helps.
Please mark the replies as answers if they help or unmark if not. If you have any feedback about my replies, please contact msdnmg@microsoft.com Microsoft One Code Framework
Thanks Arwind! That helped and I've now managed to retrieve a SAML token from the ACS using client certificate! Next problem is that I get unauthorized error when trying to use the retrieved SAML as credentials for the service bus. And, yes, the service bus is set to use SAML 2.0 as credentials. Maybe I wrongly assume that I can use the retrieved token as credential to the service bus?
Exception when trying to connect to service bus with saml token:
"The token provider was unable to provide a security token while accessing ''. Token provider returned message: 'Error:Code:401:SubCode:T0:Detail::TraceID:01815c06-97c5-4a02-b0af-9fcf3e49075b:TimeStamp:2012-03-22 13:08:41Z'."
With inner exception: "The remote server returned an error: (401) Unauthorized."
To get the token from ACS I modified this sample:
Two good sources of information:
and
Service Bus is automatically paired with the ACS namespace and expects SWT tokens. You can only work with the -sb namespace to set up federation for now and the -sb namespace in ACS already has the correct baseline setup with SWT tokens.
Hi Thirumalai,
Yes, I reached a solution together with MS support. Primary problem with my approach was that I didn't need to retrieve a token from ACS before I connect to the SB. Instead, I create a token by myself and and use that to connect to the SB. Basically, I created a SAML token and signed it with my certificate.
Let me know if you need code sample.
Hi JimmyCalsson,
Thanks for your response. I solved the issue by following code from acs\WebServices\Acs2CertificateBindingSample folder which downloadable from.
But if you find time, Pls send me the code. I am interested to get to know the way you solved.
Thanks you...
I know this does not have anything in particular to do with Jimmy Carslon's issue but I was getting the same error, it turns out changing my app.config and rebuilding an repackaging azure does not update the configuration files for azure which was what my app was running from.
So if you ever change your issuer secret in app.config check these changes are applied to the azure config files
Hi Jimmy - I'm looking at exactly the same scenario as you were. Namely, I have an on-premises application that has a X.509 client certificate that I'd like to use as credentials to authenticate and use the Service Bus Relay to publish a WCF service's endpoint via NetTcpRelayBinding.
As I understand it, the steps you took were:
1. Added a Service Identity in the Service Bus's buddy -sb namespace and added the X.509 certificate (i.e., .cer) to it.
2. Created a SAML 2 token, signed it with the X.509 certificate's private key and attached the signed SAML token to the TokenProvider before registering the WCF service with the Service Bus. I assume the SAML token had the appropriate set of Service Bus claims added to it (e.g., net.windows.servicebus.action = Listen)?
Would it be possible to get a code sample to show how you did this? Many thanks in advance for your help and advice.
- Editado Neville J. Parakh viernes, 07 de diciembre de 2012 23:44
"Primary problem with my approach was that I didn't need to retrieve a token from ACS before I connect to the SB."
This is interesting, because the SB endpoint would behave like an ordinary https endpoint with client certificate authentication. I'm very interested in this scenario and would like to see the code.
So far, I've only seen clients which were specifically designed to use the Service Bus bindings. | http://social.msdn.microsoft.com/Forums/windowsazure/es-ES/b45cb1ef-0ab0-4e8c-82c2-66e66c687bb1/how-to-retrieve-token-for-service-bus-from-acs?forum=windowsazureconnectivity | CC-MAIN-2014-15 | refinedweb | 955 | 64.1 |
Hi Thanks for posting the question. Should you find the answer below incomplete or you are not fully answered, please drop a reply before rating.
As you may have read on various tax forums or internet – Sanzar closed shop. Im told one of the reasons for shutting down is the “loan” schemes they were offering. With a couple court ruling in favour of HMRC in the past few years, HMRC have ben continuously monitoring people who had been using different off-shore schemes like Sanzar.
I understand the scheme worked like this- only a small proportion of your income was taxed as salary and the bulk of it was treated as a loan which was never repaid to Sanzar. The loan only appeared on the P11D. Now HMRC would want to tax this loan as this was essentially your income misclassified as a loan.
Similar rules apply to say to a director who has taken a loan from a business and the loan account is overdrawn, the director is taxed if the loan is not repaid as this is taken as disguised loan yet its essentially a salary.
My advice is to provide HMRC with as much of the information and to be forthcoming with information and see what they intend to do. IF they ask you to pay you may be entitled to raise a complaint on why HRMC had not raised this earlier.
If you are unable to resolve your concerns, then you should make a complaint to a complaints handler. HMRC accepts complaints by telephone or in writing but its better to put this in writing so that there is an audit trail.
Alternatively if you don't want the headaches of dealing with HMRC, find a tax expert who is experienced in dealing with HMRC investigations and he will charge minimum £200 to act on your behalf. But this will not likely remove the liability.
You can easily get a local tax expert near your area by posting your request of sites like HERE and HERE.
Hope this helps. Let me know if you have any further queries.
I will wait for a further few more minutes to answer your questions. If im logged out please feel free to post your further questions and I will answer them when im back online. Thanks..
Hi
Thanks for your reply. I feel that you reply is more general than my specific question. For example I am not a director and worked as an employee.
I was informed that I do not need to repay the loan.
Further I noticed on my tax return (submitted by accountant, I believe he also work for Sanzar Solutions) additional Information was provided as follows;
Additional Information
SA101, AI4, AOF20-any other information space
Tax Avoidance Notes: EMPLOYEMENT- Sanzar Solutions
During the 2010/2011 tax year I was an employee participating in a registered tax avoidance scheme.
I noticed on my P11D, loan was discharged on 05.04.2011.
Please advice me whether I can reply to HMRC on the basis of information provided on Tax return and P11d as follows,
Dear Sir
I worked as an employee and received £23,000 as loan. No expenses were reimbursed.
I was informed that I do not need to repay the loan as it is under registered tax avoidance scheme (please refer my tax return 2010-11) and loan was discharged on 05.04.2011 (please refer my P11d-2010-11)
Hope this satisfies your queries.
Yours faithully
Please advice whether I can sent a reply to HMRC as above.
Many thanks
Thanks for the reply.
Im sorry if my answer sounded general but the scheme worked the same as I have dealt with several people being approached by HMRC who had used the scheme ie income earned by a UK contractor was paid through a low fixed-salary and the bulk of it paid out as a loan through the Employee Benefit Trust from Sanzar Solutions. HMRC would see this as disguised salary and an attempt to reduce your tax in this way and hence would want to tax you the loans as salary under taxable income, or under long-stand standing anti-avoidance rules even though you reported the loans on PIID forms as benefit in kind. Hence the reasons HMRC is issuing these letters (you are not alone) to all people who used the schemes trying to find out how much the loan was and what was repaid. In almost all the cases - the loans were written off and that there was no intention for the loan to be repaid by the contractors, which is why HMRC think this was not a “loan” but a disguised salary/income. I did say that this is the same principle that would normally apply to directors but I didn’t mean that you are a director.
Course of Action to Take
I agree that you should write HMRC detailing how much of the money was a loan and how much was not repaid. I agree with your wording of the letter and I think you should reply to their enquiry ASAP. I would expect HMRC to come back to you with an assessment charging tax on the loan as explained above. You have the option to accept the assessment ie agree to pay the tax, or, lodge an appeal against this within 30 days from the issue date. Should your appeal be unsuccessful, and that tax is found to be payable, a surcharge of 5% will be levied on top of the tax due. This is on top of the interest charged on late paid tax. HMRC can ask for records going back four years in but in rare cases they have the right to look up to twenty years.
Conclusion
Im sorry to be so negative but my comments are from the experience of dealing with many people who have used this scheme before. With hindsight I would suggest that before paying any money out for any “tax efficient scheme”, you should have asked from the scheme provider for its HMRC Approved Scheme reference number or check with HMRC whether the scheme is approved to avoid all the hassles that you may be facing.
Im afraid there is much leeway for a basis of an appeal.
However my suggestion is to get tax investigation expert review your case. They wont charge a fee unless they see the potential for a solution. You can use sites like HERE where you post your request for free and local experts contact you directly – whether by phone or meetings with their offers of solutions. Hope this helps.
Let me know if you have any further queries. I will wait for a further few more minutes to answer your questions. If im logged out please feel free to post your further questions and I will answer them when im back online. If you are happy please rate before you go.
Here is the link – CLICK HERE . There is limited ground for winning an appeal case. However there is no harm in getting a specialised tax expert review your case in details – looking at the agreements, past returns and what work you were doing etc and see if there is any ground for an appeal- they normally do this for FREE. As said all you need to do is post your requirements on that that site in as much details as possible on the site and you don’t get charged for posting anything and local specialised tax experts contact you directly – whether by phone or meetings with their offers of solutions. Only then if you see the costs vs the benefit you then go ahead with the person you select …but you need to tell him/her that you want to know if you could appeal this and the chances of that being successful before hiring the expert. Hope this helps. | http://www.justanswer.com/uk-tax/80mih-hi-worked-employee-sanzar-solutions-during-2010-2011.html | CC-MAIN-2015-06 | refinedweb | 1,322 | 66.67 |
allow you to easily mock HTTP responses in your tests
Project description
responses_proxy allow you to easily mock HTTP responses in your tests
Installation
With pip:
$ pip install responses_proxy
Using docker:
$ docker run --rm -v tests/responses:/tests/responses bearstech/responses_proxy -h
Usage
Check command line arguments:
$ responses-proxy -h
First save some stuff using the proxy mode:
$ responses-proxy --proxy
If your target site use ssl then use:
$ responses-proxy --proxy --use-ssl
The proxy do not support ssl so you need to make http request. But first set the HTTP_PROXY env var:
$ export HTTP_PROXY=
Then run some code to make some requests:
python -c "import requests; requests.get('')"
This will generate some file in tests/responses/
NB: With docker you’ll have to mount the volume:
$ docker run --rm -v tests/responses:/tests/responses bearstech/responses_proxy
You can now restart the server without the proxy mode and the client will react the same way without calling the real server.
You can aslo use a RequestsMock in you unit tests:
import responses_proxy import requsests def test_url(): with responses_proxy.RequestsMock(): requests.get('') # https will work to. both are registered requests.get('')
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/responses_proxy/ | CC-MAIN-2022-05 | refinedweb | 214 | 55.17 |
In brief, I'm feeding my code a piece of unformatted source code. My code transforms the text into a string, then list in order to easily iterate through the latter and format depending on the keyword/expression come across. Now, on coming across '{' a break is executed, but how do you suggest I do the indentation "logic"?
For instance
It should return,It should return,Code :
public class jello{ public static main(String[] args){ jello a = new jello(); run();} public boolean run(){ if (x =1){ ok}}}
How do you suggest I "code" the indentation?How do you suggest I "code" the indentation?Code :
public class jello { public static main(String[] args) { jello a = new jello(); run(); } public boolean run() { if (x ==1) { return ok; } } }
Many thanks! | http://www.javaprogrammingforums.com/%20java-theory-questions/3782-how-indent-printingthethread.html | CC-MAIN-2014-15 | refinedweb | 127 | 59.84 |
Hi everyone,
Somehow struggling to have a dynamic import in our Meteor / React app. Problem is quite simple, we’re using a npm package that exports a component. We use it only once in our whole application so would like it to be out of the bundle and just loaded when we reach the parent Component calling it. A simplication of the issue and what I tried is:
// CURRENT CODE:
import ComponentA from "@bla/A" const ParentComponent = () => { (...) return ( <div> (...) <ComponentA /> </div> ) }
// I TRIED
const ParentComponent = async () => { const ComponentA = await import("@bla/A"); (...) return ( <div> (...) <ComponentA /> </div> ) }
and getting the following error:
I guess I am missing a point somewhere but couldn’t find such basic example in the various articles I found online recently.
Thanks in advance.
Edit; Bonus question: is this worth it if we deliver our bundle from a CDN anyway ? | https://forums.meteor.com/t/simple-dynamic-import-of-react-component-from-npm-library/55224 | CC-MAIN-2022-21 | refinedweb | 143 | 53.92 |
If wxPython is controlling the standard streams, then text sent to the streams via any mechanism—including a print statement or a system traceback—is redirected to a separate wxPython frame. Text sent to the streams before the wxPython application begins or after it ends is, of course, processed normally. Listing 2.1, demonstrates both the application lifecycle and the stdout/stderr redirection.
Listing 2.1 A sample startup script showing output stream redirection
#!/usr/bin/env python import wx import sys class Frame(wx.Frame):
class App(wx.App)
def _init_(self, redirect=True, filename=None):
print "App _init_"
wx.App._init_(self, redirect, filename)
def Onlnit(self):
print "Onlnit" <— Writing to stdout self.frame = Frame(parent=None, id=-1, title='Startup') <1— Creating self.frame.Show() the frame self.SetTopWindow(self.frame)
print >> sys.stderr, "A pretend error message" <1— Writing to stderr return True def OnExit(self): print "OnExit"
app = App(redirect=True) Q Text redirection starts here print "before MainLoop"
app.MainLoop() C The main event loop is entered here print "after MainLoop"
Q This line creates the application object. After this line, all text sent to stderr or stdout can be redirected to a frame by wxPython. The arguments to the constructor determine whether this redirection takes place. C When run, this application creates a blank frame, and also generates a frame with the redirected output, as shown in figure 2.3. Notice also that both stdout and stderr messages get directed to the window.
After you run this program you'll see that your console has the following output:
App _init_
after MainLoop
The first line is generated before the frames are opened, the second line is generated after they close.
By looking at both the console and the output frame, we can trace the application lifecycle.
The first bubble in figure 2.2—Start Script—corresponds to the first lines run from the script's_main_clause. The transition to the next bubble comes immediately in the line marked Q. The instantiation of the instance calls the method
Figure 2.3 The stdout/stderr window created by Listing 2.1
Figure 2.3 The stdout/stderr window created by Listing 2.1
wx.App._init_(). Then control goes to OnInit(), which is automatically called by wxPython. From there, the program jumps to the wx.Frame.__init__(), which is run when the wx.Frame instance is instantiated. Finally, control winds back to the _main_ clause, where MainLoop() is invoked, corresponding to the third bubble in figure 2.2. After the main loop ends, then wx.App.OnExit() is called by wxPython, transitioning to the fourth bubble, and then the rest of the script finishes out the process.
"Wait a minute," you say, "the message from OnExit() didn't display in either the window or the console." As we'll see, the message does display in the wxPython frame, but it does so right before the window is closed, so that it's nearly impossible to capture in a screen shot.
The quickly vanishing OnExit() message is a symptom of a larger issue with the output frame. Although it's a useful feature during development, you don't necessarily want the error stream frame popping out in a user's face at run time. Furthermore, if an error condition happens during the OnInit() method, it gets sent to the output frame, but the error causes the application to exit, since OnInit() will return a False value in case of an error condition. The result is that the line of text is displayed but disappears far too quickly to be seen.
Was this article helpful? | https://www.pythonstudio.us/wxpython/redirecting-output.html | CC-MAIN-2019-51 | refinedweb | 607 | 57.57 |
Write a python program to sort all words of a String in Alphabetical order :
In this python programming tutorial, we will learn how to sort all words in alphabetical order. Mainly we are going to use the split method of python string and for-loop for iterating through the words. If you are not familiar with python string and loops, please go through the tutorials on string and loop first.
To sort all words of a string, first, we need to extract each word and store them somewhere. We will use one list to keep all words of the string. We will sort the words alphabetically in the list and then print out the words one by one.
Following is the algorithm we will use :
Algorithm :
- Ask the user to enter a string. Read and store it in a variable.
- Split the string into words and put them all in a list.
- Sort the words in the list alphabetically.
- Using one for loop, print out the words of the list. Or it will print the words of the string alphabetically.
As you can see above, the main idea of solving this problem is to put all words in a list and sort them alphabetically.
Example Program :
def sortAllWords(given_string): words_list = given_string.split() words_list.sort() print ("Sorted string words are : ") for word in words_list: print(word," ") user_string = input("Enter input string : ") sortAllWords(user_string)
You can also download this program from here.
Explanation :
- In the example above, we are using one different method for the main process to sort the words in alphabetic order. sortAllWords is the method for sorting the words. This method takes one string as an argument. It sorts the words in the string and prints the result.
- For splitting the string into words, we are using the split() method. This method splits the string into words and put all words in a list. words_list is the list we are using here to hold all words.
- For sorting all words in the list, we are using the sort() method. This method is used to sort all words alphabetically.
- We are using one for-loop to print out the content of the list. As you can see above, we can easily print out the contents of a list using a for loop.
- For reading the input from the user, we are using the input() method. This method takes one string argument. It will print this string to the user on console and hold the program waiting for user response. After the ‘enter’ is pressed, it will read the content user has written on the console. In the above program, we are using the user_string variable to hold this content or the string.
- We are calling the sortAllWords method with user_string as a parameter to print out the sorted words.
Example :
Conclusion :
In this tutorial, we have learned how to sort all words of a string in python. A string is immutable. We can’t change the words or any character in a string directly. For sorting the words in a string, we are creating one list with the words of the string as its elements. The list is mutable. We can modify the list items in python. We are using the ‘sort()’ method to sort the contents of the list. That’s it. Try to run the example above and drop one comment below if you have any queries.
Similar tutorials :
- How to use Hashlib to encrypt a string in python
- Python program to find all numbers in a string
- Python 3 program to check if a string is pangram or not
- Python 3 program to count the total number of characters in a string
- Find total number of lowercase characters in a string using Python 3
- Python program to remove characters from odd or even index of a string | https://www.codevscolor.com/python-program-sort-words-string-alphabetical-order | CC-MAIN-2020-45 | refinedweb | 640 | 81.22 |
>>:: ...
Exercise - Add a Splash Screen [ID:559] (13/14)
in series: Build a wxPython Image Viewer
video tutorial by Ian Ozsvald, added 03/08
Name:
[002] Ian Ozsvald
Member: 110 exercise you'll add a touch of professionalism by using a Splash Screen. The exercise is fairly short and only requires a few lines of code. The worked solution is in the next episode. Links - wx.SplashScreen, os.path.
Download 3 test images in a zip file. The necessary source code is shown below in the Source Code tab.
import os import wx import wx.html""" text = '''<html> <h1>ShowMeDo Image Viewer</h1> <p>The ShowMeDo Image Viewer is a demonstration application for the ShowMeDo wxPython 'image viewing' tutorial.</p> <p>More information is available at <a href="">ShowMeDo.com</a>.<p> <p>Created February 2008, Copyright © ShowMeDo Ltd.</p> </html>''' def __init__(self, parent): wx.Dialog.__init__(self, parent, -1, 'About the ShowMeDo Image Viewer...', size=ABOUT_DIALOG_SIZE) html = wx.html.HtmlWindow(self) html.SetPage(self.text) # If a button has an ID of wx.ID_OK it will automatically close a wx.Dialog when pressed # create a 'button' object from wx.Button, give it the ID wx.ID_OK and text 'Okay' button = wx.Button(self, wx.ID_OK, 'Okay') #) # Add the button, ask it to grow by 0% #sizer.Add(button, 0) # also ask the button to align in the centre (my UK spelling!), with a 5 pixel border # around all sides sizer.Add(button, 0, wx.ALIGN_CENTER|wx.ALL, 5) #About(self, event): dlg = ImageViewerAbout(self) dlg.ShowModal() dlg.Destroy()) # TODO add a splash screen before the MainLoop() # 1. load in a wx.Image (see OnOpen above) # 2. make a wx.StaticBitmap (either see ShowBitmap above or do img.ConvertToBitmap() inline) # 3. call wx.SplashScreen: # Try these for splashstyle (using bitwise OR) wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT # Add a timeout in milliseconds, e.g. 1000 is 1 second # Note that parent can be None and id is the usual -1 # Bonus - only open the wx.Image *if* the image exists on disk # by asking os.path if the filename exists # app.MainLoop()
Got any questions?
Get answers in the ShowMeDo Learners Google Group.
Video statistics:
- Video's rank shown in the most popular listing
- Video plays: 71 | http://showmedo.com/videotutorials/video?name=1790120 | CC-MAIN-2015-06 | refinedweb | 376 | 62.54 |
I wanted to do a quick performance (very unscientific though) test on std::vector and std::list and I was very surprised by the results. Maybe it's just me not understanding or knowing how each implements everything internally.
My surprise came when I sorted a vector vs. sorted a equally size linked list. I understand that std::sort requires a random access iterator that std::list doesn't provide which is why their is a list::sort method. Though I thought that using std::sort would require a swap internally (not sure why I do think that, I'm sure I should be doing more research about the internals of each) which wold require each and every object to be copied over. Now the test object I use is just a very basic struct that "simulates" a Rectangle that has a length, width, x position, and y position, all stored as doubles. I overloaded the < operator in it to do the sort and it should sort it based on area (just went ahead and calculated the length*width instead of storing an area member variable, not trying to make this scientific or find performances).
In my test I store 1,000,000 rectangles in a vector a list and set the length, width, xPosition, and yPosition to random numbers for each element in the vector. I then set each elements length, width, xPosition, and yPosition in the list to the vectors corresponding element. Calculate the time for each. Maybe I should use a more scientific approach to this, as I am only using std::clock_t and CLOCKS_PER_SEC to calculate.
When doing this I am very surprised at the performance gap between the two!
First, here's my code to do this quick test, although it isn't anything special or scientific
// Tests Sorting Lists and Vectors Performance #include <iostream> #include <vector> #include <list> #include <algorithm> #include <ctime> struct Rectangle { double length; double width; double xPosition; double yPosition; bool operator<(const Rectangle& rect) const { return (length*width) < (rect.length*rect.width); } }; int main() { const int NUM_ELEMENTS = 1000000; std::clock_t startTime; std::clock_t stopTime; std::vector<Rectangle> myVector(NUM_ELEMENTS); std::vector<Rectangle>::iterator vectIter; // Insert rectangle data in vector startTime = clock(); for(vectIter = myVector.begin(); vectIter != myVector.end(); ++vectIter) { vectIter->length = 1.0*rand()/RAND_MAX; vectIter->width = 1.0*rand()/RAND_MAX; vectIter->xPosition = 1.0*rand()/RAND_MAX; vectIter->yPosition = 1.0*rand()/RAND_MAX; } stopTime = clock(); double totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC; std::cout << "Inserted rectangles in vector in: " << totalTime <<std::endl; std::list<Rectangle> myList(NUM_ELEMENTS); std::list<Rectangle>::iterator listIter; // Insert rectangle data in list startTime = clock(); for(vectIter = myVector.begin(), listIter = myList.begin(); listIter != myList.end() && vectIter != myVector.end(); ++listIter, ++vectIter) { listIter->length = vectIter->length; listIter->width = vectIter->width; listIter->xPosition = vectIter->xPosition; listIter->yPosition = vectIter->yPosition; } stopTime = clock(); totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC; std::cout << "Inserted rectangles in list in: " << totalTime <<std::endl; // sort the vector using std::sort algoorithm startTime = clock(); std::sort(myVector.begin(), myVector.end()); stopTime = clock(); totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC; std::cout << "Time for sorting a vector: " << totalTime << std::endl; // sort the list // can't use std::sort, use the list member function startTime = clock(); myList.sort(); stopTime = clock(); totalTime = (stopTime-startTime)/(double) CLOCKS_PER_SEC; std::cout << "Time for sorting a list: " << totalTime << std::endl; return 0; }
The output/performance I get
Inserted Rectangles in Vector in: 1.597
Inserted Rectangles in List in: 2.989
Time for sorting a vector: 3.384
Time for sorting a list: 111.252
What's with the HUGE perforamance decrease in sorting that list? I understand list is slow at random access and that is what std::vector is strong at, but that big a performance hit when using a list? I think list::sort uses a merge sort, which is O(NlogN), I believe. What would std::sort be using in this case? is their any guarantee or way to see what implementation it is using (maybe I didn't research enough), but does the standard guarantee what it will use? Is their a worst case Big-Oh run time that std::sort guarantees? Average Big-Oh run time?
I understand that this isn't a scientific test nor would I use something like that in a real world code, but is their something just crazy wrong with my code that I'm missing that is causing the list to be that much slower? I do still understand where benefits of using a list would come in, but if this is correct I can totally understand why I've always been told "look at std::vector first." Is this correct? Maybe it's because since the object I am sorting in each is very basic and if I was using a larger and more advanced class that would take longer to copy and results could be different?
Interested in any comments on this.
Note: this is just curiosity and I am not trying to pre-optimize current real world code that I have or anything. Just my Computer Science brain being curious.
Edited by Chad Smith, 17 May 2013 - 06:31 PM. | http://www.gamedev.net/topic/643237-stdsort-vs-listsort/ | CC-MAIN-2013-48 | refinedweb | 856 | 53.51 |
TL;DR: In this tutorial, I'll show you how easy it is to build a web application and secure an API with KeystoneJS. Check out the repo to get the code.
KeystoneJS is an open-source Node.js based CMS and web application framework created by Jed Watson in 2013. KeystoneJS makes it very easy to build database-driven websites, applications & APIs. The framework is built upon Express and MongoDB.
Express is a minimalist web framework for Node.js. It provides a myriad of HTTP utility methods and middleware at your disposal. MongoDB is a very powerful non-relational database.
A lot of folks such as MacMillan, Suitshop already use KeystoneJS to power their CMSes. It's a great tool for quickly developing a blog, portal, forum or any form of managment system that really needs a content management system.
KeystoneJS Architecture
KeystoneJS uses the Model View Template pattern. In a typical framework architecture, there exists a seperation of concern of functionalities; presentation, business, and data access realm.
Data Access - Model: This is the data access layer. It defines how data is being interacted with in the application. Validation, behaviour, and transformation of data.
Business Logic - View: In a typical framework, the view simply presents data to the screen. In KeystoneJS, it serves as the busines logic layer that contains the logic that accesses the model, otherwise known as controllers. It serves as a bridge between the models and templates.
Presentation - Templates: This is the presentation layer. It displays data on the screen.
KeystoneJS Features
KeystoneJS provides a standardized set of components that allows developers to build web applications quickly with JavaScript. It has a number of features that makes it a worthy framework to consider when looking for a good tool for your next project.
- Session Management : KeystoneJS ships with session management and authentication features out of the box.
- Routing: KeystoneJS provides a router that allows you to express how your web application or API routes should look like.
- Form Validation: KeystoneJS provides form validation out of the box.
- Modularity: KeystoneJS configures Express for you. It also uses Mongoose to connect seamlessly with MongoDB and it separates views, routes and templates nicely by providing their specific directories.
- Admin UI: KeystoneJS has an auto-generated Admin UI that saves you a lot of time and makes managing data from your database so easy.
- Email Administration: With KeystoneJS, you can set up, preview and send template-based emails for your application seamlessly. It offers a Mandrill integration out of the box.
KeystoneJS Key Requirements
In order to use KeystoneJS, you need to have the following tools installed on your machine.
- Node.js: Navigate to the Node.js website and install the latest version on your machine.
- MongoDB:.
- Yeoman: Make sure yeoman is installed on your machine by running
npm install -g yo.
- Familiarity with database concepts, and working knowledge of JavaScript.
Building a Blog Rapidly With KeystoneJS
I mentioned earlier that KeystoneJS is a tool for rapidly building out web applications. What you might not be aware of is that it is even easier to set up a blog with KeystoneJS. Let's quickly go through how to setup one.
Use Keystone Yeoman Generator
Run the following command in your terminal to install the powerful Yeoman generator for KeystoneJS:
npm install -g generator-keystone
Create a
blog directory and
cd into it.
mkdir blog && cd blog
Now, run the generator.
yo keystone
Note: To run the command above, you will need Yeoman. Fortunatelly, installing it is as simple as
npm install -g yo.
A wizard comes up and several questions are asked, including if you want a blog, image gallery and contact form. Answer the questions like I did in the image below:
Keystone wizard
Go ahead and run your newly created project with the following command:
node keystone
The blog should run on port 3000 by default. Check out your new blog on.
Sign in to the AdminUI with the credentials you passed in during the wizard generation process.
AdminUI Sign In
Admin Dashboard
Try to create new posts and mark them as published. Also create new users. The Admin UI makes it so easy to do that. Check out the blog, itself and see the posts.
You might be asking some questions already. How do I change the style of the blog? How do I create pages? Let's look into that now.
Create Pages
Head over to the code directory. In the directory structure, you'll see a
models directory that contains
PostCategory,
User and
Enquiry models.
Create a
Page.js model inside the
models directory and add code to it like so:
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Page Model * ========== */ var Page = new keystone.List('Page', { map: { name: 'title' }, autokey: { path: 'slug', from: 'title', unique: true }, }); Page.add({ title: { type: String, required: true }, state: { type: Types.Select, options: 'draft, published, archived', default: 'draft', index: true }, publishedDate: { type: Types.Date, index: true, dependsOn: { state: 'published' } }, image: { type: Types.CloudinaryImage }, content: { brief: { type: Types.Html, wysiwyg: true, height: 150 }, extended: { type: Types.Html, wysiwyg: true, height: 400 }, } }); Page.schema.virtual('content.full').get(function () { return this.content.extended || this.content.brief; }); Page.defaultColumns = 'title, state|20%'; Page.register();
It's similar to the Post model. I specified the Page model attributes and in the Admin UI we only want to display page title and state, which is why I have
Page.defaultColumns = 'title, state|20%';. 20% refers to the column width.
Rerun your app with
node keystone and go to. You should be able to create new pages now.
Let's add
Pages to the Admin UI top navigation for easy access. Open
keystone.js file located in the root of our project directory and add a new route to
keystone.set(nav) section like so:
// Configure the navigation bar in Keystone's Admin UI keystone.set('nav', { posts: ['posts', 'post-categories'], enquiries: 'enquiries', users: 'users', pages: 'pages' });
Note: If you don't want to keep stopping and running your app over and over again, you can install a node module called
nodemon. Then just run:
nodemon keystone. Once we make any change to our app, it automatically restarts the server.
Now, check your Admin UI:
Admin UI Pages Nav
Now, let's configure Pages to show on the user facing end.
Head over to
routes/views and create a
page.js file. Add code to it:
var keystone = require('keystone'); exports = module.exports = function (req, res) { var view = new keystone.View(req, res); var locals = res.locals; // Set locals locals.section = 'pages'; locals.filters = { post: req.params.page, }; locals.data = { posts: [], }; // Load the current post view.on('init', function (next) { var q = keystone.list('Page').model.findOne({ state: 'published', slug: locals.filters.post, }); q.exec(function (err, result) { locals.data.post = result; next(err); }); }); // Load other posts view.on('init', function (next) { var q = keystone.list('Page').model.find().where('state', 'published').sort('-publishedDate').limit('4'); q.exec(function (err, results) { locals.data.posts = results; next(err); }); }); // Render the view view.render('page'); };
This is a page view. It manipulates the data from the model and renders a template. It basically pulls in the slug of the page from the URL and checks if that page slug exists in the database. And it renders the result to the view.
Next step, add the page template. Go to
templates/views,create a
page.pug file and add code to it like so:
{% extends "../layouts/default.twig" %} {% block content %} <div class="container"> <div class="row"> <div class="col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2"> <article> <p> <a href="/blog">← back to the blog</a> </p> <hr> {% if not data.post %} <h2>Invalid Page.</h2> {% else %} <header> <h1>{{ data.post.title }}</h1> <h5>Posted</h5> {% if data.post.publishedDate %} on {{ data.post.publishedDate|date("M d, Y") }} {% endif %} {% if data.post.categories and data.post.categories.length %} in {% for cat in data.post.categories %} <a href="/blog/{{ cat.key }}">{{ cat.name }}</a> {% if not loop.last %}, {% endif %} {% endfor %} {% endif %} </header> <div class="post"> {% if data.post.image.exists %} <div class="image-wrap"> <img src="{{ data.post._.image.fit(750,450) }}" class="img-responsive"> </div> {% endif %} {{ data.post.content.full | raw }} </div> {% endif %} </article> </div> </div> </div> {% endblock %}
Finally, we'll define a new route for pages.
Head over to
routes/index.js file, navigate to the routes section and add
app.get('/pages/:page', routes.views.page); like so:
... app.get('/', routes.views.index); app.get('/blog/:category?', routes.views.blog); app.get('/blog/post/:post', routes.views.post); app.all('/contact', routes.views.contact); app.get('/pages/:page', routes.views.page);
Now, let's add a Page to our user-facing navigation. One of the pages I created from the backend is a page called
team. This is how to add it:
Head over to
routes/middleware.js and add
{ label: 'Team', key: 'team', href: '/pages/team' } to the list of navLinks like so:
... exports.initLocals = function (req, res, next) { res.locals.navLinks = [ { label: 'Home', key: 'home', href: '/' }, { label: 'Blog', key: 'blog', href: '/blog' }, { label: 'Team', key: 'team', href: '/pages/team' }, { label: 'Contact', key: 'contact', href: '/contact' }, ]; res.locals.user = req.user; next(); };
That's all.
Check your app, you should see a
Team nav item or whatever page you created.
We have just built a blog with a functional Admin UI within just a few minutes. You can add more functionalities or extend it to be a hotel or ticket or booking or any type of management system.
Instead of building another application, let's look at how to build a functional API with KeystoneJS.
Building a Star Wars API Rapidly With KeystoneJS
Let's build a Star Wars API with KeystoneJS. The Star Wars API will grant developers access to all the Star Wars data they have ever wanted. Well, this is a KeystoneJS tutorial therefore the data will be very limited, but we'll put the API structure in place and learn how to secure it.
Create an
apifolder inside the
routesdirectory. This is where we will place our logic for fetching data from the database and returning it to the user.
Let's create models for our API. We'll have three models namely, People, Starship and Planet. Each of these models will have certain attributes. Let's outline them:
People: - name - height - mass - gender
Starship: - name - model - manufacturer - crew
Planet: - name - diameter - population - rotation_period
Now, let's create the models. Create
models/People.js,
models/Starship.js, and
models/Planet.js respectively and add code to them like so:
models/People.js
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * People Model * ========== */ var People = new keystone.List('People'); People.add({ name: { type: Types.Name, required: true }, height: { type: Types.Number, required: true, initial: false }, mass: { type: Types.Number, required: true, initial: false }, gender: { type: String }, }); /** * Registration */ People.register();
models/Starship.js
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Starship Model * ========== */ var Starship = new keystone.List('Starship'); Starship.add({ name: { type: String, required: true }, model: { type: String, required: true, initial: false }, manufacturer: { type: String, required: true, initial: false }, crew: { type: Number, required: true, initial: false }, }); /** * Registration */ Starship.register();
models/Planet.js
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Planet Model * ========== */ var Planet = new keystone.List('Planet'); Planet.add({ name: { type: Types.Name, required: true }, diameter: { type: Types.Number, required: true, initial: false }, population: { type: Types.Number, required: true, initial: false }, rotation_period: { type: Types.Number, required: true, initial: false }, }); /** * Registration */ Planet.register();
These models are basically our Database Schemas.
The next step is to create a Keystone view-like logic. In this case, we are dealing with APIs, so we will write them in a different way. Inside the
routes/api directory, create these three files,
people.js,
planet.js and
starship.js respectively.
Go ahead and add code to them like so:
routes/api/people.js
var keystone = require('keystone'); var People = keystone.list('People'); /** * List People */ exports.list = function(req, res) { People.model.find(function(err, items) { if (err) return res.json({ err: err }); res.json({ people: items }); }); } /** * Get People by ID */ exports.get = function(req, res) { People.model.findById(req.params.id).exec(function(err, item) { if (err) return res.json({ err: err }); if (!item) return res.json('not found'); res.json({ people: item }); }); } /** * Create a People */ exports.create = function(req, res) { var item = new People.model(), data = (req.method == 'POST') ? req.body : req.query; item.getUpdateHandler(req).process(data, function(err) { if (err) return res.json({ error: err }); res.json({ people: item }); }); } /** * Patch People by ID */ exports.update = function(req, res) { People.model.findById(req.params.id).exec(function(err, item) { if (err) return res.json({ err: err }); if (!item) return res.json({ err: 'not found' }); var data = (req.method == 'PUT') ? req.body : req.query; item.getUpdateHandler(req).process(data, function(err) { if (err) return res.json({ err: err }); res.json({ people: item }); }); }); } /** * Delete People by ID */ exports.remove = function(req, res) { People.model.findById(req.params.id).exec(function (err, item) { if (err) return res.json({ dberror: err }); if (!item) return res.json('not found'); item.remove(function (err) { if (err) return res.json({ dberror: err }); return res.json({ success: true }); }); }); }
routes/api/planet.js
routes/api/starship.js
Let's analyze the code above. We have four functions in each of the files.
list,
create,
update and
remove. These functions are mapped to HTTP operations like so:
list- /GET
create- /POST
get- /GET
update- /PUT
remove- /DELETE
For example, if you make a POST request to
/people API endpoint, the
create function will be invoked.
- The
listfunction checks the document for all the resources for an API endpoint.
- The
createfunction creates a new resource for an API endpoint.
- The
getfunction checks the document store for a single resource for an API endpoint.
- The
updatefunction checks if a resource exists and allows the resource to be updated for an API endpoint.
- The
removefunction checks if a resource exists and deletes it for an API endpoint.
Now, we need to map these functions to the API routes for a functional API to exist. Head over to the
routes/index.js file. In the Route binding section, add this code to it like so:
// Setup Route Bindings exports = module.exports = function (app) { // Views app.get('/', routes.views.index); // API app.get('/api/people', routes.api.people.list); app.get('/api/people/:id', routes.api.people.get); app.post('/api/people', routes.api.people.create); app.put('/api/people/:id', routes.api.people.update); app.delete('/api/people/:id', routes.api.people.remove); app.get('/api/planets', routes.api.planet.list); app.get('/api/planets/:id', routes.api.planet.get); app.post('/api/planets', routes.api.planet.create); app.put('/api/planets/:id', routes.api.planet.update); app.delete('/api/planets/:id', routes.api.planet.remove); app.get('/api/starships', routes.api.starship.list); app.get('/api/starships/:id', routes.api.starship.get); app.post('/api/starships', routes.api.starship.create); app.put('/api/starships/:id', routes.api.starship.update); app.delete('/api/starships/:id', routes.api.starship.remove); // NOTE: To protect a route so that only admins can see it, use the requireUser middleware: // app.get('/protected', middleware.requireUser, routes.views.protected); };
Then, we need to update the
routes/index.js file as follows:
// ... require statements ... // ... common middleware ... // Import Route Controllers var routes = { views: importRoutes('./views'), api: importRoutes('./api'), }; // ... module.exports ...
Finally, test the API routes with Postman.
People GET operation
People POST operation
People DELETE operation
Our API works. Awesome!
Securing a Star Wars, your
routes/index.js file. Just before the route bindings, add this code:
... var'] });
Also, make sure you require the
express-jwt and
jwks-rsa modules at the top of the file.
var jwt = require('express-jwt'); var jwks = require('jwks-rsa');
Add the
authCheck function to the endpoints as a middleware like so:
// Setup Route Bindings exports = module.exports = function (app) { // Views app.get('/', routes.views.index); // API app.get('/api/people', routes.api.people.list); app.get('/api/people/:id', routes.api.people.get); app.post('/api/people', authCheck, routes.api.people.create); app.put('/api/people/:id', authCheck, routes.api.people.update); app.delete('/api/people/:id', authCheck, routes.api.people.remove); app.get('/api/planets', routes.api.planet.list); app.get('/api/planets/:id', routes.api.planet.get); app.post('/api/planets', authCheck, routes.api.planet.create); app.put('/api/planets/:id', authCheck, routes.api.planet.update); app.delete('/api/planets/:id', authCheck, routes.api.planet.remove); app.get('/api/starships', routes.api.starship.list); app.get('/api/starships/:id', routes.api.starship.get); app.post('/api/starships', authCheck, routes.api.starship.create); app.put('/api/starships/:id', authCheck, routes.api.starship.update); app.delete('/api/starships/:id', authCheck, routes.api.starship.remove); // NOTE: To protect a route so that only admins can see it, use the requireUser middleware: // app.get('/protected', middleware.requireUser, routes.views.protected); };
- The
express..
Accessing the POST people endpoint without an access token
Now, let's test it with a valid access token. Head over to the
test tab of your newly created API on your Auth0 dashboard.
Grab the Access token from the Test tab
Grab the Access Token
Now use this
access token in Postman by sending it as an Authorization header to make a POST request to
api/people endpoint.
Accessing the endpoint securely
It validates the access token and successfully makes the POST request.
Wondering how to integrate the secure API with a frontend? Check out our amazing React and Vue.js authentication tutorials.
Conclusion
Well done! You have learned how to build a blog and an API with KeystoneJS. The KeystoneJS tutorial focuses on building a content management system as fast as possible and fleshing out secure APIs.
KeystoneJS definitely saves a developer a lot of time during development because of the amazing out-of-the-box features.
"KeystoneJS definitely saves a developer a lot of time during development because of the amazing out-of-the-box features."
Auth0 Docs
Implement Authentication in Minutes | https://auth0.com/blog/developing-web-apps-and-restful-apis-with-keystonejs/ | CC-MAIN-2020-05 | refinedweb | 3,026 | 53.07 |
.
(or are keywords case insensitive?)
just a suggestion
I am asking for some alternative as a lot of code used by
other C guys also need to be changed so please suggest an alternative.
regards
venkatesh
Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!
Learn how Concerto can help you.
I have answered the other copy of this question. For some reason E-E won't let me post a answer on this version of the question.
agvenkat - If you like my answer to the other copy agvenkat you can delete this copy to get your pts back
I'll use a trivial example to illustrate. Let's say the library contains only one function, declared in lib.h:
int class(char* new);
You create a new C header file, CppLib.h, which contains the following declaration:
extern "C" {
int LibClass(char* inNew);
}
It's corresponding CppLib.c file (compiled with the C compiler) will be:
#include "lib.h"
int LibClass(char* inNew)
{
return class(inNew);
}
Your C++ program will #include the header CppLib.h, and not the original lib.h .
Now you have the same C library, compiled with a C compiler, but it is usable for C++ programs. All you need to write is the C++ friendly facade.
If you also have C++ keywords as fields in structs, unions or enums, the same principle apply: Declare a new struct, say, with the offensive field renamed, and let your facade translate it to the original struct when passing it on to the original library.
Your CppLib.h should be:
#ifdef __cplusplus
extern "C" {
#endif
int LibClass(char* inNew);
#ifdef __cplusplus
}
#endif
Thanks for your help
venkatesh | https://www.experts-exchange.com/questions/10092575/C-and-C-libraries.html | CC-MAIN-2018-05 | refinedweb | 302 | 63.9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.